From 9be079d6f8dcf770372861a094c93b35a9bc3f99 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: every projection samples with tiling, rotation and offset, Filtering, UV Wrap and Match per UV Tile --- crates/compose/src/axis_frame.rs | 158 +++++++++ crates/compose/src/fill_place.rs | 12 + crates/compose/src/mip_level.rs | 35 ++ crates/compose/src/pattern.rs | 454 +++++++++++++++++------- crates/compose/src/tile_length.rs | 155 ++++++++ crates/core/src/layer.rs | 231 +++++++++++- crates/engine/tests/it/fill_patterns.rs | 69 ++++ crates/engine/tests/it/fill_sampling.rs | 218 ++++++++++++ 8 files changed, 1188 insertions(+), 144 deletions(-) create mode 100644 crates/compose/src/axis_frame.rs create mode 100644 crates/compose/src/fill_place.rs create mode 100644 crates/compose/src/mip_level.rs create mode 100644 crates/compose/src/tile_length.rs create mode 100644 crates/engine/tests/it/fill_patterns.rs create mode 100644 crates/engine/tests/it/fill_sampling.rs diff --git a/crates/compose/src/axis_frame.rs b/crates/compose/src/axis_frame.rs new file mode 100644 index 00000000..a4daa864 --- /dev/null +++ b/crates/compose/src/axis_frame.rs @@ -0,0 +1,158 @@ +//! The frame an axis planar projection projects from: moving one on the model places it as that frame, so its images land where they did + +use texturecraft_core::{Decal, Projection, Projector, Source}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec3}; + +use crate::frame_placement::culling_folds; +use crate::pattern::{DEPTH_FADE_START, frame_uv_from_corner, mesh_frame, nonzero_stretch, projector_stretch}; + +/// The placed planar projection that reads images exactly as axis planar `proj` does on a mesh within `bounds` (None for other projections, placed ones included, and while backface culling cannot keep its facing in a frame: see [`culling_folds`]) +pub fn placed_from_axis(proj: &Projection, bounds: (Vec3, Vec3)) -> Option { + let Projection::Planar { scale, axis, offset, uv, projector, placed: None } = proj else { return None }; + + if !culling_folds(projector) { + return None; + } + + let frame = axis_frame(*scale, *axis, Vec3::from(*offset), projector, bounds)?; + + // The turn and per-axis scale are now in the frame; culling and crop stay + let projector = Projector { rotation: [0.0; 3], scale: [1.0; 3], ..*projector }; + + // An axis planar turns its image round the top left, a frame round its centre + let uv = frame_uv_from_corner(uv); + Some(Projection::Planar { scale: *scale, axis: *axis, offset: *offset, uv, projector, placed: Some(frame) }) +} + +/// Whether placing an axis planar that reads `sources` would move a pattern: a procedural reads an axis planar's plane but a placed frame's uv, so such a planar keeps its axis +pub fn placing_moves_pattern<'a>(mut sources: impl Iterator) -> bool { + sources.any(|source| matches!(source, Source::Procedural { .. })) +} + +/// The frame of an axis planar projection: its image's 0..1 square on the plane through the mesh, turned and sized by `projector` +pub fn axis_frame(scale: f32, axis: u8, offset: Vec3, projector: &Projector, bounds: (Vec3, Vec3)) -> Option { + let (center, radius) = mesh_frame(bounds); + let [x, y, z] = projector.rotation.map(f32::to_radians); + let turn = Mat3::from_euler(EulerRot::ZYX, z, y, x); + let stretch = projector_stretch(projector); + let scale = nonzero_stretch(scale); + + // Where the image's centre sits, then its across, up and out directions with the stretch along each + let origin = center + turn * (stretch * -offset / scale) * radius; + let (across, up, out) = match axis { + 0 => (Vec3::Z, Vec3::Y, Vec3::NEG_X), + 1 => (Vec3::X, Vec3::NEG_Z, Vec3::Y), + _ => (Vec3::X, Vec3::Y, Vec3::Z), + }; + let side = |direction: Vec3| 2.0 * radius * direction.abs().dot(stretch) / scale; + + // A negative stretch or scale turns that side over + let flip = |direction: Vec3| direction * side(direction).signum(); + let (across, up) = (flip(across), flip(up)); + let size = [side(across).abs(), side(up).abs()]; + let out = turn * across.cross(up).normalize_or(out); + + // Deep enough never to crop the mesh by depth: the fade starts at three quarters of it + let reach = (radius + (origin - center).length()) / DEPTH_FADE_START * DEPTH_SPARE; + let frame = Decal { + center: origin.to_array(), + normal: out.to_array(), + up: (turn * up).to_array(), + size, + rotation: 0.0, + offset: [0.0; 2], + depth: reach, + symmetry: None, + flip: [false; 2], + }; + (origin.is_finite() && size.iter().all(|side| side.is_finite() && *side > 0.0) && reach.is_finite()).then_some(frame) +} + +/// Extra reach past the farthest mesh point +const DEPTH_SPARE: f32 = 1.01; + +#[cfg(test)] +mod tests { + use texturecraft_core::{Backface, ShapeCrop, UvTransform}; + use texturecraft_geom::glam::Vec2; + + use super::*; + use crate::pattern::{Coords, image_samples}; + use crate::projector_cover::{framed_cover, projector_cover}; + + /// Points spread through the box `lo`..`hi` with varied normals + fn points(lo: Vec3, hi: Vec3) -> Vec<(Vec3, Vec3)> { + (0..64) + .map(|i| { + let spread = |salt: u32| ((i * 37 + salt * 11) % 64) as f32 / 63.0; + let position = lo + (hi - lo) * Vec3::new(spread(1), spread(2), spread(3)); + let normal = Vec3::new(spread(4) - 0.4, spread(5) - 0.3, spread(6) - 0.2).normalize_or(Vec3::Z); + (position, normal) + }) + .collect() + } + + #[test] + fn a_placed_axis_planar_reads_images_where_it_did() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + for axis in 0..3 { + for (rotation, stretch) in [([0.0; 3], [1.0; 3]), ([20.0, -35.0, 50.0], [1.5, 0.7, 2.0])] { + for crop in [ShapeCrop::ExtendsOutside, ShapeCrop::Cropped] { + let projector = Projector { rotation, scale: stretch, crop, ..Projector::default() }; + let uv = UvTransform { tiling: [2.0, 3.0], rotation: 30.0, offset: [0.1, -0.2] }; + let axis_planar = Projection::Planar { scale: 1.7, axis, offset: [0.3, -0.4, 0.2], uv, projector, placed: None }; + let placed = placed_from_axis(&axis_planar, (lo, hi)).expect("an axis planar has a frame"); + for (position, normal) in points(lo, hi) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (before, _) = image_samples(&axis_planar, &coords)[0]; + let (uv_after, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + let (after, _) = image_samples(&placed, &Coords { uv: uv_after, ..coords })[0]; + assert!(before.distance(after) < 1e-3, "axis {axis} {rotation:?}: {before} became {after}"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "axis {axis} {crop:?}: cover changed at {position}"); + } + } + } + } + } + + #[test] + fn a_placed_axis_planar_keeps_what_backface_culling_hides() { + let (lo, hi) = (Vec3::new(-1.0, -0.5, -2.0), Vec3::new(3.0, 1.5, 0.5)); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length() * 0.5; + let backface = Backface { on: true, angle: 60.0, hardness: 1.0 }; + + // Half way between across and out: a stretch across tilts the culled normal past the angle, a negative one turns it round + let halfway = (center, Vec3::new(1.0, 0.0, 1.0).normalize()); + + for stretch in [[4.0, 1.0, 1.0], [1.5, -1.5, 1.5], [1.7; 3]] { + let projector = Projector { scale: stretch, backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: None }; + let Some(placed) = placed_from_axis(&axis_planar, (lo, hi)) else { + assert!(!culling_folds(&projector), "{stretch:?}: only a stretch culling cannot keep stays unplaced"); + continue; + }; + + for (position, normal) in points(lo, hi).into_iter().chain([halfway]) { + let coords = Coords { uv: Vec2::ZERO, pos: (position - center) / radius, nrm: normal }; + let (_, cover) = framed_cover(&placed, position, normal, center).expect("a placed frame covers"); + assert!((projector_cover(&axis_planar, &coords) - cover).abs() < 1e-3, "{stretch:?}: culling changed at {normal}"); + } + } + + let even = Projector { scale: [1.7; 3], backface, ..Projector::default() }; + let axis_planar = Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: even, placed: None }; + assert!(placed_from_axis(&axis_planar, (lo, hi)).is_some(), "an even stretch is still placed"); + } + + #[test] + fn only_axis_planars_are_placed() { + let bounds = (Vec3::NEG_ONE, Vec3::ONE); + assert!(placed_from_axis(&Projection::default(), bounds).is_none()); + let frame = axis_frame(1.0, 2, Vec3::ZERO, &Projector::default(), bounds).expect("a frame"); + assert!(placed_from_axis(&Projection::decal(frame), bounds).is_none()); + assert!(axis_frame(f32::NAN, 2, Vec3::ZERO, &Projector::default(), bounds).is_none()); + } +} diff --git a/crates/compose/src/fill_place.rs b/crates/compose/src/fill_place.rs new file mode 100644 index 00000000..2bad25f0 --- /dev/null +++ b/crates/compose/src/fill_place.rs @@ -0,0 +1,12 @@ +use texturecraft_core::Fill; + +use crate::projector_depth::ProjectorDepth; + +/// A fill as a texel samples it: the fill, its projector's depth map when it culls by depth, and whether it covers every texel +#[derive(Clone, Copy)] +pub(crate) struct FillPlace<'f> { + pub fill: &'f Fill, + pub depth: Option<&'f ProjectorDepth>, + /// Decided once per tile, so a texel never works its coverage out + pub covers_all: bool, +} diff --git a/crates/compose/src/mip_level.rs b/crates/compose/src/mip_level.rs new file mode 100644 index 00000000..4af44d24 --- /dev/null +++ b/crates/compose/src/mip_level.rs @@ -0,0 +1,35 @@ +//! One halved copy of an image resource, read by high-quality bilinear filtering when an image is shrunk + +use crate::store::texel_of; + +/// One halved copy of an image (box-filtered; see `halve` for its edges) +#[derive(Clone, Debug, PartialEq)] +pub struct MipLevel { + pub width: u32, + pub height: u32, + pub rgba: Vec<[f32; 4]>, +} + +/// Share of each of the 2 × 2 texels in a halved texel +const TEXEL_SHARE: f32 = 0.25; + +impl MipLevel { + /// `rgba` halved: each texel averages the 2 × 2 texels it covers (a size of 1 wraps; an odd size above leaves out its last row or column) + pub(crate) fn halve(rgba: &[[f32; 4]], width: u32, height: u32) -> MipLevel { + let (w, h) = ((width / 2).max(1), (height / 2).max(1)); + let mut halved = Vec::with_capacity(w as usize * h as usize); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let mut sum = [0.0f32; 4]; + for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] { + let texel = texel_of(rgba, width, height, x * 2 + dx, y * 2 + dy, (true, true)); + for (total, value) in sum.iter_mut().zip(texel) { + *total += value * TEXEL_SHARE; + } + } + halved.push(sum); + } + } + MipLevel { width: w, height: h, rgba: halved } + } +} diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 5634b3a1..f94b1d8b 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -1,7 +1,7 @@ //! Procedural patterns and projections. -use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_core::{Decal, FULL_TURN_DEGREES, Procedural, ProceduralKind, Projection, Projector, UvTransform}; +use texturecraft_geom::glam::{EulerRot, Mat3, Vec2, Vec3}; use texturecraft_texel::noise; use crate::pattern_context::PatternContext; @@ -381,7 +381,7 @@ const TRIPLANAR_SKIP: f32 = 1.0 / 131_072.0; /// to change a 0..1 value scaled by `gain` afterwards weigh 0 (see [`TRIPLANAR_SKIP`]). fn triplanar_weights(nrm: Vec3, sharpness: f32, gain: f32) -> Vec3 { let weights = sharpen(nrm.abs(), sharpness); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); let skip_threshold = TRIPLANAR_SKIP / gain.max(1.0); let retained = Vec3::select(weights.cmplt(Vec3::splat(skip_threshold)), Vec3::ZERO, weights); @@ -394,6 +394,132 @@ fn shape(pattern: &Procedural, value: f32) -> f32 { if pattern.invert { 1.0 - adjusted } else { adjusted } } +/// `point` turned by `rotation` degrees, scaled by `tiling` and moved by `offset`, as UV transformations place it +fn place(point: Vec2, tiling: Vec2, rotation: f32, offset: Vec2) -> Vec2 { + placement(tiling, rotation, offset)(point) +} + +/// [`place`] with its turn's sine and cosine worked out once, for a projection that places several points +fn placement(tiling: Vec2, rotation: f32, offset: Vec2) -> impl Fn(Vec2) -> Vec2 { + let (sin, cos) = rotation.to_radians().sin_cos(); + move |point| Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) * tiling + offset +} + +/// `point` placed as a 3D projection's UV transformation `uv` lays its image +fn place_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + uv_placement(uv)(point) +} + +/// [`place_uv`] worked out once for every point a projection places +fn uv_placement(uv: &UvTransform) -> impl Fn(Vec2) -> Vec2 { + placement(Vec2::from(uv.tiling), uv.rotation, Vec2::from(uv.offset)) +} + +/// 0..1 around a cylindrical projection's axis (`depth` over `across`), over an arc of `angle` degrees centred on the front +fn around(across: f32, depth: f32, angle: f32) -> f32 { + let turn = depth.atan2(across) / std::f32::consts::TAU + 0.5; + + // A full turn reads the turn untouched, as projects saved before the angle existed did, bit for bit + if angle == FULL_TURN_DEGREES { turn } else { (turn - 0.5) * FULL_TURN_DEGREES / angle.max(MIN_CYLINDER_ANGLE) + 0.5 } +} + +/// Narrowest arc in degrees a cylindrical projection wraps its image round, so a zero angle never divides by zero +pub const MIN_CYLINDER_ANGLE: f32 = *Projection::CYLINDER_ANGLE_RANGE.start(); + +/// How many pattern tiles a procedural lays round and down a spherical projection, so its cells stay near square +const SPHERE_PATTERN_TILES: Vec2 = Vec2::new(4.0, 2.0); + +/// How many pattern tiles a procedural lays round a cylindrical projection's axis +const CYLINDER_PATTERN_TILES: f32 = 4.0; + +/// Smallest sum of tri-planar blend weights, so a zero normal never divides by zero +const MIN_WEIGHT_SUM: f32 = 1e-6; + +/// Smallest frame side or depth (world units), so a flat frame never divides by zero +const MIN_FRAME_EXTENT: f32 = 1e-6; + +/// Where `coords` lies round a spherical projection: 0..1 round its pole axis and down from its top +fn spherical_uv(projector: &Projector, offset: &[f32; 3], coords: &Coords) -> Vec2 { + let direction = (projector_local(projector, coords).pos + Vec3::from(*offset)).try_normalize().unwrap_or(Vec3::Y); + let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5; + let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; + Vec2::new(u, v) +} + +/// The axis index (0 X, 1 Y, 2 Z) a cylindrical projection's stored `axis` wraps round: any value but X or Z reads as Y +pub fn cylinder_axis_index(axis: u8) -> usize { + match axis { + 0 => 0, + 2 => 2, + _ => 1, + } +} + +/// Where `coords` lies for a cylindrical projection round `axis`: 0..1 round the axis over `angle` degrees, and its height along the axis +fn cylinder_coords(axis: u8, projector: &Projector, offset: &[f32; 3], angle: f32, coords: &Coords) -> (f32, f32) { + let point = projector_local(projector, coords).pos + Vec3::from(*offset); + let (across, height, depth) = match cylinder_axis_index(axis) { + 0 => (point.y, point.x, point.z), + 2 => (point.x, point.z, point.y), + _ => (point.x, point.y, point.z), + }; + (around(across, depth, angle), height) +} + +/// Smallest mesh radius projections measure in, so a flat or empty mesh never divides by zero +const MIN_MESH_RADIUS: f32 = 1e-4; + +/// Nearest to zero a projection scale or stretch gets, so it never divides by zero +const MIN_STRETCH: f32 = 1e-6; + +/// The mesh's centre and its radius (half the diagonal) from its bounds +pub fn mesh_frame((lo, hi): (Vec3, Vec3)) -> (Vec3, f32) { + ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(MIN_MESH_RADIUS)) +} + +/// `value` kept at least [`MIN_STRETCH`] from zero, on its own side +pub fn nonzero_stretch(value: f32) -> f32 { + value.signum() * value.abs().max(MIN_STRETCH) +} + +/// A projector's per-axis scale with no axis at zero, each keeping its sign +pub fn projector_stretch(projector: &Projector) -> Vec3 { + Vec3::from(projector.scale).map(nonzero_stretch) +} + +/// The middle of a frame's 0..1 texture coordinates: a frame's image turns round it +pub const FRAME_UV_CENTER: Vec2 = Vec2::splat(0.5); + +/// `point` (0..1 across and down a frame) placed as `uv` lays a frame's image: turned round the frame's centre, then tiled and moved from its top left +pub fn place_frame_uv(point: Vec2, uv: &UvTransform) -> Vec2 { + // An unplaced image reads `point` itself, bit for bit as decals saved before image placement did + if *uv == UvTransform::default() { + return point; + } + + let tiling = Vec2::from(uv.tiling); + place(point - FRAME_UV_CENTER, tiling, uv.rotation, Vec2::from(uv.offset)) + FRAME_UV_CENTER * tiling +} + +/// The image placement a frame needs to lay images exactly as `uv` does from the top left (a frame turns its image round its centre) +pub fn frame_uv_from_corner(uv: &UvTransform) -> UvTransform { + let offset = place_uv(FRAME_UV_CENTER, uv) - FRAME_UV_CENTER * Vec2::from(uv.tiling); + UvTransform { offset: offset.to_array(), ..*uv } +} + +/// `coords` inside a projector turned and scaled by `projector`; the default projector returns `coords` unchanged +pub fn projector_local(projector: &Projector, coords: &Coords) -> Coords { + if !projector.turns() { + return *coords; + } + + let [x, y, z] = projector.rotation.map(f32::to_radians); + let to_local = Mat3::from_euler(EulerRot::ZYX, z, y, x).transpose(); + let scale = projector_stretch(projector); + let nrm = (to_local * coords.nrm * scale).try_normalize().unwrap_or(coords.nrm); + Coords { pos: to_local * coords.pos / scale, nrm, ..*coords } +} + /// Evaluate a procedural through a projection, at full resolution and without images pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { procedural_in(pattern, projection, coords, &PatternContext::default()) @@ -402,51 +528,41 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords /// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 { let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE); - let sample = |point: Vec3| plane_value(pattern, point, context); - let value = match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - // Evaluate two-dimensional patterns on a slice of the volume - sample((uv * pattern_scale).extend(0.0)) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + // Evaluate two-dimensional patterns on a slice of the volume + let flat = |point: Vec2| plane_value(pattern, point.extend(0.0), context); + let value = match projection { + Projection::UvTile => flat((coords.uv - coords.uv.floor()) * pattern_scale), + Projection::Uv { scale, rotation, offset } => flat(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset)) * pattern_scale), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale * pattern_scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Shape scales the blend by the contrast - let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); - let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))]; - planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum() + let weights = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); + let planes = [(weights.x, Vec2::new(point.z, point.y)), (weights.y, Vec2::new(point.x, point.z)), (weights.z, Vec2::new(point.x, point.y))]; + planes.into_iter().filter(|(weight, _)| *weight > 0.0).map(|(weight, plane)| flat(place_plane(plane)) * weight).sum() } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec3::new(p.z, p.y, 0.0), - 1 => Vec3::new(p.x, p.z, 0.0), - _ => Vec3::new(p.x, p.y, 0.0), + // The coordinates are already in the placed or warped frame (see [`placed_uv`] and [`crate::warp::warp_uv`]) + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => flat(place_frame_uv(coords.uv, uv) * pattern_scale), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale * pattern_scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, point.y), }; - sample(q) + flat(place_uv(plane, uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale) + Projection::Spherical { scale, uv, offset, projector } => { + let sphere = spherical_uv(projector, offset, coords); + flat(place_uv(sphere * SPHERE_PATTERN_TILES * *scale * pattern_scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale) + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + flat(place_uv(Vec2::new(around_axis * CYLINDER_PATTERN_TILES, height) * *scale * pattern_scale, uv)) } - - // The decal already supplied coordinates in its local frame - Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)), }; shape(pattern, value) @@ -476,7 +592,7 @@ fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f let base = grid.floor(); let fraction = grid - base; - let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context); + let at = |across: f32, down: f32| pattern_value(pattern, ((base + Vec2::new(across, down) + 0.5) / cells).extend(point.z), context); let top_left = at(0.0, 0.0); let bottom_left = at(0.0, 1.0); let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x; @@ -497,45 +613,37 @@ fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)]; match projection { - Projection::Uv { scale, rotation, offset } => { - let (sn, cs) = rotation.to_radians().sin_cos(); - let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); - one(uv) - } - Projection::Triplanar { scale, sharpness, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); + Projection::UvTile => one(coords.uv - coords.uv.floor()), + Projection::Uv { scale, rotation, offset } => one(place(coords.uv, Vec2::from(*scale), *rotation, Vec2::from(*offset))), + Projection::Triplanar { scale, sharpness, offset, uv, projector } => { + let coords = &projector_local(projector, coords); + let point = coords.pos * *scale + Vec3::from(*offset); + let place_plane = uv_placement(uv); // Float images can exceed 1, so even a tiny plane weight can carry visible detail let weights = coords.nrm.abs().powf(sharpness.max(1.0)); - let weights = weights / (weights.x + weights.y + weights.z).max(1e-6); - [(Vec2::new(p.z, -p.y), weights.x), (Vec2::new(p.x, p.z), weights.y), (Vec2::new(p.x, -p.y), weights.z)] + let weights = weights / (weights.x + weights.y + weights.z).max(MIN_WEIGHT_SUM); + [ + (place_plane(Vec2::new(point.z, -point.y)), weights.x), + (place_plane(Vec2::new(point.x, point.z)), weights.y), + (place_plane(Vec2::new(point.x, -point.y)), weights.z), + ] } - Projection::Planar { scale, axis, offset } => { - let p = coords.pos * *scale + Vec3::from(*offset); - let q = match axis { - 0 => Vec2::new(p.z, -p.y), - 1 => Vec2::new(p.x, p.z), - _ => Vec2::new(p.x, -p.y), + Projection::Planar { uv, placed: Some(_), .. } | Projection::Warp { uv, .. } => one(place_frame_uv(coords.uv, uv)), + Projection::Planar { scale, axis, offset, uv, projector, .. } => { + let point = projector_local(projector, coords).pos * *scale + Vec3::from(*offset); + let plane = match axis { + 0 => Vec2::new(point.z, -point.y), + 1 => Vec2::new(point.x, point.z), + _ => Vec2::new(point.x, -point.y), }; - one(q * 0.5 + Vec2::splat(0.5)) + one(place_uv(plane * 0.5 + Vec2::splat(0.5), uv)) } - Projection::Spherical { scale } => { - let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); - let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; - let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - one(Vec2::new(u, v) * *scale) + Projection::Spherical { scale, uv, offset, projector } => one(place_uv(spherical_uv(projector, offset, coords) * *scale, uv)), + Projection::Cylindrical { scale, axis, uv, offset, projector, angle } => { + let (around_axis, height) = cylinder_coords(*axis, projector, offset, *angle, coords); + one(place_uv(Vec2::new(around_axis, 0.5 - height * 0.5) * *scale, uv)) } - Projection::Cylindrical { scale, axis } => { - let p = coords.pos; - let (a, h, b) = match axis { - 0 => (p.y, p.x, p.z), - 2 => (p.x, p.z, p.y), - _ => (p.x, p.y, p.z), - }; - let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - one(Vec2::new(u, 0.5 - h * 0.5) * *scale) - } - Projection::Decal(_) => one(coords.uv), } } @@ -561,50 +669,55 @@ pub fn decal_corners(d: &Decal) -> Option<[Vec3; 4]> { Some([o - r * hw + u * hh, o + r * hw + u * hh, o + r * hw - u * hh, o - r * hw - u * hh]) } -/// Where world point `p` with surface normal `nrm` falls in the decal: texture coordinates -/// (v down) and how much the decal covers it, None outside the frame, behind it, beyond its -/// depth or on faces turned away. Coverage fades on grazing faces and near the depth limit. -pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { - let (o, r, u, n) = decal_axes(d)?; - let facing = nrm.dot(n); - let q = p - o; - let (lx, ly, lz) = (q.dot(r) / d.size[0].max(1e-6), q.dot(u) / d.size[1].max(1e-6), q.dot(n).abs()); - let depth = d.depth.max(1e-6); - if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) { - return None; +/// World point `point` in frame `frame` turned and scaled by `projector`: across and up in frame sizes, out along its normal in world units +pub fn frame_local(frame: &Decal, projector: &Projector, point: Vec3) -> Option { + let (origin, right, up, normal) = decal_axes(frame)?; + let from_origin = point - origin; + let mut local = Vec3::new(from_origin.dot(right), from_origin.dot(up), from_origin.dot(normal)); + if projector.turns() { + local = projector_local(projector, &Coords { uv: Vec2::ZERO, pos: local, nrm: Vec3::Z }).pos; } - let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz)); - Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w)) + let local = Vec3::new(local.x / frame.size[0].max(MIN_FRAME_EXTENT), local.y / frame.size[1].max(MIN_FRAME_EXTENT), local.z); + local.is_finite().then_some(local) } -/// `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 }) -} - -/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the -/// point more. The copy is the decal reflected through the plane across `center` (the mesh -/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked. -pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { - let direct = decal_uv(d, p, nrm); - let Some(symmetry) = d.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 = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| { - 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), +/// How squarely a surface with normal `nrm` faces frame `frame` turned by `projector` (the cosine of the turn) +pub fn frame_facing(frame: &Decal, projector: &Projector, nrm: Vec3) -> f32 { + let Some((_, right, up, normal)) = decal_axes(frame) else { return 0.0 }; + if !projector.turns() { + return nrm.dot(normal); } + + let turned = Vec3::new(nrm.dot(right), nrm.dot(up), nrm.dot(normal)); + projector_local(projector, &Coords { uv: Vec2::ZERO, pos: Vec3::ZERO, nrm: turned }).nrm.z +} + +/// Texture coordinates (v down) of a point at `local` in its frame (see [`frame_local`]) +pub fn placed_uv(local: Vec3) -> Vec2 { + Vec2::new(local.x + 0.5, 0.5 - local.y) +} + +/// How much frame `frame` covers a point at `local` when cropped to its shape: 0 outside the frame or past its depth, fading near the depth +pub fn frame_crop(frame: &Decal, local: Vec3) -> f32 { + if local.x.abs() > 0.5 || local.y.abs() > 0.5 { + return 0.0; + } + + depth_fade(local.z, frame.depth) +} + +/// Where a frame's depth fade starts, as a share of its depth +pub const DEPTH_FADE_START: f32 = 0.75; + +/// How much a frame reaching `depth` in front of and behind it covers a point `z` out from it: 0 past the depth, fading near it +pub fn depth_fade(z: f32, depth: f32) -> f32 { + let (distance, depth) = (z.abs(), depth.max(MIN_FRAME_EXTENT)); + if distance > depth { + return 0.0; + } + + 1.0 - smoothstep(DEPTH_FADE_START * depth, depth, distance) } /// World-space noise used by generators (seamless across UV islands). @@ -642,15 +755,98 @@ mod tests { assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); } + /// A stored cylinder axis past Z (only a hand-edited project holds one) wraps round Y + #[test] + fn a_cylinder_axis_past_z_reads_as_y() { + assert_eq!([0, 1, 2, 3, u8::MAX].map(cylinder_axis_index), [0, 1, 2, 1, 1]); + } + + /// A decal saved before image placement reads its frame coordinates bit for bit as it did: its image at them, its procedural at them times the pattern scale + #[test] + fn an_unplaced_decal_reads_its_frame_coordinates_bit_for_bit() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let decal = Projection::decal(frame); + let pattern = Procedural { scale: 3.0, ..Procedural::new(ProceduralKind::Gradient) }; + for across in 0..=1000 { + for down in [0.0, 0.1, 0.37, 1.0] { + let uv = Vec2::new(across as f32 / 1000.0, down); + let coords = Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + assert_eq!(image_samples(&decal, &coords)[0].0, uv, "image at {uv}"); + + let expected = shape(&pattern, raw(pattern.kind, (uv * pattern.scale).extend(0.0), pattern.seed)); + assert_eq!(procedural(&pattern, &decal, &coords).to_bits(), expected.to_bits(), "procedural at {uv}"); + } + } + } + + /// A frame's image turns round the frame's centre: the centre reads the same texel at any Rotation, and an unturned image reads exactly as before for any Tiling and Offset + #[test] + fn a_frame_image_turns_round_the_frame_centre() { + let frame = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [1.0; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let at = |uv: Vec2| Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Z }; + let sample = |rotation: f32, tiling: [f32; 2], offset: [f32; 2], uv: Vec2| { + image_samples( + &Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: 0.1, + uv: UvTransform { tiling, rotation, offset }, + projector: Projector::default(), + }, + &at(uv), + )[0] + .0 + }; + for rotation in [37.0, 90.0, 180.0] { + let center = sample(rotation, [1.0; 2], [0.0; 2], FRAME_UV_CENTER); + assert!((center - FRAME_UV_CENTER).length() < 1e-5, "{rotation}°: the centre stays put, not swung round the top left: {center}"); + } + let corner = sample(90.0, [1.0; 2], [0.0; 2], Vec2::ZERO); + assert!((corner - Vec2::new(1.0, 0.0)).length() < 1e-5, "a quarter turn brings the top left to the top right: {corner}"); + let placed = Projection::Planar { + scale: 1.0, + axis: 2, + offset: [0.0; 3], + uv: UvTransform { rotation: 90.0, ..UvTransform::default() }, + projector: Projector::default(), + placed: Some(frame), + }; + assert!((image_samples(&placed, &at(FRAME_UV_CENTER))[0].0 - FRAME_UV_CENTER).length() < 1e-5, "a placed planar frame turns the same way"); + for (tiling, offset, uv) in [([2.0, 3.0], [0.25, -0.5], Vec2::new(0.1, 0.8)), ([1.0, 1.0], [0.0, 0.0], Vec2::new(0.7, 0.2))] { + let before = uv * Vec2::from(tiling) + Vec2::from(offset); + assert!((sample(0.0, tiling, offset, uv) - before).length() < 1e-6, "unturned: as before"); + } + } + #[test] fn every_pattern_and_projection_stays_in_range() { let projections = [ Projection::default(), - Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] }, - Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] }, - Projection::Spherical { scale: 1.0 }, - Projection::Cylindrical { scale: 1.0, axis: 1 }, - Projection::Decal(Decal { + Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3], uv: Default::default(), projector: Default::default() }, + Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3], uv: Default::default(), projector: Default::default(), placed: None }, + Projection::Spherical { scale: 1.0, uv: Default::default(), offset: [0.0; 3], projector: Default::default() }, + Projection::Cylindrical { scale: 1.0, axis: 1, uv: Default::default(), offset: [0.0; 3], projector: Default::default(), angle: FULL_TURN_DEGREES }, + Projection::decal(Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], @@ -662,20 +858,17 @@ mod tests { flip: [false; 2], }), ]; - for kind in ProceduralKind::ALL { let pattern = Procedural::new(kind); for projection in &projections { - for i in 0..50 { - let t = i as f32 * 0.13; + for index in 0..50 { + let position = index as f32 * 0.13; let coords = Coords { - uv: Vec2::new(t.fract(), (t * 0.7).fract()), - pos: Vec3::new(t.sin(), t.cos(), t * 0.1), + uv: Vec2::new(position.fract(), (position * 0.7).fract()), + pos: Vec3::new(position.sin(), position.cos(), position * 0.1), nrm: Vec3::new(0.3, 0.9, 0.1).normalize(), }; - let value = procedural(&pattern, projection, &coords); - assert!((0.0..=1.0).contains(&value), "{kind:?} {projection:?} {value}"); } } @@ -702,7 +895,8 @@ mod tests { for contrast in [1.0, 4.0, 16.0] { let pattern = Procedural { contrast, ..Procedural::new(kind) }; for sharpness in [1.0, 4.0, 8.0, 16.0] { - let projection = Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3] }; + let projection = + Projection::Triplanar { scale: 1.0, sharpness, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; for index in 0..400 { // Cover axis aligned and oblique normals at varied positions let position = index as f32 / 400.0; @@ -731,9 +925,9 @@ mod tests { #[test] fn triplanar_image_sampling_preserves_bright_float_pixels() { - let image = crate::ImageRes { width: 2, height: 2, rgba: vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], srgb: false }; + let image = crate::ImageRes::new(2, 2, vec![[0.0; 4], [0.0; 4], [0.0; 4], [100_000.0; 4]], false); let coords = Coords { uv: Vec2::ZERO, pos: Vec3::new(0.25, 0.25, 0.75), nrm: Vec3::new(0.2, 1.0, 0.1).normalize() }; - let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }; + let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; let weights = coords.nrm.abs().powf(8.0); let expected = 100_000.0 * weights.x / (weights.x + weights.y + weights.z); @@ -761,6 +955,12 @@ mod tests { } } + /// Where frame `frame`'s planar projection lands at `point` facing `nrm`, None where it does not cover + fn decal_uv(frame: &Decal, point: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { + let Projection::Planar { projector, .. } = Projection::decal(*frame) else { return None }; + crate::projector_cover::placed_cover(frame, &projector, point, nrm).filter(|(_, cover)| *cover > 0.0) + } + #[test] fn decals_cover_their_frame_facing_them() { let d = Decal { diff --git a/crates/compose/src/tile_length.rs b/crates/compose/src/tile_length.rs new file mode 100644 index 00000000..c08e668f --- /dev/null +++ b/crates/compose/src/tile_length.rs @@ -0,0 +1,155 @@ +//! How long one repeat of a fill's tile is on the mesh (mesh units): Physical size reads it from the tiling and writes tiling back + +use std::f32::consts::TAU; + +use texturecraft_core::{FULL_TURN_DEGREES, Projection}; + +use crate::pattern::{MIN_CYLINDER_ANGLE, cylinder_axis_index, projector_stretch}; + +/// The mesh's size as the projections see it: the bounds radius (3D projections) and the mesh units one UV unit covers (UV) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshSize { + pub radius: f32, + pub uv_density: f32, +} + +/// Mesh units one tile covers across and down at a tiling of 1, the projector's stretch included; None without a physical size (per UV tile, spherical, or a stretch uneven across the planes a tile wraps round) +fn unit_tile(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let radius = size.radius; + match projection { + Projection::Uv { .. } => Some([size.uv_density; 2]), + Projection::Triplanar { scale, projector, .. } => { + // Every plane repeats in the one length only while the stretch is even + let stretch = projector_stretch(projector).abs(); + let even = stretch.x == stretch.y && stretch.y == stretch.z; + even.then_some([radius * stretch.x / scale; 2]) + } + Projection::Planar { placed: Some(frame), projector, .. } | Projection::Warp { frame, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + Some([frame.size[0] * stretch.x, frame.size[1] * stretch.y]) + } + Projection::Planar { scale, axis, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let [across, down] = match axis { + 0 => [stretch.z, stretch.y], + 1 => [stretch.x, stretch.z], + _ => [stretch.x, stretch.y], + }; + Some([2.0 * radius * across / scale, 2.0 * radius * down / scale]) + } + Projection::Cylindrical { scale, axis, angle, projector, .. } => { + let stretch = projector_stretch(projector).abs(); + let ([across, depth], height) = match cylinder_axis_index(*axis) { + 0 => ([stretch.y, stretch.z], stretch.x), + 2 => ([stretch.x, stretch.y], stretch.z), + _ => ([stretch.x, stretch.z], stretch.y), + }; + + // Round an uneven cross-section the turn is no fixed length of surface + if across != depth { + return None; + } + + let around = TAU * radius * across * (angle.max(MIN_CYLINDER_ANGLE) / FULL_TURN_DEGREES); + Some([around / scale, 2.0 * radius * height / scale]) + } + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// The tiling a physical size reads and writes: UV's own tiling, a 3D projection's UV tiling +fn tiling(projection: &Projection) -> Option<[f32; 2]> { + match projection { + Projection::Uv { scale, .. } => Some(*scale), + Projection::Triplanar { uv, .. } | Projection::Planar { uv, .. } | Projection::Cylindrical { uv, .. } | Projection::Warp { uv, .. } => Some(uv.tiling), + Projection::UvTile | Projection::Spherical { .. } => None, + } +} + +/// Mesh units one repeat of the tile covers across and down +pub fn tile_length(projection: &Projection, size: MeshSize) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + let tiling = tiling(projection)?; + Some([unit[0] / tiling[0].max(f32::EPSILON), unit[1] / tiling[1].max(f32::EPSILON)]) +} + +/// The tiling that makes one repeat `length` mesh units long across and down +pub fn tiling_for_length(projection: &Projection, size: MeshSize, length: [f32; 2]) -> Option<[f32; 2]> { + let unit = unit_tile(projection, size)?; + Some([unit[0] / length[0].max(f32::EPSILON), unit[1] / length[1].max(f32::EPSILON)]) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pattern::{Coords, image_samples}; + use texturecraft_core::{Projector, UvTransform}; + use texturecraft_geom::glam::{Vec2, Vec3}; + + const SIZE: MeshSize = MeshSize { radius: 2.0, uv_density: 3.0 }; + + #[test] + fn uv_tile_length_is_the_uv_density_over_the_tiling() { + let uv = Projection::Uv { scale: [2.0, 4.0], rotation: 0.0, offset: [0.0; 2] }; + assert_eq!(tile_length(&uv, SIZE), Some([1.5, 0.75])); + } + + #[test] + fn a_length_read_back_gives_the_same_tiling() { + let uv = UvTransform { tiling: [3.0, 1.5], ..UvTransform::default() }; + for projection in [ + Projection::Uv { scale: [3.0, 1.5], rotation: 0.0, offset: [0.0; 2] }, + Projection::Triplanar { scale: 1.5, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector: Default::default() }, + Projection::Planar { scale: 0.5, axis: 2, offset: [0.0; 3], uv, projector: Default::default(), placed: None }, + Projection::Cylindrical { scale: 2.0, axis: 1, uv, offset: [0.0; 3], projector: Default::default(), angle: 360.0 }, + ] { + let length = tile_length(&projection, SIZE).unwrap(); + let tiling = tiling_for_length(&projection, SIZE, length).unwrap(); + assert!((tiling[0] - 3.0).abs() < 1e-5 && (tiling[1] - 1.5).abs() < 1e-5, "{projection:?}: {tiling:?}"); + } + } + + #[test] + fn a_written_length_is_the_repeat_on_the_mesh_through_a_stretched_projector() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let axis_planar = |uv| Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv, projector, placed: None }; + let length = 2.0; + + let tiling = tiling_for_length(&axis_planar(UvTransform::default()), SIZE, [length; 2]).unwrap(); + let planar = axis_planar(UvTransform { tiling, ..UvTransform::default() }); + let at = |x: f32, y: f32| image_samples(&planar, &Coords { uv: Vec2::ZERO, pos: Vec3::new(x, y, 0.0) / SIZE.radius, nrm: Vec3::Z })[0].0; + let across = at(0.3 + length, 0.1) - at(0.3, 0.1); + let down = at(0.3, 0.1 + length) - at(0.3, 0.1); + + assert_eq!(tile_length(&axis_planar(UvTransform::default()), SIZE), Some([8.0, 4.0]), "the stretch doubles the repeat across"); + assert!((across.x.abs() - 1.0).abs() < 1e-4 && across.y.abs() < 1e-4, "one length across is one tile: {across}"); + assert!(down.x.abs() < 1e-4 && (down.y.abs() - 1.0).abs() < 1e-4, "one length down is one tile: {down}"); + } + + #[test] + fn a_stretch_uneven_round_the_planes_has_no_physical_size() { + let projector = Projector { scale: [2.0, 1.0, 1.0], ..Projector::default() }; + let uv = UvTransform::default(); + + let triplanar = Projection::Triplanar { scale: 1.0, sharpness: Projection::TRIPLANAR_SHARPNESS, offset: [0.0; 3], uv, projector }; + let cylinder = Projection::Cylindrical { scale: 1.0, axis: 1, uv, offset: [0.0; 3], projector, angle: 360.0 }; + let along_axis = Projection::Cylindrical { scale: 1.0, axis: 0, uv, offset: [0.0; 3], projector, angle: 360.0 }; + + assert_eq!(tile_length(&triplanar, SIZE), None); + assert_eq!(tile_length(&cylinder, SIZE), None); + assert_eq!(tile_length(&along_axis, SIZE).map(|[_, down]| down), Some(8.0), "a stretch along the axis lengthens the repeat down it"); + } + + #[test] + fn a_cylinder_of_no_angle_still_has_a_length() { + let flat = Projection::Cylindrical { scale: 1.0, axis: 1, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default(), angle: 0.0 }; + let length = tile_length(&flat, SIZE).unwrap(); + assert!(length[0] > 0.0, "{length:?}"); + assert!(tiling_for_length(&flat, SIZE, length).unwrap()[0] > 0.0, "a written-back tiling is never 0"); + } + + #[test] + fn spherical_has_no_physical_size() { + assert_eq!(tile_length(&Projection::Spherical { scale: 1.0, uv: UvTransform::default(), offset: [0.0; 3], projector: Default::default() }, SIZE), None); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index ebd2ae0d..b9677515 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -108,6 +108,10 @@ impl HeightMask { } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[expect( + clippy::large_enum_variant, + reason = "a fill holds its projection inline; boxing it would cost every fill read an indirection to save a few hundred bytes per paint layer or folder" +)] pub enum LayerKind { /// Painted pixels, stored per channel by the engine under the layer id. Paint, @@ -178,20 +182,90 @@ impl Layer { pub enum Projection { /// Texture coordinates of the mesh. Uv { scale: [f32; 2], rotation: f32, offset: [f32; 2] }, + /// The source stretched once over each UV tile (0..1 in every tile) + UvTile, /// World-space box projection blended by the normal. - Triplanar { scale: f32, sharpness: f32, offset: [f32; 3] }, - /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z). - Planar { scale: f32, axis: u8, offset: [f32; 3] }, - /// Spherical projection around the mesh center. - Spherical { scale: f32 }, - /// Cylindrical projection around an axis. - Cylindrical { scale: f32, axis: u8 }, - /// A geometry decal: the image projected from a frame placed on the surface (outside the - /// frame, behind it or beyond its depth the fill does not cover). - Decal(Decal), + Triplanar { + scale: f32, + sharpness: f32, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z), or from a frame placed on the surface + Planar { + scale: f32, + axis: u8, + offset: [f32; 3], + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The frame it projects from when placed on the surface (scale, axis and offset then unused) + #[serde(default, skip_serializing_if = "Option::is_none")] + placed: Option, + }, + /// Spherical projection around the mesh center + Spherical { + scale: f32, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + }, + /// Cylindrical projection around an axis + Cylindrical { + scale: f32, + axis: u8, + #[serde(default, skip_serializing_if = "UvTransform::is_default")] + uv: UvTransform, + #[serde(default, skip_serializing_if = "is_zero_offset")] + offset: [f32; 3], + #[serde(default, skip_serializing_if = "Projector::is_default")] + projector: Projector, + /// The arc one repeat of the source spans around the axis (degrees), centred on the front + #[serde(default = "full_turn", skip_serializing_if = "is_full_turn")] + angle: f32, + }, + /// A planar projection from a frame whose four corners are pulled freely, bending the image to the quad they make + Warp { + /// The frame it projects from (its depth is unused: `depth` sets the reach) + frame: Decal, + /// Where the frame's corners sit (top left, top right, bottom right, bottom left), across and up in frame sizes from its centre + corners: [[f32; 2]; 4], + /// Projection Depth: how far in front of and behind the frame it reaches when cropped to its shape, in lengths of the frame's longer side + depth: f32, + uv: UvTransform, + projector: Projector, + }, } -/// The frame a decal projects from (world space). +/// Tiling, rotation (degrees) and offset a 3D projection lays on the surface; the default changes nothing +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct UvTransform { + pub tiling: [f32; 2], + pub rotation: f32, + pub offset: [f32; 2], +} + +impl Default for UvTransform { + fn default() -> Self { + UvTransform { tiling: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } + } +} + +impl UvTransform { + /// Whether it changes nothing, as projections saved before it existed did (not saved then) + pub fn is_default(&self) -> bool { + *self == UvTransform::default() + } +} + +/// The frame a planar projection placed on the surface (a decal) projects from, in world space #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Decal { /// The surface point the decal was placed on. @@ -222,6 +296,21 @@ fn not_flipped(flip: &[bool; 2]) -> bool { !flip[0] && !flip[1] } +/// Serde default of a cylindrical projection's angle: the whole way round +fn full_turn() -> f32 { + crate::FULL_TURN_DEGREES +} + +/// Whether a cylindrical projection spans the whole way round, as ones saved before the angle did (not saved then) +fn is_full_turn(angle: &f32) -> bool { + *angle == full_turn() +} + +/// Whether a spherical or cylindrical projection sits unshifted, as ones saved before the offset did (not saved then) +fn is_zero_offset(offset: &[f32; 3]) -> bool { + *offset == [0.0; 3] +} + impl Default for Projection { fn default() -> Self { Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] } @@ -229,14 +318,88 @@ impl Default for Projection { } impl Projection { + /// A warp's corners before any is pulled: the frame's own + pub const FRAME_CORNERS: [[f32; 2]; 4] = [[-0.5, 0.5], [0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]]; + + /// A new warp's Projection Depth + pub const WARP_DEPTH: f32 = 0.1; + + /// A new tri-planar projection's blend sharpness + pub const TRIPLANAR_SHARPNESS: f32 = 8.0; + + /// The blend sharpness a tri-planar projection takes: an exponent from soft (1) to near hard (64) + pub const TRIPLANAR_SHARPNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + + /// The arc in degrees a cylindrical projection wraps its image round; a zero arc would divide by zero + pub const CYLINDER_ANGLE_RANGE: std::ops::RangeInclusive = 1.0..=crate::FULL_TURN_DEGREES; + + /// A tri-planar projection with a new fill's settings + pub fn triplanar() -> Projection { + Projection::Triplanar { + scale: 1.0, + sharpness: Self::TRIPLANAR_SHARPNESS, + offset: [0.0; 3], + uv: UvTransform::default(), + projector: Projector::default(), + } + } + + /// A warp projection from `frame` with its corners where the frame's are + pub fn warp(frame: Decal) -> Projection { + Projection::Warp { + frame, + corners: Projection::FRAME_CORNERS, + depth: Projection::WARP_DEPTH, + uv: UvTransform::default(), + projector: Projector::depth_culled(), + } + } + + /// A planar projection from `frame` with a decal's look: cropped to its frame, depth and image alpha, off faces turned away + pub fn decal(frame: Decal) -> Projection { + let projector = Projector { crop: ShapeCrop::Cropped, backface: Backface { on: true, ..Backface::default() }, ..Projector::default() }; + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector, placed: Some(frame) } + } + + /// The depth culling of a planar or warp projection that has it on + pub fn depth_culling(&self) -> Option { + match self { + Projection::Planar { projector, .. } | Projection::Warp { projector, .. } => Some(projector.depth).filter(|depth| depth.on), + _ => None, + } + } + + /// Whether the projection works in 3D, so a fill's symmetry can copy it (UV projections cannot) + pub fn takes_symmetry(&self) -> bool { + !matches!(self, Projection::Uv { .. } | Projection::UvTile) + } + + /// The frame on the surface a placed planar projection projects from + pub fn placed(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + _ => None, + } + } + + /// The frame on the surface a placed planar or a warp projection projects from + pub fn frame(&self) -> Option<&Decal> { + match self { + Projection::Planar { placed, .. } => placed.as_ref(), + Projection::Warp { frame, .. } => Some(frame), + _ => None, + } + } + pub fn label(&self) -> &'static str { match self { + Projection::UvTile => "Fill (Match per UV Tile)", Projection::Uv { .. } => "UV projection", Projection::Triplanar { .. } => "Tri-planar projection", Projection::Planar { .. } => "Planar projection", Projection::Spherical { .. } => "Spherical projection", Projection::Cylindrical { .. } => "Cylindrical projection", - Projection::Decal(_) => "Decal projection", + Projection::Warp { .. } => "Warp projection", } } } @@ -550,7 +713,10 @@ impl Source { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Fill { pub sources: BTreeMap, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] pub projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + pub sampling: Sampling, /// Set when the sources are maps cooked from a MaterialCraft material. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option>, @@ -1179,7 +1345,10 @@ pub enum EffectKind { /// A uniform or procedural grayscale fill. Fill { source: Source, + #[serde(serialize_with = "crate::saved_projection::save", deserialize_with = "crate::saved_projection::load")] projection: Projection, + #[serde(default = "Sampling::saved_before", skip_serializing_if = "Sampling::is_saved_before")] + sampling: Sampling, }, Generator(Generator), Levels(Levels), @@ -1198,10 +1367,7 @@ pub enum EffectKind { /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). Material(Fill), - /// Records the stack at its place so masks, fills and generators above can read it - /// ([`Source::Anchor`]). In a content stack it records the composited stack right after its - /// layer (that layer and everything below); in a mask, the mask value at that point (every - /// channel reads that gray). + /// Records the stack at its place so masks, fills and generators above can read it ([`Source::Anchor`]): in a content stack the composited stack right after its layer (that layer and everything below), in a mask the mask value there (every channel reads that gray) Anchor, } @@ -1547,21 +1713,27 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); + let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); + let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { - effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], + effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); + assert!(fill_layer.reads_anchor()); // A generator with micro detail reads its anchor too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); + assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(generator_layer.reads_anchor()); } @@ -1605,6 +1777,31 @@ mod tests { } } + #[test] + fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { + let fills = [ + r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, + r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, + r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, + ]; + for saved in fills { + let loaded: Fill = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); + } + + let effects = [ + r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, + ]; + for saved in effects { + let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); + } + } + #[test] fn procedural_kinds_parse_labels_and_saved_names() { for kind in ProceduralKind::ALL { diff --git a/crates/engine/tests/it/fill_patterns.rs b/crates/engine/tests/it/fill_patterns.rs new file mode 100644 index 00000000..c5d854ba --- /dev/null +++ b/crates/engine/tests/it/fill_patterns.rs @@ -0,0 +1,69 @@ +//! A fill's procedural pattern through `layer.fill.set`: a parameter given alone changes only itself + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Procedural, ProceduralKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A fill layer whose roughness is a Clouds pattern with every parameter away from its default +fn clouds_fill() -> (Session, LayerId) { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let pattern = json!({ + "layer": layer.0, "channel": "roughness", "procedural": "Clouds", "scale": 9.0, "contrast": 1.5, "seed": 7, + "balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], + }); + execute(&mut session, "layer.fill.set", &pattern).unwrap(); + (session, layer) +} + +/// The roughness pattern and its Low and High colours +type Roughness = (Procedural, [f32; 3], [f32; 3]); + +fn roughness(session: &Session, layer: LayerId) -> Roughness { + match &session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => match fill.source(Channel::Roughness) { + Source::Procedural { pattern, low, high, .. } => (pattern, low, high), + other => panic!("not a procedural: {other:?}"), + }, + other => panic!("not a fill: {other:?}"), + } +} + +/// One parameter sent alone, its value, and what it changes in the stored pattern +type PatternEdit = (&'static str, Value, fn(&mut Roughness)); + +/// What the Scale, Contrast, Seed, Balance and Invert controls and the Low/High swatches send: one parameter each +#[test] +fn a_pattern_parameter_given_alone_keeps_every_other_one() { + let (mut session, layer) = clouds_fill(); + let edits: [PatternEdit; 7] = [ + ("scale", json!(3.0), |(pattern, ..)| pattern.scale = 3.0), + ("contrast", json!(0.5), |(pattern, ..)| pattern.contrast = 0.5), + ("seed", json!(42), |(pattern, ..)| pattern.seed = 42), + ("balance", json!(-0.5), |(pattern, ..)| pattern.balance = -0.5), + ("invert", json!(false), |(pattern, ..)| pattern.invert = false), + ("low", json!([0.1, 0.1, 0.1]), |(_, low, _)| *low = [0.1; 3]), + ("high", json!([0.9, 0.9, 0.9]), |(.., high)| *high = [0.9; 3]), + ]; + for (key, value, change) in edits { + let mut expected = roughness(&session, layer); + change(&mut expected); + let mut edit = json!({"layer": layer.0, "channel": "roughness", "procedural": "Clouds"}); + edit[key] = value; + execute(&mut session, "layer.fill.set", &edit).unwrap(); + + assert_eq!(roughness(&session, layer), expected, "`{key}` alone changes only itself"); + } + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"balance\":-0.5") && inspected.contains("\"invert\":false"), "inspect shows the balance and invert"); +} + +/// Another kind is a new pattern: its defaults between black and white, as before +#[test] +fn another_pattern_kind_starts_from_its_defaults() { + let (mut session, layer) = clouds_fill(); + execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "procedural": "Cells"})).unwrap(); + assert_eq!(roughness(&session, layer), (Procedural::new(ProceduralKind::Cells), [0.0; 3], [1.0; 3])); +} diff --git a/crates/engine/tests/it/fill_sampling.rs b/crates/engine/tests/it/fill_sampling.rs new file mode 100644 index 00000000..fd17f481 --- /dev/null +++ b/crates/engine/tests/it/fill_sampling.rs @@ -0,0 +1,218 @@ +//! How fills read their image sources (filtering), through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, Fill, Filtering, LayerId, LayerKind, Projection, Sampling, ScaleMode}; +use texturecraft_engine::geom::NO_TRI; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.update(); + s +} + +fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// A fill layer whose base color is a one-texel black and white checker, tiled `tiling` times +fn checker_fill(s: &mut Session, tiling: f32) -> LayerId { + let name = s.import_resource_bytes("checker.png", png(64, 64, |x, y| if (x + y) % 2 == 0 { [255; 4] } else { [0, 0, 0, 255] })).unwrap(); + let layer = LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(s, "layer.fill.set", &json!({"layer": layer.0, "channel": "baseColor", "image": name})).unwrap(); + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "scale": tiling})).unwrap(); + layer +} + +/// Lowest and highest base color red across the covered texels of the set's middle band +fn spread(s: &mut Session) -> (f32, f32) { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let mut range = (f32::MAX, f32::MIN); + for y in h * 3 / 8..h * 5 / 8 { + for x in w / 4..w * 3 / 4 { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + range = (range.0.min(red), range.1.max(red)); + } + } + } + range +} + +fn filtering(s: &mut Session, layer: LayerId, id: &str) { + execute(s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": id})).unwrap(); +} + +/// A checker shrunk to two image texels per texel: HQ averages it, Sharp aliases it, Nearest keeps black and white +#[test] +fn filtering_decides_how_a_shrunk_image_reads() { + let mut s = session(); + let layer = checker_fill(&mut s, 7.3); + let (lo, hi) = spread(&mut s); + assert!(hi - lo < 0.2, "a new fill reads with Bilinear | HQ: an even gray, got {lo}..{hi}"); + + filtering(&mut s, layer, "bilinearSharp"); + let (lo, hi) = spread(&mut s); + assert!(hi - lo > 0.5, "Bilinear | Sharp aliases a shrunk checker: {lo}..{hi}"); + + filtering(&mut s, layer, "nearest"); + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let pure = (h * 3 / 8..h * 5 / 8) + .flat_map(|y| (w / 4..w * 3 / 4).map(move |x| (x, y))) + .filter(|&(x, y)| cache.gbuf.tri[(y * w + x) as usize] != NO_TRI) + .all(|(x, y)| { + let red = cache.composite.value(Channel::BaseColor, x, y)[0]; + !(0.01..=0.99).contains(&red) + }); + assert!(pure, "Nearest reads one image texel: black or white only"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["filtering"], json!("nearest")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "filtering": "trilinear"})).is_err()); +} + +/// Fills saved before Filtering existed read images as before (plain bilinear); new fills start on Bilinear | HQ +#[test] +fn fills_saved_before_filtering_keep_their_look() { + let mut s = session(); + let layer = checker_fill(&mut s, 1.0); + let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + assert_eq!(fill.sampling.filtering, Filtering::BilinearHq); + + let mut saved = serde_json::to_value(fill).unwrap(); + saved.as_object_mut().unwrap().remove("sampling"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling, Sampling::SAVED_BEFORE); + assert_eq!(loaded.sampling.filtering, Filtering::BilinearSharp); +} + +/// Share of the middle band's covered texels where the white fill shows over the black layer below +fn shown(s: &mut Session) -> f32 { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + let (mut on, mut all) = (0usize, 0usize); + for y in h * 3 / 8..h * 5 / 8 { + for x in 0..w { + if cache.gbuf.tri[(y * w + x) as usize] != NO_TRI { + all += 1; + on += usize::from(cache.composite.value(Channel::BaseColor, x, y)[0] > 0.5); + } + } + } + on as f32 / all.max(1) as f32 +} + +/// UV Wrap on a white fill tiled 4 × 2: Repeat covers the band, None one tile, one-axis repeats in between +#[test] +fn uv_wrap_repeats_the_tile_or_stops_at_its_edge() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + set(&mut s, json!({"scale": [4, 2]})).unwrap(); + let near = |got: f32, want: f32| (got - want).abs() < 0.05; + let repeat = shown(&mut s); + assert!(near(repeat, 1.0), "Repeat covers the band: {repeat}"); + set(&mut s, json!({"wrap": "none"})).unwrap(); + let none = shown(&mut s); + assert!(near(none, 0.125), "None: a quarter across, half down: {none}"); + set(&mut s, json!({"wrap": "repeatHorizontally"})).unwrap(); + let across = shown(&mut s); + assert!(near(across, 0.5), "repeating across: the whole width, half down: {across}"); + set(&mut s, json!({"wrap": "repeatVertically"})).unwrap(); + let down = shown(&mut s); + assert!(near(down, 0.25), "repeating down: a quarter across, the whole height: {down}"); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["wrap"], json!("repeatVertically")); + assert!(set(&mut s, json!({"wrap": "mirror"})).is_err()); + + // Tri-planar has no tile: it covers whatever the wrap says + set(&mut s, json!({"projection": "triplanar", "wrap": "none"})).unwrap(); + let triplanar = shown(&mut s); + assert!(near(triplanar, 1.0), "{triplanar}"); +} + +/// 3D projections take UV transformations; older saves look as they did; world scale and offset stay separate +#[test] +fn three_d_projections_take_uv_transformations() { + use texturecraft_engine::core::{Projection, UvTransform}; + let mut s = session(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer.0); + execute(s, "layer.fill.projection", &p) + }; + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer.0, "channel": "baseColor", "procedural": "Checker", "scale": 4, "low": [0, 0, 0], "high": [1, 1, 1]}), + ) + .unwrap(); + set(&mut s, json!({"projection": "triplanar"})).unwrap(); + let projection = |s: &Session| match &s.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(f) => f.projection.clone(), + _ => panic!("a fill layer"), + }; + let snapshot = |s: &mut Session| { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h).map(|i| cache.composite.value(Channel::BaseColor, i % w, i / w)[0]).collect::>() + }; + let plain = snapshot(&mut s); + + set(&mut s, json!({"tiling": [2, 3], "rotation": 45, "uvOffset": [0.25, 0.5]})).unwrap(); + let Projection::Triplanar { uv, scale, .. } = projection(&s) else { panic!("tri-planar") }; + assert_eq!(uv, UvTransform { tiling: [2.0, 3.0], rotation: 45.0, offset: [0.25, 0.5] }); + assert_eq!(scale, 1.0, "the world scale is its own param"); + assert_ne!(snapshot(&mut s), plain, "the UV transformations move the pattern"); + + // A fill saved before 3D projections had UV transformations loads them as nothing + let mut saved = serde_json::to_value(projection(&s)).unwrap(); + saved["Triplanar"].as_object_mut().unwrap().remove("uv"); + let loaded: Projection = serde_json::from_value(saved).unwrap(); + assert!(matches!(loaded, Projection::Triplanar { uv, .. } if uv == UvTransform::default())); + set(&mut s, json!({"tiling": 1, "rotation": 0, "uvOffset": [0, 0]})).unwrap(); + assert_eq!(snapshot(&mut s), plain, "the identity transform changes nothing"); + + // On a UV projection, tiling is its scale + set(&mut s, json!({"projection": "uv", "tiling": [2, 4]})).unwrap(); + assert!(matches!(projection(&s), Projection::Uv { scale, .. } if scale == [2.0, 4.0])); +} + +/// Physical size keeps the fill's tiling; inspect reports the mode and older fills open on Tiling +#[test] +fn scale_mode_is_stored_without_changing_the_tiling() { + let mut s = session(); + let layer = checker_fill(&mut s, 2.0); + execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "physicalSize"})).unwrap(); + let LayerKind::Fill(fill) = s.doc.project.layer(layer).unwrap().kind.clone() else { panic!("a fill layer") }; + assert_eq!(fill.sampling.scale, ScaleMode::PhysicalSize); + assert!(matches!(fill.projection, Projection::Uv { scale: [2.0, 2.0], .. }), "{:?}", fill.projection); + + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == layer.0).unwrap().clone(); + assert_eq!(row["fill"]["scaleMode"], json!("physicalSize")); + assert!(execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "scaleMode": "inches"})).is_err()); + + let mut saved = serde_json::to_value(&fill).unwrap(); + saved["sampling"].as_object_mut().unwrap().remove("scale"); + let loaded: Fill = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.sampling.scale, ScaleMode::Tiling); +}