From 9958edaece10fca80473ea7259dda075418c5717 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:10 +0000 Subject: [PATCH] Fills: Shape crop, Backface culling and Depth culling on 3D projections --- crates/compose/src/projector_cover.rs | 281 +++++++++++++++++++++++++ crates/compose/src/projector_depth.rs | 287 ++++++++++++++++++++++++++ crates/compose/src/projector_view.rs | 62 ++++++ 3 files changed, 630 insertions(+) create mode 100644 crates/compose/src/projector_cover.rs create mode 100644 crates/compose/src/projector_depth.rs create mode 100644 crates/compose/src/projector_view.rs diff --git a/crates/compose/src/projector_cover.rs b/crates/compose/src/projector_cover.rs new file mode 100644 index 00000000..e19a6c73 --- /dev/null +++ b/crates/compose/src/projector_cover.rs @@ -0,0 +1,281 @@ +//! How much of a texel a 3D projection reaches: its shape crop and its backface culling + +use texturecraft_core::{Backface, Decal, DecalFlip, Projection, Projector, ShapeCrop}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::frame_placement::warp_reach; +use crate::organic::smoothstep; +use crate::pattern::{Coords, depth_fade, frame_crop, frame_facing, frame_local, placed_uv, projector_local}; +use crate::warp::warp_uv; + +/// Nearer a cylinder's axis than this a texel has no outward direction, so it counts as facing out +const MIN_AXIS_DISTANCE: f32 = 1e-6; + +/// The turn (in cosine) over which backface culling fades at hardness 0 +const BACKFACE_FADE: f32 = 0.6; + +/// The shape crop and backface culling [`projector_cover`] applies, None where it lets every texel through +fn cropping_projector(proj: &Projection) -> Option<&Projector> { + let projector = match proj { + Projection::Triplanar { projector, .. } + | Projection::Planar { projector, .. } + | Projection::Spherical { projector, .. } + | Projection::Cylindrical { projector, .. } => projector, + // Framed on the surface: see [`framed_cover`] + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => return None, + }; + Some(projector).filter(|projector| projector.crop != ShapeCrop::ExtendsOutside || projector.backface.on) +} + +/// Whether [`projector_cover`] is 1 on every texel, so it needs no texel's place +pub fn projector_covers_all(proj: &Projection) -> bool { + cropping_projector(proj).is_none() +} + +/// How much of the texel at `coords` the projection reaches through its shape crop and backface culling; not for placed planars or warps (see [`framed_cover`]) +pub fn projector_cover(proj: &Projection, coords: &Coords) -> f32 { + let Some(projector) = cropping_projector(proj) else { return 1.0 }; + + let local = projector_local(projector, coords); + let (inside, facing) = match proj { + Projection::Triplanar { .. } => (local.pos.abs().max_element() <= 1.0, None), + Projection::Planar { scale, axis, offset, .. } => { + let scaled = local.pos * *scale + Vec3::from(*offset); + + // The frame across the axis, and the side the image reads the right way round from + let (frame, facing) = match axis { + 0 => (scaled.z.abs().max(scaled.y.abs()), -local.nrm.x), + 1 => (scaled.x.abs().max(scaled.z.abs()), local.nrm.y), + _ => (scaled.x.abs().max(scaled.y.abs()), local.nrm.z), + }; + (frame <= 1.0, Some(facing)) + } + Projection::Spherical { offset, .. } => ((local.pos + Vec3::from(*offset)).length() <= 1.0, None), + Projection::Cylindrical { axis, offset, .. } => { + let position = local.pos + Vec3::from(*offset); + let normal = local.nrm; + let ((across, height, depth), (normal_across, normal_depth)) = match axis { + 0 => ((position.y, position.x, position.z), (normal.y, normal.z)), + 2 => ((position.x, position.z, position.y), (normal.x, normal.y)), + _ => ((position.x, position.y, position.z), (normal.x, normal.z)), + }; + let radius = across.hypot(depth); + let outward = if radius > MIN_AXIS_DISTANCE { (normal_across * across + normal_depth * depth) / radius } else { 1.0 }; + (radius <= 1.0 && height.abs() <= 1.0, Some(outward)) + } + Projection::Warp { .. } | Projection::Uv { .. } | Projection::UvTile => (true, None), + }; + if projector.crop == ShapeCrop::Cropped && !inside { + return 0.0; + } + + match facing { + Some(facing) if projector.backface.on => backface_cover(&projector.backface, facing), + _ => 1.0, + } +} + +/// How much a face turned `facing` (the cosine of its turn from the projection) keeps +pub fn backface_cover(backface: &Backface, facing: f32) -> f32 { + // A hand-edited NaN angle or hardness keeps the layer visible rather than making its texels NaN + if !(backface.angle.is_finite() && backface.hardness.is_finite()) { + return 1.0; + } + + // cos(angle) as sin(90 - angle): exactly 0 at 90 degrees + let threshold = (90.0 - backface.angle).to_radians().sin(); + let width = (1.0 - backface.hardness.clamp(0.0, 1.0)) * BACKFACE_FADE; + if width <= f32::EPSILON { + return f32::from(u8::from(facing > threshold)); + } + + smoothstep(threshold, threshold + width, facing) +} + +/// A planar projection placed on the surface at world point `p` with normal `nrm`: its texture coordinates and how much its backface culling and shape crop let through (None when the frame is degenerate) +pub fn placed_cover(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let mut cover = if projector.backface.on { backface_cover(&projector.backface, frame_facing(frame, projector, nrm)) } else { 1.0 }; + if projector.crop == ShapeCrop::Cropped { + cover *= frame_crop(frame, local); + } + Some((flip_uv(placed_uv(local), frame.flip), cover)) +} + +/// [`placed_cover`] for a frame with a mirrored copy: whichever of the frame and its copy covers the point more. The copy is the frame reflected through the plane `offset` away from `center` (the mesh center) on the symmetry axis, its image flipped as asked +pub fn placed_cover_symmetric(frame: &Decal, projector: &Projector, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let direct = placed_cover(frame, projector, p, nrm); + let Some(symmetry) = frame.symmetry else { return direct }; + + let axis = usize::from(symmetry.axis.min(2)); + let (mut mirrored_position, mut mirrored_normal) = (p, nrm); + mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + mirrored_normal[axis] = -nrm[axis]; + let mirrored = placed_cover(frame, projector, mirrored_position, mirrored_normal).map(|(uv, cover)| { + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, cover) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } +} + +/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame +fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { + Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) +} + +/// A projection from a frame on the surface (a placed planar or a warp) at world point `p` with normal `nrm`, `center` the mesh center a placed planar's mirrored copy reflects across: its texture coordinates and how much it covers there (None for other projections, a degenerate frame or where nothing lands) +pub fn framed_cover(proj: &Projection, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + match proj { + Projection::Planar { projector, placed: Some(frame), .. } => placed_cover_symmetric(frame, projector, p, nrm, center), + Projection::Warp { frame, corners, depth, projector, .. } => warp_cover(frame, corners, *depth, projector, p), + _ => None, + } +} + +/// A warp projection at world point `p`: its texture coordinates in the quad its corners make, and, cropped to its shape, how much of the quad and of its Projection Depth (in lengths of the frame's longer side) cover it +pub fn warp_cover(frame: &Decal, corners: &[[f32; 2]; 4], depth: f32, projector: &Projector, p: Vec3) -> Option<(Vec2, f32)> { + let local = frame_local(frame, projector, p)?; + let uv = warp_uv(corners, local.truncate())?; + if projector.crop == ShapeCrop::ExtendsOutside { + return Some((uv, 1.0)); + } + + let inside = (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y); + let reach = warp_reach(frame.size, depth); + Some((uv, if inside { depth_fade(local.z, reach) } else { 0.0 })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The decal formula from before decals were placed planar projections, kept to check they still look the same + fn decal_before(frame: &Decal, point: Vec3, surface_normal: Vec3) -> Option<(Vec2, f32)> { + let (origin, right, up, normal) = crate::pattern::decal_axes(frame)?; + let facing = surface_normal.dot(normal); + let offset = point - origin; + let (local_x, local_y, local_z) = (offset.dot(right) / frame.size[0].max(1e-6), offset.dot(up) / frame.size[1].max(1e-6), offset.dot(normal).abs()); + let depth = frame.depth.max(1e-6); + if facing <= 0.0 || local_x.abs() > 0.5 || local_y.abs() > 0.5 || local_z > depth || !(local_x.is_finite() && local_y.is_finite()) { + return None; + } + + let cover = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, local_z)); + Some((Vec2::new(local_x + 0.5, 0.5 - local_y), cover)) + } + + #[test] + fn a_nan_backface_angle_or_hardness_culls_nothing() { + for backface in [Backface { on: true, angle: f32::NAN, hardness: 0.5 }, Backface { on: true, angle: 60.0, hardness: f32::NAN }] { + assert_eq!(backface_cover(&backface, -0.5), 1.0, "{backface:?}"); + } + } + + #[test] + fn saved_decals_cover_exactly_as_before() { + let frames = [ + Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [2.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }, + Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + for sample in 0..4000 { + let phase = sample as f32 * 0.137; + let point = Vec3::new(phase.sin() * 1.3, (phase * 0.71).cos() * 1.1, (phase * 0.33).sin() * 0.8); + let normal = Vec3::new((phase * 1.7).cos(), (phase * 0.9).sin(), (phase * 0.4).cos()).normalize(); + let now = placed_cover(&placed, &projector, point, normal).filter(|(_, cover)| *cover > 0.0); + match (decal_before(&frame, point, normal), now) { + (Some(before), Some(now)) => assert_eq!(before, now, "{point} {normal}"), + (None, None) => {} + (before, now) => panic!("{point} {normal}: {before:?} became {now:?}"), + } + } + } + } + + /// The mirrored copy's formula as the decal model before placed planar projections had it (flip and symmetry on a decal) + fn symmetric_before(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let flip = |uv: Vec2| flip_uv(uv, d.flip); + let direct = decal_before(d, p, nrm).map(|(uv, w)| (flip(uv), w)); + let Some(symmetry) = d.symmetry else { return direct }; + let axis = usize::from(symmetry.axis.min(2)); + let (mut q, mut m) = (p, nrm); + q[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + m[axis] = -nrm[axis]; + let mirrored = decal_before(d, q, m).map(|(uv, w)| { + let uv = flip(uv); + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, w) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } + } + + #[test] + fn saved_mirrored_and_flipped_decals_cover_exactly_as_before() { + let base = Decal { + center: [0.3, -0.2, 0.1], + normal: [0.4, 0.5, 0.7], + up: [0.0, 1.0, 0.0], + size: [0.7, 1.3], + rotation: 37.0, + offset: [0.2, -0.1], + depth: 0.4, + symmetry: None, + flip: [false; 2], + }; + let center = Vec3::new(0.1, -0.05, 0.2); + let frames = [ + Decal { flip: [true, false], ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }), ..base }, + Decal { symmetry: Some(texturecraft_core::DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: -0.15 }), flip: [false, true], ..base }, + ]; + for frame in frames { + let Projection::Planar { projector, placed: Some(placed), .. } = Projection::decal(frame) else { panic!("a placed planar projection") }; + let mut mirrored = 0; + for i in 0..4000 { + let t = i as f32 * 0.137; + let p = Vec3::new(t.sin() * 1.3, (t * 0.71).cos() * 1.1, (t * 0.33).sin() * 0.8); + let nrm = Vec3::new((t * 1.7).cos(), (t * 0.9).sin(), (t * 0.4).cos()).normalize(); + let now = placed_cover_symmetric(&placed, &projector, p, nrm, center).filter(|(_, cover)| *cover > 0.0); + let before = symmetric_before(&frame, p, nrm, center); + mirrored += usize::from(before.is_some() && decal_before(&frame, p, nrm).is_none()); + assert_eq!(before, now, "{p} {nrm}"); + } + assert!(frame.symmetry.is_none() || mirrored > 0, "the mirrored copy covers points the frame does not"); + } + } +} diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs new file mode 100644 index 00000000..bf0aafcd --- /dev/null +++ b/crates/compose/src/projector_depth.rs @@ -0,0 +1,287 @@ +//! The depth map of a planar or warp projection: the surface nearest its projector across its view, for depth culling + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex}; + +use texturecraft_core::Projection; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::organic::smoothstep; +use crate::projector_view::ProjectorView; + +/// The nearest surface in each cell of a grid across a projector's view +pub struct ProjectorDepth { + view: ProjectorView, + /// The view point at the grid's lower corner + origin: Vec2, + /// One cell's size across and up in the view + cell: Vec2, + /// Per cell: the nearness of the nearest surface at the cell centre and its slope across and up (nearness -inf where no surface is) + front: Vec<[f32; 3]>, +} + +/// Built maps by their view and the mesh they come from +type CacheEntry = (ProjectorView, u64, Arc); + +/// The smallest grid cell across and up, so a flat view still divides +const MIN_CELL_SIZE: f32 = 1e-6; + +/// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps +const EDGE_TOLERANCE: f32 = 1e-6; + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl ProjectorDepth { + /// The depth map of `proj` over `mesh` within `bounds`, built once per view and mesh; None unless `proj` culls by depth + pub fn of(mesh: &Mesh, bounds: (Vec3, Vec3), proj: &Projection) -> Option> { + let view = ProjectorView::of(proj, bounds)?; + let mesh_key = fingerprint(mesh); + + // Built with the cache locked: the build runs no parallel work, and tiles asking for the same map wait for it instead of building it again + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(at) = cache.iter().position(|(cached_view, cached_mesh, _)| *cached_view == view && *cached_mesh == mesh_key) { + let (cached_view, cached_mesh, depth) = cache.remove(at); + cache.insert(0, (cached_view, cached_mesh, depth.clone())); + return Some(depth); + } + + let depth = Arc::new(ProjectorDepth::build(view, mesh)?); + cache.insert(0, (view, mesh_key, depth.clone())); + cache.truncate(CACHE_MAPS); + Some(depth) + } + + /// Drop every built map: a mesh replacing another (a reimport, another project) can share the old one's fingerprint + pub fn forget_all() { + CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clear(); + } + + /// Rasterize every triangle of `mesh` in `view`, keeping the nearest per cell (None when no vertex lands in the view) + pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { + let local: Vec> = mesh.positions.iter().map(|position| view.local(*position)).collect(); + let (lo, hi) = local + .iter() + .flatten() + .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); + if lo.x > hi.x || lo.y > hi.y { + return None; + } + + let cell = ((hi - lo) / SIZE as f32).max(Vec2::splat(MIN_CELL_SIZE)); + let mut depth = ProjectorDepth { view, origin: lo, cell, front: vec![[f32::NEG_INFINITY, 0.0, 0.0]; SIZE * SIZE] }; + let mut budget = CELL_BUDGET; + for tri in mesh.indices.as_chunks::<3>().0 { + let corner = |i: u32| local.get(i as usize).copied().flatten(); + let (Some(a), Some(b), Some(c)) = (corner(tri[0]), corner(tri[1]), corner(tri[2])) else { continue }; + if !depth.raster([a, b, c], &mut budget) { + break; + } + } + Some(depth) + } + + /// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out + fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { + let [a, b, c] = triangle; + let (d1, d2) = (b - a, c - a); + let det = d1.x * d2.y - d1.y * d2.x; + if !det.is_finite() || det.abs() < MIN_SCREEN_AREA { + // Seen edge on, it covers nothing + return true; + } + + let slope = Vec2::new((d1.z * d2.y - d2.z * d1.y) / det, (d1.x * d2.z - d2.x * d1.z) / det).clamp(Vec2::splat(-MAX_SLOPE), Vec2::splat(MAX_SLOPE)); + + // Corners in cells: cell (i, j) has its centre at (i + 0.5, j + 0.5) + let [pa, pb, pc] = triangle.map(|corner| (corner.truncate() - self.origin) / self.cell); + let (lo, hi) = (pa.min(pb).min(pc), pa.max(pb).max(pc)); + let first = |v: f32| (v - 0.5).ceil().clamp(0.0, SIZE as f32) as usize; + let last = |v: f32| ((v - 0.5).floor() + 1.0).clamp(0.0, SIZE as f32) as usize; + let (x0, x1, y0, y1) = (first(lo.x), last(hi.x), first(lo.y), last(hi.y)); + let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0)); + let Some(left) = budget.checked_sub(cells) else { return false }; + *budget = left; + + let area = edge(pa, pb, pc); + for y in y0..y1 { + for x in x0..x1 { + let cell_centre = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let inside = [edge(pb, pc, cell_centre), edge(pc, pa, cell_centre), edge(pa, pb, cell_centre)] + .iter() + .all(|weight| weight * area.signum() >= -EDGE_TOLERANCE * area.abs()); + if !inside { + continue; + } + + let near = a.z + slope.dot(self.origin + cell_centre * self.cell - a.truncate()); + if let Some(cell) = self.front.get_mut(y * SIZE + x) + && near > cell[0] + { + *cell = [near, slope.x, slope.y]; + } + } + } + true + } + + /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front + pub fn cover(&self, p: Vec3, hardness: f32) -> f32 { + // A hand-edited NaN hardness keeps the layer visible rather than making its texels NaN + if !hardness.is_finite() { + return 1.0; + } + + let Some(view_point) = self.view.local(p) else { return 1.0 }; + let at = (view_point.truncate() - self.origin) / self.cell; + if !(at.x >= 0.0 && at.y >= 0.0 && at.x < SIZE as f32 && at.y < SIZE as f32) { + return 1.0; + } + + let (x, y) = (at.x as usize, at.y as usize); + let Some(&[near, across, up]) = self.front.get(y * SIZE + x).filter(|cell| cell[0].is_finite()) else { return 1.0 }; + + // The nearest surface's plane carried from the cell centre to the point, so a surface is never behind itself + let centre = self.origin + (Vec2::new(x as f32, y as f32) + 0.5) * self.cell; + let slope = Vec2::new(across, up); + let behind = near + slope.dot(view_point.truncate() - centre) - view_point.z; + let unit = self.view.unit(); + + // Neighbouring triangles of a curved surface part from the carried plane by about one cell of its slope + let bias = BIAS * unit + (slope.abs() * self.cell).element_sum().min(MAX_SLOPE_BIAS * unit); + let width = (1.0 - hardness.clamp(0.0, 1.0)) * FADE * unit; + if width <= f32::EPSILON { + return f32::from(u8::from(behind <= bias)); + } + + 1.0 - smoothstep(bias, bias + width, behind) + } +} + +/// Twice the signed area of triangle `a`, `b`, `q` +fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { + (b - a).perp_dot(q - a) +} + +/// Which mesh a map was built for: its sizes and a spread of its vertices and indices +fn fingerprint(mesh: &Mesh) -> u64 { + let mut hasher = DefaultHasher::new(); + (mesh.positions.len(), mesh.indices.len()).hash(&mut hasher); + for position in mesh.positions.iter().step_by((mesh.positions.len() / FINGERPRINT_SAMPLES).max(1)) { + position.to_array().map(f32::to_bits).hash(&mut hasher); + } + for index in mesh.indices.iter().step_by((mesh.indices.len() / FINGERPRINT_SAMPLES).max(1)) { + index.hash(&mut hasher); + } + hasher.finish() +} + +/// Cells across and up the grid +const SIZE: usize = 512; + +/// A triangle flatter than this on screen is seen edge on +const MIN_SCREEN_AREA: f32 = 1e-12; + +/// Most cells all triangles together may visit before the rest are left out (hostile meshes of huge overlapping triangles) +const CELL_BUDGET: usize = 256 * SIZE * SIZE; + +/// Steepest surface slope kept, in nearness per view unit +const MAX_SLOPE: f32 = 1e4; + +/// How far behind the nearest surface a point may sit and keep everything, in mesh radii +const BIAS: f32 = 0.002; + +/// Most the slope adds to the bias, in mesh radii +const MAX_SLOPE_BIAS: f32 = 0.05; + +/// How far behind the nearest surface culling fades out at hardness 0, in mesh radii +const FADE: f32 = 0.1; + +/// Maps kept built (each is about 3 MB) +const CACHE_MAPS: usize = 8; + +/// Vertices and indices the mesh fingerprint reads +const FINGERPRINT_SAMPLES: usize = 64; + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Projector, UvTransform}; + + /// Two squares facing +Z, one at z = `front` covering x 0..1, one at z = `back` covering x -1..1 + fn two_squares(front: f32, back: f32) -> Mesh { + let positions = vec![ + Vec3::new(0.0, -1.0, front), + Vec3::new(1.0, -1.0, front), + Vec3::new(1.0, 1.0, front), + Vec3::new(0.0, 1.0, front), + Vec3::new(-1.0, -1.0, back), + Vec3::new(1.0, -1.0, back), + Vec3::new(1.0, 1.0, back), + Vec3::new(-1.0, 1.0, back), + ]; + Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7], ..Mesh::default() } + } + + fn planar_z(on: bool, hardness: f32) -> Projection { + let mut projector = Projector::depth_culled(); + projector.depth.on = on; + projector.depth.hardness = hardness; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None } + } + + #[test] + fn surfaces_behind_others_are_culled_and_the_nearest_keeps_everything() { + let mesh = two_squares(0.5, -0.5); + let bounds = mesh.bounds(); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), bounds).unwrap(), &mesh).unwrap(); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, 0.5), 1.0), 1.0, "the front square"); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the back square behind it"); + assert_eq!(depth.cover(Vec3::new(-0.5, 0.3, -0.5), 1.0), 1.0, "the back square where nothing is in front"); + let soft = depth.cover(Vec3::new(0.5, 0.3, 0.5 - 0.01), 0.0); + assert!(soft > 0.0 && soft < 1.0, "a soft cull fades just behind the front: {soft}"); + assert!(ProjectorView::of(&planar_z(false, 1.0), bounds).is_none(), "off, there is nothing to build"); + } + + #[test] + fn a_nan_hardness_culls_nothing() { + let mesh = two_squares(0.5, -0.5); + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + + let behind = depth.cover(Vec3::new(0.5, 0.3, -0.5), f32::NAN); + + assert_eq!(behind, 1.0, "a hand-edited NaN hardness keeps the back square visible"); + } + + #[test] + fn a_mesh_edited_where_its_fingerprint_does_not_look_is_rebuilt_once_forgotten() { + // Unused vertices spread the fingerprint's samples so the front square's right edge is not among them + let mut mesh = two_squares(0.5, -0.5); + mesh.positions.extend((0..FINGERPRINT_SAMPLES * 3).map(|_| Vec3::ZERO)); + let mut edited = mesh.clone(); + for right in [1, 2] { + edited.positions[right].x = 0.5; + } + assert_eq!(fingerprint(&mesh), fingerprint(&edited), "the edit is unseen by the fingerprint"); + let proj = planar_z(true, 1.0); + let behind_the_cut = Vec3::new(0.75, 0.3, -0.5); + let bounds = mesh.bounds(); + assert_eq!(ProjectorDepth::of(&mesh, bounds, &proj).unwrap().cover(behind_the_cut, 1.0), 0.0); + + ProjectorDepth::forget_all(); + + let rebuilt = ProjectorDepth::of(&edited, bounds, &proj).unwrap(); + assert_eq!(rebuilt.cover(behind_the_cut, 1.0), 1.0, "nothing is in front there any more"); + } + + #[test] + fn a_slanted_surface_is_never_behind_itself() { + let positions = vec![Vec3::new(-1.0, -1.0, -0.9), Vec3::new(1.0, -1.0, 0.9), Vec3::new(1.0, 1.0, 0.9), Vec3::new(-1.0, 1.0, -0.9)]; + let mesh = Mesh { positions, indices: vec![0, 1, 2, 0, 2, 3], ..Mesh::default() }; + let depth = ProjectorDepth::build(ProjectorView::of(&planar_z(true, 1.0), mesh.bounds()).unwrap(), &mesh).unwrap(); + for i in 0..1000 { + let (x, y) = ((i as f32 * 0.618).fract() * 1.98 - 0.99, (i as f32 * 0.377).fract() * 1.98 - 0.99); + assert_eq!(depth.cover(Vec3::new(x, y, x * 0.9), 1.0), 1.0, "{x} {y}"); + } + } +} diff --git a/crates/compose/src/projector_view.rs b/crates/compose/src/projector_view.rs new file mode 100644 index 00000000..982d0820 --- /dev/null +++ b/crates/compose/src/projector_view.rs @@ -0,0 +1,62 @@ +//! Where a planar or warp projection's projector looks from, for depth culling + +use texturecraft_core::{Decal, Projection, Projector}; +use texturecraft_geom::glam::{Vec2, Vec3}; + +use crate::pattern::{Coords, frame_local, mesh_frame, projector_local}; + +/// The view of a depth-culled planar or warp projection: points in it run across, up and towards the projector +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum ProjectorView { + /// An axis planar projection, reading positions around the mesh centre in mesh radii + Axis { axis: u8, projector: Projector, center: Vec3, radius: f32 }, + /// A planar projection placed on the surface or a warp, from its frame + Frame { frame: Decal, projector: Projector, radius: f32 }, +} + +impl ProjectorView { + /// The view of `proj` over a mesh within `bounds`, None unless it is a planar or warp projection with depth culling on + pub fn of(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + proj.depth_culling()?; + let (center, radius) = mesh_frame(bounds); + match proj { + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + Some(ProjectorView::Frame { frame: *frame, projector: turn_only(projector), radius }) + } + Projection::Planar { axis, projector, .. } => Some(ProjectorView::Axis { axis: *axis, projector: turn_only(projector), center, radius }), + _ => None, + } + } + + /// World point `point` in the view: across, up and how near the projector (None where the view is degenerate) + pub fn local(&self, point: Vec3) -> Option { + let local = match self { + ProjectorView::Axis { axis, projector, center, radius } => { + let at = Coords { uv: Vec2::ZERO, pos: (point - *center) / *radius, nrm: Vec3::Z }; + let projected = projector_local(projector, &at).pos; + + // The side each axis projects from, as its backface culling reads it + match axis { + 0 => Vec3::new(projected.z, projected.y, -projected.x), + 1 => Vec3::new(projected.x, projected.z, projected.y), + _ => projected, + } + } + ProjectorView::Frame { frame, projector, .. } => frame_local(frame, projector, point)?, + }; + local.is_finite().then_some(local) + } + + /// The mesh radius in the view's nearness units + pub fn unit(&self) -> f32 { + match self { + ProjectorView::Axis { .. } => 1.0, + ProjectorView::Frame { radius, .. } => *radius, + } + } +} + +/// Only what moves the view: the turn and stretch, not the culling settings (changing those keeps the depth map) +fn turn_only(projector: &Projector) -> Projector { + Projector { rotation: projector.rotation, scale: projector.scale, ..Projector::default() } +}