From bced280aa17b1e27b24169f5a781397d78854e47 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Mon, 2 Nov 2026 07:06:07 +0000 Subject: [PATCH 001/275] Bake: curvature from short rays around each texel, on the GPU when there is one Replace the per-vertex mesh curvature with short ray rings around each texel, so triangle size no longer decides the result: walls beside the point (concave), hard edges (convex), the spread of the smooth normals and true curvature where shading and faces agree. A high poly uses a small true-curvature radius, and with match by mesh name a part only reads itself. Rays go through RayScene::closest in bounded chunks, so they run on the GPU tracer when there is one. Ray is laid out as the shader reads it and uploads without a copy. Output stays 0..1 with 0.5 flat; curvatureStrength and curvature_from_normal keep their meaning. Clean-room implementation. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/bake/Cargo.toml | 1 + crates/bake/src/lib.rs | 18 +- crates/bake/src/maps.rs | 354 ++++++++++++++++++++++++++++------ crates/bake/src/rays.rs | 7 +- crates/bake/src/tests.rs | 220 ++++++++++++++++++++- crates/render/src/gpu_bake.rs | 32 +-- 7 files changed, 553 insertions(+), 80 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5085d081..c4fab2f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3854,6 +3854,7 @@ dependencies = [ name = "texturecraft-bake" version = "0.3.0" dependencies = [ + "bytemuck", "rayon", "texturecraft-core", "texturecraft-geom", diff --git a/crates/bake/Cargo.toml b/crates/bake/Cargo.toml index 9b893562..7125135f 100644 --- a/crates/bake/Cargo.toml +++ b/crates/bake/Cargo.toml @@ -12,5 +12,6 @@ workspace = true texturecraft-core = { workspace = true } texturecraft-geom = { workspace = true } texturecraft-texel = { workspace = true } +bytemuck = { workspace = true, features = ["extern_crate_alloc"] } rayon = { workspace = true } thiserror = { workspace = true } diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 39d466e1..d42e3f3d 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -26,7 +26,7 @@ use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; use rayon::prelude::*; use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, UvGBuffer}; +use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::DilationMap; use crate::rays::{CpuTracer, RayScene, Tracer}; @@ -42,6 +42,9 @@ pub const MAX_TEXELS: u64 = 1 << 27; const STRIP_TEXELS: usize = 1 << 24; /// Supersamples ray-cast per batch: bounds the per-sample buffers (~40 MB) and a GPU submission. const BATCH: usize = 1 << 18; +/// The same with curvature rays, which take far longer per sample: smaller batches keep progress and +/// cancel responsive (their rays are cast in bounded chunks either way). +const CURVATURE_BATCH: usize = 1 << 15; /// Shared progress / cancellation flag of a running bake. #[derive(Debug, Default)] @@ -226,7 +229,9 @@ fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize, t // UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA. let (sw, full_h) = (w * aa, h * aa); let strip_rows = (strip_texels / (sw * aa)).max(1).min(h); - let batch_rows = (BATCH / (sw * aa)).max(1); + // Curvature casts many rays per sample: smaller batches keep progress moving. + let batch = if ctx.traces_curvature() { CURVATURE_BATCH } else { BATCH }; + let batch_rows = (batch / (sw * aa)).max(1); let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() }; for y0 in (0..h).step_by(strip_rows) { let rows = strip_rows.min(h - y0); @@ -329,6 +334,14 @@ fn bake_rows( false => Vec::new(), }; let transfer = |k: usize| transfers.get(k).and_then(Option::as_ref); + let curvature = match ctx.traces_curvature() { + true => { + let items: Vec<(&Surface, Option<&maps::Transfer>)> = + per_row.iter().zip(&starts).flat_map(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| (&p.surf, transfer(k))).collect(); + ctx.trace_curvature(scene, &items)? + } + false => Vec::new(), + }; let queries: Vec = match ctx.ao.is_some() || ctx.bent.is_some() || ctx.thickness.is_some() { true => { per_row.par_iter().zip(&starts).flat_map_iter(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| ctx.query(transfer(k), &p.surf, p.seed)).collect() @@ -355,6 +368,7 @@ fn bake_rows( ao: ao.get(k).map_or(1.0, |v| v[0]), bent: bent.get(k).map(|v| Vec3::new(v[1], v[2], v[3])), thickness: thickness.get(k).map_or(1.0, |v| v[0]), + curvature: curvature.get(k).copied().unwrap_or(0.5), }; ctx.evaluate(maps, &p.surf, p.bary, transfer(k), &traced, &mut sample); for (a, v) in acc.iter_mut().zip(&sample) { diff --git a/crates/bake/src/maps.rs b/crates/bake/src/maps.rs index 5aa60ba1..6373ea77 100644 --- a/crates/bake/src/maps.rs +++ b/crates/bake/src/maps.rs @@ -9,7 +9,9 @@ use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use texturecraft_geom::{BaseColor, Bvh, Hit, Mesh, Surface, surface_at}; use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; -use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, TraceMesh}; +use rayon::prelude::*; + +use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::skew::Prepared; use crate::{BakeError, BakeRequest}; @@ -17,8 +19,6 @@ use crate::{BakeError, BakeRequest}; struct Source<'a> { mesh: &'a Mesh, bvh: &'a Bvh, - /// Per-vertex curvature offset from 0.5 (empty unless mesh curvature is baked). - curvature: Vec, /// Submesh (part) index of each triangle ([`ANY`] outside every part). part: Vec, /// Match key of each triangle: its part name without the low / high suffix. @@ -28,16 +28,7 @@ struct Source<'a> { } impl<'a> Source<'a> { - fn new( - mesh: &'a Mesh, - bvh: &'a Bvh, - base_color: &'a [Option>], - s: &BakeSettings, - diag: f32, - suffix: &str, - keys: &mut HashMap, - ) -> Source<'a> { - let mesh_curvature = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal; + fn new(mesh: &'a Mesh, bvh: &'a Bvh, base_color: &'a [Option>], suffix: &str, keys: &mut HashMap) -> Source<'a> { let tris = mesh.triangle_count(); let mut part = vec![ANY; tris]; for (i, sm) in mesh.submeshes.iter().enumerate() { @@ -46,18 +37,13 @@ impl<'a> Source<'a> { } let ids: Vec = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect(); let key = part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(ANY)).collect(); - let curvature = if mesh_curvature { vertex_curvature(mesh, diag, s.curvature_strength) } else { Vec::new() }; - Source { mesh, bvh, curvature, part, key, base_color } + Source { mesh, bvh, part, key, base_color } } fn trace(&self) -> TraceMesh<'_> { TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key } } - fn curvature(&self, s: &Surface, bary: [f32; 2]) -> f32 { - (0.5 + interpolate(self.mesh, &self.curvature, s.tri, bary).unwrap_or(0.0)).clamp(0.0, 1.0) - } - /// Vertex color times the material's base color (color sRGB-encoded like a base color /// texture, alpha linear). fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 { @@ -101,6 +87,217 @@ fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { *keys.entry(base).or_insert(next) } +/// Mesh curvature from short rays around each sample, in batches, so the GPU casts them when there +/// is one. The result does not depend on how big the triangles are, and it reads across UV seams and +/// between separate parts. Line radii are in texels of the low poly triangle under the sample, so a +/// line is as wide on a small densely unwrapped part as on a big plate. +struct Curvature { + on: bool, + strength: f32, + /// Sampling radius of the walls, and of the smooth normals, in texels. + walls: f32, + spread: f32, + /// World size of a texel on triangles without usable UVs. + fallback: f32, + /// World size of one texel on each low poly triangle; empty when off. + texels: Vec, + /// Cosine and sine of each direction of a ring. + ring: [(f32, f32); CURVATURE_RAYS], + /// Read from the low poly itself, and from a high poly. + low: Tuning, + high: Tuning, +} + +/// What differs between reading the low poly and reading a high poly. +struct Tuning { + convex: f32, + /// World radius of the true curvature: wider than the facets of a dense mesh, so it averages + /// across them, and the same at any map size. + true_radius: f32, + true_strength: f32, +} + +/// Rays per ring around a sample. +const CURVATURE_RAYS: usize = 8; +/// Samples whose curvature rays are cast at once: bounds their memory (about 2 MB of rays and hits +/// per thousand samples) and a GPU submission, at any resolution and antialiasing. +const CURVATURE_CHUNK: usize = 1 << 15; +/// Rings: wall above, wall below, smooth normals, true curvature. +const CURVATURE_RINGS: usize = 4; +/// Sampling radius of the walls, in texels of the low poly triangle. +const CURVATURE_WALLS: f32 = 1.5; +/// Weight of the concave walls, and of the convex edges from the low poly itself and a high poly. +const CURVATURE_CONCAVE: f32 = 1.5; +const CURVATURE_CONVEX: f32 = 1.5; +const CURVATURE_CONVEX_HIGH: f32 = 0.5; +/// Radius of the true curvature, as a fraction of the model size, and its strength, from the low +/// poly itself and from a high poly. A high poly's small radius keeps a line along a whole edge and +/// its dense detail from wearing in patches. +const CURVATURE_TRUE_RADIUS: f32 = 0.003; +const CURVATURE_TRUE: f32 = 1.3; +const CURVATURE_TRUE_RADIUS_HIGH: f32 = 0.0007; +const CURVATURE_TRUE_HIGH: f32 = 1.6; +/// How much the shading normal must turn (1 − cos) for a corner to count as hard. +const CURVATURE_HARD_EDGE: f32 = 0.05; +/// Map value below which true curvature counts as gently round. +const CURVATURE_GENTLE: f32 = 0.1; + +fn triangle_normal(mesh: &Mesh, tri: u32) -> Option { + let [a, b, c] = mesh.tri(tri as usize)?; + let p = |i: usize| mesh.positions.get(i).copied(); + (p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize() +} + +/// The geometric normal on the side of the shading normal, and two directions along the surface. +fn surface_frame(surf: &Surface) -> (Vec3, Vec3, Vec3) { + let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm }; + let (t, b) = geo.any_orthonormal_pair(); + (geo, t, b) +} + +/// Only tight curves count: a gently round surface like a barrel is not an edge. Lifting it would put +/// it on a wear mask's threshold, and the mask's noise would show as patches. +fn tight(v: f32) -> f32 { + v.signum() * (v.abs() - CURVATURE_GENTLE).max(0.0) +} + +/// What shading and faces agree on. A flat low poly face only turns in its shading, a smooth shaded +/// low poly corner only in its faces; a real rounded surface turns in both. +fn agreed(shading: f32, faces: f32) -> f32 { + if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) } +} + +impl Curvature { + fn new(s: &BakeSettings, low: &Mesh, diag: f32, tiles: (u32, u32)) -> Curvature { + let on = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal && s.curvature_strength != 0.0; + // UVs are in atlas space: across the whole tile grid, each tile `resolution` texels wide. + let resolution = s.resolution.max(1) as f32 * ((tiles.0.max(1) * tiles.1.max(1)) as f32).sqrt(); + let texel = |tri: usize| { + let [a, b, c] = low.tri(tri)?; + let (pa, pb, pc) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?); + let (ua, ub, uc) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?); + let world = (pb - pa).cross(pc - pa).length(); + let uv = (ub - ua).perp_dot(uc - ua).abs(); + (uv > 1e-12 && world > 0.0).then(|| (world / uv).sqrt() / resolution) + }; + let fallback = diag * 1e-3; + let tris = if on { low.triangle_count() } else { 0 }; + let walls = CURVATURE_WALLS; + Curvature { + on, + strength: s.curvature_strength, + walls, + spread: walls * 4.0 / 3.0, + fallback, + texels: (0..tris).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(), + low: Tuning { convex: CURVATURE_CONVEX, true_radius: diag * CURVATURE_TRUE_RADIUS, true_strength: CURVATURE_TRUE }, + high: Tuning { convex: CURVATURE_CONVEX_HIGH, true_radius: diag * CURVATURE_TRUE_RADIUS_HIGH, true_strength: CURVATURE_TRUE_HIGH }, + ring: std::array::from_fn(|i| { + let a = std::f32::consts::TAU * i as f32 / CURVATURE_RAYS as f32; + (a.cos(), a.sin()) + }), + } + } + + /// World size of one texel on low poly triangle `tri`. + fn texel(&self, tri: u32) -> f32 { + self.texels.get(tri as usize).copied().unwrap_or(self.fallback) + } + + /// The rings' radii around a sample whose low poly texel is `texel`. + fn radii(&self, tuning: &Tuning, texel: f32) -> [f32; CURVATURE_RINGS] { + let r = self.walls * texel; + [r, r, self.spread * texel, tuning.true_radius] + } + + /// The directions of a ring around a surface. + fn directions(&self, t: Vec3, b: Vec3) -> [Vec3; CURVATURE_RAYS] { + self.ring.map(|(cos, sin)| t * cos + b * sin) + } + + /// Every ring's rays of one sample, in order, hitting only triangles of `key`. + fn rays(&self, tuning: &Tuning, surf: &Surface, texel: f32, key: u32, out: &mut [Ray]) { + let (geo, t, b) = surface_frame(surf); + let directions = self.directions(t, b); + let radii = self.radii(tuning, texel); + for (ring, (rays, r)) in out.chunks_exact_mut(CURVATURE_RAYS).zip(radii).enumerate() { + for (ray, d) in rays.iter_mut().zip(directions) { + *ray = match ring { + 0 => Ray { origin: surf.pos + geo * (0.15 * r), dir: d, tmax: r, key }, + 1 => Ray { origin: surf.pos - geo * (0.15 * r), dir: d, tmax: r, key }, + _ => Ray { origin: surf.pos + d * r + geo * (0.25 * r), dir: -geo, tmax: 2.25 * r, key }, + }; + } + } + } + + /// The check of each wall above: a contact stands on this surface, so just before the wall the + /// ground is still there. `None` for a ray that hit no wall. + fn ground_rays(&self, surf: &Surface, texel: f32, key: u32, walls: &[Option], out: &mut Vec) { + let (geo, t, b) = surface_frame(surf); + let r = self.walls * texel; + for (w, d) in walls.iter().zip(self.directions(t, b)) { + if let Some(h) = w { + out.push(Ray { origin: surf.pos + geo * (0.15 * r) + d * (h.t * 0.85), dir: -geo, tmax: 0.5 * r, key }); + } + } + } + + /// How much wall stands around the sample. A hit counts by how upright the surface hit is and by + /// how far the shading normal really breaks there: a smooth shaded corner is a smooth surface, + /// however low poly. `keep`: whether each hit counts at all. + fn wall(&self, src: &Source, surf: &Surface, geo: Vec3, r: f32, hits: &[Option], keep: &mut dyn FnMut() -> bool) -> f32 { + let mut sum = 0.0; + for h in hits.iter().flatten() { + if !keep() { + continue; + } + let upright = triangle_normal(src.mesh, h.tri).map_or(1.0, |n| (1.0 - n.dot(geo).powi(2)).max(0.0).sqrt()); + let shaded = interpolate(src.mesh, &src.mesh.normals, h.tri, [h.u, h.v]).and_then(Vec3::try_normalize).unwrap_or(surf.nrm); + let hard = ((1.0 - shaded.dot(surf.nrm)) / CURVATURE_HARD_EDGE).clamp(0.0, 1.0); + sum += (1.0 - h.t / r) * upright * hard; + } + sum / CURVATURE_RAYS as f32 + } + + /// How the normals spread apart (positive, convex) or lean together around the sample, as the + /// mean turn along the ring: of the smooth shading, and of the faces. `turn`: the most the shading + /// may turn (1 − cos) for a sample to count. + fn spread(&self, src: &Source, surf: &Surface, geo: Vec3, directions: &[Vec3; CURVATURE_RAYS], hits: &[Option], turn: f32) -> (f32, f32) { + let (mut shading, mut faces) = (0.0, 0.0); + for (h, dir) in hits.iter().zip(directions) { + let Some(h) = h else { continue }; + let n = interpolate(src.mesh, &src.mesh.normals, h.tri, [h.u, h.v]).and_then(Vec3::try_normalize).unwrap_or(surf.nrm); + if 1.0 - n.dot(surf.nrm) <= turn { + shading += (n - surf.nrm).dot(*dir); + if let Some(f) = triangle_normal(src.mesh, h.tri) { + let f = if f.dot(geo) < 0.0 { -f } else { f }; + faces += (f - geo).dot(*dir); + } + } + } + (shading / CURVATURE_RAYS as f32, faces / CURVATURE_RAYS as f32) + } + + /// The value of one sample from its rings' hits, and whether each wall above stands on the ground. + fn value(&self, tuning: &Tuning, src: &Source, surf: &Surface, texel: f32, hits: &[Option], grounds: &[Option]) -> f32 { + let (geo, t, b) = surface_frame(surf); + let directions = self.directions(t, b); + let ring = |n: usize| hits.get(n * CURVATURE_RAYS..(n + 1) * CURVATURE_RAYS).unwrap_or_default(); + let r = self.walls * texel; + let mut next = grounds.iter(); + let above = self.wall(src, surf, geo, r, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * r)); + let below = self.wall(src, surf, geo, r, ring(1), &mut || true); + let (shading, _) = self.spread(src, surf, geo, &directions, ring(2), 2.0); + let (true_shading, true_faces) = self.spread(src, surf, geo, &directions, ring(3), 2.0); + let v = -above * CURVATURE_CONCAVE + + (below - above).max(0.0) * tuning.convex + + shading * 0.5 + + tight(agreed(true_shading, true_faces) * tuning.true_strength); + (0.5 + v * self.strength).clamp(0.0, 1.0) + } +} + /// Barycentric interpolation of a per-vertex attribute over triangle `tri`. fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { let [a, b, c] = mesh.tri(tri as usize)?; @@ -131,6 +328,7 @@ pub(crate) struct Traced { /// None when bent normals are not baked. pub bent: Option, pub thickness: f32, + pub curvature: f32, } /// Everything a sample needs, computed once per bake. @@ -152,6 +350,7 @@ pub(crate) struct Ctx<'a> { direction_mode: DirectionMode, position_mode: PositionMode, curvature_from_normal: bool, + curvature: Curvature, /// Secondary-ray passes of the requested maps. pub ao: Option, pub bent: Option, @@ -167,8 +366,8 @@ impl<'a> Ctx<'a> { return Err(BakeError::Invalid("mesh bounds are too large".into())); } let mut keys = HashMap::new(); - let low = Source::new(req.mesh, req.bvh, &[], s, diag, &s.low_suffix, &mut keys); - let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, s, diag, &s.high_suffix, &mut keys)); + let low = Source::new(req.mesh, req.bvh, &[], &s.low_suffix, &mut keys); + let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, &s.high_suffix, &mut keys)); let ray_normals = match s.average_normals && high.is_some() { true => { let (weld, _, nrm) = welded(req.mesh, diag); @@ -209,6 +408,7 @@ impl<'a> Ctx<'a> { direction_mode: s.direction_mode, position_mode: s.position_mode, curvature_from_normal: s.curvature_from_normal, + curvature: Curvature::new(s, req.mesh, diag, req.tiles), ao: pass(BakedMap::AmbientOcclusion, &s.ao, RayKind::Occlusion), bent: pass(BakedMap::BentNormal, &s.bent_normal, RayKind::Occlusion), thickness: pass(BakedMap::Thickness, &s.thickness, RayKind::Thickness), @@ -221,7 +421,7 @@ impl<'a> Ctx<'a> { /// Whether the bake casts any ray. pub(crate) fn casts_rays(&self) -> bool { - self.has_high() || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() + self.has_high() || self.curvature.on || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() } /// The meshes rays are cast against: the low poly, then the high poly. @@ -272,6 +472,79 @@ impl<'a> Ctx<'a> { Query { pos: surf.pos, nrm: surf.nrm, geo, rot, key: src.key.get(surf.tri as usize).copied().unwrap_or(ANY), mesh } } + /// Whether this bake traces curvature rays. + pub(crate) fn traces_curvature(&self) -> bool { + self.curvature.on + } + + /// Curvature of every sample: `(low poly surface, transfer)`. Rays go in batches per mesh, the + /// ground checks in a second pass. + pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result, BakeError> { + let mut out = vec![0.5; samples.len()]; + let c = &self.curvature; + for mesh in [0usize, 1] { + let Some(src) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue }; + let tuning = if mesh == 0 { &c.low } else { &c.high }; + // Matched by name, a high poly part only reads itself, like its transfer rays. + let key = |surf: &Surface| if mesh == 1 && self.by_name { src.key.get(surf.tri as usize).copied().unwrap_or(ANY) } else { ANY }; + let chosen: Vec<(usize, &Surface, f32)> = samples + .par_iter() + .enumerate() + .filter_map(|(k, (s, tr))| { + let surf = match (mesh, tr) { + (1, Some(t)) => &t.surf, + (0, None) => *s, + _ => return None, + }; + Some((k, surf, c.texel(s.tri))) + }) + .collect(); + let per = CURVATURE_RINGS * CURVATURE_RAYS; + // A batch can hold whole rows of a big supersampled map: cast them in chunks. + for chunk in chosen.chunks(CURVATURE_CHUNK) { + let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * per); + rays.par_chunks_mut(per).zip(chunk).for_each(|(out, (_, surf, texel))| c.rays(tuning, surf, *texel, key(surf), out)); + let hits = scene.closest(mesh, &rays)?; + let walls = |i: usize| hits.get(i * per..i * per + CURVATURE_RAYS).unwrap_or_default(); + let grounds: Vec = chunk + .par_iter() + .enumerate() + .flat_map_iter(|(i, (_, surf, texel))| { + let mut v = Vec::new(); + c.ground_rays(surf, *texel, key(surf), walls(i), &mut v); + v + }) + .collect(); + let ground_hits = scene.closest(mesh, &grounds)?; + // Each sample's share of the ground checks. + let firsts: Vec = (0..chunk.len()) + .scan(0, |first, i| { + let at = *first; + *first += walls(i).iter().flatten().count(); + Some(at) + }) + .collect(); + let values: Vec<(usize, f32)> = chunk + .par_iter() + .zip(&firsts) + .enumerate() + .map(|(i, ((k, surf, texel), first))| { + let n = walls(i).iter().flatten().count(); + let g = ground_hits.get(*first..*first + n).unwrap_or_default(); + let h = hits.get(i * per..(i + 1) * per).unwrap_or_default(); + (*k, c.value(tuning, src, surf, *texel, h, g)) + }) + .collect(); + for (k, v) in values { + if let Some(o) = out.get_mut(k) { + *o = v; + } + } + } + } + Ok(out) + } + /// Every map of `maps` at one low-poly sample, into `out` (scalars fill all three). pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], transfer: Option<&Transfer>, traced: &Traced, out: &mut [[f32; 3]]) { // The surface the bakers read: the high poly where a ray found it, else the low poly. @@ -286,7 +559,7 @@ impl<'a> Ctx<'a> { BakedMap::BentNormal => pack(traced.bent.unwrap_or(surf.nrm)), BakedMap::Thickness => [traced.thickness; 3], BakedMap::Curvature if self.curvature_from_normal => [0.5; 3], - BakedMap::Curvature => [src.curvature(surf, sb); 3], + BakedMap::Curvature => [traced.curvature; 3], BakedMap::WorldNormal => pack(surf.nrm), BakedMap::Position => self.position(surf.pos), BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize), @@ -381,41 +654,6 @@ fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { (weld, pos, nrm) } -/// Per-vertex curvature offset `−k · avg_edge · strength`, where `k` is the mean of -/// `n·(p_j − p_i)/|p_j − p_i|²` over the 1-ring of the welded mesh. Convex edges give a -/// positive offset. -fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec { - let q = diag * 1e-5; - let (weld, pos, nrm) = welded(mesh, diag); - let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]); - let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64); - for t in mesh.indices.chunks_exact(3) { - for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] { - let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue }; - let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue }; - let d = *pb - *pa; - let l2 = d.length_squared(); - if wa == wb || l2 <= q * q { - continue; - } - if let (Some(k), Some(c)) = (ksum.get_mut(wa as usize), kcnt.get_mut(wa as usize)) { - *k += na.dot(d) / l2; - *c += 1; - } - edge_sum += f64::from(l2.sqrt()); - edge_cnt += 1; - } - } - let scale = (edge_sum / edge_cnt.max(1) as f64) as f32 * strength; - weld.iter() - .map(|w| { - let i = *w as usize; - let k = ksum.get(i).copied().unwrap_or(0.0) / kcnt.get(i).copied().unwrap_or(0).max(1) as f32; - if k.is_finite() { -k * scale } else { 0.0 } - }) - .collect() -} - /// A well-separated hue per part (golden-ratio steps around the HSV wheel). fn material_color(part: usize) -> [f32; 3] { let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; diff --git a/crates/bake/src/rays.rs b/crates/bake/src/rays.rs index 6e1ce02a..5438e89b 100644 --- a/crates/bake/src/rays.rs +++ b/crates/bake/src/rays.rs @@ -34,12 +34,13 @@ impl TraceMesh<'_> { } } -/// A closest-hit ray (the high-poly transfer). -#[derive(Clone, Copy, Debug, PartialEq)] +/// A closest-hit ray. Laid out as the GPU reads it, so a batch uploads without a copy. +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] pub struct Ray { pub origin: Vec3, - pub dir: Vec3, pub tmax: f32, + pub dir: Vec3, /// Only triangles with this part key are hit ([`ANY`]: all). pub key: u32, } diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 8fcca53f..9efa3733 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -81,12 +81,146 @@ fn thin_slab_is_thinner_than_a_block() { } #[test] -fn sphere_curvature_is_nearly_constant() { - let m = primitives::sphere(1.0, 64, 32); +fn sphere_curvature_stays_calm() { + // A smooth sphere has no edges to draw: a soft value, no lines, whatever the triangle size. + for (rings, res) in [(64, 64), (12, 128)] { + let m = primitives::sphere(1.0, rings * 2, rings); + let s = settings(res, &[BakedMap::Curvature]); + let out = run(&m, &s).unwrap(); + let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect(); + let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); + // Convex all over, so a little above grey is right; a line would be a jump between texels. + assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.08, "{rings} rings: {lo}..{hi}"); + } +} + +#[test] +fn flat_surface_is_exactly_mid_grey() { + let m = quad(); let out = run(&m, &settings(64, &[BakedMap::Curvature])).unwrap(); - let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect(); - let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.03, "{lo}..{hi}"); + let c = covered_values(&m, &out, BakedMap::Curvature); + assert!(c.iter().filter(|(p, _)| p.x.abs() < 0.9 && p.z.abs() < 0.9).all(|(_, v)| *v == 0.5)); +} + +#[test] +fn contact_with_a_wall_is_a_dark_line_and_the_rest_stays_flat() { + let m = floor_and_wall(false); + let s = settings(128, &[BakedMap::Curvature]); + let line = floor_mean(&m, &s, BakedMap::Curvature, 0.96..1.0); + assert!(line < 0.47, "beside the wall {line}"); + assert_eq!(floor_mean(&m, &s, BakedMap::Curvature, -0.9..0.5), 0.5); +} + +/// A box whose corners share one smooth normal per corner, each face in its own UV cell. +fn smooth_shaded_box() -> Mesh { + let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let faces: [(Vec3, Vec3, Vec3); 6] = [ + (Vec3::X, Vec3::Y, Vec3::Z), + (Vec3::NEG_X, Vec3::Z, Vec3::Y), + (Vec3::Y, Vec3::Z, Vec3::X), + (Vec3::NEG_Y, Vec3::X, Vec3::Z), + (Vec3::Z, Vec3::X, Vec3::Y), + (Vec3::NEG_Z, Vec3::Y, Vec3::X), + ]; + for (f, (n, a, b)) in faces.iter().enumerate() { + let base = pos.len() as u32; + let cell = Vec2::new((f % 3) as f32 / 3.0, (f / 3) as f32 / 2.0); + for (u, v) in [(-1.0f32, -1.0f32), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)] { + let p = *n + *a * u + *b * v; + pos.push(p); + nrm.push(p.normalize()); + uvs.push(cell + Vec2::new((u * 0.5 + 0.5) * 0.3 + 0.015, (v * 0.5 + 0.5) * 0.45 + 0.025)); + } + idx.extend([base, base + 1, base + 2, base, base + 2, base + 3]); + } + Mesh::from_parts(pos, Some(nrm), uvs, idx, "Smooth box").unwrap() +} + +/// Largest distance from mid grey among samples within `band` of a box edge (half extent 1). +fn edge_peak(m: &Mesh, res: u32, band: f32) -> f32 { + let c = covered_values(m, &run(m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|v| **v > 1.0 - band).count() >= 2).map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max) +} + +#[test] +fn smooth_shaded_corners_draw_no_hard_line() { + // The same geometry: hard shading has a real edge, smooth shading has none to draw. + let (hard, smooth) = (edge_peak(&primitives::cube(2.0), 256, 0.03), edge_peak(&smooth_shaded_box(), 256, 0.03)); + assert!(hard > 0.05, "hard {hard}"); + assert!(smooth < hard * 0.5, "smooth {smooth} hard {hard}"); +} + +#[test] +fn lines_are_as_wide_in_texels_at_any_scale_of_the_part() { + // The radius follows the texels of the triangle: twice the map, half the world width. + let width = |res: u32| { + let m = primitives::cube(2.0); + let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + c.iter() + .filter(|(p, v)| (v - 0.5).abs() > 0.02 && p.abs().to_array().iter().filter(|a| **a > 0.999).count() == 1) + .map(|(p, _)| { + let mut a = p.abs().to_array(); + a.sort_by(f32::total_cmp); + 1.0 - a[1] + }) + .fold(0.0, f32::max) + }; + let (coarse, fine) = (width(128), width(256)); + assert!(fine > 0.0 && (fine / coarse - 0.5).abs() < 0.2, "world widths {coarse} and {fine}"); +} + +/// A dense smooth cylinder along Y with UVs that unwrap its side. +fn barrel(radius: f32) -> Mesh { + const N: u32 = 128; + let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for i in 0..=N { + let u = i as f32 / N as f32; + let (s, c) = (u * std::f32::consts::TAU).sin_cos(); + for (y, v) in [(-1.0f32, 0.0f32), (1.0, 1.0)] { + pos.push(Vec3::new(c * radius, y, s * radius)); + nrm.push(Vec3::new(c, 0.0, s)); + uvs.push(Vec2::new(u, v)); + } + } + for i in 0..N { + let b = i * 2; + idx.extend([b, b + 1, b + 2, b + 1, b + 3, b + 2]); + } + Mesh::from_parts(pos, Some(nrm), uvs, idx, "Barrel").unwrap() +} + +#[test] +fn a_gently_round_barrel_stays_below_the_wear_masks() { + // Edge masks start around 0.6 with their noise: a plain round surface must stay well under them. + let m = barrel(0.1); + let c = covered_values(&m, &run(&m, &settings(512, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + let (lo, hi) = c.iter().filter(|(p, _)| p.y.abs() < 0.9).fold((1.0f32, 0.0f32), |(lo, hi), (_, v)| (lo.min(*v), hi.max(*v))); + assert!(hi < 0.53 && hi - lo < 0.02, "{lo}..{hi}"); +} + +#[test] +fn a_rounded_bevel_reads_the_same_at_any_map_size() { + let m = primitives::rounded_box(Vec3::ONE, 0.05); + let peak = |res: u32| { + let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); + let mut v: Vec = c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|a| **a > 0.97).count() >= 2).map(|v| v.1).collect(); + v.sort_by(f32::total_cmp); + v.get(v.len() / 2).copied().unwrap_or(0.5) + }; + let (coarse, fine) = (peak(512), peak(1024)); + assert!(coarse > 0.58, "bevel at 512: {coarse}"); + assert!((coarse - fine).abs() < 0.1, "512: {coarse}, 1024: {fine}"); +} + +#[test] +fn curvature_strength_scales_the_result_and_zero_is_flat() { + let m = primitives::cube(2.0); + let peak = |strength: f32| { + let s = BakeSettings { curvature_strength: strength, ..settings(128, &[BakedMap::Curvature]) }; + covered_values(&m, &run(&m, &s).unwrap(), BakedMap::Curvature).iter().map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max) + }; + assert_eq!(peak(0.0), 0.0); + assert!(peak(1.0) > peak(0.25)); } /// Bevel / edge texels (two coordinates near the half extent) are convex-bright; face centres @@ -158,6 +292,27 @@ fn cancel_and_progress() { assert_eq!(p.fraction(), 1.0); } +#[test] +fn a_curvature_bake_can_be_cancelled_midway_and_reports_progress() { + let m = primitives::rounded_box(Vec3::ONE, 0.15); + let bvh = Bvh::new(&m); + let s = settings(2048, &[BakedMap::Curvature]); + let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let p = Progress::new(); + std::thread::scope(|t| { + let baking = t.spawn(|| bake(&req, &p)); + let start = std::time::Instant::now(); + while p.done.load(Relaxed) == 0 { + assert!(!baking.is_finished() && start.elapsed().as_secs() < 120, "the bake ended or stalled before reporting progress"); + std::thread::yield_now(); + } + let partway = p.fraction(); + p.cancel(); + assert!(partway < 1.0, "{partway}"); + assert!(matches!(baking.join().unwrap(), Err(BakeError::Cancelled))); + }); +} + #[test] fn invalid_requests_are_errors() { let m = quad(); @@ -270,6 +425,44 @@ fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> R ) } +/// The same box as its own high poly: its edges still read bright and its faces stay flat. +#[test] +fn a_high_poly_box_has_bright_edges_and_flat_faces() { + let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(128, &[BakedMap::Curvature]) }; + for (m, edge) in [(primitives::cube(2.0), 0.97), (primitives::rounded_box(Vec3::ONE, 0.15), 0.9)] { + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count(); + let brightest = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).fold(0.0, f32::max); + assert!(brightest > 0.55, "edge {brightest}"); + assert!(c.iter().filter(|(p, _)| near(*p, 0.5) == 1).all(|v| (0.45..=0.55).contains(&v.1)), "faces"); + } +} + +/// A narrow high poly bevel keeps a bright line. Wide ones read softer, like any gentle curve. +#[test] +fn a_narrow_high_poly_bevel_stays_bright() { + let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(1024, &[BakedMap::Curvature]) }; + let brightest = |bevel: f32| { + let m = primitives::rounded_box(Vec3::ONE, bevel); + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let edge = 1.0 - bevel * 0.7; + c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|c| **c > edge).count() >= 2).map(|v| v.1).fold(0.0, f32::max) + }; + let (narrow, wide) = (brightest(0.01), brightest(0.05)); + assert!(narrow > 0.8, "narrow: {narrow}"); + assert!(wide > 0.55, "wide: {wide}"); +} + +/// A gently round high poly stays below the wear masks' thresholds. +#[test] +fn a_gently_round_high_poly_stays_below_the_wear_masks() { + let m = primitives::sphere(1.0, 96, 48); + let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(256, &[BakedMap::Curvature]) }; + let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); + let over = c.iter().filter(|v| v.1 > 0.65).count() as f32 / c.len() as f32; + assert!(over < 0.01, "{over}"); +} + /// Texel (x, y) of a `res`² bake of [`quad`] sits over world (2u − 1, 0, 2v − 1). fn quad_texel(res: u32, x: f32, z: f32) -> usize { let t = |c: f32| (((c + 1.0) * 0.5 * res as f32) as usize).min(res as usize - 1); @@ -480,6 +673,23 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() { assert!(bake(&too_many, &Progress::new()).is_err()); } +/// On a UV tile grid, curvature lines keep their width in texels of the tile. +#[test] +fn curvature_on_uv_tiles_matches_a_single_tile() { + let one = primitives::rounded_box(Vec3::ONE, 0.15); + let mut two = one.clone(); + two.uvs.iter_mut().for_each(|uv| uv.x *= 0.5); + let s = BakeSettings { dilation: 0, ..settings(64, &[BakedMap::Curvature]) }; + let bake_tiles = |m: &Mesh, tiles| { + let bvh = Bvh::new(m); + bake(&BakeRequest { mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles }, &Progress::new()).unwrap() + }; + let (a, b) = (bake_tiles(&one, (1, 1)), bake_tiles(&two, (2, 1))); + let (a, b) = (&a.maps[&BakedMap::Curvature], &b.maps[&BakedMap::Curvature]); + let worst = (0..64 * 64).map(|i| (a[i] - b[(i / 64) * 128 + i % 64]).abs()).fold(0.0, f32::max); + assert!(worst < 1e-3, "{worst}"); +} + /// A floor ([`quad`], part "Quad") with a wall (part "Wall") standing at x = +1, facing the /// floor (−X) or, when `away`, away from it (+X); winding and normals agree. fn floor_and_wall(away: bool) -> Mesh { diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 08fc76eb..5dee6a02 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -232,10 +232,17 @@ impl GpuScene<'_> { } /// Run `pipeline` over `n` items (`items`: their rows) once per pass in one submission, and - /// read back one result row per item and pass (pass after pass). - fn run(&mut self, pipeline: &wgpu::ComputePipeline, items: &[[u32; 4]], n: usize, passes: &[Pass]) -> Result, BakeError> { + /// hand `read` one result row per item and pass (pass after pass). + fn run( + &mut self, + pipeline: &wgpu::ComputePipeline, + items: &[u8], + n: usize, + passes: &[Pass], + read: impl FnOnce(&[[u32; 4]]) -> R, + ) -> Result { if n == 0 || passes.is_empty() { - return Ok(Vec::new()); + return Ok(R::default()); } let g = self.gpu; let max_groups = g.device.limits().max_compute_workgroups_per_dimension as usize; @@ -250,14 +257,14 @@ impl GpuScene<'_> { blocks.resize(blocks.len().next_multiple_of(g.stride), 0); } } - let (in_bytes, out_bytes) = (items.len() as u64 * 16, (n * passes.len()) as u64 * 16); + let (in_bytes, out_bytes) = (items.len() as u64, (n * passes.len()) as u64 * 16); if in_bytes.max(out_bytes) > g.max_buffer() { return Err(err("a batch exceeds this GPU's buffer limit")); } let io = self.io(in_bytes, out_bytes, blocks.len() as u64)?; let dev = &g.device; scoped(dev, "GPU baking: dispatch", || { - g.queue.write_buffer(&io.items, 0, bytemuck::cast_slice(items)); + g.queue.write_buffer(&io.items, 0, items); g.queue.write_buffer(&io.params, 0, &blocks); let mut enc = dev.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_bake") }); { @@ -280,7 +287,7 @@ impl GpuScene<'_> { dev.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).map_err(err)?; rx.recv().map_err(err)?.map_err(err)?; let data = slice.get_mapped_range().map_err(err)?; - let out = bytemuck::try_cast_slice::(&data).map(<[_]>::to_vec).map_err(err); + let out = bytemuck::try_cast_slice::(&data).map(read).map_err(err); drop(data); io.staging.unmap(); out @@ -294,11 +301,11 @@ fn row(v: Vec3, w: u32) -> [u32; 4] { impl RayScene for GpuScene<'_> { fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { - let items: Vec<[u32; 4]> = rays.par_iter().flat_map_iter(|r| [row(r.origin, r.tmax.to_bits()), row(r.dir, r.key)]).collect(); let pass = Pass { params: Params { root: self.root(mesh)?, ..Params::default() }, per_dispatch: RAYS_PER_DISPATCH, per_group: WORKGROUP as usize }; let gpu = self.gpu; - let out = self.run(&gpu.transfer, &items, rays.len(), &[pass])?; - Ok(out.into_iter().map(|[t, u, v, tri]| (tri != NONE).then(|| Hit { t: f32::from_bits(t), tri, u: f32::from_bits(u), v: f32::from_bits(v) })).collect()) + self.run(&gpu.transfer, bytemuck::cast_slice(rays), rays.len(), &[pass], |out| { + out.par_iter().map(|&[t, u, v, tri]| (tri != NONE).then(|| Hit { t: f32::from_bits(t), tri, u: f32::from_bits(u), v: f32::from_bits(v) })).collect() + }) } fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { @@ -335,8 +342,9 @@ impl RayScene for GpuScene<'_> { }) .collect(); let gpu = self.gpu; - let out = self.run(&gpu.hemisphere, &items, queries.len(), &passes)?; - Ok(out.chunks(queries.len().max(1)).map(|c| c.iter().map(|v| v.map(f32::from_bits)).collect()).collect()) + self.run(&gpu.hemisphere, bytemuck::cast_slice(&items), queries.len(), &passes, |out| { + out.chunks(queries.len().max(1)).map(|c| c.iter().map(|v| v.map(f32::from_bits)).collect()).collect() + }) } } @@ -417,7 +425,7 @@ mod tests { let s = BakeSettings { resolution: 128, dilation: 0, - maps: [BakedMap::Normal, BakedMap::Height, BakedMap::Id, BakedMap::Opacity, BakedMap::AmbientOcclusion, BakedMap::WorldNormal] + maps: [BakedMap::Normal, BakedMap::Height, BakedMap::Id, BakedMap::Opacity, BakedMap::AmbientOcclusion, BakedMap::WorldNormal, BakedMap::Curvature] .into_iter() .collect(), max_frontal: 0.02, From 07fec78a5386f1fc2bfd783914f1088daae544c6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:07:05 +0100 Subject: [PATCH 002/275] Compress project file entries on several threads Saving compressed every zip entry one after the other with deflate level 6 on a single thread; the baked maps were about three quarters of the time. The entries are independent, so native builds now compress them on up to 8 worker threads (one core is left to the UI) and copy the finished entries into the file in the original order with raw_copy_file. Entry names, order, methods, CRCs and sizes are unchanged, the format is unchanged, older versions open the files. Memory stays bounded: a worker only starts an entry while the estimated size of the entries started and not yet written is under 3 GiB, and baked maps and pixel tiles stream into the compressor instead of building a raw copy first. wasm and single-core machines keep the serial writer. The atomic tmp + fsync + rename path is unchanged. Refs #200, fixes #214 Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 174 +++++++++++++++++++++ crates/formats/src/project_file/mod.rs | 107 +++++++++---- crates/formats/src/project_file/tests.rs | 126 +++++++++++++++ 3 files changed, 375 insertions(+), 32 deletions(-) create mode 100644 crates/formats/src/project_file/entries.rs diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs new file mode 100644 index 00000000..a04eab51 --- /dev/null +++ b/crates/formats/src/project_file/entries.rs @@ -0,0 +1,174 @@ +//! Writing the zip entries of a project file. +//! +//! Compressing the baked maps dominates a save (deflate level 6 over gigabytes of `f32`), and every +//! entry is independent, so on native targets the entries are compressed on several threads. Each +//! worker builds a one-entry zip in memory with the same options the serial writer uses; the writing +//! thread copies those entries into the real file in the original order with +//! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are +//! therefore the same as in a serial save. +//! +//! Memory stays bounded: a worker only starts an entry while the entries started but not yet written +//! have an estimated compressed size under [`IN_FLIGHT_BUDGET`] (a single entry larger than that runs +//! alone), and entry bodies stream into the compressor instead of building a raw copy first. + +use std::io::{Seek, Write}; + +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +use super::zip_err; +use crate::Result; + +/// Produces the uncompressed bytes of one entry into the zip writer. +pub(super) type Body<'a> = Box std::io::Result<()> + Send + 'a>; + +pub(super) struct Entry<'a> { + pub name: String, + pub options: SimpleFileOptions, + /// Upper bound of the compressed size in bytes (the uncompressed size is a safe choice). + pub weight: u64, + pub body: Body<'a>, +} + +/// Compressed bytes (estimated) that may be held in memory at once while entries are in flight. +#[cfg(not(target_arch = "wasm32"))] +const IN_FLIGHT_BUDGET: u64 = 3 << 30; +/// More workers than this do not help: a project has a handful of large entries. +#[cfg(not(target_arch = "wasm32"))] +const MAX_WORKERS: usize = 8; + +/// Write `entries` in order: in parallel where threads exist, else one after the other. +pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + // Leave one core to the UI: an autosave runs while the user keeps painting. + let cpus = std::thread::available_parallelism().map_or(1, usize::from); + let workers = cpus.saturating_sub(1).clamp(1, MAX_WORKERS).min(entries.len()); + if workers > 1 { + return parallel::write(zip, entries, workers, IN_FLIGHT_BUDGET); + } + } + write_serial(zip, entries) +} + +/// One entry after the other straight into `zip`. +pub(super) fn write_serial(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + for e in entries { + zip.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(zip)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) mod parallel { + use std::collections::BTreeMap; + use std::io::{Cursor, Seek, Write}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Condvar, Mutex, MutexGuard}; + + use zip::{ZipArchive, ZipWriter}; + + use super::Entry; + use crate::project_file::zip_err; + use crate::{FormatError, Result}; + + struct State { + /// Next entry to start. + next: usize, + /// Estimated bytes of the entries started and not yet written. + in_flight: u64, + /// Finished entries (one-entry zips) waiting for their turn. + ready: BTreeMap>>, + /// The writer failed: start nothing more. + stop: bool, + } + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait<'a>(cv: &Condvar, g: MutexGuard<'a, State>) -> MutexGuard<'a, State> { + cv.wait(g).unwrap_or_else(|e| e.into_inner()) + } + + /// Compress one entry into a zip of its own. + fn compress(e: Entry<'_>) -> Result> { + let mut z = ZipWriter::new(Cursor::new(Vec::new())); + z.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(&mut z)?; + Ok(z.finish().map_err(zip_err)?.into_inner()) + } + + fn worker(slots: &[Mutex>>], weights: &[u64], budget: u64, state: &Mutex, cv: &Condvar) { + loop { + let i = { + let mut st = lock(state); + loop { + if st.stop || st.next >= slots.len() { + return; + } + let w = weights.get(st.next).copied().unwrap_or(0); + // The first entry in line always starts, however large. + if st.in_flight == 0 || st.in_flight.saturating_add(w) <= budget { + let i = st.next; + st.next += 1; + st.in_flight = st.in_flight.saturating_add(w); + break i; + } + st = wait(cv, st); + } + }; + let entry = slots.get(i).and_then(|s| lock(s).take()); + let res = match entry { + Some(e) => { + catch_unwind(AssertUnwindSafe(|| compress(e))).unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))) + } + None => Err(FormatError::Invalid("project entry missing".into())), + }; + lock(state).ready.insert(i, res); + cv.notify_all(); + } + } + + /// Copy the compressed entry of a one-entry zip into `zip` without recompressing. + fn copy_entry(zip: &mut ZipWriter, bytes: Vec) -> Result<()> { + let mut a = ZipArchive::new(Cursor::new(bytes)).map_err(zip_err)?; + let f = a.by_index_raw(0).map_err(zip_err)?; + zip.raw_copy_file(f).map_err(zip_err) + } + + pub(in crate::project_file) fn write(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + let weights: Vec = entries.iter().map(|e| e.weight).collect(); + let slots: Vec>>> = entries.into_iter().map(|e| Mutex::new(Some(e))).collect(); + let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); + let cv = Condvar::new(); + std::thread::scope(|s| { + for _ in 0..workers { + s.spawn(|| worker(&slots, &weights, budget, &state, &cv)); + } + let res = (|| -> Result<()> { + for (i, w) in weights.iter().enumerate() { + let done = { + let mut st = lock(&state); + loop { + if let Some(r) = st.ready.remove(&i) { + st.in_flight = st.in_flight.saturating_sub(*w); + cv.notify_all(); + break r; + } + st = wait(&cv, st); + } + }; + copy_entry(zip, done?)?; + } + Ok(()) + })(); + if res.is_err() { + lock(&state).stop = true; + cv.notify_all(); + } + res + }) + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..bf8c4b53 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -28,8 +28,11 @@ use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; +use self::entries::{Body, Entry}; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; +mod entries; + const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; /// Version of the `.bin` layout. @@ -164,47 +167,75 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -fn write_project(out: W, pf: &ProjectFile) -> Result<()> { - let mut zip = ZipWriter::new(out); +/// Floats converted to bytes at a time when a baked map streams into the compressor. +const BAKED_CHUNK: usize = 1 << 16; + +fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { + w.write_all(&header(res, h, comps, 0))?; + let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); + for chunk in data.chunks(BAKED_CHUNK) { + buf.clear(); + buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); + w.write_all(&buf)?; + } + Ok(()) +} + +/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. +fn entries(pf: &ProjectFile) -> Result>> { let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; - zip.start_file("project.json", deflate).map_err(zip_err)?; - zip.write_all(&json)?; + let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; if let Some((ext, bytes)) = &pf.mesh { - zip.start_file(format!("mesh.{}", sanitize_ext(ext)), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: format!("mesh.{}", sanitize_ext(ext)), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } let mut used = HashSet::new(); for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { - zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name(dir, name, &mut used), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { - zip.start_file("skew.bin", deflate).map_err(zip_err)?; - let mut b = SKEW_MAGIC.to_vec(); - b.extend_from_slice(&BIN_VERSION.to_le_bytes()); - for v in [k.width, k.height] { - b.extend_from_slice(&v.to_le_bytes()); - } - for v in [k.edge_distance, k.edge_contrast] { - b.extend_from_slice(&v.to_le_bytes()); - } - b.push(u8::from(k.per_triangle)); - b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); - zip.write_all(&b)?; + let body: Body<'_> = Box::new(move |w| { + let mut b = SKEW_MAGIC.to_vec(); + b.extend_from_slice(&BIN_VERSION.to_le_bytes()); + for v in [k.width, k.height] { + b.extend_from_slice(&v.to_le_bytes()); + } + for v in [k.edge_distance, k.edge_contrast] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.push(u8::from(k.per_triangle)); + b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); + w.write_all(&b) + }); + out.push(Entry { name: "skew.bin".into(), options: deflate, weight: k.values.len() as u64 * 4, body }); } let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); for ((id, c), img) in layers { - zip.start_file(format!("pixels/layer_{}_{}.bin", id.0, c.id()), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { + name: format!("pixels/layer_{}_{}.bin", id.0, c.id()), + options: deflate, + weight, + body: Box::new(move |mut w| write_tiles(&mut w, img)), + }); } let mut masks: Vec<_> = pf.pixels.masks.iter().collect(); masks.sort_by_key(|(k, _)| **k); for (id, img) in masks { - zip.start_file(format!("pixels/mask_{}.bin", id.0), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) }); } for (ts, maps) in &pf.baked { let r = maps.resolution; @@ -214,21 +245,33 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { if h == 0 || data.len() != (r as usize) * (h as usize) * m.components() { continue; } - zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).map_err(zip_err)?; - zip.write_all(&header(r, h, m.components(), 0))?; - let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); - zip.write_all(&bytes)?; + let comps = m.components(); + out.push(Entry { + name: format!("baked/{ts}_{}.bin", m.id()), + options: deflate, + weight: data.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, r, h, comps, data)), + }); } } if let Some(png) = &pf.thumbnail { - zip.start_file("thumbnail.png", stored).map_err(zip_err)?; - zip.write_all(png)?; + out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) }); } used.clear(); for (name, bytes) in &pf.resources { - zip.start_file(unique_entry_name("resources", name, &mut used), stored).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name("resources", name, &mut used), + options: stored, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } + Ok(out) +} + +fn write_project(out: W, pf: &ProjectFile) -> Result<()> { + let mut zip = ZipWriter::new(out); + entries::write_entries(&mut zip, entries(pf)?)?; zip.finish().map_err(zip_err)?; Ok(()) } diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..eacc939a 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -211,3 +211,129 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +/// Every entry of a zip in file order: (name, method, crc, sizes, the compressed bytes as stored). +/// The zip headers around them (version fields, zip64 size placeholders) are not part of this: +/// copying an entry between zips rewrites them. +#[allow(clippy::type_complexity)] +fn payloads(zip: &[u8]) -> Vec<(String, CompressionMethod, u32, u64, u64, Vec)> { + let mut a = ZipArchive::new(Cursor::new(zip)).unwrap(); + (0..a.len()) + .map(|i| { + let mut f = a.by_index_raw(i).unwrap(); + let mut raw = Vec::new(); + f.read_to_end(&mut raw).unwrap(); + (f.name().unwrap().into_owned(), f.compression(), f.crc32(), f.size(), f.compressed_size(), raw) + }) + .collect() +} + +/// A project with several baked maps and pixel layers, big enough that entries stream in chunks. +fn big_sample() -> ProjectFile { + let mut s = sample(); + let mut x = 12345u32; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|i| { + x = x.wrapping_mul(1664525).wrapping_add(1013904223); + (i as f32 * 0.001).sin() * 0.5 + 0.5 + (x >> 24) as f32 * 1e-4 + }) + .collect() + }; + let r = 300usize; + let maps = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Position] + .into_iter() + .map(|m| (m, Arc::new(noise(r * r * m.components())))) + .collect(); + s.pf.baked.insert(1, BakedMaps { resolution: r as u32, maps }); + s.pf.mesh = Some(("obj".into(), noise(5000).iter().map(|v| (v * 200.0) as u8).collect())); + s.pf +} + +fn serial_bytes(pf: &ProjectFile) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::write_serial(&mut zip, entries(pf).unwrap()).unwrap(); + zip.finish().unwrap().into_inner() +} + +fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_writes_the_same_entries_as_serial() { + let pf = big_sample(); + let serial = serial_bytes(&pf); + let want = payloads(&serial); + assert!(want.len() > 10); + for (workers, budget) in [(2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The public entry point (threads chosen by the machine) agrees too, and loads back. + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want); + assert_same(&pf, &load_project_bytes(&serial).unwrap()); +} + +/// The files written before entries were compressed in parallel: each entry written in one go. +fn reference_one_shot(pf: &ProjectFile) -> Vec { + let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file("project.json", deflate).unwrap(); + zip.write_all(&serde_json::to_vec_pretty(&pf.project).unwrap()).unwrap(); + for (ts, maps) in &pf.baked { + for (m, data) in &maps.maps { + zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).unwrap(); + zip.write_all(&header(maps.resolution, maps.height(*m), m.components(), 0)).unwrap(); + let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); + zip.write_all(&bytes).unwrap(); + } + } + zip.finish().unwrap().into_inner() +} + +/// Streaming a baked map into the compressor in chunks may place deflate block boundaries a few +/// bytes differently than one big write, so the stored bytes can differ slightly; what the entry +/// holds (name, method, CRC, size) must not, and the compressed size stays within 0.01%. +#[test] +fn baked_entries_hold_what_the_one_shot_writer_wrote() { + let mut pf = big_sample(); + (pf.mesh, pf.high_poly, pf.cage, pf.skew, pf.thumbnail, pf.resources) = (None, vec![], None, None, None, BTreeMap::new()); + pf.pixels = PixelStore::default(); + let (new, old) = (payloads(&save_project_bytes(&pf).unwrap()), payloads(&reference_one_shot(&pf))); + assert_eq!(new.len(), old.len()); + for (n, o) in new.iter().zip(&old) { + assert_eq!((&n.0, n.1, n.2, n.3), (&o.0, o.1, o.2, o.3)); + assert!(n.4.abs_diff(o.4) <= 64 + o.4 / 10_000, "{}: {} vs {}", n.0, n.4, o.4); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_failing_entry_is_an_error_not_a_hang() { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for fail_at in [0usize, 3, 9] { + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| { + if i == fail_at { + return Err(std::io::Error::other("boom")); + } + if i == 5 && fail_at == 9 { + panic!("worker panic"); + } + w.write_all(&[i as u8; 100]) + }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + assert!(entries::parallel::write(&mut zip, list, 4, 25).is_err(), "fail at {fail_at}"); + } +} From 11d672661fcb300606414041ff2c2cae35e8be4e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:09:19 +0100 Subject: [PATCH 003/275] Parallel save: fall back when threads cannot start; release entry share after copy Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 25 ++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index a04eab51..a068e9b9 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -26,6 +26,7 @@ pub(super) struct Entry<'a> { pub name: String, pub options: SimpleFileOptions, /// Upper bound of the compressed size in bytes (the uncompressed size is a safe choice). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub weight: u64, pub body: Body<'a>, } @@ -144,23 +145,39 @@ pub(super) mod parallel { let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); let cv = Condvar::new(); std::thread::scope(|s| { + let mut started = 0; for _ in 0..workers { - s.spawn(|| worker(&slots, &weights, budget, &state, &cv)); + // Thread creation can fail (process limits); the workers that did start drain the queue. + if std::thread::Builder::new().spawn_scoped(s, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { + started += 1; + } } let res = (|| -> Result<()> { for (i, w) in weights.iter().enumerate() { + if started == 0 { + // No thread at all: compress here, one entry after the other. + let entry = slots.get(i).and_then(|s| lock(s).take()); + let bytes = compress(entry.ok_or_else(|| FormatError::Invalid("project entry missing".into()))?)?; + copy_entry(zip, bytes)?; + continue; + } let done = { let mut st = lock(&state); loop { if let Some(r) = st.ready.remove(&i) { - st.in_flight = st.in_flight.saturating_sub(*w); - cv.notify_all(); break r; } st = wait(&cv, st); } }; - copy_entry(zip, done?)?; + let copied = done.and_then(|bytes| copy_entry(zip, bytes)); + // Release the entry's share only once its bytes are gone. + { + let mut st = lock(&state); + st.in_flight = st.in_flight.saturating_sub(*w); + } + cv.notify_all(); + copied?; } Ok(()) })(); From 52505ecbc206b654ce78f195303f47a0581a3f6e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:17:06 +0100 Subject: [PATCH 004/275] Refuse to save a project that could not be opened again Opening a project file stops at 8 GiB of decompressed data (MAX_TOTAL), but saving had no matching check, so a too big project saved fine and then failed to open. Saving now counts the bytes the loader would count and refuses before the temporary file is created, with an error that names the size and the limit; the existing file stays as it was. The limit itself is unchanged. A test checks that the count equals what load counts for a real file. Fixes #215. Refs #200 Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 60 +++++++++++++++++++++++- crates/formats/src/project_file/tests.rs | 46 ++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..0b8ca754 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -88,6 +88,7 @@ pub fn sanitize_resource_name(name: &str) -> String { // Save. pub fn save_project_bytes(pf: &ProjectFile) -> Result> { + check_loadable(pf, MAX_TOTAL)?; let mut out = Cursor::new(Vec::new()); write_project(&mut out, pf)?; Ok(out.into_inner()) @@ -96,6 +97,14 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { /// Save atomically: `.tmp` first, then rename over `path`. #[cfg(not(target_arch = "wasm32"))] pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { + save_project_limited(path, pf, MAX_TOTAL) +} + +/// [`save_project`] with the size [`load`] would accept as a parameter (tests lower it). +#[cfg(not(target_arch = "wasm32"))] +fn save_project_limited(path: &std::path::Path, pf: &ProjectFile, limit: u64) -> Result<()> { + // Before the temp file exists, so a refusal leaves the file on disk as it was. + check_loadable(pf, limit)?; let mut tmp = path.as_os_str().to_owned(); tmp.push(".tmp"); let tmp = std::path::PathBuf::from(tmp); @@ -112,6 +121,50 @@ pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { res } +/// Decompressed bytes that [`load`] counts against [`MAX_TOTAL`] when it reads `pf` back: the +/// payload of every entry it reads, without the `.bin` headers. Keep in step with `load` +/// (`load_size_matches_what_load_counts` checks it). Pixels of layers that are in no stack are +/// dropped by `load` without counting, so they are not counted here either. +fn load_size(pf: &ProjectFile) -> Result { + let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; + let mut n = json.len() as u64; + n += pf.mesh.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.high_poly.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.cage.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.thumbnail.iter().map(|b| b.len() as u64).sum::(); + n += pf.resources.values().map(|b| b.len() as u64).sum::(); + if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { + n += k.values.len() as u64 * 4; + } + let tiles = |img: &TileImage| (img.allocated_count() as u64) * (TILE_AREA * img.comps() * 2) as u64; + n += pf.pixels.layers.iter().filter(|((id, _), _)| texture_set_of(&pf.project, *id).is_some()).map(|(_, img)| tiles(img)).sum::(); + n += pf.pixels.masks.iter().filter(|(id, _)| texture_set_of(&pf.project, **id).is_some()).map(|(_, img)| tiles(img)).sum::(); + for maps in pf.baked.values() { + for (m, data) in &maps.maps { + let h = maps.height(*m); + if h != 0 && data.len() == (maps.resolution as usize) * (h as usize) * m.components() { + n += data.len() as u64 * 4; + } + } + } + Ok(n) +} + +/// Refuse to save a project that [`load`] would reject as too large, before anything is written. +fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { + let size = load_size(pf)?; + if size > limit { + let gib = |b: u64| b as f64 / (1u64 << 30) as f64; + return Err(FormatError::TooLarge(format!( + "the project holds {:.1} GiB of data once unpacked, but TextureCraft opens project files only up to {:.1} GiB, so it was not saved and the file on disk is unchanged. \ + Remove paint layers or baked maps, or lower the texture resolution", + gib(size), + gib(limit) + ))); + } + Ok(()) +} + fn zip_err(e: zip::result::ZipError) -> FormatError { match e { zip::result::ZipError::Io(e) => FormatError::Io(e), @@ -375,6 +428,11 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option { } fn load(reader: R) -> Result { + load_counted(reader).map(|(pf, _)| pf) +} + +/// [`load`], also returning the decompressed bytes it counted against [`MAX_TOTAL`]. +fn load_counted(reader: R) -> Result<(ProjectFile, u64)> { let mut zip = ZipArchive::new(reader).map_err(zip_err)?; if zip.len() > MAX_ENTRIES { return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); @@ -464,7 +522,7 @@ fn load(reader: R) -> Result { } // Other entries (from newer minor revisions) are ignored. } - Ok(pf) + Ok((pf, budget.0)) } #[cfg(test)] diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..5ae008f8 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -211,3 +211,49 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +#[test] +fn load_size_matches_what_load_counts() { + let s = sample(); + let mut tiled = sample().pf; + tiled.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + tiled.pixels = PixelStore::default(); + tiled.baked = [(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 16]))].into() })].into(); + for pf in [&s.pf, &tiled] { + let bytes = save_project_bytes(pf).unwrap(); + let (_, counted) = load_counted(Cursor::new(bytes)).unwrap(); + assert!(counted > 1000); + assert_eq!(load_size(pf).unwrap(), counted); + } +} + +#[test] +fn a_project_too_big_to_reopen_is_not_saved() { + let s = sample(); + let size = load_size(&s.pf).unwrap(); + assert!(check_loadable(&s.pf, size).is_ok()); + let err = check_loadable(&s.pf, size - 1).unwrap_err(); + assert!(matches!(err, FormatError::TooLarge(_))); + assert!(err.to_string().contains("not saved"), "{err}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_refused_save_leaves_the_existing_file_alone() { + let s = sample(); + let dir = std::env::temp_dir().join(format!("tc-formats-toobig-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("demo.tcraft"); + save_project(&path, &s.pf).unwrap(); + let before = std::fs::read(&path).unwrap(); + let mut changed = s.pf.clone(); + changed.project.name = "Changed".into(); + assert!(matches!(save_project_limited(&path, &changed, 10), Err(FormatError::TooLarge(_)))); + assert_eq!(std::fs::read(&path).unwrap(), before); + assert!(!dir.join("demo.tcraft.tmp").exists()); + // A path that does not exist yet stays absent. + let fresh = dir.join("new.tcraft"); + assert!(save_project_limited(&fresh, &changed, 10).is_err()); + assert!(!fresh.exists() && !dir.join("new.tcraft.tmp").exists()); + std::fs::remove_dir_all(&dir).unwrap(); +} From b99ebf73210efa7ae065ea5bfd7709f547da17d7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:17:57 +0100 Subject: [PATCH 005/275] Save size check: skip orphan baked sets, clearer message, wider test Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 7 ++++--- crates/formats/src/project_file/tests.rs | 12 ++++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 0b8ca754..e9513793 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -139,7 +139,8 @@ fn load_size(pf: &ProjectFile) -> Result { let tiles = |img: &TileImage| (img.allocated_count() as u64) * (TILE_AREA * img.comps() * 2) as u64; n += pf.pixels.layers.iter().filter(|((id, _), _)| texture_set_of(&pf.project, *id).is_some()).map(|(_, img)| tiles(img)).sum::(); n += pf.pixels.masks.iter().filter(|(id, _)| texture_set_of(&pf.project, **id).is_some()).map(|(_, img)| tiles(img)).sum::(); - for maps in pf.baked.values() { + // `load` skips the baked maps of a texture set that no longer exists. + for maps in pf.baked.iter().filter(|(ts, _)| **ts < pf.project.texture_sets.len()).map(|(_, m)| m) { for (m, data) in &maps.maps { let h = maps.height(*m); if h != 0 && data.len() == (maps.resolution as usize) * (h as usize) * m.components() { @@ -156,8 +157,8 @@ fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { if size > limit { let gib = |b: u64| b as f64 / (1u64 << 30) as f64; return Err(FormatError::TooLarge(format!( - "the project holds {:.1} GiB of data once unpacked, but TextureCraft opens project files only up to {:.1} GiB, so it was not saved and the file on disk is unchanged. \ - Remove paint layers or baked maps, or lower the texture resolution", + "the project holds {:.2} GiB of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB, so nothing was saved and an existing file is unchanged. \ + Remove paint layers or baked maps to make it smaller", gib(size), gib(limit) ))); diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5ae008f8..44fd17cf 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -219,7 +219,15 @@ fn load_size_matches_what_load_counts() { tiled.project.texture_sets[0].uv_tiles = vec![1001, 1002]; tiled.pixels = PixelStore::default(); tiled.baked = [(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 16]))].into() })].into(); - for pf in [&s.pf, &tiled] { + // The branches where the count could drift: pixels of a layer in no stack, a baked map of a + // set that does not exist, and a baked map whose size does not match (not written). + let mut odd = sample().pf; + odd.pixels.layer_mut(LayerId(999), Channel::BaseColor, (128, 128)).set(1, 1, &[1, 2, 3, 4]); + odd.pixels.mask_mut(LayerId(998), (64, 64)).set(1, 1, &[1, 2]); + odd.baked.insert(7, BakedMaps { resolution: 16, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 256]))].into() }); + odd.baked.entry(1).or_default().resolution = 8; + odd.baked.get_mut(&1).unwrap().maps.insert(BakedMap::Curvature, Arc::new(vec![0.5; 13])); + for pf in [&s.pf, &tiled, &odd] { let bytes = save_project_bytes(pf).unwrap(); let (_, counted) = load_counted(Cursor::new(bytes)).unwrap(); assert!(counted > 1000); @@ -234,7 +242,7 @@ fn a_project_too_big_to_reopen_is_not_saved() { assert!(check_loadable(&s.pf, size).is_ok()); let err = check_loadable(&s.pf, size - 1).unwrap_err(); assert!(matches!(err, FormatError::TooLarge(_))); - assert!(err.to_string().contains("not saved"), "{err}"); + assert!(err.to_string().contains("nothing was saved"), "{err}"); } #[cfg(not(target_arch = "wasm32"))] From 132f5d1f065f814ac6326a7f2cc82d42d743f019 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 3 Nov 2026 21:27:42 +0000 Subject: [PATCH 006/275] Bake: ambient occlusion defaults of 64 rays and a tenth of the diagonal, linear falloff The secondary-ray maps now start from 64 rays reaching a tenth of the bounding-box diagonal (was 32 rays and a quarter), the defaults common to mesh-map bakers. Occlusion falls off linearly with the hit distance instead of with its square, on the CPU and in the GPU shader, so a hit halfway to the max distance counts half. Thickness keeps its 0.1 reach and also gets 64 rays; bent normals still share the occlusion rays. Tests: a floor under a ceiling at half the max distance bakes 0.5 occlusion (0.25 with the squared falloff), and the default ray settings. Co-Authored-By: Claude Opus 5.5 --- crates/bake/src/rays.rs | 3 ++- crates/bake/src/tests.rs | 26 ++++++++++++++++++++++++++ crates/core/src/project.rs | 5 ++--- crates/render/src/shaders/bake.wgsl | 3 +-- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/bake/src/rays.rs b/crates/bake/src/rays.rs index 6e1ce02a..4144933b 100644 --- a/crates/bake/src/rays.rs +++ b/crates/bake/src/rays.rs @@ -131,7 +131,8 @@ impl Hemisphere { }; match self.kind { RayKind::Occlusion => { - let v = hit.map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2)); + // Linear falloff: a hit at the max distance no longer occludes. + let v = hit.map_or(0.0, |h| 1.0 - h.t / self.dmax); sum += v; bent += d * (1.0 - v); } diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 8fcca53f..cb81e4a9 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -538,6 +538,32 @@ fn ambient_occlusion_settings_shape_the_occlusion() { assert!(back(true, true) > 0.999 && (back(false, true) - wide).abs() < 1e-6); } +#[test] +fn occlusion_falls_off_linearly_to_the_max_distance() { + // A floor under a ceiling at height 0.5; the ceiling has no UV area, so only the floor bakes. + let h = 0.5; + let corners = |y: f32| [Vec3::new(-1.0, y, -1.0), Vec3::new(1.0, y, -1.0), Vec3::new(1.0, y, 1.0), Vec3::new(-1.0, y, 1.0)]; + let mut uvs = vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)]; + uvs.extend([Vec2::ZERO; 4]); + let normals = [[Vec3::Y; 4], [Vec3::NEG_Y; 4]].concat(); + let m = + Mesh::from_parts(corners(0.0).into_iter().chain(corners(h)).collect(), Some(normals), uvs, vec![0, 2, 1, 0, 3, 2, 4, 5, 6, 4, 6, 7], "Room").unwrap(); + let diag = (8.0 + h * h).sqrt(); + // Nearly vertical rays meet the ceiling at half the max distance. + let mut s = settings(16, &[BakedMap::AmbientOcclusion]); + s.ao = RaySettings { max_distance: 2.0 * h / diag, spread: 2.0, ..s.ao }; + let ao = mean(covered_values(&m, &run(&m, &s).unwrap(), BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); + assert!((ao - 0.5).abs() < 0.01, "{ao}"); +} + +#[test] +fn ambient_occlusion_defaults_follow_the_common_convention() { + // 64 rays, a tenth of the bounding-box diagonal, the whole hemisphere, cosine-weighted. + let d = BakeSettings::default(); + assert_eq!(d.ao, RaySettings { rays: 64, max_distance: 0.1, spread: 180.0, distribution: RayDistribution::Cosine }); + assert_eq!((d.thickness, d.bent_normal), (d.ao, d.ao), "thickness and bent normals start from the same rays"); +} + #[test] fn bent_normals_and_thickness_have_their_own_rays() { let m = floor_and_wall(false); diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index c144ec98..978168b7 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -197,7 +197,7 @@ pub struct RaySettings { impl Default for RaySettings { fn default() -> Self { - RaySettings { rays: 32, max_distance: 0.25, spread: 180.0, distribution: RayDistribution::Cosine } + RaySettings { rays: 64, max_distance: 0.1, spread: 180.0, distribution: RayDistribution::Cosine } } } @@ -254,8 +254,7 @@ impl Default for BakeSettings { ao: RaySettings::default(), ao_ignore_backface: false, ao_self_occlusion: SelfOcclusion::Always, - // Thickness is hit distance / max distance: long rays turn thin parts almost black. - thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() }, + thickness: RaySettings::default(), bent_normal: RaySettings::default(), curvature_strength: 1.0, curvature_from_normal: false, diff --git a/crates/render/src/shaders/bake.wgsl b/crates/render/src/shaders/bake.wgsl index f321bc84..6fdf63ef 100644 --- a/crates/render/src/shaders/bake.wgsl +++ b/crates/render/src/shaders/bake.wgsl @@ -113,8 +113,7 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati let h = traverse_from(root, o, d, P.dmax, false); let hit = h.idx != NONE; if (occlusion) { - let f = h.t / P.dmax; - let v = select(0.0, 1.0 - f * f, hit); + let v = select(0.0, 1.0 - h.t / P.dmax, hit); sum += v; bent += d * (1.0 - v); } else { From e0404360e4cf7f7cd1cd7a59ffcc364a27b20ae2 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:42:10 +0100 Subject: [PATCH 007/275] 2D view: draw the brush outline under the pointer while painting Fixes #179 Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 30 ++++++++++++++++++ crates/ui-egui/tests/brush_cursor_2d.rs | 41 +++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 crates/ui-egui/tests/brush_cursor_2d.rs diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a809c341..a0ab8bb9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1056,6 +1056,20 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); } } + // Brush cursor: the stamp's size and hardness at the pointer, as in the 3D view. + let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + if cursor_mode + && !path_tool + && brush_tool(app.session.tool.tool) + && !resp.dragged_by(PointerButton::Middle) + // While a Ctrl+drag changes the brush, its cursor stays where the drag began. + && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos().or_else(|| resp.interact_pointer_pos()) } + { + // A UV brush stamp has a radius of twice the brush size, as in `continue_stroke_uv`. + let r = (to(app.session.tool.brush.size * 2.0, 0.0).x - to(0.0, 0.0).x).abs().max(1.5); + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); + } brush_readout(app, ui, &resp, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); @@ -1064,6 +1078,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let _ = (RichText::new(""), Channel::BaseColor); } +/// The brush outline (and its hardness ring) as screen circles around `c`, radius `r` in points. +fn brush_cursor_2d(p: &egui::Painter, c: egui::Pos2, r: f32, hardness: f32) { + p.circle_stroke(c, r, Stroke::new(2.5, Color32::from_black_alpha(140))); + p.circle_stroke(c, r, Stroke::new(1.2, Color32::from_white_alpha(230))); + if hardness > 0.05 { + let inner: Vec = (0..=48) + .map(|k| { + let a = k as f32 / 48.0 * std::f32::consts::TAU; + c + vec2(a.cos(), a.sin()) * r * hardness + }) + .collect(); + p.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + } + p.circle_filled(c, 1.5, Color32::WHITE); +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with("skew_last"); diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs new file mode 100644 index 00000000..58cb4a8e --- /dev/null +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -0,0 +1,41 @@ +//! The 2D view hides the system pointer and draws the brush outline under it while painting. + +use egui::CursorIcon; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +fn cursor(h: &Harness<'_, TextureCraftApp>) -> CursorIcon { + h.output().platform_output.cursor_icon +} + +#[test] +fn painting_in_the_2d_view_replaces_the_pointer_with_the_brush_outline() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "the brush outline replaces the pointer"); + h.hover_at(egui::pos2(2.0, 2.0)); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is back"); +} + +#[test] +fn outside_painting_the_2d_view_keeps_the_normal_pointer() { + let mut h = harness(); + h.state_mut().ui.mode = Mode::Baking; + h.run_steps(3); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None); +} From e59bf5569e86780b5bbc4f2efe9635075b56f9ee Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 23:36:50 +0100 Subject: [PATCH 008/275] Add an offset to mesh-map generators The generator panel had level, softness and noise but no way to lift or lower the finished mask. The new offset is added to the result and clamped to 0..1. The thresholding now lives in Generator::shape, shared by the compositor and the preview. Co-Authored-By: Claude Sonnet 5.5 --- crates/compose/src/eval.rs | 6 +----- crates/core/src/layer.rs | 29 ++++++++++++++++++++++++++++- crates/engine/src/inspect.rs | 2 +- crates/engine/src/mask_cmds.rs | 7 +++++-- crates/engine/src/preview.rs | 5 +---- crates/engine/tests/session.rs | 26 ++++++++++++++++++++++++++ crates/ui-egui/src/dock.rs | 10 +++++++--- 7 files changed, 69 insertions(+), 16 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index de26d5bd..d2f6d2ce 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1122,11 +1122,7 @@ impl<'a, 'b> Texel<'a, 'b> { GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + g.shape(s) } fn mask(&mut self, m: &MaskPlan) -> f32 { diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 551c9803..d1adcde0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -537,6 +537,9 @@ pub struct Generator { pub noise_amount: f32, pub noise_scale: f32, pub seed: u32, + /// Added to the finished mask value and clamped to 0..1 (−1..1; 0 = unchanged). + #[serde(default)] + pub offset: f32, /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, @@ -550,7 +553,18 @@ impl Generator { GeneratorKind::ThinAreas => (0.3, 0.2, 0.0), _ => (0.5, 0.25, 0.0), }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false } + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false } + } + + /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over + /// `softness`, inverted if asked, then shifted by `offset`. + pub fn shape(&self, s: f32) -> f32 { + let th = 1.0 - self.level.clamp(0.0, 1.0); + let soft = self.softness.max(1e-3); + let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); + let v = t * t * (3.0 - 2.0 * t); + let v = if self.invert { 1.0 - v } else { v }; + (v + self.offset).clamp(0.0, 1.0) } } @@ -1050,6 +1064,19 @@ impl Effect { mod tests { use super::*; + #[test] + fn generator_offset_shifts_the_mask_value() { + let mut g = Generator::new(GeneratorKind::Position); + let base = g.shape(0.2); + assert!(base < 0.5); + g.offset = 0.3; + assert!((g.shape(0.2) - (base + 0.3)).abs() < 1e-6, "the offset is added"); + g.offset = 1.0; + assert_eq!(g.shape(0.2), 1.0, "and the result is clamped"); + g.offset = -1.0; + assert_eq!(g.shape(0.9), 0.0); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..cbd31942 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -38,7 +38,7 @@ fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity }); match &e.kind { EffectKind::Generator(g) => { - ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) + ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "offset": g.offset, "invert": g.invert }) } EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), EffectKind::Path(paths) => { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..315e90c4 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, offset?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -324,6 +324,9 @@ fn generator_from(p: &Value, g: &mut Generator) { if let Some(v) = f32p(p, "noise") { g.noise_amount = v.clamp(0.0, 2.0); } + if let Some(v) = f32p(p, "offset") { + g.offset = v.clamp(-1.0, 1.0); + } if let Some(v) = f32p(p, "noiseScale") { g.noise_scale = v.clamp(0.01, 1000.0); } diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..170989b6 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -63,10 +63,7 @@ fn generator(g: &Generator, c: &Coords) -> f32 { }; // Same thresholding as the compositor. let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + g.shape(s) } fn mask(m: &Mask, c: &Coords) -> f32 { diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..af1dbc6a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -54,6 +54,32 @@ fn layers_masks_materials_and_bake() { assert_eq!(s.doc.project.walk(0).len(), 1, "back to the initial paint layer"); } +#[test] +fn generator_offset_is_settable_and_clamped() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + let offset = |s: &Session| { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() + }; + assert_eq!(offset(&s), 0.25); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": 5.0})).unwrap(); + assert_eq!(offset(&s), 1.0, "clamped to 1"); +} + #[test] fn layer_rename_and_undo() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 471f164d..7bfe926a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1875,15 +1875,19 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } }); - let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); + let (mut level, mut soft, mut noise, mut ns, mut off) = (g.level, g.softness, g.noise_amount, g.noise_scale, g.offset); let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); + let r6 = slider_edit(ui, tr("Offset"), &mut off, -1.0..=1.0, 2); let mut inv = g.invert; let r5 = ui.checkbox(&mut inv, tr("Invert")); - if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) { - app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge})); + if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r6).or(r5.changed().then_some(false)) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "offset": off, "invert": inv, "merge": merge}), + ); } if !app.session.doc.baked.contains_key(&app.session.ts()) { ui.label( From d7ae9891ef079ef0aa6e2bba406306eec01b5df5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:45:24 +0100 Subject: [PATCH 009/275] Parallel save: stream entries when no worker thread starts Review point: with no worker thread the fallback built a whole in-memory zip per entry; it now writes each entry straight into the file like the serial writer, and the test covers that path. Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 8 ++++---- crates/formats/src/project_file/tests.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index a068e9b9..9e4c6d03 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -155,10 +155,10 @@ pub(super) mod parallel { let res = (|| -> Result<()> { for (i, w) in weights.iter().enumerate() { if started == 0 { - // No thread at all: compress here, one entry after the other. - let entry = slots.get(i).and_then(|s| lock(s).take()); - let bytes = compress(entry.ok_or_else(|| FormatError::Invalid("project entry missing".into()))?)?; - copy_entry(zip, bytes)?; + // No thread at all: stream the entry into the file like the serial writer does. + let entry = slots.get(i).and_then(|s| lock(s).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; continue; } let done = { diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index eacc939a..48045f5d 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -269,7 +269,7 @@ fn parallel_save_writes_the_same_entries_as_serial() { let serial = serial_bytes(&pf); let want = payloads(&serial); assert!(want.len() > 10); - for (workers, budget) in [(2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + for (workers, budget) in [(0, 1), (2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { let got = parallel_bytes(&pf, workers, budget); assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); assert_same(&pf, &load_project_bytes(&got).unwrap()); From 715baf47609f689eb5ab0676825869639820a3e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:36:12 +0100 Subject: [PATCH 010/275] Use as_chunks where the chunk size is a constant Clippy 1.99 flags chunks_exact and chunks_exact_mut with a constant chunk size (chunks_exact_to_as_chunks). Switch those call sites to as_chunks / as_chunks_mut. Behaviour is unchanged: the trailing partial chunk was already dropped. Fixes #233 Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/maps.rs | 2 +- crates/bake/src/tests.rs | 2 +- crates/compose/src/display.rs | 4 ++-- crates/compose/src/eval.rs | 2 +- crates/engine/src/quick_mask.rs | 2 +- crates/engine/tests/auto_rebake.rs | 2 +- crates/engine/tests/bake.rs | 2 +- crates/formats/src/fonts.rs | 4 ++-- crates/formats/src/mesh_export.rs | 2 +- crates/formats/src/mesh_export/usd.rs | 2 +- crates/formats/src/mesh_import/abc/mod.rs | 18 +++++++++--------- crates/formats/src/mesh_import/fbx.rs | 10 +++++----- crates/formats/src/mesh_import/gltf.rs | 4 ++-- crates/formats/src/mesh_import/mod.rs | 4 ++-- crates/formats/src/mesh_import/obj.rs | 8 ++++---- crates/formats/src/mesh_import/usd/usdc.rs | 4 ++-- crates/formats/src/project_file/mod.rs | 6 +++--- crates/geom/src/mesh.rs | 10 +++++----- crates/render/src/subdivide.rs | 4 ++-- 19 files changed, 46 insertions(+), 46 deletions(-) diff --git a/crates/bake/src/maps.rs b/crates/bake/src/maps.rs index 5aa60ba1..72d6e45c 100644 --- a/crates/bake/src/maps.rs +++ b/crates/bake/src/maps.rs @@ -389,7 +389,7 @@ fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec { let (weld, pos, nrm) = welded(mesh, diag); let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]); let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64); - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] { let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue }; let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue }; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index cb81e4a9..17baa8b7 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -59,7 +59,7 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { let mut m = primitives::cube(2.0); - for t in m.indices.chunks_exact_mut(3) { + for t in m.indices.as_chunks_mut::<3>().0.iter_mut() { t.swap(1, 2); } for n in &mut m.normals { diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 56a4d4e1..6ab98ed4 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -131,7 +131,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.chunks_exact_mut(4).enumerate() { + for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (d, lane) in px.iter_mut().zip(&lanes) { *d = lane(i); } @@ -143,7 +143,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; // A TILE never straddles two atlas blocks. let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.chunks_exact_mut(4).enumerate() { + for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (k, d) in px.iter_mut().take(2).enumerate() { *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index de26d5bd..22f44442 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2002,7 +2002,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option< n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); for (ch, buf, _) in &mut bufs { if ch.kind() == ChannelKind::Signed { - for px in buf.chunks_exact_mut(2) { + for px in buf.as_chunks_mut::<2>().0.iter_mut() { px[0] = to_u16_signed(0.0); } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..92d00962 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -115,7 +115,7 @@ impl Session { let mut out = vec![255u8; size as usize * size as usize * 4]; out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32; - for (x, px) in row.chunks_exact_mut(4).enumerate() { + for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32; let mut m = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs index e6a37275..c95c026d 100644 --- a/crates/engine/tests/auto_rebake.rs +++ b/crates/engine/tests/auto_rebake.rs @@ -14,7 +14,7 @@ fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { for p in &mesh.positions { obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); } - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index 8f592937..db08f0f0 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -17,7 +17,7 @@ fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String { for p in &mesh.positions { s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]); } - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } s diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index b047ba49..ca7db930 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -91,7 +91,7 @@ pub fn faces_of(path: &Path) -> std::io::Result> { for (index, offset) in offsets.into_iter().enumerate() { let dir = at(offset, 12)?; let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; - let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue }; + let Some(rec) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); @@ -125,7 +125,7 @@ fn name_string(t: &[u8], id: u16) -> Option { } let (rank, s) = match platform { 3 | 0 => { - let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); + let s = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); (if language == 0x409 { 0 } else { 1 }, s) } 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 49b1ef81..454ceffd 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -93,7 +93,7 @@ fn obj_text(mesh: &Mesh, name: &str, mtllib: Option<&str>) -> String { let material = materials.get(sm.material).map_or("default", String::as_str); let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name)); let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize); - for tri in mesh.indices.get(a..b).unwrap_or_default().chunks_exact(3) { + for tri in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { s.push('f'); for i in tri { let i = i + 1; diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 77d0d5ad..25c8f04c 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -184,7 +184,7 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result> = vec![Vec::new(); mesh.materials.len()]; for sm in parts(mesh, name) { let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default(); - for t in range.chunks_exact(3) { + for t in range.as_chunks::<3>().0 { if let Some(f) = faces_of.get_mut(sm.material) { f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); } diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index 6730b334..00c5ce02 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -227,14 +227,14 @@ impl<'a> Ogawa<'a> { Ok(match p.pod { 0 | 1 => raw.iter().map(|v| *v as f64).collect(), 2 => raw.iter().map(|v| *v as i8 as f64).collect(), - 3 => raw.chunks_exact(2).map(|c| u16::from_le_bytes(le(c)) as f64).collect(), - 4 => raw.chunks_exact(2).map(|c| i16::from_le_bytes(le(c)) as f64).collect(), - 5 => raw.chunks_exact(4).map(|c| u32::from_le_bytes(le(c)) as f64).collect(), - 6 => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - 7 => raw.chunks_exact(8).map(|c| u64::from_le_bytes(le(c)) as f64).collect(), - 8 => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - 10 => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(le(c)) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(le(c)) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(le(c)) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(le(c)) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), }) } @@ -502,7 +502,7 @@ impl Walk<'_, '_> { let indices = get(&mut self.o, ".faceIndices")?; let counts = get(&mut self.o, ".faceCounts")?; check_vertices(p.len() / 3)?; - let points: Vec = p.chunks_exact(3).map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let points: Vec = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let n = [points.len(), counts.len(), indices.len()]; let normals = self.param(&props, "N", n)?; let uvs = self.param(&props, "uv", n)?; diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d7dd46fc..d1d2e121 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -283,10 +283,10 @@ impl<'a> Binary<'a> { <[u8; N]>::try_from(c).unwrap_or([0; N]) } Ok(match ty { - b'd' => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), - b'l' => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - b'f' => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - b'i' => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), + b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), + b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), + b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), _ => raw.iter().map(|b| *b as f64).collect(), }) } @@ -786,7 +786,7 @@ impl Layer<'_> { fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> { let verts = g.child("Vertices").map(Node::arr).unwrap_or_default(); check_vertices(verts.len() / 3)?; - let points: Vec = verts.chunks_exact(3).map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let points: Vec = verts.as_chunks::<3>().0.iter().map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex"); let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex"); diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index bf1f88e0..92f64077 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -169,7 +169,7 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m attrs.uvs.extend((0..n).map(uv_of)); attrs.colors.extend((0..n).map(color_of)); let group = raw.group(&name, part); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let (a, b, c) = (t[0] + base, t[1] + base, t[2] + base); group.extend_from_slice(&if flip { [a, c, b] } else { [a, b, c] }); } @@ -177,7 +177,7 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m None => { // glTF: flat normals when none are given, so every triangle gets its own corners. let mut tris = Vec::with_capacity(indices.len()); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] }; let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default()); let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 3daff3c2..7fd9b113 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -403,7 +403,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { } if !diagonals.is_empty() { let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); - mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); + mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); } if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); @@ -484,7 +484,7 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { let weld = weld_ids(&mesh.positions); let mut acc = vec![Vec3::ZERO; mesh.positions.len()]; - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])); for v in t { diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index f9002ad0..d6cc9eb8 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -44,10 +44,10 @@ fn read_inner(bytes: &[u8]) -> Result { let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; - raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); + raw.positions.extend(m.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); if m.normals.len() == n * 3 { if let Some(v) = &mut normals { - v.extend(m.normals.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); + v.extend(m.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); } } else { normals = None; @@ -55,7 +55,7 @@ fn read_inner(bytes: &[u8]) -> Result { if m.texcoords.len() == n * 2 { if let Some(v) = &mut uvs { // OBJ UVs have their origin bottom-left. - v.extend(m.texcoords.chunks_exact(2).map(|t| Vec2::new(t[0], 1.0 - t[1]))); + v.extend(m.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); } } else { partial_uvs |= n > 0 && !m.indices.is_empty(); @@ -63,7 +63,7 @@ fn read_inner(bytes: &[u8]) -> Result { } // `v x y z r g b`: objects without colors are white. match m.vertex_color.len() == n * 3 { - true => colors.extend(m.vertex_color.chunks_exact(3).map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), + true => colors.extend(m.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)), } let name = match m.material_id { diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 61874c67..9d3cc55d 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -134,7 +134,7 @@ fn is_quat(t: u8) -> bool { /// Quaternions are stored imaginary first; values keep USD's text order (real first). fn quat_order(t: u8, v: &mut [f64]) { if is_quat(t) { - for q in v.chunks_exact_mut(4) { + for q in v.as_chunks_mut::<4>().0 { q.rotate_right(1); } } @@ -234,7 +234,7 @@ impl<'a> Crate<'a> { if reps.len() != n * 8 { return Err(malformed(KIND, "field values are truncated")); } - self.fields = tokens.iter().zip(reps.chunks_exact(8)).map(|(t, r)| (*t as u32, u64::from_le_bytes(r.try_into().unwrap_or_default()))).collect(); + self.fields = tokens.iter().zip(reps.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); Ok(()) } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..4639c4b6 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -320,7 +320,7 @@ fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Bu } read_exact(r, &mut buf, what)?; budget.take(buf.len() as u64)?; - let data: Vec = buf.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); + let data: Vec = buf.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); img.set_tile(tx, ty, Some(Arc::new(data))); } expect_end(r, what)?; @@ -338,7 +338,7 @@ fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) let mut bytes = vec![0u8; len * 4]; read_exact(r, &mut bytes, what)?; expect_end(r, what)?; - Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) + Ok((w, h, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) } /// The skew map entry: header, then the values. @@ -363,7 +363,7 @@ fn read_skew(r: &mut impl Read, budget: &mut Budget, what: &str) -> Result = bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); + let values: Vec = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); // A map with a stray number is dropped by the caller's validation; here only the shape is checked. Ok(SkewData { width: w, height: ht, values, edge_distance, edge_contrast, per_triangle }) } diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..419eb32a 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -156,8 +156,8 @@ impl Mesh { /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { let mut n = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { @@ -194,8 +194,8 @@ impl Mesh { fn simple_tangents(&mut self) { let mut acc = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; let (e1, e2) = (*pb - *pa, *pc - *pa); @@ -244,7 +244,7 @@ impl Mesh { } } let mut shared = vec![false; self.positions.len()]; - for (_, tri) in self.indices.chunks_exact(3).enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { *s = true; diff --git a/crates/render/src/subdivide.rs b/crates/render/src/subdivide.rs index d08a82f2..3da5e465 100644 --- a/crates/render/src/subdivide.rs +++ b/crates/render/src/subdivide.rs @@ -71,7 +71,7 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level for &(start, count, material) in draws { let first = out_i.len() as u32; let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); - for t in tris.chunks_exact(3) { + for t in tris.as_chunks::<3>().0 { let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; let base = out_v.len() as u32; // Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on @@ -118,7 +118,7 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level /// far a height change moves the surface for the slope height-to-normal shows. pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option { let (mut world, mut uv) = (0.0f64, 0.0f64); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])]; let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos)); From bc563f504a65c3040932603a6aaf07f2eba06172 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:40:30 +0100 Subject: [PATCH 011/275] Fix the remaining Rust 1.99 clippy findings Use slice fill in the particles test (manual_slice_fill) and AtomicUsize::try_update, the renamed fetch_update, in the connection limiter. Both are behaviour-neutral. Refs #233 Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/security.rs | 2 +- crates/paint/src/particles.rs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0f5e6ab5..7613ecd5 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -179,7 +179,7 @@ pub struct Permit(Arc); impl ConnectionLimiter { pub fn try_acquire(&self, max: usize) -> Option { - self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + self.0.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) } } diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index 64ec2dde..ad81732e 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -83,9 +83,7 @@ mod tests { for p in &mut m.positions { *p = Vec3::new(p.x, -p.z, 0.0); } - for n in &mut m.normals { - *n = Vec3::Z; - } + m.normals.fill(Vec3::Z); let bvh = Bvh::new(&m); let cam = OrbitCamera::default(); let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) }; From d00d0e92643b2ca3e9913bd1435b2fb4d1c8d8e2 Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Tue, 3 Nov 2026 22:19:19 -0500 Subject: [PATCH 012/275] Add guideline to avoid naming reference product Added a guideline to avoid naming the reference product in various contexts. --- AGENTS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index ad435dac..af26da00 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,13 @@ replace it without touching the engine. ## 3. Golden rules +### Never name the reference product (absolutely essential) + +- The repository never names the commercial product TextureCraft is modeled on, nor its vendor, + in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference + app", "the professional model-painter workflow" or describe the feature itself. +- Notes that name it may live only in the gitignored `plan/` folder. + ### Assets, icons and images (absolutely essential) - **Never use any icon, image, logo, texture, material, brush, environment, font or other asset From 56cd36a433e3347dfcb14a9f072b478479c0b0a1 Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:36:04 +0000 Subject: [PATCH 013/275] =?UTF-8?q?=F0=9F=93=9D=20CodeRabbit=20Chat:=20Rep?= =?UTF-8?q?lace=20reference=20product=20and=20vendor=20names=20in=20AGENTS?= =?UTF-8?q?.md=20with=20neutral=20wording?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index af26da00..0e9e8756 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md: guide for AI agents and contributors TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the -workflow known from Adobe Substance 3D Painter, written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview +workflow of the reference app, written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **TextureCraft** @@ -15,7 +15,7 @@ to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a standards, and contribute reusable learnings back there. Shared code goes only in craft-libs (`standards/shared-libraries.md`); otherwise copy, don't depend. -The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer +The goal is 1:1 parity with the reference app's workflow (same panels, menus, shortcuts, layer stack semantics and export conventions) with better performance, every feature drivable by agents, and builds for Windows, macOS, Linux, FreeBSD and the web. Read this file first, then `docs/`. @@ -26,7 +26,7 @@ and builds for Windows, macOS, Linux, FreeBSD and the web. Read this file first, | `docs/architecture.md` | Crate map, layers, the CPU texel engine + GPU viewport split, data flow | | `docs/control-protocol.md` | The JSON control channel and MCP: how agents drive the running app | | `ROADMAP.md` | Honest parity estimate, milestones, **current focus** | -| `docs/parity.md` | Generated list of Painter menu items: live or missing | +| `docs/parity.md` | Generated list of menu items in the reference app: live or missing | | `docs/releasing.md` | Versioning (`cargo xtask version`), the `release` branch, packaging | | `ATTRIBUTION.md` | Every bundled asset with author, source, license | | `crates//README.md` (where present) | Public API of that crate | @@ -68,7 +68,8 @@ replace it without touching the engine. ### Assets, icons and images (absolutely essential) - **Never use any icon, image, logo, texture, material, brush, environment, font or other asset - from Adobe, Avid, Image-Line or Autodesk products**, and never copy files from any installed + from the reference app, any other products from its vendor, or Avid, Image-Line or Autodesk + products**, and never copy files from any installed commercial application (proprietary formats such as `.sbsar`, `.spexp`, `.sppr` or `.spsm`, HDR environments, UI icons). Not as reference files in the repo either. - Every image or icon must be **open source, public domain, Creative Commons (CC0/CC-BY), or @@ -91,8 +92,8 @@ workflow. Work from public documentation, general domain knowledge, public algor (GGX/Smith/Schlick, split-sum IBL, MikkTSpace, jump-flood/BFS dilation, Möller–Trumbore, SAH BVH, spherical harmonics, reoriented normal mapping, W3C blend modes) and public engine conventions (glTF, Unreal, Unity packing). Never copy proprietary code, shaders, presets or file formats; -Painter file compatibility (`.spp`, `.spexp`, `.sbsar`) is a non-goal. Always describe TextureCraft -as a clean-room implementation, in code, docs and commits. +File compatibility with the reference app (`.spp`, `.spexp`, `.sbsar`) is a non-goal. Always describe +TextureCraft as a clean-room implementation, in code, docs and commits. ### Never crash (outranks feature work) @@ -175,7 +176,7 @@ after every arc of work that builds and passes. ## 7. Where things are tracked - `ROADMAP.md`: milestones, parity estimate and remaining effort. -- `docs/parity.md`: generated Painter menu coverage. +- `docs/parity.md`: generated menu coverage for the reference app. - `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. - `plan/` (local, gitignored): execution plan and notes. - `log/` (local, gitignored): the dev log. From e4405760f1239904aeda1968604a8262279cc066 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 02:04:45 -0500 Subject: [PATCH 014/275] Major refactor of Bake Mode settings and some UI, lots of cleanup for parity --- AGENTS.md | 2 +- ROADMAP.md | 8 +- crates/bake/README.md | 51 +- crates/bake/src/bake_error.rs | 9 + crates/bake/src/bake_output.rs | 11 + crates/bake/src/bake_request.rs | 16 + crates/bake/src/high_poly.rs | 9 + crates/bake/src/lib.rs | 494 ++++++------- crates/bake/src/map.rs | 15 + crates/bake/src/map/bake_context.rs | 250 +++++++ crates/bake/src/map/curvature.rs | 198 +++++ crates/bake/src/map/curvature_tuning.rs | 5 + crates/bake/src/map/normal_curvature.rs | 26 + crates/bake/src/map/sample.rs | 8 + crates/bake/src/map/sampling.rs | 67 ++ crates/bake/src/map/source.rs | 70 ++ crates/bake/src/map/traced.rs | 8 + crates/bake/src/map/transfer.rs | 8 + crates/bake/src/maps.rs | 678 ------------------ crates/bake/src/progress.rs | 22 + crates/bake/src/rays.rs | 207 ------ crates/bake/src/skew.rs | 267 +------ crates/bake/src/skew/prepared_skew.rs | 81 +++ crates/bake/src/skew/skew_map.rs | 135 ++++ crates/bake/src/tests.rs | 544 +++++++------- crates/bake/src/tracing.rs | 21 + crates/bake/src/tracing/cpu_scene.rs | 29 + crates/bake/src/tracing/cpu_tracer.rs | 16 + crates/bake/src/tracing/hemisphere.rs | 81 +++ crates/bake/src/tracing/query.rs | 11 + crates/bake/src/tracing/ray.rs | 11 + crates/bake/src/tracing/ray_kind.rs | 5 + crates/bake/src/tracing/ray_scene.rs | 8 + crates/bake/src/tracing/trace_mesh.rs | 22 + crates/bake/src/tracing/tracer.rs | 7 + crates/core/src/bake.rs | 71 ++ .../src/bake/ambient_occlusion_attenuation.rs | 9 + .../src/bake/ambient_occlusion_settings.rs | 12 + crates/core/src/bake/backface_mode.rs | 9 + crates/core/src/bake/bake_antialiasing.rs | 27 + crates/core/src/bake/bake_resolution.rs | 39 + crates/core/src/bake/bake_settings.rs | 13 + crates/core/src/bake/baked_map.rs | 82 +++ crates/core/src/bake/bent_normal_settings.rs | 10 + crates/core/src/bake/cage_settings.rs | 19 + crates/core/src/bake/cage_type.rs | 8 + crates/core/src/bake/common_bake_settings.rs | 34 + crates/core/src/bake/curvature_method.rs | 8 + crates/core/src/bake/curvature_settings.rs | 16 + crates/core/src/bake/ground_plane_settings.rs | 9 + crates/core/src/bake/height_normalization.rs | 10 + crates/core/src/bake/height_settings.rs | 15 + crates/core/src/bake/high_poly_settings.rs | 23 + crates/core/src/bake/id_color_generator.rs | 9 + crates/core/src/bake/id_color_source.rs | 11 + crates/core/src/bake/id_settings.rs | 9 + crates/core/src/bake/map_settings.rs | 20 + .../core/src/bake/mesh_curvature_settings.rs | 30 + crates/core/src/bake/mesh_map_settings.rs | 83 +++ .../src/bake/normal_map_curvature_settings.rs | 15 + crates/core/src/bake/position_axis.rs | 10 + crates/core/src/bake/position_mode.rs | 13 + .../src/bake/position_normalization_scale.rs | 8 + crates/core/src/bake/position_settings.rs | 10 + crates/core/src/bake/ray_distribution.rs | 11 + crates/core/src/bake/ray_settings.rs | 24 + crates/core/src/bake/self_occlusion.rs | 11 + crates/core/src/bake/skew_settings.rs | 18 + .../core/src/bake/thickness_normalization.rs | 9 + crates/core/src/bake/thickness_settings.rs | 20 + crates/core/src/lib.rs | 12 +- crates/core/src/project.rs | 316 +------- crates/core/tests/bake_settings.rs | 188 +++++ crates/engine/src/auto_rebake.rs | 209 ------ crates/engine/src/bake_cmds.rs | 405 ++++++----- crates/engine/src/commands.rs | 1 - crates/engine/src/lib.rs | 1 - crates/engine/src/link_cmds.rs | 23 +- crates/engine/src/meshmap_cmds.rs | 6 +- crates/engine/src/project_cmds.rs | 49 +- crates/engine/src/session.rs | 5 +- crates/engine/tests/auto_rebake.rs | 156 ---- crates/engine/tests/bake.rs | 476 +++++++----- crates/engine/tests/materialcraft_link.rs | 33 +- crates/engine/tests/painter_gaps.rs | 10 +- crates/engine/tests/udim.rs | 2 +- crates/formats/src/export/tests.rs | 2 +- crates/formats/src/project_file/mod.rs | 53 +- crates/formats/src/project_file/tests.rs | 34 +- crates/render/src/gpu_bake.rs | 112 ++- crates/render/src/shaders/bake.wgsl | 2 +- crates/ui-egui/src/bake_mode.rs | 95 +++ .../ui-egui/src/bake_mode/common_settings.rs | 165 +++++ crates/ui-egui/src/bake_mode/controls.rs | 116 +++ crates/ui-egui/src/bake_mode/map_settings.rs | 184 +++++ crates/ui-egui/src/dock.rs | 10 +- crates/ui-egui/src/docking.rs | 87 ++- crates/ui-egui/src/export_templates.rs | 4 +- crates/ui-egui/src/i18n.rs | 34 +- crates/ui-egui/src/i18n/ar.rs | 161 +++-- crates/ui-egui/src/i18n/de.rs | 170 ++--- crates/ui-egui/src/i18n/es.rs | 167 ++--- crates/ui-egui/src/i18n/fr.rs | 167 ++--- crates/ui-egui/src/i18n/it.rs | 167 ++--- crates/ui-egui/src/i18n/ja.rs | 155 ++-- crates/ui-egui/src/i18n/ko.rs | 155 ++-- crates/ui-egui/src/i18n/pt_br.rs | 167 ++--- crates/ui-egui/src/i18n/zh_hans.rs | 149 ++-- crates/ui-egui/src/lib.rs | 95 +-- crates/ui-egui/src/menus.rs | 61 +- crates/ui-egui/src/shelf.rs | 34 +- crates/ui-egui/src/state.rs | 20 +- crates/ui-egui/src/toolbar.rs | 153 ++-- crates/ui-egui/src/viewport.rs | 106 +-- crates/ui-egui/src/widgets.rs | 124 ++-- crates/ui-egui/src/windows.rs | 320 +-------- crates/ui-egui/tests/bake_mode.rs | 119 +++ crates/ui-egui/tests/skew_paint.rs | 15 +- crates/ui-egui/tests/ui_snapshots.rs | 184 +++-- pr-review-guidelines.md | 68 ++ 120 files changed, 5472 insertions(+), 4200 deletions(-) create mode 100644 crates/bake/src/bake_error.rs create mode 100644 crates/bake/src/bake_output.rs create mode 100644 crates/bake/src/bake_request.rs create mode 100644 crates/bake/src/high_poly.rs create mode 100644 crates/bake/src/map.rs create mode 100644 crates/bake/src/map/bake_context.rs create mode 100644 crates/bake/src/map/curvature.rs create mode 100644 crates/bake/src/map/curvature_tuning.rs create mode 100644 crates/bake/src/map/normal_curvature.rs create mode 100644 crates/bake/src/map/sample.rs create mode 100644 crates/bake/src/map/sampling.rs create mode 100644 crates/bake/src/map/source.rs create mode 100644 crates/bake/src/map/traced.rs create mode 100644 crates/bake/src/map/transfer.rs delete mode 100644 crates/bake/src/maps.rs create mode 100644 crates/bake/src/progress.rs delete mode 100644 crates/bake/src/rays.rs create mode 100644 crates/bake/src/skew/prepared_skew.rs create mode 100644 crates/bake/src/skew/skew_map.rs create mode 100644 crates/bake/src/tracing.rs create mode 100644 crates/bake/src/tracing/cpu_scene.rs create mode 100644 crates/bake/src/tracing/cpu_tracer.rs create mode 100644 crates/bake/src/tracing/hemisphere.rs create mode 100644 crates/bake/src/tracing/query.rs create mode 100644 crates/bake/src/tracing/ray.rs create mode 100644 crates/bake/src/tracing/ray_kind.rs create mode 100644 crates/bake/src/tracing/ray_scene.rs create mode 100644 crates/bake/src/tracing/trace_mesh.rs create mode 100644 crates/bake/src/tracing/tracer.rs create mode 100644 crates/core/src/bake.rs create mode 100644 crates/core/src/bake/ambient_occlusion_attenuation.rs create mode 100644 crates/core/src/bake/ambient_occlusion_settings.rs create mode 100644 crates/core/src/bake/backface_mode.rs create mode 100644 crates/core/src/bake/bake_antialiasing.rs create mode 100644 crates/core/src/bake/bake_resolution.rs create mode 100644 crates/core/src/bake/bake_settings.rs create mode 100644 crates/core/src/bake/baked_map.rs create mode 100644 crates/core/src/bake/bent_normal_settings.rs create mode 100644 crates/core/src/bake/cage_settings.rs create mode 100644 crates/core/src/bake/cage_type.rs create mode 100644 crates/core/src/bake/common_bake_settings.rs create mode 100644 crates/core/src/bake/curvature_method.rs create mode 100644 crates/core/src/bake/curvature_settings.rs create mode 100644 crates/core/src/bake/ground_plane_settings.rs create mode 100644 crates/core/src/bake/height_normalization.rs create mode 100644 crates/core/src/bake/height_settings.rs create mode 100644 crates/core/src/bake/high_poly_settings.rs create mode 100644 crates/core/src/bake/id_color_generator.rs create mode 100644 crates/core/src/bake/id_color_source.rs create mode 100644 crates/core/src/bake/id_settings.rs create mode 100644 crates/core/src/bake/map_settings.rs create mode 100644 crates/core/src/bake/mesh_curvature_settings.rs create mode 100644 crates/core/src/bake/mesh_map_settings.rs create mode 100644 crates/core/src/bake/normal_map_curvature_settings.rs create mode 100644 crates/core/src/bake/position_axis.rs create mode 100644 crates/core/src/bake/position_mode.rs create mode 100644 crates/core/src/bake/position_normalization_scale.rs create mode 100644 crates/core/src/bake/position_settings.rs create mode 100644 crates/core/src/bake/ray_distribution.rs create mode 100644 crates/core/src/bake/ray_settings.rs create mode 100644 crates/core/src/bake/self_occlusion.rs create mode 100644 crates/core/src/bake/skew_settings.rs create mode 100644 crates/core/src/bake/thickness_normalization.rs create mode 100644 crates/core/src/bake/thickness_settings.rs create mode 100644 crates/core/tests/bake_settings.rs delete mode 100644 crates/engine/src/auto_rebake.rs delete mode 100644 crates/engine/tests/auto_rebake.rs create mode 100644 crates/ui-egui/src/bake_mode.rs create mode 100644 crates/ui-egui/src/bake_mode/common_settings.rs create mode 100644 crates/ui-egui/src/bake_mode/controls.rs create mode 100644 crates/ui-egui/src/bake_mode/map_settings.rs create mode 100644 crates/ui-egui/tests/bake_mode.rs create mode 100644 pr-review-guidelines.md diff --git a/AGENTS.md b/AGENTS.md index ad435dac..53aa71df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -126,7 +126,7 @@ panic. The shared standard is `../craftrules/standards/never-crash.md`. Benchmark heavy paths (bake, composite, export) in release and record numbers in the dev log. 8. **Cross-app formats are shared conventions.** MaterialCraft's `.mcmat` portable materials are read here with our own code (`formats::mcmat`): keep the manifest fields, usage ids and - mesh-map identifiers (`BakedMap::interop_id`) in step with MaterialCraft's + mesh-map identifiers (`BakedMap::id`) in step with MaterialCraft's `docs/control-protocol.md`, and never depend on MaterialCraft's crates; talk to it through `materialcraft-cli`. 9. **Verify UI changes visually.** Launch with `--control ` and call `ui.screenshot` (whole diff --git a/ROADMAP.md b/ROADMAP.md index e856b3ff..4bb4209b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -16,13 +16,13 @@ end to end today (engine + UI + automation + tests), not what is planned. | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | 100% | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals, opacity, color map and world-space direction**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection), **match by mesh name**; per-texture-set selection, common and per-map parameters, progress and cancel; **Auto-rebake** (`bake.autoRebake`: one map bakes itself again in the background when its bake settings, the low poly, the high polys or the skew map change); **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | — | +| Baking | 10 | Partial | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals and opacity**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection); per-texture-set selection, common and per-map parameters, progress and cancel; **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | Reference settings have typed, persistent controls in left-hand Texture Sets / Settings / Bake Maps tabs, numeric limits and section resets; added baker behavior and Paint Cage remain pending | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 94%** | | | +| **Total** | **100** | **Under review** | Baking parity is being reassessed | | Beyond the reference app: every command is available to agents through MCP, the CLI and the app's control channel (MCP workspace tools cover every file action: projects, meshes, high polys and @@ -38,13 +38,13 @@ parallel on separate crates: | M1 Layer stack depth | Done | 0 h | | M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h | | M3 Assets | Done | 0 h | -| M4 Baking | Done | 0 h | +| M4 Baking | Integrate the reference settings with commands, UI and baking | TBD | | M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h | | M6 Shader | Done | 0 h | | M7 Formats | Done | 0 h | | M8 UX | Native review of translations | 1 h | | M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h | -| **Total** | | **≈ 6 h** | +| **Total** | | **≈ 6 h + baking TBD** | ## Current focus diff --git a/crates/bake/README.md b/crates/bake/README.md index 786f69f3..da72f0d3 100644 --- a/crates/bake/README.md +++ b/crates/bake/README.md @@ -1,10 +1,10 @@ # texturecraft-bake -Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `rays::Tracer`, then all requested maps are evaluated per sample (rayon over rows). +Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (usually 0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `tracing::Tracer`, then all requested maps are evaluated per sample (rayon over rows). -The rays run on the CPU (`rays::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran. +The rays run on the CPU (`tracing::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran. -With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. With `BakeMatch::ByMeshName`, a low-poly part only sees high-poly parts of the same name once `low_suffix` / `high_suffix` are removed (`wheel_low` ↔ `wheel_high`, case-insensitive). Every map but position and world-space direction then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly). +With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. Every map then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly). Ambient occlusion, thickness and bent normals each have their own `RaySettings`: ray count, max distance (relative to the bounding-box diagonal), spread angle (the full cone around the normal; 180° = the hemisphere) and distribution (cosine-weighted or uniform over the cone). Ambient occlusion can ignore back faces and limit occluders to parts of the same mesh name (`SelfOcclusion::SameMeshName`); bent normals follow those occluder rules and share the AO rays when their settings match. @@ -13,14 +13,51 @@ Ambient occlusion, thickness and bent normals each have their own `RaySettings`: | Ambient occlusion | How open the surface is (rays over the cone, distance falloff) | 0 occluded … 1 open | | Bent normals | Mean unoccluded direction of the bent-normal rays, world space | packed ·0.5+0.5 | | Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick | -| Curvature | Mean curvature of the position-welded mesh, or (`curvature_from_normal`) the divergence of the baked normal map over `curvature_radius` texels (0: by resolution) | 0 concave … 0.5 flat … 1 convex | +| Curvature | Short-ray mesh curvature, or (`CurvatureMethod::NormalMap`) the divergence of the baked normal map over a texel radius derived from the output resolution | 0 concave … 0.5 flat … 1 convex | | Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 | | Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front | | World normal | Shading normal in world space | packed ·0.5+0.5 | -| Position | Position in the low poly's bounding box (per axis) or bounding sphere (`position_mode`) | 0 … 1 | +| Position | Bounding-box or bounding-sphere normalization; None preserves mesh coordinates | 0 … 1, or mesh units for None | | ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 | | Opacity | 1 where the high poly was found (times its vertex and base color alpha), 0 where the ray missed | 0 … 1 | -| Color map | The high poly's vertex colors times its materials' base color (`HighPoly::base_color`: factor × texture at the hit UV, bilinear in linear light), sRGB-encoded like a base color texture | RGB 0 … 1 | -| World space direction | Facing ratio towards `direction`: signed (0.5 perpendicular) or positive (`direction_mode`) | 0 away … 1 facing | Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmarks (2K, the 7 default maps at 64 rays): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` (CPU, per-map breakdown) and `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed` (CPU vs GPU). + +## Settings model + +The clean-room `core::BakeSettings` model contains separate common, high-poly, cage, skew and per-map +settings containers. Each map uses `MapSettings` to keep `is_enabled` beside its typed +parameters; bake selection and UI control visibility read that same flag. Curvature groups its method-specific settings; +AO groups its ground-plane settings. Each container owns its defaults. New projects use the reference defaults: 2048 square output, dilation 1, 64 AO / +thickness / bent-normal rays, curvature from the normal map, and bounding-sphere position +normalization. Old project representations are not preserved. + +New model options include rectangular output (`common.resolution_height: None` locks the axes), +diffusion, high-poly backface filtering and suffix, cage distance units, skew edge protection, +ID source/generator, minimum occluder distance and ray units, AO attenuation/ground plane, +independent bent-normal and thickness occlusion, both curvature methods' detailed controls, +position axis/scope/no-normalization, and thickness/height normalization. AO backface handling +and position normalization each use one enum field. Curvature methods also store named +choices (`NormalMap`/`Mesh`). All dropdowns use enums, +including resolution and antialiasing. Map display labels belong to the localized UI; the +model contains identities and values. `BakedMap::id()` uses the shared MaterialCraft mesh-map +identifiers in commands, project entries and mesh-map exports; `BakedMap::parse()` is their +single parser. + +Bake Mode exposes the model through Texture Sets, Settings and Bake Maps tabs on the left, +with collapsible sections, conditional controls, reference numeric ranges, section resets, and a lockable +output-size pair. Paint and Bake Mode keep separate panel layouts; texture sets use visibility +buttons in Paint Mode and bake-inclusion checkboxes in Bake Mode. +`bake.settings` accepts the complete nested model; edits persist with the project. +Algorithm integration for the added options remains a subsequent stage, including by-mesh-name +backface filtering. Paint Cage is a disabled placeholder. The current command path preserves +the full AO backface and position enums; position None returns mesh coordinates. +The algorithms described above still apply. Color map and World space direction have been +removed without legacy-map migration. + +## Code organization + +Types and their implementations live in individual files named after the full type. Module +folders are singular (`map`, `tracing`, `skew`). Shared sampling and ray-setting logic has one +implementation. Persisted settings live in `core`; Bake Mode controls and localized labels +live in `ui-egui`. The baker has no localization dependency. diff --git a/crates/bake/src/bake_error.rs b/crates/bake/src/bake_error.rs new file mode 100644 index 00000000..f9fe3879 --- /dev/null +++ b/crates/bake/src/bake_error.rs @@ -0,0 +1,9 @@ +#[derive(Debug, thiserror::Error)] +pub enum BakeError { + #[error("bake cancelled")] + Cancelled, + #[error("invalid bake request: {0}")] + Invalid(String), + #[error("ray tracer: {0}")] + Tracer(String), +} diff --git a/crates/bake/src/bake_output.rs b/crates/bake/src/bake_output.rs new file mode 100644 index 00000000..bc021f6f --- /dev/null +++ b/crates/bake/src/bake_output.rs @@ -0,0 +1,11 @@ +use std::collections::BTreeMap; +use texturecraft_core::BakedMap; + +#[derive(Clone, Debug, PartialEq)] +/// Row-major maps, with BakedMap::components() floats per texel +pub struct BakeOutput { + pub resolution: u32, + pub height: u32, + pub maps: BTreeMap>, + pub tracer: String, +} diff --git a/crates/bake/src/bake_request.rs b/crates/bake/src/bake_request.rs new file mode 100644 index 00000000..22919aa3 --- /dev/null +++ b/crates/bake/src/bake_request.rs @@ -0,0 +1,16 @@ +use crate::{HighPoly, SkewMap}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct BakeRequest<'a> { + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + pub material: usize, + pub settings: &'a BakeSettings, + pub high: Option>, + pub cage: Option<&'a Mesh>, + pub skew: Option<&'a SkewMap>, + /// UV atlas grid; each tile uses the configured output resolution + pub tiles: (u32, u32), +} diff --git a/crates/bake/src/high_poly.rs b/crates/bake/src/high_poly.rs new file mode 100644 index 00000000..5c59ee0e --- /dev/null +++ b/crates/bake/src/high_poly.rs @@ -0,0 +1,9 @@ +use std::sync::Arc; +use texturecraft_geom::{BaseColor, Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct HighPoly<'a> { + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + pub base_color: &'a [Option>], +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index d42e3f3d..18742e90 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -1,388 +1,342 @@ -//! # texturecraft-bake -//! -//! Mesh-map baking. [`bake`] rasterizes one texture set's UV layout with a supersampled -//! [`UvGBuffer`] and works through it in batches of samples: the high-poly transfer rays, then -//! the secondary rays of ambient occlusion, bent normals and thickness (each with its own -//! [`texturecraft_core::RaySettings`]) go to a [`rays::Tracer`], then every requested -//! [`BakedMap`] is evaluated per sample (rayon over rows), box-downsampled, and the UV islands -//! are padded with [`DilationMap`]. The rays run on the CPU ([`rays::CpuTracer`], the oracle) or -//! on a GPU tracer passed to [`bake_on`]. With a high poly, every map but position and -//! world-space direction reads the high-poly surface found along the cage / frontal-rear ray; -//! the color map multiplies its vertex colors by its materials' [`BaseColor`]s. Sampling is -//! deterministic, so the same request always gives the same pixels. +//! Deterministic mesh-map baking with bounded batches and CPU fallback + #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -mod maps; -pub mod rays; +mod bake_error; +mod bake_output; +mod bake_request; +mod high_poly; +mod progress; + +pub use bake_error::BakeError; +pub use bake_output::BakeOutput; +pub use bake_request::BakeRequest; +pub use high_poly::HighPoly; +pub use progress::Progress; + +mod map; mod skew; #[cfg(test)] mod tests; +pub mod tracing; use std::collections::BTreeMap; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; +use std::sync::atomic::Ordering::Relaxed; use rayon::prelude::*; -use texturecraft_core::{BakeSettings, BakedMap}; +use texturecraft_core::{BakedMap, CurvatureMethod}; use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{BaseColor, Bvh, Mesh, NO_TRI, Surface, UvGBuffer}; +use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::DilationMap; -use crate::rays::{CpuTracer, RayScene, Tracer}; pub use crate::skew::SkewMap; +use crate::tracing::{CpuTracer, RayScene, Tracer}; -/// Largest accepted output resolution (per axis). pub const MAX_RESOLUTION: u32 = 8192; -/// Largest accepted ray count per texel (AO, thickness). pub const MAX_RAYS: u32 = 4096; -/// Largest accepted output (texels over every UV tile). pub const MAX_TEXELS: u64 = 1 << 27; -/// Supersampled texels rasterized at once: bounds the G-buffer at ~200 MB for any resolution × AA. +// Bound each supersampled G-buffer to roughly 200 MB const STRIP_TEXELS: usize = 1 << 24; -/// Supersamples ray-cast per batch: bounds the per-sample buffers (~40 MB) and a GPU submission. const BATCH: usize = 1 << 18; -/// The same with curvature rays, which take far longer per sample: smaller batches keep progress and -/// cancel responsive (their rays are cast in bounded chunks either way). +// Curvature batches stay small so progress and cancellation remain responsive const CURVATURE_BATCH: usize = 1 << 15; -/// Shared progress / cancellation flag of a running bake. -#[derive(Debug, Default)] -pub struct Progress { - /// Basis points, 0..=10_000 (all requested maps done). - pub done: AtomicU32, - pub cancel: AtomicBool, -} +fn validate(request: &BakeRequest) -> Result<(), BakeError> { + let settings = request.settings; + let invalid = |message: String| Err(BakeError::Invalid(message)); + let resolution = settings.common.resolution.pixels(); -impl Progress { - pub fn new() -> Self { - Self::default() + let (columns, rows) = request.tiles; + let width = u64::from(resolution) * u64::from(columns); + let height = u64::from(resolution) * u64::from(rows); + if columns == 0 || rows == 0 || width.saturating_mul(height) > MAX_TEXELS { + return invalid(format!("{columns} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", resolution)); } - /// Completed fraction, 0..=1. - pub fn fraction(&self) -> f32 { - self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 - } - - /// Ask the bake to stop; it returns [`BakeError::Cancelled`] at the next row. - pub fn cancel(&self) { - self.cancel.store(true, Relaxed); - } -} - -/// A high-poly source mesh (all high-definition meshes appended into one). -#[derive(Clone, Copy, Debug)] -pub struct HighPoly<'a> { - pub mesh: &'a Mesh, - pub bvh: &'a Bvh, - /// Base color per material of `mesh` (missing or None: white). - pub base_color: &'a [Option>], -} - -/// One texture set to bake. -#[derive(Clone, Copy, Debug)] -pub struct BakeRequest<'a> { - pub mesh: &'a Mesh, - /// BVH of the whole low-poly mesh: every material occludes. - pub bvh: &'a Bvh, - pub material: usize, - pub settings: &'a BakeSettings, - pub high: Option>, - /// Cage: the low poly inflated (same triangles); transfer rays start on it. - pub cage: Option<&'a Mesh>, - /// Skew correction of the high-poly transfer rays (see [`SkewMap`]); ignored with a cage mesh. - pub skew: Option<&'a SkewMap>, - /// UV tile grid (columns, rows) of the texture set: the maps are `settings.resolution` per - /// tile, (1, 1) for a classic set. The mesh's UVs are in atlas space (0..1 over the grid). - pub tiles: (u32, u32), -} - -/// Baked maps: row-major `resolution × height`, `BakedMap::components()` floats per texel, -/// rows top → bottom (y = v·H, as [`UvGBuffer`]). -#[derive(Clone, Debug, PartialEq)] -pub struct BakeOutput { - /// Width in texels. - pub resolution: u32, - pub height: u32, - pub maps: BTreeMap>, - /// Where the rays ran ([`Tracer::name`]). - pub tracer: String, -} - -#[derive(Debug, thiserror::Error)] -pub enum BakeError { - #[error("bake cancelled")] - Cancelled, - #[error("invalid bake request: {0}")] - Invalid(String), - /// The ray tracer failed ([`bake_on`] then bakes on the CPU). - #[error("ray tracer: {0}")] - Tracer(String), -} - -fn validate(req: &BakeRequest) -> Result<(), BakeError> { - let s = req.settings; - let invalid = |m: String| Err(BakeError::Invalid(m)); - if s.resolution == 0 || s.resolution > MAX_RESOLUTION { - return invalid(format!("resolution {} is not in 1..={MAX_RESOLUTION}", s.resolution)); - } - let (cols, rows) = req.tiles; - if cols == 0 || rows == 0 || (s.resolution as u64 * cols as u64) * (s.resolution as u64 * rows as u64) > MAX_TEXELS { - return invalid(format!("{cols} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", s.resolution)); - } - if ![1, 2, 4, 8].contains(&s.antialiasing) { - return invalid(format!("antialiasing {} is not 1, 2, 4 or 8", s.antialiasing)); - } - for (map, r) in [(BakedMap::AmbientOcclusion, &s.ao), (BakedMap::Thickness, &s.thickness), (BakedMap::BentNormal, &s.bent_normal)] { - if !s.maps.contains(&map) { + for (map, ray_settings) in [ + (BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays), + (BakedMap::Thickness, &settings.maps.thickness.parameters.rays), + (BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays), + ] { + if !settings.maps.is_enabled(map) { continue; } - if r.rays == 0 || r.rays > MAX_RAYS { - return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.label(), r.rays)); + + if ray_settings.rays == 0 || ray_settings.rays > MAX_RAYS { + return invalid(format!("{} ray count {} is not in 1..={MAX_RAYS}", map.id(), ray_settings.rays)); } - if !(r.max_distance.is_finite() && r.max_distance > 0.0) { - return invalid(format!("{} max distance {} must be positive", map.label(), r.max_distance)); + + if !(ray_settings.max_distance.is_finite() && ray_settings.max_distance > 0.0) { + return invalid(format!("{} max distance {} must be positive", map.id(), ray_settings.max_distance)); } - if !r.spread.is_finite() { - return invalid(format!("{} spread angle is not finite", map.label())); + + if !ray_settings.spread.is_finite() { + return invalid(format!("{} spread angle is not finite", map.id())); } } - if !s.curvature_strength.is_finite() { - return invalid("curvature strength is not finite".into()); + + if !(settings.cage.max_frontal.is_finite() && settings.cage.max_frontal >= 0.0 && settings.cage.max_rear.is_finite() && settings.cage.max_rear >= 0.0) { + return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", settings.cage.max_frontal, settings.cage.max_rear)); } - if !(s.direction.iter().all(|c| c.is_finite()) && s.direction.iter().any(|c| *c != 0.0)) { - return invalid(format!("direction {:?} must be finite and non-zero", s.direction)); + request.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?; + if request.material >= request.mesh.materials.len().max(1) { + return invalid(format!("material {} out of range ({} materials)", request.material, request.mesh.materials.len())); } - if !(s.max_frontal.is_finite() && s.max_frontal >= 0.0 && s.max_rear.is_finite() && s.max_rear >= 0.0) { - return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", s.max_frontal, s.max_rear)); + + if let Some(high) = &request.high { + high.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?; } - req.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?; - if req.material >= req.mesh.materials.len().max(1) { - return invalid(format!("material {} out of range ({} materials)", req.material, req.mesh.materials.len())); - } - if let Some(h) = &req.high { - h.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?; - } - if let Some(c) = req.cage { - c.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?; - if c.indices.len() != req.mesh.indices.len() { - return invalid(format!("the cage has {} triangles, the low poly {}", c.triangle_count(), req.mesh.triangle_count())); + + if let Some(cage) = request.cage { + cage.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?; + if cage.indices.len() != request.mesh.indices.len() { + return invalid(format!("the cage has {} triangles, the low poly {}", cage.triangle_count(), request.mesh.triangle_count())); } } + Ok(()) } -/// `vec![value; n]` that reports allocation failure instead of aborting. -fn alloc(n: usize, value: T) -> Result, BakeError> { - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| BakeError::Invalid(format!("out of memory allocating {n} texels")))?; - v.resize(n, value); - Ok(v) +fn alloc(count: usize, value: T) -> Result, BakeError> { + let mut values = Vec::new(); + values.try_reserve_exact(count).map_err(|_| BakeError::Invalid(format!("out of memory allocating {count} texels")))?; + values.resize(count, value); + Ok(values) } -/// Bake the maps in `req.settings.maps` for one material of the low-poly mesh, on the CPU. -pub fn bake(req: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(req, progress, STRIP_TEXELS, &CpuTracer) +pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { + bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer) } -/// [`bake`] with the rays cast by `tracer` (a GPU); when the tracer fails (no adapter, a mesh -/// too large for it, a lost device) the bake runs again on the CPU. -pub fn bake_on(req: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { - match bake_in_strips(req, progress, STRIP_TEXELS, tracer) { - Err(BakeError::Tracer(e)) => { - let mut out = bake(req, progress)?; - out.tracer = format!("CPU ({} unavailable: {e})", tracer.name()); - Ok(out) +/// Retry on the CPU if the supplied tracer fails +pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { + match bake_in_strips(request, progress, STRIP_TEXELS, tracer) { + Err(BakeError::Tracer(error)) => { + let mut output = bake(request, progress)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) } - r => r, + result => result, } } -/// One output row of a strip: its slice of every map. type OutRow<'a> = Vec<&'a mut [f32]>; -fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { - validate(req)?; - let s = req.settings; - let (tile_res, aa) = (s.resolution as usize, s.antialiasing as usize); - let (w, h) = (tile_res * req.tiles.0 as usize, tile_res * req.tiles.1 as usize); - let ctx = maps::Ctx::new(req)?; - let tracer = if ctx.casts_rays() { tracer } else { &CpuTracer }; - let meshes = ctx.trace_meshes(); +fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { + validate(request)?; + let settings = request.settings; + let (tile_resolution, samples_per_axis) = (settings.common.resolution.pixels() as usize, settings.common.antialiasing.samples_per_axis() as usize); + let (width, height) = (tile_resolution * request.tiles.0 as usize, tile_resolution * request.tiles.1 as usize); + let context = map::BakeContext::new(request)?; + let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; + let meshes = context.trace_meshes(); let mut scene = tracer.scene(&meshes)?; progress.done.store(0, Relaxed); - // Curvature from the normal map needs the normal map: baked alongside when not requested. - let from_normal = s.curvature_from_normal && s.maps.contains(&BakedMap::Curvature); - let mut maps: Vec = s.maps.iter().copied().collect(); + // Normal-map curvature needs a normal bake even when normal output is disabled + let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature); + let mut maps: Vec = settings.maps.enabled().collect(); if from_normal && !maps.contains(&BakedMap::Normal) { maps.push(BakedMap::Normal); } - let mut bufs = maps.iter().map(|m| alloc(w * h * m.components(), 0.0f32)).collect::, _>>()?; - let mut covered = alloc(w * h, false)?; - let mut pad = None; - let total = h.max(1) as u64; + let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::, _>>()?; + let mut covered = alloc(width * height, false)?; + let mut padding_map = None; + let total_rows = height.max(1) as u64; let mut rows_done = 0u64; - let strip_err = || BakeError::Invalid("strip out of range".into()); + let strip_error = || BakeError::Invalid("strip output of range".into()); - // Rasterize in horizontal strips of the supersampled image: a strip's G-buffer is built from - // UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA. - let (sw, full_h) = (w * aa, h * aa); - let strip_rows = (strip_texels / (sw * aa)).max(1).min(h); - // Curvature casts many rays per sample: smaller batches keep progress moving. - let batch = if ctx.traces_curvature() { CURVATURE_BATCH } else { BATCH }; - let batch_rows = (batch / (sw * aa)).max(1); - let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() }; - for y0 in (0..h).step_by(strip_rows) { - let rows = strip_rows.min(h - y0); - let (sy0, sh) = (y0 * aa, rows * aa); - strip_mesh.uvs = req.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * full_h as f32 - sy0 as f32) / sh as f32)).collect(); - let g = UvGBuffer::new(&strip_mesh, req.material, sw as u32, sh as u32); - // A texel is covered when any of its supersamples is. - let cov = covered.get_mut(y0 * w..(y0 + rows) * w).ok_or_else(strip_err)?; - cov.par_chunks_mut(w).enumerate().for_each(|(r, row)| { - for (x, c) in row.iter_mut().enumerate() { - *c = (0..aa * aa).any(|k| g.tri.get((r * aa + k / aa) * sw + x * aa + k % aa).is_some_and(|t| *t != NO_TRI)); + let (sample_width, sample_height) = (width * samples_per_axis, height * samples_per_axis); + let rows_per_strip = (strip_texels / (sample_width * samples_per_axis)).max(1).min(height); + let batch = if context.traces_curvature() { CURVATURE_BATCH } else { BATCH }; + let rows_per_batch = (batch / (sample_width * samples_per_axis)).max(1); + let mut strip_mesh = Mesh { indices: request.mesh.indices.clone(), submeshes: request.mesh.submeshes.clone(), ..Mesh::default() }; + for strip_start in (0..height).step_by(rows_per_strip) { + let rows = rows_per_strip.min(height - strip_start); + let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis); + strip_mesh.uvs = + request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect(); + let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?; + coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| { + for (x, covered_pixel) in row.iter_mut().enumerate() { + *covered_pixel = (0..samples_per_axis * samples_per_axis).any(|sample_index| { + gbuffer + .tri + .get( + (row_index * samples_per_axis + sample_index / samples_per_axis) * sample_width + + x * samples_per_axis + + sample_index % samples_per_axis, + ) + .is_some_and(|triangle_index| *triangle_index != NO_TRI) + }); } }); - let mut out_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); - for (m, data) in maps.iter().zip(bufs.iter_mut()) { - let comps = m.components(); - let strip = data.get_mut(y0 * w * comps..(y0 + rows) * w * comps).ok_or_else(strip_err)?; - for (row, chunk) in out_rows.iter_mut().zip(strip.chunks_mut(w * comps)) { + let mut output_rows: Vec = (0..rows).map(|_| Vec::with_capacity(maps.len())).collect(); + for (map, data) in maps.iter().zip(buffers.iter_mut()) { + let component_count = map.components(); + let strip = data.get_mut(strip_start * width * component_count..(strip_start + rows) * width * component_count).ok_or_else(strip_error)?; + for (row, chunk) in output_rows.iter_mut().zip(strip.chunks_mut(width * component_count)) { row.push(chunk); } } let mut bake_strip = || { - for (b, batch) in out_rows.chunks_mut(batch_rows).enumerate() { + for (batch_index, batch) in output_rows.chunks_mut(rows_per_batch).enumerate() { if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } - // Seed by the global supersample index so strips and batches don't change the noise. - bake_rows(&ctx, &maps, req.mesh, &g, scene.as_mut(), batch, b * batch_rows, (w, aa, sy0 * sw))?; + // Global sample indices keep noise unchanged across strip and batch sizes + bake_rows( + &context, + &maps, + request.mesh, + &gbuffer, + scene.as_mut(), + batch, + batch_index * rows_per_batch, + (width, samples_per_axis, sample_start_y * sample_width), + )?; rows_done += batch.len() as u64; - progress.done.store((rows_done.saturating_mul(10_000) / total).min(10_000) as u32, Relaxed); + progress.done.store((rows_done.saturating_mul(10_000) / total_rows).min(10_000) as u32, Relaxed); } Ok(()) }; - if y0 + rows < h || s.dilation == 0 { + if strip_start + rows < height || settings.common.dilation == 0 { bake_strip()?; } else { - // The coverage is complete: find the padding (UV tile by UV tile) while the last strip bakes. - let padding = || DilationMap::in_blocks(&covered, w as u32, h as u32, Some(s.dilation), s.resolution); - let (p, baked) = rayon::join(padding, bake_strip); + let padding = || DilationMap::in_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), settings.common.resolution.pixels()); + let (padding, baked) = rayon::join(padding, bake_strip); baked?; - pad = Some(p); + padding_map = Some(padding); } } - let mut out: BTreeMap> = maps.into_iter().zip(bufs).collect(); + let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { - let normal = if s.maps.contains(&BakedMap::Normal) { out.get(&BakedMap::Normal).cloned() } else { out.remove(&BakedMap::Normal) }; - if let (Some(normal), Some(curv)) = (normal, out.get_mut(&BakedMap::Curvature)) { - maps::curvature_from_normal(&normal, &covered, w, tile_res, s.curvature_radius, s.curvature_strength, curv); + let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) }; + if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) { + map::curvature_from_normal(&normal, &covered, width, tile_resolution, curvature_pixels); } } - if let Some(pad) = pad { - for (m, data) in out.iter_mut() { - pad.apply(data, m.components()); + if let Some(padding_map) = padding_map { + for (map, data) in output.iter_mut() { + padding_map.apply(data, map.components()); } } progress.done.store(10_000, Relaxed); - Ok(BakeOutput { resolution: w as u32, height: h as u32, maps: out, tracer: tracer.name() }) + Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } -/// Bake output rows `r0..` of a strip's G-buffer `g` into `rows`: gather the covered -/// supersamples, cast their transfer and secondary rays in batches on `scene`, then evaluate -/// and average every map per texel. `seed0` is the strip's first supersample index. #[allow(clippy::too_many_arguments)] fn bake_rows( - ctx: &maps::Ctx, + context: &map::BakeContext, maps: &[BakedMap], mesh: &Mesh, - g: &UvGBuffer, + gbuffer: &UvGBuffer, scene: &mut dyn RayScene, rows: &mut [OutRow], - r0: usize, - (w, aa, seed0): (usize, usize, usize), + first_row: usize, + (width, samples_per_axis, first_sample_seed): (usize, usize, usize), ) -> Result<(), BakeError> { - let sw = w * aa; - let per_row: Vec> = (r0..r0 + rows.len()) + let sample_width = width * samples_per_axis; + let samples_by_row: Vec> = (first_row..first_row + rows.len()) .into_par_iter() - .map(|r| { - let subsamples = (0..w).flat_map(|x| (0..aa * aa).map(move |k| (x, (r * aa + k / aa) * sw + x * aa + k % aa))); - subsamples.filter_map(|(x, i)| Some(maps::Sample { x, surf: g.surface(mesh, i)?, bary: *g.bary.get(i)?, seed: (seed0 + i) as u64 })).collect() + .map(|row| { + let subsamples = (0..width).flat_map(|x| { + (0..samples_per_axis * samples_per_axis).map(move |sample_index| { + (x, (row * samples_per_axis + sample_index / samples_per_axis) * sample_width + x * samples_per_axis + sample_index % samples_per_axis) + }) + }); + subsamples + .filter_map(|(x, sample_index)| { + Some(map::Sample { + x, + surface: gbuffer.surface(mesh, sample_index)?, + bary: *gbuffer.bary.get(sample_index)?, + seed: (first_sample_seed + sample_index) as u64, + }) + }) + .collect() }) .collect(); - // Index of each row's first sample in the batch arrays. - let starts: Vec = per_row + let row_offsets: Vec = samples_by_row .iter() - .scan(0, |n, r| { - *n += r.len(); - Some(*n - r.len()) + .scan(0, |sample_count, row| { + *sample_count += row.len(); + Some(*sample_count - row.len()) }) .collect(); - let samples = || per_row.par_iter().flat_map_iter(|r| r.iter()); + let samples = || samples_by_row.par_iter().flat_map_iter(|row| row.iter()); - let transfers = match ctx.has_high() { + let transfers = match context.has_high() { true => { - let (rays, fronts): (Vec, Vec) = samples().map(|p| ctx.transfer_ray(&p.surf, p.bary)).unzip(); + let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); let hits = scene.closest(1, &rays)?; - hits.into_par_iter().zip(fronts).map(|(hit, front)| ctx.transfer(hit, front)).collect() + hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() } false => Vec::new(), }; - let transfer = |k: usize| transfers.get(k).and_then(Option::as_ref); - let curvature = match ctx.traces_curvature() { + let transfer = |sample_index: usize| transfers.get(sample_index).and_then(Option::as_ref); + let curvature = match context.traces_curvature() { true => { - let items: Vec<(&Surface, Option<&maps::Transfer>)> = - per_row.iter().zip(&starts).flat_map(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| (&p.surf, transfer(k))).collect(); - ctx.trace_curvature(scene, &items)? + let items: Vec<(&Surface, Option<&map::Transfer>)> = samples_by_row + .iter() + .zip(&row_offsets) + .flat_map(|(row, &first)| row.iter().zip(first..)) + .map(|(sample, sample_index)| (&sample.surface, transfer(sample_index))) + .collect(); + context.trace_curvature(scene, &items)? } false => Vec::new(), }; - let queries: Vec = match ctx.ao.is_some() || ctx.bent.is_some() || ctx.thickness.is_some() { - true => { - per_row.par_iter().zip(&starts).flat_map_iter(|(r, &first)| r.iter().zip(first..)).map(|(p, k)| ctx.query(transfer(k), &p.surf, p.seed)).collect() - } + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { + true => samples_by_row + .par_iter() + .zip(&row_offsets) + .flat_map_iter(|(row, &first)| row.iter().zip(first..)) + .map(|(sample, sample_index)| context.query(transfer(sample_index), &sample.surface, sample.seed)) + .collect(), false => Vec::new(), }; - // Bent normals come with the occlusion rays when they share the settings. - let own_bent = ctx.bent.filter(|_| ctx.bent != ctx.ao); - let passes: Vec = [ctx.ao, own_bent, ctx.thickness].into_iter().flatten().collect(); + // Share occlusion results when the bent-normal ray settings match + let separate_bent_pass = context.bent.filter(|_| context.bent != context.ao); + let passes: Vec = [context.ao, separate_bent_pass, context.thickness].into_iter().flatten().collect(); let mut results = scene.hemispheres(&passes, &queries)?.into_iter(); - let mut next = |on: bool| if on { results.next().unwrap_or_default() } else { Vec::new() }; - let (ao, bent_own, thickness) = (next(ctx.ao.is_some()), next(own_bent.is_some()), next(ctx.thickness.is_some())); - let bent = if own_bent.is_some() { &bent_own } else { &ao }; + let mut next = |enabled: bool| if enabled { results.next().unwrap_or_default() } else { Vec::new() }; + let (occlusion_results, separate_bent_results, thickness) = + (next(context.ao.is_some()), next(separate_bent_pass.is_some()), next(context.thickness.is_some())); + let bent_results = if separate_bent_pass.is_some() { &separate_bent_results } else { &occlusion_results }; - rows.par_iter_mut().zip(&per_row).zip(&starts).for_each(|((row, samples), &first)| { - let mut sample = [[0.0f32; 3]; BakedMap::ALL.len()]; - let mut j = 0; - for x in 0..w { - let mut acc = [[0.0f32; 3]; BakedMap::ALL.len()]; - let mut n = 0u32; - while let Some(p) = samples.get(j).filter(|p| p.x == x) { - let k = first + j; - let traced = maps::Traced { - ao: ao.get(k).map_or(1.0, |v| v[0]), - bent: bent.get(k).map(|v| Vec3::new(v[1], v[2], v[3])), - thickness: thickness.get(k).map_or(1.0, |v| v[0]), - curvature: curvature.get(k).copied().unwrap_or(0.5), + rows.par_iter_mut().zip(&samples_by_row).zip(&row_offsets).for_each(|((row, samples), &first)| { + let mut sample_values = [[0.0f32; 3]; BakedMap::ALL.len()]; + let mut row_sample_index = 0; + for x in 0..width { + let mut accumulated = [[0.0f32; 3]; BakedMap::ALL.len()]; + let mut sample_count = 0u32; + while let Some(sample) = samples.get(row_sample_index).filter(|sample| sample.x == x) { + let sample_index = first + row_sample_index; + let traced = map::Traced { + ao: occlusion_results.get(sample_index).map_or(1.0, |value| value[0]), + bent: bent_results.get(sample_index).map(|value| Vec3::new(value[1], value[2], value[3])), + thickness: thickness.get(sample_index).map_or(1.0, |value| value[0]), + curvature: curvature.get(sample_index).copied().unwrap_or(0.5), }; - ctx.evaluate(maps, &p.surf, p.bary, transfer(k), &traced, &mut sample); - for (a, v) in acc.iter_mut().zip(&sample) { - a.iter_mut().zip(v).for_each(|(a, v)| *a += v); + context.evaluate(maps, &sample.surface, sample.bary, transfer(sample_index), &traced, &mut sample_values); + for (sum, value) in accumulated.iter_mut().zip(&sample_values) { + sum.iter_mut().zip(value).for_each(|(sum, value)| *sum += value); } - n += 1; - j += 1; + sample_count += 1; + row_sample_index += 1; } - for ((m, dst), a) in maps.iter().zip(row.iter_mut()).zip(&acc) { - let comps = m.components(); - let mean = a.map(|a| a / n.max(1) as f32); - let v = if n == 0 || mean.iter().any(|v| !v.is_finite()) { m.neutral() } else { mean }; - if let Some(d) = dst.get_mut(x * comps..(x + 1) * comps) { - d.iter_mut().zip(v).for_each(|(d, v)| *d = v); + + for ((map, destination), sum) in maps.iter().zip(row.iter_mut()).zip(&accumulated) { + let component_count = map.components(); + let mean = sum.map(|sum| sum / sample_count.max(1) as f32); + let value = if sample_count == 0 || mean.iter().any(|value| !value.is_finite()) { map.neutral() } else { mean }; + if let Some(pixel) = destination.get_mut(x * component_count..(x + 1) * component_count) { + pixel.iter_mut().zip(value).for_each(|(component, value)| *component = value); } } } diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs new file mode 100644 index 00000000..30bb29d0 --- /dev/null +++ b/crates/bake/src/map.rs @@ -0,0 +1,15 @@ +mod bake_context; +mod curvature; +mod curvature_tuning; +mod normal_curvature; +mod sample; +mod sampling; +mod source; +mod traced; +mod transfer; + +pub(crate) use bake_context::BakeContext; +pub(crate) use normal_curvature::curvature_from_normal; +pub(crate) use sample::Sample; +pub(crate) use traced::Traced; +pub(crate) use transfer::Transfer; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs new file mode 100644 index 00000000..c359350f --- /dev/null +++ b/crates/bake/src/map/bake_context.rs @@ -0,0 +1,250 @@ +use super::curvature::{Curvature, RAYS_PER_RING, RING_COUNT}; +use super::sampling::{interpolate, material_color, pack, splitmix64, tangent_normal, welded}; +use super::{source::Source, traced::Traced, transfer::Transfer}; +use crate::skew::PreparedSkew; +use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; +use crate::{BakeError, BakeRequest}; +use rayon::prelude::*; +use std::collections::HashMap; +use texturecraft_core::{BackfaceMode, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; + +const CURVATURE_CHUNK: usize = 1 << 15; + +pub(crate) struct BakeContext<'a> { + low: Source<'a>, + high: Option>, + cage: Option<&'a Mesh>, + skew: Option>, + ray_normals: Vec, + lo: Vec3, + extent: Vec3, + eps: f32, + frontal: f32, + rear: f32, + position_mode: PositionMode, + curvature_method: CurvatureMethod, + curvature: Curvature, + pub ao: Option, + pub bent: Option, + pub thickness: Option, +} + +impl<'a> BakeContext<'a> { + pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + let settings = request.settings; + let (bounds_min, bounds_max) = request.mesh.bounds(); + let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); + if !mesh_diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, &[], &settings.high_poly.low_suffix, &mut name_keys); + let high = + request.high.map(|high_mesh| Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, &settings.high_poly.high_suffix, &mut name_keys)); + let ray_normals = match settings.cage.average_normals && high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_diagonal)).transpose()?; + let ray_epsilon = 1e-4 * mesh_diagonal; + let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { + let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); + let occlusion = kind == RayKind::Occlusion; + settings.maps.is_enabled(map).then_some(Hemisphere { + kind, + rays: ray_settings.rays, + dmax: ray_settings.max_distance * mesh_diagonal, + eps: ray_epsilon, + cos_max: half_angle_radians.cos(), + sin_max: half_angle_radians.sin(), + uniform: ray_settings.distribution == RayDistribution::Uniform, + ignore_backface: occlusion && settings.maps.ao.parameters.ignore_backface != BackfaceMode::Never, + same_key: occlusion && settings.maps.ao.parameters.self_occlusion == SelfOcclusion::SameMeshName, + }) + }; + + Ok(BakeContext { + low, + high, + cage: request.cage, + skew, + ray_normals, + lo: bounds_min, + extent: bounds_max - bounds_min, + eps: ray_epsilon, + frontal: settings.cage.max_frontal * mesh_diagonal, + rear: settings.cage.max_rear * mesh_diagonal, + position_mode: settings.maps.position.parameters.normalization, + curvature_method: settings.maps.curvature.parameters.method, + curvature: Curvature::new(settings, request.mesh, mesh_diagonal, request.tiles), + ao: pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion), + bent: pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion), + thickness: pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness), + }) + } + + pub(crate) fn has_high(&self) -> bool { + self.high.is_some() + } + + pub(crate) fn casts_rays(&self) -> bool { + self.has_high() || self.curvature.is_enabled || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() + } + + pub(crate) fn trace_meshes(&self) -> Vec> { + std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect() + } + + pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { + let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let cage = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.eps); + let (origin, direction, front) = match cage { + Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), + None => { + let up = match &self.skew { + Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), + None => averaged_normal, + }; + (surface.pos + up * self.frontal, -up, self.frontal) + } + }; + (Ray { origin, direction, max_distance: front + self.rear, key: ANY }, front) + } + + pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + let (high, hit) = (self.high.as_ref()?, hit?); + let surface = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front }) + } + + pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { + let (source, surface, mesh) = match (&self.high, transfer) { + (Some(high), Some(transfer_hit)) => (high, &transfer_hit.surface, 1), + _ => (&self.low, low_surface, 0), + }; + let seed_hash = splitmix64(seed); + let rot = [(seed_hash >> 40) as f32 / (1u64 << 24) as f32, ((seed_hash >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32]; + let geo = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm }; + Query { pos: surface.pos, nrm: surface.nrm, geo, rot, key: source.key.get(surface.tri as usize).copied().unwrap_or(ANY), mesh } + } + + pub(crate) fn traces_curvature(&self) -> bool { + self.curvature.is_enabled + } + + pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result, BakeError> { + let mut output = vec![0.5; samples.len()]; + let curvature = &self.curvature; + for mesh in [0usize, 1] { + let Some(source) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue }; + let tuning = if mesh == 0 { &curvature.low } else { &curvature.high }; + let chosen: Vec<(usize, &Surface, f32)> = samples + .par_iter() + .enumerate() + .filter_map(|(sample_index, (low_surface, transfer_hit))| { + let surface = match (mesh, transfer_hit) { + (1, Some(hit)) => &hit.surface, + (0, None) => *low_surface, + _ => return None, + }; + Some((sample_index, surface, curvature.texel(low_surface.tri))) + }) + .collect(); + let rays_per_sample = RING_COUNT * RAYS_PER_RING; + for chunk in chosen.chunks(CURVATURE_CHUNK) { + let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * rays_per_sample); + rays.par_chunks_mut(rays_per_sample).zip(chunk).for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, ANY, output)); + let hits = scene.closest(mesh, &rays)?; + let walls = |chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + RAYS_PER_RING).unwrap_or_default(); + let grounds: Vec = chunk + .par_iter() + .enumerate() + .flat_map_iter(|(chunk_index, (_, surface, texel))| { + let mut value = Vec::new(); + curvature.ground_rays(surface, *texel, ANY, walls(chunk_index), &mut value); + value + }) + .collect(); + let ground_hits = scene.closest(mesh, &grounds)?; + let ground_offsets: Vec = (0..chunk.len()) + .scan(0, |first, chunk_index| { + let offset = *first; + *first += walls(chunk_index).iter().flatten().count(); + Some(offset) + }) + .collect(); + let values: Vec<(usize, f32)> = chunk + .par_iter() + .zip(&ground_offsets) + .enumerate() + .map(|(chunk_index, ((sample_index, surface, texel), first))| { + let ground_count = walls(chunk_index).iter().flatten().count(); + let sample_ground_hits = ground_hits.get(*first..*first + ground_count).unwrap_or_default(); + let sample_hits = hits.get(chunk_index * rays_per_sample..(chunk_index + 1) * rays_per_sample).unwrap_or_default(); + (*sample_index, curvature.value(tuning, source, surface, *texel, sample_hits, sample_ground_hits)) + }) + .collect(); + for (sample_index, value) in values { + if let Some(destination) = output.get_mut(sample_index) { + *destination = value; + } + } + } + } + Ok(output) + } + + pub(crate) fn evaluate( + &self, + maps: &[BakedMap], + low_surface: &Surface, + barycentric: [f32; 2], + transfer: Option<&Transfer>, + traced: &Traced, + outputs: &mut [[f32; 3]], + ) { + let (source, surface, source_barycentric) = match (&self.high, transfer) { + (Some(high), Some(hit)) => (high, &hit.surface, hit.bary), + _ => (&self.low, low_surface, barycentric), + }; + + let missed = self.high.is_some() && transfer.is_none(); + for (&map, output) in maps.iter().zip(outputs.iter_mut()) { + *output = match map { + BakedMap::AmbientOcclusion => [traced.ao; 3], + BakedMap::BentNormal => pack(traced.bent.unwrap_or(surface.nrm)), + BakedMap::Thickness => [traced.thickness; 3], + BakedMap::Curvature if self.curvature_method == CurvatureMethod::NormalMap => [0.5; 3], + BakedMap::Curvature => [traced.curvature; 3], + BakedMap::WorldNormal => pack(surface.nrm), + BakedMap::Position => self.position(surface.pos), + BakedMap::Id => material_color(source.part.get(surface.tri as usize).copied().unwrap_or(0) as usize), + BakedMap::Normal => transfer.map_or(map.neutral(), |hit| tangent_normal(low_surface, hit.surface.nrm)), + BakedMap::Height => [transfer.map_or(0.5, |hit| (0.5 + (hit.front - hit.t) / (hit.front + self.rear)).clamp(0.0, 1.0)); 3], + BakedMap::Opacity if missed => [0.0; 3], + BakedMap::Opacity => [source.color(surface, source_barycentric).w; 3], + }; + } + } + + fn position(&self, position: Vec3) -> [f32; 3] { + let normalized = match self.position_mode { + PositionMode::BoundingBox => (position - self.lo) / self.extent.max(Vec3::splat(1e-20)), + PositionMode::BoundingSphere => (position - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5, + PositionMode::None => return position.to_array(), + }; + + normalized.clamp(Vec3::ZERO, Vec3::ONE).to_array() + } +} diff --git a/crates/bake/src/map/curvature.rs b/crates/bake/src/map/curvature.rs new file mode 100644 index 00000000..6aa74776 --- /dev/null +++ b/crates/bake/src/map/curvature.rs @@ -0,0 +1,198 @@ +use super::{curvature_tuning::CurvatureTuning, sampling::interpolate, source::Source}; +use crate::tracing::Ray; +use rayon::prelude::*; +use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Hit, Mesh, Surface}; + +pub(super) const RAYS_PER_RING: usize = 8; +pub(super) const RING_COUNT: usize = 4; +const WALL_RADIUS_TEXELS: f32 = 1.5; +const CONCAVE_WEIGHT: f32 = 1.5; +const LOW_POLY_CONVEX_WEIGHT: f32 = 1.5; +const HIGH_POLY_CONVEX_WEIGHT: f32 = 0.5; +const LOW_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.003; +const LOW_POLY_CURVATURE_WEIGHT: f32 = 1.3; +const HIGH_POLY_CURVATURE_RADIUS_RATIO: f32 = 0.0007; +const HIGH_POLY_CURVATURE_WEIGHT: f32 = 1.6; +const HARD_EDGE_NORMAL_CHANGE_THRESHOLD: f32 = 0.05; +const GENTLE_CURVATURE_THRESHOLD: f32 = 0.1; + +pub(super) struct Curvature { + pub(super) is_enabled: bool, + walls: f32, + spread: f32, + fallback: f32, + texels: Vec, + ring: [(f32, f32); RAYS_PER_RING], + pub(super) low: CurvatureTuning, + pub(super) high: CurvatureTuning, +} + +impl Curvature { + pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_diagonal: f32, tiles: (u32, u32)) -> Curvature { + let is_enabled = settings.maps.is_enabled(BakedMap::Curvature) && settings.maps.curvature.parameters.method == CurvatureMethod::Mesh; + let resolution = settings.common.resolution.pixels() as f32 * ((tiles.0.max(1) * tiles.1.max(1)) as f32).sqrt(); + let texel = |triangle: usize| { + let [a, b, c] = low.tri(triangle)?; + let (position_a, position_b, position_c) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?); + let (uv_a, uv_b, uv_c) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?); + let world_area = (position_b - position_a).cross(position_c - position_a).length(); + let uv_area = (uv_b - uv_a).perp_dot(uv_c - uv_a).abs(); + (uv_area > 1e-12 && world_area > 0.0).then(|| (world_area / uv_area).sqrt() / resolution) + }; + let fallback = mesh_diagonal * 1e-3; + let triangle_count = if is_enabled { low.triangle_count() } else { 0 }; + let walls = WALL_RADIUS_TEXELS; + Curvature { + is_enabled, + walls, + spread: walls * 4.0 / 3.0, + fallback, + texels: (0..triangle_count).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(), + low: CurvatureTuning { + convex: LOW_POLY_CONVEX_WEIGHT, + true_radius: mesh_diagonal * LOW_POLY_CURVATURE_RADIUS_RATIO, + true_strength: LOW_POLY_CURVATURE_WEIGHT, + }, + high: CurvatureTuning { + convex: HIGH_POLY_CONVEX_WEIGHT, + true_radius: mesh_diagonal * HIGH_POLY_CURVATURE_RADIUS_RATIO, + true_strength: HIGH_POLY_CURVATURE_WEIGHT, + }, + ring: std::array::from_fn(|i| { + let a = std::f32::consts::TAU * i as f32 / RAYS_PER_RING as f32; + (a.cos(), a.sin()) + }), + } + } + + pub(super) fn texel(&self, tri: u32) -> f32 { + self.texels.get(tri as usize).copied().unwrap_or(self.fallback) + } + + fn radii(&self, tuning: &CurvatureTuning, texel: f32) -> [f32; RING_COUNT] { + let r = self.walls * texel; + [r, r, self.spread * texel, tuning.true_radius] + } + + fn directions(&self, tangent: Vec3, bitangent: Vec3) -> [Vec3; RAYS_PER_RING] { + self.ring.map(|(cos, sin)| tangent * cos + bitangent * sin) + } + + pub(super) fn rays(&self, tuning: &CurvatureTuning, surface: &Surface, texel_size: f32, key: u32, output: &mut [Ray]) { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let directions = self.directions(tangent, bitangent); + let radii = self.radii(tuning, texel_size); + for (ring, (rays, radius)) in output.chunks_exact_mut(RAYS_PER_RING).zip(radii).enumerate() { + for (ray, direction) in rays.iter_mut().zip(directions) { + *ray = match ring { + 0 => Ray { origin: surface.pos + geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, + 1 => Ray { origin: surface.pos - geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, + _ => Ray { + origin: surface.pos + direction * radius + geometric_normal * (0.25 * radius), + direction: -geometric_normal, + max_distance: 2.25 * radius, + key, + }, + }; + } + } + } + + pub(super) fn ground_rays(&self, surface: &Surface, texel_size: f32, key: u32, walls: &[Option], output: &mut Vec) { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let radius = self.walls * texel_size; + for (w, direction) in walls.iter().zip(self.directions(tangent, bitangent)) { + if let Some(hit) = w { + output.push(Ray { + origin: surface.pos + geometric_normal * (0.15 * radius) + direction * (hit.t * 0.85), + direction: -geometric_normal, + max_distance: 0.5 * radius, + key, + }); + } + } + } + + fn wall(&self, source: &Source, surface: &Surface, geometric_normal: Vec3, radius: f32, hits: &[Option], keep: &mut dyn FnMut() -> bool) -> f32 { + let mut sum = 0.0; + for hit in hits.iter().flatten() { + if !keep() { + continue; + } + let upright = triangle_normal(source.mesh, hit.tri).map_or(1.0, |normal| (1.0 - normal.dot(geometric_normal).powi(2)).max(0.0).sqrt()); + let shaded = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let hard = ((1.0 - shaded.dot(surface.nrm)) / HARD_EDGE_NORMAL_CHANGE_THRESHOLD).clamp(0.0, 1.0); + sum += (1.0 - hit.t / radius) * upright * hard; + } + sum / RAYS_PER_RING as f32 + } + + fn spread( + &self, + source: &Source, + surface: &Surface, + geometric_normal: Vec3, + directions: &[Vec3; RAYS_PER_RING], + hits: &[Option], + turn: f32, + ) -> (f32, f32) { + let (mut shading, mut faces) = (0.0, 0.0); + for (hit, direction) in hits.iter().zip(directions) { + let Some(hit) = hit else { continue }; + let normal = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + if 1.0 - normal.dot(surface.nrm) <= turn { + shading += (normal - surface.nrm).dot(*direction); + if let Some(f) = triangle_normal(source.mesh, hit.tri) { + let f = if f.dot(geometric_normal) < 0.0 { -f } else { f }; + faces += (f - geometric_normal).dot(*direction); + } + } + } + (shading / RAYS_PER_RING as f32, faces / RAYS_PER_RING as f32) + } + + pub(super) fn value( + &self, + tuning: &CurvatureTuning, + source: &Source, + surface: &Surface, + texel_size: f32, + hits: &[Option], + ground_hits: &[Option], + ) -> f32 { + let (geometric_normal, tangent, bitangent) = surface_frame(surface); + let directions = self.directions(tangent, bitangent); + let ring = |ring_index: usize| hits.get(ring_index * RAYS_PER_RING..(ring_index + 1) * RAYS_PER_RING).unwrap_or_default(); + let radius = self.walls * texel_size; + let mut next = ground_hits.iter(); + let above = self.wall(source, surface, geometric_normal, radius, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * radius)); + let below = self.wall(source, surface, geometric_normal, radius, ring(1), &mut || true); + let (shading, _) = self.spread(source, surface, geometric_normal, &directions, ring(2), 2.0); + let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, &directions, ring(3), 2.0); + let value = + -above * CONCAVE_WEIGHT + (below - above).max(0.0) * tuning.convex + shading * 0.5 + tight(agreed(true_shading, true_faces) * tuning.true_strength); + (0.5 + value).clamp(0.0, 1.0) + } +} + +fn triangle_normal(mesh: &Mesh, tri: u32) -> Option { + let [a, b, c] = mesh.tri(tri as usize)?; + let p = |i: usize| mesh.positions.get(i).copied(); + (p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize() +} + +fn surface_frame(surface: &Surface) -> (Vec3, Vec3, Vec3) { + let geometric_normal = if surface.geo_nrm.dot(surface.nrm) < 0.0 { -surface.geo_nrm } else { surface.geo_nrm }; + let (tangent, bitangent) = geometric_normal.any_orthonormal_pair(); + (geometric_normal, tangent, bitangent) +} + +fn tight(v: f32) -> f32 { + v.signum() * (v.abs() - GENTLE_CURVATURE_THRESHOLD).max(0.0) +} + +fn agreed(shading: f32, faces: f32) -> f32 { + if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) } +} diff --git a/crates/bake/src/map/curvature_tuning.rs b/crates/bake/src/map/curvature_tuning.rs new file mode 100644 index 00000000..753edfb6 --- /dev/null +++ b/crates/bake/src/map/curvature_tuning.rs @@ -0,0 +1,5 @@ +pub(super) struct CurvatureTuning { + pub(super) convex: f32, + pub(super) true_radius: f32, + pub(super) true_strength: f32, +} diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs new file mode 100644 index 00000000..2507ff9c --- /dev/null +++ b/crates/bake/src/map/normal_curvature.rs @@ -0,0 +1,26 @@ +/// Divergence of the tangent-space normal map; positive curvature is convex +pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], width: usize, tile_resolution: usize, output: &mut [f32]) { + use rayon::prelude::*; + let radius_texels = (tile_resolution / 512).max(1); + let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) { + Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback), + _ => fallback, + }; + output.par_chunks_mut(width).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + if covered.get(y * width + x) != Some(&true) { + continue; + } + let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5)); + let (left, right) = ( + normal_component(x.saturating_sub(radius_texels), y, 0, center_x), + if x + radius_texels < width { normal_component(x + radius_texels, y, 0, center_x) } else { center_x }, + ); + let (up, down) = ( + normal_component(x, y.saturating_sub(radius_texels), 1, center_y), + if y + radius_texels < width { normal_component(x, y + radius_texels, 1, center_y) } else { center_y }, + ); + *value = (0.5 + (right - left) + (up - down)).clamp(0.0, 1.0); + } + }); +} diff --git a/crates/bake/src/map/sample.rs b/crates/bake/src/map/sample.rs new file mode 100644 index 00000000..2ff9a10e --- /dev/null +++ b/crates/bake/src/map/sample.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::Surface; + +pub(crate) struct Sample { + pub x: usize, + pub surface: Surface, + pub bary: [f32; 2], + pub seed: u64, +} diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs new file mode 100644 index 00000000..ab5f187d --- /dev/null +++ b/crates/bake/src/map/sampling.rs @@ -0,0 +1,67 @@ +use std::collections::HashMap; +use std::ops::{Add, Mul}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { + let [a, b, c] = mesh.tri(tri as usize)?; + Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +} + +pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { + let q = diag * 1e-5; + let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); + let weld: Vec = mesh + .positions + .iter() + .zip(&mesh.normals) + .map(|(p, n)| { + let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); + let id = *ids.entry(key).or_insert_with(|| { + pos.push(*p); + nrm.push(Vec3::ZERO); + (pos.len() - 1) as u32 + }); + if let Some(acc) = nrm.get_mut(id as usize) { + *acc += *n; + } + id + }) + .collect(); + let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (weld, pos, nrm) +} + +pub(super) fn splitmix64(x: u64) -> u64 { + let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +pub(super) fn pack(v: Vec3) -> [f32; 3] { + (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array() +} + +pub(super) fn material_color(part: usize) -> [f32; 3] { + let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; + let (s, v) = (0.7f32, 0.95f32); + let f = h.fract(); + let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); + match h as u32 { + 0 => [v, t, p], + 1 => [q, v, p], + 2 => [p, v, t], + 3 => [p, q, v], + 4 => [t, p, v], + _ => [v, p, q], + } +} + +pub(super) fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] { + let z = s.nrm; + let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector()); + let b = z.cross(t) * s.tangent.w; + pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n))) +} diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs new file mode 100644 index 00000000..6760df57 --- /dev/null +++ b/crates/bake/src/map/source.rs @@ -0,0 +1,70 @@ +use super::sampling::interpolate; +use crate::tracing::{ANY, TraceMesh}; +use std::collections::HashMap; +use std::sync::Arc; +use texturecraft_geom::glam::{Vec2, Vec4}; +use texturecraft_geom::{BaseColor, Bvh, Mesh, Surface}; +use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; + +pub(super) struct Source<'a> { + pub(super) mesh: &'a Mesh, + bvh: &'a Bvh, + pub(super) part: Vec, + pub(super) key: Vec, + base_color: &'a [Option>], +} + +impl<'a> Source<'a> { + pub(super) fn new(mesh: &'a Mesh, bvh: &'a Bvh, base_color: &'a [Option>], suffix: &str, keys: &mut HashMap) -> Source<'a> { + let triangle_count = mesh.triangle_count(); + let mut part = vec![ANY; triangle_count]; + for (part_index, submesh) in mesh.submeshes.iter().enumerate() { + let (first_triangle, last_triangle) = ((submesh.start / 3) as usize, (submesh.start.saturating_add(submesh.count) / 3) as usize); + part.get_mut(first_triangle.min(last_triangle)..last_triangle.min(triangle_count)).unwrap_or_default().fill(part_index as u32); + } + let part_keys: Vec = mesh.submeshes.iter().map(|submesh| match_key(&submesh.name, suffix, keys)).collect(); + let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect(); + Source { mesh, bvh, part, key, base_color } + } + + pub(super) fn trace(&self) -> TraceMesh<'_> { + TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key } + } + + pub(super) fn color(&self, surface: &Surface, barycentric: [f32; 2]) -> Vec4 { + let vertex = interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE); + let material = self.part.get(surface.tri as usize).and_then(|part_index| self.mesh.submeshes.get(*part_index as usize)).map(|submesh| submesh.material); + match material.and_then(|material_index| self.base_color.get(material_index)?.as_deref()) { + Some(material_color) => vertex * base_color(material_color, surface.uv), + None => vertex, + } + } +} + +fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { + let sampled_color = if material.texels.is_empty() || !uv.is_finite() { + Vec4::ONE + } else { + let (width, height) = (i64::from(material.width.max(1)), i64::from(material.height.max(1))); + let texel = |x: i64, y: i64| { + let rgba = material.texels.get((y.rem_euclid(height) * width + x.rem_euclid(width)) as usize).copied().unwrap_or([255; 4]); + let color = |component: usize| f32::from(rgba[component]) / 255.0; + Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) + }; + let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + }; + let color = sampled_color * material.factor; + Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) +} + +fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { + let name = name.trim().to_lowercase(); + let suffix = suffix.trim().to_lowercase(); + let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string(); + let next = keys.len() as u32; + *keys.entry(base).or_insert(next) +} diff --git a/crates/bake/src/map/traced.rs b/crates/bake/src/map/traced.rs new file mode 100644 index 00000000..45107d66 --- /dev/null +++ b/crates/bake/src/map/traced.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::glam::Vec3; + +pub(crate) struct Traced { + pub ao: f32, + pub bent: Option, + pub thickness: f32, + pub curvature: f32, +} diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs new file mode 100644 index 00000000..c1200053 --- /dev/null +++ b/crates/bake/src/map/transfer.rs @@ -0,0 +1,8 @@ +use texturecraft_geom::Surface; + +pub(crate) struct Transfer { + pub(super) surface: Surface, + pub(super) bary: [f32; 2], + pub(super) t: f32, + pub(super) front: f32, +} diff --git a/crates/bake/src/maps.rs b/crates/bake/src/maps.rs deleted file mode 100644 index 6373ea77..00000000 --- a/crates/bake/src/maps.rs +++ /dev/null @@ -1,678 +0,0 @@ -//! Per-sample evaluation of every baked map. - -use std::collections::HashMap; -use std::ops::{Add, Mul}; -use std::sync::Arc; - -use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; -use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; -use texturecraft_geom::{BaseColor, Bvh, Hit, Mesh, Surface, surface_at}; -use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; - -use rayon::prelude::*; - -use crate::rays::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::skew::Prepared; -use crate::{BakeError, BakeRequest}; - -/// A mesh the bakers sample: the low poly, or the high poly detail is transferred from. -struct Source<'a> { - mesh: &'a Mesh, - bvh: &'a Bvh, - /// Submesh (part) index of each triangle ([`ANY`] outside every part). - part: Vec, - /// Match key of each triangle: its part name without the low / high suffix. - key: Vec, - /// Base color per material (empty: vertex colors only). - base_color: &'a [Option>], -} - -impl<'a> Source<'a> { - fn new(mesh: &'a Mesh, bvh: &'a Bvh, base_color: &'a [Option>], suffix: &str, keys: &mut HashMap) -> Source<'a> { - let tris = mesh.triangle_count(); - let mut part = vec![ANY; tris]; - for (i, sm) in mesh.submeshes.iter().enumerate() { - let (a, b) = ((sm.start / 3) as usize, (sm.start.saturating_add(sm.count) / 3) as usize); - part.get_mut(a.min(b)..b.min(tris)).unwrap_or_default().fill(i as u32); - } - let ids: Vec = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect(); - let key = part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(ANY)).collect(); - Source { mesh, bvh, part, key, base_color } - } - - fn trace(&self) -> TraceMesh<'_> { - TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key } - } - - /// Vertex color times the material's base color (color sRGB-encoded like a base color - /// texture, alpha linear). - fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 { - let vertex = interpolate(self.mesh, &self.mesh.colors, s.tri, bary).unwrap_or(Vec4::ONE); - let material = self.part.get(s.tri as usize).and_then(|p| self.mesh.submeshes.get(*p as usize)).map(|sm| sm.material); - match material.and_then(|m| self.base_color.get(m)?.as_deref()) { - Some(b) => vertex * base_color(b, s.uv), - None => vertex, - } - } -} - -/// `b` at `uv` (bilinear in linear light, wrapped) times its factor: color sRGB-encoded, -/// alpha linear. -fn base_color(b: &BaseColor, uv: Vec2) -> Vec4 { - let tex = if b.texels.is_empty() || !uv.is_finite() { - Vec4::ONE - } else { - let (w, h) = (i64::from(b.width.max(1)), i64::from(b.height.max(1))); - let texel = |x: i64, y: i64| { - let t = b.texels.get((y.rem_euclid(h) * w + x.rem_euclid(w)) as usize).copied().unwrap_or([255; 4]); - let c = |k: usize| f32::from(t[k]) / 255.0; - Vec4::new(srgb_to_linear(c(0)), srgb_to_linear(c(1)), srgb_to_linear(c(2)), c(3)) - }; - let (fx, fy) = (uv.x * w as f32 - 0.5, uv.y * h as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) - }; - let c = tex * b.factor; - Vec4::new(linear_to_srgb(c.x), linear_to_srgb(c.y), linear_to_srgb(c.z), c.w) -} - -/// The part name without its low / high suffix (case-insensitive), as a shared id. -fn match_key(name: &str, suffix: &str, keys: &mut HashMap) -> u32 { - let name = name.trim().to_lowercase(); - let suffix = suffix.trim().to_lowercase(); - let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string(); - let next = keys.len() as u32; - *keys.entry(base).or_insert(next) -} - -/// Mesh curvature from short rays around each sample, in batches, so the GPU casts them when there -/// is one. The result does not depend on how big the triangles are, and it reads across UV seams and -/// between separate parts. Line radii are in texels of the low poly triangle under the sample, so a -/// line is as wide on a small densely unwrapped part as on a big plate. -struct Curvature { - on: bool, - strength: f32, - /// Sampling radius of the walls, and of the smooth normals, in texels. - walls: f32, - spread: f32, - /// World size of a texel on triangles without usable UVs. - fallback: f32, - /// World size of one texel on each low poly triangle; empty when off. - texels: Vec, - /// Cosine and sine of each direction of a ring. - ring: [(f32, f32); CURVATURE_RAYS], - /// Read from the low poly itself, and from a high poly. - low: Tuning, - high: Tuning, -} - -/// What differs between reading the low poly and reading a high poly. -struct Tuning { - convex: f32, - /// World radius of the true curvature: wider than the facets of a dense mesh, so it averages - /// across them, and the same at any map size. - true_radius: f32, - true_strength: f32, -} - -/// Rays per ring around a sample. -const CURVATURE_RAYS: usize = 8; -/// Samples whose curvature rays are cast at once: bounds their memory (about 2 MB of rays and hits -/// per thousand samples) and a GPU submission, at any resolution and antialiasing. -const CURVATURE_CHUNK: usize = 1 << 15; -/// Rings: wall above, wall below, smooth normals, true curvature. -const CURVATURE_RINGS: usize = 4; -/// Sampling radius of the walls, in texels of the low poly triangle. -const CURVATURE_WALLS: f32 = 1.5; -/// Weight of the concave walls, and of the convex edges from the low poly itself and a high poly. -const CURVATURE_CONCAVE: f32 = 1.5; -const CURVATURE_CONVEX: f32 = 1.5; -const CURVATURE_CONVEX_HIGH: f32 = 0.5; -/// Radius of the true curvature, as a fraction of the model size, and its strength, from the low -/// poly itself and from a high poly. A high poly's small radius keeps a line along a whole edge and -/// its dense detail from wearing in patches. -const CURVATURE_TRUE_RADIUS: f32 = 0.003; -const CURVATURE_TRUE: f32 = 1.3; -const CURVATURE_TRUE_RADIUS_HIGH: f32 = 0.0007; -const CURVATURE_TRUE_HIGH: f32 = 1.6; -/// How much the shading normal must turn (1 − cos) for a corner to count as hard. -const CURVATURE_HARD_EDGE: f32 = 0.05; -/// Map value below which true curvature counts as gently round. -const CURVATURE_GENTLE: f32 = 0.1; - -fn triangle_normal(mesh: &Mesh, tri: u32) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - let p = |i: usize| mesh.positions.get(i).copied(); - (p(b)? - p(a)?).cross(p(c)? - p(a)?).try_normalize() -} - -/// The geometric normal on the side of the shading normal, and two directions along the surface. -fn surface_frame(surf: &Surface) -> (Vec3, Vec3, Vec3) { - let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm }; - let (t, b) = geo.any_orthonormal_pair(); - (geo, t, b) -} - -/// Only tight curves count: a gently round surface like a barrel is not an edge. Lifting it would put -/// it on a wear mask's threshold, and the mask's noise would show as patches. -fn tight(v: f32) -> f32 { - v.signum() * (v.abs() - CURVATURE_GENTLE).max(0.0) -} - -/// What shading and faces agree on. A flat low poly face only turns in its shading, a smooth shaded -/// low poly corner only in its faces; a real rounded surface turns in both. -fn agreed(shading: f32, faces: f32) -> f32 { - if shading * faces <= 0.0 { 0.0 } else { shading.abs().min(faces.abs()).copysign(shading) } -} - -impl Curvature { - fn new(s: &BakeSettings, low: &Mesh, diag: f32, tiles: (u32, u32)) -> Curvature { - let on = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal && s.curvature_strength != 0.0; - // UVs are in atlas space: across the whole tile grid, each tile `resolution` texels wide. - let resolution = s.resolution.max(1) as f32 * ((tiles.0.max(1) * tiles.1.max(1)) as f32).sqrt(); - let texel = |tri: usize| { - let [a, b, c] = low.tri(tri)?; - let (pa, pb, pc) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?); - let (ua, ub, uc) = (*low.uvs.get(a)?, *low.uvs.get(b)?, *low.uvs.get(c)?); - let world = (pb - pa).cross(pc - pa).length(); - let uv = (ub - ua).perp_dot(uc - ua).abs(); - (uv > 1e-12 && world > 0.0).then(|| (world / uv).sqrt() / resolution) - }; - let fallback = diag * 1e-3; - let tris = if on { low.triangle_count() } else { 0 }; - let walls = CURVATURE_WALLS; - Curvature { - on, - strength: s.curvature_strength, - walls, - spread: walls * 4.0 / 3.0, - fallback, - texels: (0..tris).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(), - low: Tuning { convex: CURVATURE_CONVEX, true_radius: diag * CURVATURE_TRUE_RADIUS, true_strength: CURVATURE_TRUE }, - high: Tuning { convex: CURVATURE_CONVEX_HIGH, true_radius: diag * CURVATURE_TRUE_RADIUS_HIGH, true_strength: CURVATURE_TRUE_HIGH }, - ring: std::array::from_fn(|i| { - let a = std::f32::consts::TAU * i as f32 / CURVATURE_RAYS as f32; - (a.cos(), a.sin()) - }), - } - } - - /// World size of one texel on low poly triangle `tri`. - fn texel(&self, tri: u32) -> f32 { - self.texels.get(tri as usize).copied().unwrap_or(self.fallback) - } - - /// The rings' radii around a sample whose low poly texel is `texel`. - fn radii(&self, tuning: &Tuning, texel: f32) -> [f32; CURVATURE_RINGS] { - let r = self.walls * texel; - [r, r, self.spread * texel, tuning.true_radius] - } - - /// The directions of a ring around a surface. - fn directions(&self, t: Vec3, b: Vec3) -> [Vec3; CURVATURE_RAYS] { - self.ring.map(|(cos, sin)| t * cos + b * sin) - } - - /// Every ring's rays of one sample, in order, hitting only triangles of `key`. - fn rays(&self, tuning: &Tuning, surf: &Surface, texel: f32, key: u32, out: &mut [Ray]) { - let (geo, t, b) = surface_frame(surf); - let directions = self.directions(t, b); - let radii = self.radii(tuning, texel); - for (ring, (rays, r)) in out.chunks_exact_mut(CURVATURE_RAYS).zip(radii).enumerate() { - for (ray, d) in rays.iter_mut().zip(directions) { - *ray = match ring { - 0 => Ray { origin: surf.pos + geo * (0.15 * r), dir: d, tmax: r, key }, - 1 => Ray { origin: surf.pos - geo * (0.15 * r), dir: d, tmax: r, key }, - _ => Ray { origin: surf.pos + d * r + geo * (0.25 * r), dir: -geo, tmax: 2.25 * r, key }, - }; - } - } - } - - /// The check of each wall above: a contact stands on this surface, so just before the wall the - /// ground is still there. `None` for a ray that hit no wall. - fn ground_rays(&self, surf: &Surface, texel: f32, key: u32, walls: &[Option], out: &mut Vec) { - let (geo, t, b) = surface_frame(surf); - let r = self.walls * texel; - for (w, d) in walls.iter().zip(self.directions(t, b)) { - if let Some(h) = w { - out.push(Ray { origin: surf.pos + geo * (0.15 * r) + d * (h.t * 0.85), dir: -geo, tmax: 0.5 * r, key }); - } - } - } - - /// How much wall stands around the sample. A hit counts by how upright the surface hit is and by - /// how far the shading normal really breaks there: a smooth shaded corner is a smooth surface, - /// however low poly. `keep`: whether each hit counts at all. - fn wall(&self, src: &Source, surf: &Surface, geo: Vec3, r: f32, hits: &[Option], keep: &mut dyn FnMut() -> bool) -> f32 { - let mut sum = 0.0; - for h in hits.iter().flatten() { - if !keep() { - continue; - } - let upright = triangle_normal(src.mesh, h.tri).map_or(1.0, |n| (1.0 - n.dot(geo).powi(2)).max(0.0).sqrt()); - let shaded = interpolate(src.mesh, &src.mesh.normals, h.tri, [h.u, h.v]).and_then(Vec3::try_normalize).unwrap_or(surf.nrm); - let hard = ((1.0 - shaded.dot(surf.nrm)) / CURVATURE_HARD_EDGE).clamp(0.0, 1.0); - sum += (1.0 - h.t / r) * upright * hard; - } - sum / CURVATURE_RAYS as f32 - } - - /// How the normals spread apart (positive, convex) or lean together around the sample, as the - /// mean turn along the ring: of the smooth shading, and of the faces. `turn`: the most the shading - /// may turn (1 − cos) for a sample to count. - fn spread(&self, src: &Source, surf: &Surface, geo: Vec3, directions: &[Vec3; CURVATURE_RAYS], hits: &[Option], turn: f32) -> (f32, f32) { - let (mut shading, mut faces) = (0.0, 0.0); - for (h, dir) in hits.iter().zip(directions) { - let Some(h) = h else { continue }; - let n = interpolate(src.mesh, &src.mesh.normals, h.tri, [h.u, h.v]).and_then(Vec3::try_normalize).unwrap_or(surf.nrm); - if 1.0 - n.dot(surf.nrm) <= turn { - shading += (n - surf.nrm).dot(*dir); - if let Some(f) = triangle_normal(src.mesh, h.tri) { - let f = if f.dot(geo) < 0.0 { -f } else { f }; - faces += (f - geo).dot(*dir); - } - } - } - (shading / CURVATURE_RAYS as f32, faces / CURVATURE_RAYS as f32) - } - - /// The value of one sample from its rings' hits, and whether each wall above stands on the ground. - fn value(&self, tuning: &Tuning, src: &Source, surf: &Surface, texel: f32, hits: &[Option], grounds: &[Option]) -> f32 { - let (geo, t, b) = surface_frame(surf); - let directions = self.directions(t, b); - let ring = |n: usize| hits.get(n * CURVATURE_RAYS..(n + 1) * CURVATURE_RAYS).unwrap_or_default(); - let r = self.walls * texel; - let mut next = grounds.iter(); - let above = self.wall(src, surf, geo, r, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * r)); - let below = self.wall(src, surf, geo, r, ring(1), &mut || true); - let (shading, _) = self.spread(src, surf, geo, &directions, ring(2), 2.0); - let (true_shading, true_faces) = self.spread(src, surf, geo, &directions, ring(3), 2.0); - let v = -above * CURVATURE_CONCAVE - + (below - above).max(0.0) * tuning.convex - + shading * 0.5 - + tight(agreed(true_shading, true_faces) * tuning.true_strength); - (0.5 + v * self.strength).clamp(0.0, 1.0) - } -} - -/// Barycentric interpolation of a per-vertex attribute over triangle `tri`. -fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) -} - -/// A covered low-poly supersample of a batch. -pub(crate) struct Sample { - /// Output column. - pub x: usize, - pub surf: Surface, - pub bary: [f32; 2], - pub seed: u64, -} - -/// The high-poly surface found for a low-poly sample, and where along the ray. -pub(crate) struct Transfer { - surf: Surface, - bary: [f32; 2], - /// Hit distance from the ray origin, and the origin's distance in front of the low poly. - t: f32, - front: f32, -} - -/// A sample's secondary-ray results. -pub(crate) struct Traced { - pub ao: f32, - /// None when bent normals are not baked. - pub bent: Option, - pub thickness: f32, - pub curvature: f32, -} - -/// Everything a sample needs, computed once per bake. -pub(crate) struct Ctx<'a> { - low: Source<'a>, - high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - /// Normals averaged over coincident vertices (rays don't split at hard edges); empty when off. - ray_normals: Vec, - lo: Vec3, - extent: Vec3, - /// Ray offset off the surface. - eps: f32, - frontal: f32, - rear: f32, - by_name: bool, - direction: Vec3, - direction_mode: DirectionMode, - position_mode: PositionMode, - curvature_from_normal: bool, - curvature: Curvature, - /// Secondary-ray passes of the requested maps. - pub ao: Option, - pub bent: Option, - pub thickness: Option, -} - -impl<'a> Ctx<'a> { - pub(crate) fn new(req: &BakeRequest<'a>) -> Result, BakeError> { - let s = req.settings; - let (lo, hi) = req.mesh.bounds(); - let diag = (hi - lo).length().max(1e-6); - if !diag.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - let mut keys = HashMap::new(); - let low = Source::new(req.mesh, req.bvh, &[], &s.low_suffix, &mut keys); - let high = req.high.map(|h| Source::new(h.mesh, h.bvh, h.base_color, &s.high_suffix, &mut keys)); - let ray_normals = match s.average_normals && high.is_some() { - true => { - let (weld, _, nrm) = welded(req.mesh, diag); - weld.iter().map(|w| nrm.get(*w as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - let skew = req.skew.map(|m| Prepared::new(m, req.mesh, diag)).transpose()?; - let eps = 1e-4 * diag; - let pass = |map: BakedMap, r: &RaySettings, kind: RayKind| { - let half = (r.spread.clamp(0.0, 180.0) * 0.5).to_radians(); - let occlusion = kind == RayKind::Occlusion; - s.maps.contains(&map).then_some(Hemisphere { - kind, - rays: r.rays, - dmax: r.max_distance * diag, - eps, - cos_max: half.cos(), - sin_max: half.sin(), - uniform: r.distribution == RayDistribution::Uniform, - ignore_backface: occlusion && s.ao_ignore_backface, - same_key: occlusion && s.ao_self_occlusion == SelfOcclusion::SameMeshName, - }) - }; - Ok(Ctx { - low, - high, - cage: req.cage, - skew, - ray_normals, - lo, - extent: hi - lo, - eps, - frontal: s.max_frontal * diag, - rear: s.max_rear * diag, - by_name: s.matching == BakeMatch::ByMeshName, - direction: Vec3::from(s.direction).try_normalize().unwrap_or(Vec3::Y), - direction_mode: s.direction_mode, - position_mode: s.position_mode, - curvature_from_normal: s.curvature_from_normal, - curvature: Curvature::new(s, req.mesh, diag, req.tiles), - ao: pass(BakedMap::AmbientOcclusion, &s.ao, RayKind::Occlusion), - bent: pass(BakedMap::BentNormal, &s.bent_normal, RayKind::Occlusion), - thickness: pass(BakedMap::Thickness, &s.thickness, RayKind::Thickness), - }) - } - - pub(crate) fn has_high(&self) -> bool { - self.high.is_some() - } - - /// Whether the bake casts any ray. - pub(crate) fn casts_rays(&self) -> bool { - self.has_high() || self.curvature.on || self.ao.is_some() || self.bent.is_some() || self.thickness.is_some() - } - - /// The meshes rays are cast against: the low poly, then the high poly. - pub(crate) fn trace_meshes(&self) -> Vec> { - std::iter::once(&self.low).chain(&self.high).map(Source::trace).collect() - } - - /// The transfer ray of a low-poly sample: from the cage (or `frontal` in front of the low - /// poly) back through it to `rear` behind, onto the matching high-poly part; and the - /// origin's distance in front of the low poly. Parts without a key cast nothing when - /// matched by name. - pub(crate) fn transfer_ray(&self, s: &Surface, bary: [f32; 2]) -> (Ray, f32) { - let n = interpolate(self.low.mesh, &self.ray_normals, s.tri, bary).and_then(Vec3::try_normalize).unwrap_or(s.nrm); - let cage = self.cage.and_then(|c| interpolate(c, &c.positions, s.tri, bary)).map(|c| s.pos - c).filter(|v| v.length() > self.eps); - let (origin, dir, front) = match cage { - Some(v) => (s.pos - v, v.normalize(), v.length()), - None => { - // Skew correction turns the averaged direction towards the base normal. - let up = match &self.skew { - Some(k) => k.correct(self.low.mesh, s, n), - None => n, - }; - (s.pos + up * self.frontal, -up, self.frontal) - } - }; - let key = if self.by_name { self.low.key.get(s.tri as usize).copied().unwrap_or(ANY) } else { ANY }; - let tmax = if self.by_name && key == ANY { 0.0 } else { front + self.rear }; - (Ray { origin, dir, tmax, key }, front) - } - - /// The high-poly surface a transfer ray hit. - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { - let (high, hit) = (self.high.as_ref()?, hit?); - let surf = surface_at(high.mesh, hit.tri, hit.u, hit.v)?; - Some(Transfer { surf, bary: [hit.u, hit.v], t: hit.t, front }) - } - - /// The secondary-ray query of a sample: on the high poly where the transfer found it. - pub(crate) fn query(&self, transfer: Option<&Transfer>, s: &Surface, seed: u64) -> Query { - let (src, surf, mesh) = match (&self.high, transfer) { - (Some(h), Some(tr)) => (h, &tr.surf, 1), - _ => (&self.low, s, 0), - }; - let h = splitmix64(seed); - let rot = [(h >> 40) as f32 / (1u64 << 24) as f32, ((h >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32]; - // The geometric normal on the side of the shading normal. - let geo = if surf.geo_nrm.dot(surf.nrm) < 0.0 { -surf.geo_nrm } else { surf.geo_nrm }; - Query { pos: surf.pos, nrm: surf.nrm, geo, rot, key: src.key.get(surf.tri as usize).copied().unwrap_or(ANY), mesh } - } - - /// Whether this bake traces curvature rays. - pub(crate) fn traces_curvature(&self) -> bool { - self.curvature.on - } - - /// Curvature of every sample: `(low poly surface, transfer)`. Rays go in batches per mesh, the - /// ground checks in a second pass. - pub(crate) fn trace_curvature(&self, scene: &mut dyn RayScene, samples: &[(&Surface, Option<&Transfer>)]) -> Result, BakeError> { - let mut out = vec![0.5; samples.len()]; - let c = &self.curvature; - for mesh in [0usize, 1] { - let Some(src) = (if mesh == 0 { Some(&self.low) } else { self.high.as_ref() }) else { continue }; - let tuning = if mesh == 0 { &c.low } else { &c.high }; - // Matched by name, a high poly part only reads itself, like its transfer rays. - let key = |surf: &Surface| if mesh == 1 && self.by_name { src.key.get(surf.tri as usize).copied().unwrap_or(ANY) } else { ANY }; - let chosen: Vec<(usize, &Surface, f32)> = samples - .par_iter() - .enumerate() - .filter_map(|(k, (s, tr))| { - let surf = match (mesh, tr) { - (1, Some(t)) => &t.surf, - (0, None) => *s, - _ => return None, - }; - Some((k, surf, c.texel(s.tri))) - }) - .collect(); - let per = CURVATURE_RINGS * CURVATURE_RAYS; - // A batch can hold whole rows of a big supersampled map: cast them in chunks. - for chunk in chosen.chunks(CURVATURE_CHUNK) { - let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * per); - rays.par_chunks_mut(per).zip(chunk).for_each(|(out, (_, surf, texel))| c.rays(tuning, surf, *texel, key(surf), out)); - let hits = scene.closest(mesh, &rays)?; - let walls = |i: usize| hits.get(i * per..i * per + CURVATURE_RAYS).unwrap_or_default(); - let grounds: Vec = chunk - .par_iter() - .enumerate() - .flat_map_iter(|(i, (_, surf, texel))| { - let mut v = Vec::new(); - c.ground_rays(surf, *texel, key(surf), walls(i), &mut v); - v - }) - .collect(); - let ground_hits = scene.closest(mesh, &grounds)?; - // Each sample's share of the ground checks. - let firsts: Vec = (0..chunk.len()) - .scan(0, |first, i| { - let at = *first; - *first += walls(i).iter().flatten().count(); - Some(at) - }) - .collect(); - let values: Vec<(usize, f32)> = chunk - .par_iter() - .zip(&firsts) - .enumerate() - .map(|(i, ((k, surf, texel), first))| { - let n = walls(i).iter().flatten().count(); - let g = ground_hits.get(*first..*first + n).unwrap_or_default(); - let h = hits.get(i * per..(i + 1) * per).unwrap_or_default(); - (*k, c.value(tuning, src, surf, *texel, h, g)) - }) - .collect(); - for (k, v) in values { - if let Some(o) = out.get_mut(k) { - *o = v; - } - } - } - } - Ok(out) - } - - /// Every map of `maps` at one low-poly sample, into `out` (scalars fill all three). - pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], transfer: Option<&Transfer>, traced: &Traced, out: &mut [[f32; 3]]) { - // The surface the bakers read: the high poly where a ray found it, else the low poly. - let (src, surf, sb) = match (&self.high, transfer) { - (Some(h), Some(tr)) => (h, &tr.surf, tr.bary), - _ => (&self.low, s, bary), - }; - let missed = self.high.is_some() && transfer.is_none(); - for (&map, o) in maps.iter().zip(out.iter_mut()) { - *o = match map { - BakedMap::AmbientOcclusion => [traced.ao; 3], - BakedMap::BentNormal => pack(traced.bent.unwrap_or(surf.nrm)), - BakedMap::Thickness => [traced.thickness; 3], - BakedMap::Curvature if self.curvature_from_normal => [0.5; 3], - BakedMap::Curvature => [traced.curvature; 3], - BakedMap::WorldNormal => pack(surf.nrm), - BakedMap::Position => self.position(surf.pos), - BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize), - BakedMap::Normal => transfer.map_or(map.neutral(), |tr| tangent_normal(s, tr.surf.nrm)), - BakedMap::Height => [transfer.map_or(0.5, |tr| (0.5 + (tr.front - tr.t) / (tr.front + self.rear)).clamp(0.0, 1.0)); 3], - BakedMap::Opacity if missed => [0.0; 3], - BakedMap::Opacity => [src.color(surf, sb).w; 3], - BakedMap::ColorMap if missed => map.neutral(), - BakedMap::ColorMap => src.color(surf, sb).truncate().to_array(), - BakedMap::WorldDirection => { - let f = surf.nrm.dot(self.direction); - [match self.direction_mode { - DirectionMode::Signed => f * 0.5 + 0.5, - DirectionMode::Positive => f.clamp(0.0, 1.0), - }; 3] - } - }; - } - } - - /// `p` normalized to 0..1 over the low poly's bounding box or bounding sphere. - fn position(&self, p: Vec3) -> [f32; 3] { - let v = match self.position_mode { - PositionMode::BoundingBox => (p - self.lo) / self.extent.max(Vec3::splat(1e-20)), - PositionMode::BoundingSphere => (p - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5, - }; - v.clamp(Vec3::ZERO, Vec3::ONE).to_array() - } -} - -/// A unit vector packed to 0..1. -fn pack(v: Vec3) -> [f32; 3] { - (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array() -} - -/// `n` in the tangent space of low-poly sample `s` (OpenGL: +Y up the image), packed to 0..1. -fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] { - let z = s.nrm; - let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector()); - let b = z.cross(t) * s.tangent.w; - pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n))) -} - -/// Curvature from a baked tangent-space normal map: the divergence of its XY over `radius` -/// texels (convex = above 0.5; 0: one texel per 512 of a UV tile's resolution). Writes covered -/// texels of `out` (one float per texel). `res` is the image width. -pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], res: usize, tile_res: usize, radius: u32, strength: f32, out: &mut [f32]) { - use rayon::prelude::*; - let r = if radius > 0 { radius as usize } else { (tile_res / 512).max(1) }; - let n = |x: usize, y: usize, c: usize, fallback: f32| match covered.get(y * res + x) { - Some(true) => normal.get((y * res + x) * 3 + c).copied().unwrap_or(fallback), - _ => fallback, - }; - out.par_chunks_mut(res).enumerate().for_each(|(y, row)| { - for (x, v) in row.iter_mut().enumerate() { - if covered.get(y * res + x) != Some(&true) { - continue; - } - let (cx, cy) = (n(x, y, 0, 0.5), n(x, y, 1, 0.5)); - let (l, r_) = (n(x.saturating_sub(r), y, 0, cx), if x + r < res { n(x + r, y, 0, cx) } else { cx }); - let (u, d) = (n(x, y.saturating_sub(r), 1, cy), if y + r < res { n(x, y + r, 1, cy) } else { cy }); - // Image rows run down while +Y (OpenGL) points up: convex bumps tilt +Y above. - *v = (0.5 + strength * ((r_ - l) + (u - d))).clamp(0.0, 1.0); - } - }); -} - -/// Position-welded copy of `mesh` (UV seams and hard edges share neighbours): the weld id of -/// every vertex, welded positions and their averaged normals. -fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh - .positions - .iter() - .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 - }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; - } - id - }) - .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) -} - -/// A well-separated hue per part (golden-ratio steps around the HSV wheel). -fn material_color(part: usize) -> [f32; 3] { - let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; - let (s, v) = (0.7f32, 0.95f32); - let f = h.fract(); - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - match h as u32 { - 0 => [v, t, p], - 1 => [q, v, p], - 2 => [p, v, t], - 3 => [p, q, v], - 4 => [t, p, v], - _ => [v, p, q], - } -} - -fn splitmix64(x: u64) -> u64 { - let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15); - z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - z ^ (z >> 31) -} diff --git a/crates/bake/src/progress.rs b/crates/bake/src/progress.rs new file mode 100644 index 00000000..5bb924ec --- /dev/null +++ b/crates/bake/src/progress.rs @@ -0,0 +1,22 @@ +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed}; + +#[derive(Debug, Default)] +pub struct Progress { + /// Completed basis points, from 0 to 10,000 + pub done: AtomicU32, + pub cancel: AtomicBool, +} + +impl Progress { + pub fn new() -> Self { + Self::default() + } + + pub fn fraction(&self) -> f32 { + self.done.load(Relaxed).min(10_000) as f32 / 10_000.0 + } + + pub fn cancel(&self) { + self.cancel.store(true, Relaxed); + } +} diff --git a/crates/bake/src/rays.rs b/crates/bake/src/rays.rs deleted file mode 100644 index 5438e89b..00000000 --- a/crates/bake/src/rays.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! The ray casts of a bake, in batches. [`CpuTracer`] is the oracle; a GPU [`Tracer`] (the -//! render crate's compute baker) must give the same results: it receives the same rays and -//! queries, and generates the same secondary-ray directions from each query's rotation. - -use std::f32::consts::TAU; - -use rayon::prelude::*; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Bvh, Hit, Mesh}; - -use crate::BakeError; - -/// A ray or query key that matches every triangle (no part filter). -pub const ANY: u32 = u32::MAX; - -/// A mesh rays are cast against: [`RayScene`] mesh 0 is the low poly, mesh 1 the high poly. -#[derive(Clone, Copy, Debug)] -pub struct TraceMesh<'a> { - pub mesh: &'a Mesh, - pub bvh: &'a Bvh, - /// Part key of every triangle (original order); triangles of no part hold [`ANY`]. - pub keys: &'a [u32], -} - -impl TraceMesh<'_> { - fn key_matches(&self, tri: u32, key: u32) -> bool { - key == ANY || self.keys.get(tri as usize) == Some(&key) - } - - /// Whether `d` meets triangle `tri` from behind (against its winding's normal). - fn back_facing(&self, tri: u32, d: Vec3) -> bool { - let p = |i: usize| self.mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); - self.mesh.tri(tri as usize).is_some_and(|[a, b, c]| (p(b) - p(a)).cross(p(c) - p(a)).dot(d) > 0.0) - } -} - -/// A closest-hit ray. Laid out as the GPU reads it, so a batch uploads without a copy. -#[repr(C)] -#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] -pub struct Ray { - pub origin: Vec3, - pub tmax: f32, - pub dir: Vec3, - /// Only triangles with this part key are hit ([`ANY`]: all). - pub key: u32, -} - -/// One sample's secondary rays (ambient occlusion, bent normal or thickness). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Query { - pub pos: Vec3, - /// Shading normal: the axis of the ray cone. - pub nrm: Vec3, - /// Geometric normal on the shading normal's side: rays below its plane are skipped. - pub geo: Vec3, - /// Cranley–Patterson rotation of the sample's ray set. - pub rot: [f32; 2], - /// Part key of the sample's triangle (for [`Hemisphere::same_key`]). - pub key: u32, - /// Scene mesh the rays are cast against. - pub mesh: u32, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum RayKind { - /// Out of the surface: ambient occlusion and the bent normal. - Occlusion, - /// Into the surface: the distance through the mesh. - Thickness, -} - -/// Parameters of one pass of secondary rays (distances absolute). -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Hemisphere { - pub kind: RayKind, - pub rays: u32, - pub dmax: f32, - /// Ray start offset along the geometric normal. - pub eps: f32, - /// Cosine and sine of the cone's half angle. - pub cos_max: f32, - pub sin_max: f32, - /// Uniform over the cone's solid angle (else cosine-weighted). - pub uniform: bool, - pub ignore_backface: bool, - /// Only triangles with the query's part key occlude. - pub same_key: bool, -} - -impl Hemisphere { - /// Direction `i` of a query's ray set around `axis` (basis `t`, `b`): Hammersley points - /// rotated by `rot`, mapped onto the cone. - pub fn direction(&self, (t, b, axis): (Vec3, Vec3, Vec3), i: u32, rot: [f32; 2]) -> Vec3 { - let u1 = (i as f32 / self.rays as f32 + rot[0]).fract(); - let u2 = (i.reverse_bits() as f32 / 4_294_967_296.0 + rot[1]).fract(); - let (r, z) = if self.uniform { - let z = 1.0 - u2 * (1.0 - self.cos_max); - ((1.0 - z * z).max(0.0).sqrt(), z) - } else { - let r = self.sin_max * u2.sqrt(); - (r, (1.0 - r * r).max(0.0).sqrt()) - }; - let phi = TAU * u1; - t * (r * phi.cos()) + b * (r * phi.sin()) + axis * z - } - - /// The axis, geometric normal and ray origin of `q` for this kind of rays. - fn frame(&self, q: &Query) -> (Vec3, Vec3, Vec3) { - let (axis, geo) = match self.kind { - RayKind::Occlusion => (q.nrm, q.geo), - RayKind::Thickness => (-q.nrm, -q.geo), - }; - (axis, geo, q.pos + geo * self.eps) - } - - /// `q`'s result on `m`: occlusion gives (ambient occlusion, bent normal), thickness gives - /// (thickness, 0, 0, 0); both relative and in 0..1 (1 = open / thick). - pub fn evaluate(&self, m: &TraceMesh, q: &Query) -> [f32; 4] { - let (axis, geo, o) = self.frame(q); - let (t, b) = axis.any_orthonormal_pair(); - let key = if self.same_key && self.kind == RayKind::Occlusion { q.key } else { ANY }; - let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion); - let (mut sum, mut bent, mut n) = (0.0f32, Vec3::ZERO, 0u32); - for i in 0..self.rays { - let d = self.direction((t, b, axis), i, q.rot); - if d.dot(geo) <= 0.0 { - continue; - } - let hit = match filtered { - true => m.bvh.closest_filtered(o, d, self.dmax, &|tri| m.key_matches(tri, key) && !(self.ignore_backface && m.back_facing(tri, d))), - false => m.bvh.closest(o, d, self.dmax), - }; - match self.kind { - RayKind::Occlusion => { - let v = hit.map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2)); - sum += v; - bent += d * (1.0 - v); - } - RayKind::Thickness => sum += hit.map_or(self.dmax, |h| h.t), - } - n += 1; - } - match self.kind { - RayKind::Occlusion => { - let ao = if n == 0 { 1.0 } else { (1.0 - sum / n as f32).clamp(0.0, 1.0) }; - let bent = bent.try_normalize().unwrap_or(q.nrm); - [ao, bent.x, bent.y, bent.z] - } - RayKind::Thickness => [if n == 0 { 1.0 } else { (sum / n as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0], - } - } -} - -/// Ray casts on the meshes of one bake. -pub trait RayScene: Send { - /// The closest hit of every ray on scene mesh `mesh` (triangles of the ray's key). - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError>; - /// [`Hemisphere::evaluate`] of every query, for each pass. - fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>; -} - -/// Where ray casts run. -pub trait Tracer: Send + Sync { - /// Shown in logs and command results ("CPU", the GPU's name). - fn name(&self) -> String; - /// Prepare `meshes` (low poly, then the high poly if any) for ray casts. - fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>; -} - -/// Ray casts on the CPU (rayon over the batch). -#[derive(Clone, Copy, Debug, Default)] -pub struct CpuTracer; - -struct CpuScene<'a>(Vec>); - -impl CpuScene<'_> { - fn mesh(&self, i: usize) -> Result<&TraceMesh<'_>, BakeError> { - self.0.get(i).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {i}"))) - } -} - -impl RayScene for CpuScene<'_> { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { - let m = self.mesh(mesh)?; - Ok(rays - .par_iter() - .map(|r| match r.key { - ANY => m.bvh.closest(r.origin, r.dir, r.tmax), - key => m.bvh.closest_filtered(r.origin, r.dir, r.tmax, &|t| m.key_matches(t, key)), - }) - .collect()) - } - - fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { - passes.iter().map(|h| queries.par_iter().map(|q| Ok(h.evaluate(self.mesh(q.mesh as usize)?, q))).collect()).collect() - } -} - -impl Tracer for CpuTracer { - fn name(&self) -> String { - "CPU".into() - } - - fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> { - Ok(Box::new(CpuScene(meshes.to_vec()))) - } -} diff --git a/crates/bake/src/skew.rs b/crates/bake/src/skew.rs index 28cd4c92..780c396d 100644 --- a/crates/bake/src/skew.rs +++ b/crates/bake/src/skew.rs @@ -1,261 +1,19 @@ -//! Skew correction: a greyscale map over the UV atlas that turns the transfer rays of a -//! high-poly bake from the averaged cage direction towards the low poly's own normal. Where the -//! averaged direction leans away from a surface (the classic "skewed" details on a bevelled -//! edge or a cylinder's cap), painting the map white there sends the rays straight along the -//! surface normal instead, and grey values blend the two. -//! -//! Ported from SurfaceCraft's baker (`crates/bake`, MIT OR Apache-2.0), adapted to this crate's -//! [`crate::maps::Ctx`] rays. Like the averaged cage it only changes rays that start from the -//! built-in distance cage: a custom cage mesh sets its own directions and ignores the map. +//! Skew correction adapted from SurfaceCraft's baker (MIT OR Apache-2.0) -use std::collections::HashMap; +mod prepared_skew; +mod skew_map; -use texturecraft_geom::glam::{Vec2, Vec3}; -use texturecraft_geom::{Mesh, Surface}; - -use crate::{BakeError, MAX_TEXELS}; - -/// Most dabs one [`SkewMap::paint`] call places. -pub const MAX_DABS: usize = 200_000; - -/// Most texels one [`SkewMap::paint`] call may visit, summed over its dabs (about 70 ms of work): -/// a big brush on a big map costs per dab what a whole-map pass costs, so dabs alone don't bound it. -pub const MAX_PAINT_TEXELS: u64 = 1 << 26; - -/// Edges steeper than this cosine between two faces count as hard (about 30 degrees). -const HARD_EDGE_COS: f32 = 0.866; - -/// A skew map over the whole UV atlas. -#[derive(Clone, Debug, PartialEq)] -pub struct SkewMap { - pub width: u32, - pub height: u32, - /// `width * height` values in 0..=1, row 0 at the top (v = 1): 0 keeps a ray on the cage's - /// averaged direction, 1 turns it fully onto the base normal. - pub values: Vec, - /// Edge protection: the correction fades out within this fraction of the mesh diagonal of a - /// hard edge (0: off). - pub edge_distance: f32, - /// Edge protection's falloff exponent: 1 is linear, more holds the correction back longer. - pub edge_contrast: f32, - /// Correct towards each triangle's flat normal instead of the interpolated vertex normal. - pub per_triangle: bool, -} - -impl SkewMap { - /// A map of one value everywhere. - pub fn constant(value: f32) -> SkewMap { - SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false } - } - - /// Refuses maps whose size doesn't match their values, non-finite numbers and absurd sizes. - pub fn validate(&self) -> Result<(), BakeError> { - let invalid = |m: &str| Err(BakeError::Invalid(m.into())); - let texels = u64::from(self.width) * u64::from(self.height); - if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels { - return invalid("the skew map's size doesn't match its values"); - } - if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) { - return invalid("the skew edge distance must be 0 or more and the contrast above 0"); - } - if self.values.iter().any(|v| !v.is_finite()) { - return invalid("the skew map has a value that is not a finite number"); - } - Ok(()) - } - - /// The map resampled (bilinear) to `width` × `height`; the other settings carry over. - pub fn resized(&self, width: u32, height: u32) -> Result { - let texels = u64::from(width) * u64::from(height); - if width == 0 || height == 0 || texels > MAX_TEXELS { - return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size"))); - } - let mut values = Vec::with_capacity(texels as usize); - for y in 0..height { - let v = 1.0 - (y as f32 + 0.5) / height as f32; - for x in 0..width { - values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v))); - } - } - Ok(SkewMap { width, height, values, ..self.clone() }) - } - - /// Paint round dabs along `points` (atlas uv): `value` is blended in with `strength` (0..=1), - /// fully inside `hardness` (0..=1) of `radius` (in uv units) and fading to nothing at the rim. - /// Dabs are placed a quarter radius apart along each segment; `MAX_DABS` bounds one call. - pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> { - let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite(); - if !ok || points.iter().any(|p| !p.is_finite()) { - return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into())); - } - self.validate()?; - let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0)); - let step = (radius * 0.25).max(1e-5); - let mut dabs = Vec::new(); - for (i, p) in points.iter().enumerate() { - match i.checked_sub(1).and_then(|j| points.get(j)) { - Some(prev) => { - let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize; - dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32))); - } - None => dabs.push(*p), - } - if dabs.len() > MAX_DABS { - return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); - } - } - let (w, h) = (self.width as usize, self.height as usize); - // The texel box of a dab, row 0 at the top (v = 1). - let span = |c: Vec2| { - let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize; - let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize; - let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize; - let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; - (x0, x1, y0, y1) - }; - // Refuse a stroke that would take too long before the first texel changes. - let work: u64 = dabs - .iter() - .map(|c| { - let (x0, x1, y0, y1) = span(*c); - x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64 - }) - .fold(0, u64::saturating_add); - if work > MAX_PAINT_TEXELS { - return Err(BakeError::Invalid(format!( - "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke" - ))); - } - for c in dabs { - let (x0, x1, y0, y1) = span(c); - for y in y0..y1 { - let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y; - for x in x0..x1 { - let du = (x as f32 + 0.5) / w as f32 - c.x; - let t = (du * du + dv * dv).sqrt() / radius; - if t >= 1.0 { - continue; - } - let fall = if t <= hardness { - 1.0 - } else { - let k = (1.0 - t) / (1.0 - hardness); - k * k * (3.0 - 2.0 * k) - }; - if let Some(v) = self.values.get_mut(y * w + x) { - *v += (value - *v) * fall * strength; - } - } - } - } - Ok(()) - } - - /// The map at atlas `uv`: bilinear, edges clamped. - pub(crate) fn at(&self, uv: Vec2) -> f32 { - let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize); - if !uv.is_finite() { - return 0.0; - } - let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0); - let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); - let (x0, y0) = (x.floor() as usize, y.floor() as usize); - let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); - let (fx, fy) = (x - x0 as f32, y - y0 as f32); - let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0); - let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx; - let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx; - (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0) - } -} - -/// A skew map ready for a bake: the map plus what edge protection needs. -pub(crate) struct Prepared<'a> { - map: &'a SkewMap, - /// Per triangle, which of its edges (v0-v1, v1-v2, v2-v0) are hard; only with edge protection. - hard: Vec<[bool; 3]>, - diag: f32, -} - -impl<'a> Prepared<'a> { - pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, diag: f32) -> Result, BakeError> { - map.validate()?; - let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; - Ok(Prepared { map, hard, diag }) - } - - /// The ray direction `up` (unit, away from the surface) at the low-poly sample `s` turned - /// towards its base normal: the interpolated vertex normal, or the flat one per triangle. - pub(crate) fn correct(&self, mesh: &Mesh, s: &Surface, up: Vec3) -> Vec3 { - let amount = self.map.at(s.uv); - if amount <= 0.0 { - return up; - } - let protect = match (self.hard.get(s.tri as usize), mesh.tri(s.tri as usize)) { - (Some(edges), Some(c)) => { - let near = (0..3) - .filter(|&k| edges[k]) - .filter_map(|k| { - let a = mesh.positions.get(*c.get(k)?)?; - let b = mesh.positions.get(*c.get((k + 1) % 3)?)?; - Some(segment_distance(s.pos, *a, *b)) - }) - .fold(f32::INFINITY, f32::min); - (near / (self.map.edge_distance * self.diag).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast) - } - _ => 1.0, - }; - let base = if self.map.per_triangle { s.geo_nrm } else { s.nrm }; - let t = amount * protect; - (up * (1.0 - t) + base * t).try_normalize().unwrap_or(up) - } -} - -/// Per triangle, which edges are hard: shared with a triangle whose face normal is more than -/// about 30 degrees away. Edges are matched by position, so split vertices still pair up. -fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> { - let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); - let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits())); - let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) }; - let count = mesh.triangle_count(); - let mut face = vec![Vec3::ZERO; count]; - let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new(); - for (t, f) in face.iter_mut().enumerate() { - let Some(c) = mesh.tri(t) else { continue }; - *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO); - for k in 0..3 { - edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t); - } - } - (0..count) - .map(|t| { - let mut out = [false; 3]; - if let Some(c) = mesh.tri(t) { - let own = face.get(t).copied().unwrap_or(Vec3::ZERO); - for (k, hard) in out.iter_mut().enumerate() { - let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3]))); - *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS))); - } - } - out - }) - .collect() -} - -/// Distance from `p` to the segment `a`-`b`. -fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 { - let ab = b - a; - let len2 = ab.length_squared(); - let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; - (p - (a + ab * t)).length() -} +pub(crate) use prepared_skew::PreparedSkew; +pub use skew_map::SkewMap; #[cfg(test)] mod tests { + use super::prepared_skew::{hard_edges, segment_distance}; use super::*; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::{Mesh, Surface}; fn fold() -> Mesh { - // Two triangles folded 90 degrees along (0,0,0)-(1,0,0), and a third continuing flat. Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::Z, Vec3::new(1.0, 1.0, 0.0)], indices: vec![0, 1, 2, 0, 3, 1, 1, 4, 2], ..Mesh::default() } } @@ -295,13 +53,12 @@ mod tests { let base = Vec3::Y; let go = |map: &SkewMap, pos: Vec3| { let s = Surface { pos, nrm: base, geo_nrm: base, tangent: Default::default(), uv: Vec2::splat(0.5), tri: 0 }; - Prepared::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up) + PreparedSkew::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up) }; assert!((go(&SkewMap::constant(0.0), Vec3::ZERO) - up).length() < 1e-6, "black leaves the ray alone"); assert!((go(&SkewMap::constant(1.0), Vec3::ZERO) - base).length() < 1e-6, "white turns it onto the base normal"); let half = go(&SkewMap::constant(0.5), Vec3::ZERO); assert!(half.x > 0.0 && half.x < up.x && (half.length() - 1.0).abs() < 1e-5, "grey is in between and still unit: {half}"); - // Triangle 0's edge (0,0,0)-(1,0,0) is hard: on it the correction is held back, far from it it is not. let guarded = SkewMap { edge_distance: 0.5, ..SkewMap::constant(1.0) }; assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0)) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction"); assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0)) - base).length() < 1e-6, "away from every hard edge the correction is full"); @@ -311,11 +68,9 @@ mod tests { fn painting_blends_dabs_in_and_resizing_keeps_the_picture() { let mut map = SkewMap::constant(0.0).resized(64, 64).unwrap(); assert!(map.values.iter().all(|v| *v == 0.0)); - // One hard dab at the centre: white inside, untouched outside, in between at the rim. map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 1.0, 1.0, 1.0).unwrap(); let at = |m: &SkewMap, u: f32, v: f32| m.at(Vec2::new(u, v)); assert!(at(&map, 0.5, 0.5) > 0.99 && at(&map, 0.95, 0.95) == 0.0, "{} {}", at(&map, 0.5, 0.5), at(&map, 0.95, 0.95)); - // Strength blends one dab in part of the way; a stroke's overlapping dabs build up towards the value; v is up. let mut dab = SkewMap::constant(0.0).resized(64, 64).unwrap(); dab.paint(&[Vec2::new(0.5, 0.5)], 0.1, 0.8, 1.0, 0.5).unwrap(); assert!((at(&dab, 0.5, 0.5) - 0.4).abs() < 0.02, "{}", at(&dab, 0.5, 0.5)); @@ -323,10 +78,8 @@ mod tests { line.paint(&[Vec2::new(0.1, 0.9), Vec2::new(0.9, 0.9)], 0.05, 0.5, 1.0, 0.5).unwrap(); assert!(at(&line, 0.5, 0.9) > 0.45 && at(&line, 0.5, 0.9) <= 0.5 + 1e-4, "{}", at(&line, 0.5, 0.9)); assert!(at(&line, 0.5, 0.1) == 0.0, "the other end of v is untouched"); - // Erasing (value 0) brings a painted area back down. map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 0.0, 1.0, 1.0).unwrap(); assert!(at(&map, 0.5, 0.5) < 0.01); - // Resampling keeps the picture and the edge settings. let mut small = SkewMap { edge_distance: 0.1, ..SkewMap::constant(0.0).resized(8, 8).unwrap() }; small.paint(&[Vec2::new(0.25, 0.75)], 0.2, 1.0, 1.0, 1.0).unwrap(); let big = small.resized(32, 32).unwrap(); @@ -344,12 +97,10 @@ mod tests { { assert!(map.paint(pts, r, v, 0.5, 1.0).is_err(), "{pts:?} {r} {v}"); } - // Points far outside the atlas are harmless; a huge stroke is refused before any dab lands. map.paint(&[Vec2::new(1e6, -1e6)], 0.1, 1.0, 0.5, 1.0).unwrap(); assert_eq!(map, before); assert!(map.paint(&[Vec2::ZERO, Vec2::new(1e6, 1e6)], 1e-4, 1.0, 0.5, 1.0).is_err()); assert_eq!(map, before); - // A big brush over a big map is refused up front, whatever the dab count: one dab here covers 16.7 M texels. let mut big = SkewMap::constant(0.0).resized(4096, 4096).unwrap(); let untouched = big.clone(); assert!(big.paint(&[Vec2::splat(0.5); 8], 1.0, 1.0, 0.5, 1.0).is_err()); diff --git a/crates/bake/src/skew/prepared_skew.rs b/crates/bake/src/skew/prepared_skew.rs new file mode 100644 index 00000000..b287c2d3 --- /dev/null +++ b/crates/bake/src/skew/prepared_skew.rs @@ -0,0 +1,81 @@ +use super::SkewMap; +use crate::BakeError; +use std::collections::HashMap; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +const HARD_EDGE_COS: f32 = 0.866; + +pub(crate) struct PreparedSkew<'a> { + map: &'a SkewMap, + hard: Vec<[bool; 3]>, + mesh_diagonal: f32, +} + +impl<'a> PreparedSkew<'a> { + pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, mesh_diagonal: f32) -> Result, BakeError> { + map.validate()?; + let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; + Ok(PreparedSkew { map, hard, mesh_diagonal }) + } + + pub(crate) fn correct(&self, mesh: &Mesh, surface: &Surface, up: Vec3) -> Vec3 { + let amount = self.map.at(surface.uv); + if amount <= 0.0 { + return up; + } + let protection = match (self.hard.get(surface.tri as usize), mesh.tri(surface.tri as usize)) { + (Some(edges), Some(corners)) => { + let nearest_edge_distance = (0..3) + .filter(|&edge_index| edges[edge_index]) + .filter_map(|edge_index| { + let edge_start = mesh.positions.get(*corners.get(edge_index)?)?; + let edge_end = mesh.positions.get(*corners.get((edge_index + 1) % 3)?)?; + Some(segment_distance(surface.pos, *edge_start, *edge_end)) + }) + .fold(f32::INFINITY, f32::min); + (nearest_edge_distance / (self.map.edge_distance * self.mesh_diagonal).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast) + } + _ => 1.0, + }; + let base = surface.nrm; + let blend = amount * protection; + (up * (1.0 - blend) + base * blend).try_normalize().unwrap_or(up) + } +} + +pub(super) fn hard_edges(mesh: &Mesh) -> Vec<[bool; 3]> { + let pt = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); + let key = |i: usize| mesh.positions.get(i).map_or([0; 3], |p| p.to_array().map(|c| (c + 0.0).to_bits())); + let ordered = |a: [u32; 3], b: [u32; 3]| if a <= b { (a, b) } else { (b, a) }; + let count = mesh.triangle_count(); + let mut face = vec![Vec3::ZERO; count]; + let mut edges: HashMap<([u32; 3], [u32; 3]), Vec> = HashMap::new(); + for (t, f) in face.iter_mut().enumerate() { + let Some(c) = mesh.tri(t) else { continue }; + *f = (pt(c[1]) - pt(c[0])).cross(pt(c[2]) - pt(c[0])).try_normalize().unwrap_or(Vec3::ZERO); + for k in 0..3 { + edges.entry(ordered(key(c[k]), key(c[(k + 1) % 3]))).or_default().push(t); + } + } + (0..count) + .map(|t| { + let mut out = [false; 3]; + if let Some(c) = mesh.tri(t) { + let own = face.get(t).copied().unwrap_or(Vec3::ZERO); + for (k, hard) in out.iter_mut().enumerate() { + let others = edges.get(&ordered(key(c[k]), key(c[(k + 1) % 3]))); + *hard = others.is_some_and(|ts| ts.iter().any(|&o| o != t && face.get(o).is_some_and(|f| f.dot(own) < HARD_EDGE_COS))); + } + } + out + }) + .collect() +} + +pub(super) fn segment_distance(p: Vec3, a: Vec3, b: Vec3) -> f32 { + let ab = b - a; + let len2 = ab.length_squared(); + let t = if len2 > 1e-20 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + (p - (a + ab * t)).length() +} diff --git a/crates/bake/src/skew/skew_map.rs b/crates/bake/src/skew/skew_map.rs new file mode 100644 index 00000000..be6a7bcc --- /dev/null +++ b/crates/bake/src/skew/skew_map.rs @@ -0,0 +1,135 @@ +use crate::{BakeError, MAX_TEXELS}; +use texturecraft_geom::glam::Vec2; + +pub const MAX_DABS: usize = 200_000; + +// Bound total work across all dabs before changing any pixels +pub const MAX_PAINT_TEXELS: u64 = 1 << 26; + +#[derive(Clone, Debug, PartialEq)] +pub struct SkewMap { + pub width: u32, + pub height: u32, + /// Atlas values: 0 keeps the cage direction; 1 uses the base normal + pub values: Vec, + pub edge_distance: f32, + pub edge_contrast: f32, +} + +impl SkewMap { + pub fn constant(value: f32) -> SkewMap { + SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0 } + } + + pub fn validate(&self) -> Result<(), BakeError> { + let invalid = |m: &str| Err(BakeError::Invalid(m.into())); + let texels = u64::from(self.width) * u64::from(self.height); + if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels { + return invalid("the skew map's size doesn't match its values"); + } + if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) { + return invalid("the skew edge distance must be 0 or more and the contrast above 0"); + } + if self.values.iter().any(|v| !v.is_finite()) { + return invalid("the skew map has a value that is not a finite number"); + } + Ok(()) + } + + pub fn resized(&self, width: u32, height: u32) -> Result { + let texels = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || texels > MAX_TEXELS { + return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size"))); + } + let mut values = Vec::with_capacity(texels as usize); + for y in 0..height { + let v = 1.0 - (y as f32 + 0.5) / height as f32; + for x in 0..width { + values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v))); + } + } + Ok(SkewMap { width, height, values, ..self.clone() }) + } + + pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> { + let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite(); + if !ok || points.iter().any(|p| !p.is_finite()) { + return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into())); + } + self.validate()?; + let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0)); + let step = (radius * 0.25).max(1e-5); + let mut dabs = Vec::new(); + for (i, p) in points.iter().enumerate() { + match i.checked_sub(1).and_then(|j| points.get(j)) { + Some(prev) => { + let n = ((*p - *prev).length() / step).ceil().clamp(1.0, MAX_DABS as f32) as usize; + dabs.extend((1..=n).map(|k| *prev + (*p - *prev) * (k as f32 / n as f32))); + } + None => dabs.push(*p), + } + if dabs.len() > MAX_DABS { + return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); + } + } + let (w, h) = (self.width as usize, self.height as usize); + let span = |c: Vec2| { + let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize; + let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize; + let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize; + let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; + (x0, x1, y0, y1) + }; + let work: u64 = dabs + .iter() + .map(|c| { + let (x0, x1, y0, y1) = span(*c); + x1.saturating_sub(x0) as u64 * y1.saturating_sub(y0) as u64 + }) + .fold(0, u64::saturating_add); + if work > MAX_PAINT_TEXELS { + return Err(BakeError::Invalid(format!( + "this stroke would visit {work} texels (limit {MAX_PAINT_TEXELS}); use a smaller radius, a smaller map or a shorter stroke" + ))); + } + for c in dabs { + let (x0, x1, y0, y1) = span(c); + for y in y0..y1 { + let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y; + for x in x0..x1 { + let du = (x as f32 + 0.5) / w as f32 - c.x; + let t = (du * du + dv * dv).sqrt() / radius; + if t >= 1.0 { + continue; + } + let fall = if t <= hardness { + 1.0 + } else { + let k = (1.0 - t) / (1.0 - hardness); + k * k * (3.0 - 2.0 * k) + }; + if let Some(v) = self.values.get_mut(y * w + x) { + *v += (value - *v) * fall * strength; + } + } + } + } + Ok(()) + } + + pub(crate) fn at(&self, uv: Vec2) -> f32 { + let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize); + if !uv.is_finite() { + return 0.0; + } + let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0); + let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); + let (x0, y0) = (x.floor() as usize, y.floor() as usize); + let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); + let (fx, fy) = (x - x0 as f32, y - y0 as f32); + let v = |xx: usize, yy: usize| self.values.get(yy * w + xx).copied().unwrap_or(0.0); + let top = v(x0, y0) * (1.0 - fx) + v(x1, y0) * fx; + let bottom = v(x0, y1) * (1.0 - fx) + v(x1, y1) * fx; + (top * (1.0 - fy) + bottom * fy).clamp(0.0, 1.0) + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 9efa3733..2259aa95 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -1,18 +1,36 @@ +use std::sync::Arc; +use texturecraft_geom::{BaseColor, Bvh}; + +use texturecraft_core::{ + AmbientOcclusionSettings, BakeAntialiasing, BakeResolution, BakeSettings, BentNormalSettings, CageSettings, CommonBakeSettings, CurvatureSettings, + PositionSettings, +}; + use std::sync::atomic::Ordering::Relaxed; -use texturecraft_core::{BakeMatch, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_core::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; use texturecraft_geom::glam::{Vec2, Vec3, Vec4}; use texturecraft_geom::primitives; use super::*; -fn settings(res: u32, maps: &[BakedMap]) -> BakeSettings { - with_rays(BakeSettings { resolution: res, dilation: 0, maps: maps.iter().copied().collect(), ..BakeSettings::default() }, 64, 0.25) +fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { + with_rays( + { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::from_pixels(resolution).unwrap(), dilation: 0, ..base.common }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base.maps.position.parameters = PositionSettings { normalization: PositionMode::BoundingBox, ..base.maps.position.parameters }; + base.maps.select(maps.iter().copied()); + base + }, + 64, + 0.25, + ) } -/// `s` with every secondary-ray map at `rays` rays of length `max_distance`. fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings { - for r in [&mut s.ao, &mut s.thickness, &mut s.bent_normal] { + for r in [&mut s.maps.ao.parameters.rays, &mut s.maps.thickness.parameters.rays, &mut s.maps.bent_normal.parameters.rays] { *r = RaySettings { rays, max_distance, ..*r }; } s @@ -23,7 +41,6 @@ fn run(mesh: &Mesh, s: &BakeSettings) -> Result { bake(&BakeRequest { mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()) } -/// Values of `map` (first component) at texels the UV layout covers, with their surface positions. fn covered_values(mesh: &Mesh, out: &BakeOutput, map: BakedMap) -> Vec<(Vec3, f32)> { let res = out.resolution; let g = UvGBuffer::new(mesh, 0, res, res); @@ -66,7 +83,7 @@ fn inside_of_a_closed_box_is_occluded() { *n = -*n; } m.compute_tangents(); - let s = with_rays(settings(48, &[BakedMap::AmbientOcclusion]), 64, 4.0); + let s = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); let out = run(&m, &s).unwrap(); let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); assert!(ao < 0.3, "{ao}"); @@ -74,7 +91,7 @@ fn inside_of_a_closed_box_is_occluded() { #[test] fn thin_slab_is_thinner_than_a_block() { - let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(48, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1)); + let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(64, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1)); let slab = thick(&primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0)); let block = thick(&primitives::cube(2.0)); assert!(slab < 0.4 && block > 0.6, "slab {slab}, block {block}"); @@ -82,14 +99,12 @@ fn thin_slab_is_thinner_than_a_block() { #[test] fn sphere_curvature_stays_calm() { - // A smooth sphere has no edges to draw: a soft value, no lines, whatever the triangle size. for (rings, res) in [(64, 64), (12, 128)] { let m = primitives::sphere(1.0, rings * 2, rings); let s = settings(res, &[BakedMap::Curvature]); let out = run(&m, &s).unwrap(); let c: Vec = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect(); let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v))); - // Convex all over, so a little above grey is right; a line would be a jump between texels. assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.08, "{rings} rings: {lo}..{hi}"); } } @@ -111,7 +126,6 @@ fn contact_with_a_wall_is_a_dark_line_and_the_rest_stays_flat() { assert_eq!(floor_mean(&m, &s, BakedMap::Curvature, -0.9..0.5), 0.5); } -/// A box whose corners share one smooth normal per corner, each face in its own UV cell. fn smooth_shaded_box() -> Mesh { let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); let faces: [(Vec3, Vec3, Vec3); 6] = [ @@ -136,7 +150,6 @@ fn smooth_shaded_box() -> Mesh { Mesh::from_parts(pos, Some(nrm), uvs, idx, "Smooth box").unwrap() } -/// Largest distance from mid grey among samples within `band` of a box edge (half extent 1). fn edge_peak(m: &Mesh, res: u32, band: f32) -> f32 { let c = covered_values(m, &run(m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); c.iter().filter(|(p, _)| p.abs().to_array().iter().filter(|v| **v > 1.0 - band).count() >= 2).map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max) @@ -144,7 +157,6 @@ fn edge_peak(m: &Mesh, res: u32, band: f32) -> f32 { #[test] fn smooth_shaded_corners_draw_no_hard_line() { - // The same geometry: hard shading has a real edge, smooth shading has none to draw. let (hard, smooth) = (edge_peak(&primitives::cube(2.0), 256, 0.03), edge_peak(&smooth_shaded_box(), 256, 0.03)); assert!(hard > 0.05, "hard {hard}"); assert!(smooth < hard * 0.5, "smooth {smooth} hard {hard}"); @@ -152,7 +164,6 @@ fn smooth_shaded_corners_draw_no_hard_line() { #[test] fn lines_are_as_wide_in_texels_at_any_scale_of_the_part() { - // The radius follows the texels of the triangle: twice the map, half the world width. let width = |res: u32| { let m = primitives::cube(2.0); let c = covered_values(&m, &run(&m, &settings(res, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); @@ -169,7 +180,6 @@ fn lines_are_as_wide_in_texels_at_any_scale_of_the_part() { assert!(fine > 0.0 && (fine / coarse - 0.5).abs() < 0.2, "world widths {coarse} and {fine}"); } -/// A dense smooth cylinder along Y with UVs that unwrap its side. fn barrel(radius: f32) -> Mesh { const N: u32 = 128; let (mut pos, mut nrm, mut uvs, mut idx) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); @@ -191,7 +201,6 @@ fn barrel(radius: f32) -> Mesh { #[test] fn a_gently_round_barrel_stays_below_the_wear_masks() { - // Edge masks start around 0.6 with their noise: a plain round surface must stay well under them. let m = barrel(0.1); let c = covered_values(&m, &run(&m, &settings(512, &[BakedMap::Curvature])).unwrap(), BakedMap::Curvature); let (lo, hi) = c.iter().filter(|(p, _)| p.y.abs() < 0.9).fold((1.0f32, 0.0f32), |(lo, hi), (_, v)| (lo.min(*v), hi.max(*v))); @@ -212,21 +221,12 @@ fn a_rounded_bevel_reads_the_same_at_any_map_size() { assert!((coarse - fine).abs() < 0.1, "512: {coarse}, 1024: {fine}"); } -#[test] -fn curvature_strength_scales_the_result_and_zero_is_flat() { - let m = primitives::cube(2.0); - let peak = |strength: f32| { - let s = BakeSettings { curvature_strength: strength, ..settings(128, &[BakedMap::Curvature]) }; - covered_values(&m, &run(&m, &s).unwrap(), BakedMap::Curvature).iter().map(|(_, v)| (v - 0.5).abs()).fold(0.0, f32::max) - }; - assert_eq!(peak(0.0), 0.0); - assert!(peak(1.0) > peak(0.25)); -} - -/// Bevel / edge texels (two coordinates near the half extent) are convex-bright; face centres -/// stay mid-grey. fn check_box_curvature(m: &Mesh, edge: f32) { - let s = BakeSettings { dilation: 4, ..settings(128, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(128, &[BakedMap::Curvature]); + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let c = covered_values(m, &run(m, &s).unwrap(), BakedMap::Curvature); let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count(); let edges: Vec = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).collect(); @@ -250,13 +250,22 @@ fn cube_edges_are_convex() { #[test] fn two_runs_are_identical_and_sized() { let m = primitives::material_ball(); - let s = with_rays(BakeSettings { antialiasing: 2, dilation: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(40, &[]) }, 8, 0.25); + let s = with_rays( + { + let mut base = settings(32, &[]); + base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, dilation: 2, ..base.common }; + base.maps.select(BakedMap::ALL); + base + }, + 8, + 0.25, + ); let a = run(&m, &s).unwrap(); let b = run(&m, &s).unwrap(); assert_eq!(a, b); assert_eq!(a.maps.len(), BakedMap::ALL.len()); for (map, data) in &a.maps { - assert_eq!(data.len(), 40 * 40 * map.components(), "{map:?}"); + assert_eq!(data.len(), 32 * 32 * map.components(), "{map:?}"); assert!(data.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{map:?}"); } } @@ -265,10 +274,18 @@ fn two_runs_are_identical_and_sized() { fn strips_match_a_single_pass() { let m = primitives::material_ball(); let bvh = Bvh::new(&m); - let s = with_rays(BakeSettings { antialiasing: 2, maps: BakedMap::ALL.into_iter().collect(), ..settings(64, &[]) }, 4, 0.25); + let s = with_rays( + { + let mut base = settings(64, &[]); + base.common = CommonBakeSettings { antialiasing: BakeAntialiasing::Subsampling2x2, ..base.common }; + base.maps.select(BakedMap::ALL); + base + }, + 4, + 0.25, + ); let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; let whole = bake(&req, &Progress::new()).unwrap(); - // 128 × 2 supersampled texels per strip = 1 output row: 64 strips. let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; @@ -313,22 +330,59 @@ fn a_curvature_bake_can_be_cancelled_midway_and_reports_progress() { }); } +#[test] +fn hostile_tile_dimensions_are_rejected() { + let mesh = quad(); + let bvh = Bvh::new(&mesh); + let settings = settings(16, &[BakedMap::Position]); + + for tiles in [(1 << 31, 1 << 31), (u32::MAX, u32::MAX), (MAX_TEXELS as u32, 1), (0, 1), (1, 0)] { + let request = BakeRequest { mesh: &mesh, bvh: &bvh, material: 0, settings: &settings, high: None, cage: None, skew: None, tiles }; + + assert!(matches!(validate(&request), Err(BakeError::Invalid(_))), "{tiles:?}"); + assert!(matches!(bake(&request, &Progress::new()), Err(BakeError::Invalid(_))), "{tiles:?}"); + } +} + #[test] fn invalid_requests_are_errors() { let m = quad(); - let ok = settings(8, &[BakedMap::AmbientOcclusion]); + let ok = settings(16, &[BakedMap::AmbientOcclusion]); let bad = [ - BakeSettings { resolution: 0, ..ok.clone() }, - BakeSettings { resolution: 8193, ..ok.clone() }, - BakeSettings { antialiasing: 3, ..ok.clone() }, - BakeSettings { antialiasing: 0, ..ok.clone() }, - BakeSettings { ao: RaySettings { rays: 0, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { rays: MAX_RAYS + 1, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { max_distance: f32::NAN, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { max_distance: 0.0, ..ok.ao }, ..ok.clone() }, - BakeSettings { ao: RaySettings { spread: f32::INFINITY, ..ok.ao }, ..ok.clone() }, - BakeSettings { max_rear: -1.0, ..ok.clone() }, - BakeSettings { curvature_strength: f32::INFINITY, ..ok.clone() }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { rays: 0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { rays: MAX_RAYS + 1, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { max_distance: f32::NAN, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { max_distance: 0.0, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.maps.ao.parameters = + AmbientOcclusionSettings { rays: RaySettings { spread: f32::INFINITY, ..ok.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + { + let mut base = ok.clone(); + base.cage = CageSettings { max_rear: -1.0, ..base.cage }; + base + }, ]; for s in &bad { assert!(matches!(run(&m, s), Err(BakeError::Invalid(_))), "{s:?}"); @@ -344,7 +398,6 @@ fn invalid_requests_are_errors() { let mut nan = m.clone(); nan.positions[0].x = f32::NAN; assert!(matches!(req(&nan, 0), Err(BakeError::Invalid(_)))); - // An empty mesh bakes to neutral values. let empty = Mesh { materials: vec!["m".into()], ..Mesh::default() }; let out = req(&empty, 0).unwrap(); assert!(out.maps[&BakedMap::AmbientOcclusion].iter().all(|v| *v == 1.0)); @@ -352,13 +405,17 @@ fn invalid_requests_are_errors() { #[test] fn neutral_values_and_padding() { - // The quad covers only the left half of UV space. let mut m = quad(); for uv in &mut m.uvs { uv.x *= 0.5; } let maps = [BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Thickness, BakedMap::Normal, BakedMap::Position]; - let out = run(&m, &BakeSettings { dilation: 2, ..settings(16, &maps) }).unwrap(); + let out = run(&m, &{ + let mut base = settings(16, &maps); + base.common = CommonBakeSettings { dilation: 2, ..base.common }; + base + }) + .unwrap(); let pos = &out.maps[&BakedMap::Position]; let at = |x: usize, y: usize| &pos[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3]; assert_eq!(at(9, 5)[0], at(7, 5)[0], "padded texel copies a texel of the last covered column"); @@ -397,12 +454,10 @@ fn normal_and_height_transfer_from_a_high_poly() { .unwrap(); let i = 8 * 16 + 8; let n = &out.maps[&BakedMap::Normal][i * 3..i * 3 + 3]; - // Tangent = +X (u), bitangent = −Z (up the image), normal = +Y. assert!((n[0] - (0.5 + 0.5 * tilt.x)).abs() < 1e-3 && (n[1] - 0.5).abs() < 1e-3 && (n[2] - (0.5 + 0.5 * tilt.y)).abs() < 1e-3, "{n:?}"); let diag = 8.0f32.sqrt(); let expected = 0.5 + 0.005 / (0.02 * diag); assert!((out.maps[&BakedMap::Height][i] - expected).abs() < 1e-3, "{}", out.maps[&BakedMap::Height][i]); - // Without a high poly both maps are flat. let flat = run(&low, &s).unwrap(); assert_eq!(&flat.maps[&BakedMap::Normal][i * 3..i * 3 + 3], [0.5, 0.5, 1.0]); assert_eq!(flat.maps[&BakedMap::Height][i], 0.5); @@ -425,10 +480,14 @@ fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> R ) } -/// The same box as its own high poly: its edges still read bright and its faces stay flat. #[test] fn a_high_poly_box_has_bright_edges_and_flat_faces() { - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(128, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(128, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; for (m, edge) in [(primitives::cube(2.0), 0.97), (primitives::rounded_box(Vec3::ONE, 0.15), 0.9)] { let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count(); @@ -438,10 +497,14 @@ fn a_high_poly_box_has_bright_edges_and_flat_faces() { } } -/// A narrow high poly bevel keeps a bright line. Wide ones read softer, like any gentle curve. #[test] fn a_narrow_high_poly_bevel_stays_bright() { - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(1024, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(1024, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let brightest = |bevel: f32| { let m = primitives::rounded_box(Vec3::ONE, bevel); let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); @@ -453,23 +516,25 @@ fn a_narrow_high_poly_bevel_stays_bright() { assert!(wide > 0.55, "wide: {wide}"); } -/// A gently round high poly stays below the wear masks' thresholds. #[test] fn a_gently_round_high_poly_stays_below_the_wear_masks() { let m = primitives::sphere(1.0, 96, 48); - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, dilation: 4, ..settings(256, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(256, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let c = covered_values(&m, &transfer(&m, &m, None, &s).unwrap(), BakedMap::Curvature); let over = c.iter().filter(|v| v.1 > 0.65).count() as f32 / c.len() as f32; assert!(over < 0.01, "{over}"); } -/// Texel (x, y) of a `res`² bake of [`quad`] sits over world (2u − 1, 0, 2v − 1). fn quad_texel(res: u32, x: f32, z: f32) -> usize { let t = |c: f32| (((c + 1.0) * 0.5 * res as f32) as usize).min(res as usize - 1); t(z) * res as usize + t(x) } -/// [`quad`]'s footprint with a smooth bump `h · exp(−r²/σ²)`. fn bumped(h: f32, sigma: f32) -> Mesh { let mut m = primitives::plane(2.0, 128); for p in &mut m.positions { @@ -483,17 +548,19 @@ fn bumped(h: f32, sigma: f32) -> Mesh { #[test] fn bump_tilts_the_baked_normal() { let (h, sigma) = (0.1f32, 0.4f32); - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, ..settings(64, &[BakedMap::Normal, BakedMap::Height]) }; + let s = { + let mut base = settings(64, &[BakedMap::Normal, BakedMap::Height]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base + }; let out = transfer(&quad(), &bumped(h, sigma), None, &s).unwrap(); let normal = &out.maps[&BakedMap::Normal]; for (x, z) in [(0.3f32, 0.0f32), (-0.3, 0.0), (0.0, 0.3), (0.0, -0.3), (0.25, 0.25)] { let i = quad_texel(64, x, z); - // Analytic normal of the bump at the texel centre. let (cx, cz) = (((i % 64) as f32 + 0.5) / 32.0 - 1.0, ((i / 64) as f32 + 0.5) / 32.0 - 1.0); let f = h * (-(cx * cx + cz * cz) / (sigma * sigma)).exp(); let (dx, dz) = (-2.0 * cx / (sigma * sigma) * f, -2.0 * cz / (sigma * sigma) * f); let n = Vec3::new(-dx, 1.0, -dz).normalize(); - // Tangent = +X, bitangent = −Z, normal = +Y. let expected = [0.5 + 0.5 * n.x, 0.5 - 0.5 * n.z, 0.5 + 0.5 * n.y]; let got = &normal[i * 3..i * 3 + 3]; assert!(got.iter().zip(expected).all(|(g, e)| (g - e).abs() < 0.02), "at {x},{z}: {got:?} vs {expected:?}"); @@ -505,7 +572,12 @@ fn bump_tilts_the_baked_normal() { #[test] fn curvature_from_the_normal_map_sees_the_bump() { - let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, ..settings(64, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(64, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; + base + }; let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap(); assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned"); let c = &out.maps[&BakedMap::Curvature]; @@ -513,47 +585,8 @@ fn curvature_from_the_normal_map_sees_the_bump() { assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]); } -/// Two unit boxes 0.2 apart: "A" (material 0, centre x = −0.6) and "B" (material 1, x = +0.6). -fn two_boxes(suffix: &str, colors: Option<[Vec4; 2]>) -> Mesh { - let part = |name: &str, x: f32, color: Option| { - let mut b = primitives::cube(1.0); - b.positions.iter_mut().for_each(|p| p.x += x); - b.submeshes[0].name = format!("{name}{suffix}"); - b.colors = color.map(|c| vec![c; b.positions.len()]).unwrap_or_default(); - b - }; - let mut m = part("A", -0.6, colors.map(|c| c[0])); - m.append(&part("B", 0.6, colors.map(|c| c[1]))); - m -} - -#[test] -fn match_by_mesh_name_pairs_the_right_parts() { - let (red, blue) = (Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 0.0, 1.0, 1.0)); - let (low, high) = (two_boxes("_low", None), two_boxes("_HIGH", Some([red, blue]))); - // Rays start 1.3 in front of A's +X face: beyond B, so B's high poly is hit first unless - // parts are matched by name. - let s = BakeSettings { max_frontal: 0.5, ..settings(64, &[BakedMap::ColorMap]) }; - let face = |s: &BakeSettings| { - let out = transfer(&low, &high, None, s).unwrap(); - covered_values(&low, &out, BakedMap::ColorMap) - .into_iter() - .filter(|(p, _)| p.x > -0.105 && p.y.abs() < 0.4 && p.z.abs() < 0.4) - .map(|v| v.1) - .collect::>() - }; - let always = face(&s); - assert!(!always.is_empty() && always.iter().all(|r| *r < 0.01), "always: B's (blue) high poly occludes A's face"); - let by_name = face(&BakeSettings { matching: BakeMatch::ByMeshName, ..s.clone() }); - assert!(by_name.iter().all(|r| *r > 0.99), "by name: A's face gets A's red"); - // Parts without a counterpart get nothing. - let lonely = BakeSettings { matching: BakeMatch::ByMeshName, low_suffix: "_none".into(), ..s }; - assert!(face(&lonely).iter().all(|r| *r == 0.0)); -} - #[test] fn bent_normals_point_away_from_occluders() { - // A floor (material 0) with a wall standing at x = +1, facing −X (material 1). let mut m = quad(); let wall = Mesh::from_parts( vec![Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(1.0, 2.0, 1.0), Vec3::new(1.0, 2.0, -1.0)], @@ -580,20 +613,17 @@ fn bent_normals_point_away_from_occluders() { } #[test] -fn opacity_and_color_transfer_where_the_high_poly_is() { - // The high poly covers x < 0 only, colored green. +fn opacity_transfers_where_the_high_poly_is() { let mut high = quad(); high.positions.iter_mut().for_each(|p| p.x = p.x.min(0.0)); high.colors = vec![Vec4::new(0.0, 1.0, 0.0, 0.5); 4]; - let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap(); - let (op, col) = (&out.maps[&BakedMap::Opacity], &out.maps[&BakedMap::ColorMap]); + let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity])).unwrap(); + let opacity = &out.maps[&BakedMap::Opacity]; let (left, right) = (quad_texel(32, -0.5, 0.0), quad_texel(32, 0.5, 0.0)); - assert_eq!((op[left], op[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed"); - assert_eq!(&col[left * 3..left * 3 + 3], [0.0, 1.0, 0.0]); - assert_eq!(&col[right * 3..right * 3 + 3], BakedMap::ColorMap.neutral()); - // Without a high poly the low poly covers itself (white, opaque). - let own = run(&quad(), &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap(); - assert_eq!((own.maps[&BakedMap::Opacity][right], own.maps[&BakedMap::ColorMap][right * 3]), (1.0, 1.0)); + assert_eq!((opacity[left], opacity[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed"); + + let low_poly_bake = run(&quad(), &settings(32, &[BakedMap::Opacity])).unwrap(); + assert_eq!(low_poly_bake.maps[&BakedMap::Opacity][right], 1.0); } #[test] @@ -605,59 +635,76 @@ fn ray_distances_and_the_cage_limit_hits() { let opacity = |s: &BakeSettings, cage: Option<&Mesh>| transfer(&low, &high, cage, s).map(|o| o.maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]); let near = settings(16, &[BakedMap::Opacity]); assert_eq!(opacity(&near, None).unwrap(), 0.0, "0.2 above is beyond the default frontal distance"); - assert_eq!(opacity(&BakeSettings { max_frontal: 0.25 / diag, ..near.clone() }, None).unwrap(), 1.0); - // The rear distance only reaches below the surface. + assert_eq!( + opacity( + &{ + let mut base = near.clone(); + base.cage = CageSettings { max_frontal: 0.25 / diag, ..base.cage }; + base + }, + None + ) + .unwrap(), + 1.0 + ); let mut below = high.clone(); below.positions.iter_mut().for_each(|p| p.y -= 0.4); - let rear = |r: f32| transfer(&low, &below, None, &BakeSettings { max_rear: r, ..near.clone() }).unwrap().maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]; + let rear = |r: f32| { + transfer(&low, &below, None, &{ + let mut base = near.clone(); + base.cage = CageSettings { max_rear: r, ..base.cage }; + base + }) + .unwrap() + .maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)] + }; assert_eq!((rear(0.1 / diag), rear(0.25 / diag)), (0.0, 1.0)); - // A cage 0.3 above the low poly starts the rays above the high poly. let mut cage = low.clone(); cage.positions.iter_mut().for_each(|p| p.y += 0.3); assert_eq!(opacity(&near, Some(&cage)).unwrap(), 1.0); - // A cage 0.1 above starts below it. cage.positions.iter_mut().for_each(|p| p.y -= 0.2); assert_eq!(opacity(&near, Some(&cage)).unwrap(), 0.0); - // The cage must have the low poly's triangles. assert!(matches!(opacity(&near, Some(&primitives::cube(1.0))), Err(BakeError::Invalid(_)))); } -#[test] -fn world_space_direction_is_a_facing_ratio() { - let m = quad(); - let at = - |d: [f32; 3]| run(&m, &BakeSettings { direction: d, ..settings(8, &[BakedMap::WorldDirection]) }).map(|o| o.maps[&BakedMap::WorldDirection][4 * 8 + 4]); - assert_eq!(at([0.0, 2.0, 0.0]).unwrap(), 1.0); - assert_eq!(at([1.0, 0.0, 0.0]).unwrap(), 0.5); - assert_eq!(at([0.0, -1.0, 0.0]).unwrap(), 0.0); - assert!(matches!(at([0.0; 3]), Err(BakeError::Invalid(_)))); -} - -/// `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` #[test] #[ignore] fn bench_material_ball_2k() { let m = primitives::material_ball(); let bvh = Bvh::new(&m); - let all = with_rays(BakeSettings { resolution: 2048, ..BakeSettings::default() }, 64, 0.25); - for maps in - [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.iter().copied().collect()] + let all = with_rays( + { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R2048, ..base.common }; + base + }, + 64, + 0.25, + ); + for maps in [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.enabled().collect()] { - let s = BakeSettings { maps: maps.into_iter().collect(), ..all.clone() }; + let s = { + let mut base = all.clone(); + base.maps.select(maps); + base + }; let t = std::time::Instant::now(); let out = bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()).unwrap(); - println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.ao.rays, t.elapsed()); + println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.maps.ao.parameters.rays.rays, t.elapsed()); } } #[test] fn uv_tiles_bake_side_by_side_in_one_atlas() { - // Tiles 1001 (x < 0) and 1002 (x > 0) of the UDIM plane, in atlas UVs. let mut m = primitives::udim_plane(); let grid = texturecraft_core::TileGrid::of(&[1001, 1002]).unwrap(); m.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array()))); - let s = BakeSettings { dilation: 4, ..settings(32, &[BakedMap::Position]) }; + let s = { + let mut base = settings(32, &[BakedMap::Position]); + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base + }; let bvh = Bvh::new(&m); let out = bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (2, 1) }, &Progress::new()).unwrap(); @@ -673,13 +720,16 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() { assert!(bake(&too_many, &Progress::new()).is_err()); } -/// On a UV tile grid, curvature lines keep their width in texels of the tile. #[test] fn curvature_on_uv_tiles_matches_a_single_tile() { let one = primitives::rounded_box(Vec3::ONE, 0.15); let mut two = one.clone(); two.uvs.iter_mut().for_each(|uv| uv.x *= 0.5); - let s = BakeSettings { dilation: 0, ..settings(64, &[BakedMap::Curvature]) }; + let s = { + let mut base = settings(64, &[BakedMap::Curvature]); + base.common = CommonBakeSettings { dilation: 0, ..base.common }; + base + }; let bake_tiles = |m: &Mesh, tiles| { let bvh = Bvh::new(m); bake(&BakeRequest { mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles }, &Progress::new()).unwrap() @@ -690,8 +740,6 @@ fn curvature_on_uv_tiles_matches_a_single_tile() { assert!(worst < 1e-3, "{worst}"); } -/// A floor ([`quad`], part "Quad") with a wall (part "Wall") standing at x = +1, facing the -/// floor (−X) or, when `away`, away from it (+X); winding and normals agree. fn floor_and_wall(away: bool) -> Mesh { let mut m = quad(); let (n, indices) = if away { (Vec3::X, vec![0, 2, 1, 0, 3, 2]) } else { (-Vec3::X, vec![0, 1, 2, 0, 2, 3]) }; @@ -707,45 +755,69 @@ fn floor_and_wall(away: bool) -> Mesh { m } -/// Mean of `map` (first component) over the floor where `x` is in `range` (the wall is at 1). fn floor_mean(m: &Mesh, s: &BakeSettings, map: BakedMap, range: std::ops::Range) -> f32 { let out = run(m, s).unwrap(); mean(covered_values(m, &out, map).into_iter().filter(|(p, _)| range.contains(&p.x)).map(|v| v.1)) } -/// [`floor_mean`] next to the wall. fn near_wall(m: &Mesh, s: &BakeSettings, map: BakedMap) -> f32 { floor_mean(m, s, map, 0.6..1.0) } #[test] fn ambient_occlusion_settings_shape_the_occlusion() { - let m = floor_and_wall(false); + let mesh = floor_and_wall(false); let base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0); - let ao = |f: &dyn Fn(&mut BakeSettings)| { - let mut s = base.clone(); - f(&mut s); - near_wall(&m, &s, BakedMap::AmbientOcclusion) + let ao = |configure: &dyn Fn(&mut BakeSettings)| { + let mut bake_settings = base.clone(); + configure(&mut bake_settings); + near_wall(&mesh, &bake_settings, BakedMap::AmbientOcclusion) }; let wide = ao(&|_| {}); assert!(wide < 0.85, "the wall occludes the floor beside it: {wide}"); - // A wider spread gathers occlusion from farther away: the wall darkens a wider, softer band. - let far = |spread: f32| floor_mean(&m, &BakeSettings { ao: RaySettings { spread, ..base.ao }, ..base.clone() }, BakedMap::AmbientOcclusion, -1.0..-0.2); + + let far = |spread: f32| { + floor_mean( + &mesh, + &{ + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { spread, ..base.maps.ao.parameters.rays }, ..base.maps.ao.parameters }; + base + }, + BakedMap::AmbientOcclusion, + -1.0..-0.2, + ) + }; let (narrow, wide_far) = (far(60.0), far(180.0)); assert!(narrow > 0.99 && wide_far < narrow - 0.05, "far from the wall: spread 60° {narrow}, 180° {wide_far}"); - // Uniform rays graze the floor more often than cosine-weighted ones: they reach the wall - // from farther away. - let uniform = BakeSettings { ao: RaySettings { distribution: RayDistribution::Uniform, ..base.ao }, ..base.clone() }; - let uniform_far = floor_mean(&m, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2); + + let uniform = { + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { distribution: RayDistribution::Uniform, ..base.maps.ao.parameters.rays }, + ..base.maps.ao.parameters + }; + base + }; + let uniform_far = floor_mean(&mesh, &uniform, BakedMap::AmbientOcclusion, -1.0..-0.2); assert!(uniform_far < wide_far - 0.02, "far from the wall: uniform {uniform_far}, cosine {wide_far}"); - // Parts only occlude themselves when matched by name: the wall is another part. - let own = ao(&|s| s.ao_self_occlusion = SelfOcclusion::SameMeshName); + + let own = ao(&|bake_settings| bake_settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName); assert!(own > 0.999, "{own}"); - // Back faces are ignored on request: a wall turned away no longer occludes. - let back = - |away: bool, ignore: bool| near_wall(&floor_and_wall(away), &BakeSettings { ao_ignore_backface: ignore, ..base.clone() }, BakedMap::AmbientOcclusion); - assert!((back(true, false) - wide).abs() < 1e-6, "without the option a wall occludes from either side"); - assert!(back(true, true) > 0.999 && (back(false, true) - wide).abs() < 1e-6); + + let back = |away: bool, ignore: BackfaceMode| { + near_wall( + &floor_and_wall(away), + &{ + let mut base = base.clone(); + base.maps.ao.parameters = AmbientOcclusionSettings { ignore_backface: ignore, ..base.maps.ao.parameters }; + base + }, + BakedMap::AmbientOcclusion, + ) + }; + assert!((back(true, BackfaceMode::Never) - wide).abs() < 1e-6, "without the option a wall occludes from either side"); + assert!(back(true, BackfaceMode::Always) > 0.999 && (back(false, BackfaceMode::Always) - wide).abs() < 1e-6); } #[test] @@ -754,16 +826,18 @@ fn bent_normals_and_thickness_have_their_own_rays() { let s = with_rays(settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]), 64, 2.0); let lean = |s: &BakeSettings| near_wall(&m, s, BakedMap::BentNormal) * 2.0 - 1.0; assert!(lean(&s) < -0.15, "{}", lean(&s)); - // Bent-normal rays shorter than the gap to the wall see nothing; the AO keeps its own rays. - let short = BakeSettings { bent_normal: RaySettings { max_distance: 0.05, rays: 16, ..s.bent_normal }, ..s.clone() }; + let short = { + let mut base = s.clone(); + base.maps.bent_normal.parameters = + BentNormalSettings { rays: RaySettings { max_distance: 0.05, rays: 16, ..s.maps.bent_normal.parameters.rays }, ..base.maps.bent_normal.parameters }; + base + }; assert!(lean(&short) > 0.5 * lean(&s), "{} vs {}", lean(&short), lean(&s)); assert_eq!(near_wall(&m, &short, BakedMap::AmbientOcclusion), near_wall(&m, &s, BakedMap::AmbientOcclusion)); - // Thickness of the slab's top and bottom: a wider spread sends rays through it at grazing - // angles (longer paths). let slab = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0); let thick = |spread: f32| { - let mut s = settings(48, &[BakedMap::Thickness]); - s.thickness.spread = spread; + let mut s = settings(64, &[BakedMap::Thickness]); + s.maps.thickness.parameters.rays.spread = spread; mean( covered_values(&slab, &run(&slab, &s).unwrap(), BakedMap::Thickness) .into_iter() @@ -776,83 +850,76 @@ fn bent_normals_and_thickness_have_their_own_rays() { } #[test] -fn position_and_direction_modes() { - let m = quad(); - let pos = |mode: PositionMode| { - let out = run(&m, &BakeSettings { position_mode: mode, ..settings(16, &[BakedMap::Position]) }).unwrap(); - let g = UvGBuffer::new(&m, 0, 16, 16); - (0..256).filter(|i| g.surface(&m, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>() +fn position_modes() { + let mesh = quad(); + let positions = |mode: PositionMode| { + let out = run(&mesh, &{ + let mut base = settings(16, &[BakedMap::Position]); + base.maps.position.parameters = PositionSettings { normalization: mode, ..base.maps.position.parameters }; + base + }) + .unwrap(); + let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16); + (0..256).filter(|i| gbuffer.surface(&mesh, *i).is_some()).map(|i| [0, 1, 2].map(|k| out.maps[&BakedMap::Position][i * 3 + k])).collect::>() }; - // The flat quad: the box squashes y to 0 and stretches x, z over 0..1; the sphere keeps - // proportions around the centre (half diagonal √2 of 2√2 per unit). - let (bbox, sphere) = (pos(PositionMode::BoundingBox), pos(PositionMode::BoundingSphere)); - assert!(bbox.iter().all(|p| p[1] == 0.0) && bbox.iter().any(|p| p[0] < 0.05) && bbox.iter().any(|p| p[0] > 0.95)); - let r = 0.5 / 8.0f32.sqrt(); - assert!(sphere.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * r + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * r + 1e-4)); - let dir = |d: [f32; 3], mode| { - run(&m, &BakeSettings { direction: d, direction_mode: mode, ..settings(8, &[BakedMap::WorldDirection]) }).unwrap().maps[&BakedMap::WorldDirection] - [4 * 8 + 4] + + let (box_positions, sphere_positions) = (positions(PositionMode::BoundingBox), positions(PositionMode::BoundingSphere)); + assert!(box_positions.iter().all(|p| p[1] == 0.0) && box_positions.iter().any(|p| p[0] < 0.05) && box_positions.iter().any(|p| p[0] > 0.95)); + let unit_scale = 0.5 / 8.0f32.sqrt(); + assert!(sphere_positions.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * unit_scale + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * unit_scale + 1e-4)); + + let raw_settings = { + let mut base = settings(16, &[BakedMap::Position]); + base.maps.position.parameters = PositionSettings { normalization: PositionMode::None, ..base.maps.position.parameters }; + base }; - assert_eq!( - (dir([1.0, 0.0, 0.0], DirectionMode::Positive), dir([0.0, -1.0, 0.0], DirectionMode::Positive), dir([0.0, 1.0, 0.0], DirectionMode::Positive)), - (0.0, 0.0, 1.0) - ); - assert_eq!(dir([1.0, 0.0, 0.0], DirectionMode::Signed), 0.5); + let raw = run(&mesh, &raw_settings).unwrap(); + let gbuffer = UvGBuffer::new(&mesh, 0, 16, 16); + for texel in 0..16 * 16 { + let Some(surface) = gbuffer.surface(&mesh, texel) else { continue }; + + let actual = &raw.maps[&BakedMap::Position][texel * 3..texel * 3 + 3]; + assert!(actual.iter().zip(surface.pos.to_array()).all(|(actual, expected)| (actual - expected).abs() < 1e-6)); + } } #[test] -fn curvature_radius_widens_the_normal_map_sampling() { - let at_top = |radius: u32| { - let s = - BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, curvature_radius: radius, ..settings(64, &[BakedMap::Curvature]) }; - transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap().maps[&BakedMap::Curvature][quad_texel(64, 0.0, 0.0)] - }; - let (one, four) = (at_top(1), at_top(4)); - assert!(one > 0.5 && four > one + 0.02, "radius 1: {one}, radius 4: {four}"); -} - -#[test] -fn color_map_samples_the_high_poly_base_color_texture() { +fn opacity_samples_the_high_poly_base_color_texture() { let low = quad(); let mut high = quad(); high.positions.iter_mut().for_each(|p| p.y += 0.005); - // Four texels across u: red, red, blue (half transparent), blue; a second material tinted - // by its factor only. + let red = [255, 0, 0, 255]; let blue = [0, 0, 255, 128]; - let tex = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] }; - let hb = Bvh::new(&high); - let lb = Bvh::new(&low); - let s = settings(32, &[BakedMap::ColorMap, BakedMap::Opacity]); - let bake_with = |c: BaseColor| { - let base_color = [Some(Arc::new(c))]; - let req = BakeRequest { + let texture = BaseColor { factor: Vec4::ONE, width: 4, height: 1, texels: vec![red, red, blue, blue] }; + let high_bvh = Bvh::new(&high); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(32, &[BakedMap::Opacity]); + let bake_with = |base_color: BaseColor| { + let base_color = [Some(Arc::new(base_color))]; + let request = BakeRequest { mesh: &low, - bvh: &lb, + bvh: &low_bvh, material: 0, - settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &base_color }), + settings: &bake_settings, + high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &base_color }), cage: None, skew: None, tiles: (1, 1), }; - bake(&req, &Progress::new()).unwrap() + bake(&request, &Progress::new()).unwrap() }; - let out = bake_with(tex); - // Row 16 (v ≈ 0.5); columns 8 and 24 sit inside the red and blue halves (u ≈ 0.27, 0.77). + + let out = bake_with(texture); + let (left, right) = (16 * 32 + 8, 16 * 32 + 24); - let (color, opacity) = (&out.maps[&BakedMap::ColorMap], &out.maps[&BakedMap::Opacity]); - let near = |a: &[f32], b: [f32; 3]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-3); - assert!(near(&color[left * 3..left * 3 + 3], [1.0, 0.0, 0.0]), "{:?}", &color[left * 3..left * 3 + 3]); - assert!(near(&color[right * 3..right * 3 + 3], [0.0, 0.0, 1.0]), "{:?}", &color[right * 3..right * 3 + 3]); + let opacity = &out.maps[&BakedMap::Opacity]; assert!((opacity[left] - 1.0).abs() < 1e-6 && (opacity[right] - 128.0 / 255.0).abs() < 1e-3); - // A factor alone tints in linear light; the map holds display-encoded color like a texture. - let half = bake_with(BaseColor { factor: Vec4::new(0.5, 1.0, 1.0, 1.0), width: 0, height: 0, texels: Vec::new() }); - let r = half.maps[&BakedMap::ColorMap][left * 3]; - assert!((r - texturecraft_texel::linear_to_srgb(0.5)).abs() < 1e-4, "{r}"); + + let half = bake_with(BaseColor { factor: Vec4::new(1.0, 1.0, 1.0, 0.5), width: 0, height: 0, texels: Vec::new() }); + assert_eq!(half.maps[&BakedMap::Opacity][left], 0.5); } -/// A tracer that never works (no GPU). struct Broken; impl Tracer for Broken { @@ -860,7 +927,7 @@ impl Tracer for Broken { "Broken".into() } - fn scene<'a>(&'a self, _: &[rays::TraceMesh<'a>]) -> Result, BakeError> { + fn scene<'a>(&'a self, _: &[tracing::TraceMesh<'a>]) -> Result, BakeError> { Err(BakeError::Tracer("no device".into())) } } @@ -874,12 +941,14 @@ fn a_failing_tracer_falls_back_to_the_cpu() { let out = bake_on(&req, &Progress::new(), &Broken).unwrap(); assert_eq!(out.tracer, "CPU (Broken unavailable: no device)"); assert_eq!(out.maps, bake(&req, &Progress::new()).unwrap().maps); - // Bakes without rays never ask the tracer. - let flat = BakeSettings { maps: [BakedMap::Position].into_iter().collect(), ..s.clone() }; + let flat = { + let mut base = s.clone(); + base.maps.select([BakedMap::Position]); + base + }; assert_eq!(bake_on(&BakeRequest { settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU"); } -/// A flat quad of half-size `half` at height `y`, every vertex normal `n`. fn plane(y: f32, half: f32, n: Vec3) -> Mesh { Mesh::from_parts( vec![Vec3::new(-half, y, -half), Vec3::new(half, y, -half), Vec3::new(half, y, half), Vec3::new(-half, y, half)], @@ -892,12 +961,15 @@ fn plane(y: f32, half: f32, n: Vec3) -> Mesh { } #[test] -fn skew_correction_turns_transfer_rays_from_the_averaged_direction_to_the_base_normal() { - // A flat low poly whose smooth normals lean (0.6, 0.8, 0); the high poly is a plane 0.3 above it. +fn skew_correction_preserves_uniform_mesh_normals_and_rejects_invalid_values() { let lean = Vec3::new(0.6, 0.8, 0.0); let (low, high) = (plane(0.0, 1.0, lean), plane(0.3, 4.0, Vec3::Y)); let (lb, hb) = (Bvh::new(&low), Bvh::new(&high)); - let s = BakeSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..settings(16, &[BakedMap::Height]) }; + let s = { + let mut base = settings(16, &[BakedMap::Height]); + base.cage = CageSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..base.cage }; + base + }; let diag = (low.bounds().1 - low.bounds().0).length(); let (front, rear) = (0.5 * diag, 0.1 * diag); let height = |skew: Option<&SkewMap>| { @@ -913,19 +985,11 @@ fn skew_correction_turns_transfer_rays_from_the_averaged_direction_to_the_base_n }; bake(&req, &Progress::new()).unwrap().maps[&BakedMap::Height][8 * 16 + 8] }; - // Along a direction with vertical component c the ray meets the plane at t = front - 0.3 / c. let expect = |c: f32| 0.5 + (0.3 / c) / (front + rear); - let map = |v: f32, per_triangle: bool| SkewMap { per_triangle, ..SkewMap::constant(v) }; let plain = height(None); assert!((plain - expect(0.8)).abs() < 1e-3, "leaning rays: {plain} vs {}", expect(0.8)); - assert!((height(Some(&map(0.0, true))) - plain).abs() < 1e-6, "black leaves the rays alone"); - let full = height(Some(&map(1.0, true))); - assert!((full - expect(1.0)).abs() < 1e-3, "white turns them onto the flat normal: {full} vs {}", expect(1.0)); - let half = height(Some(&map(0.5, true))); - assert!(half > full.min(plain) && half < full.max(plain), "grey is in between: {half}"); - // With the interpolated vertex normal as the base, correcting changes nothing on this mesh. - assert!((height(Some(&map(1.0, false))) - plain).abs() < 1e-4); - // A bad map is refused, not baked. + assert!((height(Some(&SkewMap::constant(0.0))) - plain).abs() < 1e-6, "black leaves the rays alone"); + assert!((height(Some(&SkewMap::constant(1.0))) - plain).abs() < 1e-4); let bad = SkewMap { values: vec![f32::NAN], ..SkewMap::constant(0.0) }; let req = BakeRequest { mesh: &low, bvh: &lb, material: 0, settings: &s, high: None, cage: None, skew: Some(&bad), tiles: (1, 1) }; assert!(matches!(bake(&req, &Progress::new()), Err(BakeError::Invalid(_)))); diff --git a/crates/bake/src/tracing.rs b/crates/bake/src/tracing.rs new file mode 100644 index 00000000..c07596f6 --- /dev/null +++ b/crates/bake/src/tracing.rs @@ -0,0 +1,21 @@ +mod cpu_scene; +mod cpu_tracer; +mod hemisphere; +mod query; +mod ray; +mod ray_kind; +mod ray_scene; +mod trace_mesh; +mod tracer; + +pub use cpu_tracer::CpuTracer; +pub use hemisphere::Hemisphere; +pub use query::Query; +pub use ray::Ray; +pub use ray_kind::RayKind; +pub use ray_scene::RayScene; +pub use trace_mesh::TraceMesh; +pub use tracer::Tracer; + +/// Part key that disables triangle filtering +pub const ANY: u32 = u32::MAX; diff --git a/crates/bake/src/tracing/cpu_scene.rs b/crates/bake/src/tracing/cpu_scene.rs new file mode 100644 index 00000000..125e5a48 --- /dev/null +++ b/crates/bake/src/tracing/cpu_scene.rs @@ -0,0 +1,29 @@ +use super::{ANY, Hemisphere, Query, Ray, RayScene, TraceMesh}; +use crate::BakeError; +use rayon::prelude::*; +use texturecraft_geom::Hit; + +pub(super) struct CpuScene<'a>(pub(super) Vec>); + +impl CpuScene<'_> { + fn mesh(&self, index: usize) -> Result<&TraceMesh<'_>, BakeError> { + self.0.get(index).ok_or_else(|| BakeError::Invalid(format!("no scene mesh {index}"))) + } +} + +impl RayScene for CpuScene<'_> { + fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { + let trace_mesh = self.mesh(mesh)?; + Ok(rays + .par_iter() + .map(|ray| match ray.key { + ANY => trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance), + key => trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| trace_mesh.key_matches(triangle, key)), + }) + .collect()) + } + + fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError> { + passes.iter().map(|hemisphere| queries.par_iter().map(|query| Ok(hemisphere.evaluate(self.mesh(query.mesh as usize)?, query))).collect()).collect() + } +} diff --git a/crates/bake/src/tracing/cpu_tracer.rs b/crates/bake/src/tracing/cpu_tracer.rs new file mode 100644 index 00000000..5276e6aa --- /dev/null +++ b/crates/bake/src/tracing/cpu_tracer.rs @@ -0,0 +1,16 @@ +use super::cpu_scene::CpuScene; +use super::{RayScene, TraceMesh, Tracer}; +use crate::BakeError; + +#[derive(Clone, Copy, Debug, Default)] +pub struct CpuTracer; + +impl Tracer for CpuTracer { + fn name(&self) -> String { + "CPU".into() + } + + fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError> { + Ok(Box::new(CpuScene(meshes.to_vec()))) + } +} diff --git a/crates/bake/src/tracing/hemisphere.rs b/crates/bake/src/tracing/hemisphere.rs new file mode 100644 index 00000000..a6f96e00 --- /dev/null +++ b/crates/bake/src/tracing/hemisphere.rs @@ -0,0 +1,81 @@ +use super::{ANY, Query, RayKind, TraceMesh}; +use std::f32::consts::TAU; +use texturecraft_geom::glam::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Hemisphere { + pub kind: RayKind, + pub rays: u32, + /// Maximum ray distance in mesh units + pub dmax: f32, + /// Ray origin offset along the geometric normal + pub eps: f32, + pub cos_max: f32, + pub sin_max: f32, + pub uniform: bool, + pub ignore_backface: bool, + pub same_key: bool, +} + +impl Hemisphere { + pub fn direction(&self, (tangent, bitangent, axis): (Vec3, Vec3, Vec3), ray_index: u32, rotation: [f32; 2]) -> Vec3 { + let azimuth_sample = (ray_index as f32 / self.rays as f32 + rotation[0]).fract(); + let elevation_sample = (ray_index.reverse_bits() as f32 / 4_294_967_296.0 + rotation[1]).fract(); + let (radius, height) = if self.uniform { + let height = 1.0 - elevation_sample * (1.0 - self.cos_max); + ((1.0 - height * height).max(0.0).sqrt(), height) + } else { + let radius = self.sin_max * elevation_sample.sqrt(); + (radius, (1.0 - radius * radius).max(0.0).sqrt()) + }; + let azimuth = TAU * azimuth_sample; + tangent * (radius * azimuth.cos()) + bitangent * (radius * azimuth.sin()) + axis * height + } + + fn frame(&self, query: &Query) -> (Vec3, Vec3, Vec3) { + let (axis, geometric_normal) = match self.kind { + RayKind::Occlusion => (query.nrm, query.geo), + RayKind::Thickness => (-query.nrm, -query.geo), + }; + (axis, geometric_normal, query.pos + geometric_normal * self.eps) + } + + pub fn evaluate(&self, mesh: &TraceMesh, query: &Query) -> [f32; 4] { + let (axis, geometric_normal, origin) = self.frame(query); + let (tangent, bitangent) = axis.any_orthonormal_pair(); + let key = if self.same_key && self.kind == RayKind::Occlusion { query.key } else { ANY }; + let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion); + let (mut accumulated, mut bent_normal, mut accepted_ray_count) = (0.0f32, Vec3::ZERO, 0u32); + for ray_index in 0..self.rays { + let direction = self.direction((tangent, bitangent, axis), ray_index, query.rot); + if direction.dot(geometric_normal) <= 0.0 { + continue; + } + let hit = match filtered { + true => mesh.bvh.closest_filtered(origin, direction, self.dmax, &|tri| { + mesh.key_matches(tri, key) && !(self.ignore_backface && mesh.back_facing(tri, direction)) + }), + false => mesh.bvh.closest(origin, direction, self.dmax), + }; + match self.kind { + RayKind::Occlusion => { + let occlusion = hit.map_or(0.0, |hit| 1.0 - (hit.t / self.dmax).powi(2)); + accumulated += occlusion; + bent_normal += direction * (1.0 - occlusion); + } + RayKind::Thickness => accumulated += hit.map_or(self.dmax, |hit| hit.t), + } + accepted_ray_count += 1; + } + match self.kind { + RayKind::Occlusion => { + let ambient_occlusion = if accepted_ray_count == 0 { 1.0 } else { (1.0 - accumulated / accepted_ray_count as f32).clamp(0.0, 1.0) }; + let bent_normal = bent_normal.try_normalize().unwrap_or(query.nrm); + [ambient_occlusion, bent_normal.x, bent_normal.y, bent_normal.z] + } + RayKind::Thickness => { + [if accepted_ray_count == 0 { 1.0 } else { (accumulated / accepted_ray_count as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0] + } + } + } +} diff --git a/crates/bake/src/tracing/query.rs b/crates/bake/src/tracing/query.rs new file mode 100644 index 00000000..a42e7091 --- /dev/null +++ b/crates/bake/src/tracing/query.rs @@ -0,0 +1,11 @@ +use texturecraft_geom::glam::Vec3; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Query { + pub pos: Vec3, + pub nrm: Vec3, + pub geo: Vec3, + pub rot: [f32; 2], + pub key: u32, + pub mesh: u32, +} diff --git a/crates/bake/src/tracing/ray.rs b/crates/bake/src/tracing/ray.rs new file mode 100644 index 00000000..85303f1e --- /dev/null +++ b/crates/bake/src/tracing/ray.rs @@ -0,0 +1,11 @@ +use texturecraft_geom::glam::Vec3; + +/// GPU buffer layout; batches upload without repacking +#[repr(C)] +#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)] +pub struct Ray { + pub origin: Vec3, + pub max_distance: f32, + pub direction: Vec3, + pub key: u32, +} diff --git a/crates/bake/src/tracing/ray_kind.rs b/crates/bake/src/tracing/ray_kind.rs new file mode 100644 index 00000000..1ce6eed9 --- /dev/null +++ b/crates/bake/src/tracing/ray_kind.rs @@ -0,0 +1,5 @@ +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RayKind { + Occlusion, + Thickness, +} diff --git a/crates/bake/src/tracing/ray_scene.rs b/crates/bake/src/tracing/ray_scene.rs new file mode 100644 index 00000000..6249e241 --- /dev/null +++ b/crates/bake/src/tracing/ray_scene.rs @@ -0,0 +1,8 @@ +use super::{Hemisphere, Query, Ray}; +use crate::BakeError; +use texturecraft_geom::Hit; + +pub trait RayScene: Send { + fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError>; + fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>; +} diff --git a/crates/bake/src/tracing/trace_mesh.rs b/crates/bake/src/tracing/trace_mesh.rs new file mode 100644 index 00000000..7ad6010b --- /dev/null +++ b/crates/bake/src/tracing/trace_mesh.rs @@ -0,0 +1,22 @@ +use super::ANY; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh}; + +#[derive(Clone, Copy, Debug)] +pub struct TraceMesh<'a> { + pub mesh: &'a Mesh, + pub bvh: &'a Bvh, + /// Part key per triangle in original mesh order + pub keys: &'a [u32], +} + +impl TraceMesh<'_> { + pub(super) fn key_matches(&self, triangle: u32, key: u32) -> bool { + key == ANY || self.keys.get(triangle as usize) == Some(&key) + } + + pub(super) fn back_facing(&self, triangle: u32, direction: Vec3) -> bool { + let position = |vertex_index: usize| self.mesh.positions.get(vertex_index).copied().unwrap_or(Vec3::ZERO); + self.mesh.tri(triangle as usize).is_some_and(|[a, b, c]| (position(b) - position(a)).cross(position(c) - position(a)).dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/tracing/tracer.rs b/crates/bake/src/tracing/tracer.rs new file mode 100644 index 00000000..cda49f13 --- /dev/null +++ b/crates/bake/src/tracing/tracer.rs @@ -0,0 +1,7 @@ +use super::{RayScene, TraceMesh}; +use crate::BakeError; + +pub trait Tracer: Send + Sync { + fn name(&self) -> String; + fn scene<'a>(&'a self, meshes: &[TraceMesh<'a>]) -> Result, BakeError>; +} diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs new file mode 100644 index 00000000..df3ddf46 --- /dev/null +++ b/crates/core/src/bake.rs @@ -0,0 +1,71 @@ +//! Bake model types and component defaults + +mod ambient_occlusion_attenuation; +mod ambient_occlusion_settings; +mod backface_mode; +mod bake_antialiasing; +mod bake_resolution; +mod bake_settings; +mod baked_map; +mod bent_normal_settings; +mod cage_settings; +mod cage_type; +mod common_bake_settings; +mod curvature_method; +mod curvature_settings; +mod ground_plane_settings; +mod height_normalization; +mod height_settings; +mod high_poly_settings; +mod id_color_generator; +mod id_color_source; +mod id_settings; +mod map_settings; +mod mesh_curvature_settings; +mod mesh_map_settings; +mod normal_map_curvature_settings; +mod position_axis; +mod position_mode; +mod position_normalization_scale; +mod position_settings; +mod ray_distribution; +mod ray_settings; +mod self_occlusion; +mod skew_settings; +mod thickness_normalization; +mod thickness_settings; + +pub use ambient_occlusion_attenuation::AmbientOcclusionAttenuation; +pub use ambient_occlusion_settings::AmbientOcclusionSettings; +pub use backface_mode::BackfaceMode; +pub use bake_antialiasing::BakeAntialiasing; +pub use bake_resolution::BakeResolution; +pub use bake_settings::BakeSettings; +pub use baked_map::BakedMap; +pub use bent_normal_settings::BentNormalSettings; +pub use cage_settings::CageSettings; +pub use cage_type::CageType; +pub use common_bake_settings::CommonBakeSettings; +pub use curvature_method::CurvatureMethod; +pub use curvature_settings::CurvatureSettings; +pub use ground_plane_settings::GroundPlaneSettings; +pub use height_normalization::HeightNormalization; +pub use height_settings::HeightSettings; +pub use high_poly_settings::HighPolySettings; +pub use id_color_generator::IdColorGenerator; +pub use id_color_source::IdColorSource; +pub use id_settings::IdSettings; +pub use map_settings::MapSettings; +pub use mesh_curvature_settings::MeshCurvatureSettings; +pub use mesh_map_settings::MeshMapSettings; +pub use normal_map_curvature_settings::NormalMapCurvatureSettings; +pub use position_axis::PositionAxis; +pub use position_mode::PositionMode; +pub use position_normalization_scale::PositionNormalizationScale; +pub use position_settings::PositionSettings; +pub use ray_distribution::RayDistribution; +pub use ray_settings::RaySettings; +pub use self_occlusion::SelfOcclusion; +pub use skew_settings::SkewSettings; +pub use thickness_normalization::ThicknessNormalization; +pub use thickness_settings::ThicknessSettings; diff --git a/crates/core/src/bake/ambient_occlusion_attenuation.rs b/crates/core/src/bake/ambient_occlusion_attenuation.rs new file mode 100644 index 00000000..92e2dffb --- /dev/null +++ b/crates/core/src/bake/ambient_occlusion_attenuation.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AmbientOcclusionAttenuation { + None, + Smooth, + #[default] + Linear, +} diff --git a/crates/core/src/bake/ambient_occlusion_settings.rs b/crates/core/src/bake/ambient_occlusion_settings.rs new file mode 100644 index 00000000..3ba308c0 --- /dev/null +++ b/crates/core/src/bake/ambient_occlusion_settings.rs @@ -0,0 +1,12 @@ +use super::{AmbientOcclusionAttenuation, BackfaceMode, GroundPlaneSettings, RaySettings, SelfOcclusion}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AmbientOcclusionSettings { + pub rays: RaySettings, + pub ignore_backface: BackfaceMode, + pub self_occlusion: SelfOcclusion, + pub attenuation: AmbientOcclusionAttenuation, + pub ground_plane: GroundPlaneSettings, +} diff --git a/crates/core/src/bake/backface_mode.rs b/crates/core/src/bake/backface_mode.rs new file mode 100644 index 00000000..2b46f585 --- /dev/null +++ b/crates/core/src/bake/backface_mode.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BackfaceMode { + #[default] + Never, + Always, + ByMeshName, +} diff --git a/crates/core/src/bake/bake_antialiasing.rs b/crates/core/src/bake/bake_antialiasing.rs new file mode 100644 index 00000000..8d7cff98 --- /dev/null +++ b/crates/core/src/bake/bake_antialiasing.rs @@ -0,0 +1,27 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BakeAntialiasing { + #[default] + None, + Subsampling2x2, + Subsampling4x4, + Subsampling8x8, +} + +impl BakeAntialiasing { + pub const ALL: [Self; 4] = [Self::None, Self::Subsampling2x2, Self::Subsampling4x4, Self::Subsampling8x8]; + + pub fn samples_per_axis(self) -> u32 { + match self { + Self::None => 1, + Self::Subsampling2x2 => 2, + Self::Subsampling4x4 => 4, + Self::Subsampling8x8 => 8, + } + } + + pub fn from_samples_per_axis(samples: u32) -> Option { + Self::ALL.into_iter().find(|antialiasing| antialiasing.samples_per_axis() == samples) + } +} diff --git a/crates/core/src/bake/bake_resolution.rs b/crates/core/src/bake/bake_resolution.rs new file mode 100644 index 00000000..1ff49186 --- /dev/null +++ b/crates/core/src/bake/bake_resolution.rs @@ -0,0 +1,39 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum BakeResolution { + R16, + R32, + R64, + R128, + R256, + R512, + R1024, + #[default] + R2048, + R4096, + R8192, +} + +impl BakeResolution { + pub const ALL: [Self; 10] = [Self::R16, Self::R32, Self::R64, Self::R128, Self::R256, Self::R512, Self::R1024, Self::R2048, Self::R4096, Self::R8192]; + + pub fn pixels(self) -> u32 { + match self { + Self::R16 => 16, + Self::R32 => 32, + Self::R64 => 64, + Self::R128 => 128, + Self::R256 => 256, + Self::R512 => 512, + Self::R1024 => 1024, + Self::R2048 => 2048, + Self::R4096 => 4096, + Self::R8192 => 8192, + } + } + + pub fn from_pixels(pixels: u32) -> Option { + Self::ALL.into_iter().find(|resolution| resolution.pixels() == pixels) + } +} diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs new file mode 100644 index 00000000..4528270d --- /dev/null +++ b/crates/core/src/bake/bake_settings.rs @@ -0,0 +1,13 @@ +use super::{CageSettings, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use serde::{Deserialize, Serialize}; + +/// Persisted clean-room bake settings, grouped by the controls they belong to +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeSettings { + pub common: CommonBakeSettings, + pub high_poly: HighPolySettings, + pub cage: CageSettings, + pub skew: SkewSettings, + pub maps: MeshMapSettings, +} diff --git a/crates/core/src/bake/baked_map.rs b/crates/core/src/bake/baked_map.rs new file mode 100644 index 00000000..ed6e695d --- /dev/null +++ b/crates/core/src/bake/baked_map.rs @@ -0,0 +1,82 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] +pub enum BakedMap { + Normal, + WorldNormal, + Id, + AmbientOcclusion, + Curvature, + Position, + Thickness, + Height, + /// World-space direction of least occlusion (packed like the world-space normal) + BentNormal, + /// High-poly coverage times vertex and material alpha + Opacity, +} + +impl BakedMap { + pub const ALL: [BakedMap; 10] = [ + BakedMap::Normal, + BakedMap::WorldNormal, + BakedMap::Id, + BakedMap::AmbientOcclusion, + BakedMap::Curvature, + BakedMap::Position, + BakedMap::Thickness, + BakedMap::Height, + BakedMap::BentNormal, + BakedMap::Opacity, + ]; + + /// Mesh-map identifier shared with MaterialCraft + pub fn id(self) -> &'static str { + match self { + BakedMap::Normal => "normal", + BakedMap::WorldNormal => "worldNormal", + BakedMap::Id => "id", + BakedMap::AmbientOcclusion => "ambientOcclusion", + BakedMap::Curvature => "curvature", + BakedMap::Position => "position", + BakedMap::Thickness => "thickness", + BakedMap::Height => "height", + BakedMap::BentNormal => "bentNormal", + BakedMap::Opacity => "opacity", + } + } + + /// Components stored (3 for vector maps, 1 for scalar maps) + pub fn components(self) -> usize { + match self { + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal => 3, + _ => 1, + } + } + + /// Value where nothing was baked (uncovered texels, missing maps) + pub fn neutral(self) -> [f32; 3] { + match self { + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0], + BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3], + BakedMap::Curvature | BakedMap::Height => [0.5; 3], + BakedMap::Id | BakedMap::Position | BakedMap::Opacity => [0.0; 3], + } + } + + pub fn parse(identifier: &str) -> Option { + match identifier { + "normal" => Some(BakedMap::Normal), + "worldNormal" => Some(BakedMap::WorldNormal), + "id" => Some(BakedMap::Id), + "ambientOcclusion" => Some(BakedMap::AmbientOcclusion), + "curvature" => Some(BakedMap::Curvature), + "position" => Some(BakedMap::Position), + "thickness" => Some(BakedMap::Thickness), + "height" => Some(BakedMap::Height), + "bentNormal" => Some(BakedMap::BentNormal), + "opacity" => Some(BakedMap::Opacity), + _ => None, + } + } +} diff --git a/crates/core/src/bake/bent_normal_settings.rs b/crates/core/src/bake/bent_normal_settings.rs new file mode 100644 index 00000000..dcc03cda --- /dev/null +++ b/crates/core/src/bake/bent_normal_settings.rs @@ -0,0 +1,10 @@ +use super::{BackfaceMode, RaySettings, SelfOcclusion}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BentNormalSettings { + pub rays: RaySettings, + pub ignore_backface: BackfaceMode, + pub self_occlusion: SelfOcclusion, +} diff --git a/crates/core/src/bake/cage_settings.rs b/crates/core/src/bake/cage_settings.rs new file mode 100644 index 00000000..13b18929 --- /dev/null +++ b/crates/core/src/bake/cage_settings.rs @@ -0,0 +1,19 @@ +use super::CageType; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CageSettings { + pub kind: CageType, + /// Distance-based cage offsets (slider range 0..=0.05) + pub max_frontal: f32, + pub max_rear: f32, + pub relative_to_bounding_box: bool, + pub average_normals: bool, +} + +impl Default for CageSettings { + fn default() -> Self { + Self { kind: CageType::DistanceBased, max_frontal: 0.01, max_rear: 0.01, relative_to_bounding_box: true, average_normals: true } + } +} diff --git a/crates/core/src/bake/cage_type.rs b/crates/core/src/bake/cage_type.rs new file mode 100644 index 00000000..1985055f --- /dev/null +++ b/crates/core/src/bake/cage_type.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CageType { + #[default] + DistanceBased, + CustomFile, +} diff --git a/crates/core/src/bake/common_bake_settings.rs b/crates/core/src/bake/common_bake_settings.rs new file mode 100644 index 00000000..3f743fff --- /dev/null +++ b/crates/core/src/bake/common_bake_settings.rs @@ -0,0 +1,34 @@ +use super::{BakeAntialiasing, BakeResolution}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CommonBakeSettings { + pub is_enabled: bool, + pub resolution: BakeResolution, + /// None locks both axes to the same resolution + pub resolution_height: Option, + pub antialiasing: BakeAntialiasing, + /// Padding width in pixels (0..=128) + pub dilation: u32, + pub apply_diffusion: bool, +} + +impl Default for CommonBakeSettings { + fn default() -> Self { + Self { + is_enabled: true, + resolution: BakeResolution::R2048, + resolution_height: None, + antialiasing: BakeAntialiasing::None, + dilation: 1, + apply_diffusion: true, + } + } +} + +impl CommonBakeSettings { + pub fn output_size(&self) -> (u32, u32) { + (self.resolution.pixels(), self.resolution_height.unwrap_or(self.resolution).pixels()) + } +} diff --git a/crates/core/src/bake/curvature_method.rs b/crates/core/src/bake/curvature_method.rs new file mode 100644 index 00000000..2085c85b --- /dev/null +++ b/crates/core/src/bake/curvature_method.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CurvatureMethod { + #[default] + NormalMap, + Mesh, +} diff --git a/crates/core/src/bake/curvature_settings.rs b/crates/core/src/bake/curvature_settings.rs new file mode 100644 index 00000000..d67138b8 --- /dev/null +++ b/crates/core/src/bake/curvature_settings.rs @@ -0,0 +1,16 @@ +use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct CurvatureSettings { + pub method: CurvatureMethod, + pub normal_map: NormalMapCurvatureSettings, + pub mesh: MeshCurvatureSettings, +} + +impl Default for CurvatureSettings { + fn default() -> Self { + Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() } + } +} diff --git a/crates/core/src/bake/ground_plane_settings.rs b/crates/core/src/bake/ground_plane_settings.rs new file mode 100644 index 00000000..077c9bfd --- /dev/null +++ b/crates/core/src/bake/ground_plane_settings.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct GroundPlaneSettings { + pub enabled: bool, + /// Offset in mesh units (0..=100) + pub offset: f32, +} diff --git a/crates/core/src/bake/height_normalization.rs b/crates/core/src/bake/height_normalization.rs new file mode 100644 index 00000000..84113725 --- /dev/null +++ b/crates/core/src/bake/height_normalization.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum HeightNormalization { + RelativeToRayDistances, + #[default] + RelativeToLowMesh, + RelativeToMinMax, + Manual, +} diff --git a/crates/core/src/bake/height_settings.rs b/crates/core/src/bake/height_settings.rs new file mode 100644 index 00000000..4200acf5 --- /dev/null +++ b/crates/core/src/bake/height_settings.rs @@ -0,0 +1,15 @@ +use super::HeightNormalization; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct HeightSettings { + pub normalization: HeightNormalization, + pub scaling_divisor: f32, +} + +impl Default for HeightSettings { + fn default() -> Self { + Self { normalization: HeightNormalization::RelativeToLowMesh, scaling_divisor: 1.0 } + } +} diff --git a/crates/core/src/bake/high_poly_settings.rs b/crates/core/src/bake/high_poly_settings.rs new file mode 100644 index 00000000..414989cc --- /dev/null +++ b/crates/core/src/bake/high_poly_settings.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct HighPolySettings { + pub use_low_as_high: bool, + pub ignore_backface: bool, + pub low_suffix: String, + pub high_suffix: String, + pub ignore_backface_suffix: String, +} + +impl Default for HighPolySettings { + fn default() -> Self { + Self { + use_low_as_high: false, + ignore_backface: true, + low_suffix: "_low".into(), + high_suffix: "_high".into(), + ignore_backface_suffix: "_ignorebf".into(), + } + } +} diff --git a/crates/core/src/bake/id_color_generator.rs b/crates/core/src/bake/id_color_generator.rs new file mode 100644 index 00000000..33b279d7 --- /dev/null +++ b/crates/core/src/bake/id_color_generator.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum IdColorGenerator { + Random, + #[default] + HueShift, + Grayscale, +} diff --git a/crates/core/src/bake/id_color_source.rs b/crates/core/src/bake/id_color_source.rs new file mode 100644 index 00000000..6551f5fc --- /dev/null +++ b/crates/core/src/bake/id_color_source.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum IdColorSource { + VertexColor, + #[default] + MaterialColor, + FileId, + MeshId, + Submesh, +} diff --git a/crates/core/src/bake/id_settings.rs b/crates/core/src/bake/id_settings.rs new file mode 100644 index 00000000..3a7f20d4 --- /dev/null +++ b/crates/core/src/bake/id_settings.rs @@ -0,0 +1,9 @@ +use super::{IdColorGenerator, IdColorSource}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct IdSettings { + pub source: IdColorSource, + pub generator: IdColorGenerator, +} diff --git a/crates/core/src/bake/map_settings.rs b/crates/core/src/bake/map_settings.rs new file mode 100644 index 00000000..47849b6e --- /dev/null +++ b/crates/core/src/bake/map_settings.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; + +/// One map's enablement and typed parameters +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct MapSettings { + pub is_enabled: bool, + pub parameters: T, +} + +impl Default for MapSettings { + fn default() -> Self { + Self { is_enabled: true, parameters: T::default() } + } +} + +impl MapSettings { + pub fn disabled() -> Self { + Self { is_enabled: false, ..Self::default() } + } +} diff --git a/crates/core/src/bake/mesh_curvature_settings.rs b/crates/core/src/bake/mesh_curvature_settings.rs new file mode 100644 index 00000000..c1c61c05 --- /dev/null +++ b/crates/core/src/bake/mesh_curvature_settings.rs @@ -0,0 +1,30 @@ +use super::SelfOcclusion; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MeshCurvatureSettings { + pub rays: u32, + /// Radius (0.00001..=10 relative to bounds, 0.00001..=1 in mesh units) + pub sampling_radius: f32, + pub relative_to_bounding_box: bool, + pub self_intersection: SelfOcclusion, + pub auto_tonemapping: bool, + /// Value bounds (-10..=10) + pub value_min: f32, + pub value_max: f32, +} + +impl Default for MeshCurvatureSettings { + fn default() -> Self { + Self { + rays: 32, + sampling_radius: 0.001, + relative_to_bounding_box: true, + self_intersection: SelfOcclusion::Always, + auto_tonemapping: true, + value_min: -1.0, + value_max: -1.0, + } + } +} diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs new file mode 100644 index 00000000..c0a38673 --- /dev/null +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -0,0 +1,83 @@ +use super::{ + AmbientOcclusionSettings, BakedMap, BentNormalSettings, CurvatureSettings, HeightSettings, IdSettings, MapSettings, PositionSettings, ThicknessSettings, +}; +use serde::{Deserialize, Serialize}; + +/// Per-map configuration; enabled outputs are derived from these flags +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct MeshMapSettings { + pub normal: MapSettings, + pub world_normal: MapSettings, + pub id: MapSettings, + pub ao: MapSettings, + pub curvature: MapSettings, + pub position: MapSettings, + pub thickness: MapSettings, + pub height: MapSettings, + pub bent_normal: MapSettings, + pub opacity: MapSettings, +} + +impl Default for MeshMapSettings { + fn default() -> Self { + Self { + normal: MapSettings::default(), + world_normal: MapSettings::default(), + id: MapSettings::default(), + ao: MapSettings::default(), + curvature: MapSettings::default(), + position: MapSettings::default(), + thickness: MapSettings::default(), + height: MapSettings::disabled(), + bent_normal: MapSettings::disabled(), + opacity: MapSettings::disabled(), + } + } +} + +impl MeshMapSettings { + pub fn is_enabled(&self, map: BakedMap) -> bool { + match map { + BakedMap::Normal => self.normal.is_enabled, + BakedMap::WorldNormal => self.world_normal.is_enabled, + BakedMap::Id => self.id.is_enabled, + BakedMap::AmbientOcclusion => self.ao.is_enabled, + BakedMap::Curvature => self.curvature.is_enabled, + BakedMap::Position => self.position.is_enabled, + BakedMap::Thickness => self.thickness.is_enabled, + BakedMap::Height => self.height.is_enabled, + BakedMap::BentNormal => self.bent_normal.is_enabled, + BakedMap::Opacity => self.opacity.is_enabled, + } + } + + pub fn set_enabled(&mut self, map: BakedMap, is_enabled: bool) { + let enabled = match map { + BakedMap::Normal => &mut self.normal.is_enabled, + BakedMap::WorldNormal => &mut self.world_normal.is_enabled, + BakedMap::Id => &mut self.id.is_enabled, + BakedMap::AmbientOcclusion => &mut self.ao.is_enabled, + BakedMap::Curvature => &mut self.curvature.is_enabled, + BakedMap::Position => &mut self.position.is_enabled, + BakedMap::Thickness => &mut self.thickness.is_enabled, + BakedMap::Height => &mut self.height.is_enabled, + BakedMap::BentNormal => &mut self.bent_normal.is_enabled, + BakedMap::Opacity => &mut self.opacity.is_enabled, + }; + *enabled = is_enabled; + } + + pub fn enabled(&self) -> impl Iterator { + BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) + } + + pub fn select(&mut self, maps: impl IntoIterator) { + for map in BakedMap::ALL { + self.set_enabled(map, false); + } + for map in maps { + self.set_enabled(map, true); + } + } +} diff --git a/crates/core/src/bake/normal_map_curvature_settings.rs b/crates/core/src/bake/normal_map_curvature_settings.rs new file mode 100644 index 00000000..cb31b904 --- /dev/null +++ b/crates/core/src/bake/normal_map_curvature_settings.rs @@ -0,0 +1,15 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct NormalMapCurvatureSettings { + pub details: f32, + pub enable_seams: bool, + pub seams_intensity: f32, +} + +impl Default for NormalMapCurvatureSettings { + fn default() -> Self { + Self { details: 0.5, enable_seams: true, seams_intensity: 1.0 } + } +} diff --git a/crates/core/src/bake/position_axis.rs b/crates/core/src/bake/position_axis.rs new file mode 100644 index 00000000..0507e902 --- /dev/null +++ b/crates/core/src/bake/position_axis.rs @@ -0,0 +1,10 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PositionAxis { + #[default] + All, + X, + Y, + Z, +} diff --git a/crates/core/src/bake/position_mode.rs b/crates/core/src/bake/position_mode.rs new file mode 100644 index 00000000..b2f85005 --- /dev/null +++ b/crates/core/src/bake/position_mode.rs @@ -0,0 +1,13 @@ +use serde::{Deserialize, Serialize}; + +/// Position map normalization +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum PositionMode { + /// Each axis spans the bounding box (0..1 per axis) + BoundingBox, + /// One scale for every axis: the bounding sphere around the box centre (keeps proportions) + #[default] + BoundingSphere, + /// Keep mesh coordinates without normalization + None, +} diff --git a/crates/core/src/bake/position_normalization_scale.rs b/crates/core/src/bake/position_normalization_scale.rs new file mode 100644 index 00000000..ef51c8c3 --- /dev/null +++ b/crates/core/src/bake/position_normalization_scale.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum PositionNormalizationScale { + PerMaterial, + #[default] + FullScene, +} diff --git a/crates/core/src/bake/position_settings.rs b/crates/core/src/bake/position_settings.rs new file mode 100644 index 00000000..9fe62110 --- /dev/null +++ b/crates/core/src/bake/position_settings.rs @@ -0,0 +1,10 @@ +use super::{PositionAxis, PositionMode, PositionNormalizationScale}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct PositionSettings { + pub axis: PositionAxis, + pub normalization: PositionMode, + pub scale: PositionNormalizationScale, +} diff --git a/crates/core/src/bake/ray_distribution.rs b/crates/core/src/bake/ray_distribution.rs new file mode 100644 index 00000000..4d38a287 --- /dev/null +++ b/crates/core/src/bake/ray_distribution.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// How secondary rays spread over their cone +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum RayDistribution { + /// Cosine-weighted: more rays near the normal + #[default] + Cosine, + /// Uniform over the cone's solid angle + Uniform, +} diff --git a/crates/core/src/bake/ray_settings.rs b/crates/core/src/bake/ray_settings.rs new file mode 100644 index 00000000..5aa76651 --- /dev/null +++ b/crates/core/src/bake/ray_settings.rs @@ -0,0 +1,24 @@ +use super::RayDistribution; +use serde::{Deserialize, Serialize}; + +/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct RaySettings { + /// Rays per sample (settings range 1..=256) + pub rays: u32, + /// Minimum distance in the same units as max_distance (0.00001..=1) + pub min_distance: f32, + /// Maximum distance: 0.00001..=1 relative to the bounding box, or 0.00001..=10 in mesh units + pub max_distance: f32, + pub relative_to_bounding_box: bool, + /// Full cone angle around the normal in degrees (180 = the whole hemisphere) + pub spread: f32, + pub distribution: RayDistribution, +} + +impl Default for RaySettings { + fn default() -> Self { + RaySettings { rays: 64, min_distance: 0.00001, max_distance: 1.0, relative_to_bounding_box: true, spread: 180.0, distribution: RayDistribution::Cosine } + } +} diff --git a/crates/core/src/bake/self_occlusion.rs b/crates/core/src/bake/self_occlusion.rs new file mode 100644 index 00000000..a48f592d --- /dev/null +++ b/crates/core/src/bake/self_occlusion.rs @@ -0,0 +1,11 @@ +use serde::{Deserialize, Serialize}; + +/// Mesh filtering for occlusion, thickness and curvature rays +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum SelfOcclusion { + /// Every part occludes every other + #[default] + Always, + /// Only parts with the same mesh name (suffixes removed) occlude each other + SameMeshName, +} diff --git a/crates/core/src/bake/skew_settings.rs b/crates/core/src/bake/skew_settings.rs new file mode 100644 index 00000000..296bacbf --- /dev/null +++ b/crates/core/src/bake/skew_settings.rs @@ -0,0 +1,18 @@ +use serde::{Deserialize, Serialize}; + +/// Skew controls independent of the painted pixel asset +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SkewSettings { + pub edge_protection: bool, + /// Edge protection distance (0..=1), retained while protection is disabled + pub edge_distance: f32, + /// Edge protection contrast (0..=1) + pub edge_contrast: f32, +} + +impl Default for SkewSettings { + fn default() -> Self { + Self { edge_protection: false, edge_distance: 0.15, edge_contrast: 0.5 } + } +} diff --git a/crates/core/src/bake/thickness_normalization.rs b/crates/core/src/bake/thickness_normalization.rs new file mode 100644 index 00000000..1a01a86e --- /dev/null +++ b/crates/core/src/bake/thickness_normalization.rs @@ -0,0 +1,9 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ThicknessNormalization { + RelativeToRayDistances, + #[default] + RelativeToMinMax, + None, +} diff --git a/crates/core/src/bake/thickness_settings.rs b/crates/core/src/bake/thickness_settings.rs new file mode 100644 index 00000000..659391a2 --- /dev/null +++ b/crates/core/src/bake/thickness_settings.rs @@ -0,0 +1,20 @@ +use super::{RaySettings, SelfOcclusion, ThicknessNormalization}; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ThicknessSettings { + pub rays: RaySettings, + pub self_occlusion: SelfOcclusion, + pub normalization: ThicknessNormalization, +} + +impl Default for ThicknessSettings { + fn default() -> Self { + Self { + rays: RaySettings { max_distance: 0.1, ..RaySettings::default() }, + self_occlusion: SelfOcclusion::Always, + normalization: ThicknessNormalization::RelativeToMinMax, + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 80f1cafe..ae96b85e 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -7,11 +7,18 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake; pub mod blend; pub mod channel; pub mod layer; pub mod project; +pub use bake::{ + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, BentNormalSettings, + CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, + IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, NormalMapCurvatureSettings, PositionAxis, PositionMode, + PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewSettings, ThicknessNormalization, ThicknessSettings, +}; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ @@ -19,9 +26,8 @@ pub use layer::{ LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ - AoMixing, BakeMatch, BakeSettings, BakedMap, BlockScales, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, - MIN_RESOLUTION, NormalFormat, NormalMixing, PositionMode, Project, RayDistribution, RaySettings, SelfOcclusion, TextureSet, TileGrid, ToneMapping, - UDIM_RANGE, udim_at, + AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, + TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; #[derive(Debug, thiserror::Error, Clone, PartialEq)] diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index c144ec98..26d4f6e6 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -1,14 +1,14 @@ -//! The project: texture sets, their layer stacks, and project-wide settings. +//! The project: texture sets, their layer stacks, and project-wide settings use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub const FORMAT_VERSION: u32 = 1; -/// Maximum group nesting (also bounds recursion over hostile project files). +/// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -18,273 +18,6 @@ pub enum NormalFormat { DirectX, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub enum BakedMap { - Normal, - WorldNormal, - Id, - AmbientOcclusion, - Curvature, - Position, - Thickness, - Height, - /// World-space direction of least occlusion (packed like the world-space normal). - BentNormal, - /// 1 where the high poly covers the low poly (times the high poly's vertex alpha). - Opacity, - /// The high poly's vertex colors. - ColorMap, - /// Facing ratio towards [`BakeSettings::direction`] (0.5 = perpendicular). - WorldDirection, -} - -impl BakedMap { - pub const ALL: [BakedMap; 12] = [ - BakedMap::Normal, - BakedMap::WorldNormal, - BakedMap::Id, - BakedMap::AmbientOcclusion, - BakedMap::Curvature, - BakedMap::Position, - BakedMap::Thickness, - BakedMap::Height, - BakedMap::BentNormal, - BakedMap::Opacity, - BakedMap::ColorMap, - BakedMap::WorldDirection, - ]; - pub fn label(self) -> &'static str { - match self { - BakedMap::Normal => "Normal", - BakedMap::WorldNormal => "World space normal", - BakedMap::Id => "ID", - BakedMap::AmbientOcclusion => "Ambient occlusion", - BakedMap::Curvature => "Curvature", - BakedMap::Position => "Position", - BakedMap::Thickness => "Thickness", - BakedMap::Height => "Height", - BakedMap::BentNormal => "Bent normals", - BakedMap::Opacity => "Opacity", - BakedMap::ColorMap => "Color map", - BakedMap::WorldDirection => "World space direction", - } - } - pub fn id(self) -> &'static str { - match self { - BakedMap::Normal => "normal_base", - BakedMap::WorldNormal => "world_space_normals", - BakedMap::Id => "id", - BakedMap::AmbientOcclusion => "ambient_occlusion", - BakedMap::Curvature => "curvature", - BakedMap::Position => "position", - BakedMap::Thickness => "thickness", - BakedMap::Height => "height", - BakedMap::BentNormal => "bent_normals", - BakedMap::Opacity => "opacity", - BakedMap::ColorMap => "color_map", - BakedMap::WorldDirection => "world_space_direction", - } - } - /// The identifier shared with MaterialCraft (graph inputs fed from this map). - pub fn interop_id(self) -> &'static str { - match self { - BakedMap::Normal => "normal", - BakedMap::WorldNormal => "worldNormal", - BakedMap::Id => "id", - BakedMap::AmbientOcclusion => "ambientOcclusion", - BakedMap::Curvature => "curvature", - BakedMap::Position => "position", - BakedMap::Thickness => "thickness", - BakedMap::Height => "height", - BakedMap::BentNormal => "bentNormal", - BakedMap::Opacity => "opacity", - BakedMap::ColorMap => "colorMap", - BakedMap::WorldDirection => "worldDirection", - } - } - /// The map a MaterialCraft graph input `identifier` reads: its shared or own id, ignoring - /// case and underscores (`ambient_occlusion` = `ambientOcclusion`). - pub fn for_input(identifier: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace(['_', '-', ' '], ""); - let want = norm(identifier); - BakedMap::ALL.into_iter().find(|m| norm(m.interop_id()) == want || norm(m.id()) == want) - } - /// Components stored (3 for vector maps, 1 for scalar maps). - pub fn components(self) -> usize { - match self { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal | BakedMap::ColorMap => 3, - _ => 1, - } - } - /// Value where nothing was baked (uncovered texels, missing maps). - pub fn neutral(self) -> [f32; 3] { - match self { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0], - BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3], - BakedMap::Curvature | BakedMap::Height | BakedMap::WorldDirection => [0.5; 3], - BakedMap::Id | BakedMap::Position | BakedMap::Opacity | BakedMap::ColorMap => [0.0; 3], - } - } - pub fn parse(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], ""); - BakedMap::ALL.into_iter().find(|m| norm(m.label()) == norm(s) || norm(m.id()) == norm(s) || norm(&format!("{m:?}")) == norm(s)) - } -} - -/// How low-poly parts find their high-poly counterparts (the bake "Match" option). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum BakeMatch { - /// Every low-poly part sees every high-poly part. - #[default] - Always, - /// A low-poly part sees only high-poly parts of the same name once the suffixes are removed - /// (`wheel_low` ↔ `wheel_high`). - ByMeshName, -} - -/// How secondary rays spread over their cone. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum RayDistribution { - /// Cosine-weighted: more rays near the normal. - #[default] - Cosine, - /// Uniform over the cone's solid angle. - Uniform, -} - -/// Which geometry occludes ambient occlusion and bent-normal rays. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum SelfOcclusion { - /// Every part occludes every other. - #[default] - Always, - /// Only parts with the same mesh name (suffixes removed) occlude each other. - SameMeshName, -} - -/// Position map normalization. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum PositionMode { - /// Each axis spans the bounding box (0..1 per axis). - #[default] - BoundingBox, - /// One scale for every axis: the bounding sphere around the box centre (keeps proportions). - BoundingSphere, -} - -/// World space direction map encoding. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum DirectionMode { - /// −1..1 to 0..1: mid grey where the surface is perpendicular to the direction. - #[default] - Signed, - /// 0..1: black where the surface is perpendicular or faces away. - Positive, -} - -/// Secondary-ray parameters of one map (ambient occlusion, thickness, bent normals). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct RaySettings { - /// Rays per sample. - pub rays: u32, - /// Max ray length relative to the bounding-box diagonal. - pub max_distance: f32, - /// Full cone angle around the normal in degrees (180 = the whole hemisphere). - pub spread: f32, - pub distribution: RayDistribution, -} - -impl Default for RaySettings { - fn default() -> Self { - RaySettings { rays: 32, max_distance: 0.25, spread: 180.0, distribution: RayDistribution::Cosine } - } -} - -/// Bake parameters (the common parameters plus the per-map parameters). Fields missing -/// from older projects take their defaults. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct BakeSettings { - /// Included by "Bake selected textures". - pub enabled: bool, - pub resolution: u32, - /// Supersampling per axis: 1 (none), 2, 4 or 8. - pub antialiasing: u32, - pub dilation: u32, - /// Ambient occlusion rays. - pub ao: RaySettings, - /// Ambient occlusion and bent-normal rays ignore surfaces they hit from behind. - pub ao_ignore_backface: bool, - pub ao_self_occlusion: SelfOcclusion, - /// Thickness rays (into the surface). - pub thickness: RaySettings, - /// Bent-normal rays (they follow the ambient occlusion's occluder rules). - pub bent_normal: RaySettings, - /// Curvature strength. - pub curvature_strength: f32, - /// Curvature from the baked normal map instead of the mesh. - pub curvature_from_normal: bool, - /// Sampling radius of curvature from the normal map, in texels (0: by resolution). - pub curvature_radius: u32, - pub position_mode: PositionMode, - /// World-space direction of the "World space direction" map. - pub direction: [f32; 3], - pub direction_mode: DirectionMode, - pub maps: BTreeSet, - /// Bake from the low poly itself ("Use low poly mesh as high poly"). - pub use_low_as_high: bool, - /// Ray start distance in front of the low poly, relative to the bbox diagonal. - pub max_frontal: f32, - pub max_rear: f32, - /// Cast rays along normals averaged over hard edges (no gaps at split normals). - pub average_normals: bool, - pub matching: BakeMatch, - pub low_suffix: String, - pub high_suffix: String, -} - -impl Default for BakeSettings { - fn default() -> Self { - BakeSettings { - enabled: true, - resolution: 1024, - antialiasing: 1, - dilation: 16, - ao: RaySettings::default(), - ao_ignore_backface: false, - ao_self_occlusion: SelfOcclusion::Always, - // Thickness is hit distance / max distance: long rays turn thin parts almost black. - thickness: RaySettings { max_distance: 0.1, ..RaySettings::default() }, - bent_normal: RaySettings::default(), - curvature_strength: 1.0, - curvature_from_normal: false, - curvature_radius: 0, - position_mode: PositionMode::BoundingBox, - direction: [0.0, 1.0, 0.0], - direction_mode: DirectionMode::Signed, - maps: [ - BakedMap::Normal, - BakedMap::WorldNormal, - BakedMap::Id, - BakedMap::AmbientOcclusion, - BakedMap::Curvature, - BakedMap::Position, - BakedMap::Thickness, - ] - .into_iter() - .collect(), - use_low_as_high: true, - max_frontal: 0.01, - max_rear: 0.01, - average_normals: true, - matching: BakeMatch::Always, - low_suffix: "_low".into(), - high_suffix: "_high".into(), - } - } -} - #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum NormalMixing { #[default] @@ -1027,34 +760,21 @@ mod tests { } #[test] - fn per_map_bake_settings_round_trip_and_old_projects_load() { - let mut p = project(); - let b = &mut p.texture_sets[0].bake; - b.ao = RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform }; - b.ao_ignore_backface = true; - b.ao_self_occlusion = SelfOcclusion::SameMeshName; - b.thickness.spread = 60.0; - b.bent_normal.rays = 8; - b.curvature_radius = 3; - b.position_mode = PositionMode::BoundingSphere; - b.direction_mode = DirectionMode::Positive; - let json = serde_json::to_string(&p).unwrap(); - assert_eq!(serde_json::from_str::(&json).unwrap(), p); - // Settings saved before per-map rays (one shared ray count) load with the defaults. - let mut v: serde_json::Value = serde_json::from_str(&json).unwrap(); - let old = v["texture_sets"][0]["bake"].as_object_mut().unwrap(); - for k in ["ao", "ao_ignore_backface", "ao_self_occlusion", "thickness", "bent_normal", "curvature_radius", "position_mode", "direction_mode"] { - old.remove(k); - } - old.insert("rays".into(), 64.into()); - old.insert("max_distance".into(), 0.3.into()); - let back: Project = serde_json::from_value(v).unwrap(); - let d = BakeSettings::default(); - let b = &back.texture_sets[0].bake; - assert_eq!( - (b.ao, b.thickness, b.bent_normal, b.ao_self_occlusion, b.position_mode), - (d.ao, d.thickness, d.bent_normal, d.ao_self_occlusion, d.position_mode) - ); + fn per_map_bake_settings_round_trip() { + use crate::{BackfaceMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; + + let mut project = project(); + let settings = &mut project.texture_sets[0].bake; + settings.maps.ao.parameters.rays = + RaySettings { rays: 96, max_distance: 0.4, spread: 120.0, distribution: RayDistribution::Uniform, ..RaySettings::default() }; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::Always; + settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + settings.maps.thickness.parameters.rays.spread = 60.0; + settings.maps.bent_normal.parameters.rays.rays = 8; + settings.maps.position.parameters.normalization = PositionMode::BoundingSphere; + + let json = serde_json::to_string(&project).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), project); } #[test] diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs new file mode 100644 index 00000000..9264e3f4 --- /dev/null +++ b/crates/core/tests/bake_settings.rs @@ -0,0 +1,188 @@ +#![recursion_limit = "256"] + +use serde::{Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; +use texturecraft_core::{self as bake, BakedMap, Project, TextureSet}; + +#[test] +fn reference_defaults_cover_common_and_per_map_settings() { + let rays = json!({ + "rays": 64, "min_distance": 0.00001, "max_distance": 1.0, + "relative_to_bounding_box": true, "spread": 180.0, "distribution": "Cosine" + }); + let mut thickness_rays = rays.clone(); + thickness_rays["max_distance"] = json!(0.1); + let mut expected = json!({ + "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true}, + "high_poly": {"use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, + "cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true}, + "skew": {"edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "id": {"source": "MaterialColor", "generator": "HueShift"}, + "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, + "curvature": { + "method": "NormalMap", + "normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0}, + "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": -1.0} + }, + "position": {"axis": "All", "normalization": "BoundingSphere", "scale": "FullScene"}, + "thickness": {"rays": thickness_rays, "self_occlusion": "Always", "normalization": "RelativeToMinMax"}, + "height": {"normalization": "RelativeToLowMesh", "scaling_divisor": 1.0}, + "bent_normal": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always"} + }); + + let mut maps = serde_json::Map::new(); + for key in ["id", "ao", "curvature", "position", "thickness", "height", "bent_normal"] { + let parameters = expected.as_object_mut().unwrap().remove(key).unwrap(); + maps.insert(key.into(), json!({"is_enabled": !["height", "bent_normal"].contains(&key), "parameters": parameters})); + } + for key in ["normal", "world_normal", "opacity"] { + maps.insert(key.into(), json!({"is_enabled": key != "opacity", "parameters": null})); + } + expected["maps"] = Value::Object(maps); + + // Normalize the expected JSON floats to f32 before comparing every value + let decoded: bake::BakeSettings = serde_json::from_value(expected.clone()).unwrap(); + assert_eq!(bake::BakeSettings::default(), decoded); + assert_eq!(serde_json::from_str::("{}").unwrap(), decoded); + assert_eq!(decoded.common.output_size(), (2048, 2048)); + + fn assert_shape(actual: &Value, expected: &Value) { + if let (Some(actual), Some(expected)) = (actual.as_object(), expected.as_object()) { + assert_eq!(actual.keys().collect::>(), expected.keys().collect::>()); + for (key, expected) in expected { + assert_shape(&actual[key], expected); + } + } + } + assert_shape(&serde_json::to_value(decoded).unwrap(), &expected); + assert_eq!(BakedMap::ALL.len(), 10); + for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] { + assert_eq!(BakedMap::parse(name), None); + } +} + +fn assert_choices(choices: &[T]) { + for choice in choices { + let encoded = serde_json::to_value(choice).unwrap(); + assert!(encoded.is_string()); + assert_eq!(serde_json::from_value::(encoded).unwrap(), *choice); + } + + for invalid in [json!(true), json!(false), json!(1), json!(3), json!("invalid")] { + assert!(serde_json::from_value::(invalid).is_err()); + } +} + +#[test] +fn all_dropdowns_store_enum_choices() { + assert_choices(&bake::BakeResolution::ALL); + assert_choices(&bake::BakeAntialiasing::ALL); + assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]); + assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]); + assert_choices(&[ + bake::IdColorSource::VertexColor, + bake::IdColorSource::MaterialColor, + bake::IdColorSource::FileId, + bake::IdColorSource::MeshId, + bake::IdColorSource::Submesh, + ]); + assert_choices(&[bake::IdColorGenerator::Random, bake::IdColorGenerator::HueShift, bake::IdColorGenerator::Grayscale]); + assert_choices(&[bake::RayDistribution::Uniform, bake::RayDistribution::Cosine]); + assert_choices(&[bake::BackfaceMode::Never, bake::BackfaceMode::Always, bake::BackfaceMode::ByMeshName]); + assert_choices(&[bake::SelfOcclusion::Always, bake::SelfOcclusion::SameMeshName]); + assert_choices(&[bake::AmbientOcclusionAttenuation::None, bake::AmbientOcclusionAttenuation::Smooth, bake::AmbientOcclusionAttenuation::Linear]); + assert_choices(&[bake::PositionAxis::All, bake::PositionAxis::X, bake::PositionAxis::Y, bake::PositionAxis::Z]); + assert_choices(&[bake::PositionMode::BoundingBox, bake::PositionMode::BoundingSphere, bake::PositionMode::None]); + assert_choices(&[bake::PositionNormalizationScale::PerMaterial, bake::PositionNormalizationScale::FullScene]); + assert_choices(&[bake::ThicknessNormalization::RelativeToRayDistances, bake::ThicknessNormalization::RelativeToMinMax, bake::ThicknessNormalization::None]); + assert_choices(&[ + bake::HeightNormalization::RelativeToRayDistances, + bake::HeightNormalization::RelativeToLowMesh, + bake::HeightNormalization::RelativeToMinMax, + bake::HeightNormalization::Manual, + ]); +} + +#[test] +fn components_keep_their_own_defaults() { + let settings: bake::BakeSettings = serde_json::from_value(json!({ + "common": {}, "cage": {}, "high_poly": {}, "skew": {}, + "maps": { + "ao": {"is_enabled": true, "parameters": {"ground_plane": {}}}, + "curvature": {"is_enabled": true, "parameters": {"normal_map": {}, "mesh": {}}} + } + })) + .unwrap(); + assert_eq!(settings, bake::BakeSettings::default()); + assert_eq!(settings.maps.thickness.parameters.rays.max_distance, 0.1); +} + +#[test] +fn nested_settings_round_trip_per_texture_set() { + let mut settings = bake::BakeSettings::default(); + settings.common.resolution = bake::BakeResolution::R16; + settings.common.resolution_height = Some(bake::BakeResolution::R8192); + settings.common.antialiasing = bake::BakeAntialiasing::Subsampling8x8; + settings.common.apply_diffusion = false; + settings.high_poly.ignore_backface_suffix = "_two_sided".into(); + settings.cage.kind = bake::CageType::CustomFile; + settings.skew.edge_protection = true; + settings.maps.id.parameters.source = bake::IdColorSource::Submesh; + settings.maps.id.parameters.generator = bake::IdColorGenerator::Grayscale; + settings.maps.ao.parameters.ignore_backface = bake::BackfaceMode::ByMeshName; + settings.maps.ao.parameters.ground_plane = bake::GroundPlaneSettings { enabled: true, offset: 5.0 }; + settings.maps.curvature.parameters.method = bake::CurvatureMethod::Mesh; + settings.maps.curvature.parameters.normal_map.details = 0.25; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.25; + settings.maps.curvature.parameters.mesh.auto_tonemapping = false; + settings.maps.position.parameters.axis = bake::PositionAxis::Z; + settings.maps.position.parameters.normalization = bake::PositionMode::None; + settings.maps.thickness.parameters.normalization = bake::ThicknessNormalization::None; + settings.maps.height.parameters.normalization = bake::HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 2.0; + settings.maps.bent_normal.parameters.ignore_backface = bake::BackfaceMode::ByMeshName; + + let mut project = Project::new("Bake options", "builtin:plane"); + project.texture_sets.push(TextureSet::new("A", 0, 128)); + project.texture_sets.push(TextureSet::new("B", 1, 128)); + project.texture_sets[0].bake = settings; + + let reloaded: Project = serde_json::from_str(&serde_json::to_string(&project).unwrap()).unwrap(); + assert_eq!(project, reloaded); + assert_eq!(reloaded.texture_sets[0].bake.common.output_size(), (16, 8192)); + assert_eq!(reloaded.texture_sets[1].bake, bake::BakeSettings::default()); +} + +#[test] +fn malformed_settings_are_rejected() { + for invalid in [ + json!({"maps": {"ao": {"is_enabled": "yes", "parameters": {}}}}), + json!({"maps": {"ao": {"is_enabled": true, "parameters": {"rays": {"min_distance": "bad"}}}}}), + json!({"common": {"resolution_height": -1}}), + json!({"maps": {"curvature": {"is_enabled": true, "parameters": {"method": true}}}}), + Value::Null, + ] { + assert!(serde_json::from_value::(invalid).is_err()); + } +} + +#[test] +fn map_enablement_is_owned_by_each_map() { + let mut settings = bake::BakeSettings::default(); + settings.maps.ao.parameters.rays.rays = 23; + settings.maps.ao.is_enabled = false; + settings.maps.height.is_enabled = true; + assert!(!settings.maps.enabled().any(|map| map == BakedMap::AmbientOcclusion)); + assert!(settings.maps.enabled().any(|map| map == BakedMap::Height)); + + let encoded = serde_json::to_value(&settings).unwrap(); + assert_eq!(encoded["maps"]["ao"]["is_enabled"], false); + assert!(encoded.get("selection").is_none()); + let mut reloaded: bake::BakeSettings = serde_json::from_value(encoded).unwrap(); + assert_eq!(reloaded, settings); + + reloaded.maps.select([BakedMap::AmbientOcclusion]); + assert_eq!(reloaded.maps.enabled().collect::>(), [BakedMap::AmbientOcclusion]); + assert!(reloaded.maps.ao.is_enabled); + assert_eq!(reloaded.maps.ao.parameters.rays.rays, 23); +} diff --git a/crates/engine/src/auto_rebake.rs b/crates/engine/src/auto_rebake.rs deleted file mode 100644 index 8c37a83b..00000000 --- a/crates/engine/src/auto_rebake.rs +++ /dev/null @@ -1,209 +0,0 @@ -//! Auto-rebake: one mesh map that bakes itself again when what it was baked from changes. -//! -//! The map is chosen with `bake.autoRebake`. From then on, [`Session::auto_rebake_due`] names the -//! texture sets whose bake inputs (the set's bake settings except the list of maps, the low poly, -//! the high polys, the cage and the skew map) differ from those of their last bake of that map. -//! The apps poll it each frame and bake the due sets in the background; `bake.autoRebake.run` -//! does the same thing once, blocking, for agents and scripts. -//! -//! A set only takes part once it has the map baked at its current output size: Auto-rebake -//! keeps a bake up to date, it doesn't start one, and it never leaves a set's maps at two sizes. -//! The choice isn't part of the project. - -use std::collections::BTreeMap; -use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; -use std::sync::{Arc, Weak}; - -use serde_json::{Value, json}; -use texturecraft_bake::Progress; -use texturecraft_core::BakedMap; - -use crate::bake_cmds::BakeTask; -use crate::commands::{CommandSpec, always, bad, boolp}; -use crate::{Result, Session, cmd}; - -/// Which map rebakes itself, and what each texture set was last baked from. -#[derive(Clone, Debug, Default)] -pub struct AutoRebake { - pub map: Option, - /// Fingerprint of each set's bake inputs when it last baked [`AutoRebake::map`]. - seen: BTreeMap, - /// Fingerprint taken when a set's bake started, kept when that bake finishes. - pending: BTreeMap, - /// What each map image in use was baked from. Undo and redo bring back an older image; its own - /// entry says its inputs no longer match. Weak, so a freed image doesn't linger and its - /// address can't be taken by a new one. - origin: Vec<(Weak>, u64)>, -} - -impl AutoRebake { - fn remember(&mut self, image: &Arc>, key: u64) { - self.origin.retain(|(w, _)| w.strong_count() > 0); - self.origin.retain(|(w, _)| !std::ptr::eq(w.as_ptr(), Arc::as_ptr(image))); - self.origin.push((Arc::downgrade(image), key)); - } - - fn origin_of(&self, image: &Arc>) -> Option { - self.origin.iter().find(|(w, _)| std::ptr::eq(w.as_ptr(), Arc::as_ptr(image))).map(|(_, k)| *k) - } -} - -pub fn specs() -> Vec { - vec![ - cmd!( - "bake.autoRebake", - "Auto-rebake", - [], - None, - "{map?: map id (e.g. \"normal_base\", \"height\") to keep up to date, or null / off: true to turn it off; no params: just report} → {map, due: [texture sets that need a rebake]}", - always, - auto_rebake - ), - cmd!( - "bake.autoRebake.run", - "Run Auto-rebake", - [], - None, - "{cpu?: true (skip the GPU)} → {rebaked: [texture sets]}: bakes the Auto-rebake map of every set whose bake inputs changed since it was last baked, now", - always, - auto_rebake_run - ), - ] -} - -impl Session { - /// A fingerprint of everything a bake of texture set `ts` is made from, except which maps it - /// makes. - pub fn bake_inputs_key(&self, ts: usize) -> Option { - let set = self.doc.project.texture_sets.get(ts)?; - let mut settings = set.bake.clone(); - settings.maps.clear(); - settings.enabled = true; - let mut h = DefaultHasher::new(); - serde_json::to_string(&settings).ok()?.hash(&mut h); - (Arc::as_ptr(&self.mesh) as usize).hash(&mut h); - for m in &self.bake_meshes.high { - (Arc::as_ptr(&m.mesh) as usize).hash(&mut h); - } - self.bake_meshes.cage.as_ref().map(|c| Arc::as_ptr(&c.mesh) as usize).hash(&mut h); - (self.bake_meshes.skew.is_some(), self.bake_meshes.skew_rev).hash(&mut h); - Some(h.finish()) - } - - /// Texture sets whose Auto-rebake map is out of date. A set seen for the first time (a project - /// just opened, a bake from before Auto-rebake was on) is taken as up to date. - pub fn auto_rebake_due(&mut self) -> Vec { - let Some(map) = self.auto_rebake.map else { return Vec::new() }; - let mut due = Vec::new(); - for ts in 0..self.doc.project.texture_sets.len() { - let Some(set) = self.doc.project.texture_sets.get(ts).filter(|t| t.bake.enabled) else { continue }; - let columns = set.tile_grid().map_or(1, |g| g.cols); - let baked = self.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map) && b.resolution == set.bake.resolution.saturating_mul(columns)); - let Some(key) = self.bake_inputs_key(ts).filter(|_| baked) else { continue }; - let image = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned(); - // An image whose inputs are known is judged by them (this is what undo is caught by); - // one not seen before is taken as up to date, like a project just opened. - match (image.as_ref().and_then(|i| self.auto_rebake.origin_of(i)), self.auto_rebake.seen.get(&ts)) { - (Some(made_from), _) if made_from != key => due.push(ts), - (Some(_), _) => {} - (None, Some(seen)) if *seen != key => due.push(ts), - (None, Some(_)) => {} - (None, None) => { - self.auto_rebake.seen.insert(ts, key); - if let Some(image) = &image { - self.auto_rebake.remember(image, key); - } - } - } - } - due - } - - /// Call right before building the bake task of `ts`: remembers what it is baked from, so a - /// finished bake of the Auto-rebake map marks the set up to date (and a change made while it - /// ran still triggers another). - pub fn begin_bake(&mut self, ts: usize) { - if let Some(key) = self.bake_inputs_key(ts) { - self.auto_rebake.pending.insert(ts, key); - } - } - - /// The bake task of `ts` restricted to one map (Auto-rebake's: the other maps stay as they are). - pub fn bake_task_for(&self, ts: usize, only: Option) -> Result { - let mut task = self.bake_task(ts)?; - if let Some(m) = only { - task.settings.maps = std::iter::once(m).collect(); - } - Ok(task) - } - - /// Records a finished bake: when it made the Auto-rebake map, the set is up to date. - pub(crate) fn note_baked(&mut self, ts: usize, mut made: impl Iterator) { - let key = self.auto_rebake.pending.remove(&ts); - if let (Some(key), Some(map)) = (key, self.auto_rebake.map) - && made.any(|m| m == map) - { - self.auto_rebake.seen.insert(ts, key); - if let Some(image) = self.doc.baked.get(&ts).and_then(|b| b.maps.get(&map)).cloned() { - self.auto_rebake.remember(&image, key); - } - } - } - - /// Records bakes of `sets` that were cancelled, failed or never started: Auto-rebake leaves - /// those sets alone until their bake inputs change again, instead of retrying every frame. - pub fn bake_abandoned(&mut self, sets: impl IntoIterator) { - for ts in sets { - if let Some(key) = self.auto_rebake.pending.remove(&ts).or_else(|| self.bake_inputs_key(ts)) { - self.auto_rebake.seen.insert(ts, key); - // The map as it stands is left alone for these inputs. - let image = self.auto_rebake.map.and_then(|m| self.doc.baked.get(&ts)?.maps.get(&m).cloned()); - if let Some(image) = image { - self.auto_rebake.remember(&image, key); - } - } - } - } - - /// Bakes every due set's Auto-rebake map now (blocking); returns the sets. - pub fn auto_rebake_now(&mut self, cpu: bool) -> Result> { - let due = self.auto_rebake_due(); - let map = self.auto_rebake.map; - for &ts in &due { - self.begin_bake(ts); - let mut task = self.bake_task_for(ts, map)?; - if cpu { - task.tracer = None; - } - let out = task.run(&Progress::new())?; - self.apply_bake(ts, out)?; - } - Ok(due) - } -} - -fn state(s: &mut Session) -> Value { - json!({ "map": s.auto_rebake.map.map(BakedMap::id), "due": s.auto_rebake_due() }) -} - -fn auto_rebake(s: &mut Session, p: &Value) -> Result { - if boolp(p, "off") == Some(true) || p.get("map").is_some_and(Value::is_null) { - s.auto_rebake = AutoRebake::default(); - } else if let Some(id) = p.get("map") { - let map = id.as_str().and_then(BakedMap::parse).ok_or_else(|| bad("bake.autoRebake", format!("unknown mesh map {id}")))?; - if s.auto_rebake.map != Some(map) { - s.auto_rebake = AutoRebake { map: Some(map), ..AutoRebake::default() }; - } - } - Ok(state(s)) -} - -fn auto_rebake_run(s: &mut Session, p: &Value) -> Result { - if s.auto_rebake.map.is_none() { - return Err(bad("bake.autoRebake.run", "no Auto-rebake map is set; run bake.autoRebake {map} first")); - } - let rebaked = s.auto_rebake_now(boolp(p, "cpu") == Some(true))?; - s.update(); - Ok(json!({ "rebaked": rebaked })) -} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake_cmds.rs index 6bd3ea67..158d74f0 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake_cmds.rs @@ -6,9 +6,11 @@ use std::collections::BTreeSet; use std::sync::{Arc, OnceLock}; use serde_json::{Value, json}; -use texturecraft_bake::rays::Tracer; +use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, MAX_RAYS, Progress, SkewMap, bake, bake_on}; -use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_core::{ + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, +}; use texturecraft_geom::{BaseColor, Bvh, Mesh}; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; @@ -30,7 +32,7 @@ pub fn specs() -> Vec { "Bake settings", [], None, - "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureStrength?, curvatureFromNormal?, curvatureRadius?: texels (0 = auto), positionMode?: boundingBox|boundingSphere, direction?: [x,y,z], directionMode?: signed|positive, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, matching?: always|byMeshName, lowSuffix?, highSuffix?}", + "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", always, settings ), @@ -39,7 +41,7 @@ pub fn specs() -> Vec { "Add high definition mesh", [], None, - "{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer feed the color map)", + "{path} — a mesh file (glb, gltf, fbx, dae, usd, usda, usdc, usdz, abc, obj, ply, stl; base color textures from glTF, embedded FBX media, usdz packages and image files next to a .gltf or USD layer supply opacity)", always, high_add ), @@ -56,7 +58,7 @@ pub fn specs() -> Vec { "Set skew correction", [], None, - "{value?: 0..1 (a constant map, default 1) | path: a greyscale image over the UV atlas (white turns the rays onto the base normal, black keeps the cage's averaged direction), edgeDistance?: fraction of the mesh diagonal over which hard edges hold the correction back (default 0), edgeContrast?: falloff exponent (default 1), base?: mesh|triangle (default mesh)} → {skew}. Applies to the transfer rays of a bake from the built-in distance cage; a cage mesh ignores it", + "{value?: 0..1 (a constant map, default 1) | path: a greyscale image over the UV atlas (white turns the rays onto the base normal, black keeps the cage's averaged direction), edgeDistance?: fraction of the mesh diagonal over which hard edges hold the correction back (default 0), edgeContrast?: falloff exponent (default 1)} → {skew}. Applies to the transfer rays of a bake from the built-in distance cage; a cage mesh ignores it", always, skew_set ), @@ -197,7 +199,7 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { impl Session { pub fn bake_task(&self, ts: usize) -> Result { let set = self.doc.project.texture_set(ts)?; - let high = if set.bake.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; + let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; let cage = high.as_ref().and(self.bake_meshes.cage.as_ref()).map(|c| c.mesh.clone()); let skew = high.as_ref().and(self.bake_meshes.skew.clone()); let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); @@ -208,7 +210,6 @@ impl Session { /// Store a finished bake (one undo step). pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> { self.log.push(format!("Baked texture set {ts} ({})", out.tracer)); - let made: Vec = out.maps.keys().copied().collect(); self.edit("Bake mesh maps", |s| { let maps: BTreeSet = out.maps.keys().copied().collect(); let entry = s.doc.baked.entry(ts).or_default(); @@ -219,13 +220,11 @@ impl Session { s.doc.project.texture_set_mut(ts)?.baked.extend(maps); Ok(()) })?; - self.note_baked(ts, made.into_iter()); Ok(()) } /// Bake texture set `ts` now (blocking), on the CPU when `cpu`; returns where the rays ran. pub fn bake_now(&mut self, ts: usize, cpu: bool) -> Result { - self.begin_bake(ts); let mut task = self.bake_task(ts)?; if cpu { task.tracer = None; @@ -248,7 +247,7 @@ impl Session { self.bake_meshes.high.push(m); self.bake_meshes.rebuild(); for set in &mut self.doc.project.texture_sets { - set.bake.use_low_as_high = false; + set.bake.high_poly.use_low_as_high = false; } self.modified = true; Ok(name) @@ -310,14 +309,7 @@ impl Session { /// The skew map of a project file, if it passes the baker's checks. pub(crate) fn load_skew(&mut self, skew: Option) { let Some(k) = skew else { return }; - let map = SkewMap { - width: k.width, - height: k.height, - values: k.values, - edge_distance: k.edge_distance, - edge_contrast: k.edge_contrast, - per_triangle: k.per_triangle, - }; + let map = SkewMap { width: k.width, height: k.height, values: k.values, edge_distance: k.edge_distance, edge_contrast: k.edge_contrast }; match map.validate() { Ok(()) => { self.bake_meshes.skew = Some(Arc::new(map)); @@ -336,7 +328,6 @@ impl Session { values: k.values.clone(), edge_distance: k.edge_distance, edge_contrast: k.edge_contrast, - per_triangle: k.per_triangle, }) } @@ -350,9 +341,8 @@ impl Session { /// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). pub fn meshes_json(s: &Session) -> Value { let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); - let skew = s.bake_meshes.skew.as_ref().map(|k| { - json!({ "width": k.width, "height": k.height, "edgeDistance": k.edge_distance, "edgeContrast": k.edge_contrast, "base": if k.per_triangle { "triangle" } else { "mesh" } }) - }); + let skew = + s.bake_meshes.skew.as_ref().map(|k| json!({ "width": k.width, "height": k.height, "edgeDistance": k.edge_distance, "edgeContrast": k.edge_contrast })); json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": skew }) } @@ -418,11 +408,6 @@ fn skew_set(s: &mut Session, p: &Value) -> Result { }; map.edge_distance = f32p(p, "edgeDistance").unwrap_or(0.0); map.edge_contrast = f32p(p, "edgeContrast").unwrap_or(1.0); - map.per_triangle = match strp(p, "base") { - None | Some("mesh") => false, - Some("triangle") => true, - Some(other) => return Err(bad(cmd, format!("unknown base `{other}`"))), - }; map.validate().map_err(|e| bad(cmd, e.to_string()))?; s.bake_meshes.skew = Some(Arc::new(map)); s.bake_meshes.skew_rev += 1; @@ -440,189 +425,279 @@ fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}"))); match p.get("ts") { Some(Value::String(a)) if a == "all" => Ok((0..n).collect()), - Some(Value::String(a)) if a == "selected" => Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.enabled)).collect()), + Some(Value::String(a)) if a == "selected" => { + Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.common.is_enabled)).collect()) + } Some(Value::Array(a)) => a.iter().map(one).collect(), Some(v) => Ok(vec![one(v)?]), None => Ok(vec![s.ts()]), } } -/// `b` as `bake.settings` parameters (what the command returns and the UI sends back). -pub fn settings_params(b: &BakeSettings) -> Value { - let mut ao = rays_params(&b.ao); - ao["ignoreBackface"] = b.ao_ignore_backface.into(); - ao["selfOcclusion"] = SELF_OCCLUSION.name(b.ao_self_occlusion).into(); +/// Parameters shared by the current bake command and UI +pub fn settings_params(settings: &BakeSettings) -> Value { + let mut ao = rays_params(&settings.maps.ao.parameters.rays); + ao["ignoreBackface"] = match settings.maps.ao.parameters.ignore_backface { + BackfaceMode::Never => "never", + BackfaceMode::Always => "always", + BackfaceMode::ByMeshName => "byMeshName", + } + .into(); + ao["selfOcclusion"] = match settings.maps.ao.parameters.self_occlusion { + SelfOcclusion::Always => "always", + SelfOcclusion::SameMeshName => "sameMeshName", + } + .into(); + json!({ - "resolution": b.resolution, - "antialiasing": b.antialiasing, - "dilation": b.dilation, + "resolution": settings.common.resolution.pixels(), + "antialiasing": settings.common.antialiasing.samples_per_axis(), + "dilation": settings.common.dilation, "ao": ao, - "thickness": rays_params(&b.thickness), - "bentNormal": rays_params(&b.bent_normal), - "curvatureStrength": b.curvature_strength, - "curvatureFromNormal": b.curvature_from_normal, - "curvatureRadius": b.curvature_radius, - "positionMode": POSITION_MODE.name(b.position_mode), - "direction": b.direction, - "directionMode": DIRECTION_MODE.name(b.direction_mode), - "maps": b.maps.iter().map(|m| m.id()).collect::>(), - "enabled": b.enabled, - "useLowAsHigh": b.use_low_as_high, - "maxFrontal": b.max_frontal, - "maxRear": b.max_rear, - "averageNormals": b.average_normals, - "matching": match b.matching { BakeMatch::Always => "always", BakeMatch::ByMeshName => "byMeshName" }, - "lowSuffix": b.low_suffix, - "highSuffix": b.high_suffix, + "thickness": rays_params(&settings.maps.thickness.parameters.rays), + "bentNormal": rays_params(&settings.maps.bent_normal.parameters.rays), + "curvatureMethod": match settings.maps.curvature.parameters.method { CurvatureMethod::NormalMap => "normalMap", CurvatureMethod::Mesh => "mesh" }, + "positionMode": match settings.maps.position.parameters.normalization { PositionMode::BoundingBox => "boundingBox", PositionMode::BoundingSphere => "boundingSphere", PositionMode::None => "none" }, + "maps": settings.maps.enabled().map(|m| m.id()).collect::>(), + "enabled": settings.common.is_enabled, + "useLowAsHigh": settings.high_poly.use_low_as_high, + "maxFrontal": settings.cage.max_frontal, + "maxRear": settings.cage.max_rear, + "averageNormals": settings.cage.average_normals, + "lowSuffix": settings.high_poly.low_suffix, + "highSuffix": settings.high_poly.high_suffix, }) } -/// Apply the `bake.settings` parameters present in `p` to `b`. -fn apply_settings(b: &mut BakeSettings, p: &Value, cmd: &str) -> Result<()> { - if let Some(r) = u64p(p, "resolution") { - b.resolution = crate::session::check_resolution(u32::try_from(r).unwrap_or(0))?; - } - if let Some(a) = u64p(p, "antialiasing") { - if ![1, 2, 4, 8].contains(&a) { - return Err(bad(cmd, "antialiasing must be 1, 2, 4 or 8")); - } - b.antialiasing = a as u32; - } - if let Some(d) = u64p(p, "dilation") { - b.dilation = d.min(256) as u32; - } - // `rays` / `maxDistance` set every ray map; the per-map objects override. - for r in [&mut b.ao, &mut b.thickness, &mut b.bent_normal] { - apply_rays(r, p, cmd)?; - } - for (k, r) in [("ao", &mut b.ao), ("thickness", &mut b.thickness), ("bentNormal", &mut b.bent_normal)] { - if let Some(o) = p.get(k) { - apply_rays(r, o, cmd)?; +/// Apply only the bake parameters supplied by the caller +fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> { + // Keep the current command limits until the reference controls are integrated + const MAX_DILATION_PIXELS: u32 = 256; + const MAX_SUFFIX_CHARS: usize = 64; + + if let Some(model) = params.get("model") { + let replacement: BakeSettings = serde_json::from_value(model.clone()).map_err(|error| bad(command, error.to_string()))?; + validate_model_settings(&replacement, command)?; + let is_enabled = settings.common.is_enabled; + *settings = replacement; + if boolp(params, "preserveEnabled") == Some(true) { + settings.common.is_enabled = is_enabled; } } - if let Some(ao) = p.get("ao") { - if let Some(v) = boolp(ao, "ignoreBackface") { - b.ao_ignore_backface = v; - } - if let Some(v) = strp(ao, "selfOcclusion") { - b.ao_self_occlusion = SELF_OCCLUSION.parse(cmd, "selfOcclusion", v)?; - } + + if let Some(resolution) = u64p(params, "resolution") { + settings.common.resolution = u32::try_from(resolution) + .ok() + .and_then(BakeResolution::from_pixels) + .ok_or_else(|| bad(command, "resolution must be a power of two from 16 to 8192"))?; } - if let Some(v) = strp(p, "positionMode") { - b.position_mode = POSITION_MODE.parse(cmd, "positionMode", v)?; + + if let Some(antialiasing) = u64p(params, "antialiasing") { + settings.common.antialiasing = u32::try_from(antialiasing) + .ok() + .and_then(BakeAntialiasing::from_samples_per_axis) + .ok_or_else(|| bad(command, "antialiasing must be 1, 2, 4 or 8"))?; } - if let Some(v) = strp(p, "directionMode") { - b.direction_mode = DIRECTION_MODE.parse(cmd, "directionMode", v)?; + + if let Some(dilation) = u64p(params, "dilation") { + settings.common.dilation = dilation.min(u64::from(MAX_DILATION_PIXELS)) as u32; } - if let Some(r) = u64p(p, "curvatureRadius") { - b.curvature_radius = r.min(64) as u32; + + // Per-map values override the shared ray settings + for ray_settings in [&mut settings.maps.ao.parameters.rays, &mut settings.maps.thickness.parameters.rays, &mut settings.maps.bent_normal.parameters.rays] { + apply_rays(ray_settings, params, command)?; } - for (k, slot, lo, hi) in - [("curvatureStrength", &mut b.curvature_strength, 0.0, 16.0), ("maxFrontal", &mut b.max_frontal, 0.0, 1.0), ("maxRear", &mut b.max_rear, 0.0, 1.0)] - { - if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) { - *slot = v.clamp(lo, hi); - } - } - for (k, slot) in [ - ("curvatureFromNormal", &mut b.curvature_from_normal), - ("enabled", &mut b.enabled), - ("useLowAsHigh", &mut b.use_low_as_high), - ("averageNormals", &mut b.average_normals), + + for (key, ray_settings) in [ + ("ao", &mut settings.maps.ao.parameters.rays), + ("thickness", &mut settings.maps.thickness.parameters.rays), + ("bentNormal", &mut settings.maps.bent_normal.parameters.rays), ] { - if let Some(v) = boolp(p, k) { - *slot = v; + if let Some(map_params) = params.get(key) { + apply_rays(ray_settings, map_params, command)?; } } - if let Some(d) = p.get("direction") { - let v: Vec = d.as_array().into_iter().flatten().filter_map(Value::as_f64).map(|x| x as f32).collect(); - match v[..] { - [x, y, z] if [x, y, z].iter().all(|c| c.is_finite()) && [x, y, z] != [0.0; 3] => b.direction = [x, y, z], - _ => return Err(bad(cmd, "`direction` must be three finite numbers, not all zero")), + + if let Some(ao) = params.get("ao") { + if let Some(value) = ao.get("ignoreBackface") { + let mode = value.as_str().ok_or_else(|| bad(command, "ignoreBackface must be never, always or byMeshName"))?; + settings.maps.ao.parameters.ignore_backface = match mode { + "never" => BackfaceMode::Never, + "always" => BackfaceMode::Always, + "byMeshName" => BackfaceMode::ByMeshName, + _ => return Err(bad(command, "ignoreBackface must be never, always or byMeshName")), + }; + } + + if let Some(self_occlusion) = strp(ao, "selfOcclusion") { + settings.maps.ao.parameters.self_occlusion = match self_occlusion { + "always" => SelfOcclusion::Always, + "sameMeshName" => SelfOcclusion::SameMeshName, + _ => return Err(bad(command, "selfOcclusion must be always or sameMeshName")), + }; } } - if let Some(a) = p.get("maps").and_then(Value::as_array) { - b.maps = a.iter().map(|v| v.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(cmd, format!("unknown mesh map {v}")))).collect::>()?; + + if let Some(position_mode) = strp(params, "positionMode") { + settings.maps.position.parameters.normalization = match position_mode { + "boundingBox" => PositionMode::BoundingBox, + "boundingSphere" => PositionMode::BoundingSphere, + "none" => PositionMode::None, + _ => return Err(bad(command, "positionMode must be boundingBox, boundingSphere or none")), + }; } - match strp(p, "matching") { - Some("always") => b.matching = BakeMatch::Always, - Some("byMeshName") | Some("byName") => b.matching = BakeMatch::ByMeshName, - Some(o) => return Err(bad(cmd, format!("unknown matching `{o}` (always|byMeshName)"))), - None => {} + + if let Some(value) = params.get("curvatureMethod") { + let method = value.as_str().ok_or_else(|| bad(command, "curvatureMethod must be normalMap or mesh"))?; + settings.maps.curvature.parameters.method = match method { + "normalMap" => CurvatureMethod::NormalMap, + "mesh" => CurvatureMethod::Mesh, + _ => return Err(bad(command, "curvatureMethod must be normalMap or mesh")), + }; } - for (k, slot) in [("lowSuffix", &mut b.low_suffix), ("highSuffix", &mut b.high_suffix)] { - if let Some(v) = strp(p, k) { - *slot = v.chars().take(64).collect(); + + for (key, setting, minimum, maximum) in [("maxFrontal", &mut settings.cage.max_frontal, 0.0, 1.0), ("maxRear", &mut settings.cage.max_rear, 0.0, 1.0)] { + if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) { + *setting = value.clamp(minimum, maximum); } } + + for (key, setting) in [ + ("enabled", &mut settings.common.is_enabled), + ("useLowAsHigh", &mut settings.high_poly.use_low_as_high), + ("averageNormals", &mut settings.cage.average_normals), + ] { + if let Some(value) = boolp(params, key) { + *setting = value; + } + } + + if let Some(maps) = params.get("maps").and_then(Value::as_array) { + let selected = maps + .iter() + .map(|map| map.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(command, format!("unknown mesh map {map}")))) + .collect::>>()?; + settings.maps.select(selected); + } + + for (key, setting) in [("lowSuffix", &mut settings.high_poly.low_suffix), ("highSuffix", &mut settings.high_poly.high_suffix)] { + if let Some(suffix) = strp(params, key) { + *setting = suffix.chars().take(MAX_SUFFIX_CHARS).collect(); + } + } + + Ok(()) +} + +fn validate_model_settings(settings: &BakeSettings, command: &str) -> Result<()> { + let range = |name: &str, value: f32, minimum: f32, maximum: f32| { + if value.is_finite() && (minimum..=maximum).contains(&value) { Ok(()) } else { Err(bad(command, format!("{name} must be in {minimum}..={maximum}"))) } + }; + if settings.common.dilation > 128 { + return Err(bad(command, "dilation must be at most 128")); + } + for rays in [&settings.maps.ao.parameters.rays, &settings.maps.thickness.parameters.rays, &settings.maps.bent_normal.parameters.rays] { + if !(1..=256).contains(&rays.rays) { + return Err(bad(command, "secondary rays must be in 1..=256")); + } + range("minimum occluder distance", rays.min_distance, 0.00001, 1.0)?; + range("maximum occluder distance", rays.max_distance, 0.00001, if rays.relative_to_bounding_box { 1.0 } else { 10.0 })?; + range("spread angle", rays.spread, 0.0, 180.0)?; + } + let curvature = &settings.maps.curvature.parameters; + if !(1..=256).contains(&curvature.mesh.rays) { + return Err(bad(command, "curvature rays must be in 1..=256")); + } + range("sampling radius", curvature.mesh.sampling_radius, 0.00001, if curvature.mesh.relative_to_bounding_box { 10.0 } else { 1.0 })?; + for (name, value, minimum, maximum) in [ + ("frontal distance", settings.cage.max_frontal, 0.0, 0.05), + ("rear distance", settings.cage.max_rear, 0.0, 0.05), + ("edge distance", settings.skew.edge_distance, 0.0, 1.0), + ("edge contrast", settings.skew.edge_contrast, 0.0, 1.0), + ("ground plane offset", settings.maps.ao.parameters.ground_plane.offset, 0.0, 100.0), + ("curvature details", curvature.normal_map.details, 0.0, 1.0), + ("seams intensity", curvature.normal_map.seams_intensity, 0.0, 1.0), + ("value bounds minimum", curvature.mesh.value_min, -10.0, 10.0), + ("value bounds maximum", curvature.mesh.value_max, -10.0, 10.0), + ("height scaling divisor", settings.maps.height.parameters.scaling_divisor, 0.00001, 100.0), + ] { + range(name, value, minimum, maximum)?; + } Ok(()) } -/// Parameter names of a settings enum. -struct Names(&'static [(&'static str, T)]); - -impl Names { - fn name(&self, v: T) -> &'static str { - self.0.iter().find(|(_, x)| *x == v).map_or("", |(n, _)| n) - } - - fn parse(&self, cmd: &str, key: &str, s: &str) -> Result { - let all = || self.0.iter().map(|(n, _)| *n).collect::>().join("|"); - self.0.iter().find(|(n, _)| *n == s).map(|(_, v)| *v).ok_or_else(|| bad(cmd, format!("unknown {key} `{s}` ({})", all()))) - } +/// Ray settings supported by the current bake command +fn rays_params(settings: &RaySettings) -> Value { + json!({ + "rays": settings.rays, + "maxDistance": settings.max_distance, + "spread": settings.spread, + "distribution": match settings.distribution { + RayDistribution::Cosine => "cosine", + RayDistribution::Uniform => "uniform", + }, + }) } -const SELF_OCCLUSION: Names = Names(&[("always", SelfOcclusion::Always), ("sameMeshName", SelfOcclusion::SameMeshName)]); -const DISTRIBUTION: Names = Names(&[("cosine", RayDistribution::Cosine), ("uniform", RayDistribution::Uniform)]); -const POSITION_MODE: Names = Names(&[("boundingBox", PositionMode::BoundingBox), ("boundingSphere", PositionMode::BoundingSphere)]); -const DIRECTION_MODE: Names = Names(&[("signed", DirectionMode::Signed), ("positive", DirectionMode::Positive)]); - -/// `r` as `bake.settings` parameters. -fn rays_params(r: &RaySettings) -> Value { - json!({ "rays": r.rays, "maxDistance": r.max_distance, "spread": r.spread, "distribution": DISTRIBUTION.name(r.distribution) }) -} - -/// Apply the ray parameters present in `p` (`rays`, `maxDistance`, `spread`, `distribution`). -fn apply_rays(r: &mut RaySettings, p: &Value, cmd: &str) -> Result<()> { - if let Some(n) = u64p(p, "rays") { - r.rays = n.clamp(1, u64::from(MAX_RAYS)) as u32; +/// Apply only the ray parameters supplied by the caller +fn apply_rays(settings: &mut RaySettings, params: &Value, command: &str) -> Result<()> { + if let Some(count) = u64p(params, "rays") { + settings.rays = count.clamp(1, u64::from(MAX_RAYS)) as u32; } - for (k, slot, lo, hi) in [("maxDistance", &mut r.max_distance, 0.001, 10.0), ("spread", &mut r.spread, 0.0, 180.0)] { - if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) { - *slot = v.clamp(lo, hi); + + for (key, setting, minimum, maximum) in [("maxDistance", &mut settings.max_distance, 0.001, 10.0), ("spread", &mut settings.spread, 0.0, 180.0)] { + if let Some(value) = f32p(params, key).filter(|value| value.is_finite()) { + *setting = value.clamp(minimum, maximum); } } - if let Some(v) = strp(p, "distribution") { - r.distribution = DISTRIBUTION.parse(cmd, "distribution", v)?; + + if let Some(distribution) = strp(params, "distribution") { + settings.distribution = match distribution { + "cosine" => RayDistribution::Cosine, + "uniform" => RayDistribution::Uniform, + _ => return Err(bad(command, "distribution must be cosine or uniform")), + }; } + Ok(()) } -/// Validate and apply the settings parameters to every set first, so a bad parameter changes -/// nothing. -fn set_settings(s: &mut Session, p: &Value, cmd: &str) -> Result> { - let sets = sets_param(s, cmd, p)?; +/// Validate every target before applying settings +fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { + let sets = sets_param(session, command, params)?; let mut next = Vec::with_capacity(sets.len()); - for &ts in &sets { - let mut b = s.doc.project.texture_set(ts)?.bake.clone(); - apply_settings(&mut b, p, cmd)?; - next.push((ts, b)); + for &set_index in &sets { + let mut settings = session.doc.project.texture_set(set_index)?.bake.clone(); + apply_settings(&mut settings, params, command)?; + next.push((set_index, settings)); } - for (ts, b) in next { - let set = s.doc.project.texture_set_mut(ts)?; - if set.bake != b { - set.bake = b; - s.modified = true; + + for (set_index, settings) in next { + let texture_set = session.doc.project.texture_set_mut(set_index)?; + if texture_set.bake != settings { + texture_set.bake = settings; + session.modified = true; } } + Ok(sets) } -fn settings(s: &mut Session, p: &Value) -> Result { - let sets = set_settings(s, p, "bake.settings")?; - let out: Vec = - sets.iter().filter_map(|t| s.doc.project.texture_sets.get(*t).map(|set| json!({ "ts": t, "settings": settings_params(&set.bake) }))).collect(); - Ok(json!(out)) +fn settings(session: &mut Session, params: &Value) -> Result { + let sets = set_settings(session, params, "bake.settings")?; + let result: Vec = sets + .iter() + .filter_map(|set_index| { + session + .doc + .project + .texture_sets + .get(*set_index) + .map(|texture_set| json!({ "ts": set_index, "settings": settings_params(&texture_set.bake), "model": &texture_set.bake })) + }) + .collect(); + + Ok(json!(result)) } fn bake_run(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index c5fb7134..6dbc5ce6 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -68,7 +68,6 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::auto_rebake::specs()); v.extend(crate::bake_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ec99643f..e5fca41e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,7 +8,6 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod auto_rebake; pub mod bake_cmds; pub mod brush_preset_cmds; pub mod camera_cmds; diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index ddd7bfd5..7829efd2 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -354,23 +354,26 @@ impl Session { Ok(link_of(self, "material.link", id)?.params.iter().map(|p| (p.id.clone(), p.value.clone())).collect()) } - /// The re-cook of linked layer `id` with `overrides` over its values, at its texture set's - /// resolution, with the set's baked mesh maps for matching graph inputs. + /// Prepare a re-cook with current parameter values and matching baked mesh maps pub fn link_job(&self, id: LayerId, overrides: &Map) -> Result { let link = link_of(self, "material.link", id)?; - let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; + let (texture_set, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?; let mut values = self.link_values(id)?; values.extend(overrides.clone()); + let mut inputs = Vec::new(); - if let Some(baked) = self.doc.baked.get(&ts) { - for ident in &link.inputs { - let Some((m, data)) = BakedMap::for_input(ident).and_then(|m| Some((m, baked.maps.get(&m)?))) else { continue }; - let png = texturecraft_formats::mcmat::mesh_map_png(baked.resolution, m.components(), data).map_err(|e| EngineError::Other(e.to_string()))?; - inputs.push((ident.clone(), png)); + if let Some(baked) = self.doc.baked.get(&texture_set) { + for identifier in &link.inputs { + let Some((map, data)) = BakedMap::parse(identifier).and_then(|map| Some((map, baked.maps.get(&map)?))) else { continue }; + + let png = texturecraft_formats::mcmat::mesh_map_png(baked.resolution, map.components(), data) + .map_err(|error| EngineError::Other(error.to_string()))?; + inputs.push((identifier.clone(), png)); } } - // shortcut: one cook per texture set at its base resolution; UDIM tiles share it. - let size = self.doc.project.texture_set(ts)?.resolution; + + // UDIM tiles share one cook at the texture set's base resolution + let size = self.doc.project.texture_set(texture_set)?.resolution; Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs }) } diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 3f3a414e..5f2c5069 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Use image as mesh map", [], None, - "{ts?, map: mesh map id (normal_base, ambient_occlusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format. A UV-tiled set takes one image per tile, named alike with the tile number (`image: \"ao.1001.png\"` finds ao.1002.png…)", + "{ts?, map: mesh map id (normal, ambientOcclusion, curvature, id, height…), image: resource name} → {map, resolution} — resampled to the size of the set's other mesh maps (or its bake size); a normal map is read in the project's normal format. A UV-tiled set takes one image per tile, named alike with the tile number (`image: \"ao.1001.png\"` finds ao.1002.png…)", always, set ), @@ -46,7 +46,7 @@ fn set(s: &mut Session, p: &Value) -> Result { let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => (set.bake.resolution.saturating_mul(cols), set.bake.resolution.saturating_mul(rows)), + None => (set.bake.common.resolution.pixels().saturating_mul(cols), set.bake.common.resolution.pixels().saturating_mul(rows)), }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); @@ -118,7 +118,7 @@ fn clear(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; if !s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) { - return Err(bad(CMD, format!("texture set {ts} has no {} map", map.label()))); + return Err(bad(CMD, format!("texture set {ts} has no {} map", map.id()))); } s.edit("Clear mesh map", |s| { if let Some(b) = s.doc.baked.get_mut(&ts) { diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 4bea6deb..b3a753ff 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -2,6 +2,7 @@ use serde_json::{Value, json}; use texturecraft_compose::BakedMaps; +use texturecraft_core::{BakeResolution, CurvatureMethod}; use texturecraft_geom::primitives; use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p}; @@ -56,31 +57,37 @@ fn material(s: &mut Session, p: &Value) -> Result { Ok(json!({ "layer": l.0 })) } -/// The sample project: the material ball, baked, with smart materials on both texture sets. +/// A baked material ball with smart materials on both texture sets pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result { - let mut s = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?; - for ts in 0..s.set_count() { - let set = s.doc.project.texture_set_mut(ts)?; - set.bake.resolution = bake_resolution; - for r in [&mut set.bake.ao, &mut set.bake.thickness, &mut set.bake.bent_normal] { - r.rays = 24; + let mut session = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?; + for set_index in 0..session.set_count() { + let set = session.doc.project.texture_set_mut(set_index)?; + set.bake.common.resolution = BakeResolution::from_pixels(bake_resolution).ok_or_else(|| bad("project.sample", "invalid bake resolution"))?; + + // Mesh curvature gives the procedural sample visible edge wear + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + for ray_settings in + [&mut set.bake.maps.ao.parameters.rays, &mut set.bake.maps.thickness.parameters.rays, &mut set.bake.maps.bent_normal.parameters.rays] + { + ray_settings.rays = 24; } - s.bake_now(ts, false)?; + session.bake_now(set_index, false)?; } - s.active_set = 1; - crate::materials::apply(&mut s, "iron_rusted")?; - s.active_set = 0; - crate::materials::apply(&mut s, "steel_painted_worn")?; - // Ready to paint: an empty paint layer on top of each stack, selected (the smart material - // fully covers the bottom layer, so strokes there would stay hidden). - for ts in (0..s.set_count()).rev() { - s.active_set = ts; - s.selected.remove(&ts); - crate::execute(&mut s, "layer.add.paint", &Value::Null)?; + session.active_set = 1; + crate::materials::apply(&mut session, "iron_rusted")?; + session.active_set = 0; + crate::materials::apply(&mut session, "steel_painted_worn")?; + + // Paint above the smart material so new strokes remain visible + for set_index in (0..session.set_count()).rev() { + session.active_set = set_index; + session.selected.remove(&set_index); + crate::execute(&mut session, "layer.add.paint", &Value::Null)?; } - s.undo.clear(); - s.modified = false; - Ok(s) + session.undo.clear(); + session.modified = false; + Ok(session) } fn sample(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 10a90287..28843881 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -152,7 +152,7 @@ impl ViewMode { match self { ViewMode::Material => "Material".into(), ViewMode::Channel(c) => c.label().into(), - ViewMode::MeshMap(m) => m.label().into(), + ViewMode::MeshMap(m) => m.id().into(), ViewMode::UvChecker => "UV checker".into(), ViewMode::Mask(_) => "Layer mask".into(), } @@ -320,8 +320,6 @@ pub struct Session { pub mesh_source: Option<(String, Vec)>, /// High-definition meshes and cage for baking (saved inside the project). pub bake_meshes: crate::BakeMeshes, - /// The map that bakes itself again when its inputs change (not saved). - pub auto_rebake: crate::auto_rebake::AutoRebake, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -384,7 +382,6 @@ impl Session { bvh: Arc::new(bvh), mesh_source, bake_meshes: Default::default(), - auto_rebake: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs deleted file mode 100644 index e6a37275..00000000 --- a/crates/engine/tests/auto_rebake.rs +++ /dev/null @@ -1,156 +0,0 @@ -//! Auto-rebake: one mesh map bakes itself again when its bake inputs change. - -use std::sync::Arc; - -use serde_json::{Value, json}; -use texturecraft_engine::core::BakedMap; -use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; - -/// A plane with a high poly just above it, baked once with height and opacity. -fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { - let mesh = primitives::builtin("plane").unwrap(); - let mut obj = String::from("o Part_high\n"); - for p in &mesh.positions { - obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); - } - for t in mesh.indices.chunks_exact(3) { - obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); - } - let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let path = dir.join("hp.obj"); - std::fs::write(&path, obj).unwrap(); - let mut s = Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap(); - execute(&mut s, "bake.highPoly.add", &json!({ "path": path.display().to_string() })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "resolution": 128, "dilation": 0, "maps": ["height", "opacity"] })).unwrap(); - execute(&mut s, "bake.run", &json!({ "cpu": true })).unwrap(); - (s, dir) -} - -fn due(s: &mut Session) -> Vec { - execute(s, "bake.autoRebake", &Value::Null).unwrap()["due"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect() -} - -fn image(s: &Session, map: BakedMap) -> Arc> { - s.doc.baked[&0].maps[&map].clone() -} - -#[test] -fn a_changed_bake_input_rebakes_only_the_chosen_map() { - let (mut s, dir) = baked_session("rebake"); - // Off by default; nothing is due and the run command says what to do first. - assert_eq!(execute(&mut s, "bake.autoRebake", &Value::Null).unwrap()["map"], Value::Null); - assert!(execute(&mut s, "bake.autoRebake.run", &Value::Null).is_err()); - let r = execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert_eq!(r["map"], "height"); - assert!(due(&mut s).is_empty(), "turning it on takes the current bake as up to date"); - - // Which maps are ticked is not a bake input; a setting is. - execute(&mut s, "bake.settings", &json!({ "maps": ["height", "opacity", "ambient_occlusion"] })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2, "maps": ["height", "opacity"] })).unwrap(); - assert_eq!(due(&mut s), [0]); - - let (height, opacity) = (image(&s, BakedMap::Height), image(&s, BakedMap::Opacity)); - let r = execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert_eq!(r["rebaked"], json!([0])); - assert!(!Arc::ptr_eq(&height, &image(&s, BakedMap::Height)), "the Auto-rebake map was baked again"); - assert!(Arc::ptr_eq(&opacity, &image(&s, BakedMap::Opacity)), "the other maps were left alone"); - assert!(due(&mut s).is_empty(), "and the set is up to date"); - assert_eq!(execute(&mut s, "bake.autoRebake.run", &Value::Null).unwrap()["rebaked"], json!([])); - - // A manual bake of the map also counts; a changed high poly list is a change again. - execute(&mut s, "bake.settings", &json!({ "antialiasing": 2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - s.begin_bake(0); - let out = s.bake_task_for(0, None).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap(); - s.apply_bake(0, out).unwrap(); - assert!(due(&mut s).is_empty(), "a manual bake of the map marks it up to date"); - execute(&mut s, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); - assert_eq!(due(&mut s), [0]); - - // A different output size is left to a manual bake: the maps would end up at two sizes. - execute(&mut s, "bake.settings", &json!({ "resolution": 256 })).unwrap(); - assert!(due(&mut s).is_empty()); - - // Hostile input, and turning it off. - for bad in [json!({ "map": "nonsense" }), json!({ "map": 3 })] { - assert!(execute(&mut s, "bake.autoRebake", &bad).is_err(), "{bad}"); - } - assert_eq!(execute(&mut s, "bake.autoRebake", &json!({ "map": null })).unwrap()["map"], Value::Null); - assert!(due(&mut s).is_empty()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_cancelled_or_failed_bake_is_not_queued_again_until_the_inputs_change() { - let (mut s, dir) = baked_session("cancel"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - - // What the app does: start the bake, cancel it, record the abandoned bake. - s.begin_bake(0); - let mut task = s.bake_task_for(0, Some(BakedMap::Height)).unwrap(); - task.tracer = None; - let progress = texturecraft_engine::bake::Progress::new(); - progress.cancel(); - assert!(task.run(&progress).is_err(), "a cancelled bake fails"); - s.bake_abandoned([0]); - assert!(due(&mut s).is_empty(), "not queued again on the next frame"); - - // The next change makes it due again; a bake that never started (queued behind a failed - // one) is recorded the same way. - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); - assert_eq!(due(&mut s), [0]); - s.bake_abandoned([0]); - assert!(due(&mut s).is_empty()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn a_set_without_the_map_baked_is_left_alone() { - let mut s = Session::new_project("t", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap(); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.3 })).unwrap(); - assert!(due(&mut s).is_empty(), "Auto-rebake keeps a bake up to date, it doesn't start one"); -} - -#[test] -fn undoing_a_rebake_brings_back_a_stale_map_and_it_is_due_again() { - let (mut s, dir) = baked_session("undo"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.settings", &json!({ "maxFrontal": 0.2 })).unwrap(); - assert_eq!(due(&mut s), [0]); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert!(due(&mut s).is_empty()); - // Undo the bake: the older map is back, baked with the older settings, which no longer match. - let newer = image(&s, BakedMap::Height); - execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert!(!Arc::ptr_eq(&newer, &image(&s, BakedMap::Height)), "undo restored the older map"); - assert_eq!(due(&mut s), [0], "the restored map is out of date and rebakes"); - // Redo brings the newer map back, which does match. - execute(&mut s, "edit.redo", &Value::Null).unwrap(); - assert!(due(&mut s).is_empty(), "the newer map matches the current settings"); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn painting_or_clearing_the_skew_map_is_a_change() { - let (mut s, dir) = baked_session("skew"); - execute(&mut s, "bake.autoRebake", &json!({ "map": "height" })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); - assert_eq!(due(&mut s), [0], "a skew map is a bake input"); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - assert!(due(&mut s).is_empty()); - execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "size": 32 })).unwrap(); - assert_eq!(due(&mut s), [0], "so is a stroke painted into it"); - execute(&mut s, "bake.autoRebake.run", &json!({ "cpu": true })).unwrap(); - execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert_eq!(due(&mut s), [0], "and so is taking it away"); - let _ = std::fs::remove_dir_all(dir); -} diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index 8f592937..2375fca3 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -1,7 +1,7 @@ -//! Bake commands: settings, high-definition meshes, cage, and project round trips. +//! Bake commands, mesh assets and project persistence use serde_json::{Value, json}; -use texturecraft_engine::core::{BakeMatch, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_engine::core::{BackfaceMode, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; use texturecraft_engine::geom::{Mesh, primitives}; use texturecraft_engine::{Session, execute}; @@ -33,158 +33,288 @@ fn temp_file(name: &str, text: &str) -> String { #[test] fn high_poly_meshes_drive_the_bake_and_round_trip() { - let mut s = plane_session(); - let low = s.mesh.as_ref().clone(); - let (lo, hi) = low.bounds(); - let mid = (lo.x + hi.x) * 0.5; - // A red high poly over the left half of the plane, just above it. - let high = temp_file("hp_high.obj", &obj(&low, 0.002, mid, [1.0, 0.0, 0.0])); - let r = execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); - assert_eq!(r["name"], "hp_high.obj"); - assert!(s.doc.project.texture_sets.iter().all(|t| !t.bake.use_low_as_high), "adding a high poly bakes from it"); - let list = execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap(); - assert_eq!(list["highPoly"][0]["parts"][0], "Part_high"); - assert!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["bakeMeshes"]["highPoly"].as_array().is_some_and(|a| a.len() == 1)); + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["opacity", "color_map"], "dilation": 0 })).unwrap(); - let baked = &s.doc.baked[&0]; + let low = session.mesh.as_ref().clone(); + let (lo, hi) = low.bounds(); + let midpoint_x = (lo.x + hi.x) * 0.5; + + // A red high poly over the left half of the plane, just above it + let high = temp_file("hp_high.obj", &obj(&low, 0.002, midpoint_x, [1.0, 0.0, 0.0])); + let result = execute(&mut session, "bake.highPoly.add", &json!({ "path": high })).unwrap(); + assert_eq!(result["name"], "hp_high.obj"); + assert!(session.doc.project.texture_sets.iter().all(|texture_set| !texture_set.bake.high_poly.use_low_as_high), "adding a high poly bakes from it"); + let list = execute(&mut session, "bake.highPoly.list", &Value::Null).unwrap(); + assert_eq!(list["highPoly"][0]["parts"][0], "Part_high"); + assert!(execute(&mut session, "project.inspect", &Value::Null).unwrap()["bakeMeshes"]["highPoly"].as_array().is_some_and(|a| a.len() == 1)); + + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + let baked = &session.doc.baked[&0]; let opacity = &baked.maps[&BakedMap::Opacity]; let covered = opacity.iter().filter(|v| **v > 0.99).count() as f32 / opacity.len() as f32; assert!((covered - 0.5).abs() < 0.08, "the high poly covers half the plane: {covered}"); - let color = &baked.maps[&BakedMap::ColorMap]; - assert!(opacity.iter().zip(color.chunks(3)).filter(|(o, _)| **o > 0.99).all(|(_, c)| c == [1.0, 0.0, 0.0]), "red where covered"); - // A cage must have the low poly's triangles. - let tri = temp_file("tri.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); - assert!(execute(&mut s, "bake.cage.set", &json!({ "path": tri })).is_err()); + // A cage must have the low poly's triangles + let invalid_cage = temp_file("tri.obj", "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"); + assert!(execute(&mut session, "bake.cage.set", &json!({ "path": invalid_cage })).is_err()); let cage = temp_file("cage.obj", &obj(&low, 0.05, f32::MAX, [1.0; 3])); - execute(&mut s, "bake.cage.set", &json!({ "path": cage })).unwrap(); - execute(&mut s, "bake.settings", &json!({ "matching": "byMeshName", "maxFrontal": 0.05 })).unwrap(); + execute(&mut session, "bake.cage.set", &json!({ "path": cage })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "maxFrontal": 0.05 })).unwrap(); - // Save and reopen: meshes, cage and settings come back. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - let names = |s: &Session| s.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); - assert_eq!(names(&back), names(&s)); - assert_eq!(back.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); - assert_eq!(back.doc.project.texture_sets[0].bake, s.doc.project.texture_sets[0].bake); - assert_eq!(back.doc.project.texture_sets[0].bake.matching, BakeMatch::ByMeshName); + // Save and reopen: meshes, cage and settings come back + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + let names = |session: &Session| session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect::>(); + assert_eq!(names(&reloaded), names(&session)); + assert_eq!(reloaded.bake_meshes.cage.as_ref().map(|c| c.name.as_str()), Some("cage.obj")); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, session.doc.project.texture_sets[0].bake); - execute(&mut s, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); - assert!(s.bake_meshes.high.is_empty()); - execute(&mut s, "bake.cage.clear", &Value::Null).unwrap(); - assert!(s.bake_meshes.cage.is_none()); - // Without high polys the bake falls back to the low poly. - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); - assert!(s.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|v| *v == 1.0)); + execute(&mut session, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); + assert!(session.bake_meshes.high.is_empty()); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + assert!(session.bake_meshes.cage.is_none()); + + // Without high polys the bake falls back to the low poly + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"] })).unwrap(); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|v| *v == 1.0)); let _ = std::fs::remove_dir_all(std::path::Path::new(&high).parent().unwrap()); } #[test] fn malformed_high_poly_input_errors_cleanly() { - let mut s = plane_session(); - assert!(s.add_high_poly_bytes("bad.obj", b"this is not a mesh".to_vec()).is_err()); - assert!(s.add_high_poly_bytes("bad.glb", b"glTF\x02\0\0\0\xff\xff\xff\xff".to_vec()).is_err()); - assert!(s.add_high_poly_bytes("bad.xyz", vec![1, 2, 3]).is_err()); - assert!(s.set_cage_bytes("bad.stl", vec![0; 10]).is_err()); - assert!(execute(&mut s, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); - assert!(execute(&mut s, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); - assert!(execute(&mut s, "bake.highPoly.remove", &Value::Null).is_err()); - assert!(s.bake_meshes.high.is_empty() && s.bake_meshes.cage.is_none()); - assert!(s.doc.project.texture_sets.iter().all(|t| t.bake.use_low_as_high), "failed adds change nothing"); + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + let before = session.doc.project.clone(); + + assert!(session.add_high_poly_bytes("bad.obj", b"this is not a mesh".to_vec()).is_err()); + assert!(session.add_high_poly_bytes("bad.glb", b"glTF\x02\0\0\0\xff\xff\xff\xff".to_vec()).is_err()); + assert!(session.add_high_poly_bytes("bad.xyz", vec![1, 2, 3]).is_err()); + assert!(session.set_cage_bytes("bad.stl", vec![0; 10]).is_err()); + assert!(execute(&mut session, "bake.highPoly.add", &json!({ "path": "/definitely/missing.obj" })).is_err()); + assert!(execute(&mut session, "bake.highPoly.remove", &json!({ "index": 3 })).is_err()); + assert!(execute(&mut session, "bake.highPoly.remove", &Value::Null).is_err()); + assert!(session.bake_meshes.high.is_empty() && session.bake_meshes.cage.is_none()); + assert_eq!(session.doc.project, before, "failed imports preserve project settings"); } #[test] fn bake_settings_apply_atomically() { - let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); - let r = - execute(&mut s, "bake.settings", &json!({ "ts": "all", "antialiasing": 4, "direction": [1, 0, 0], "maps": ["bent_normals", "World space direction"] })) - .unwrap(); - assert_eq!(r.as_array().map(Vec::len), Some(2)); - for t in &s.doc.project.texture_sets { - assert_eq!((t.bake.antialiasing, t.bake.direction), (4, [1.0, 0.0, 0.0])); - assert_eq!(t.bake.maps.iter().copied().collect::>(), [BakedMap::BentNormal, BakedMap::WorldDirection]); + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let result = execute(&mut session, "bake.settings", &json!({ "ts": "all", "antialiasing": 4, "maps": ["bentNormal", "opacity"] })).unwrap(); + assert_eq!(result.as_array().map(Vec::len), Some(2)); + + for texture_set in &session.doc.project.texture_sets { + assert_eq!(texture_set.bake.common.antialiasing, texturecraft_core::BakeAntialiasing::Subsampling4x4); + assert_eq!(texture_set.bake.maps.enabled().collect::>(), [BakedMap::BentNormal, BakedMap::Opacity]); } - let before = s.doc.project.texture_sets[0].bake.clone(); + + let before = session.doc.project.clone(); + for bad in [ json!({ "rays": 4, "antialiasing": 3 }), json!({ "maps": ["nope"] }), - json!({ "direction": [0, 0, 0] }), - json!({ "matching": "?" }), + json!({ "ts": "all", "dilation": 8, "maps": ["color_map"] }), + json!({ "ts": "all", "dilation": 8, "maps": ["world_space_direction"] }), json!({ "ts": [0, 9] }), ] { - assert!(execute(&mut s, "bake.settings", &bad).is_err(), "{bad}"); - assert_eq!(s.doc.project.texture_sets[0].bake, before, "{bad} changed nothing"); + assert!(execute(&mut session, "bake.settings", &bad).is_err(), "{bad}"); + assert_eq!(session.doc.project, before, "{bad} changed nothing"); } - // "selected" = the sets checked for baking. - execute(&mut s, "bake.settings", &json!({ "ts": 1, "enabled": false })).unwrap(); - let r = execute(&mut s, "bake.settings", &json!({ "ts": "selected", "rays": 8 })).unwrap(); - assert_eq!(r[0]["ts"], 0); - assert_eq!(r.as_array().map(Vec::len), Some(1)); - // The returned parameters set the same settings again (what the UI sends back). - let mut copy = r[0]["settings"].clone(); + + // "selected" = the sets checked for baking + execute(&mut session, "bake.settings", &json!({ "ts": 1, "enabled": false })).unwrap(); + let result = execute(&mut session, "bake.settings", &json!({ "ts": "selected", "rays": 8 })).unwrap(); + assert_eq!(result[0]["ts"], 0); + assert_eq!(result.as_array().map(Vec::len), Some(1)); + + // The returned parameters set the same settings again (what the UI sends back) + let mut copy = result[0]["settings"].clone(); copy["ts"] = 1.into(); - execute(&mut s, "bake.settings", ©).unwrap(); - let (a, b) = (&s.doc.project.texture_sets[0].bake, &s.doc.project.texture_sets[1].bake); - assert_eq!(a, b); + execute(&mut session, "bake.settings", ©).unwrap(); + let first = &session.doc.project.texture_sets[0].bake; + let second = &session.doc.project.texture_sets[1].bake; + assert_eq!(first, second); +} + +#[test] +fn current_ui_parameters_preserve_nested_model_settings() { + let mut session = plane_session(); + let settings = &mut session.doc.project.texture_sets[0].bake; + settings.common.resolution_height = Some(texturecraft_core::BakeResolution::R1024); + settings.common.apply_diffusion = false; + settings.high_poly.ignore_backface_suffix = "_open".into(); + settings.cage.relative_to_bounding_box = false; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.ao.parameters.ground_plane.offset = 3.0; + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.25; + settings.maps.curvature.parameters.normal_map.details = 0.75; + settings.maps.height.parameters.scaling_divisor = 2.0; + + for (name, method) in [("normalMap", CurvatureMethod::NormalMap), ("mesh", CurvatureMethod::Mesh)] { + let result = execute(&mut session, "bake.settings", &json!({"curvatureMethod": name})).unwrap(); + let expected = session.doc.project.texture_sets[0].bake.clone(); + assert_eq!(expected.maps.curvature.parameters.method, method); + assert_eq!(result[0]["settings"]["curvatureMethod"], name); + + execute(&mut session, "bake.settings", &result[0]["settings"]).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake, expected); + + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, expected); + } + + let expected = session.doc.project.clone(); + for method in [json!(true), json!(1), json!("invalid")] { + assert!(execute(&mut session, "bake.settings", &json!({"dilation": 8, "curvatureMethod": method})).is_err()); + assert_eq!(session.doc.project, expected); + } +} + +#[test] +fn complete_model_edits_round_trip_and_preserve_texture_set_selection() { + use texturecraft_core::{BakeResolution, HeightNormalization, IdColorGenerator, IdColorSource}; + + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 1, "enabled": false})).unwrap(); + let mut model = session.doc.project.texture_sets[0].bake.clone(); + model.common.resolution_height = Some(BakeResolution::R512); + model.common.apply_diffusion = false; + model.maps.id.parameters.source = IdColorSource::MeshId; + model.maps.id.parameters.generator = IdColorGenerator::Grayscale; + model.maps.ao.parameters.ground_plane.enabled = true; + model.maps.ao.parameters.ground_plane.offset = 3.25; + model.maps.height.is_enabled = true; + model.maps.height.parameters.normalization = HeightNormalization::Manual; + model.maps.height.parameters.scaling_divisor = 2.125; + + let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "model": model, "preserveEnabled": true})).unwrap(); + assert_eq!(result[0]["model"], json!(model)); + assert!(session.modified); + assert_eq!(session.doc.project.texture_sets[0].bake, model); + model.common.is_enabled = false; + assert_eq!(session.doc.project.texture_sets[1].bake, model); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets, session.doc.project.texture_sets); +} + +#[test] +fn invalid_model_edits_leave_all_texture_sets_unchanged() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let before = session.doc.project.clone(); + let model = json!(before.texture_sets[0].bake); + for (path, invalid_value) in [ + ("/common/dilation", json!(129)), + ("/common/antialiasing", json!(true)), + ("/cage/max_frontal", json!(0.06)), + ("/skew/edge_distance", json!(-0.1)), + ("/maps/ao/parameters/rays/rays", json!(257)), + ("/maps/ao/parameters/rays/min_distance", json!(0)), + ("/maps/ao/parameters/rays/max_distance", json!(1.5)), + ("/maps/curvature/parameters/mesh/sampling_radius", json!(11)), + ("/maps/curvature/parameters/mesh/value_max", json!(11)), + ("/maps/height/parameters/normalization", json!(1)), + ("/maps/height/parameters/scaling_divisor", json!(0)), + ] { + let mut invalid = model.clone(); + *invalid.pointer_mut(path).unwrap() = invalid_value; + assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "model": invalid})).is_err(), "{path}"); + assert_eq!(session.doc.project, before, "{path}"); + } } #[test] fn per_map_ray_settings_round_trip() { - let mut s = plane_session(); - let p = json!({ - "ao": { "rays": 48, "maxDistance": 0.5, "spread": 90, "distribution": "uniform", "ignoreBackface": true, "selfOcclusion": "sameMeshName" }, + let mut session = plane_session(); + let params = json!({ + "ao": { "rays": 48, "maxDistance": 0.5, "spread": 90, "distribution": "uniform", "ignoreBackface": "always", "selfOcclusion": "sameMeshName" }, "thickness": { "rays": 12, "spread": 45 }, "bentNormal": { "rays": 6, "maxDistance": 0.1 }, - "curvatureRadius": 3, "positionMode": "boundingSphere", - "directionMode": "positive", }); - let r = execute(&mut s, "bake.settings", &p).unwrap(); - let b = s.doc.project.texture_sets[0].bake.clone(); - assert_eq!(b.ao, RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform }); - assert!(b.ao_ignore_backface && b.ao_self_occlusion == SelfOcclusion::SameMeshName); - assert_eq!((b.thickness.rays, b.thickness.spread, b.thickness.max_distance), (12, 45.0, 0.1)); - assert_eq!((b.bent_normal.rays, b.bent_normal.max_distance, b.bent_normal.spread), (6, 0.1, 180.0)); - assert_eq!((b.curvature_radius, b.position_mode, b.direction_mode), (3, PositionMode::BoundingSphere, DirectionMode::Positive)); - assert_eq!(r[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); - assert_eq!(r[0]["settings"]["thickness"]["distribution"], "cosine"); - // The project file keeps them. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.doc.project.texture_sets[0].bake, b); - // `rays` and `maxDistance` set every ray map; unknown names change nothing. - execute(&mut s, "bake.settings", &json!({ "rays": 16, "maxDistance": 0.2 })).unwrap(); - let b = s.doc.project.texture_sets[0].bake.clone(); - assert!([b.ao, b.thickness, b.bent_normal].iter().all(|r| r.rays == 16 && r.max_distance == 0.2)); + let result = execute(&mut session, "bake.settings", ¶ms).unwrap(); + let settings = session.doc.project.texture_sets[0].bake.clone(); + assert_eq!( + settings.maps.ao.parameters.rays, + RaySettings { rays: 48, max_distance: 0.5, spread: 90.0, distribution: RayDistribution::Uniform, ..RaySettings::default() } + ); + assert_eq!(settings.maps.ao.parameters.ignore_backface, BackfaceMode::Always); + assert_eq!(settings.maps.ao.parameters.self_occlusion, SelfOcclusion::SameMeshName); + assert_eq!( + (settings.maps.thickness.parameters.rays.rays, settings.maps.thickness.parameters.rays.spread, settings.maps.thickness.parameters.rays.max_distance), + (12, 45.0, 0.1) + ); + assert_eq!( + ( + settings.maps.bent_normal.parameters.rays.rays, + settings.maps.bent_normal.parameters.rays.max_distance, + settings.maps.bent_normal.parameters.rays.spread + ), + (6, 0.1, 180.0) + ); + assert_eq!(settings.maps.position.parameters.normalization, PositionMode::BoundingSphere); + assert_eq!(result[0]["settings"]["ao"]["selfOcclusion"], "sameMeshName"); + assert_eq!(result[0]["settings"]["thickness"]["distribution"], "cosine"); + + // The project file keeps them + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.project.texture_sets[0].bake, settings); + + // `rays` and `maxDistance` set every ray map; unknown names change nothing + execute(&mut session, "bake.settings", &json!({ "rays": 16, "maxDistance": 0.2 })).unwrap(); + let settings = session.doc.project.texture_sets[0].bake.clone(); + assert!( + [settings.maps.ao.parameters.rays, settings.maps.thickness.parameters.rays, settings.maps.bent_normal.parameters.rays] + .iter() + .all(|rays| rays.rays == 16 && rays.max_distance == 0.2) + ); for bad in [ json!({ "rays": 8, "ao": { "distribution": "gaussian" } }), json!({ "ao": { "selfOcclusion": "never" } }), json!({ "thickness": { "distribution": 3, "rays": 2 }, "positionMode": "uv" }), - json!({ "directionMode": "absolute" }), ] { - assert!(execute(&mut s, "bake.settings", &bad).is_err(), "{bad}"); - assert_eq!(s.doc.project.texture_sets[0].bake, b, "{bad} changed nothing"); + assert!(execute(&mut session, "bake.settings", &bad).is_err(), "{bad}"); + assert_eq!(session.doc.project.texture_sets[0].bake, settings, "{bad} changed nothing"); + } + + // Forcing the CPU bakes there + let result = execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["ambientOcclusion"], "cpu": true })).unwrap(); + assert_eq!(result["tracer"], json!(["CPU"])); + + for (mode, expected) in [("never", BackfaceMode::Never), ("always", BackfaceMode::Always), ("byMeshName", BackfaceMode::ByMeshName)] { + let result = execute(&mut session, "bake.settings", &json!({"ao": {"ignoreBackface": mode}, "positionMode": "none"})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.ignore_backface, expected); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.position.parameters.normalization, PositionMode::None); + + let params = &result[0]["settings"]; + assert_eq!(params["ao"]["ignoreBackface"], mode); + assert_eq!(params["positionMode"], "none"); + execute(&mut session, "bake.settings", params).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].bake.maps.ao.parameters.ignore_backface, expected); + } + + let before = session.doc.project.clone(); + for invalid in [json!({"ao": {"ignoreBackface": true}}), json!({"ao": {"ignoreBackface": "invalid"}})] { + assert!(execute(&mut session, "bake.settings", &invalid).is_err()); + assert_eq!(session.doc.project, before); } - // Forcing the CPU bakes there. - let r = execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["ambient_occlusion"], "cpu": true })).unwrap(); - assert_eq!(r["tracer"], json!(["CPU"])); } -/// A 4×4 PNG in quadrants: red, green / blue, mid grey (top row = v 0). +/// A 4×4 PNG with quadrant alpha values 255, 128, 64 and 32 fn quadrants_png() -> Vec { - let quadrant = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [128, 128, 128, 255]]; - let img = image::RgbaImage::from_fn(4, 4, |x, y| image::Rgba(quadrant[(y / 2 * 2 + x / 2) as usize])); + let quadrants = [[255, 0, 0, 255], [0, 255, 0, 128], [0, 0, 255, 64], [128, 128, 128, 32]]; + let image = image::RgbaImage::from_fn(4, 4, |x, y| image::Rgba(quadrants[(y / 2 * 2 + x / 2) as usize])); let mut png = Vec::new(); - img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); png } -/// The baked 128 px color map of set 0 shows [`quadrants_png`] on the plane. -fn assert_quadrants(s: &Session) { - let color = &s.doc.baked[&0].maps[&BakedMap::ColorMap]; - let at = |x: usize, y: usize| &color[(y * 128 + x) * 3..(y * 128 + x) * 3 + 3]; - let grey = 128.0 / 255.0; - for ((x, y), want) in [((32, 32), [1.0, 0.0, 0.0]), ((96, 32), [0.0, 1.0, 0.0]), ((32, 96), [0.0, 0.0, 1.0]), ((96, 96), [grey; 3])] { - assert!(at(x, y).iter().zip(want).all(|(a, b)| (a - b).abs() < 2e-3), "texel {x},{y}: {:?} vs {want:?}", at(x, y)); +/// Check the alpha at the center of each baked quadrant +fn assert_opacity_quadrants(session: &Session) { + let opacity = &session.doc.baked[&0].maps[&BakedMap::Opacity]; + for ((x, y), alpha) in [((32, 32), 255.0), ((96, 32), 128.0), ((32, 96), 64.0), ((96, 96), 32.0)] { + let actual = opacity[y * 128 + x]; + assert!((actual - alpha / 255.0).abs() < 2e-3, "texel {x},{y}: {actual} vs {alpha}/255"); } } @@ -237,46 +367,48 @@ fn textured_glb(mesh: &Mesh, dy: f32, png: &[u8]) -> Vec { } #[test] -fn color_map_samples_a_textured_gltf_high_poly() { - let mut s = plane_session(); - let low = s.mesh.as_ref().clone(); +fn opacity_samples_a_textured_gltf_high_poly() { + let mut session = plane_session(); + let low = session.mesh.as_ref().clone(); let png = quadrants_png(); - s.add_high_poly_bytes("painted.glb", textured_glb(&low, 0.002, &png)).unwrap(); - assert!(s.log.iter().any(|l| l.contains("1 base color textures")), "{:?}", s.log); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map", "opacity"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); - assert!(s.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|o| *o > 0.99), "the high poly covers the plane"); - // The textures come back with the project. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.high[0].base_color, s.bake_meshes.high[0].base_color); + session.add_high_poly_bytes("painted.glb", textured_glb(&low, 0.002, &png)).unwrap(); + assert!(session.log.iter().any(|l| l.contains("1 base color textures")), "{:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|o| *o > 0.0), "the high poly covers the plane"); + + // The textures come back with the project + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color); } -/// The color map reads a USDZ high poly's UsdPreviewSurface texture like a glTF one. +/// USDZ opacity uses the UsdPreviewSurface texture alpha #[test] -fn color_map_samples_a_textured_usdz_high_poly() { +fn opacity_samples_a_textured_usdz_high_poly() { use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; - let mut s = plane_session(); - let mut high = s.mesh.as_ref().clone(); + let mut session = plane_session(); + let mut high = session.mesh.as_ref().clone(); for p in &mut high.positions { p.y += 0.002; } + let png = quadrants_png(); let texture = ExportedFile { name: "BaseColor.png".into(), bytes: png, width: 4, height: 4, warnings: vec![] }; let usdz = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usdz).unwrap().bytes; - s.add_high_poly_bytes("painted.usdz", usdz).unwrap(); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); + session.add_high_poly_bytes("painted.usdz", usdz).unwrap(); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); } -/// High polys whose textures are files next to them (a `.gltf` with its `.bin` and image, a loose -/// usda) are folded into one file on add, bake their color map, and come back with the project. +/// External glTF and USD textures remain available after saving the project #[test] -fn color_map_samples_textures_next_to_a_high_poly() { +fn opacity_samples_textures_next_to_a_high_poly() { use texturecraft_engine::formats::{ExportedFile, UsdFormat, usd_bytes}; let dir = std::env::temp_dir().join(format!("texturecraft-bake-external-{}", std::process::id())); std::fs::create_dir_all(dir.join("tex")).unwrap(); let low = plane_session().mesh.as_ref().clone(); - // The textured GLB taken apart: JSON, its .bin and the image as files. + + // The textured GLB taken apart: JSON, its .bin and the image as files let glb = textured_glb(&low, 0.002, &quadrants_png()); let jlen = u32::from_le_bytes(glb[12..16].try_into().unwrap()) as usize; let mut doc: Value = serde_json::from_slice(&glb[20..20 + jlen]).unwrap(); @@ -285,11 +417,13 @@ fn color_map_samples_textures_next_to_a_high_poly() { std::fs::write(dir.join("painted.bin"), &glb[20 + jlen + 8..]).unwrap(); std::fs::write(dir.join("tex/painted color.png"), quadrants_png()).unwrap(); std::fs::write(dir.join("painted.gltf"), serde_json::to_vec(&doc).unwrap()).unwrap(); - // The same high poly as a usda with its texture beside it. + + // The same high poly as a usda with its texture beside it let mut high = low.clone(); for p in &mut high.positions { p.y += 0.002; } + let texture = ExportedFile { name: "BaseColor.png".into(), bytes: quadrants_png(), width: 4, height: 4, warnings: vec![] }; let usda = usd_bytes(&high, "painted", &[vec![texture]], UsdFormat::Usda).unwrap(); for (name, bytes) in &usda.textures { @@ -297,21 +431,26 @@ fn color_map_samples_textures_next_to_a_high_poly() { } std::fs::write(dir.join("painted.usda"), &usda.bytes).unwrap(); for (file, stored) in [("painted.gltf", "painted.gltf"), ("painted.usda", "painted.usdz")] { - let mut s = plane_session(); - let r = execute(&mut s, "bake.highPoly.add", &json!({ "path": dir.join(file).display().to_string() })).unwrap(); - assert_eq!(r["name"], stored); - assert!(s.log.iter().any(|l| l.contains("1 base color textures")), "{file}: {:?}", s.log); - execute(&mut s, "bake.run", &json!({ "resolution": 128, "maps": ["color_map"], "dilation": 0 })).unwrap(); - assert_quadrants(&s); - // The project holds the folded file: the textures come back without the folder. - let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.high[0].base_color, s.bake_meshes.high[0].base_color, "{file}"); + let mut session = plane_session(); + let result = execute(&mut session, "bake.highPoly.add", &json!({ "path": dir.join(file).display().to_string() })).unwrap(); + assert_eq!(result["name"], stored); + assert!(session.log.iter().any(|l| l.contains("1 base color textures")), "{file}: {:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert_opacity_quadrants(&session); + + // The project holds the folded file: the textures come back without the folder + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.bake_meshes.high[0].base_color, session.bake_meshes.high[0].base_color, "{file}"); } - // A missing image is named in the log; the high poly still loads, untextured. + + // A missing image is named in the log; the high poly still loads, untextured std::fs::remove_file(dir.join("tex/painted color.png")).unwrap(); - let mut s = plane_session(); - execute(&mut s, "bake.highPoly.add", &json!({ "path": dir.join("painted.gltf").display().to_string() })).unwrap(); - assert!(s.log.iter().any(|l| l.contains("tex/painted color.png was not found")), "{:?}", s.log); + let mut session = plane_session(); + execute(&mut session, "bake.highPoly.add", &json!({ "path": dir.join("painted.gltf").display().to_string() })).unwrap(); + assert!(session.log.iter().any(|l| l.contains("tex/painted color.png was not found")), "{:?}", session.log); + execute(&mut session, "bake.run", &json!({ "resolution": 128, "maps": ["opacity"], "dilation": 0 })).unwrap(); + assert!(session.doc.baked[&0].maps[&BakedMap::Opacity].iter().all(|opacity| *opacity == 1.0)); + std::fs::remove_dir_all(&dir).unwrap(); } @@ -343,55 +482,10 @@ fn leaning_session(lean: bool) -> Session { s } -fn centre_height(s: &mut Session) -> f32 { - execute(s, "bake.run", &json!({ "cpu": true })).unwrap(); - s.doc.baked[&0].maps[&BakedMap::Height][64 * 128 + 64] -} - -#[test] -fn skew_correction_turns_the_transfer_rays_onto_the_base_normal() { - let flat = centre_height(&mut leaning_session(false)); - let mut s = leaning_session(true); - let leaning = centre_height(&mut s); - assert!((leaning - flat).abs() > 0.01, "leaning rays read a different height: {leaning} vs {flat}"); - - // Black changes nothing; white onto each triangle's flat normal matches the upright bake. - let r = execute(&mut s, "bake.skew.set", &json!({ "value": 0.0, "base": "triangle" })).unwrap(); - assert_eq!(r["skew"]["base"], "triangle"); - assert!((centre_height(&mut s) - leaning).abs() < 1e-6); - execute(&mut s, "bake.skew.set", &json!({ "value": 1.0, "base": "triangle", "edgeDistance": 0.1, "edgeContrast": 2.0 })).unwrap(); - assert_eq!(execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap()["skew"]["edgeContrast"], 2.0); - assert!((centre_height(&mut s) - flat).abs() < 1e-3, "skew-corrected: {} vs upright {flat}", centre_height(&mut s)); - - // A greyscale image over the atlas: white everywhere is the same as value 1. - let dir = std::env::temp_dir().join(format!("texturecraft-skew-test-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let png = dir.join("skew.png"); - image::GrayImage::from_pixel(4, 4, image::Luma([255])).save(&png).unwrap(); - execute(&mut s, "bake.skew.set", &json!({ "path": png.display().to_string(), "base": "triangle" })).unwrap(); - assert_eq!(execute(&mut s, "bake.highPoly.list", &Value::Null).unwrap()["skew"]["width"], 4); - assert!((centre_height(&mut s) - flat).abs() < 1e-3); - - // Clearing restores the plain bake; hostile input is an error and leaves the state alone. - execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert!((centre_height(&mut s) - leaning).abs() < 1e-6); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); - for bad in [ - json!({ "base": "sideways" }), - json!({ "edgeDistance": -1.0 }), - json!({ "edgeContrast": 0.0 }), - json!({ "path": dir.join("missing.png").display().to_string() }), - ] { - assert!(execute(&mut s, "bake.skew.set", &bad).is_err(), "{bad}"); - } - assert!(s.bake_meshes.skew.as_ref().is_some_and(|k| k.values == [0.5]), "a refused skew keeps the previous one"); - let _ = std::fs::remove_dir_all(&dir); -} - #[test] fn the_skew_map_is_saved_with_the_project() { let mut s = leaning_session(false); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.25, "edgeDistance": 0.1, "edgeContrast": 3.0, "base": "triangle" })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25, "edgeDistance": 0.1, "edgeContrast": 3.0 })).unwrap(); let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); assert_eq!(back.bake_meshes.skew, s.bake_meshes.skew); // No skew: none comes back. @@ -399,7 +493,7 @@ fn the_skew_map_is_saved_with_the_project() { assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().bake_meshes.skew.is_none()); // A map with a non-finite value is skipped with a log line, and the project still opens. let mut pf = s.project_file(); - pf.skew = Some(texturecraft_formats::SkewData { width: 1, height: 1, values: vec![f32::NAN], edge_distance: 0.0, edge_contrast: 1.0, per_triangle: false }); + pf.skew = Some(texturecraft_formats::SkewData { width: 1, height: 1, values: vec![f32::NAN], edge_distance: 0.0, edge_contrast: 1.0 }); let opened = Session::from_project_file(pf).unwrap(); assert!(opened.bake_meshes.skew.is_none() && opened.log.iter().any(|l| l.contains("skew")), "{:?}", opened.log); } diff --git a/crates/engine/tests/materialcraft_link.rs b/crates/engine/tests/materialcraft_link.rs index 057621b1..19931786 100644 --- a/crates/engine/tests/materialcraft_link.rs +++ b/crates/engine/tests/materialcraft_link.rs @@ -34,7 +34,13 @@ fn mcmat(roughness: f32, wear: f32) -> Vec { {"id": "tint", "label": "Tint", "default": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}, "value": {"t": "color", "v": [1.0, 1.0, 1.0, 1.0]}}, {"id": "note", "label": "Note", "default": {"t": "text", "v": ""}, "value": {"t": "text", "v": ""}} ], - "inputs": [{"identifier": "curvature", "kind": "gray"}], + "inputs": [ + {"identifier": "curvature", "kind": "gray"}, + {"identifier": "normal", "kind": "color"}, + {"identifier": "worldNormal", "kind": "color"}, + {"identifier": "ambientOcclusion", "kind": "gray"}, + {"identifier": "bentNormal", "kind": "color"} + ], "presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}], "source": "source.mcraft" }); @@ -86,7 +92,7 @@ fn imports_as_a_linked_fill_with_its_maps() { let l = link(&s, id); assert_eq!(l.graph, "Brick_wall"); assert_eq!(l.params.iter().map(|p| p.id.as_str()).collect::>(), ["wear", "tint"]); - assert_eq!(l.inputs, ["curvature"]); + assert_eq!(l.inputs, ["curvature", "normal", "worldNormal", "ambientOcclusion", "bentNormal"]); assert_eq!(s.doc.resources.get(&l.package).map(|b| b.as_slice()), Some(&b"package bytes"[..])); assert!(!s.images.contains_key(&l.package), "the package is not decoded as an image"); // Inspect shows the link; one undo removes everything. @@ -147,19 +153,18 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { #[test] fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { - let mut s = session(); - let id = s.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); - let dup = LayerId(execute(&mut s, "layer.duplicate", &json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap()); - let shared = map_name(&s, dup, Channel::Roughness); - s.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); - assert!(s.doc.resources.contains_key(&shared), "the duplicate still shows the first cook"); + let mut session = session(); + let id = session.add_linked_material_bytes_at(&mcmat(0.25, 0.5), Place::Selection).unwrap(); + let duplicate = LayerId(execute(&mut session, "layer.duplicate", &json!({"layer": id.0})).unwrap()["layer"].as_u64().unwrap()); + let shared = map_name(&session, duplicate, Channel::Roughness); + session.apply_link_cook(id, &mcmat(0.75, 0.5), false).unwrap(); + assert!(session.doc.resources.contains_key(&shared), "the duplicate still shows the first cook"); - s.doc.baked.insert(0, BakedMaps { resolution: 4, maps: [(BakedMap::Curvature, Arc::new(vec![0.5f32; 16]))].into_iter().collect() }); - let job = s.link_job(id, &serde_json::Map::new()).unwrap(); - assert_eq!(job.inputs.len(), 1); - assert_eq!(job.inputs[0].0, "curvature"); - assert_eq!(BakedMap::for_input("ambient_occlusion"), Some(BakedMap::AmbientOcclusion)); - assert_eq!(BakedMap::for_input("worldNormal"), Some(BakedMap::WorldNormal)); + let maps = [BakedMap::Curvature, BakedMap::Normal, BakedMap::WorldNormal, BakedMap::AmbientOcclusion, BakedMap::BentNormal]; + session.doc.baked.insert(0, BakedMaps { resolution: 4, maps: maps.into_iter().map(|map| (map, Arc::new(vec![0.5f32; 16 * map.components()]))).collect() }); + let job = session.link_job(id, &serde_json::Map::new()).unwrap(); + assert_eq!(job.inputs.iter().map(|(identifier, _)| identifier.as_str()).collect::>(), maps.map(BakedMap::id)); + assert_eq!(maps.map(BakedMap::id), ["curvature", "normal", "worldNormal", "ambientOcclusion", "bentNormal"]); } #[test] diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index e15a69bb..56118b01 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -382,9 +382,9 @@ fn images_fill_mesh_map_slots() { let mut s = session(); // Dark on the left, light on the right. let ao = s.import_resource_bytes("ao.png", png(8, 8, |x, _| if x < 4 { [64, 64, 64, 255] } else { [192, 192, 192, 255] })).unwrap(); - let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": ao})).unwrap(); - let res = s.doc.project.texture_sets[0].bake.resolution; - assert_eq!(r, json!({"map": "ambient_occlusion", "resolution": res})); + let r = execute(&mut s, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": ao})).unwrap(); + let res = s.doc.project.texture_sets[0].bake.common.resolution.pixels(); + assert_eq!(r, json!({"map": "ambientOcclusion", "resolution": res})); assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); @@ -396,10 +396,10 @@ fn images_fill_mesh_map_slots() { let v = sample(&s, BakedMap::Normal, 50); assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); // Clearing empties the slot (one undo step); bad params are errors. - execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).unwrap(); + execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).unwrap(); assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); - assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambient_occlusion"})).is_err(), "already empty"); + assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).is_err(), "already empty"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); assert!(execute(&mut s, "textureSet.meshMap.set", &json!({"map": "nope", "image": ao})).is_err()); diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/udim.rs index 6ba37904..bcfab00b 100644 --- a/crates/engine/tests/udim.rs +++ b/crates/engine/tests/udim.rs @@ -142,7 +142,7 @@ fn mesh_maps_from_images_take_one_image_per_tile() { image::RgbaImage::from_pixel(4, 4, image::Rgba([v, v, v, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); out }; - let set = |s: &mut Session, image: &str| execute(s, "textureSet.meshMap.set", &json!({"map": "ambient_occlusion", "image": image})); + let set = |s: &mut Session, image: &str| execute(s, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": image})); let left = s.import_resource_bytes("ao.1001.png", png(255)).unwrap(); assert!(set(&mut s, &left).unwrap_err().to_string().contains("ao.1002.png"), "tile 1002 has no image yet"); let plain = s.import_resource_bytes("ao.png", png(255)).unwrap(); diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 83e8cf46..8bf6ad66 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -200,7 +200,7 @@ fn ao_mixes_baked_and_channel() { let mesh_maps = fx.render_preset("Mesh maps"); assert_eq!(mesh_maps.len(), 1, "only baked maps are exported"); let ao = decode(&mesh_maps[0]); - assert_eq!(mesh_maps[0].name, "sphere_Body_Set_ambient_occlusion.png"); + assert_eq!(mesh_maps[0].name, "sphere_Body_Set_ambientOcclusion.png"); assert_eq!(ao.color(), image::ColorType::L16); } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..589b217a 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -6,7 +6,7 @@ //! | `mesh.` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:"`) | //! | `highpoly/` | a high-definition mesh file for baking, in list order | //! | `cage/` | the baking cage mesh file | -//! | `skew.bin` | the skew correction map of the bake (magic `TCSK`, version, width, height, edge distance, edge contrast, per-triangle flag; then `width × height` f32 LE) | +//! | `skew.bin` | the skew correction map of the bake (magic `TCSK`, version, width, height, edge distance, edge contrast, method byte (0 mesh normals, 1 triangle normals); then `width × height` f32 LE) | //! | `pixels/layer__.bin` | painted pixels of a paint layer (or content paint effect) channel | //! | `pixels/mask_.bin` | painted pixels of a mask paint effect | //! | `baked/_.bin` | a baked mesh map of texture set `` | @@ -53,7 +53,6 @@ pub struct SkewData { pub values: Vec, pub edge_distance: f32, pub edge_contrast: f32, - pub per_triangle: bool, } /// Everything a project file holds. @@ -190,7 +189,6 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { for v in [k.edge_distance, k.edge_contrast] { b.extend_from_slice(&v.to_le_bytes()); } - b.push(u8::from(k.per_triangle)); b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); zip.write_all(&b)?; } @@ -341,31 +339,34 @@ fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) } -/// The skew map entry: header, then the values. -fn read_skew(r: &mut impl Read, budget: &mut Budget, what: &str) -> Result { - let mut h = [0u8; 25]; - read_exact(r, &mut h, what)?; - if h.get(..4) != Some(SKEW_MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{what}: bad magic"))); +/// Decode the skew header and pixel values +fn read_skew(reader: &mut impl Read, budget: &mut Budget, entry: &str) -> Result { + let mut header = [0u8; 24]; + read_exact(reader, &mut header, entry)?; + if header.get(..4) != Some(SKEW_MAGIC.as_slice()) { + return Err(malformed(KIND, format!("{entry}: bad magic"))); } - let v = u32_at(&h, 1); - if v > BIN_VERSION { - return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION }); + + let version = u32_at(&header, 1); + if version > BIN_VERSION { + return Err(FormatError::NewerVersion { found: version, supported: BIN_VERSION }); } - let (w, ht) = (u32_at(&h, 2), u32_at(&h, 3)); - let (edge_distance, edge_contrast) = (f32::from_bits(u32_at(&h, 4)), f32::from_bits(u32_at(&h, 5))); - let per_triangle = h.get(24).is_some_and(|b| *b != 0); - if w == 0 || ht == 0 || u64::from(w) * u64::from(ht) > MAX_TEXELS { - return Err(malformed(KIND, format!("{what}: bad size {w}×{ht}"))); + + let (width, height) = (u32_at(&header, 2), u32_at(&header, 3)); + let (edge_distance, edge_contrast) = (f32::from_bits(u32_at(&header, 4)), f32::from_bits(u32_at(&header, 5))); + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS { + return Err(malformed(KIND, format!("{entry}: bad size {width}×{height}"))); } - let len = (w as usize) * (ht as usize); - budget.take(len as u64 * 4)?; - let mut bytes = vec![0u8; len * 4]; - read_exact(r, &mut bytes, what)?; - expect_end(r, what)?; - let values: Vec = bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); - // A map with a stray number is dropped by the caller's validation; here only the shape is checked. - Ok(SkewData { width: w, height: ht, values, edge_distance, edge_contrast, per_triangle }) + + let pixel_count = (width as usize) * (height as usize); + budget.take(pixel_count as u64 * 4)?; + let mut bytes = vec![0u8; pixel_count * 4]; + read_exact(reader, &mut bytes, entry)?; + expect_end(reader, entry)?; + + // The caller validates pixel values after decoding + let values = bytes.chunks_exact(4).map(|bytes| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])).collect(); + Ok(SkewData { width, height, values, edge_distance, edge_contrast }) } /// Texture set holding a paint layer, a content effect or a mask effect id. @@ -449,7 +450,7 @@ fn load(reader: R) -> Result { } else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) { let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?; - let m = BakedMap::ALL.into_iter().find(|m| m.id() == map).ok_or_else(|| malformed(KIND, format!("unknown baked map in {name}")))?; + let m = BakedMap::parse(map).ok_or_else(|| malformed(KIND, format!("unknown baked map in {name}")))?; if ts >= pf.project.texture_sets.len() { continue; } diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..34d9de7b 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -34,14 +34,7 @@ fn sample() -> Sample { mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])), high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])], cage: Some(("cage.obj".into(), vec![5, 5])), - skew: Some(SkewData { - width: 3, - height: 2, - values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125], - edge_distance: 0.05, - edge_contrast: 2.0, - per_triangle: true, - }), + skew: Some(SkewData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125], edge_distance: 0.05, edge_contrast: 2.0 }), thumbnail: Some(vec![137, 80, 78, 71]), resources: [("bricks.png".to_string(), vec![9, 8, 7])].into(), }; @@ -172,8 +165,8 @@ fn tiles_are_validated_against_the_texture_set() { let orphan = load_project_bytes(&zip_with(&[("pixels/layer_999_baseColor.bin", tile_bin(128, 4, &[(0, 0)]))])).unwrap(); assert!(orphan.pixels.layers.is_empty()); assert!(load_project_bytes(&zip_with(&[("pixels/layer_x_baseColor.bin", vec![])])).is_err()); - assert!(load_project_bytes(&zip_with(&[("baked/0_ambient_occlusion.bin", header(16, 16, 1, 0))])).is_err()); - assert!(load_project_bytes(&zip_with(&[("baked/0_ambient_occlusion.bin", header(100_000, 100_000, 1, 0))])).is_err()); + assert!(load_project_bytes(&zip_with(&[("baked/0_ambientOcclusion.bin", header(16, 16, 1, 0))])).is_err()); + assert!(load_project_bytes(&zip_with(&[("baked/0_ambientOcclusion.bin", header(100_000, 100_000, 1, 0))])).is_err()); } #[test] @@ -211,3 +204,24 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +#[test] +fn bake_model_options_survive_the_project_archive() { + use texturecraft_core::{BackfaceMode, CageType, HeightNormalization}; + + let mut project_file = sample().pf; + let settings = &mut project_file.project.texture_sets[0].bake; + settings.common.resolution_height = Some(texturecraft_core::BakeResolution::R256); + settings.cage.kind = CageType::CustomFile; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.curvature.parameters.mesh.sampling_radius = 0.002; + settings.maps.height.parameters.normalization = HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 4.0; + settings.skew.edge_protection = true; + settings.skew.edge_distance = 0.3; + + let bytes = save_project_bytes(&project_file).unwrap(); + assert_same(&project_file, &load_project_bytes(&bytes).unwrap()); +} diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 5dee6a02..028d91de 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, OnceLock}; use bytemuck::{Pod, Zeroable}; use rayon::prelude::*; use texturecraft_bake::BakeError; -use texturecraft_bake::rays::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh, Tracer}; +use texturecraft_bake::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh, Tracer}; use texturecraft_geom::Hit; use texturecraft_geom::glam::Vec3; @@ -351,9 +351,13 @@ impl RayScene for GpuScene<'_> { #[cfg(test)] mod tests { use std::time::Instant; + use texturecraft_core::{ + AmbientOcclusionSettings, BakeAntialiasing, BakeResolution, BentNormalSettings, CageSettings, CommonBakeSettings, CurvatureSettings, HighPolySettings, + ThicknessSettings, + }; use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, Progress, bake, bake_on}; - use texturecraft_core::{BakeMatch, BakeSettings, BakedMap, RayDistribution, RaySettings, SelfOcclusion}; + use texturecraft_core::{BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, RayDistribution, RaySettings, SelfOcclusion}; use texturecraft_geom::{Bvh, Mesh, primitives}; use super::*; @@ -397,23 +401,31 @@ mod tests { #[test] fn gpu_bake_matches_the_cpu() { - let Some(g) = gpu() else { return }; - // Low poly: the material ball (self-occluding); every ray map with its own settings. + let Some(gpu) = gpu() else { return }; + + // Low poly: the material ball (self-occluding); every ray map with its own settings let ball = primitives::material_ball(); let maps = [BakedMap::AmbientOcclusion, BakedMap::BentNormal, BakedMap::Thickness, BakedMap::Position, BakedMap::Curvature]; - let s = BakeSettings { - resolution: 128, - antialiasing: 2, - dilation: 0, - maps: maps.into_iter().collect(), - ao: RaySettings { rays: 24, max_distance: 0.3, spread: 150.0, distribution: RayDistribution::Uniform }, - ao_ignore_backface: true, - bent_normal: RaySettings { rays: 16, ..RaySettings::default() }, - thickness: RaySettings { rays: 20, spread: 90.0, ..RaySettings::default() }, - ..BakeSettings::default() + let settings = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R128, antialiasing: BakeAntialiasing::Subsampling2x2, dilation: 0, ..base.common }; + base.maps.select(maps); + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { rays: 24, max_distance: 0.3, spread: 150.0, distribution: RayDistribution::Uniform, ..RaySettings::default() }, + ignore_backface: BackfaceMode::Always, + ..base.maps.ao.parameters + }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base.maps.bent_normal.parameters = + BentNormalSettings { rays: RaySettings { rays: 16, ..RaySettings::default() }, ..base.maps.bent_normal.parameters }; + base.maps.thickness.parameters = + ThicknessSettings { rays: RaySettings { rays: 20, spread: 90.0, ..RaySettings::default() }, ..base.maps.thickness.parameters }; + base }; - assert_agree(&run(&ball, None, &s, None), &run(&ball, None, &s, Some(&g))); - // A bumpy high poly over a sphere, matched by name: the transfer maps and AO on it. + + assert_agree(&run(&ball, None, &settings, None), &run(&ball, None, &settings, Some(&gpu))); + + // A bumpy high poly over a sphere, matched by name: the transfer maps and AO on it let low = primitives::sphere(1.0, 32, 16); let mut high = primitives::sphere(1.0, 128, 64); for p in &mut high.positions { @@ -422,22 +434,30 @@ mod tests { high.compute_normals(); high.compute_tangents(); high.submeshes[0].name = format!("{}_high", low.submeshes[0].name); - let s = BakeSettings { - resolution: 128, - dilation: 0, - maps: [BakedMap::Normal, BakedMap::Height, BakedMap::Id, BakedMap::Opacity, BakedMap::AmbientOcclusion, BakedMap::WorldNormal, BakedMap::Curvature] - .into_iter() - .collect(), - max_frontal: 0.02, - max_rear: 0.02, - matching: BakeMatch::ByMeshName, - low_suffix: String::new(), - ao: RaySettings { rays: 16, ..RaySettings::default() }, - ao_self_occlusion: SelfOcclusion::SameMeshName, - use_low_as_high: false, - ..BakeSettings::default() + let settings = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R128, dilation: 0, ..base.common }; + base.maps.select([ + BakedMap::Normal, + BakedMap::Height, + BakedMap::Id, + BakedMap::Opacity, + BakedMap::AmbientOcclusion, + BakedMap::WorldNormal, + BakedMap::Curvature, + ]); + base.cage = CageSettings { max_frontal: 0.02, max_rear: 0.02, ..base.cage }; + base.high_poly = HighPolySettings { low_suffix: String::new(), use_low_as_high: false, ..base.high_poly }; + base.maps.ao.parameters = AmbientOcclusionSettings { + rays: RaySettings { rays: 16, ..RaySettings::default() }, + self_occlusion: SelfOcclusion::SameMeshName, + ..base.maps.ao.parameters + }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; + base }; - assert_agree(&run(&low, Some(&high), &s, None), &run(&low, Some(&high), &s, Some(&g))); + + assert_agree(&run(&low, Some(&high), &settings, None), &run(&low, Some(&high), &settings, Some(&gpu))); } /// `cargo test -p texturecraft-render --release -- --ignored --nocapture gpu_bake_speed` @@ -447,8 +467,24 @@ mod tests { let Some(g) = gpu() else { return }; let ball = primitives::material_ball(); let rays = RaySettings { rays: 64, ..RaySettings::default() }; - let s = BakeSettings { resolution: 2048, ao: rays, thickness: rays, bent_normal: rays, ..BakeSettings::default() }; - run(&ball, None, &BakeSettings { resolution: 64, ..s.clone() }, Some(&g)); + let s = { + let mut base = BakeSettings::default(); + base.common = CommonBakeSettings { resolution: BakeResolution::R2048, ..base.common }; + base.maps.ao.parameters = AmbientOcclusionSettings { rays, ..base.maps.ao.parameters }; + base.maps.thickness.parameters = ThicknessSettings { rays, ..base.maps.thickness.parameters }; + base.maps.bent_normal.parameters = BentNormalSettings { rays, ..base.maps.bent_normal.parameters }; + base + }; + run( + &ball, + None, + &{ + let mut base = s.clone(); + base.common = CommonBakeSettings { resolution: BakeResolution::R64, ..base.common }; + base + }, + Some(&g), + ); let time = |t: Option<&GpuBaker>| { let start = Instant::now(); let out = run(&ball, None, &s, t); @@ -460,16 +496,20 @@ mod tests { println!("GPU again (warm clocks): {gpu_t2:.2?}"); println!( "material ball 2048², {} maps, 64 rays: CPU {cpu_t:.2?}, {} {gpu_t:.2?}, {:.1}x", - s.maps.len(), + s.maps.enabled().count(), gpu.tracer, cpu_t.as_secs_f64() / gpu_t.as_secs_f64() ); assert_agree(&cpu, &gpu); for maps in [vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness]] { - let s = BakeSettings { maps: maps.into_iter().collect(), ..s.clone() }; + let s = { + let mut base = s.clone(); + base.maps.select(maps); + base + }; let start = Instant::now(); run(&ball, None, &s, Some(&g)); - println!("{:?}: {:.2?}", s.maps, start.elapsed()); + println!("{:?}: {:.2?}", s.maps.enabled().collect::>(), start.elapsed()); } } } diff --git a/crates/render/src/shaders/bake.wgsl b/crates/render/src/shaders/bake.wgsl index f321bc84..76241fbc 100644 --- a/crates/render/src/shaders/bake.wgsl +++ b/crates/render/src/shaders/bake.wgsl @@ -1,4 +1,4 @@ -// GPU mesh-map baking: the ray casts of `texturecraft_bake::rays` (the CPU oracle) as compute +// GPU mesh-map baking: the ray casts of `texturecraft_bake::tracing` (the CPU oracle) as compute // shaders, concatenated after rays.wgsl. `transfer_main` finds the closest high-poly hit of each // transfer ray; `hemisphere_main` casts a query's secondary rays (ambient occlusion and bent // normal, or thickness) in the same directions as `Hemisphere::direction`, spread over `lanes` diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs new file mode 100644 index 00000000..6d4f0e1b --- /dev/null +++ b/crates/ui-egui/src/bake_mode.rs @@ -0,0 +1,95 @@ +//! Bake Mode presentation; persisted settings live in core and edits use engine commands + +mod common_settings; +mod controls; +mod map_settings; + +use egui::{Ui, vec2}; +use serde_json::json; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::widgets::primary_button; + +pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { + for set_index in 0..app.session.set_count() { + let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; + + let name = texture_set.name.clone(); + let (width, height) = texture_set.bake.common.output_size(); + let mut is_enabled = texture_set.bake.common.is_enabled; + ui.push_id(set_index, |ui| { + ui.horizontal(|ui| { + if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); + } + if ui.selectable_label(set_index == app.session.ts(), format!("{name} ({width} × {height})")).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + }); + }); + } + }); +} + +pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "bake_maps", |_, ui, settings| { + for map in BakedMap::ALL { + ui.push_id(map, |ui| map_settings::show(ui, map, &mut settings.maps)); + ui.add_space(6.0); + } + }); +} + +pub fn settings_body(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "bake_common_settings", common_settings::show); +} + +fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { + let set_index = app.session.ts(); + let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; + + let mut settings = before.clone(); + egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)); + if settings != before { + app.run("bake.settings", json!({ "ts": set_index, "model": settings })); + } +} + +pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( + ctx, + |ui| { + ui.horizontal(|ui| { + if let Some(progress) = app.bake_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); + if ui.button(tr("Cancel")).clicked() { + app.cancel_bake(); + } + } else { + let texture_sets: Vec = app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) + .map(|(index, _)| index) + .collect(); + let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); + if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + app.start_bake(texture_sets); + } + } + + if ui.button(tr("Return to Painting Mode")).clicked() { + app.ui.mode = Mode::Painting; + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs new file mode 100644 index 00000000..ac666c04 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -0,0 +1,165 @@ +use super::controls::{choice, hint, integer, number, section, text_input}; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::icon_button; +use egui::Ui; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, CageType, CommonBakeSettings}; + +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + ui.push_id("common", |ui| { + let is_enabled = settings.common.is_enabled; + if section(ui, tr("Common Parameters"), None, |ui| { + output_size(ui, &mut settings.common); + choice( + ui, + tr("Antialiasing"), + &mut settings.common.antialiasing, + &[ + (BakeAntialiasing::None, tr("None")), + (BakeAntialiasing::Subsampling2x2, tr("Subsampling 2x2")), + (BakeAntialiasing::Subsampling4x4, tr("Subsampling 4x4")), + (BakeAntialiasing::Subsampling8x8, tr("Subsampling 8x8")), + ], + ); + integer(ui, tr("Dilation Width"), &mut settings.common.dilation, 0..=128); + ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); + }) { + settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; + } + }); + ui.add_space(8.0); + ui.push_id("high_poly", |ui| { + if section(ui, tr("High-Poly Parameters"), None, |ui| { + ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); + high_poly_files(app, ui); + if !app.session.bake_meshes.high.is_empty() { + ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); + text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); + text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); + } + }) { + settings.high_poly = Default::default(); + } + }); + if !app.session.bake_meshes.high.is_empty() { + ui.add_space(8.0); + ui.push_id("cage", |ui| { + if section(ui, tr("Cage"), None, |ui| { + choice( + ui, + tr("Cage Type"), + &mut settings.cage.kind, + &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], + ); + match settings.cage.kind { + CageType::DistanceBased => { + ui.add_enabled(false, egui::Button::new(tr("Paint Cage"))); + number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); + number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); + ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); + ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); + } + CageType::CustomFile => cage_file(app, ui), + } + }) { + settings.cage = Default::default(); + } + }); + if settings.cage.kind == CageType::DistanceBased { + ui.add_space(8.0); + ui.push_id("skew", |ui| { + if section(ui, tr("Skew Correction"), None, |ui| { + skew_brush(app, ui); + ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); + number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }) { + settings.skew = Default::default(); + } + }); + } + } +} + +fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { + ui.label(tr("Output Size")); + ui.horizontal(|ui| { + let dropdown_width = ((ui.available_width() - 24.0 - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); + let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { + egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { + for resolution in BakeResolution::ALL { + ui.selectable_value(value, resolution, resolution.pixels().to_string()); + } + }); + }; + resolution(ui, "output_width", &mut settings.resolution); + let locked = settings.resolution_height.is_none(); + let mut height = settings.resolution_height.unwrap_or(settings.resolution); + ui.add_enabled_ui(!locked, |ui| resolution(ui, "output_height", &mut height)); + if !locked { + settings.resolution_height = Some(height); + } + if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, 24.0).clicked() { + settings.resolution_height = if locked { Some(settings.resolution) } else { None }; + } + }); +} + +fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.label(tr("High Poly Scene")); + let meshes: Vec<_> = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); + let mut remove = None; + for (index, name) in meshes.iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized([ui.available_width() - 24.0, 24.0], egui::Label::new(name).truncate()).on_hover_text(name); + if icon_button(ui, icon::TRASH, tr("Remove"), false, 20.0).clicked() { + remove = Some(index); + } + }); + } + if meshes.is_empty() { + hint(ui, tr("No High-Poly Meshes")); + } + if let Some(index) = remove { + app.run("bake.highPoly.remove", json!({ "index": index })); + } + if ui.button(tr("Add High-Poly Meshes")).clicked() { + crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); + } +} + +fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.label(tr("Cage Scene")); + let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); + ui.horizontal(|ui| { + ui.add_sized([ui.available_width() - 52.0, 24.0], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, 20.0).clicked() { + crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); + } + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, 20.0).clicked() { + app.run("bake.cage.clear", json!({})); + } + }); +} + +fn skew_brush(app: &mut TextureCraftApp, ui: &mut Ui) { + let mut brush = app.ui.skew_brush; + if ui.add(egui::Button::new(tr("Paint Skew Correction")).selected(brush.on)).clicked() { + brush.on = !brush.on; + } + if brush.on { + number(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); + number(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); + number(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + } + if brush.on && !app.ui.skew_brush.on && app.ui.layout == crate::state::ViewLayout::Only3D { + app.ui.layout = crate::state::ViewLayout::Split; + } + app.ui.skew_brush = brush; + if app.session.bake_meshes.skew.is_some() && ui.button(tr("Remove Skew Correction")).clicked() { + app.run("bake.skew.clear", json!({})); + } +} diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs new file mode 100644 index 00000000..4c2e6b88 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -0,0 +1,116 @@ +use crate::i18n::tr; +use crate::theme::{Tokens, caption}; +use egui::collapsing_header::CollapsingState; +use egui::{RichText, Ui}; + +pub(super) fn section_header(ui: &mut Ui, title: &str, mut is_enabled: Option<&mut bool>, collapsing_state: Option<&mut CollapsingState>) -> bool { + let tokens = Tokens::get(ui.ctx()); + let text_color = if is_enabled.as_deref().copied().unwrap_or(true) { tokens.text_strong } else { tokens.text_dim }; + let mut checkbox_rect = None; + let mut arrow_rect = None; + + let header = egui::Frame::NONE.fill(tokens.row).corner_radius(tokens.cr()).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { + ui.set_min_width(ui.available_width()); + ui.horizontal(|ui| { + ui.set_min_height(ui.spacing().interact_size.y); + let checkbox = is_enabled.as_deref_mut().map(|is_enabled| ui.checkbox(is_enabled, "")); + let title_response = ui.add(egui::Label::new(caption(title).color(text_color)).selectable(false)); + if let Some(checkbox) = checkbox { + checkbox_rect = Some(checkbox.rect); + checkbox.labelled_by(title_response.id); + } + + if collapsing_state.is_some() { + arrow_rect = Some( + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 + }) + .inner, + ); + } + }); + }); + + if let (Some(collapsing_state), Some(arrow_rect)) = (collapsing_state, arrow_rect) { + let mut toggle_rect = header.response.rect; + if let Some(checkbox_rect) = checkbox_rect { + let checkbox_margin = ui.spacing().item_spacing.x * 0.5; + if ui.style().right_to_left { + toggle_rect.max.x = checkbox_rect.left() - checkbox_margin; + } else { + toggle_rect.min.x = checkbox_rect.right() + checkbox_margin; + } + } + + let response = ui.interact(toggle_rect, ui.make_persistent_id("section_header"), egui::Sense::click()); + if response.clicked() { + collapsing_state.toggle(ui); + } + + let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); + ui.put(arrow_rect, egui::Label::new(chevron).selectable(false)); + } + + is_enabled.as_deref().copied().unwrap_or(true) +} + +pub(super) fn section(ui: &mut Ui, title: &str, is_enabled: Option<&mut bool>, contents: impl FnOnce(&mut Ui)) -> bool { + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); + if !section_header(ui, title, is_enabled, Some(&mut collapsing_state)) { + collapsing_state.store(ui.ctx()); + return false; + } + + collapsing_state + .show_body_unindented(ui, |ui| { + egui::Frame::NONE + .inner_margin(egui::Margin::same(8)) + .show(ui, |ui| { + contents(ui); + ui.add_space(6.0); + ui.button(tr("Restore Defaults")).clicked() + }) + .inner + }) + .is_some_and(|response| response.inner) +} + +pub(super) fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { + let caption = ui.label(label); + let selected = options.iter().find(|(option, _)| option == value).map_or("", |(_, label)| *label); + egui::ComboBox::from_id_salt(label) + .width(ui.available_width()) + .selected_text(selected) + .show_ui(ui, |ui| { + for (option, label) in options { + ui.selectable_value(value, *option, *label); + } + }) + .response + .labelled_by(caption.id); +} + +pub(super) fn number(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { + let response = crate::widgets::slider(ui, label, value, range.clone(), decimals); + if response.changed() && (response.dragged() || response.clicked()) { + let scale = 10_f32.powi(decimals as i32); + *value = ((*value * scale).round() / scale).clamp(*range.start(), *range.end()); + } +} + +pub(super) fn integer(ui: &mut Ui, label: &str, value: &mut u32, range: std::ops::RangeInclusive) { + let mut number_value = *value as f32; + let response = crate::widgets::slider(ui, label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0); + if response.changed() { + *value = (number_value.round() as u32).clamp(*range.start(), *range.end()); + } +} + +pub(super) fn text_input(ui: &mut Ui, label: &str, value: &mut String) { + ui.label(label); + ui.add(egui::TextEdit::singleline(value).desired_width(ui.available_width())); +} + +pub(super) fn hint(ui: &mut Ui, text: &str) { + ui.label(RichText::new(text).color(Tokens::get(ui.ctx()).text_dim).size(11.0)); +} diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs new file mode 100644 index 00000000..2a07ce3d --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -0,0 +1,184 @@ +use super::controls::{choice, integer, number, section, section_header}; +use crate::i18n::{baked_map_label, tr}; +use egui::Ui; +use texturecraft_engine::core::{ + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, + HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, + PositionSettings, RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, +}; + +pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { + match map { + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { + let mut is_enabled = settings.is_enabled(map); + section_header(ui, tr(baked_map_label(map)), Some(&mut is_enabled), None); + settings.set_enabled(map, is_enabled); + } + BakedMap::Id => baker(ui, map, &mut settings.id, id), + BakedMap::AmbientOcclusion => baker(ui, map, &mut settings.ao, ambient_occlusion), + BakedMap::Curvature => baker(ui, map, &mut settings.curvature, curvature), + BakedMap::Position => baker(ui, map, &mut settings.position, position), + BakedMap::Thickness => baker(ui, map, &mut settings.thickness, thickness), + BakedMap::Height => baker(ui, map, &mut settings.height, height), + BakedMap::BentNormal => baker(ui, map, &mut settings.bent_normal, bent_normal), + } +} + +fn baker(ui: &mut Ui, map: BakedMap, settings: &mut MapSettings, controls: impl FnOnce(&mut Ui, &mut T)) { + if section(ui, tr(baked_map_label(map)), Some(&mut settings.is_enabled), |ui| controls(ui, &mut settings.parameters)) { + settings.parameters = T::default(); + } +} + +fn id(ui: &mut Ui, settings: &mut IdSettings) { + choice( + ui, + tr("Color Source"), + &mut settings.source, + &[ + (IdColorSource::VertexColor, tr("Vertex Color")), + (IdColorSource::MaterialColor, tr("Material Color")), + (IdColorSource::FileId, tr("File ID")), + (IdColorSource::MeshId, tr("Mesh ID")), + (IdColorSource::Submesh, tr("Submesh")), + ], + ); + if matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh) { + choice( + ui, + tr("Color Generator"), + &mut settings.generator, + &[(IdColorGenerator::Random, tr("Random")), (IdColorGenerator::HueShift, tr("Hue Shift")), (IdColorGenerator::Grayscale, tr("Grayscale"))], + ); + } +} + +fn rays(ui: &mut Ui, settings: &mut RaySettings) { + integer(ui, tr("Secondary Rays"), &mut settings.rays, 1..=256); + number(ui, tr("Min Occluder Distance"), &mut settings.min_distance, 0.00001..=1.0, 5); + number(ui, tr("Max Occluder Distance"), &mut settings.max_distance, 0.00001..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); + if ui.checkbox(&mut settings.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && settings.relative_to_bounding_box { + settings.max_distance = settings.max_distance.min(1.0); + } + number(ui, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); + choice(ui, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); +} + +fn backface(ui: &mut Ui, settings: &mut BackfaceMode) { + choice( + ui, + tr("Ignore Backface"), + settings, + &[(BackfaceMode::Never, tr("Never")), (BackfaceMode::Always, tr("Always")), (BackfaceMode::ByMeshName, tr("By Mesh Name"))], + ); +} + +fn occlusion(ui: &mut Ui, label: &str, settings: &mut SelfOcclusion) { + choice(ui, label, settings, &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only Same Mesh Name"))]); +} + +fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { + rays(ui, &mut settings.rays); + backface(ui, &mut settings.ignore_backface); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); + choice( + ui, + tr("Attenuation"), + &mut settings.attenuation, + &[ + (AmbientOcclusionAttenuation::None, tr("None")), + (AmbientOcclusionAttenuation::Smooth, tr("Smooth")), + (AmbientOcclusionAttenuation::Linear, tr("Linear")), + ], + ); + ui.checkbox(&mut settings.ground_plane.enabled, tr("Ground Plane")); + if settings.ground_plane.enabled { + number(ui, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2); + } +} + +fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { + choice( + ui, + tr("Method"), + &mut settings.method, + &[(CurvatureMethod::NormalMap, tr("Generate from Normal Map")), (CurvatureMethod::Mesh, tr("Generate from Mesh"))], + ); + match settings.method { + CurvatureMethod::NormalMap => { + number(ui, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); + ui.checkbox(&mut settings.normal_map.enable_seams, tr("Enable Seams")); + if settings.normal_map.enable_seams { + number(ui, tr("Seams Intensity"), &mut settings.normal_map.seams_intensity, 0.0..=1.0, 2); + } + } + CurvatureMethod::Mesh => { + let mesh = &mut settings.mesh; + integer(ui, tr("Secondary Rays"), &mut mesh.rays, 1..=256); + number(ui, tr("Sampling Radius"), &mut mesh.sampling_radius, 0.00001..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); + if ui.checkbox(&mut mesh.relative_to_bounding_box, tr("Relative to Bounding Box")).changed() && !mesh.relative_to_bounding_box { + mesh.sampling_radius = mesh.sampling_radius.min(1.0); + } + occlusion(ui, tr("Self Intersection"), &mut mesh.self_intersection); + ui.checkbox(&mut mesh.auto_tonemapping, tr("Auto Tonemapping")); + if mesh.auto_tonemapping { + number(ui, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); + number(ui, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); + } + } + } +} + +fn position(ui: &mut Ui, settings: &mut PositionSettings) { + choice(ui, tr("Axis"), &mut settings.axis, &[(PositionAxis::All, tr("All")), (PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); + choice( + ui, + tr("Normalization Type"), + &mut settings.normalization, + &[(PositionMode::BoundingBox, tr("BBox")), (PositionMode::BoundingSphere, tr("BSphere")), (PositionMode::None, tr("None"))], + ); + choice( + ui, + tr("Normalization Scale"), + &mut settings.scale, + &[(PositionNormalizationScale::PerMaterial, tr("Per Material")), (PositionNormalizationScale::FullScene, tr("Full Scene"))], + ); +} + +fn thickness(ui: &mut Ui, settings: &mut ThicknessSettings) { + rays(ui, &mut settings.rays); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); + choice( + ui, + tr("Normalization"), + &mut settings.normalization, + &[ + (ThicknessNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), + (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (ThicknessNormalization::None, tr("None")), + ], + ); +} + +fn height(ui: &mut Ui, settings: &mut HeightSettings) { + choice( + ui, + tr("Normalization"), + &mut settings.normalization, + &[ + (HeightNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), + (HeightNormalization::RelativeToLowMesh, tr("Relative to Low Mesh")), + (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (HeightNormalization::Manual, tr("Manual")), + ], + ); + if settings.normalization == HeightNormalization::Manual { + number(ui, tr("Scaling Divisor"), &mut settings.scaling_divisor, 0.00001..=100.0, 5); + } +} + +fn bent_normal(ui: &mut Ui, settings: &mut BentNormalSettings) { + rays(ui, &mut settings.rays); + backface(ui, &mut settings.ignore_backface); + occlusion(ui, tr("Self Occlusion"), &mut settings.self_occlusion); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 471f164d..3a74a80b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1,4 +1,4 @@ -//! Panel bodies of the right column: Texture Set List, Layers, Texture Set Settings, Properties +//! Panel bodies of the right column: Texture Sets, Layers, Texture Set Settings, Properties //! (hosted as dock tabs by `docking`). use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; @@ -827,7 +827,7 @@ pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { let (r, _) = ui.allocate_exact_size(vec2(26.0, 26.0), Sense::hover()); ui.painter().rect_filled(r, 2.0, if present { mesh_map_color(m) } else { tk.button }); ui.vertical(|ui| { - ui.label(RichText::new(tr(m.label())).strong()); + ui.label(RichText::new(tr(crate::i18n::baked_map_label(m))).strong()); ui.label( RichText::new(if present { format!("{}_{}", set.name, m.id()) } else { tr("Missing (bake to create)").into() }) .size(10.5) @@ -892,8 +892,8 @@ fn image_drop(ui: &Ui, resp: &egui::Response) -> Option { } } -fn mesh_map_color(m: BakedMap) -> Color32 { - match m { +fn mesh_map_color(map: BakedMap) -> Color32 { + match map { BakedMap::Normal => Color32::from_rgb(128, 128, 255), BakedMap::WorldNormal => Color32::from_rgb(120, 200, 140), BakedMap::Id => Color32::from_rgb(220, 60, 60), @@ -904,8 +904,6 @@ fn mesh_map_color(m: BakedMap) -> Color32 { BakedMap::Height => Color32::from_gray(128), BakedMap::BentNormal => Color32::from_rgb(140, 170, 230), BakedMap::Opacity => Color32::from_gray(230), - BakedMap::ColorMap => Color32::from_rgb(200, 150, 90), - BakedMap::WorldDirection => Color32::from_gray(180), } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index ed23f88a..11de63af 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -24,6 +24,8 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, + BakeMaps, + BakeSettings, TextureSetList, Layers, TextureSetSettings, @@ -35,8 +37,10 @@ pub enum Panel { } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 9] = [ +pub const VIEWS: [(&str, Panel); 11] = [ ("ui.view.assets", Panel::Assets), + ("ui.view.bakeMaps", Panel::BakeMaps), + ("ui.view.bakeSettings", Panel::BakeSettings), ("ui.view.display", Panel::Display), ("ui.view.history", Panel::History), ("ui.view.layers", Panel::Layers), @@ -53,9 +57,19 @@ pub fn view_panel(id: &str) -> Option { } impl Panel { - pub const ALL: [Panel; 10] = [ + pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { + match self { + Self::BakeMaps | Self::BakeSettings => mode == crate::state::Mode::Baking, + Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings => mode != crate::state::Mode::Baking, + _ => true, + } + } + + pub const ALL: [Panel; 12] = [ Panel::Viewport, Panel::Assets, + Panel::BakeMaps, + Panel::BakeSettings, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, @@ -70,7 +84,9 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - Panel::TextureSetList => "Texture Set List", + Panel::BakeMaps => "Bake Maps", + Panel::BakeSettings => "Settings", + Panel::TextureSetList => "Texture Sets", Panel::Layers => "Layers", Panel::TextureSetSettings => "Texture Set Settings", Panel::Properties => "Properties", @@ -133,6 +149,20 @@ pub fn default_workspace() -> Workspace { workspace.hidden.push((panel, location)); } } + for panel in [BakeMaps, BakeSettings] { + workspace.hidden.push(( + panel, + Location { + floating: None, + anchor: Some(TextureSetList), + placement: Placement::Tab { before: None }, + size: None, + stack: None, + sibling: Vec::new(), + group: None, + }, + )); + } workspace } @@ -222,6 +252,26 @@ impl Dock { Dock { workspace, raise: None } } + pub(crate) fn for_baking() -> Self { + let mut workspace = default_workspace(); + for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { + if let Ok(location) = workspace.layout.location(&panel) { + workspace.hidden.push((panel, location)); + } + } + workspace.hidden.retain(|(panel, _)| !matches!(panel, Panel::BakeMaps | Panel::BakeSettings)); + workspace.layout = Layout { + root: Some(Node::Split { + axis: SplitAxis::Horizontal, + size: SplitSize::FixedFirst(320.0), + first: Box::new(tabs(&[Panel::TextureSetList, Panel::BakeSettings, Panel::BakeMaps])), + second: Box::new(tabs(&[Panel::Viewport])), + }), + floating: Vec::new(), + }; + Dock { workspace, raise: None } + } + pub fn workspace(&self) -> &Workspace { &self.workspace } @@ -306,24 +356,29 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle { /// Draw the dock (viewport and panels) into `ui`. pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { - let ctx = ui.ctx().clone(); - let tk = Tokens::get(&ctx); - let style = style(ui, &tk); + for panel in Panel::ALL { + if !panel.available_in(app.ui.mode) && app.ui.dock.is_open(panel) { + app.ui.dock.close(panel); + } + } + + let context = ui.ctx().clone(); + let tokens = Tokens::get(&context); + let style = style(ui, &tokens); let layout = app.ui.dock.workspace.layout.clone(); - let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some()); + let mut area = DockArea::new(area_id()).input_blocked(context.memory(|memory| memory.top_modal_layer()).is_some()); if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk: tokens }); #[cfg(not(target_arch = "wasm32"))] - crate::menus::forwarded_shortcuts(app, &ctx, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); + crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); if let Some(error) = &output.error { log::warn!("docking: {error}"); } - // A body that changed the layout (a panel opened from its own menu) wins over this frame's - // gestures, which were made against the old one. + // A layout changed by a panel takes priority over gestures from the old layout if app.ui.dock.workspace.layout != layout { - craft_ui::docking::cancel_drag::(&ctx, area_id()); + craft_ui::docking::cancel_drag::(&context, area_id()); return; } for action in output.actions { @@ -346,8 +401,10 @@ impl DockContent for Panels<'_> { return; } egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::Assets if app.ui.mode == crate::state::Mode::Baking => crate::windows::bake_body(app, ui), + Panel::BakeMaps => crate::bake_mode::bake_body(app, ui), Panel::Assets => crate::shelf::body(app, ui), + Panel::BakeSettings => crate::bake_mode::settings_body(app, ui), + Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), Panel::TextureSetList => crate::dock::texture_set_list(app, ui), Panel::Layers => crate::dock::layers(app, ui), Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), @@ -368,8 +425,8 @@ impl DockContent for Panels<'_> { fn logical_label(&self, panel: &Panel) -> String { match panel { Panel::Properties => crate::dock::properties_title(self.app), - // Bake mode shows its settings where the shelf lives. - Panel::Assets if self.app.ui.mode == crate::state::Mode::Baking => tr("Bake Mesh Maps").to_string(), + Panel::BakeMaps => tr("Bake Maps").to_string(), + Panel::BakeSettings => tr("Settings").to_string(), p => tr(p.name()).to_string(), } } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index c0aee844..fe2fc5e4 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -70,7 +70,7 @@ static PALETTE: LazyLock = LazyLock::new(|| { [ (n_("Texture set channels"), Channel::ALL.iter().map(|&channel| (channel.label(), SourceRef::Channel { channel, component: 0 })).collect()), (n_("Converted maps"), VirtualMap::ALL.iter().map(|&map| (map.label(), SourceRef::Virtual { map, component: 0 })).collect()), - (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (map.label(), SourceRef::Baked { map, component: 0 })).collect()), + (n_("Mesh maps"), BakedMap::ALL.iter().map(|&map| (crate::i18n::baked_map_label(map), SourceRef::Baked { map, component: 0 })).collect()), (n_("Constants"), vec![(n_("Black"), SourceRef::Constant(0.0)), (n_("Gray 50%"), SourceRef::Constant(0.5)), (n_("White"), SourceRef::Constant(1.0))]), ] }); @@ -79,7 +79,7 @@ fn source_label(s: &SourceRef) -> &'static str { match s { SourceRef::Channel { channel, .. } => channel.label(), SourceRef::Virtual { map, .. } => map.label(), - SourceRef::Baked { map, .. } => map.label(), + SourceRef::Baked { map, .. } => crate::i18n::baked_map_label(*map), SourceRef::Constant(_) => n_("Constant"), } } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f9106d57..80105c00 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -47,6 +47,24 @@ pub static LANGUAGES: [Language; COUNT] = [ static MAPS: [OnceLock>; COUNT] = [const { OnceLock::new() }; COUNT]; static CURRENT: AtomicUsize = AtomicUsize::new(0); +/// Display labels belong to the UI; the model exposes only map identities +pub(crate) fn baked_map_label(map: texturecraft_engine::core::BakedMap) -> &'static str { + use texturecraft_engine::core::BakedMap; + + match map { + BakedMap::Normal => n_("Normal"), + BakedMap::WorldNormal => n_("World Space Normal"), + BakedMap::Id => n_("ID"), + BakedMap::AmbientOcclusion => n_("Ambient Occlusion"), + BakedMap::Curvature => n_("Curvature"), + BakedMap::Position => n_("Position"), + BakedMap::Thickness => n_("Thickness"), + BakedMap::Height => n_("Height"), + BakedMap::BentNormal => n_("Bent Normals"), + BakedMap::Opacity => n_("Opacity"), + } +} + /// Switch the UI language (unknown codes fall back to English). pub fn set_language(code: &str) { CURRENT.store(LANGUAGES.iter().position(|l| l.code == code).unwrap_or(0), Ordering::Relaxed); @@ -128,10 +146,15 @@ mod tests { fn keys() -> Vec { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); let mut keys = Vec::new(); - for entry in std::fs::read_dir(&dir).unwrap() { - let path = entry.unwrap().path(); - if path.extension().is_some_and(|e| e == "rs") { - literals(&std::fs::read_to_string(&path).unwrap(), &mut keys); + let mut directories = vec![dir]; + while let Some(directory) = directories.pop() { + for entry in std::fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() && path.file_name().is_some_and(|name| name != "i18n") { + directories.push(path); + } else if path.extension().is_some_and(|extension| extension == "rs") { + literals(&std::fs::read_to_string(path).unwrap(), &mut keys); + } } } keys.extend(catalog_keys().into_iter().map(str::to_owned)); @@ -143,7 +166,7 @@ mod tests { /// The labels of the menu catalog, panels, shortcuts, shelf tabs and engine enums that are /// translated where they are shown. fn catalog_keys() -> Vec<&'static str> { - use texturecraft_engine::core::{BakedMap, BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; + use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params}; let mut k: Vec<&'static str> = Vec::new(); k.extend(crate::menus::TOP); @@ -159,7 +182,6 @@ mod tests { k.extend(crate::shelf::TABS.iter().map(|t| t.2)); k.extend(Channel::ALL.iter().flat_map(|c| [c.label(), c.short()])); k.extend(BlendMode::all().map(|m| m.label())); - k.extend(BakedMap::ALL.iter().map(|m| m.label())); k.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|m| m.label())); k.extend(texturecraft_engine::Tool::ALL.iter().map(|t| t.label())); k.extend(ProceduralKind::ALL.iter().map(|p| p.label())); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 939b0b3c..2ca825e0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -44,7 +44,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "إضافة مرشح"), ("Add folder", "إضافة مجلد"), ("Add generator", "إضافة مولّد"), - ("Add high definition meshes", "إضافة مجسمات عالية الدقة"), ("Add levels", "إضافة مستويات"), ("Add mask", "إضافة قناع"), ("Add mask with color selection", "إضافة قناع مع تحديد لوني"), @@ -80,7 +79,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "مرتبط أيضاً بـ {item} ({menu})"), ("Alt + LMB drag", "سحب بـ Alt + زر الفأرة الأيسر"), ("Always", "دائماً"), - ("Ambient occlusion", "الانسداد المحيطي (AO)"), + ("Ambient Occlusion", "الانسداد المحيطي (AO)"), ("Ambient occlusion intensity", "شدة الانسداد المحيطي"), ("Amount", "المقدار"), ("Anchor point", "نقطة ارتكاز"), @@ -96,7 +95,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), ("Apply", "تطبيق"), - ("Apply to all texture sets", "تطبيق على جميع مجموعات الخامات"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), @@ -105,7 +103,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "تُحفظ النسخ التلقائية والمواد الذكية والإعدادات المسبقة والقوالب وتخطيطات الواجهة في مجلد البيانات. يُطبَّق المجلد الجديد عند إعادة التشغيل، وتبقى الملفات المحفوظة في مكانها.", ), - ("Average normals", "توسيط النواظم"), ("Axis", "المحور"), ("Back to painting", "العودة إلى الرسم"), ("Backface culling", "استبعاد الوجوه الخلفية"), @@ -115,8 +112,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "اخبز خرائط المجسم (F8) للمولدات المعتمدة على الانحناء والانسداد المحيطي والسماكة.", ), - ("Bake selected textures ({n})", "خبز الخامات المحددة ({n})"), - ("Bake with \"Bake selected textures\"", "اخبز باستخدام \"خبز الخامات المحددة\""), ("Baked Lighting", "إضاءة مخبوزة"), ("Baking", "الخبز"), ("Base color", "اللون الأساسي"), @@ -127,7 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "اللون الأساسي، المعدنية، الخشونة ومستوى اللمعان."), ("Based on each texture set's size", "بناءً على حجم كل مجموعة خامات"), ("Basic settings", "الإعدادات الأساسية"), - ("Bent normals", "النواظم المنحنية"), + ("Bent Normals", "النواظم المنحنية"), ("Bevel", "شطف الحواف"), ("Black", "أسود"), ("Blend sharpness", "حدة المزج"), @@ -145,7 +140,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "مدمج (للقراءة فقط): انسخه لتعديله"), ("Built-in templates are read-only: duplicate one to edit it", "القوالب المدمجة للقراءة فقط: انسخ قالباً لتعديله"), ("Built-in: {mesh}", "مدمج: {mesh}"), - ("By mesh name", "حسب اسم المجسم"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), ("Camera settings", "إعدادات الكاميرا"), @@ -177,7 +171,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "توازن الألوان"), ("Color burn", "حرق لوني (Color Burn)"), ("Color dodge", "تفتيح لوني (Color Dodge)"), - ("Color map", "خريطة الألوان"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "لون الضوء المنتقل تحت السطح (تصل كل قناة بقدر قيمتها)"), ("Color picker", "منتقي الألوان"), ("Color selection", "تحديد لوني"), @@ -185,7 +178,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Colors near the first shift towards the second, keeping their shading.", "الألوان القريبة من الأولى تتحول نحو الثانية مع الحفاظ على تظليلها."), ("Colors read as gray. Add a levels or blur effect above to shape the result.", "تُقرأ الألوان كرمادي. أضف تأثير مستويات أو تمويه في الأعلى لتشكيل النتيجة."), ("Combine with the layer's height", "الدمج مع ارتفاع الطبقة"), - ("Common parameters", "المعلمات المشتركة"), ("Compare mask", "قناع مقارنة"), ("Compositing", "التركيب"), ("Constant", "ثابت"), @@ -198,7 +190,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "نسخ من"), ("Copy layer(s)", "نسخ الطبقة (الطبقات)"), ("Copy the selected layer alone (its empty parts copy nothing)", "نسخ الطبقة المحددة وحدها (الأجزاء الفارغة لا تنسخ شيئاً)"), - ("Copy these bake settings to every texture set", "نسخ إعدادات الخبز هذه إلى كل مجموعة خامات"), ("Copy to all texture sets", "نسخ إلى جميع مجموعات الخامات"), ("Copy what the texture set shows", "نسخ ما تعرضه مجموعة الخامات"), ("Couldn't encode the render", "تعذر ترميز التصيير"), @@ -246,8 +237,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "تمديد + لون الخلفية الافتراضي"), ("Dilation + transparent", "تمديد + شفاف"), ("Dilation infinite", "تمديد لا نهائي"), - ("Dilation width", "عرض التمديد"), - ("Direction {axis}", "الاتجاه {axis}"), ("DirectX normal map", "خريطة نواظم DirectX"), ("Dirt", "أوساخ"), ("Disable", "تعطيل"), @@ -348,11 +337,6 @@ pub const TABLE: &[(&str, &str)] = &[ "للمشروع كله: طريقة قراءة صور خرائط النواظم المعيَّنة كخرائط للمجسم (أعد تعيينها بعد التغيير) والقيمة الافتراضية للتصدير", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "مجاني ومفتوح المصدر (MIT أو Apache-2.0)، كُتب بلغة Rust."), - ("From normal map", "من خريطة النواظم"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "من خريطة النواظم: انحناء تفاصيل خريطة النواظم المخبوزة بدلاً من المجسم.", - ), ("From template", "من قالب"), ("From template / project", "من قالب / مشروع"), ("Full", "كامل"), @@ -392,12 +376,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "مساعدة"), ("Hide UI", "إخفاء واجهة المستخدم"), ("High", "عالي"), - ("High definition meshes", "مجسمات عالية الدقة"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "ارتفاع المجسم عالي الدقة بين المسافة الخلفية القصوى (أسود) والأمامية القصوى (أبيض).", - ), - ("High poly mesh suffix", "لاحقة المجسم عالي الدقة"), ("High poly: {name}", "عالي الدقة: {name}"), ("Highlights", "المناطق المضيئة"), ("Histogram Range", "نطاق المدرج التكراري"), @@ -482,11 +460,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "ضوء خطي (Linear Light)"), ("List of exports", "قائمة الصادرات"), ("Load UI Layout", "تحميل تخطيط الواجهة"), - ("Load a cage (the low poly, inflated)", "تحميل القفص (مجسم منخفض الدقة منتفخ)"), ("Loaded UI layout {path}", "تم تحميل تخطيط الواجهة {path}"), ("Log", "السجل"), ("Low", "منخفض"), - ("Low poly mesh suffix", "لاحقة المجسم منخفض الدقة"), ("Luminosity", "اللمعان (Luminosity)"), ("MMB drag / Alt + MMB", "سحب بزر الفأرة الأوسط / Alt + زر الفأرة الأوسط"), ("Made by the ArtCraft team and community.", "صُنع بواسطة فريق ArtCraft والمجتمع."), @@ -500,17 +476,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "إنهاء المادة: مطروق"), ("MatFinish Raw", "إنهاء المادة: خام"), ("MatFinish Sanded", "إنهاء المادة: مصنفر"), - ("Match", "مطابقة"), ("Material", "المادة"), ("Material ball", "كرة المادة"), ("Material finish", "إنهاء المادة"), ("Materials", "المواد"), - ("Max frontal distance", "أقصى مسافة أمامية"), - ("Max occluder distance", "أقصى مسافة للحاجب"), - ("Max rear distance", "أقصى مسافة خلفية"), ("Maximum", "الحد الأقصى"), ("Mesh fill", "تعبئة المجسم"), - ("Mesh map bakers", "خَبّازو خرائط المجسم"), ("Mesh map: {map}", "خريطة المجسم: {map}"), ("Mesh maps", "خرائط المجسم"), ("Mesh maps baked", "تم خبز خرائط المجسم"), @@ -546,7 +517,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "كمية الضوضاء"), ("Noise scale", "مقياس الضوضاء"), ("None", "بلا"), - ("None: the low poly is its own high poly.", "بلا: المجسم منخفض الدقة هو نفسه عالي الدقة."), ("Normal", "عادي"), ("Normal DirectX", "ناظم DirectX"), ("Normal Invert", "عكس الناظم"), @@ -575,7 +545,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "إزاحة {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "يزيح الخامات وفق قناة الارتفاع، بقوة تحويل الارتفاع إلى ناظم"), ("On", "مفعل"), - ("One color per mesh part.", "لون واحد لكل جزء من المجسم."), ("Opacity", "العتامة"), ("Open sample project...", "فتح مشروع نموذجي..."), ("Open...", "فتح..."), @@ -589,7 +558,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "دليل الإخراج"), ("Output high", "المخرج العالي"), ("Output low", "المخرج المنخفض"), - ("Output size", "حجم المخرج"), ("Output template", "قالب الإخراج"), ("Output templates", "قوالب الإخراج"), ("Overlay", "تراكب (Overlay)"), @@ -663,7 +631,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "إعادة"), ("Reimport mesh", "إعادة استيراد المجسم"), - ("Relative to the bounding box diagonal.", "نسبة إلى قطر المربع المحيط."), ("Remove", "إزالة"), ("Remove channel", "إزالة القناة"), ("Remove effect", "إزالة التأثير"), @@ -672,7 +639,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), ("Remove mask", "إزالة القناع"), ("Remove resource", "إزالة المورد"), - ("Remove the cage", "إزالة القفص"), ("Remove the path (Esc)", "إزالة المسار (Esc)"), ("Remove the shortcut", "إزالة الاختصار"), ("Remove this output", "إزالة هذا المخرج"), @@ -695,13 +661,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), - ("Return to painting mode", "العودة إلى نمط الرسم"), ("Return to this step", "العودة إلى هذه الخطوة"), - ("Auto-rebake", "إعادة الخبز تلقائيًا"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "يعيد خبز هذه الخريطة تلقائيًا عند تغيّر إعدادات الخبز أو المجسّم منخفض الدقة أو المجسّمات عالية الدقة", - ), ("Right-click a layer > Create smart material", "انقر بزر الفأرة الأيمن على طبقة > إنشاء مادة ذكية"), ("Rotation", "التدوير"), ("Rotation (degrees)", "التدوير (بالدرجات)"), @@ -731,7 +691,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), - ("Secondary rays", "أشعة ثانوية"), ("Seed", "البذرة العشوائية (Seed)"), ("Select a layer", "تحديد طبقة"), ("Select an output template", "تحديد قالب إخراج"), @@ -799,13 +758,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "تناظر (X)"), ("Symmetry (Y)", "تناظر (Y)"), ("Tangent | Wrap", "مماس | التفاف"), - ("Tangent-space normals of the high definition meshes.", "نواظم فضاء المماس للمجسمات عالية الدقة."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "تنعيم حواف زمني (يحسّن العرض ثلاثي الأبعاد أثناء ثباته)"), - ("Texture Set List", "قائمة مجموعات الخامات"), + ("Texture Sets", "مجموعات الخامات"), ("Texture Set Settings", "إعدادات مجموعة الخامات"), ("Texture resolution", "دقة الخامة"), ("Texture set channels", "قنوات مجموعة الخامات"), - ("Texture set list", "قائمة مجموعات الخامات"), ("Texture sets", "مجموعات الخامات"), ("TextureCraft had to close:", "اضطر TextureCraft إلى الإغلاق:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - خشونة ومعدنية"), @@ -857,7 +814,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Uniform value", "قيمة موحدة"), ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "استخدم كألفا للفرشاة (أو اسحبها إلى منفذ العرض أو خصائص الفرشاة)"), - ("Use low poly mesh as high poly mesh", "استخدام المجسم منخفض الدقة كمجسم عالي الدقة"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), @@ -878,15 +834,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "العجلة / سحب بـ Alt + زر الفأرة الأيمن"), ("White", "أبيض"), - ("White where the surface faces the direction, black where it faces away.", "أبيض حيث يواجه السطح الاتجاه، وأسود حيث يتجه بعيداً عنه."), ("Width", "العرض"), ("Width (texels at 2K)", "العرض (تكسل بدقة 2K)"), ("Window", "نافذة"), ("Wood grain", "حبيبات الخشب"), ("Works in texture space, like the blur: it does not cross UV seams.", "يعمل في فضاء الخامات، مثل التمويه: لا يعبر درزات UV."), - ("World space direction", "اتجاه الفضاء العالمي"), - ("World space normal", "ناظم الفضاء العالمي"), - ("World-space normals of the high poly (or the low poly).", "نواظم الفضاء العالمي للمجسم عالي الدقة (أو منخفض الدقة)."), + ("World Space Normal", "ناظم الفضاء العالمي"), ("Yellow / blue", "أصفر / أزرق"), ("Zoom", "تكبير/تصغير"), ("a missing layer", "طبقة مفقودة"), @@ -923,7 +876,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: إضافة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات أو إلى منفذ العرض)", ), - ("{name} ({n} triangles)", "{name} ({n} مثلث)"), ("{name} copy", "نسخة من {name}"), ("{n} bits", "{n} بت"), ( @@ -934,28 +886,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (المقياس {scale}، البذرة {seed})"), ("Template name", "اسم القالب"), ("Save current project as template", "حفظ المشروع الحالي كقالب"), - ("Spread angle", "زاوية الانتشار"), ("Distribution", "التوزيع"), ("Cosine", "جيب التمام (Cosine)"), ("Uniform", "موحد (Uniform)"), - ("Ignore backface", "تجاهل الوجه الخلفي"), - ("Self occlusion", "انسداد ذاتي"), - ("Only same mesh name", "نفس اسم المجسم فقط"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "أشعة النواظم المنحنية تتبع إعدادات حاجب الانسداد المحيطي."), - ("Sampling radius", "نصف قطر العينات"), - ("0 picks a radius from the output size.", "0 يختار نصف القطر تلقائياً من حجم المخرج."), - ("Encoding", "الترميز"), - ("Signed (-1..1)", "ذو إشارة (-1..1)"), - ("Positive (0..1)", "موجب (0..1)"), ("Normalization", "تسوية (Normalization)"), - ("Bounding box", "المربع المحيط"), - ("Bounding sphere", "الكرة المحيطة"), - ("Position normalized to the low poly's bounding box or sphere.", "الموضع مُسوّى بالنسبة للمربع أو الكرة المحيطة للمجسم منخفض الدقة."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "الألوان الأساسية (الخامات، المعاملات) وألوان الرؤوس للمجسمات عالية الدقة.", - ), - ("White where the high poly covers the low poly, times its alpha.", "أبيض حيث يغطي المجسم عالي الدقة المجسم منخفض الدقة، مضروباً في قيمة ألفا."), ("Brightness", "السطوع"), ("Dark", "داكن"), ("Medium dark", "متوسط الدكنة"), @@ -1001,12 +935,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "تغييرات غير محفوظة"), ("Don't save", "عدم الحفظ"), ("Save the changes to {name} before closing?", "هل تريد حفظ التغييرات في {name} قبل الإغلاق؟"), - ("Skew correction", "تصحيح الانحراف"), - ("Paint skew in the 2D view", "ارسم الانحراف في العرض ثنائي الأبعاد"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "اسحب في العرض ثنائي الأبعاد لرسم المواضع التي تنعطف فيها أشعة الخَبْز نحو الناظم الأساسي؛ ارسم بالقيمة 0 للمسح", - ), ("Radius", "نصف القطر"), ("Remove skew correction", "إزالة تصحيح الانحراف"), ("Twill weave", "نسيج مائل"), @@ -1026,4 +954,85 @@ pub const TABLE: &[(&str, &str)] = &[ "فُتحت في MaterialCraft: استخدم هناك ملف > إرسال إلى TextureCraft لإعادة تغييراتك", ), ("Parameters change in the desktop app, with MaterialCraft installed", "تتغير المعلمات في تطبيق سطح المكتب مع تثبيت MaterialCraft"), + ("Add High-Poly Meshes", "إضافة مجسمات عالية التفاصيل"), + ("All", "الكل"), + ("Apply Diffusion", "تطبيق الانتشار"), + ("Attenuation", "التوهين"), + ("Auto Tonemapping", "تعيين درجات الألوان تلقائيًا"), + ("Average Normals", "توسيط النواظم"), + ("BBox", "صندوق الإحاطة"), + ("BSphere", "كرة الإحاطة"), + ("Bake Maps", "خبز الخرائط"), + ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), + ("By Mesh Name", "حسب اسم المجسم"), + ("Cage", "القفص"), + ("Cage Scene", "مشهد القفص"), + ("Cage Type", "نوع القفص"), + ("Color Generator", "مولد الألوان"), + ("Color Source", "مصدر اللون"), + ("Common Parameters", "المعلمات المشتركة"), + ("Custom File", "ملف مخصص"), + ("Details", "التفاصيل"), + ("Dilation Width", "عرض التمديد"), + ("Distance-Based", "حسب المسافة"), + ("Edge Contrast", "تباين الحواف"), + ("Edge Distance", "مسافة الحواف"), + ("Edge Protection", "حماية الحواف"), + ("Enable Seams", "تفعيل الوصلات"), + ("File ID", "معرّف الملف"), + ("Full Scene", "المشهد الكامل"), + ("Generate from Mesh", "إنشاء من المجسم"), + ("Generate from Normal Map", "إنشاء من خريطة المتجهات العمودية"), + ("Ground Plane", "مستوى الأرض"), + ("Ground Plane Offset", "إزاحة مستوى الأرض"), + ("High Poly Mesh Suffix", "لاحقة المجسم عالي الدقة"), + ("High Poly Scene", "مشهد عالي التفاصيل"), + ("High-Poly Parameters", "معلمات المجسم عالي التفاصيل"), + ("Hue Shift", "إزاحة تدرج اللون"), + ("Ignore Backface", "تجاهل الوجه الخلفي"), + ("Ignore Backface Suffix", "لاحقة تجاهل الوجه الخلفي"), + ("Include in Bake", "تضمين في الخبز"), + ("Load Cage", "تحميل القفص"), + ("Lock Output Size", "قفل حجم الإخراج"), + ("Low Poly Mesh Suffix", "لاحقة المجسم منخفض الدقة"), + ("Manual", "يدوي"), + ("Material Color", "لون المادة"), + ("Max Frontal Distance", "أقصى مسافة أمامية"), + ("Max Occluder Distance", "أقصى مسافة للحاجب"), + ("Max Rear Distance", "أقصى مسافة خلفية"), + ("Mesh ID", "معرّف المجسم"), + ("Method", "الطريقة"), + ("Min Occluder Distance", "أدنى مسافة للحاجب"), + ("Never", "أبدًا"), + ("No High-Poly Meshes", "لا توجد مجسمات عالية التفاصيل"), + ("Normalization Scale", "نطاق التطبيع"), + ("Normalization Type", "نوع التطبيع"), + ("Only Same Mesh Name", "نفس اسم المجسم فقط"), + ("Output Size", "حجم المخرج"), + ("Paint Cage", "رسم القفص"), + ("Paint Skew Correction", "رسم تصحيح الميل"), + ("Per Material", "لكل مادة"), + ("Random", "عشوائي"), + ("Relative to Bounding Box", "بالنسبة إلى صندوق الإحاطة"), + ("Relative to Low Mesh", "بالنسبة إلى المجسم منخفض التفاصيل"), + ("Relative to Min/Max", "بالنسبة إلى الحد الأدنى والأقصى"), + ("Relative to Ray Distances", "بالنسبة إلى مسافات الأشعة"), + ("Remove Cage", "إزالة القفص"), + ("Remove Skew Correction", "إزالة تصحيح الانحراف"), + ("Restore Defaults", "استعادة الإعدادات الافتراضية"), + ("Return to Painting Mode", "العودة إلى نمط الرسم"), + ("Sampling Radius", "نصف قطر العينات"), + ("Scaling Divisor", "قاسم المقياس"), + ("Seams Intensity", "شدة الوصلات"), + ("Secondary Rays", "أشعة ثانوية"), + ("Self Intersection", "التقاطع الذاتي"), + ("Self Occlusion", "انسداد ذاتي"), + ("Skew Correction", "تصحيح الانحراف"), + ("Smooth", "ناعم"), + ("Spread Angle", "زاوية الانتشار"), + ("Submesh", "مجسم فرعي"), + ("Use Low Poly Mesh as High Poly Mesh", "استخدام المجسم منخفض الدقة كمجسم عالي الدقة"), + ("Value Bounds Max", "الحد الأقصى للقيمة"), + ("Value Bounds Min", "الحد الأدنى للقيمة"), + ("Vertex Color", "لون الرأس"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ae02fbd2..7e626046 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -47,7 +47,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Filter hinzufügen"), ("Add folder", "Ordner hinzufügen"), ("Add generator", "Generator hinzufügen"), - ("Add high definition meshes", "Hochauflösende Meshes hinzufügen"), ("Add levels", "Tonwertkorrektur hinzufügen"), ("Add mask", "Maske hinzufügen"), ("Add mask with color selection", "Maske mit Farbauswahl hinzufügen"), @@ -83,7 +82,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Auch belegt für {item} ({menu})"), ("Alt + LMB drag", "Alt + LMT ziehen"), ("Always", "Immer"), - ("Ambient occlusion", "Ambient Occlusion"), + ("Ambient Occlusion", "Ambient Occlusion"), ("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"), ("Amount", "Stärke"), ("Anchor point", "Ankerpunkt"), @@ -99,7 +98,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), ("Apply", "Anwenden"), - ("Apply to all texture sets", "Auf alle Textursets anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), @@ -108,15 +106,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Automatische Sicherungen, Smart-Materialien, Vorgaben, Vorlagen und UI-Layouts werden im Datenordner gespeichert. Ein neuer Ordner gilt nach einem Neustart; bereits gespeicherte Dateien bleiben, wo sie sind.", ), - ("Average normals", "Normalen mitteln"), ("Axis", "Achse"), ("Back to painting", "Zurück zum Malen"), ("Backface culling", "Rückseiten-Culling"), ("Bake Mesh Maps", "Mesh-Maps backen"), ("Bake mesh maps", "Mesh-Maps backen"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."), - ("Bake selected textures ({n})", "Ausgewählte Texturen backen ({n})"), - ("Bake with \"Bake selected textures\"", "Backen mit „Ausgewählte Texturen backen“"), ("Baked Lighting", "Gebackene Beleuchtung"), ("Baking", "Backen"), ("Base color", "Grundfarbe"), @@ -127,7 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Grundfarbe, Metallisch, Rauheit und Specular-Stärke."), ("Based on each texture set's size", "Basierend auf der Größe jedes Textursets"), ("Basic settings", "Grundeinstellungen"), - ("Bent normals", "Gebogene Normalen"), + ("Bent Normals", "Gebogene Normalen"), ("Bevel", "Abschrägung"), ("Black", "Schwarz"), ("Blend sharpness", "Übergangsschärfe"), @@ -145,7 +140,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integriert (schreibgeschützt): zum Bearbeiten duplizieren"), ("Built-in templates are read-only: duplicate one to edit it", "Integrierte Vorlagen sind schreibgeschützt: zum Bearbeiten eine duplizieren"), ("Built-in: {mesh}", "Integriert: {mesh}"), - ("By mesh name", "Nach Mesh-Name"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), ("Camera settings", "Kameraeinstellungen"), @@ -180,7 +174,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Farbbalance"), ("Color burn", "Farbig nachbelichten"), ("Color dodge", "Farbig abwedeln"), - ("Color map", "Farb-Map"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Farbe des Lichts, das unter der Oberfläche wandert (jeder Kanal reicht so weit wie sein Wert)", @@ -197,7 +190,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Farben werden als Grau gelesen. Darüber eine Tonwertkorrektur oder einen Weichzeichnen-Effekt hinzufügen, um das Ergebnis zu formen.", ), ("Combine with the layer's height", "Mit der Höhe der Ebene kombinieren"), - ("Common parameters", "Gemeinsame Parameter"), ("Compare mask", "Vergleichsmaske"), ("Compositing", "Compositing"), ("Constant", "Konstante"), @@ -210,7 +202,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Kopieren aus"), ("Copy layer(s)", "Ebene(n) kopieren"), ("Copy the selected layer alone (its empty parts copy nothing)", "Nur die ausgewählte Ebene kopieren (ihre leeren Bereiche kopieren nichts)"), - ("Copy these bake settings to every texture set", "Diese Back-Einstellungen in jedes Texturset kopieren"), ("Copy to all texture sets", "In alle Textursets kopieren"), ("Copy what the texture set shows", "Kopieren, was das Texturset anzeigt"), ("Couldn't encode the render", "Das Rendering konnte nicht kodiert werden"), @@ -261,8 +252,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatation + Standard-Hintergrundfarbe"), ("Dilation + transparent", "Dilatation + transparent"), ("Dilation infinite", "Dilatation unendlich"), - ("Dilation width", "Dilatationsbreite"), - ("Direction {axis}", "Richtung {axis}"), ("DirectX normal map", "DirectX-Normal-Map"), ("Dirt", "Schmutz"), ("Disable", "Deaktivieren"), @@ -372,11 +361,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Für das ganze Projekt: wie Normal-Map-Bilder als Mesh-Maps gelesen werden (nach einer Änderung neu zuweisen), und die Vorgabe für den Export", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Frei und quelloffen (MIT OR Apache-2.0), geschrieben in Rust."), - ("From normal map", "Aus Normal-Map"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Aus Normal-Map: Krümmung der Details der gebackenen Normal-Map statt des Meshs.", - ), ("From template", "Aus Vorlage"), ("From template / project", "Aus Vorlage / Projekt"), ("Full", "Voll"), @@ -416,12 +400,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Hilfe"), ("Hide UI", "UI ausblenden"), ("High", "Hoch"), - ("High definition meshes", "Hochauflösende Meshes"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "High-Poly-Höhe zwischen maximaler hinterer (schwarz) und maximaler vorderer (weiß) Distanz.", - ), - ("High poly mesh suffix", "Suffix für High-Poly-Mesh"), ("High poly: {name}", "High-Poly: {name}"), ("Highlights", "Lichter"), ("Histogram Range", "Histogrammbereich"), @@ -509,11 +487,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Lineares Licht"), ("List of exports", "Exportliste"), ("Load UI Layout", "UI-Layout laden"), - ("Load a cage (the low poly, inflated)", "Cage laden (das aufgeblähte Low-Poly)"), ("Loaded UI layout {path}", "UI-Layout {path} geladen"), ("Log", "Protokoll"), ("Low", "Niedrig"), - ("Low poly mesh suffix", "Suffix für Low-Poly-Mesh"), ("Luminosity", "Luminanz"), ("MMB drag / Alt + MMB", "MMT ziehen / Alt + MMT"), ("Made by the ArtCraft team and community.", "Entwickelt vom ArtCraft-Team und der Community."), @@ -527,17 +503,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Gehämmert"), ("MatFinish Raw", "MatFinish Roh"), ("MatFinish Sanded", "MatFinish Geschmirgelt"), - ("Match", "Zuordnung"), ("Material", "Material"), ("Material ball", "Materialkugel"), ("Material finish", "Materialoberfläche"), ("Materials", "Materialien"), - ("Max frontal distance", "Max. vordere Distanz"), - ("Max occluder distance", "Max. Verdeckerdistanz"), - ("Max rear distance", "Max. hintere Distanz"), ("Maximum", "Maximum"), ("Mesh fill", "Mesh-Füllung"), - ("Mesh map bakers", "Mesh-Map-Baker"), ("Mesh map: {map}", "Mesh-Map: {map}"), ("Mesh maps", "Mesh-Maps"), ("Mesh maps baked", "Mesh-Maps gebacken"), @@ -576,7 +547,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Rauschstärke"), ("Noise scale", "Rauschskalierung"), ("None", "Keine"), - ("None: the low poly is its own high poly.", "Keine: Das Low-Poly ist sein eigenes High-Poly."), ("Normal", "Normale"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Normale invertieren"), @@ -608,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Verschiebt die Texturen anhand des Höhenkanals, mit der Stärke Höhe zu Normale", ), ("On", "Ein"), - ("One color per mesh part.", "Eine Farbe pro Mesh-Teil."), ("Opacity", "Deckkraft"), ("Open sample project...", "Beispielprojekt öffnen..."), ("Open...", "Öffnen..."), @@ -622,7 +591,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "Ausgabeverzeichnis"), ("Output high", "Ausgabe hoch"), ("Output low", "Ausgabe tief"), - ("Output size", "Ausgabegröße"), ("Output template", "Ausgabevorlage"), ("Output templates", "Ausgabevorlagen"), ("Overlay", "Ineinanderkopieren"), @@ -702,7 +670,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Wiederholen"), ("Reimport mesh", "Mesh neu importieren"), - ("Relative to the bounding box diagonal.", "Relativ zur Diagonale des Begrenzungsrahmens."), ("Remove", "Entfernen"), ("Remove channel", "Kanal entfernen"), ("Remove effect", "Effekt entfernen"), @@ -711,7 +678,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "Ebene(n) entfernen"), ("Remove mask", "Maske entfernen"), ("Remove resource", "Ressource entfernen"), - ("Remove the cage", "Cage entfernen"), ("Remove the path (Esc)", "Pfad entfernen (Esc)"), ("Remove the shortcut", "Tastenkürzel entfernen"), ("Remove this output", "Diese Ausgabe entfernen"), @@ -737,13 +703,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), - ("Return to painting mode", "Zurück zum Malmodus"), ("Return to this step", "Zu diesem Schritt zurückkehren"), - ("Auto-rebake", "Automatisch neu backen"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Diese Map automatisch neu backen, wenn sich ihre Bake-Einstellungen, das Low-Poly- oder die High-Poly-Meshes ändern", - ), ("Right-click a layer > Create smart material", "Rechtsklick auf eine Ebene > Smart-Material erstellen"), ("Rotation", "Drehung"), ("Rotation (degrees)", "Drehung (Grad)"), @@ -773,7 +733,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), - ("Secondary rays", "Sekundärstrahlen"), ("Seed", "Startwert"), ("Select a layer", "Ebene auswählen"), ("Select an output template", "Ausgabevorlage auswählen"), @@ -841,13 +800,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "Symmetrie (X)"), ("Symmetry (Y)", "Symmetrie (Y)"), ("Tangent | Wrap", "Tangente | Umhüllen"), - ("Tangent-space normals of the high definition meshes.", "Tangentenraum-Normalen der hochauflösenden Meshes."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Temporale Kantenglättung (verfeinert die 3D-Ansicht im Stillstand)"), - ("Texture Set List", "Texturset-Liste"), + ("Texture Sets", "Textursets"), ("Texture Set Settings", "Texturset-Einstellungen"), ("Texture resolution", "Texturauflösung"), ("Texture set channels", "Texturset-Kanäle"), - ("Texture set list", "Texturset-Liste"), ("Texture sets", "Textursets"), ("TextureCraft had to close:", "TextureCraft musste beendet werden:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallisch/Rauheit"), @@ -902,7 +859,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "Als Pinsel-Alpha verwenden (oder in das Ansichtsfenster oder die Pinseleigenschaften ziehen)", ), - ("Use low poly mesh as high poly mesh", "Low-Poly-Mesh als High-Poly-Mesh verwenden"), ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), ("Value", "Wert"), ("Version {version}", "Version {version}"), @@ -923,10 +879,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Mausrad / Alt + RMT ziehen"), ("White", "Weiß"), - ( - "White where the surface faces the direction, black where it faces away.", - "Weiß, wo die Oberfläche in die Richtung zeigt, schwarz, wo sie abgewandt ist.", - ), ("Width", "Breite"), ("Width (texels at 2K)", "Breite (Texel bei 2K)"), ("Window", "Fenster"), @@ -935,9 +887,7 @@ pub const TABLE: &[(&str, &str)] = &[ "Works in texture space, like the blur: it does not cross UV seams.", "Arbeitet im Texturraum wie das Weichzeichnen: UV-Nähte werden nicht überschritten.", ), - ("World space direction", "Richtung (Weltkoordinaten)"), - ("World space normal", "Normale (Weltkoordinaten)"), - ("World-space normals of the high poly (or the low poly).", "Normalen des High-Poly (oder Low-Poly) in Weltkoordinaten."), + ("World Space Normal", "Normale (Weltkoordinaten)"), ("Yellow / blue", "Gelb / Blau"), ("Zoom", "Zoomen"), ("a missing layer", "eine fehlende Ebene"), @@ -974,7 +924,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel bzw. in das Ansichtsfenster ziehen)", ), - ("{name} ({n} triangles)", "{name} ({n} Dreiecke)"), ("{name} copy", "{name} Kopie"), ("{n} bits", "{n} Bit"), ( @@ -985,34 +934,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (Skalierung {scale}, Startwert {seed})"), ("Template name", "Vorlagenname"), ("Save current project as template", "Aktuelles Projekt als Vorlage speichern"), - ("Spread angle", "Streuwinkel"), ("Distribution", "Verteilung"), ("Cosine", "Kosinus"), ("Uniform", "Gleichmäßig"), - ("Ignore backface", "Rückseiten ignorieren"), - ("Self occlusion", "Eigenverdeckung"), - ("Only same mesh name", "Nur gleicher Mesh-Name"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Strahlen der gebogenen Normalen folgen den Verdecker-Einstellungen der Ambient Occlusion.", - ), - ("Sampling radius", "Abtastradius"), - ("0 picks a radius from the output size.", "0 wählt den Radius anhand der Ausgabegröße."), - ("Encoding", "Kodierung"), - ("Signed (-1..1)", "Vorzeichenbehaftet (-1..1)"), - ("Positive (0..1)", "Positiv (0..1)"), ("Normalization", "Normalisierung"), - ("Bounding box", "Begrenzungsrahmen"), - ("Bounding sphere", "Begrenzungskugel"), - ( - "Position normalized to the low poly's bounding box or sphere.", - "Position, normalisiert auf den Begrenzungsrahmen oder die Begrenzungskugel des Low-Poly.", - ), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Grundfarben (Texturen, Faktoren) und Vertexfarben der hochauflösenden Meshes.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Weiß, wo das High-Poly das Low-Poly bedeckt, mal dessen Alpha."), // Settings › Interface: brightness and accent color. ("Brightness", "Helligkeit"), ("Dark", "Dunkel"), @@ -1059,12 +984,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Ungespeicherte Änderungen"), ("Don't save", "Nicht speichern"), ("Save the changes to {name} before closing?", "Änderungen an {name} vor dem Schließen speichern?"), - ("Skew correction", "Skew-Korrektur"), - ("Paint skew in the 2D view", "Skew in der 2D-Ansicht malen"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "In der 2D-Ansicht ziehen, um zu malen, wo sich die Bake-Strahlen zur Basisnormalen drehen; mit dem Wert 0 wird gelöscht", - ), ("Radius", "Radius"), ("Remove skew correction", "Skew-Korrektur entfernen"), ("Twill weave", "Köperbindung"), @@ -1084,4 +1003,85 @@ pub const TABLE: &[(&str, &str)] = &[ "In MaterialCraft geöffnet: Dort mit Datei > An TextureCraft senden die Änderungen zurückholen", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Parameter lassen sich in der Desktop-App mit installiertem MaterialCraft ändern"), + ("Add High-Poly Meshes", "High-Poly-Meshes hinzufügen"), + ("All", "Alle"), + ("Apply Diffusion", "Diffusion anwenden"), + ("Attenuation", "Abschwächung"), + ("Auto Tonemapping", "Automatisches Tonemapping"), + ("Average Normals", "Normalen mitteln"), + ("BBox", "Begrenzungsrahmen"), + ("BSphere", "Begrenzungskugel"), + ("Bake Maps", "Maps backen"), + ("Bake Selected Textures ({n})", "Ausgewählte Texturen backen ({n})"), + ("By Mesh Name", "Nach Mesh-Name"), + ("Cage", "Käfig"), + ("Cage Scene", "Käfigszene"), + ("Cage Type", "Käfigtyp"), + ("Color Generator", "Farbgenerator"), + ("Color Source", "Farbquelle"), + ("Common Parameters", "Gemeinsame Parameter"), + ("Custom File", "Benutzerdefinierte Datei"), + ("Details", "Details"), + ("Dilation Width", "Dilatationsbreite"), + ("Distance-Based", "Distanzbasiert"), + ("Edge Contrast", "Kantenkontrast"), + ("Edge Distance", "Kantenabstand"), + ("Edge Protection", "Kantenschutz"), + ("Enable Seams", "Nähte aktivieren"), + ("File ID", "Datei-ID"), + ("Full Scene", "Gesamte Szene"), + ("Generate from Mesh", "Aus Mesh erzeugen"), + ("Generate from Normal Map", "Aus Normal-Map erzeugen"), + ("Ground Plane", "Bodenebene"), + ("Ground Plane Offset", "Bodenversatz"), + ("High Poly Mesh Suffix", "Suffix für High-Poly-Mesh"), + ("High Poly Scene", "High-Poly-Szene"), + ("High-Poly Parameters", "High-Poly-Parameter"), + ("Hue Shift", "Farbtonverschiebung"), + ("Ignore Backface", "Rückseiten ignorieren"), + ("Ignore Backface Suffix", "Suffix für ignorierte Rückseiten"), + ("Include in Bake", "Beim Backen einschließen"), + ("Load Cage", "Käfig laden"), + ("Lock Output Size", "Ausgabegröße sperren"), + ("Low Poly Mesh Suffix", "Suffix für Low-Poly-Mesh"), + ("Manual", "Manuell"), + ("Material Color", "Materialfarbe"), + ("Max Frontal Distance", "Max. vordere Distanz"), + ("Max Occluder Distance", "Max. Verdeckerdistanz"), + ("Max Rear Distance", "Max. hintere Distanz"), + ("Mesh ID", "Mesh-ID"), + ("Method", "Methode"), + ("Min Occluder Distance", "Minimaler Verdeckungsabstand"), + ("Never", "Nie"), + ("No High-Poly Meshes", "Keine High-Poly-Meshes"), + ("Normalization Scale", "Normalisierungsskala"), + ("Normalization Type", "Normalisierungstyp"), + ("Only Same Mesh Name", "Nur gleicher Mesh-Name"), + ("Output Size", "Ausgabegröße"), + ("Paint Cage", "Käfig malen"), + ("Paint Skew Correction", "Verzerrungskorrektur malen"), + ("Per Material", "Pro Material"), + ("Random", "Zufällig"), + ("Relative to Bounding Box", "Relativ zum Begrenzungsrahmen"), + ("Relative to Low Mesh", "Relativ zum Low-Poly-Mesh"), + ("Relative to Min/Max", "Relativ zu Min/Max"), + ("Relative to Ray Distances", "Relativ zu Strahlabständen"), + ("Remove Cage", "Käfig entfernen"), + ("Remove Skew Correction", "Skew-Korrektur entfernen"), + ("Restore Defaults", "Standardwerte wiederherstellen"), + ("Return to Painting Mode", "Zurück zum Malmodus"), + ("Sampling Radius", "Abtastradius"), + ("Scaling Divisor", "Skalierungsdivisor"), + ("Seams Intensity", "Nahtintensität"), + ("Secondary Rays", "Sekundärstrahlen"), + ("Self Intersection", "Selbstüberschneidung"), + ("Self Occlusion", "Eigenverdeckung"), + ("Skew Correction", "Skew-Korrektur"), + ("Smooth", "Glatt"), + ("Spread Angle", "Streuwinkel"), + ("Submesh", "Teilmesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Low-Poly-Mesh als High-Poly-Mesh verwenden"), + ("Value Bounds Max", "Maximaler Grenzwert"), + ("Value Bounds Min", "Minimaler Grenzwert"), + ("Vertex Color", "Scheitelpunktfarbe"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 00964af6..d681e213 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -44,7 +44,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Añadir filtro"), ("Add folder", "Añadir carpeta"), ("Add generator", "Añadir generador"), - ("Add high definition meshes", "Añadir mallas de alta definición"), ("Add levels", "Añadir niveles"), ("Add mask", "Añadir máscara"), ("Add mask with color selection", "Añadir máscara con selección de color"), @@ -80,7 +79,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "También asignado a {item} ({menu})"), ("Alt + LMB drag", "Alt + arrastrar con botón izq."), ("Always", "Siempre"), - ("Ambient occlusion", "Oclusión ambiental"), + ("Ambient Occlusion", "Oclusión ambiental"), ("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"), ("Amount", "Cantidad"), ("Anchor point", "Punto de anclaje"), @@ -96,7 +95,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), ("Apply", "Aplicar"), - ("Apply to all texture sets", "Aplicar a todos los conjuntos de texturas"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), @@ -105,7 +103,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Las copias automáticas, los materiales inteligentes, los ajustes preestablecidos, las plantillas y los diseños de la interfaz se guardan en la carpeta de datos. Una carpeta nueva se aplica al reiniciar; los archivos ya guardados se quedan donde están.", ), - ("Average normals", "Promediar normales"), ("Axis", "Eje"), ("Back to painting", "Volver a pintar"), ("Backface culling", "Descarte de caras traseras"), @@ -115,8 +112,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Hornea los mapas de malla (F8) para los generadores basados en curvatura, AO y grosor.", ), - ("Bake selected textures ({n})", "Hornear texturas seleccionadas ({n})"), - ("Bake with \"Bake selected textures\"", "Hornear con \"Hornear texturas seleccionadas\""), ("Baked Lighting", "Iluminación horneada"), ("Baking", "Horneado"), ("Base color", "Color base"), @@ -127,7 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Color base, Metálico, Rugosidad y Nivel especular."), ("Based on each texture set's size", "Según el tamaño de cada conjunto de texturas"), ("Basic settings", "Ajustes básicos"), - ("Bent normals", "Normales curvadas"), + ("Bent Normals", "Normales curvadas"), ("Bevel", "Bisel"), ("Black", "Negro"), ("Blend sharpness", "Nitidez de la mezcla"), @@ -145,7 +140,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integrada (solo lectura): duplícala para editarla"), ("Built-in templates are read-only: duplicate one to edit it", "Las plantillas integradas son de solo lectura: duplica una para editarla"), ("Built-in: {mesh}", "Integrada: {mesh}"), - ("By mesh name", "Por nombre de malla"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), ("Camera settings", "Ajustes de cámara"), @@ -177,7 +171,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Equilibrio de color"), ("Color burn", "Subexponer color"), ("Color dodge", "Sobreexponer color"), - ("Color map", "Mapa de color"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Color de la luz que viaja bajo la superficie (cada canal llega tan lejos como su valor)", @@ -194,7 +187,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Los colores se leen como gris. Añade encima un efecto de niveles o desenfoque para ajustar el resultado.", ), ("Combine with the layer's height", "Combinar con la altura de la capa"), - ("Common parameters", "Parámetros comunes"), ("Compare mask", "Máscara de comparación"), ("Compositing", "Composición"), ("Constant", "Constante"), @@ -207,7 +199,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar capa(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar solo la capa seleccionada (sus partes vacías no copian nada)"), - ("Copy these bake settings to every texture set", "Copiar estos ajustes de horneado a todos los conjuntos de texturas"), ("Copy to all texture sets", "Copiar a todos los conjuntos de texturas"), ("Copy what the texture set shows", "Copiar lo que muestra el conjunto de texturas"), ("Couldn't encode the render", "No se pudo codificar el render"), @@ -258,8 +249,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatación + color de fondo predeterminado"), ("Dilation + transparent", "Dilatación + transparente"), ("Dilation infinite", "Dilatación infinita"), - ("Dilation width", "Ancho de dilatación"), - ("Direction {axis}", "Dirección {axis}"), ("DirectX normal map", "Mapa de normales DirectX"), ("Dirt", "Suciedad"), ("Disable", "Desactivado"), @@ -363,11 +352,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Para todo el proyecto: cómo se leen las imágenes de mapas de normales usadas como mapas de malla (vuelve a asignarlas tras un cambio) y el valor predeterminado al exportar", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre y de código abierto (MIT OR Apache-2.0), escrito en Rust."), - ("From normal map", "Desde el mapa de normales"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Desde el mapa de normales: curvatura del detalle del mapa de normales horneado en lugar de la malla.", - ), ("From template", "Desde la plantilla"), ("From template / project", "Desde la plantilla / el proyecto"), ("Full", "Completa"), @@ -407,12 +391,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Ayuda"), ("Hide UI", "Ocultar interfaz"), ("High", "Alto"), - ("High definition meshes", "Mallas de alta definición"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altura de la malla high poly entre las distancias máximas trasera (negro) y frontal (blanco).", - ), - ("High poly mesh suffix", "Sufijo de malla high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Iluminaciones"), ("Histogram Range", "Rango de histograma"), @@ -500,11 +478,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luz lineal"), ("List of exports", "Lista de exportaciones"), ("Load UI Layout", "Cargar diseño de interfaz"), - ("Load a cage (the low poly, inflated)", "Cargar una jaula (la low poly, inflada)"), ("Loaded UI layout {path}", "Diseño de interfaz cargado: {path}"), ("Log", "Registro"), ("Low", "Bajo"), - ("Low poly mesh suffix", "Sufijo de malla low poly"), ("Luminosity", "Luminosidad"), ("MMB drag / Alt + MMB", "Arrastrar con botón central / Alt + botón central"), ("Made by the ArtCraft team and community.", "Creado por el equipo y la comunidad de ArtCraft."), @@ -518,17 +494,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "Acabado martillado"), ("MatFinish Raw", "Acabado en bruto"), ("MatFinish Sanded", "Acabado lijado"), - ("Match", "Correspondencia"), ("Material", "Material"), ("Material ball", "Bola de material"), ("Material finish", "Acabado de material"), ("Materials", "Materiales"), - ("Max frontal distance", "Distancia frontal máx."), - ("Max occluder distance", "Distancia máx. de oclusor"), - ("Max rear distance", "Distancia trasera máx."), ("Maximum", "Máximo"), ("Mesh fill", "Relleno de malla"), - ("Mesh map bakers", "Horneadores de mapas de malla"), ("Mesh map: {map}", "Mapa de malla: {map}"), ("Mesh maps", "Mapas de malla"), ("Mesh maps baked", "Mapas de malla horneados"), @@ -567,7 +538,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Cantidad de ruido"), ("Noise scale", "Escala del ruido"), ("None", "Ninguno"), - ("None: the low poly is its own high poly.", "Ninguna: la low poly es su propia high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normal DirectX"), ("Normal Invert", "Invertir normal"), @@ -599,7 +569,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Desplaza las texturas según el canal de altura, con la intensidad de altura a normal", ), ("On", "Activado"), - ("One color per mesh part.", "Un color por cada parte de la malla."), ("Opacity", "Opacidad"), ("Open sample project...", "Abrir proyecto de ejemplo..."), ("Open...", "Abrir..."), @@ -613,7 +582,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "Directorio de salida"), ("Output high", "Salida alta"), ("Output low", "Salida baja"), - ("Output size", "Tamaño de salida"), ("Output template", "Plantilla de salida"), ("Output templates", "Plantillas de salida"), ("Overlay", "Superponer"), @@ -690,7 +658,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rehacer"), ("Reimport mesh", "Reimportar malla"), - ("Relative to the bounding box diagonal.", "Relativo a la diagonal del cuadro delimitador."), ("Remove", "Quitar"), ("Remove channel", "Quitar canal"), ("Remove effect", "Quitar efecto"), @@ -699,7 +666,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "Eliminar capa(s)"), ("Remove mask", "Quitar máscara"), ("Remove resource", "Quitar recurso"), - ("Remove the cage", "Quitar la jaula"), ("Remove the path (Esc)", "Quitar el trazado (Esc)"), ("Remove the shortcut", "Quitar el atajo"), ("Remove this output", "Quitar esta salida"), @@ -725,13 +691,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "Restablecer a {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), - ("Return to painting mode", "Volver al modo de pintura"), ("Return to this step", "Volver a este paso"), - ("Auto-rebake", "Rehornear automáticamente"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Vuelve a hornear este mapa automáticamente cuando cambian sus ajustes de horneado, la malla low poly o las high poly", - ), ("Right-click a layer > Create smart material", "Clic derecho en una capa > Crear material inteligente"), ("Rotation", "Rotación"), ("Rotation (degrees)", "Rotación (grados)"), @@ -761,7 +721,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "Captura de la ventana gráfica"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), - ("Secondary rays", "Rayos secundarios"), ("Seed", "Semilla"), ("Select a layer", "Selecciona una capa"), ("Select an output template", "Selecciona una plantilla de salida"), @@ -829,13 +788,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "Simetría (X)"), ("Symmetry (Y)", "Simetría (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), - ("Tangent-space normals of the high definition meshes.", "Normales en espacio tangente de las mallas de alta definición."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antialiasing temporal (refina la vista 3D mientras está quieta)"), - ("Texture Set List", "Lista de conjuntos de texturas"), + ("Texture Sets", "Conjuntos de texturas"), ("Texture Set Settings", "Ajustes del conjunto de texturas"), ("Texture resolution", "Resolución de texturas"), ("Texture set channels", "Canales del conjunto de texturas"), - ("Texture set list", "Lista de conjuntos de texturas"), ("Texture sets", "Conjuntos de texturas"), ("TextureCraft had to close:", "TextureCraft tuvo que cerrarse:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidad"), @@ -890,7 +847,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "Usar como alfa del pincel (o arrastrarlo a la ventana gráfica o a las propiedades del pincel)", ), - ("Use low poly mesh as high poly mesh", "Usar la malla low poly como malla high poly"), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), ("Value", "Valor"), ("Version {version}", "Versión {version}"), @@ -911,18 +867,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Rueda / Alt + arrastrar con botón der."), ("White", "Blanco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Blanco donde la superficie mira hacia la dirección, negro donde mira en sentido contrario.", - ), ("Width", "Ancho"), ("Width (texels at 2K)", "Anchura (téxeles a 2K)"), ("Window", "Ventana"), ("Wood grain", "Veta de madera"), ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona en espacio de textura, como el desenfoque: no cruza las costuras UV."), - ("World space direction", "Dirección en espacio de mundo"), - ("World space normal", "Normal en espacio de mundo"), - ("World-space normals of the high poly (or the low poly).", "Normales en espacio de mundo de la high poly (o de la low poly)."), + ("World Space Normal", "Normal en espacio de mundo"), ("Yellow / blue", "Amarillo / azul"), ("Zoom", "Zoom"), ("a missing layer", "una capa inexistente"), @@ -959,7 +909,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: añadir sobre la capa seleccionada (o arrastrarlo a la pila de capas o a la ventana gráfica)", ), - ("{name} ({n} triangles)", "{name} ({n} triángulos)"), ("{name} copy", "Copia de {name}"), ("{n} bits", "{n} bits"), ( @@ -970,31 +919,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semilla {seed})"), ("Template name", "Nombre de la plantilla"), ("Save current project as template", "Guardar el proyecto actual como plantilla"), - ("Spread angle", "Ángulo de dispersión"), ("Distribution", "Distribución"), ("Cosine", "Coseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorar caras traseras"), - ("Self occlusion", "Autooclusión"), - ("Only same mesh name", "Solo el mismo nombre de malla"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Los rayos de las normales curvadas siguen los ajustes de oclusores de la oclusión ambiental.", - ), - ("Sampling radius", "Radio de muestreo"), - ("0 picks a radius from the output size.", "0 elige un radio según el tamaño de salida."), - ("Encoding", "Codificación"), - ("Signed (-1..1)", "Con signo (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalización"), - ("Bounding box", "Cuadro delimitador"), - ("Bounding sphere", "Esfera delimitadora"), - ("Position normalized to the low poly's bounding box or sphere.", "Posición normalizada al cuadro o la esfera delimitadora de la low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Colores base (texturas, factores) y colores de vértice de las mallas de alta definición.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Blanco donde la high poly cubre la low poly, multiplicado por su alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Brillo"), ("Dark", "Oscuro"), @@ -1041,12 +969,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Cambios sin guardar"), ("Don't save", "No guardar"), ("Save the changes to {name} before closing?", "¿Guardar los cambios de {name} antes de cerrar?"), - ("Skew correction", "Corrección de sesgo"), - ("Paint skew in the 2D view", "Pintar el sesgo en la vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Arrastra en la vista 2D para pintar dónde los rayos del bake se giran hacia la normal base; pinta con valor 0 para borrar", - ), ("Radius", "Radio"), ("Remove skew correction", "Quitar la corrección de sesgo"), ("Twill weave", "Tejido de sarga"), @@ -1066,4 +988,85 @@ pub const TABLE: &[(&str, &str)] = &[ "Abierto en MaterialCraft: usa allí Archivo > Enviar a TextureCraft para traer tus cambios", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Los parámetros se cambian en la app de escritorio, con MaterialCraft instalado"), + ("Add High-Poly Meshes", "Añadir mallas de alta resolución"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusión"), + ("Attenuation", "Atenuación"), + ("Auto Tonemapping", "Mapeo tonal automático"), + ("Average Normals", "Promediar normales"), + ("BBox", "Caja delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("Bake Maps", "Hornear mapas"), + ("Bake Selected Textures ({n})", "Hornear texturas seleccionadas ({n})"), + ("By Mesh Name", "Por nombre de malla"), + ("Cage", "Jaula"), + ("Cage Scene", "Escena de jaula"), + ("Cage Type", "Tipo de jaula"), + ("Color Generator", "Generador de color"), + ("Color Source", "Origen del color"), + ("Common Parameters", "Parámetros comunes"), + ("Custom File", "Archivo personalizado"), + ("Details", "Detalles"), + ("Dilation Width", "Ancho de dilatación"), + ("Distance-Based", "Basada en distancia"), + ("Edge Contrast", "Contraste de bordes"), + ("Edge Distance", "Distancia de bordes"), + ("Edge Protection", "Protección de bordes"), + ("Enable Seams", "Activar costuras"), + ("File ID", "ID de archivo"), + ("Full Scene", "Escena completa"), + ("Generate from Mesh", "Generar desde la malla"), + ("Generate from Normal Map", "Generar desde el mapa de normales"), + ("Ground Plane", "Plano del suelo"), + ("Ground Plane Offset", "Desplazamiento del suelo"), + ("High Poly Mesh Suffix", "Sufijo de malla high poly"), + ("High Poly Scene", "Escena de alta resolución"), + ("High-Poly Parameters", "Parámetros de alta resolución"), + ("Hue Shift", "Cambio de tono"), + ("Ignore Backface", "Ignorar caras traseras"), + ("Ignore Backface Suffix", "Sufijo para ignorar caras traseras"), + ("Include in Bake", "Incluir en el horneado"), + ("Load Cage", "Cargar jaula"), + ("Lock Output Size", "Bloquear tamaño de salida"), + ("Low Poly Mesh Suffix", "Sufijo de malla low poly"), + ("Manual", "Manual"), + ("Material Color", "Color del material"), + ("Max Frontal Distance", "Distancia frontal máx."), + ("Max Occluder Distance", "Distancia máx. de oclusor"), + ("Max Rear Distance", "Distancia trasera máx."), + ("Mesh ID", "ID de malla"), + ("Method", "Método"), + ("Min Occluder Distance", "Distancia mínima del oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Sin mallas de alta resolución"), + ("Normalization Scale", "Escala de normalización"), + ("Normalization Type", "Tipo de normalización"), + ("Only Same Mesh Name", "Solo el mismo nombre de malla"), + ("Output Size", "Tamaño de salida"), + ("Paint Cage", "Pintar jaula"), + ("Paint Skew Correction", "Pintar corrección de inclinación"), + ("Per Material", "Por material"), + ("Random", "Aleatorio"), + ("Relative to Bounding Box", "Relativo a la caja delimitadora"), + ("Relative to Low Mesh", "Relativo a la malla de baja resolución"), + ("Relative to Min/Max", "Relativo al mínimo/máximo"), + ("Relative to Ray Distances", "Relativo a distancias de rayos"), + ("Remove Cage", "Eliminar jaula"), + ("Remove Skew Correction", "Quitar la corrección de sesgo"), + ("Restore Defaults", "Restaurar valores predeterminados"), + ("Return to Painting Mode", "Volver al modo de pintura"), + ("Sampling Radius", "Radio de muestreo"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidad de costuras"), + ("Secondary Rays", "Rayos secundarios"), + ("Self Intersection", "Autointersección"), + ("Self Occlusion", "Autooclusión"), + ("Skew Correction", "Corrección de sesgo"), + ("Smooth", "Suave"), + ("Spread Angle", "Ángulo de dispersión"), + ("Submesh", "Submalla"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar la malla low poly como malla high poly"), + ("Value Bounds Max", "Límite máximo"), + ("Value Bounds Min", "Límite mínimo"), + ("Vertex Color", "Color de vértice"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f9fa0d3b..24ef92ea 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -50,7 +50,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Ajouter un filtre"), ("Add folder", "Ajouter un dossier"), ("Add generator", "Ajouter un générateur"), - ("Add high definition meshes", "Ajouter des maillages haute définition"), ("Add levels", "Ajouter des niveaux"), ("Add mask", "Ajouter un masque"), ("Add mask with color selection", "Ajouter un masque par sélection de couleur"), @@ -86,7 +85,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Également attribué à {item} ({menu})"), ("Alt + LMB drag", "Alt + glisser (clic gauche)"), ("Always", "Toujours"), - ("Ambient occlusion", "Occlusion ambiante"), + ("Ambient Occlusion", "Occlusion ambiante"), ("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"), ("Amount", "Quantité"), ("Anchor point", "Point d'ancrage"), @@ -102,7 +101,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), ("Apply", "Appliquer"), - ("Apply to all texture sets", "Appliquer à tous les ensembles de textures"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), @@ -111,7 +109,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Les sauvegardes automatiques, matériaux intelligents, préréglages, modèles et dispositions de l'interface vont dans le dossier de données. Un nouveau dossier s'applique au redémarrage ; les fichiers déjà enregistrés restent où ils sont.", ), - ("Average normals", "Moyenne des normales"), ("Axis", "Axe"), ("Back to painting", "Retour à la peinture"), ("Backface culling", "Élimination des faces arrière"), @@ -121,8 +118,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Précalculez les cartes de maillage (F8) pour les générateurs basés sur la courbure, l'AO et l'épaisseur.", ), - ("Bake selected textures ({n})", "Précalculer les textures sélectionnées ({n})"), - ("Bake with \"Bake selected textures\"", "Précalculer avec « Précalculer les textures sélectionnées »"), ("Baked Lighting", "Éclairage précalculé"), ("Baking", "Précalcul"), ("Base color", "Couleur de base"), @@ -133,7 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Couleur de base, Métallique, Rugosité et Niveau spéculaire."), ("Based on each texture set's size", "Selon la taille de chaque ensemble de textures"), ("Basic settings", "Paramètres de base"), - ("Bent normals", "Normales déviées"), + ("Bent Normals", "Normales déviées"), ("Bevel", "Biseau"), ("Black", "Noir"), ("Blend sharpness", "Netteté du fondu"), @@ -151,7 +146,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Intégré (lecture seule) : dupliquez-le pour le modifier"), ("Built-in templates are read-only: duplicate one to edit it", "Les modèles intégrés sont en lecture seule : dupliquez-en un pour le modifier"), ("Built-in: {mesh}", "Intégré : {mesh}"), - ("By mesh name", "Par nom de maillage"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), ("Camera settings", "Paramètres de la caméra"), @@ -183,7 +177,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Balance des couleurs"), ("Color burn", "Densité couleur +"), ("Color dodge", "Densité couleur -"), - ("Color map", "Carte de couleur"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Couleur de la lumière qui se propage sous la surface (chaque canal va aussi loin que sa valeur)", @@ -200,7 +193,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Les couleurs sont lues en niveaux de gris. Ajoutez un effet de niveaux ou de flou au-dessus pour ajuster le résultat.", ), ("Combine with the layer's height", "Combiner avec la hauteur du calque"), - ("Common parameters", "Paramètres communs"), ("Compare mask", "Masque de comparaison"), ("Compositing", "Composition"), ("Constant", "Constante"), @@ -213,7 +205,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copier depuis"), ("Copy layer(s)", "Copier le(s) calque(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copier uniquement le calque sélectionné (ses parties vides ne copient rien)"), - ("Copy these bake settings to every texture set", "Copier ces paramètres de précalcul dans chaque ensemble de textures"), ("Copy to all texture sets", "Copier dans tous les ensembles de textures"), ("Copy what the texture set shows", "Copier ce qu'affiche l'ensemble de textures"), ("Couldn't encode the render", "Impossible d'encoder le rendu"), @@ -264,8 +255,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatation + couleur de fond par défaut"), ("Dilation + transparent", "Dilatation + transparent"), ("Dilation infinite", "Dilatation infinie"), - ("Dilation width", "Largeur de dilatation"), - ("Direction {axis}", "Direction {axis}"), ("DirectX normal map", "Carte de normales DirectX"), ("Dirt", "Saleté"), ("Disable", "Désactivé"), @@ -375,11 +364,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Pour tout le projet : comment les images de carte de normales utilisées comme cartes de maillage sont lues (réaffectez-les après un changement), et la valeur par défaut à l'export", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libre et open source (MIT OR Apache-2.0), écrit en Rust."), - ("From normal map", "Depuis la carte de normales"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Depuis la carte de normales : courbure des détails de la carte de normales précalculée au lieu du maillage.", - ), ("From template", "Selon le modèle"), ("From template / project", "Selon le modèle / projet"), ("Full", "Pleine"), @@ -419,12 +403,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Aide"), ("Hide UI", "Masquer l'interface"), ("High", "Haut"), - ("High definition meshes", "Maillages haute définition"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Hauteur du high poly entre les distances arrière max (noir) et frontale max (blanc).", - ), - ("High poly mesh suffix", "Suffixe du maillage high poly"), ("High poly: {name}", "High poly : {name}"), ("Highlights", "Tons clairs"), ("Histogram Range", "Plage d'histogramme"), @@ -515,11 +493,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Lumière linéaire"), ("List of exports", "Liste des exports"), ("Load UI Layout", "Charger une disposition"), - ("Load a cage (the low poly, inflated)", "Charger une cage (le low poly, gonflé)"), ("Loaded UI layout {path}", "Disposition de l'interface chargée : {path}"), ("Log", "Journal"), ("Low", "Bas"), - ("Low poly mesh suffix", "Suffixe du maillage low poly"), ("Luminosity", "Luminosité"), ("MMB drag / Alt + MMB", "Glisser (clic milieu) / Alt + clic milieu"), ("Made by the ArtCraft team and community.", "Créé par l'équipe et la communauté ArtCraft."), @@ -533,17 +509,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martelé"), ("MatFinish Raw", "MatFinish Brut"), ("MatFinish Sanded", "MatFinish Poncé"), - ("Match", "Correspondance"), ("Material", "Matériau"), ("Material ball", "Boule de matériau"), ("Material finish", "Finition du matériau"), ("Materials", "Matériaux"), - ("Max frontal distance", "Distance frontale max"), - ("Max occluder distance", "Distance max des occulteurs"), - ("Max rear distance", "Distance arrière max"), ("Maximum", "Maximum"), ("Mesh fill", "Remplissage par maillage"), - ("Mesh map bakers", "Précalcul des cartes de maillage"), ("Mesh map: {map}", "Carte de maillage : {map}"), ("Mesh maps", "Cartes de maillage"), ("Mesh maps baked", "Cartes de maillage précalculées"), @@ -582,7 +553,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantité de bruit"), ("Noise scale", "Échelle du bruit"), ("None", "Aucun"), - ("None: the low poly is its own high poly.", "Aucun : le low poly est son propre high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Inversion de normale"), @@ -614,7 +584,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Décale les textures selon le canal de hauteur, avec l'intensité hauteur vers normale", ), ("On", "Activé"), - ("One color per mesh part.", "Une couleur par partie du maillage."), ("Opacity", "Opacité"), ("Open sample project...", "Ouvrir un projet d'exemple..."), ("Open...", "Ouvrir..."), @@ -628,7 +597,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "Dossier de sortie"), ("Output high", "Sortie haute"), ("Output low", "Sortie basse"), - ("Output size", "Taille de sortie"), ("Output template", "Modèle de sortie"), ("Output templates", "Modèles de sortie"), ("Overlay", "Incrustation"), @@ -705,7 +673,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Rétablir"), ("Reimport mesh", "Réimporter le maillage"), - ("Relative to the bounding box diagonal.", "Relatif à la diagonale de la boîte englobante."), ("Remove", "Supprimer"), ("Remove channel", "Supprimer le canal"), ("Remove effect", "Supprimer l'effet"), @@ -714,7 +681,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "Supprimer le(s) calque(s)"), ("Remove mask", "Supprimer le masque"), ("Remove resource", "Supprimer la ressource"), - ("Remove the cage", "Supprimer la cage"), ("Remove the path (Esc)", "Supprimer le tracé (Esc)"), ("Remove the shortcut", "Supprimer le raccourci"), ("Remove this output", "Supprimer cette sortie"), @@ -740,13 +706,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), - ("Return to painting mode", "Revenir au mode peinture"), ("Return to this step", "Revenir à cette étape"), - ("Auto-rebake", "Précalcul automatique"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Précalcule à nouveau cette carte automatiquement quand ses réglages de précalcul, le maillage low poly ou les maillages high poly changent", - ), ("Right-click a layer > Create smart material", "Clic droit sur un calque > Créer un matériau intelligent"), ("Rotation", "Rotation"), ("Rotation (degrees)", "Rotation (degrés)"), @@ -779,7 +739,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), - ("Secondary rays", "Rayons secondaires"), ("Seed", "Graine"), ("Select a layer", "Sélectionnez un calque"), ("Select an output template", "Sélectionnez un modèle de sortie"), @@ -847,13 +806,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "Symétrie (X)"), ("Symmetry (Y)", "Symétrie (Y)"), ("Tangent | Wrap", "Tangente | Enveloppe"), - ("Tangent-space normals of the high definition meshes.", "Normales en espace tangent des maillages haute définition."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anticrénelage temporel (affine la vue 3D tant qu'elle est immobile)"), - ("Texture Set List", "Liste des ensembles de textures"), + ("Texture Sets", "Ensembles de textures"), ("Texture Set Settings", "Paramètres de l'ensemble de textures"), ("Texture resolution", "Résolution des textures"), ("Texture set channels", "Canaux de l'ensemble de textures"), - ("Texture set list", "Liste des ensembles de textures"), ("Texture sets", "Ensembles de textures"), ("TextureCraft had to close:", "TextureCraft a dû se fermer :"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Métallique Rugosité"), @@ -908,7 +865,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "Utiliser comme alpha du pinceau (ou le glisser sur la fenêtre d'affichage ou les propriétés du pinceau)", ), - ("Use low poly mesh as high poly mesh", "Utiliser le maillage low poly comme maillage high poly"), ( "Use the control channel or `texturecraft-cli render` for screenshots", "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", @@ -932,18 +888,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Molette / Alt + glisser (clic droit)"), ("White", "Blanc"), - ( - "White where the surface faces the direction, black where it faces away.", - "Blanc là où la surface fait face à la direction, noir là où elle s'en détourne.", - ), ("Width", "Largeur"), ("Width (texels at 2K)", "Largeur (texels en 2K)"), ("Window", "Fenêtre"), ("Wood grain", "Veinage du bois"), ("Works in texture space, like the blur: it does not cross UV seams.", "Fonctionne en espace texture, comme le flou : ne traverse pas les coutures UV."), - ("World space direction", "Direction en espace monde"), - ("World space normal", "Normale en espace monde"), - ("World-space normals of the high poly (or the low poly).", "Normales en espace monde du high poly (ou du low poly)."), + ("World Space Normal", "Normale en espace monde"), ("Yellow / blue", "Jaune / bleu"), ("Zoom", "Zoom"), ("a missing layer", "un calque manquant"), @@ -980,7 +930,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file} : ajouter au-dessus du calque sélectionné (ou le glisser dans la pile de calques ou sur la fenêtre d'affichage)", ), - ("{name} ({n} triangles)", "{name} ({n} triangles)"), ("{name} copy", "Copie de {name}"), ("{n} bits", "{n} bits"), ( @@ -991,31 +940,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (échelle {scale}, graine {seed})"), ("Template name", "Nom du modèle"), ("Save current project as template", "Enregistrer le projet actuel comme modèle"), - ("Spread angle", "Angle de dispersion"), ("Distribution", "Distribution"), ("Cosine", "Cosinus"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorer les faces arrière"), - ("Self occlusion", "Auto-occlusion"), - ("Only same mesh name", "Seulement le même nom de maillage"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Les rayons des normales déviées suivent les réglages d'occulteurs de l'occlusion ambiante.", - ), - ("Sampling radius", "Rayon d'échantillonnage"), - ("0 picks a radius from the output size.", "0 choisit un rayon selon la taille de sortie."), - ("Encoding", "Encodage"), - ("Signed (-1..1)", "Signé (-1..1)"), - ("Positive (0..1)", "Positif (0..1)"), ("Normalization", "Normalisation"), - ("Bounding box", "Boîte englobante"), - ("Bounding sphere", "Sphère englobante"), - ("Position normalized to the low poly's bounding box or sphere.", "Position normalisée sur la boîte ou la sphère englobante du low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Couleurs de base (textures, facteurs) et couleurs de sommets des maillages haute définition.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Blanc là où le high poly couvre le low poly, multiplié par son alpha."), // Settings › Interface: brightness and accent color. ("Brightness", "Luminosité"), ("Dark", "Sombre"), @@ -1062,12 +990,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifications non enregistrées"), ("Don't save", "Ne pas enregistrer"), ("Save the changes to {name} before closing?", "Enregistrer les modifications de {name} avant de fermer ?"), - ("Skew correction", "Correction d'inclinaison"), - ("Paint skew in the 2D view", "Peindre l'inclinaison dans la vue 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Faites glisser dans la vue 2D pour peindre où les rayons du bake se tournent vers la normale de base ; peignez avec la valeur 0 pour effacer", - ), ("Radius", "Rayon"), ("Remove skew correction", "Supprimer la correction d'inclinaison"), ("Twill weave", "Armure sergé"), @@ -1090,4 +1012,85 @@ pub const TABLE: &[(&str, &str)] = &[ "Parameters change in the desktop app, with MaterialCraft installed", "Les paramètres se modifient dans l'application de bureau, avec MaterialCraft installé", ), + ("Add High-Poly Meshes", "Ajouter des maillages haute définition"), + ("All", "Tous"), + ("Apply Diffusion", "Appliquer la diffusion"), + ("Attenuation", "Atténuation"), + ("Auto Tonemapping", "Mappage tonal automatique"), + ("Average Normals", "Moyenne des normales"), + ("BBox", "Boîte englobante"), + ("BSphere", "Sphère englobante"), + ("Bake Maps", "Précalculer les cartes"), + ("Bake Selected Textures ({n})", "Précalculer les textures sélectionnées ({n})"), + ("By Mesh Name", "Par nom de maillage"), + ("Cage", "Cage"), + ("Cage Scene", "Scène de cage"), + ("Cage Type", "Type de cage"), + ("Color Generator", "Générateur de couleurs"), + ("Color Source", "Source de couleur"), + ("Common Parameters", "Paramètres communs"), + ("Custom File", "Fichier personnalisé"), + ("Details", "Détails"), + ("Dilation Width", "Largeur de dilatation"), + ("Distance-Based", "Selon la distance"), + ("Edge Contrast", "Contraste des arêtes"), + ("Edge Distance", "Distance des arêtes"), + ("Edge Protection", "Protection des arêtes"), + ("Enable Seams", "Activer les coutures"), + ("File ID", "ID du fichier"), + ("Full Scene", "Scène entière"), + ("Generate from Mesh", "Générer depuis le maillage"), + ("Generate from Normal Map", "Générer depuis la carte de normales"), + ("Ground Plane", "Plan du sol"), + ("Ground Plane Offset", "Décalage du sol"), + ("High Poly Mesh Suffix", "Suffixe du maillage high poly"), + ("High Poly Scene", "Scène haute définition"), + ("High-Poly Parameters", "Paramètres haute définition"), + ("Hue Shift", "Décalage de teinte"), + ("Ignore Backface", "Ignorer les faces arrière"), + ("Ignore Backface Suffix", "Suffixe des faces arrière ignorées"), + ("Include in Bake", "Inclure dans le précalcul"), + ("Load Cage", "Charger une cage"), + ("Lock Output Size", "Verrouiller les dimensions de sortie"), + ("Low Poly Mesh Suffix", "Suffixe du maillage low poly"), + ("Manual", "Manuel"), + ("Material Color", "Couleur du matériau"), + ("Max Frontal Distance", "Distance frontale max"), + ("Max Occluder Distance", "Distance max des occulteurs"), + ("Max Rear Distance", "Distance arrière max"), + ("Mesh ID", "ID du maillage"), + ("Method", "Méthode"), + ("Min Occluder Distance", "Distance minimale des occluseurs"), + ("Never", "Jamais"), + ("No High-Poly Meshes", "Aucun maillage haute définition"), + ("Normalization Scale", "Échelle de normalisation"), + ("Normalization Type", "Type de normalisation"), + ("Only Same Mesh Name", "Seulement le même nom de maillage"), + ("Output Size", "Taille de sortie"), + ("Paint Cage", "Peindre la cage"), + ("Paint Skew Correction", "Peindre la correction d'inclinaison"), + ("Per Material", "Par matériau"), + ("Random", "Aléatoire"), + ("Relative to Bounding Box", "Relatif à la boîte englobante"), + ("Relative to Low Mesh", "Relatif au maillage basse définition"), + ("Relative to Min/Max", "Relatif au minimum/maximum"), + ("Relative to Ray Distances", "Relatif aux distances des rayons"), + ("Remove Cage", "Supprimer la cage"), + ("Remove Skew Correction", "Supprimer la correction d'inclinaison"), + ("Restore Defaults", "Rétablir les valeurs par défaut"), + ("Return to Painting Mode", "Revenir au mode peinture"), + ("Sampling Radius", "Rayon d'échantillonnage"), + ("Scaling Divisor", "Diviseur d'échelle"), + ("Seams Intensity", "Intensité des coutures"), + ("Secondary Rays", "Rayons secondaires"), + ("Self Intersection", "Auto-intersection"), + ("Self Occlusion", "Auto-occlusion"), + ("Skew Correction", "Correction d'inclinaison"), + ("Smooth", "Lisse"), + ("Spread Angle", "Angle de dispersion"), + ("Submesh", "Sous-maillage"), + ("Use Low Poly Mesh as High Poly Mesh", "Utiliser le maillage low poly comme maillage high poly"), + ("Value Bounds Max", "Borne maximale"), + ("Value Bounds Min", "Borne minimale"), + ("Vertex Color", "Couleur des sommets"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 765f5e8c..f3bcbaf3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -47,7 +47,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Aggiungi filtro"), ("Add folder", "Aggiungi cartella"), ("Add generator", "Aggiungi generatore"), - ("Add high definition meshes", "Aggiungi mesh ad alta definizione"), ("Add levels", "Aggiungi Livelli"), ("Add mask", "Aggiungi maschera"), ("Add mask with color selection", "Aggiungi maschera con selezione colore"), @@ -83,7 +82,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Assegnata anche a {item} ({menu})"), ("Alt + LMB drag", "Alt + trascina (tasto sinistro)"), ("Always", "Sempre"), - ("Ambient occlusion", "Occlusione ambientale"), + ("Ambient Occlusion", "Occlusione ambientale"), ("Ambient occlusion intensity", "Intensità occlusione ambientale"), ("Amount", "Quantità"), ("Anchor point", "Punto di ancoraggio"), @@ -99,7 +98,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), ("Apply", "Applica"), - ("Apply to all texture sets", "Applica a tutti i set di texture"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), @@ -108,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Salvataggi automatici, materiali smart, preset, modelli e layout dell'interfaccia vanno nella cartella dei dati. Una nuova cartella si applica al riavvio; i file già salvati restano dove sono.", ), - ("Average normals", "Normali medie"), ("Axis", "Asse"), ("Back to painting", "Torna alla pittura"), ("Backface culling", "Culling facce posteriori"), @@ -118,8 +115,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Esegui il bake delle mappe mesh (F8) per i generatori basati su curvatura, AO e spessore.", ), - ("Bake selected textures ({n})", "Bake texture selezionate ({n})"), - ("Bake with \"Bake selected textures\"", "Esegui il bake con \"Bake texture selezionate\""), ("Baked Lighting", "Illuminazione precalcolata"), ("Baking", "Baking"), ("Base color", "Colore base"), @@ -130,7 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Colore base, Metallico, Rugosità e Livello speculare."), ("Based on each texture set's size", "In base alla dimensione di ciascun set di texture"), ("Basic settings", "Impostazioni di base"), - ("Bent normals", "Bent normal"), + ("Bent Normals", "Bent normal"), ("Bevel", "Smusso"), ("Black", "Nero"), ("Blend sharpness", "Nitidezza della fusione"), @@ -148,7 +143,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Integrato (sola lettura): duplicalo per modificarlo"), ("Built-in templates are read-only: duplicate one to edit it", "I modelli integrati sono di sola lettura: duplicane uno per modificarlo"), ("Built-in: {mesh}", "Integrata: {mesh}"), - ("By mesh name", "Per nome della mesh"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), ("Camera settings", "Impostazioni camera"), @@ -183,7 +177,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Bilanciamento colore"), ("Color burn", "Brucia colore"), ("Color dodge", "Scherma colore"), - ("Color map", "Mappa colore"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Colore della luce che viaggia sotto la superficie (ogni canale arriva fino al proprio valore)", @@ -200,7 +193,6 @@ pub const TABLE: &[(&str, &str)] = &[ "I colori vengono letti come grigio. Aggiungi sopra un effetto Livelli o Sfocatura per modellare il risultato.", ), ("Combine with the layer's height", "Combina con l'altezza del livello"), - ("Common parameters", "Parametri comuni"), ("Compare mask", "Maschera di confronto"), ("Compositing", "Compositing"), ("Constant", "Costante"), @@ -213,7 +205,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copia da"), ("Copy layer(s)", "Copia livello/i"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copia solo il livello selezionato (le sue parti vuote non copiano nulla)"), - ("Copy these bake settings to every texture set", "Copia queste impostazioni di bake in tutti i set di texture"), ("Copy to all texture sets", "Copia in tutti i set di texture"), ("Copy what the texture set shows", "Copia ciò che mostra il set di texture"), ("Couldn't encode the render", "Impossibile codificare il render"), @@ -264,8 +255,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatazione + colore di sfondo predefinito"), ("Dilation + transparent", "Dilatazione + trasparente"), ("Dilation infinite", "Dilatazione infinita"), - ("Dilation width", "Ampiezza dilatazione"), - ("Direction {axis}", "Direzione {axis}"), ("DirectX normal map", "Mappa normali DirectX"), ("Dirt", "Sporco"), ("Disable", "Disattiva"), @@ -369,11 +358,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Per l'intero progetto: come vengono lette le immagini di mappe normali usate come mappe mesh (riassegnale dopo una modifica) e il valore predefinito per l'esportazione", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Libero e open source (MIT OR Apache-2.0), scritto in Rust."), - ("From normal map", "Da mappa normali"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Da mappa normali: curvatura dei dettagli della mappa normali sottoposta a bake anziché della mesh.", - ), ("From template", "Da modello"), ("From template / project", "Da modello / progetto"), ("Full", "Piena"), @@ -413,12 +397,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Aiuto"), ("Hide UI", "Nascondi interfaccia"), ("High", "Alto"), - ("High definition meshes", "Mesh ad alta definizione"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altezza dell'high poly tra la distanza posteriore massima (nero) e la distanza frontale massima (bianco).", - ), - ("High poly mesh suffix", "Suffisso mesh high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Luci"), ("Histogram Range", "Intervallo istogramma"), @@ -506,11 +484,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luce lineare"), ("List of exports", "Elenco esportazioni"), ("Load UI Layout", "Carica layout interfaccia"), - ("Load a cage (the low poly, inflated)", "Carica una gabbia (la low poly, gonfiata)"), ("Loaded UI layout {path}", "Layout interfaccia caricato: {path}"), ("Log", "Log"), ("Low", "Basso"), - ("Low poly mesh suffix", "Suffisso mesh low poly"), ("Luminosity", "Luminosità"), ("MMB drag / Alt + MMB", "Trascina (tasto centrale) / Alt + tasto centrale"), ("Made by the ArtCraft team and community.", "Realizzato dal team e dalla community di ArtCraft."), @@ -524,17 +500,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martellato"), ("MatFinish Raw", "MatFinish Grezzo"), ("MatFinish Sanded", "MatFinish Carteggiato"), - ("Match", "Corrispondenza"), ("Material", "Materiale"), ("Material ball", "Sfera materiale"), ("Material finish", "Finitura materiale"), ("Materials", "Materiali"), - ("Max frontal distance", "Distanza frontale max"), - ("Max occluder distance", "Distanza max occlusori"), - ("Max rear distance", "Distanza posteriore max"), ("Maximum", "Massimo"), ("Mesh fill", "Riempimento mesh"), - ("Mesh map bakers", "Baker mappe mesh"), ("Mesh map: {map}", "Mappa mesh: {map}"), ("Mesh maps", "Mappe mesh"), ("Mesh maps baked", "Bake delle mappe mesh completato"), @@ -573,7 +544,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantità rumore"), ("Noise scale", "Scala rumore"), ("None", "Nessuno"), - ("None: the low poly is its own high poly.", "Nessuna: la low poly è la propria high poly."), ("Normal", "Normale"), ("Normal DirectX", "Normale DirectX"), ("Normal Invert", "Inverti normale"), @@ -605,7 +575,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Sposta le texture in base al canale altezza, con l'intensità altezza in normale", ), ("On", "Attivato"), - ("One color per mesh part.", "Un colore per ogni parte della mesh."), ("Opacity", "Opacità"), ("Open sample project...", "Apri progetto di esempio..."), ("Open...", "Apri..."), @@ -619,7 +588,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "Cartella di output"), ("Output high", "Output alto"), ("Output low", "Output basso"), - ("Output size", "Dimensione output"), ("Output template", "Modello di output"), ("Output templates", "Modelli di output"), ("Overlay", "Sovrapponi"), @@ -699,7 +667,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Ripeti"), ("Reimport mesh", "Reimporta mesh"), - ("Relative to the bounding box diagonal.", "Relativa alla diagonale del bounding box."), ("Remove", "Rimuovi"), ("Remove channel", "Rimuovi canale"), ("Remove effect", "Rimuovi effetto"), @@ -708,7 +675,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "Rimuovi livello/i"), ("Remove mask", "Rimuovi maschera"), ("Remove resource", "Rimuovi risorsa"), - ("Remove the cage", "Rimuovi la gabbia"), ("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"), ("Remove the shortcut", "Rimuovi la scorciatoia"), ("Remove this output", "Rimuovi questo output"), @@ -734,13 +700,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "Ripristina {shortcut}"), ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), - ("Return to painting mode", "Torna alla modalità pittura"), ("Return to this step", "Torna a questo passaggio"), - ("Auto-rebake", "Bake automatico"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Esegue di nuovo il bake di questa mappa quando cambiano le sue impostazioni di bake, la mesh low poly o le mesh high poly", - ), ("Right-click a layer > Create smart material", "Clic destro su un livello > Crea materiale intelligente"), ("Rotation", "Rotazione"), ("Rotation (degrees)", "Rotazione (gradi)"), @@ -770,7 +730,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "Screenshot della viewport"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), - ("Secondary rays", "Raggi secondari"), ("Seed", "Seme"), ("Select a layer", "Seleziona un livello"), ("Select an output template", "Seleziona un modello di output"), @@ -838,13 +797,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "Simmetria (X)"), ("Symmetry (Y)", "Simmetria (Y)"), ("Tangent | Wrap", "Tangente | Avvolgi"), - ("Tangent-space normals of the high definition meshes.", "Normali in spazio tangente delle mesh ad alta definizione."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anti-aliasing temporale (affina la vista 3D quando è ferma)"), - ("Texture Set List", "Elenco set di texture"), + ("Texture Sets", "Set di texture"), ("Texture Set Settings", "Impostazioni set di texture"), ("Texture resolution", "Risoluzione texture"), ("Texture set channels", "Canali del set di texture"), - ("Texture set list", "Elenco set di texture"), ("Texture sets", "Set di texture"), ("TextureCraft had to close:", "TextureCraft ha dovuto chiudersi:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metallico Rugosità"), @@ -899,7 +856,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "Usa come alpha del pennello (o trascinala nella viewport o nelle proprietà del pennello)", ), - ("Use low poly mesh as high poly mesh", "Usa la mesh low poly come mesh high poly"), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), ("Value", "Valore"), ("Version {version}", "Versione {version}"), @@ -920,18 +876,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Rotella / Alt + trascina (tasto destro)"), ("White", "Bianco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Bianco dove la superficie è rivolta verso la direzione, nero dove è rivolta nel verso opposto.", - ), ("Width", "Larghezza"), ("Width (texels at 2K)", "Larghezza (texel a 2K)"), ("Window", "Finestra"), ("Wood grain", "Venatura legno"), ("Works in texture space, like the blur: it does not cross UV seams.", "Opera nello spazio texture, come la sfocatura: non attraversa le cuciture UV."), - ("World space direction", "Direzione spazio mondo"), - ("World space normal", "Normale spazio mondo"), - ("World-space normals of the high poly (or the low poly).", "Normali in spazio mondo dell'high poly (o della low poly)."), + ("World Space Normal", "Normale spazio mondo"), ("Yellow / blue", "Giallo / blu"), ("Zoom", "Zoom"), ("a missing layer", "un livello mancante"), @@ -968,7 +918,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: aggiungi sopra il livello selezionato (o trascinalo nella pila dei livelli o nella viewport)", ), - ("{name} ({n} triangles)", "{name} ({n} triangoli)"), ("{name} copy", "{name} copia"), ("{n} bits", "{n} bit"), ( @@ -979,31 +928,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (scala {scale}, seme {seed})"), ("Template name", "Nome del modello"), ("Save current project as template", "Salva il progetto corrente come modello"), - ("Spread angle", "Angolo di diffusione"), ("Distribution", "Distribuzione"), ("Cosine", "Coseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignora facce posteriori"), - ("Self occlusion", "Auto-occlusione"), - ("Only same mesh name", "Solo stesso nome mesh"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "I raggi delle bent normal seguono le impostazioni degli occlusori dell'occlusione ambientale.", - ), - ("Sampling radius", "Raggio di campionamento"), - ("0 picks a radius from the output size.", "0 sceglie un raggio in base alla dimensione di output."), - ("Encoding", "Codifica"), - ("Signed (-1..1)", "Con segno (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalizzazione"), - ("Bounding box", "Bounding box"), - ("Bounding sphere", "Sfera di contenimento"), - ("Position normalized to the low poly's bounding box or sphere.", "Posizione normalizzata sul bounding box o sulla sfera di contenimento della low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Colori base (texture, fattori) e colori dei vertici delle mesh ad alta definizione.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Bianco dove la high poly copre la low poly, moltiplicato per il suo alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Luminosità"), ("Dark", "Scuro"), @@ -1050,12 +978,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Modifiche non salvate"), ("Don't save", "Non salvare"), ("Save the changes to {name} before closing?", "Salvare le modifiche a {name} prima di chiudere?"), - ("Skew correction", "Correzione dell'inclinazione"), - ("Paint skew in the 2D view", "Dipingi l'inclinazione nella vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Trascina nella vista 2D per dipingere dove i raggi del bake si orientano verso la normale di base; dipingi con valore 0 per cancellare", - ), ("Radius", "Raggio"), ("Remove skew correction", "Rimuovi la correzione dell'inclinazione"), ("Twill weave", "Tessuto a saia"), @@ -1075,4 +997,85 @@ pub const TABLE: &[(&str, &str)] = &[ "Aperto in MaterialCraft: usa lì File > Invia a TextureCraft per riportare le modifiche", ), ("Parameters change in the desktop app, with MaterialCraft installed", "I parametri si modificano nell'app desktop, con MaterialCraft installato"), + ("Add High-Poly Meshes", "Aggiungi mesh ad alta risoluzione"), + ("All", "Tutti"), + ("Apply Diffusion", "Applica diffusione"), + ("Attenuation", "Attenuazione"), + ("Auto Tonemapping", "Mappatura tonale automatica"), + ("Average Normals", "Normali medie"), + ("BBox", "Riquadro di delimitazione"), + ("BSphere", "Sfera di delimitazione"), + ("Bake Maps", "Bake delle mappe"), + ("Bake Selected Textures ({n})", "Bake texture selezionate ({n})"), + ("By Mesh Name", "Per nome della mesh"), + ("Cage", "Gabbia"), + ("Cage Scene", "Scena della gabbia"), + ("Cage Type", "Tipo di gabbia"), + ("Color Generator", "Generatore di colori"), + ("Color Source", "Origine del colore"), + ("Common Parameters", "Parametri comuni"), + ("Custom File", "File personalizzato"), + ("Details", "Dettagli"), + ("Dilation Width", "Ampiezza dilatazione"), + ("Distance-Based", "Basata sulla distanza"), + ("Edge Contrast", "Contrasto dei bordi"), + ("Edge Distance", "Distanza dei bordi"), + ("Edge Protection", "Protezione dei bordi"), + ("Enable Seams", "Abilita cuciture"), + ("File ID", "ID del file"), + ("Full Scene", "Intera scena"), + ("Generate from Mesh", "Genera dalla mesh"), + ("Generate from Normal Map", "Genera dalla mappa delle normali"), + ("Ground Plane", "Piano del terreno"), + ("Ground Plane Offset", "Scostamento del terreno"), + ("High Poly Mesh Suffix", "Suffisso mesh high poly"), + ("High Poly Scene", "Scena ad alta risoluzione"), + ("High-Poly Parameters", "Parametri ad alta risoluzione"), + ("Hue Shift", "Variazione di tonalità"), + ("Ignore Backface", "Ignora facce posteriori"), + ("Ignore Backface Suffix", "Suffisso per ignorare le facce posteriori"), + ("Include in Bake", "Includi nel bake"), + ("Load Cage", "Carica gabbia"), + ("Lock Output Size", "Blocca dimensioni di output"), + ("Low Poly Mesh Suffix", "Suffisso mesh low poly"), + ("Manual", "Manuale"), + ("Material Color", "Colore del materiale"), + ("Max Frontal Distance", "Distanza frontale max"), + ("Max Occluder Distance", "Distanza max occlusori"), + ("Max Rear Distance", "Distanza posteriore max"), + ("Mesh ID", "ID della mesh"), + ("Method", "Metodo"), + ("Min Occluder Distance", "Distanza minima dell'occlusore"), + ("Never", "Mai"), + ("No High-Poly Meshes", "Nessuna mesh ad alta risoluzione"), + ("Normalization Scale", "Scala di normalizzazione"), + ("Normalization Type", "Tipo di normalizzazione"), + ("Only Same Mesh Name", "Solo stesso nome mesh"), + ("Output Size", "Dimensione output"), + ("Paint Cage", "Dipingi gabbia"), + ("Paint Skew Correction", "Dipingi correzione dell'inclinazione"), + ("Per Material", "Per materiale"), + ("Random", "Casuale"), + ("Relative to Bounding Box", "Relativo al riquadro di delimitazione"), + ("Relative to Low Mesh", "Relativo alla mesh a bassa risoluzione"), + ("Relative to Min/Max", "Relativo a minimo/massimo"), + ("Relative to Ray Distances", "Relativo alle distanze dei raggi"), + ("Remove Cage", "Rimuovi gabbia"), + ("Remove Skew Correction", "Rimuovi la correzione dell'inclinazione"), + ("Restore Defaults", "Ripristina valori predefiniti"), + ("Return to Painting Mode", "Torna alla modalità pittura"), + ("Sampling Radius", "Raggio di campionamento"), + ("Scaling Divisor", "Divisore di scala"), + ("Seams Intensity", "Intensità delle cuciture"), + ("Secondary Rays", "Raggi secondari"), + ("Self Intersection", "Autointersezione"), + ("Self Occlusion", "Auto-occlusione"), + ("Skew Correction", "Correzione dell'inclinazione"), + ("Smooth", "Uniforme"), + ("Spread Angle", "Angolo di diffusione"), + ("Submesh", "Sottomesh"), + ("Use Low Poly Mesh as High Poly Mesh", "Usa la mesh low poly come mesh high poly"), + ("Value Bounds Max", "Limite massimo"), + ("Value Bounds Min", "Limite minimo"), + ("Vertex Color", "Colore dei vertici"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 41f6a048..a376e6e3 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -50,7 +50,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "フィルターを追加"), ("Add folder", "フォルダーを追加"), ("Add generator", "ジェネレーターを追加"), - ("Add high definition meshes", "高精細メッシュを追加"), ("Add levels", "レベル補正を追加"), ("Add mask", "マスクを追加"), ("Add mask with color selection", "カラー選択でマスクを追加"), @@ -86,7 +85,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "{item} ({menu}) にも割り当て済み"), ("Alt + LMB drag", "Alt + 左ドラッグ"), ("Always", "常に"), - ("Ambient occlusion", "アンビエントオクルージョン"), + ("Ambient Occlusion", "アンビエントオクルージョン"), ("Ambient occlusion intensity", "アンビエントオクルージョンの強度"), ("Amount", "量"), ("Anchor point", "アンカーポイント"), @@ -102,7 +101,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), ("Apply", "適用"), - ("Apply to all texture sets", "すべてのテクスチャセットに適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), @@ -111,7 +109,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "自動保存、スマートマテリアル、プリセット、テンプレート、UI レイアウトはデータフォルダーに保存されます。新しいフォルダーは再起動後に適用され、保存済みのファイルはそのまま残ります。", ), - ("Average normals", "法線を平均化"), ("Axis", "軸"), ("Back to painting", "ペイントに戻る"), ("Backface culling", "背面カリング"), @@ -121,8 +118,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "曲率、AO、厚みに基づくジェネレーターには、メッシュマップのベイク (F8) が必要です。", ), - ("Bake selected textures ({n})", "選択したテクスチャをベイク ({n})"), - ("Bake with \"Bake selected textures\"", "「選択したテクスチャをベイク」でベイク"), ("Baked Lighting", "ライティングのベイク"), ("Baking", "ベイク"), ("Base color", "ベースカラー"), @@ -133,7 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "ベースカラー、メタリック、ラフネス、スペキュラーレベル。"), ("Based on each texture set's size", "各テクスチャセットのサイズに基づく"), ("Basic settings", "基本設定"), - ("Bent normals", "ベントノーマル"), + ("Bent Normals", "ベントノーマル"), ("Bevel", "ベベル"), ("Black", "黒"), ("Blend sharpness", "ブレンドのシャープさ"), @@ -151,7 +146,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "組み込み (読み取り専用): 複製して編集"), ("Built-in templates are read-only: duplicate one to edit it", "組み込みテンプレートは読み取り専用です: 複製して編集"), ("Built-in: {mesh}", "組み込み: {mesh}"), - ("By mesh name", "メッシュ名で"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), ("Camera settings", "カメラ設定"), @@ -186,7 +180,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "カラーバランス"), ("Color burn", "焼き込みカラー"), ("Color dodge", "覆い焼きカラー"), - ("Color map", "カラーマップ"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "表面下を伝わる光の色 (各チャンネルは値に応じた距離まで届く)", @@ -200,7 +193,6 @@ pub const TABLE: &[(&str, &str)] = &[ "カラーはグレーとして読み取られます。結果を調整するには、上にレベル補正またはぼかしエフェクトを追加します。", ), ("Combine with the layer's height", "レイヤーのハイトと合成"), - ("Common parameters", "共通パラメーター"), ("Compare mask", "比較マスク"), ("Compositing", "合成中"), ("Constant", "定数"), @@ -213,7 +205,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "コピー元"), ("Copy layer(s)", "レイヤーをコピー"), ("Copy the selected layer alone (its empty parts copy nothing)", "選択中のレイヤーのみをコピー (空の部分は何もコピーしない)"), - ("Copy these bake settings to every texture set", "このベイク設定をすべてのテクスチャセットにコピー"), ("Copy to all texture sets", "すべてのテクスチャセットにコピー"), ("Copy what the texture set shows", "テクスチャセットの表示内容をコピー"), ("Couldn't encode the render", "レンダリング結果をエンコードできませんでした"), @@ -261,8 +252,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "ダイレーション + デフォルト背景色"), ("Dilation + transparent", "ダイレーション + 透明"), ("Dilation infinite", "ダイレーション (無限)"), - ("Dilation width", "ダイレーション幅"), - ("Direction {axis}", "方向 {axis}"), ("DirectX normal map", "DirectX ノーマルマップ"), ("Dirt", "汚れ"), ("Disable", "無効"), @@ -357,11 +346,6 @@ pub const TABLE: &[(&str, &str)] = &[ "プロジェクト全体: メッシュマップとして設定したノーマルマップ画像の読み取り方 (変更後は設定し直してください) と、書き出しの既定値", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "無料のオープンソース (MIT OR Apache-2.0)、Rustで開発。"), - ("From normal map", "ノーマルマップから"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "ノーマルマップから: メッシュではなく、ベイクしたノーマルマップのディテールの曲率。", - ), ("From template", "テンプレートから"), ("From template / project", "テンプレート / プロジェクトから"), ("Full", "フル"), @@ -401,9 +385,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "ヘルプ"), ("Hide UI", "UIを非表示"), ("High", "高"), - ("High definition meshes", "高精細メッシュ"), - ("High poly height between the max rear (black) and max frontal (white) distances.", "後方最大距離 (黒) から前方最大距離 (白) までのハイポリの高さ。"), - ("High poly mesh suffix", "ハイポリメッシュの接尾辞"), ("High poly: {name}", "ハイポリ: {name}"), ("Highlights", "ハイライト"), ("Histogram Range", "ヒストグラム範囲"), @@ -491,11 +472,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "リニアライト"), ("List of exports", "エクスポート一覧"), ("Load UI Layout", "UIレイアウトを読み込み"), - ("Load a cage (the low poly, inflated)", "ケージを読み込み (膨張させたローポリ)"), ("Loaded UI layout {path}", "UIレイアウト {path} を読み込みました"), ("Log", "ログ"), ("Low", "低"), - ("Low poly mesh suffix", "ローポリメッシュの接尾辞"), ("Luminosity", "輝度"), ("MMB drag / Alt + MMB", "中ドラッグ / Alt + 中ドラッグ"), ("Made by the ArtCraft team and community.", "ArtCraftチームとコミュニティによって制作。"), @@ -509,17 +488,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish 槌目"), ("MatFinish Raw", "MatFinish 未加工"), ("MatFinish Sanded", "MatFinish サンディング"), - ("Match", "マッチング"), ("Material", "マテリアル"), ("Material ball", "マテリアルボール"), ("Material finish", "マテリアル仕上げ"), ("Materials", "マテリアル"), - ("Max frontal distance", "前方最大距離"), - ("Max occluder distance", "遮蔽物の最大距離"), - ("Max rear distance", "後方最大距離"), ("Maximum", "最大"), ("Mesh fill", "メッシュ塗りつぶし"), - ("Mesh map bakers", "メッシュマップベイカー"), ("Mesh map: {map}", "メッシュマップ: {map}"), ("Mesh maps", "メッシュマップ"), ("Mesh maps baked", "メッシュマップをベイクしました"), @@ -558,7 +532,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "ノイズ量"), ("Noise scale", "ノイズスケール"), ("None", "なし"), - ("None: the low poly is its own high poly.", "なし: ローポリ自体をハイポリとして使用します。"), ("Normal", "ノーマル"), ("Normal DirectX", "ノーマル DirectX"), ("Normal Invert", "ノーマル反転"), @@ -590,7 +563,6 @@ pub const TABLE: &[(&str, &str)] = &[ "ハイトチャンネルに応じてテクスチャをオフセットします (強度はハイト→ノーマル強度)", ), ("On", "オン"), - ("One color per mesh part.", "メッシュパーツごとに1色。"), ("Opacity", "不透明度"), ("Open sample project...", "サンプルプロジェクトを開く..."), ("Open...", "開く..."), @@ -604,7 +576,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "出力先フォルダー"), ("Output high", "出力の上限"), ("Output low", "出力の下限"), - ("Output size", "出力サイズ"), ("Output template", "出力テンプレート"), ("Output templates", "出力テンプレート"), ("Overlay", "オーバーレイ"), @@ -678,7 +649,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "やり直し"), ("Reimport mesh", "メッシュを再インポート"), - ("Relative to the bounding box diagonal.", "バウンディングボックスの対角線に対する相対値。"), ("Remove", "削除"), ("Remove channel", "チャンネルを削除"), ("Remove effect", "エフェクトを削除"), @@ -687,7 +657,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "レイヤーを削除"), ("Remove mask", "マスクを削除"), ("Remove resource", "リソースを削除"), - ("Remove the cage", "ケージを削除"), ("Remove the path (Esc)", "パスを削除 (Esc)"), ("Remove the shortcut", "ショートカットを削除"), ("Remove this output", "この出力を削除"), @@ -713,13 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "{shortcut} にリセット"), ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), - ("Return to painting mode", "ペイントモードに戻る"), ("Return to this step", "このステップに戻る"), - ("Auto-rebake", "自動再ベイク"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "ベイク設定、ローポリ、またはハイポリが変わると、このマップを自動的にベイクし直します", - ), ("Right-click a layer > Create smart material", "レイヤーを右クリック > スマートマテリアルを作成"), ("Rotation", "回転"), ("Rotation (degrees)", "回転 (度)"), @@ -749,7 +712,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "ビューポートのスクリーンショット"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), - ("Secondary rays", "二次レイ"), ("Seed", "シード"), ("Select a layer", "レイヤーを選択"), ("Select an output template", "出力テンプレートを選択"), @@ -817,13 +779,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "対称 (X)"), ("Symmetry (Y)", "対称 (Y)"), ("Tangent | Wrap", "タンジェント | ラップ"), - ("Tangent-space normals of the high definition meshes.", "高精細メッシュのタンジェント空間法線。"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "テンポラルアンチエイリアス (静止中に3Dビューを精細化)"), - ("Texture Set List", "テクスチャセット一覧"), + ("Texture Sets", "テクスチャセット"), ("Texture Set Settings", "テクスチャセット設定"), ("Texture resolution", "テクスチャ解像度"), ("Texture set channels", "テクスチャセットのチャンネル"), - ("Texture set list", "テクスチャセット一覧"), ("Texture sets", "テクスチャセット"), ("TextureCraft had to close:", "TextureCraft を終了する必要がありました:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - メタリック/ラフネス"), @@ -878,7 +838,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "ブラシのアルファとして使用 (ビューポートやブラシプロパティへのドラッグも可)", ), - ("Use low poly mesh as high poly mesh", "ローポリメッシュをハイポリメッシュとして使用"), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", @@ -902,15 +861,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "ホイール / Alt + 右ドラッグ"), ("White", "白"), - ("White where the surface faces the direction, black where it faces away.", "表面がその方向を向く部分は白、反対を向く部分は黒。"), ("Width", "幅"), ("Width (texels at 2K)", "幅 (2K時のテクセル)"), ("Window", "ウィンドウ"), ("Wood grain", "木目"), ("Works in texture space, like the blur: it does not cross UV seams.", "ぼかしと同様にテクスチャ空間で処理するため、UVシームをまたぎません。"), - ("World space direction", "ワールド空間方向"), - ("World space normal", "ワールド空間ノーマル"), - ("World-space normals of the high poly (or the low poly).", "ハイポリ (またはローポリ) のワールド空間法線。"), + ("World Space Normal", "ワールド空間ノーマル"), ("Yellow / blue", "イエロー / ブルー"), ("Zoom", "ズーム"), ("a missing layer", "見つからないレイヤー"), @@ -947,7 +903,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: 選択中のレイヤーの上に追加 (レイヤースタックやビューポートへのドラッグも可)", ), - ("{name} ({n} triangles)", "{name} (三角形 {n} 個)"), ("{name} copy", "{name} のコピー"), ("{n} bits", "{n} ビット"), ( @@ -958,25 +913,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (スケール {scale}、シード {seed})"), ("Template name", "テンプレート名"), ("Save current project as template", "現在のプロジェクトをテンプレートとして保存"), - ("Spread angle", "拡散角度"), ("Distribution", "分布"), ("Cosine", "コサイン"), ("Uniform", "均一"), - ("Ignore backface", "裏面を無視"), - ("Self occlusion", "自己遮蔽"), - ("Only same mesh name", "同じメッシュ名のみ"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "ベントノーマルのレイはアンビエントオクルージョンの遮蔽物設定に従います。"), - ("Sampling radius", "サンプリング半径"), - ("0 picks a radius from the output size.", "0 の場合は出力サイズから半径を決めます。"), - ("Encoding", "エンコード"), - ("Signed (-1..1)", "符号付き (-1..1)"), - ("Positive (0..1)", "正の値 (0..1)"), ("Normalization", "正規化"), - ("Bounding box", "バウンディングボックス"), - ("Bounding sphere", "バウンディングスフィア"), - ("Position normalized to the low poly's bounding box or sphere.", "ローポリのバウンディングボックスまたはスフィアで正規化した位置。"), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "高精細メッシュのベースカラー (テクスチャ、係数) と頂点カラー。"), - ("White where the high poly covers the low poly, times its alpha.", "ハイポリがローポリを覆う部分が白 (アルファを乗算)。"), // Settings › Interface: brightness and accent color. ("Brightness", "明るさ"), ("Dark", "ダーク"), @@ -1023,12 +963,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存の変更"), ("Don't save", "保存しない"), ("Save the changes to {name} before closing?", "閉じる前に {name} の変更を保存しますか?"), - ("Skew correction", "スキュー補正"), - ("Paint skew in the 2D view", "2Dビューでスキューをペイント"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "2Dビューでドラッグして、ベイクのレイがベース法線へ向かう箇所をペイントします。値0でペイントすると消去されます", - ), ("Radius", "半径"), ("Remove skew correction", "スキュー補正を削除"), ("Twill weave", "綾織り"), @@ -1048,4 +982,85 @@ pub const TABLE: &[(&str, &str)] = &[ "MaterialCraft で開きました。変更を戻すには、そちらで「ファイル > TextureCraft に送る」を使います", ), ("Parameters change in the desktop app, with MaterialCraft installed", "パラメーターは MaterialCraft をインストールしたデスクトップ版で変更できます"), + ("Add High-Poly Meshes", "ハイポリメッシュを追加"), + ("All", "すべて"), + ("Apply Diffusion", "拡散を適用"), + ("Attenuation", "減衰"), + ("Auto Tonemapping", "自動トーンマッピング"), + ("Average Normals", "法線を平均化"), + ("BBox", "バウンディングボックス"), + ("BSphere", "バウンディングスフィア"), + ("Bake Maps", "マップをベイク"), + ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), + ("By Mesh Name", "メッシュ名で"), + ("Cage", "ケージ"), + ("Cage Scene", "ケージシーン"), + ("Cage Type", "ケージの種類"), + ("Color Generator", "カラー生成"), + ("Color Source", "カラーソース"), + ("Common Parameters", "共通パラメーター"), + ("Custom File", "カスタムファイル"), + ("Details", "ディテール"), + ("Dilation Width", "ダイレーション幅"), + ("Distance-Based", "距離ベース"), + ("Edge Contrast", "エッジコントラスト"), + ("Edge Distance", "エッジ距離"), + ("Edge Protection", "エッジ保護"), + ("Enable Seams", "シームを有効化"), + ("File ID", "ファイルID"), + ("Full Scene", "シーン全体"), + ("Generate from Mesh", "メッシュから生成"), + ("Generate from Normal Map", "法線マップから生成"), + ("Ground Plane", "グラウンドプレーン"), + ("Ground Plane Offset", "グラウンドプレーンのオフセット"), + ("High Poly Mesh Suffix", "ハイポリメッシュの接尾辞"), + ("High Poly Scene", "ハイポリシーン"), + ("High-Poly Parameters", "ハイポリパラメーター"), + ("Hue Shift", "色相シフト"), + ("Ignore Backface", "裏面を無視"), + ("Ignore Backface Suffix", "裏面を無視するサフィックス"), + ("Include in Bake", "ベイク対象に含める"), + ("Load Cage", "ケージを読み込む"), + ("Lock Output Size", "出力サイズをロック"), + ("Low Poly Mesh Suffix", "ローポリメッシュの接尾辞"), + ("Manual", "手動"), + ("Material Color", "マテリアルカラー"), + ("Max Frontal Distance", "前方最大距離"), + ("Max Occluder Distance", "遮蔽物の最大距離"), + ("Max Rear Distance", "後方最大距離"), + ("Mesh ID", "メッシュID"), + ("Method", "方式"), + ("Min Occluder Distance", "最小遮蔽距離"), + ("Never", "しない"), + ("No High-Poly Meshes", "ハイポリメッシュなし"), + ("Normalization Scale", "正規化スケール"), + ("Normalization Type", "正規化の種類"), + ("Only Same Mesh Name", "同じメッシュ名のみ"), + ("Output Size", "出力サイズ"), + ("Paint Cage", "ケージをペイント"), + ("Paint Skew Correction", "スキュー補正をペイント"), + ("Per Material", "マテリアルごと"), + ("Random", "ランダム"), + ("Relative to Bounding Box", "バウンディングボックスに相対"), + ("Relative to Low Mesh", "ローポリメッシュに相対"), + ("Relative to Min/Max", "最小値・最大値に相対"), + ("Relative to Ray Distances", "レイ距離に相対"), + ("Remove Cage", "ケージを削除"), + ("Remove Skew Correction", "スキュー補正を削除"), + ("Restore Defaults", "既定値に戻す"), + ("Return to Painting Mode", "ペイントモードに戻る"), + ("Sampling Radius", "サンプリング半径"), + ("Scaling Divisor", "スケーリング除数"), + ("Seams Intensity", "シームの強度"), + ("Secondary Rays", "二次レイ"), + ("Self Intersection", "自己交差"), + ("Self Occlusion", "自己遮蔽"), + ("Skew Correction", "スキュー補正"), + ("Smooth", "スムーズ"), + ("Spread Angle", "拡散角度"), + ("Submesh", "サブメッシュ"), + ("Use Low Poly Mesh as High Poly Mesh", "ローポリメッシュをハイポリメッシュとして使用"), + ("Value Bounds Max", "値の上限"), + ("Value Bounds Min", "値の下限"), + ("Vertex Color", "頂点カラー"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9f6aabbe..39f2dfad 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -47,7 +47,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "필터 추가"), ("Add folder", "폴더 추가"), ("Add generator", "제너레이터 추가"), - ("Add high definition meshes", "고해상도 메시 추가"), ("Add levels", "레벨 추가"), ("Add mask", "마스크 추가"), ("Add mask with color selection", "색상 선택으로 마스크 추가"), @@ -83,7 +82,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "{item}({menu})에도 지정됨"), ("Alt + LMB drag", "Alt + 왼쪽 드래그"), ("Always", "항상"), - ("Ambient occlusion", "앰비언트 오클루전"), + ("Ambient Occlusion", "앰비언트 오클루전"), ("Ambient occlusion intensity", "앰비언트 오클루전 강도"), ("Amount", "양"), ("Anchor point", "앵커 포인트"), @@ -99,7 +98,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), ("Apply", "적용"), - ("Apply to all texture sets", "모든 텍스처 세트에 적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), @@ -108,15 +106,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "자동 저장, 스마트 머티리얼, 프리셋, 템플릿과 UI 레이아웃은 데이터 폴더에 저장됩니다. 새 폴더는 다시 시작하면 적용되며, 이미 저장된 파일은 그대로 남습니다.", ), - ("Average normals", "노멀 평균화"), ("Axis", "축"), ("Back to painting", "페인팅으로 돌아가기"), ("Backface culling", "후면 컬링"), ("Bake Mesh Maps", "메시 맵 베이크"), ("Bake mesh maps", "메시 맵 베이크"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."), - ("Bake selected textures ({n})", "선택한 텍스처 베이크 ({n})"), - ("Bake with \"Bake selected textures\"", "\"선택한 텍스처 베이크\"로 베이크합니다"), ("Baked Lighting", "베이크된 조명"), ("Baking", "베이킹"), ("Base color", "베이스 컬러"), @@ -127,7 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "베이스 컬러, 메탈릭, 러프니스, 스페큘러 레벨."), ("Based on each texture set's size", "각 텍스처 세트 크기 기준"), ("Basic settings", "기본 설정"), - ("Bent normals", "벤트 노멀"), + ("Bent Normals", "벤트 노멀"), ("Bevel", "베벨"), ("Black", "검은색"), ("Blend sharpness", "블렌드 선명도"), @@ -145,7 +140,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "기본 제공 (읽기 전용): 편집하려면 복제하세요"), ("Built-in templates are read-only: duplicate one to edit it", "기본 제공 템플릿은 읽기 전용입니다. 편집하려면 복제하세요"), ("Built-in: {mesh}", "기본 제공: {mesh}"), - ("By mesh name", "메시 이름으로"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), ("Camera settings", "카메라 설정"), @@ -177,7 +171,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "색상 균형"), ("Color burn", "색상 번"), ("Color dodge", "색상 닷지"), - ("Color map", "컬러 맵"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "표면 아래로 이동하는 빛의 색상입니다 (각 채널은 값만큼 멀리 이동)", @@ -191,7 +184,6 @@ pub const TABLE: &[(&str, &str)] = &[ "색상은 회색으로 읽힙니다. 결과를 조정하려면 위에 레벨 또는 블러 이펙트를 추가하세요.", ), ("Combine with the layer's height", "레이어 높이와 결합"), - ("Common parameters", "공통 매개변수"), ("Compare mask", "비교 마스크"), ("Compositing", "합성 중"), ("Constant", "상수"), @@ -204,7 +196,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "복사 원본"), ("Copy layer(s)", "레이어 복사"), ("Copy the selected layer alone (its empty parts copy nothing)", "선택한 레이어만 복사합니다 (빈 부분은 복사되지 않음)"), - ("Copy these bake settings to every texture set", "이 베이크 설정을 모든 텍스처 세트에 복사합니다"), ("Copy to all texture sets", "모든 텍스처 세트에 복사"), ("Copy what the texture set shows", "텍스처 세트에 표시되는 내용을 복사합니다"), ("Couldn't encode the render", "렌더를 인코딩할 수 없습니다"), @@ -255,8 +246,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "확장 + 기본 배경색"), ("Dilation + transparent", "확장 + 투명"), ("Dilation infinite", "무한 확장"), - ("Dilation width", "확장 폭"), - ("Direction {axis}", "방향 {axis}"), ("DirectX normal map", "DirectX 노멀 맵"), ("Dirt", "먼지"), ("Disable", "비활성화"), @@ -354,8 +343,6 @@ pub const TABLE: &[(&str, &str)] = &[ "프로젝트 전체: 메시 맵으로 지정한 노멀 맵 이미지를 읽는 방식(변경 후 다시 지정하세요)과 내보내기 기본값", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Rust로 작성된 무료 오픈 소스 소프트웨어입니다 (MIT OR Apache-2.0)."), - ("From normal map", "노멀 맵에서"), - ("From normal map: curvature of the baked normal map's detail instead of the mesh.", "노멀 맵에서: 메시 대신 베이크된 노멀 맵 디테일의 곡률을 사용합니다."), ("From template", "템플릿 기준"), ("From template / project", "템플릿 / 프로젝트 기준"), ("Full", "전체"), @@ -395,12 +382,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "도움말"), ("Hide UI", "UI 숨기기"), ("High", "높음"), - ("High definition meshes", "고해상도 메시"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "최대 후방 거리(검은색)와 최대 전방 거리(흰색) 사이의 하이 폴리 높이입니다.", - ), - ("High poly mesh suffix", "하이 폴리 메시 접미사"), ("High poly: {name}", "하이 폴리: {name}"), ("Highlights", "밝은 영역"), ("Histogram Range", "히스토그램 범위"), @@ -485,11 +466,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "선형 라이트"), ("List of exports", "내보내기 목록"), ("Load UI Layout", "UI 레이아웃 불러오기"), - ("Load a cage (the low poly, inflated)", "케이지를 불러옵니다 (부풀린 로우 폴리)"), ("Loaded UI layout {path}", "UI 레이아웃 불러옴: {path}"), ("Log", "로그"), ("Low", "낮음"), - ("Low poly mesh suffix", "로우 폴리 메시 접미사"), ("Luminosity", "광도"), ("MMB drag / Alt + MMB", "가운데 드래그 / Alt + 가운데 버튼"), ("Made by the ArtCraft team and community.", "ArtCraft 팀과 커뮤니티가 만들었습니다."), @@ -503,17 +482,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "마감 - 망치 자국"), ("MatFinish Raw", "마감 - 원재료"), ("MatFinish Sanded", "마감 - 샌딩"), - ("Match", "매칭"), ("Material", "머티리얼"), ("Material ball", "머티리얼 볼"), ("Material finish", "머티리얼 마감"), ("Materials", "머티리얼"), - ("Max frontal distance", "최대 전방 거리"), - ("Max occluder distance", "최대 차폐물 거리"), - ("Max rear distance", "최대 후방 거리"), ("Maximum", "최대"), ("Mesh fill", "메시 채우기"), - ("Mesh map bakers", "메시 맵 베이커"), ("Mesh map: {map}", "메시 맵: {map}"), ("Mesh maps", "메시 맵"), ("Mesh maps baked", "메시 맵 베이크 완료"), @@ -552,7 +526,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "노이즈 양"), ("Noise scale", "노이즈 스케일"), ("None", "없음"), - ("None: the low poly is its own high poly.", "없음: 로우 폴리를 하이 폴리로 사용합니다."), ("Normal", "노멀"), ("Normal DirectX", "노멀 DirectX"), ("Normal Invert", "노멀 반전"), @@ -581,7 +554,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "오프셋 {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "높이-노멀 변환 강도로 높이 채널에 따라 텍스처를 오프셋합니다"), ("On", "켜기"), - ("One color per mesh part.", "메시 파트마다 하나의 색상을 사용합니다."), ("Opacity", "불투명도"), ("Open sample project...", "샘플 프로젝트 열기..."), ("Open...", "열기..."), @@ -595,7 +567,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "출력 디렉터리"), ("Output high", "출력 상한"), ("Output low", "출력 하한"), - ("Output size", "출력 크기"), ("Output template", "출력 템플릿"), ("Output templates", "출력 템플릿"), ("Overlay", "오버레이"), @@ -669,7 +640,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "다시 실행"), ("Reimport mesh", "메시 다시 가져오기"), - ("Relative to the bounding box diagonal.", "바운딩 박스 대각선 기준입니다."), ("Remove", "제거"), ("Remove channel", "채널 제거"), ("Remove effect", "이펙트 제거"), @@ -678,7 +648,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "레이어 제거"), ("Remove mask", "마스크 제거"), ("Remove resource", "리소스 제거"), - ("Remove the cage", "케이지를 제거합니다"), ("Remove the path (Esc)", "패스를 제거합니다 (Esc)"), ("Remove the shortcut", "단축키를 제거합니다"), ("Remove this output", "이 출력을 제거합니다"), @@ -704,13 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), - ("Return to painting mode", "페인팅 모드로 돌아가기"), ("Return to this step", "이 단계로 돌아가기"), - ("Auto-rebake", "자동 다시 베이크"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "베이크 설정, 로우 폴리 또는 하이 폴리가 바뀌면 이 맵을 자동으로 다시 베이크합니다", - ), ("Right-click a layer > Create smart material", "레이어 마우스 오른쪽 클릭 > 스마트 머티리얼 만들기"), ("Rotation", "회전"), ("Rotation (degrees)", "회전 (도)"), @@ -740,7 +703,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "뷰포트 스크린샷"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), - ("Secondary rays", "보조 광선"), ("Seed", "시드"), ("Select a layer", "레이어를 선택하세요"), ("Select an output template", "출력 템플릿을 선택하세요"), @@ -808,13 +770,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "대칭 (X)"), ("Symmetry (Y)", "대칭 (Y)"), ("Tangent | Wrap", "탄젠트 | 랩"), - ("Tangent-space normals of the high definition meshes.", "고해상도 메시의 탄젠트 공간 노멀입니다."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "시간적 안티앨리어싱 (3D 뷰가 정지해 있을 때 품질을 높임)"), - ("Texture Set List", "텍스처 세트 목록"), + ("Texture Sets", "텍스처 세트"), ("Texture Set Settings", "텍스처 세트 설정"), ("Texture resolution", "텍스처 해상도"), ("Texture set channels", "텍스처 세트 채널"), - ("Texture set list", "텍스처 세트 목록"), ("Texture sets", "텍스처 세트"), ("TextureCraft had to close:", "TextureCraft를 종료해야 했습니다:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 메탈릭 러프니스"), @@ -866,7 +826,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Uniform value", "균일 값"), ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "브러시 알파로 사용합니다 (또는 뷰포트나 브러시 속성으로 드래그)"), - ("Use low poly mesh as high poly mesh", "로우 폴리 메시를 하이 폴리 메시로 사용"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), @@ -887,15 +846,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "휠 / Alt + 오른쪽 드래그"), ("White", "흰색"), - ("White where the surface faces the direction, black where it faces away.", "표면이 해당 방향을 향하면 흰색, 반대쪽을 향하면 검은색입니다."), ("Width", "너비"), ("Width (texels at 2K)", "폭 (2K 기준 텍셀)"), ("Window", "창"), ("Wood grain", "나뭇결"), ("Works in texture space, like the blur: it does not cross UV seams.", "블러와 마찬가지로 텍스처 공간에서 작동하므로 UV 경계를 넘지 않습니다."), - ("World space direction", "월드 공간 방향"), - ("World space normal", "월드 공간 노멀"), - ("World-space normals of the high poly (or the low poly).", "하이 폴리(또는 로우 폴리)의 월드 공간 노멀입니다."), + ("World Space Normal", "월드 공간 노멀"), ("Yellow / blue", "노랑 / 파랑"), ("Zoom", "확대/축소"), ("a missing layer", "누락된 레이어"), @@ -932,7 +888,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: 선택한 레이어 위에 추가합니다 (또는 레이어 스택이나 뷰포트로 드래그)", ), - ("{name} ({n} triangles)", "{name} (삼각형 {n}개)"), ("{name} copy", "{name} 사본"), ("{n} bits", "{n}비트"), ( @@ -943,25 +898,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (스케일 {scale}, 시드 {seed})"), ("Template name", "템플릿 이름"), ("Save current project as template", "현재 프로젝트를 템플릿으로 저장"), - ("Spread angle", "확산 각도"), ("Distribution", "분포"), ("Cosine", "코사인"), ("Uniform", "균일"), - ("Ignore backface", "뒷면 무시"), - ("Self occlusion", "자기 차폐"), - ("Only same mesh name", "같은 메시 이름만"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "벤트 노멀 광선은 앰비언트 오클루전의 차폐물 설정을 따릅니다."), - ("Sampling radius", "샘플링 반경"), - ("0 picks a radius from the output size.", "0이면 출력 크기에 따라 반경을 정합니다."), - ("Encoding", "인코딩"), - ("Signed (-1..1)", "부호 있음 (-1..1)"), - ("Positive (0..1)", "양수 (0..1)"), ("Normalization", "정규화"), - ("Bounding box", "바운딩 박스"), - ("Bounding sphere", "바운딩 스피어"), - ("Position normalized to the low poly's bounding box or sphere.", "로우 폴리의 바운딩 박스 또는 스피어로 정규화한 위치입니다."), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "고해상도 메시의 베이스 컬러(텍스처, 계수)와 버텍스 컬러입니다."), - ("White where the high poly covers the low poly, times its alpha.", "하이 폴리가 로우 폴리를 덮는 곳은 흰색이며, 알파가 곱해집니다."), // Settings › Interface: brightness and accent color. ("Brightness", "밝기"), ("Dark", "어둡게"), @@ -1008,12 +948,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "저장되지 않은 변경 사항"), ("Don't save", "저장 안 함"), ("Save the changes to {name} before closing?", "닫기 전에 {name}의 변경 사항을 저장할까요?"), - ("Skew correction", "스큐 보정"), - ("Paint skew in the 2D view", "2D 뷰에서 스큐 칠하기"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "2D 뷰에서 드래그하여 베이크 레이가 기본 노멀 쪽으로 향하는 위치를 칠합니다. 값 0으로 칠하면 지워집니다", - ), ("Radius", "반경"), ("Remove skew correction", "스큐 보정 제거"), ("Twill weave", "능직"), @@ -1033,4 +967,85 @@ pub const TABLE: &[(&str, &str)] = &[ "MaterialCraft에서 열었습니다. 변경 내용을 가져오려면 그곳에서 파일 > TextureCraft로 보내기를 사용하세요", ), ("Parameters change in the desktop app, with MaterialCraft installed", "매개변수는 MaterialCraft가 설치된 데스크톱 앱에서 바꿀 수 있습니다"), + ("Add High-Poly Meshes", "하이 폴리 메시 추가"), + ("All", "전체"), + ("Apply Diffusion", "확산 적용"), + ("Attenuation", "감쇠"), + ("Auto Tonemapping", "자동 톤 매핑"), + ("Average Normals", "노멀 평균화"), + ("BBox", "경계 상자"), + ("BSphere", "경계 구"), + ("Bake Maps", "맵 베이크"), + ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), + ("By Mesh Name", "메시 이름으로"), + ("Cage", "케이지"), + ("Cage Scene", "케이지 장면"), + ("Cage Type", "케이지 유형"), + ("Color Generator", "색상 생성기"), + ("Color Source", "색상 소스"), + ("Common Parameters", "공통 매개변수"), + ("Custom File", "사용자 지정 파일"), + ("Details", "세부 사항"), + ("Dilation Width", "확장 폭"), + ("Distance-Based", "거리 기반"), + ("Edge Contrast", "가장자리 대비"), + ("Edge Distance", "가장자리 거리"), + ("Edge Protection", "가장자리 보호"), + ("Enable Seams", "이음새 활성화"), + ("File ID", "파일 ID"), + ("Full Scene", "전체 장면"), + ("Generate from Mesh", "메시에서 생성"), + ("Generate from Normal Map", "노멀 맵에서 생성"), + ("Ground Plane", "바닥 평면"), + ("Ground Plane Offset", "바닥 평면 오프셋"), + ("High Poly Mesh Suffix", "하이 폴리 메시 접미사"), + ("High Poly Scene", "하이 폴리 장면"), + ("High-Poly Parameters", "하이 폴리 매개변수"), + ("Hue Shift", "색조 이동"), + ("Ignore Backface", "뒷면 무시"), + ("Ignore Backface Suffix", "뒷면 무시 접미사"), + ("Include in Bake", "베이크에 포함"), + ("Load Cage", "케이지 불러오기"), + ("Lock Output Size", "출력 크기 잠금"), + ("Low Poly Mesh Suffix", "로우 폴리 메시 접미사"), + ("Manual", "수동"), + ("Material Color", "재질 색상"), + ("Max Frontal Distance", "최대 전방 거리"), + ("Max Occluder Distance", "최대 차폐물 거리"), + ("Max Rear Distance", "최대 후방 거리"), + ("Mesh ID", "메시 ID"), + ("Method", "방식"), + ("Min Occluder Distance", "최소 차폐 거리"), + ("Never", "안 함"), + ("No High-Poly Meshes", "하이 폴리 메시 없음"), + ("Normalization Scale", "정규화 범위"), + ("Normalization Type", "정규화 유형"), + ("Only Same Mesh Name", "같은 메시 이름만"), + ("Output Size", "출력 크기"), + ("Paint Cage", "케이지 페인트"), + ("Paint Skew Correction", "기울기 보정 페인트"), + ("Per Material", "재질별"), + ("Random", "무작위"), + ("Relative to Bounding Box", "경계 상자 기준"), + ("Relative to Low Mesh", "로우 폴리 메시 기준"), + ("Relative to Min/Max", "최소/최대 기준"), + ("Relative to Ray Distances", "광선 거리 기준"), + ("Remove Cage", "케이지 제거"), + ("Remove Skew Correction", "스큐 보정 제거"), + ("Restore Defaults", "기본값 복원"), + ("Return to Painting Mode", "페인팅 모드로 돌아가기"), + ("Sampling Radius", "샘플링 반경"), + ("Scaling Divisor", "배율 나눗수"), + ("Seams Intensity", "이음새 강도"), + ("Secondary Rays", "보조 광선"), + ("Self Intersection", "자체 교차"), + ("Self Occlusion", "자기 차폐"), + ("Skew Correction", "스큐 보정"), + ("Smooth", "부드러움"), + ("Spread Angle", "확산 각도"), + ("Submesh", "하위 메시"), + ("Use Low Poly Mesh as High Poly Mesh", "로우 폴리 메시를 하이 폴리 메시로 사용"), + ("Value Bounds Max", "값 상한"), + ("Value Bounds Min", "값 하한"), + ("Vertex Color", "정점 색상"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 67b4697b..82a838a9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -47,7 +47,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "Adicionar filtro"), ("Add folder", "Adicionar pasta"), ("Add generator", "Adicionar gerador"), - ("Add high definition meshes", "Adicionar malhas de alta definição"), ("Add levels", "Adicionar níveis"), ("Add mask", "Adicionar máscara"), ("Add mask with color selection", "Adicionar máscara com seleção de cor"), @@ -83,7 +82,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "Também atribuído a {item} ({menu})"), ("Alt + LMB drag", "Alt + arrastar com botão esquerdo"), ("Always", "Sempre"), - ("Ambient occlusion", "Oclusão de ambiente"), + ("Ambient Occlusion", "Oclusão de ambiente"), ("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"), ("Amount", "Quantidade"), ("Anchor point", "Ponto de ancoragem"), @@ -99,7 +98,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), ("Apply", "Aplicar"), - ("Apply to all texture sets", "Aplicar a todos os conjuntos de texturas"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), @@ -108,7 +106,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "Salvamentos automáticos, materiais inteligentes, predefinições, modelos e layouts da interface vão para a pasta de dados. Uma nova pasta vale após reiniciar; os arquivos já salvos ficam onde estão.", ), - ("Average normals", "Normais médias"), ("Axis", "Eixo"), ("Back to painting", "Voltar à pintura"), ("Backface culling", "Descarte de faces traseiras"), @@ -118,8 +115,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Faça o bake dos mapas de malha (F8) para geradores baseados em curvatura, AO e espessura.", ), - ("Bake selected textures ({n})", "Fazer bake das texturas selecionadas ({n})"), - ("Bake with \"Bake selected textures\"", "Faça o bake com \"Fazer bake das texturas selecionadas\""), ("Baked Lighting", "Iluminação pré-calculada"), ("Baking", "Bake"), ("Base color", "Cor base"), @@ -130,7 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "Cor base, Metálico, Rugosidade e Nível especular."), ("Based on each texture set's size", "Com base no tamanho de cada conjunto de texturas"), ("Basic settings", "Configurações básicas"), - ("Bent normals", "Normais curvadas"), + ("Bent Normals", "Normais curvadas"), ("Bevel", "Chanfro"), ("Black", "Preto"), ("Blend sharpness", "Nitidez da mistura"), @@ -148,7 +143,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "Embutido (somente leitura): duplique-o para editar"), ("Built-in templates are read-only: duplicate one to edit it", "Os modelos embutidos são somente leitura: duplique um para editá-lo"), ("Built-in: {mesh}", "Embutida: {mesh}"), - ("By mesh name", "Por nome da malha"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), ("Camera settings", "Configurações da câmera"), @@ -180,7 +174,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "Equilíbrio de cores"), ("Color burn", "Superexposição de cor"), ("Color dodge", "Subexposição de cor"), - ("Color map", "Mapa de cor"), ( "Color of the light that travels under the surface (each channel goes as far as its value)", "Cor da luz que viaja sob a superfície (cada canal vai tão longe quanto seu valor)", @@ -194,7 +187,6 @@ pub const TABLE: &[(&str, &str)] = &[ "As cores são lidas como cinza. Adicione um efeito de níveis ou desfoque acima para ajustar o resultado.", ), ("Combine with the layer's height", "Combinar com a altura da camada"), - ("Common parameters", "Parâmetros comuns"), ("Compare mask", "Máscara de comparação"), ("Compositing", "Composição"), ("Constant", "Constante"), @@ -207,7 +199,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "Copiar de"), ("Copy layer(s)", "Copiar camada(s)"), ("Copy the selected layer alone (its empty parts copy nothing)", "Copiar apenas a camada selecionada (suas partes vazias não copiam nada)"), - ("Copy these bake settings to every texture set", "Copiar estas configurações de bake para todos os conjuntos de texturas"), ("Copy to all texture sets", "Copiar para todos os conjuntos de texturas"), ("Copy what the texture set shows", "Copiar o que o conjunto de texturas exibe"), ("Couldn't encode the render", "Não foi possível codificar a renderização"), @@ -258,8 +249,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "Dilatação + cor de fundo padrão"), ("Dilation + transparent", "Dilatação + transparente"), ("Dilation infinite", "Dilatação infinita"), - ("Dilation width", "Largura da dilatação"), - ("Direction {axis}", "Direção {axis}"), ("DirectX normal map", "Mapa normal DirectX"), ("Dirt", "Sujeira"), ("Disable", "Desativado"), @@ -363,11 +352,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Para todo o projeto: como as imagens de mapa normal usadas como mapas de malha são lidas (atribua-as de novo após uma mudança), e o padrão para exportação", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "Livre e de código aberto (MIT OR Apache-2.0), escrito em Rust."), - ("From normal map", "Do mapa normal"), - ( - "From normal map: curvature of the baked normal map's detail instead of the mesh.", - "Do mapa normal: curvatura dos detalhes do mapa normal com bake em vez da malha.", - ), ("From template", "Do modelo"), ("From template / project", "Do modelo / projeto"), ("Full", "Completa"), @@ -407,12 +391,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "Ajuda"), ("Hide UI", "Ocultar interface"), ("High", "Alto"), - ("High definition meshes", "Malhas de alta definição"), - ( - "High poly height between the max rear (black) and max frontal (white) distances.", - "Altura do high poly entre as distâncias máxima traseira (preto) e máxima frontal (branco).", - ), - ("High poly mesh suffix", "Sufixo da malha high poly"), ("High poly: {name}", "High poly: {name}"), ("Highlights", "Realces"), ("Histogram Range", "Intervalo do histograma"), @@ -497,11 +475,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "Luz linear"), ("List of exports", "Lista de exportações"), ("Load UI Layout", "Carregar layout da interface"), - ("Load a cage (the low poly, inflated)", "Carregar uma cage (o low poly, inflado)"), ("Loaded UI layout {path}", "Layout da interface carregado de {path}"), ("Log", "Log"), ("Low", "Baixo"), - ("Low poly mesh suffix", "Sufixo da malha low poly"), ("Luminosity", "Luminosidade"), ("MMB drag / Alt + MMB", "Arrastar com botão do meio / Alt + botão do meio"), ("Made by the ArtCraft team and community.", "Feito pela equipe e pela comunidade ArtCraft."), @@ -515,17 +491,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "MatFinish Martelado"), ("MatFinish Raw", "MatFinish Bruto"), ("MatFinish Sanded", "MatFinish Lixado"), - ("Match", "Correspondência"), ("Material", "Material"), ("Material ball", "Esfera de material"), ("Material finish", "Acabamento de material"), ("Materials", "Materiais"), - ("Max frontal distance", "Distância frontal máxima"), - ("Max occluder distance", "Distância máxima do oclusor"), - ("Max rear distance", "Distância traseira máxima"), ("Maximum", "Máximo"), ("Mesh fill", "Preenchimento de malha"), - ("Mesh map bakers", "Bakers de mapas de malha"), ("Mesh map: {map}", "Mapa de malha: {map}"), ("Mesh maps", "Mapas de malha"), ("Mesh maps baked", "Bake dos mapas de malha concluído"), @@ -564,7 +535,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "Quantidade de ruído"), ("Noise scale", "Escala do ruído"), ("None", "Nenhum"), - ("None: the low poly is its own high poly.", "Nenhuma: o low poly é o seu próprio high poly."), ("Normal", "Normal"), ("Normal DirectX", "Normal DirectX"), ("Normal Invert", "Inverter normal"), @@ -596,7 +566,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Desloca as texturas pelo canal de altura, com a intensidade de altura para normal", ), ("On", "Ligado"), - ("One color per mesh part.", "Uma cor por parte da malha."), ("Opacity", "Opacidade"), ("Open sample project...", "Abrir projeto de exemplo..."), ("Open...", "Abrir..."), @@ -610,7 +579,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "Pasta de saída"), ("Output high", "Saída alta"), ("Output low", "Saída baixa"), - ("Output size", "Tamanho de saída"), ("Output template", "Modelo de saída"), ("Output templates", "Modelos de saída"), ("Overlay", "Sobrepor"), @@ -687,7 +655,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "Refazer"), ("Reimport mesh", "Reimportar malha"), - ("Relative to the bounding box diagonal.", "Relativo à diagonal da caixa delimitadora."), ("Remove", "Remover"), ("Remove channel", "Remover canal"), ("Remove effect", "Remover efeito"), @@ -696,7 +663,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "Remover camada(s)"), ("Remove mask", "Remover máscara"), ("Remove resource", "Remover recurso"), - ("Remove the cage", "Remover a cage"), ("Remove the path (Esc)", "Remover o caminho (Esc)"), ("Remove the shortcut", "Remover o atalho"), ("Remove this output", "Remover esta saída"), @@ -722,13 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "Redefinir para {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), - ("Return to painting mode", "Voltar ao modo de pintura"), ("Return to this step", "Voltar a esta etapa"), - ("Auto-rebake", "Refazer bake automaticamente"), - ( - "Bake this map again by itself when its bake settings, the low poly or the high polys change", - "Refaz o bake deste mapa automaticamente quando as configurações de bake, a malha low poly ou as high poly mudam", - ), ("Right-click a layer > Create smart material", "Clique com o botão direito em uma camada > Criar material inteligente"), ("Rotation", "Rotação"), ("Rotation (degrees)", "Rotação (graus)"), @@ -758,7 +718,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "Captura de tela da viewport"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), - ("Secondary rays", "Raios secundários"), ("Seed", "Semente"), ("Select a layer", "Selecione uma camada"), ("Select an output template", "Selecione um modelo de saída"), @@ -826,13 +785,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "Simetria (X)"), ("Symmetry (Y)", "Simetria (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), - ("Tangent-space normals of the high definition meshes.", "Normais em espaço tangente das malhas de alta definição."), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antisserrilhamento temporal (refina a vista 3D enquanto está parada)"), - ("Texture Set List", "Lista de conjuntos de texturas"), + ("Texture Sets", "Conjuntos de texturas"), ("Texture Set Settings", "Configurações do conjunto de texturas"), ("Texture resolution", "Resolução das texturas"), ("Texture set channels", "Canais do conjunto de texturas"), - ("Texture set list", "Lista de conjuntos de texturas"), ("Texture sets", "Conjuntos de texturas"), ("TextureCraft had to close:", "O TextureCraft precisou ser fechado:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - Metálico Rugosidade"), @@ -887,7 +844,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Use as the brush alpha (or drag it onto the viewport or brush properties)", "Usar como alpha do pincel (ou arraste-o para a viewport ou para as propriedades do pincel)", ), - ("Use low poly mesh as high poly mesh", "Usar a malha low poly como malha high poly"), ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), ("Value", "Valor"), ("Version {version}", "Versão {version}"), @@ -908,18 +864,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "Roda do mouse / Alt + arrastar com botão direito"), ("White", "Branco"), - ( - "White where the surface faces the direction, black where it faces away.", - "Branco onde a superfície está voltada para a direção, preto onde está voltada para o lado oposto.", - ), ("Width", "Largura"), ("Width (texels at 2K)", "Largura (texels em 2K)"), ("Window", "Janela"), ("Wood grain", "Veio de madeira"), ("Works in texture space, like the blur: it does not cross UV seams.", "Funciona no espaço de textura, como o desfoque: não atravessa costuras de UV."), - ("World space direction", "Direção no espaço do mundo"), - ("World space normal", "Normal no espaço do mundo"), - ("World-space normals of the high poly (or the low poly).", "Normais no espaço do mundo do high poly (ou do low poly)."), + ("World Space Normal", "Normal no espaço do mundo"), ("Yellow / blue", "Amarelo / azul"), ("Zoom", "Zoom"), ("a missing layer", "uma camada ausente"), @@ -956,7 +906,6 @@ pub const TABLE: &[(&str, &str)] = &[ "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}: adicionar acima da camada selecionada (ou arraste-o para a pilha de camadas ou para a viewport)", ), - ("{name} ({n} triangles)", "{name} ({n} triângulos)"), ("{name} copy", "Cópia de {name}"), ("{n} bits", "{n} bits"), ( @@ -967,31 +916,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern} (escala {scale}, semente {seed})"), ("Template name", "Nome do modelo"), ("Save current project as template", "Salvar o projeto atual como modelo"), - ("Spread angle", "Ângulo de dispersão"), ("Distribution", "Distribuição"), ("Cosine", "Cosseno"), ("Uniform", "Uniforme"), - ("Ignore backface", "Ignorar faces traseiras"), - ("Self occlusion", "Autooclusão"), - ("Only same mesh name", "Somente o mesmo nome de malha"), - ( - "Bent normal rays follow the ambient occlusion's occluder settings.", - "Os raios das normais curvadas seguem os ajustes de oclusores da oclusão de ambiente.", - ), - ("Sampling radius", "Raio de amostragem"), - ("0 picks a radius from the output size.", "0 escolhe um raio pelo tamanho de saída."), - ("Encoding", "Codificação"), - ("Signed (-1..1)", "Com sinal (-1..1)"), - ("Positive (0..1)", "Positivo (0..1)"), ("Normalization", "Normalização"), - ("Bounding box", "Caixa delimitadora"), - ("Bounding sphere", "Esfera delimitadora"), - ("Position normalized to the low poly's bounding box or sphere.", "Posição normalizada pela caixa ou esfera delimitadora do low poly."), - ( - "Base colors (textures, factors) and vertex colors of the high definition meshes.", - "Cores base (texturas, fatores) e cores de vértice das malhas de alta definição.", - ), - ("White where the high poly covers the low poly, times its alpha.", "Branco onde o high poly cobre o low poly, multiplicado pelo seu alfa."), // Settings › Interface: brightness and accent color. ("Brightness", "Brilho"), ("Dark", "Escuro"), @@ -1038,12 +966,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "Alterações não salvas"), ("Don't save", "Não salvar"), ("Save the changes to {name} before closing?", "Salvar as alterações em {name} antes de fechar?"), - ("Skew correction", "Correção de inclinação"), - ("Paint skew in the 2D view", "Pintar a inclinação na vista 2D"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "Arraste na vista 2D para pintar onde os raios do bake se voltam para a normal base; pinte com valor 0 para apagar", - ), ("Radius", "Raio"), ("Remove skew correction", "Remover a correção de inclinação"), ("Twill weave", "Tecido sarja"), @@ -1063,4 +985,85 @@ pub const TABLE: &[(&str, &str)] = &[ "Aberto no MaterialCraft: use lá Arquivo > Enviar para o TextureCraft para trazer suas alterações", ), ("Parameters change in the desktop app, with MaterialCraft installed", "Os parâmetros mudam no app para desktop, com o MaterialCraft instalado"), + ("Add High-Poly Meshes", "Adicionar malhas de alta resolução"), + ("All", "Todos"), + ("Apply Diffusion", "Aplicar difusão"), + ("Attenuation", "Atenuação"), + ("Auto Tonemapping", "Mapeamento tonal automático"), + ("Average Normals", "Normais médias"), + ("BBox", "Caixa delimitadora"), + ("BSphere", "Esfera delimitadora"), + ("Bake Maps", "Bake de mapas"), + ("Bake Selected Textures ({n})", "Fazer bake das texturas selecionadas ({n})"), + ("By Mesh Name", "Por nome da malha"), + ("Cage", "Gaiola"), + ("Cage Scene", "Cena da gaiola"), + ("Cage Type", "Tipo de gaiola"), + ("Color Generator", "Gerador de cores"), + ("Color Source", "Origem da cor"), + ("Common Parameters", "Parâmetros comuns"), + ("Custom File", "Arquivo personalizado"), + ("Details", "Detalhes"), + ("Dilation Width", "Largura da dilatação"), + ("Distance-Based", "Baseada em distância"), + ("Edge Contrast", "Contraste das arestas"), + ("Edge Distance", "Distância das arestas"), + ("Edge Protection", "Proteção das arestas"), + ("Enable Seams", "Ativar costuras"), + ("File ID", "ID do arquivo"), + ("Full Scene", "Cena inteira"), + ("Generate from Mesh", "Gerar a partir da malha"), + ("Generate from Normal Map", "Gerar a partir do mapa de normais"), + ("Ground Plane", "Plano do solo"), + ("Ground Plane Offset", "Deslocamento do solo"), + ("High Poly Mesh Suffix", "Sufixo da malha high poly"), + ("High Poly Scene", "Cena de alta resolução"), + ("High-Poly Parameters", "Parâmetros de alta resolução"), + ("Hue Shift", "Deslocamento de matiz"), + ("Ignore Backface", "Ignorar faces traseiras"), + ("Ignore Backface Suffix", "Sufixo para ignorar faces traseiras"), + ("Include in Bake", "Incluir no bake"), + ("Load Cage", "Carregar gaiola"), + ("Lock Output Size", "Bloquear tamanho de saída"), + ("Low Poly Mesh Suffix", "Sufixo da malha low poly"), + ("Manual", "Manual"), + ("Material Color", "Cor do material"), + ("Max Frontal Distance", "Distância frontal máxima"), + ("Max Occluder Distance", "Distância máxima do oclusor"), + ("Max Rear Distance", "Distância traseira máxima"), + ("Mesh ID", "ID da malha"), + ("Method", "Método"), + ("Min Occluder Distance", "Distância mínima do oclusor"), + ("Never", "Nunca"), + ("No High-Poly Meshes", "Nenhuma malha de alta resolução"), + ("Normalization Scale", "Escala de normalização"), + ("Normalization Type", "Tipo de normalização"), + ("Only Same Mesh Name", "Somente o mesmo nome de malha"), + ("Output Size", "Tamanho de saída"), + ("Paint Cage", "Pintar gaiola"), + ("Paint Skew Correction", "Pintar correção de inclinação"), + ("Per Material", "Por material"), + ("Random", "Aleatório"), + ("Relative to Bounding Box", "Relativo à caixa delimitadora"), + ("Relative to Low Mesh", "Relativo à malha de baixa resolução"), + ("Relative to Min/Max", "Relativo ao mínimo/máximo"), + ("Relative to Ray Distances", "Relativo às distâncias dos raios"), + ("Remove Cage", "Remover gaiola"), + ("Remove Skew Correction", "Remover a correção de inclinação"), + ("Restore Defaults", "Restaurar padrões"), + ("Return to Painting Mode", "Voltar ao modo de pintura"), + ("Sampling Radius", "Raio de amostragem"), + ("Scaling Divisor", "Divisor de escala"), + ("Seams Intensity", "Intensidade das costuras"), + ("Secondary Rays", "Raios secundários"), + ("Self Intersection", "Autointerseção"), + ("Self Occlusion", "Autooclusão"), + ("Skew Correction", "Correção de inclinação"), + ("Smooth", "Suave"), + ("Spread Angle", "Ângulo de dispersão"), + ("Submesh", "Submalha"), + ("Use Low Poly Mesh as High Poly Mesh", "Usar a malha low poly como malha high poly"), + ("Value Bounds Max", "Limite máximo"), + ("Value Bounds Min", "Limite mínimo"), + ("Vertex Color", "Cor do vértice"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 73e05b93..20c9e258 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -38,7 +38,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add filter", "添加滤镜"), ("Add folder", "添加文件夹"), ("Add generator", "添加生成器"), - ("Add high definition meshes", "添加高精度网格"), ("Add levels", "添加色阶"), ("Add mask", "添加遮罩"), ("Add mask with color selection", "添加颜色选择遮罩"), @@ -65,7 +64,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Also bound to {item} ({menu})", "同时绑定到 {item}({menu})"), ("Alt + LMB drag", "Alt + 左键拖动"), ("Always", "始终"), - ("Ambient occlusion", "环境光遮蔽"), + ("Ambient Occlusion", "环境光遮蔽"), ("Ambient occlusion intensity", "环境光遮蔽强度"), ("Amount", "数量"), ("Anchor point", "锚点"), @@ -81,7 +80,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), ("Apply", "应用"), - ("Apply to all texture sets", "应用到所有纹理集"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), @@ -90,15 +88,12 @@ pub const TABLE: &[(&str, &str)] = &[ "Autosaves, smart materials, presets, templates and UI layouts go to the data folder. A new folder applies on restart; files already saved stay where they are.", "自动保存、智能材质、预设、模板和界面布局都保存在数据文件夹中。新文件夹在重启后生效;已保存的文件保留在原处。", ), - ("Average normals", "平均法线"), ("Axis", "轴"), ("Back to painting", "返回绘画"), ("Backface culling", "背面剔除"), ("Bake Mesh Maps", "烘焙网格贴图"), ("Bake mesh maps", "烘焙网格贴图"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"), - ("Bake selected textures ({n})", "烘焙所选纹理({n})"), - ("Bake with \"Bake selected textures\"", "使用“烘焙所选纹理”进行烘焙"), ("Baked Lighting", "烘焙光照"), ("Baking", "烘焙"), ("Base color", "基础色"), @@ -109,7 +104,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Base color, Metallic, Roughness and Specular level.", "基础色、金属度、粗糙度和高光强度。"), ("Based on each texture set's size", "基于各纹理集的尺寸"), ("Basic settings", "基本设置"), - ("Bent normals", "弯曲法线"), + ("Bent Normals", "弯曲法线"), ("Bevel", "斜角"), ("Black", "黑色"), ("Blend sharpness", "混合锐度"), @@ -127,7 +122,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in (read-only): duplicate it to edit", "内置(只读):创建副本后即可编辑"), ("Built-in templates are read-only: duplicate one to edit it", "内置模板为只读:创建副本后即可编辑"), ("Built-in: {mesh}", "内置:{mesh}"), - ("By mesh name", "按网格名称"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), ("Camera settings", "相机设置"), @@ -159,7 +153,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Color Balance", "色彩平衡"), ("Color burn", "颜色加深"), ("Color dodge", "颜色减淡"), - ("Color map", "颜色贴图"), ("Color of the light that travels under the surface (each channel goes as far as its value)", "在表面下传播的光的颜色(各通道的传播距离取决于其值)"), ("Color picker", "拾色器"), ("Color selection", "颜色选择"), @@ -167,7 +160,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Colors near the first shift towards the second, keeping their shading.", "接近第一种颜色的颜色会在保留明暗的同时转向第二种颜色。"), ("Colors read as gray. Add a levels or blur effect above to shape the result.", "颜色按灰度读取。可在上方添加色阶或模糊效果来调整结果。"), ("Combine with the layer's height", "与图层高度合并"), - ("Common parameters", "通用参数"), ("Compare mask", "比较遮罩"), ("Compositing", "合成"), ("Constant", "常量"), @@ -180,7 +172,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Copy from", "复制自"), ("Copy layer(s)", "复制图层"), ("Copy the selected layer alone (its empty parts copy nothing)", "仅复制所选图层(其空白部分不复制任何内容)"), - ("Copy these bake settings to every texture set", "将这些烘焙设置复制到所有纹理集"), ("Copy to all texture sets", "复制到所有纹理集"), ("Copy what the texture set shows", "复制纹理集显示的内容"), ("Couldn't encode the render", "无法编码渲染结果"), @@ -228,8 +219,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Dilation + default background color", "扩张 + 默认背景色"), ("Dilation + transparent", "扩张 + 透明"), ("Dilation infinite", "无限扩张"), - ("Dilation width", "扩张宽度"), - ("Direction {axis}", "方向 {axis}"), ("DirectX normal map", "DirectX 法线贴图"), ("Dirt", "污垢"), ("Disable", "禁用"), @@ -318,8 +307,6 @@ pub const TABLE: &[(&str, &str)] = &[ "整个项目:设为网格贴图的法线贴图图像的读取方式(更改后请重新设置),以及导出的默认值", ), ("Free and open source (MIT OR Apache-2.0), written in Rust.", "免费开源(MIT OR Apache-2.0),使用 Rust 编写。"), - ("From normal map", "基于法线贴图"), - ("From normal map: curvature of the baked normal map's detail instead of the mesh.", "基于法线贴图:使用烘焙法线贴图细节的曲率,而非网格的曲率。"), ("From template", "基于模板"), ("From template / project", "基于模板 / 项目"), ("Full", "完整"), @@ -359,9 +346,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Help", "帮助"), ("Hide UI", "隐藏界面"), ("High", "高"), - ("High definition meshes", "高精度网格"), - ("High poly height between the max rear (black) and max frontal (white) distances.", "高模高度,介于最大后向(黑)与最大前向(白)距离之间。"), - ("High poly mesh suffix", "高模网格后缀"), ("High poly: {name}", "高模:{name}"), ("Highlights", "高光"), ("Histogram Range", "直方图范围"), @@ -440,11 +424,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Linear light", "线性光"), ("List of exports", "导出列表"), ("Load UI Layout", "加载界面布局"), - ("Load a cage (the low poly, inflated)", "加载笼体(膨胀后的低模)"), ("Loaded UI layout {path}", "已加载界面布局 {path}"), ("Log", "日志"), ("Low", "低"), - ("Low poly mesh suffix", "低模网格后缀"), ("Luminosity", "亮度"), ("MMB drag / Alt + MMB", "中键拖动 / Alt + 中键"), ("Made by the ArtCraft team and community.", "由 ArtCraft 团队和社区打造。"), @@ -458,17 +440,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("MatFinish Hammered", "表面处理:锤纹"), ("MatFinish Raw", "表面处理:原始"), ("MatFinish Sanded", "表面处理:砂磨"), - ("Match", "匹配"), ("Material", "材质"), ("Material ball", "材质球"), ("Material finish", "材质表面处理"), ("Materials", "材质"), - ("Max frontal distance", "最大前向距离"), - ("Max occluder distance", "最大遮挡物距离"), - ("Max rear distance", "最大后向距离"), ("Maximum", "最大值"), ("Mesh fill", "网格填充"), - ("Mesh map bakers", "网格贴图烘焙器"), ("Mesh map: {map}", "网格贴图:{map}"), ("Mesh maps", "网格贴图"), ("Mesh maps baked", "网格贴图已烘焙"), @@ -504,7 +481,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Noise amount", "噪波量"), ("Noise scale", "噪波缩放"), ("None", "无"), - ("None: the low poly is its own high poly.", "无:低模即为其自身的高模。"), ("Normal", "法线"), ("Normal DirectX", "法线 DirectX"), ("Normal Invert", "法线反转"), @@ -533,7 +509,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Offset {axis}", "偏移 {axis}"), ("Offsets the textures by the height channel, at the height to normal strength", "按高度通道偏移纹理,偏移量取决于高度转法线强度"), ("On", "开"), - ("One color per mesh part.", "每个网格部件一种颜色。"), ("Opacity", "不透明度"), ("Open sample project...", "打开示例项目..."), ("Open...", "打开..."), @@ -547,7 +522,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Output directory", "输出目录"), ("Output high", "输出高"), ("Output low", "输出低"), - ("Output size", "输出尺寸"), ("Output template", "输出模板"), ("Output templates", "输出模板"), ("Overlay", "叠加"), @@ -618,7 +592,6 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Redo", "重做"), ("Reimport mesh", "重新导入网格"), - ("Relative to the bounding box diagonal.", "相对于包围盒对角线。"), ("Remove", "移除"), ("Remove channel", "移除通道"), ("Remove effect", "移除效果"), @@ -627,7 +600,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer(s)", "移除图层"), ("Remove mask", "移除遮罩"), ("Remove resource", "移除资源"), - ("Remove the cage", "移除笼体"), ("Remove the path (Esc)", "移除路径(Esc)"), ("Remove the shortcut", "移除快捷键"), ("Remove this output", "移除此输出"), @@ -650,10 +622,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Reset to {shortcut}", "重置为 {shortcut}"), ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), - ("Return to painting mode", "返回绘画模式"), ("Return to this step", "返回到此步骤"), - ("Auto-rebake", "自动重新烘焙"), - ("Bake this map again by itself when its bake settings, the low poly or the high polys change", "当烘焙设置、低模或高模发生变化时,自动重新烘焙此贴图"), ("Right-click a layer > Create smart material", "右键单击图层 > 创建智能材质"), ("Rotation", "旋转"), ("Rotation (degrees)", "旋转(度)"), @@ -683,7 +652,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Screenshot of the viewport", "视口截图"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), - ("Secondary rays", "二次光线"), ("Seed", "随机种子"), ("Select a layer", "选择图层"), ("Select an output template", "选择输出模板"), @@ -751,13 +719,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Symmetry (X)", "对称(X)"), ("Symmetry (Y)", "对称(Y)"), ("Tangent | Wrap", "切线 | 包裹"), - ("Tangent-space normals of the high definition meshes.", "高精度网格的切线空间法线。"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "时间抗锯齿(在 3D 视图静止时逐步细化)"), - ("Texture Set List", "纹理集列表"), + ("Texture Sets", "纹理集"), ("Texture Set Settings", "纹理集设置"), ("Texture resolution", "纹理分辨率"), ("Texture set channels", "纹理集通道"), - ("Texture set list", "纹理集列表"), ("Texture sets", "纹理集"), ("TextureCraft had to close:", "TextureCraft 不得不关闭:"), ("TextureCraft PBR - Metallic Roughness", "TextureCraft PBR - 金属度/粗糙度"), @@ -809,7 +775,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Uniform value", "统一值"), ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "用作笔刷 Alpha(或将其拖到视口或笔刷属性上)"), - ("Use low poly mesh as high poly mesh", "将低模用作高模"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), @@ -830,15 +795,12 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Wheel / Alt + RMB drag", "滚轮 / Alt + 右键拖动"), ("White", "白色"), - ("White where the surface faces the direction, black where it faces away.", "表面朝向该方向处为白色,背向处为黑色。"), ("Width", "宽度"), ("Width (texels at 2K)", "宽度(2K 下的纹素数)"), ("Window", "窗口"), ("Wood grain", "木纹"), ("Works in texture space, like the blur: it does not cross UV seams.", "在纹理空间中工作,与模糊相同:不会跨越 UV 接缝。"), - ("World space direction", "世界空间方向"), - ("World space normal", "世界空间法线"), - ("World-space normals of the high poly (or the low poly).", "高模(或低模)的世界空间法线。"), + ("World Space Normal", "世界空间法线"), ("Yellow / blue", "黄色 / 蓝色"), ("Zoom", "缩放"), ("a missing layer", "缺失的图层"), @@ -872,7 +834,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("transm", "透射"), ("{action} (undone)", "{action}(已撤销)"), ("{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", "{file}:添加到所选图层上方(或将其拖入图层堆栈或视口)"), - ("{name} ({n} triangles)", "{name}({n} 个三角形)"), ("{name} copy", "{name} 副本"), ("{n} bits", "{n} 位"), ( @@ -883,25 +844,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("{pattern} (scale {scale}, seed {seed})", "{pattern}(缩放 {scale},种子 {seed})"), ("Template name", "模板名称"), ("Save current project as template", "将当前项目保存为模板"), - ("Spread angle", "扩散角度"), ("Distribution", "分布"), ("Cosine", "余弦"), ("Uniform", "均匀"), - ("Ignore backface", "忽略背面"), - ("Self occlusion", "自遮蔽"), - ("Only same mesh name", "仅相同网格名称"), - ("Bent normal rays follow the ambient occlusion's occluder settings.", "弯曲法线的光线沿用环境光遮蔽的遮挡物设置。"), - ("Sampling radius", "采样半径"), - ("0 picks a radius from the output size.", "0 表示根据输出尺寸选择半径。"), - ("Encoding", "编码"), - ("Signed (-1..1)", "有符号 (-1..1)"), - ("Positive (0..1)", "正值 (0..1)"), ("Normalization", "归一化"), - ("Bounding box", "包围盒"), - ("Bounding sphere", "包围球"), - ("Position normalized to the low poly's bounding box or sphere.", "按低模包围盒或包围球归一化的位置。"), - ("Base colors (textures, factors) and vertex colors of the high definition meshes.", "高精度网格的基础颜色(纹理、系数)和顶点颜色。"), - ("White where the high poly covers the low poly, times its alpha.", "高模覆盖低模处为白色,再乘以其 Alpha。"), // Settings › Interface: brightness and accent color. ("Brightness", "亮度"), ("Dark", "深色"), @@ -948,12 +894,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Unsaved changes", "未保存的更改"), ("Don't save", "不保存"), ("Save the changes to {name} before closing?", "关闭前是否保存对 {name} 的更改?"), - ("Skew correction", "倾斜校正"), - ("Paint skew in the 2D view", "在 2D 视图中绘制倾斜"), - ( - "Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase", - "在 2D 视图中拖动,绘制烘焙射线转向基础法线的位置;以值 0 绘制可擦除", - ), ("Radius", "半径"), ("Remove skew correction", "移除倾斜校正"), ("Twill weave", "斜纹织物"), @@ -973,4 +913,85 @@ pub const TABLE: &[(&str, &str)] = &[ "已在 MaterialCraft 中打开:在其中使用“文件 > 发送到 TextureCraft”即可带回更改", ), ("Parameters change in the desktop app, with MaterialCraft installed", "参数可在安装了 MaterialCraft 的桌面版中修改"), + ("Add High-Poly Meshes", "添加高模网格"), + ("All", "全部"), + ("Apply Diffusion", "应用扩散"), + ("Attenuation", "衰减"), + ("Auto Tonemapping", "自动色调映射"), + ("Average Normals", "平均法线"), + ("BBox", "包围盒"), + ("BSphere", "包围球"), + ("Bake Maps", "烘焙贴图"), + ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), + ("By Mesh Name", "按网格名称"), + ("Cage", "笼形"), + ("Cage Scene", "笼形场景"), + ("Cage Type", "笼形类型"), + ("Color Generator", "颜色生成器"), + ("Color Source", "颜色来源"), + ("Common Parameters", "通用参数"), + ("Custom File", "自定义文件"), + ("Details", "细节"), + ("Dilation Width", "扩张宽度"), + ("Distance-Based", "基于距离"), + ("Edge Contrast", "边缘对比度"), + ("Edge Distance", "边缘距离"), + ("Edge Protection", "边缘保护"), + ("Enable Seams", "启用接缝"), + ("File ID", "文件 ID"), + ("Full Scene", "整个场景"), + ("Generate from Mesh", "从网格生成"), + ("Generate from Normal Map", "从法线贴图生成"), + ("Ground Plane", "地平面"), + ("Ground Plane Offset", "地平面偏移"), + ("High Poly Mesh Suffix", "高模网格后缀"), + ("High Poly Scene", "高模场景"), + ("High-Poly Parameters", "高模参数"), + ("Hue Shift", "色相偏移"), + ("Ignore Backface", "忽略背面"), + ("Ignore Backface Suffix", "忽略背面后缀"), + ("Include in Bake", "包含在烘焙中"), + ("Load Cage", "加载笼形"), + ("Lock Output Size", "锁定输出尺寸"), + ("Low Poly Mesh Suffix", "低模网格后缀"), + ("Manual", "手动"), + ("Material Color", "材质颜色"), + ("Max Frontal Distance", "最大前向距离"), + ("Max Occluder Distance", "最大遮挡物距离"), + ("Max Rear Distance", "最大后向距离"), + ("Mesh ID", "网格 ID"), + ("Method", "方法"), + ("Min Occluder Distance", "最小遮挡距离"), + ("Never", "从不"), + ("No High-Poly Meshes", "无高模网格"), + ("Normalization Scale", "归一化范围"), + ("Normalization Type", "归一化类型"), + ("Only Same Mesh Name", "仅相同网格名称"), + ("Output Size", "输出尺寸"), + ("Paint Cage", "绘制笼形"), + ("Paint Skew Correction", "绘制倾斜校正"), + ("Per Material", "按材质"), + ("Random", "随机"), + ("Relative to Bounding Box", "相对于包围盒"), + ("Relative to Low Mesh", "相对于低模网格"), + ("Relative to Min/Max", "相对于最小值/最大值"), + ("Relative to Ray Distances", "相对于射线距离"), + ("Remove Cage", "移除笼形"), + ("Remove Skew Correction", "移除倾斜校正"), + ("Restore Defaults", "恢复默认值"), + ("Return to Painting Mode", "返回绘画模式"), + ("Sampling Radius", "采样半径"), + ("Scaling Divisor", "缩放除数"), + ("Seams Intensity", "接缝强度"), + ("Secondary Rays", "二次光线"), + ("Self Intersection", "自相交"), + ("Self Occlusion", "自遮蔽"), + ("Skew Correction", "倾斜校正"), + ("Smooth", "平滑"), + ("Spread Angle", "扩散角度"), + ("Submesh", "子网格"), + ("Use Low Poly Mesh as High Poly Mesh", "将低模用作高模"), + ("Value Bounds Max", "值上限"), + ("Value Bounds Min", "值下限"), + ("Vertex Color", "顶点颜色"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1d0841dc..8bfc66c9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_mode; pub mod control; pub mod dock; pub mod docking; @@ -51,8 +52,6 @@ pub struct BakeJob { pub queue: Vec, pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, pub total: usize, - /// Bake only this map (an Auto-rebake); None bakes every ticked map. - pub only: Option, } /// A MaterialCraft material re-cooking on a worker thread (one per layer at a time). @@ -209,7 +208,7 @@ impl TextureCraftApp { return; } let total = sets.len(); - self.bake = Some(BakeJob { queue: sets, current: None, total, only: None }); + self.bake = Some(BakeJob { queue: sets, current: None, total }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -263,21 +262,20 @@ impl TextureCraftApp { fn poll_bake(&mut self, ctx: &egui::Context) { let Some(job) = self.bake.as_mut() else { return }; + ctx.request_repaint_after(std::time::Duration::from_millis(50)); - if let Some((ts, _, rx)) = &job.current { - match rx.try_recv() { - Ok(Ok(out)) => { - let ts = *ts; + if let Some((set_index, _, receiver)) = &job.current { + match receiver.try_recv() { + Ok(Ok(output)) => { + let set_index = *set_index; job.current = None; - if let Err(e) = self.session.apply_bake(ts, out) { - self.session.bake_abandoned([ts]); - self.toast(e.to_string(), true); + if let Err(error) = self.session.apply_bake(set_index, output) { + self.toast(error.to_string(), true); } } - Ok(Err(e)) => { - let msg = e.to_string(); + Ok(Err(error)) => { self.cancel_bake(); - self.toast(msg, true); + self.toast(error.to_string(), true); return; } Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -289,57 +287,33 @@ impl TextureCraftApp { } } let Some(job) = self.bake.as_mut() else { return }; - if job.current.is_none() { - if job.queue.is_empty() { - self.bake = None; - self.toast(i18n::tr("Mesh maps baked"), false); - return; - } - let (ts, only) = (job.queue.remove(0), job.only); - self.session.begin_bake(ts); - match self.session.bake_task_for(ts, only) { - Ok(task) => { - let progress = Arc::new(Progress::new()); - let p = progress.clone(); - let rx = spawn_worker("texturecraft-bake", move || task.run(&p)); - if let Some(job) = self.bake.as_mut() { - job.current = Some((ts, progress, rx)); - } - } - Err(e) => { - self.session.bake_abandoned([ts]); - self.toast(e.to_string(), true); + + if job.queue.is_empty() { + self.bake = None; + self.toast(i18n::tr("Mesh maps baked"), false); + return; + } + let set_index = job.queue.remove(0); + match self.session.bake_task(set_index) { + Ok(task) => { + let progress = Arc::new(Progress::new()); + let worker_progress = progress.clone(); + let receiver = spawn_worker("texturecraft-bake", move || task.run(&worker_progress)); + if let Some(job) = self.bake.as_mut() { + job.current = Some((set_index, progress, receiver)); } } + Err(error) => self.toast(error.to_string(), true), } } - /// Auto-rebake: when the chosen map's bake inputs changed, bake it again in the background - /// (one set after another, only that map), unless a bake or a stroke is running. - fn drive_auto_rebake(&mut self) { - // The web build runs a bake on the page's own thread, which would freeze the browser: there - // Auto-rebake is left to the manual command (`bake.autoRebake.run`). - if cfg!(target_arch = "wasm32") { - return; - } - if self.bake.is_some() || self.session.stroke_active() || self.session.auto_rebake.map.is_none() { - return; - } - let due = self.session.auto_rebake_due(); - if !due.is_empty() { - let total = due.len(); - self.bake = Some(BakeJob { queue: due, current: None, total, only: self.session.auto_rebake.map }); - } - } - - /// Stops the bake job (also after an error). The set being baked and the queued ones wait for - /// their next bake input change before Auto-rebake tries them again. + /// Cancel the active bake and discard queued sets pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - if let Some((_, p, _)) = &job.current { - p.cancel.store(true, Ordering::Relaxed); + + if let Some((_, progress, _)) = job.current { + progress.cancel.store(true, Ordering::Relaxed); } - self.session.bake_abandoned(job.current.map(|(ts, ..)| ts).into_iter().chain(job.queue)); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when @@ -475,7 +449,6 @@ impl eframe::App for TextureCraftApp { web_files::dropped(self, ctx, f); } self.poll_bake(ctx); - self.drive_auto_rebake(); self.poll_resize(ctx); self.poll_link_cooks(ctx); // The library shelf rescans when the window comes back (MaterialCraft may have sent a material). @@ -514,14 +487,12 @@ impl eframe::App for TextureCraftApp { if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); - toolbar::top_bar(self, ui); toolbar::status_bar(self, ui); toolbar::tool_shelf(self, ui); - // Bake settings take the Assets slot; a side panel only when Assets is closed. - if self.ui.mode == state::Mode::Baking && !self.ui.dock.is_open(docking::Panel::Assets) { - windows::bake_left(self, ui); + self.ui.sync_mode_dock(); + if self.ui.mode != state::Mode::Baking { + toolbar::rail(self, ui); } - toolbar::rail(self, ui); } let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 09f19c07..a2e85bf7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -61,13 +61,15 @@ pub const CATALOG: &[Item] = &[ it("Mode", "Painting", "ui.mode.paint", Some("F9")), it("Mode", "Rendering (path traced)", "ui.mode.render", Some("F10")), sub("Window", "Views", "Assets", "ui.view.assets", None), + sub("Window", "Views", "Bake Maps", "ui.view.bakeMaps", None), + sub("Window", "Views", "Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), sub("Window", "Views", "History", "ui.view.history", None), sub("Window", "Views", "Layers", "ui.view.layers", None), sub("Window", "Views", "Log", "ui.view.log", None), sub("Window", "Views", "Properties", "ui.view.properties", None), sub("Window", "Views", "Shader Settings", "ui.view.shader", None), - sub("Window", "Views", "Texture Set List", "ui.view.textureSetList", None), + sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), sub("Window", "Views", "Texture Set Settings", "ui.view.textureSetSettings", None), sub("Window", "Save UI Layout", "Save current layout...", "ui.layout.save", None), it("Window", "Load UI Layout", "ui.layout.load", None), @@ -106,6 +108,14 @@ fn is_ui(id: &str) -> bool { /// Whether an item can run now. pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { + if let Some(panel) = crate::docking::view_panel(id) { + return panel.available_in(app.ui.mode); + } + + if app.ui.mode != Mode::Painting && (id.starts_with("tool.") || id.starts_with("viewport.quickMask")) { + return false; + } + if is_ui(id) { return true; } @@ -119,6 +129,10 @@ pub fn implemented(id: &str) -> bool { /// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { + if !enabled(app, id) { + return; + } + if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { @@ -293,39 +307,44 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } - ctx.input_mut(|i| { - let keys: Vec<_> = i.events.iter().filter_map(|e| clipboard_key(e, i.modifiers)).collect(); - i.events.extend(keys); + + ctx.input_mut(|input| { + let keys: Vec<_> = input.events.iter().filter_map(|event| clipboard_key(event, input.modifiers)).collect(); + input.events.extend(keys); }); - if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) { + + if !ctx.input(|input| input.events.iter().any(|event| matches!(event, egui::Event::Key { pressed: true, .. }))) { return; } - let active = crate::keymap::active(&app.ui.keymap); - let mut fire: Vec<&str> = Vec::new(); - ctx.input_mut(|i| { - for (id, sc) in &active { - if i.consume_shortcut(sc) { - fire.push(*id); + + let active_shortcuts = crate::keymap::active(&app.ui.keymap); + let mut commands_to_invoke: Vec<&str> = Vec::new(); + ctx.input_mut(|input| { + for (id, shortcut) in &active_shortcuts { + if input.consume_shortcut(shortcut) { + commands_to_invoke.push(*id); } } - // Brush size and hardness: [ and ]. - let size_down = i.consume_key(Modifiers::NONE, Key::OpenBracket); - let size_up = i.consume_key(Modifiers::NONE, Key::CloseBracket); - if size_down || size_up { - let f = if size_up { 1.15 } else { 1.0 / 1.15 }; - app.session.tool.brush.size = (app.session.tool.brush.size * f).clamp(0.0005, 0.25); + + let size_down = input.consume_key(Modifiers::NONE, Key::OpenBracket); + let size_up = input.consume_key(Modifiers::NONE, Key::CloseBracket); + if app.ui.mode == Mode::Painting && (size_down || size_up) { + let scale = if size_up { 1.15 } else { 1.0 / 1.15 }; + app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(0.0005, 0.25); } - if i.consume_key(Modifiers::NONE, Key::Escape) { + + if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; } }); - for id in fire { + + for id in commands_to_invoke { if matches!(id, "layer.copy" | "layer.cut") - && let Some(layer) = app.session.selected_layer().and_then(|l| app.session.doc.project.layers.get(&l)) + && let Some(layer) = app.session.selected_layer().and_then(|layer| app.session.doc.project.layers.get(&layer)) { - // Ctrl+V reaches the app only while the system clipboard holds text or an image. + // Ctrl+V reaches the app only while the system clipboard holds text or an image ctx.copy_text(layer.name.clone()); } invoke(app, ctx, effect_command(app, id)); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 8f75452b..f2aaeb65 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -123,27 +123,33 @@ pub enum DropZone { View3d, } -/// Make `resp` a drop target for shelf assets `zone` accepts: outline it while one hovers, -/// apply it on release. -pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, zone: DropZone) { - let tk = Tokens::get(ui.ctx()); - let accepts = |d: &ShelfDrag| match d.asset { +/// Highlight accepted shelf assets on hover and apply them on drop +pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { + if app.ui.mode != crate::state::Mode::Painting { + return; + } + + let tokens = Tokens::get(ui.ctx()); + let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush, Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - if resp.dnd_hover_payload::().is_some_and(|d| accepts(&d)) { - ui.painter().rect_stroke(resp.rect.shrink(1.0), 3.0, Stroke::new(2.0, tk.accent), egui::StrokeKind::Inside); + if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag)) { + ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } - let pointer = ui.input(|i| i.pointer.interact_pos()); - if let Some(d) = dnd_release::(resp) - && accepts(&d) + let pointer = ui.input(|input| input.pointer.interact_pos()); + if let Some(drag) = dnd_release::(response) + && accepts(&drag) { - match (&d.asset, pointer) { - (Asset::Texture(name), Some(p)) => { - let (q, vp) = (p - resp.rect.min, resp.rect.size()); - app.run("layer.add.decal", json!({"image": name, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + match (&drag.asset, pointer) { + (Asset::Texture(name), Some(position)) => { + let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); + app.run( + "layer.add.decal", + json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}), + ); } (asset, _) => apply(app, asset), } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b4831be7..0947b2fd 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::Channel; use crate::docking::Dock; use crate::keymap::Keymap; @@ -239,6 +239,10 @@ pub struct UiState { /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, + #[serde(default = "Dock::for_baking")] + pub(crate) inactive_mode_dock: Dock, + #[serde(default)] + pub(crate) dock_is_baking: bool, /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, @@ -273,9 +277,6 @@ pub struct UiState { /// Custom keyboard shortcuts (item id → "Ctrl+Shift+E", "" = none) over the defaults. #[serde(default)] pub keymap: Keymap, - /// The baker whose parameters bake mode shows (None: the common parameters). - #[serde(default)] - pub bake_baker: Option, /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub skew_brush: SkewBrush, @@ -298,6 +299,14 @@ impl Default for SkewBrush { } impl UiState { + pub(crate) fn sync_mode_dock(&mut self) { + let baking = self.mode == Mode::Baking; + if baking != self.dock_is_baking { + std::mem::swap(&mut self.dock, &mut self.inactive_mode_dock); + self.dock_is_baking = baking; + } + } + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export /// settings and recent files. pub fn adopt_layout(&mut self, layout: UiState) { @@ -318,6 +327,8 @@ impl Default for UiState { mode: Mode::Painting, layout: ViewLayout::Split, dock: Dock::default(), + inactive_mode_dock: Dock::for_baking(), + dock_is_baking: false, hide_ui: false, windows: Windows::default(), uv_zoom: 1.0, @@ -336,7 +347,6 @@ impl Default for UiState { export: ExportUi::default(), recent: Vec::new(), keymap: Keymap::new(), - bake_baker: None, skew_brush: SkewBrush::default(), } } diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 03ef13d0..2c900ed3 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -28,68 +28,64 @@ pub fn tool_icon(t: Tool) -> &'static str { } } -pub fn top_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::top("tool_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: GUTTER, right: GUTTER, top: GUTTER, bottom: 0 }, egui::Margin::symmetric(8, 0), |ui| { +pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let tokens = Tokens::get(ui.ctx()); + egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { ui.horizontal_centered(|ui| { ui.spacing_mut().item_spacing.x = 10.0; - if app.ui.mode == Mode::Baking { - ui.label(RichText::new(tr("Bake Mesh Maps")).color(tk.text_strong)); - return; - } let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tk.text_strong)).on_hover_text(tool.label()); - let b = &mut app.session.tool.brush; + ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tokens.text_strong)).on_hover_text(tool.label()); + let brush = &mut app.session.tool.brush; match tool { Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = b.size / 0.25 * 100.0; + let mut size = brush.size / 0.25 * 100.0; if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); + brush.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); } - let mut flow = b.flow * 100.0; + let mut flow = brush.flow * 100.0; if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - b.flow = flow / 100.0; + brush.flow = flow / 100.0; } - let mut op = b.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut op, 0.0..=100.0, 110.0).changed() { - b.opacity = op / 100.0; + let mut opacity = brush.opacity * 100.0; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { + brush.opacity = opacity / 100.0; } - let mut sp = b.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut sp, 1.0..=200.0, 100.0).changed() { - b.spacing = sp / 100.0; + let mut spacing = brush.spacing * 100.0; + if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { + brush.spacing = spacing / 100.0; } ui.separator(); - let lazy_on = b.lazy > 0.0; + let lazy_on = brush.lazy > 0.0; if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - b.lazy = if lazy_on { 0.0 } else { 20.0 }; + brush.lazy = if lazy_on { 0.0 } else { 20.0 }; } if lazy_on { - let mut d = b.lazy; - if bar_slider(ui, tr("Distance"), &mut d, 1.0..=200.0, 90.0).changed() { - b.lazy = d; + let mut distance = brush.lazy; + if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + brush.lazy = distance; } } ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), b.symmetry.x, 24.0).clicked() { - b.symmetry.x = !b.symmetry.x; + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { + brush.symmetry.x = !brush.symmetry.x; } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), b.symmetry.y, 24.0).clicked() { - b.symmetry.y = !b.symmetry.y; + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { + brush.symmetry.y = !brush.symmetry.y; } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), b.particles.enabled, 24.0).clicked() { - b.particles.enabled = !b.particles.enabled; + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { + brush.particles.enabled = !brush.particles.enabled; } if tool == Tool::Smudge { ui.separator(); - let mut st = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut st, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (st / 100.0).clamp(0.0, 1.0); + let mut strength = app.session.tool.smudge_strength * 100.0; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { + app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); } } if tool == Tool::Clone && app.session.tool.clone_source.is_none() { ui.separator(); - ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tk.text_dim)); + ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); } if tool == Tool::Path { ui.separator(); @@ -98,21 +94,21 @@ pub fn top_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } Tool::PolygonFill => { use texturecraft_engine::FillMode; - for (m, icon, tip) in [ + for (fill_mode, icon, tip) in [ (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), ] { - if icon_button(ui, icon, tip, app.session.tool.fill_mode == m, 24.0).clicked() { - app.session.tool.fill_mode = m; + if icon_button(ui, icon, tip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { + app.session.tool.fill_mode = fill_mode; } } } Tool::ColorPicker => { - ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tk.text_dim)); + ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); } Tool::GeometryMask => { - ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); } } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -120,13 +116,13 @@ pub fn top_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); } ui.separator(); - for (l, icon, label, id) in [ + for (layout, icon, label, id) in [ (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), app.ui.layout == l, 24.0).clicked() { - app.ui.layout = l; + if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), app.ui.layout == layout, 24.0).clicked() { + app.ui.layout = layout; } } ui.separator(); @@ -165,46 +161,53 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { + card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { ui.spacing_mut().item_spacing.y = 3.0; - let painting = app.ui.mode == Mode::Painting; - for t in Tool::ALL { - let selected = painting && app.session.tool.tool == t; - let hint = tip(&app.ui.keymap, tr(t.label()), &format!("tool.{}", t.id())); - if icon_button(ui, tool_icon(t), &hint, selected, 28.0).clicked() { - app.ui.mode = Mode::Painting; - app.run("tool.select", json!({"tool": t.id()})); - } - } - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); - let q = &app.session.quick_mask; - for (id, icon, label, on) in [ - ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), q.enabled), - ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), q.editing), - ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), q.inverted), + for (mode, icon, label, command) in [ + (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), + (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), + (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), on, 28.0).clicked() { - app.run(id, json!({})); + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 28.0).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); } } + ui.add_space(6.0); ui.separator(); ui.add_space(6.0); - if icon_button(ui, ic::ATOM, &tip(&app.ui.keymap, tr("Bake mesh maps"), "ui.mode.bake"), app.ui.mode == Mode::Baking, 28.0).clicked() { - app.ui.mode = if app.ui.mode == Mode::Baking { Mode::Painting } else { Mode::Baking }; - } - if icon_button(ui, ic::APERTURE, &tip(&app.ui.keymap, tr("Rendering, path traced"), "ui.mode.render"), app.ui.mode == Mode::Rendering, 28.0) - .clicked() - { - app.ui.mode = if app.ui.mode == Mode::Rendering { Mode::Painting } else { Mode::Rendering }; - } - if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() { - app.ui.dock.focus(Panel::Assets); - } + ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { + for tool in Tool::ALL { + let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; + let hint = tip(&app.ui.keymap, tr(tool.label()), &format!("tool.{}", tool.id())); + if icon_button(ui, tool_icon(tool), &hint, selected, 28.0).clicked() { + app.run("tool.select", json!({"tool": tool.id()})); + } + } + + ui.add_space(6.0); + ui.separator(); + ui.add_space(6.0); + let quick_mask = &app.session.quick_mask; + for (command, icon, label, selected) in [ + ("viewport.quickMask", ic::SELECTION_BACKGROUND, tr("Quick mask"), quick_mask.enabled), + ("viewport.quickMask.edit", ic::SELECTION, tr("Edit quick mask"), quick_mask.editing), + ("viewport.quickMask.invert", ic::SELECTION_INVERSE, tr("Invert quick mask"), quick_mask.inverted), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), selected, 28.0).clicked() { + app.run(command, json!({})); + } + } + + ui.add_space(6.0); + ui.separator(); + ui.add_space(6.0); + if icon_button(ui, ic::SPHERE, tr("Add smart material from the shelf"), false, 28.0).clicked() { + app.ui.dock.focus(Panel::Assets); + } + }); }); }); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a809c341..38767838 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -35,30 +35,44 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { } pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let mode = app.ui.mode; + let skew_painting = mode == crate::state::Mode::Baking + && app.ui.skew_brush.on + && !app.session.bake_meshes.high.is_empty() + && app + .session + .doc + .project + .texture_sets + .get(app.session.ts()) + .is_some_and(|texture_set| texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased); + app.ui.skew_brush.on = skew_painting; + if mode == crate::state::Mode::Painting && !app.ui.hide_ui { + crate::toolbar::paint_bar(app, ui); + } + + let tokens = Tokens::get(ui.ctx()); let aux = match app.session.view { - _ if app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), + _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(m) => Some(crate::gpu::AuxView::MeshMap(m)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; let mut sync = PendingSync(Some(aux)); - let full = ui.max_rect(); - let mode = app.ui.mode; + let full = ui.available_rect_before_wrap(); path_keys(app, ui); - // Bake mode shows the 3D view alone, except while the skew brush needs the 2D view to paint in. - let skew_painting = mode == crate::state::Mode::Baking && app.ui.skew_brush.on; + // Skew painting needs the 2D view alongside the 3D Bake preview let layout = if mode == crate::state::Mode::Painting || skew_painting { app.ui.layout } else { ViewLayout::Only3D }; match layout { ViewLayout::Only3D => view_3d(app, ui, full, &mut sync), ViewLayout::Only2D => view_2d(app, ui, full, &mut sync), ViewLayout::Split => { - let mid = full.center().x; - let left = Rect::from_min_max(full.min, pos2(mid - 1.0, full.max.y)); - let right = Rect::from_min_max(pos2(mid + 1.0, full.min.y), full.max); + let midpoint = full.center().x; + let left = Rect::from_min_max(full.min, pos2(midpoint - 1.0, full.max.y)); + let right = Rect::from_min_max(pos2(midpoint + 1.0, full.min.y), full.max); view_3d(app, ui, left, &mut sync); view_2d(app, ui, right, &mut sync); - ui.painter().line_segment([pos2(mid, full.top()), pos2(mid, full.bottom())], Stroke::new(2.0, tk.chrome)); + ui.painter().line_segment([pos2(midpoint, full.top()), pos2(midpoint, full.bottom())], Stroke::new(2.0, tokens.chrome)); } } if mode == crate::state::Mode::Rendering { @@ -66,7 +80,10 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } else if app.render.is_active() { crate::render_mode::stop(app); } - // Keep drawing while the 3D view accumulates anti-aliasing samples (it stops on its own). + if mode == crate::state::Mode::Baking { + crate::bake_mode::bake_bar(app, ui.ctx(), full); + } + // Keep drawing until the 3D view finishes accumulating anti-aliasing samples let accumulating = layout != ViewLayout::Only2D && app .render_state @@ -79,16 +96,16 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.session.quick_mask.editing => (2, 0), + _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0), ViewMode::Material => (0, 0), - ViewMode::Channel(c) => (1, c.index() as u32), + ViewMode::Channel(selected_channel) => (1, selected_channel.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0), ViewMode::UvChecker => (3, 0), }; - let ts = app.session.ts(); - let hs = app.session.doc.project.texture_sets.get(ts).map(|t| t.atlas_height_strength()).unwrap_or(1.0); + let set_index = app.session.ts(); + let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); Shade { - height_strength: hs, + height_strength, view_mode, channel, wireframe: app.ui.uv_wireframe, @@ -200,7 +217,10 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); - let label = app.session.view.label(); + let label = match app.session.view { + ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), + _ => app.session.view.label(), + }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); egui::ComboBox::from_id_salt(format!("{id}_mode")).width(130.0).selected_text(tr(&label)).show_ui(&mut child, |ui| { if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { @@ -214,7 +234,8 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { } ui.separator(); for m in BakedMap::ALL { - if ui.selectable_label(app.session.view == ViewMode::MeshMap(m), trf("Mesh map: {map}", &[("map", &tr(m.label()))])).clicked() { + if ui.selectable_label(app.session.view == ViewMode::MeshMap(m), trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(m)))])).clicked() + { app.run("viewport.view", json!({"mode": format!("map:{}", m.id())})); } } @@ -261,7 +282,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Navigation (S + drag manipulates the projection stencil instead, below). let delta = ui.input(|i| i.pointer.delta()); - let s_held = ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); + let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { // The stencil moves, turns and scales instead of the camera (handled below), or the @@ -284,9 +305,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if resp.hovered() { let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll != 0.0 { - if shift { - let b = &mut app.session.tool.brush; - b.size = (b.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); + if shift && app.ui.mode == crate::state::Mode::Painting { + let brush = &mut app.session.tool.brush; + brush.size = (brush.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); } else { app.session.camera.zoom(scroll * 0.0025); } @@ -606,6 +627,10 @@ fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: /// The frame of the selected decal layer over the 3D view with its handles (and a hint while /// placing it): outline, corner handles, the rotation handle and the projection direction. fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { + if app.ui.mode != crate::state::Mode::Painting { + return; + } + let tk = Tokens::get(ui.ctx()); use texturecraft_engine::core::{Fill, LayerKind, Projection}; let p = &app.session.doc.project; @@ -654,32 +679,33 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { } } -/// Draw the projection stencil over the 3D view. +/// Draw the projection stencil in Paint Mode fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { - if app.session.tool.tool != Tool::Projection { + if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Projection { return; } - let Some(st) = app.session.tool.stencil.clone() else { return }; - let Some(img) = app.session.images.get(&st.image).cloned() else { return }; - let tex = app.thumbs.stencil(ui.ctx(), &st.image, &img); + let Some(stencil) = app.session.tool.stencil.clone() else { return }; + let Some(image) = app.session.images.get(&stencil.image).cloned() else { return }; + + let texture = app.thumbs.stencil(ui.ctx(), &stencil.image, &image); let aspect = rect.width() / rect.height().max(1.0); - let (center, half, rot) = st.placement(img.width as f32 / img.height.max(1) as f32, aspect); - let to_screen = |nx: f32, ny: f32| pos2(rect.left() + (nx * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ny * 0.5) * rect.height()); - let (sn, cs) = rot.sin_cos(); - let corner = |lx: f32, ly: f32| { - let (x, y) = (lx * half[0], ly * half[1]); - to_screen(center[0] + x * cs - y * sn, center[1] + x * sn + y * cs) + let (center, half_size, rotation) = stencil.placement(image.width as f32 / image.height.max(1) as f32, aspect); + let to_screen = |x: f32, y: f32| pos2(rect.left() + (x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - y * 0.5) * rect.height()); + let (sine, cosine) = rotation.sin_cos(); + let corner = |x: f32, y: f32| { + let (x, y) = (x * half_size[0], y * half_size[1]); + to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) }; - let tint = Color32::from_white_alpha((st.opacity * 255.0) as u8); - let mut mesh = egui::Mesh::with_texture(tex.id()); - for (lx, ly, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] { - mesh.vertices.push(egui::epaint::Vertex { pos: corner(lx, ly), uv: pos2(u, v), color: tint }); + let tint = Color32::from_white_alpha((stencil.opacity * 255.0) as u8); + let mut mesh = egui::Mesh::with_texture(texture.id()); + for (x, y, u, v) in [(-1.0, 1.0, 0.0, 0.0), (1.0, 1.0, 1.0, 0.0), (1.0, -1.0, 1.0, 1.0), (-1.0, -1.0, 0.0, 1.0)] { + mesh.vertices.push(egui::epaint::Vertex { pos: corner(x, y), uv: pos2(u, v), color: tint }); } mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]); - let p = ui.painter_at(rect); - p.add(egui::Shape::mesh(mesh)); + let painter = ui.painter_at(rect); + painter.add(egui::Shape::mesh(mesh)); let outline = vec![corner(-1.0, 1.0), corner(1.0, 1.0), corner(1.0, -1.0), corner(-1.0, -1.0), corner(-1.0, 1.0)]; - p.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); + painter.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); } /// A world point on screen in the 3D view `rect` (None behind the camera). diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 5e000fa8..eb3a8eb4 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -29,35 +29,46 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R } fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { - let tk = Tokens::get(ui.ctx()); - let (lo, hi) = (*range.start(), *range.end()); - let w = ui.available_width(); + let tokens = Tokens::get(ui.ctx()); + let (minimum, maximum) = (*range.start(), *range.end()); + let width = ui.available_width(); + let font = egui::TextStyle::Body.resolve(ui.style()); + let value_width = [minimum, maximum] + .into_iter() + .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) + .fold(44.0, f32::max); let mut edit = None; let field = ui .horizontal(|ui| { - ui.label(RichText::new(label).color(tk.text)); + ui.label(RichText::new(label).color(tokens.text)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); - let shown = format!("{:.*}", decimals, value); - // What is typed lives here while the field has focus (`value` is re-read every frame). - let mut text = ui.data(|d| d.get_temp::(id)).unwrap_or_else(|| shown.clone()); - let r = ui.add(egui::TextEdit::singleline(&mut text).id(id).desired_width(44.0).align(egui::Align2::RIGHT_CENTER).frame(egui::Frame::NONE)); - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(id, text.clone())); + let shown = format!("{value:.decimals$}"); + // Keep unfinished input while the document value is re-read each frame + let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); + let response = ui.add( + egui::TextEdit::singleline(&mut text) + .id(id) + .font(font) + .desired_width(value_width) + .align(egui::Align2::RIGHT_CENTER) + .frame(egui::Frame::NONE), + ); + if response.has_focus() { + ui.data_mut(|data| data.insert_temp(id, text.clone())); } else { - ui.data_mut(|d| d.remove_temp::(id)); - // Escape unfocuses the field before the app's shortcuts may consume the key, so - // look at the raw input. - let escape = ui.input(|i| i.raw.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); - // Leaving the field unchanged (or with Escape) keeps the value as it is. - if r.lost_focus() + ui.data_mut(|data| data.remove_temp::(id)); + // Escape can lose focus before the app consumes the key + let escape = + ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if response.lost_focus() && !escape && text != shown - && let Ok(v) = text.trim().parse::() - && v.is_finite() - && v.clamp(lo, hi) != *value + && let Ok(parsed) = text.trim().parse::() + && parsed.is_finite() + && parsed.clamp(minimum, maximum) != *value { - *value = v.clamp(lo, hi); + *value = parsed.clamp(minimum, maximum); edit = Some(false); } } @@ -66,34 +77,33 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang .inner }) .inner; - let (rect, mut resp) = ui.allocate_exact_size(vec2(w, 14.0), Sense::click_and_drag()); - if resp.is_pointer_button_down_on() { - // Using the track drops what was typed in the field (a drag does not take its focus). - ui.data_mut(|d| d.remove_temp::(field)); - ui.memory_mut(|m| m.surrender_focus(field)); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, 14.0), Sense::click_and_drag()); + if response.is_pointer_button_down_on() { + ui.data_mut(|data| data.remove_temp::(field)); + ui.memory_mut(|memory| memory.surrender_focus(field)); } if edit.is_some() { - // A typed value is a change for `slider`'s callers too. - resp.mark_changed(); + response.mark_changed(); } - if (resp.dragged() || resp.clicked()) - && let Some(p) = resp.interact_pointer_pos() + if (response.dragged() || response.clicked()) + && let Some(pointer) = response.interact_pointer_pos() { - let t = ((p.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); - let v = lo + (hi - lo) * t; - if (v - *value).abs() > f32::EPSILON { - *value = v; - resp.mark_changed(); - // Whether this drag already applied a value (cleared when it ends). - edit = Some(ui.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::(resp.id), true))); + let fraction = ((pointer.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); + let next = minimum + (maximum - minimum) * fraction; + if (next - *value).abs() > f32::EPSILON { + *value = next; + response.mark_changed(); + // Later frames of one drag share its undo step + edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); } } - if resp.drag_stopped() || resp.clicked() { - ui.data_mut(|d| d.remove_temp::(resp.id)); + if response.drag_stopped() || response.clicked() { + ui.data_mut(|data| data.remove_temp::(response.id)); } - let t = if hi > lo { ((*value - lo) / (hi - lo)).clamp(0.0, 1.0) } else { 0.0 }; - track(ui, &resp, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, t, 2.0, 4.5); - (resp, edit) + + let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 }; + track(ui, &response, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, fraction, 2.0, 4.5); + (response, edit) } /// A small inline slider for the top tool bar: "Label value" above a short track. @@ -207,24 +217,34 @@ pub fn combo(ui: &mut Ui, label: &str, selected: impl Into, me .inner } -/// A collapsible section header with a chevron ("> Size"). +pub(crate) fn section_chevron(ui: &Ui, is_open: bool) -> RichText { + let chevron = if is_open { + egui_phosphor::regular::CARET_DOWN + } else if ui.style().right_to_left { + egui_phosphor::regular::CARET_LEFT + } else { + egui_phosphor::regular::CARET_RIGHT + }; + RichText::new(chevron).size(10.0).color(Tokens::get(ui.ctx()).text_dim) +} + +/// A collapsible section header with a chevron pub fn section(ui: &mut Ui, id: &str, title: &str, default_open: bool, body: impl FnOnce(&mut Ui)) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); - let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); - let open = state.is_open(); - let resp = ui + let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); + let response = ui .horizontal(|ui| { - let chev = if open { egui_phosphor::regular::CARET_DOWN } else { egui_phosphor::regular::CARET_RIGHT }; - ui.label(RichText::new(chev).size(10.0).color(tk.text_dim)); - ui.label(RichText::new(title).strong().color(tk.text_strong)); + ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); + ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); }) .response .interact(Sense::click()); - if resp.clicked() { - state.toggle(ui); + if response.clicked() { + collapsing_state.toggle(ui); } - state.show_body_unindented(ui, |ui| { + + collapsing_state.show_body_unindented(ui, |ui| { ui.indent(id.with("in"), body); }); } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ecab281..c8bd72c5 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,12 +1,10 @@ -//! Floating windows, the dockable panel bodies (display, shader, history, log) and the bake mode -//! panels. +//! Floating windows and dockable display, shader, history and log panels use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; -use texturecraft_engine::bake_cmds; +use texturecraft_engine::core::ToneMapping; use texturecraft_engine::core::project::ENV_RESOURCE_PREFIX; -use texturecraft_engine::core::{BakeMatch, BakeSettings, BakedMap, DirectionMode, PositionMode, RayDistribution, RaySettings, SelfOcclusion, ToneMapping}; use texturecraft_engine::geom::primitives::BUILTINS; use texturecraft_render::ibl::ENVIRONMENTS; @@ -26,9 +24,6 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::windows::export(app, ctx); #[cfg(target_arch = "wasm32")] export_mesh(app, ctx); - if app.ui.mode == Mode::Baking { - bake_bar(app, ctx); - } unsaved(app, ctx); } @@ -678,317 +673,6 @@ pub(crate) fn log(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -// --------------------------------------------------------------------------------------------- -// Bake mode ("Bake Mesh Maps": texture sets, bakers, common and per-map parameters) - -pub fn bake_left(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::left("bake_left").resizable(true).default_size(320.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - crate::theme::card( - ui, - &tk, - egui::Margin { left: crate::theme::GUTTER, right: 0, top: crate::theme::GUTTER, bottom: crate::theme::GUTTER }, - egui::Margin::symmetric(8, 6), - |ui| bake_body(app, ui), - ); - }); -} - -/// The bake settings, scrollable (the Assets dock slot shows them in bake mode). -pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().id_salt("bake_body").auto_shrink([false; 2]).show(ui, |ui| bake_panel(app, ui)); -} - -fn bake_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Texture set list"))); - for i in 0..app.session.set_count() { - let Some(t) = app.session.doc.project.texture_sets.get(i) else { continue }; - let (name, res, mut on) = (t.name.clone(), t.bake.resolution, t.bake.enabled); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").on_hover_text(tr("Bake with \"Bake selected textures\"")).changed() { - app.run("bake.settings", json!({ "ts": i, "enabled": on })); - } - if ui.selectable_label(i == app.session.ts(), format!("{name} ({res}x{res})")).clicked() { - app.run("textureSet.select", json!({ "ts": i })); - } - }); - } - ui.separator(); - let ts = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(ts).map(|t| t.bake.clone()) else { return }; - let mut b = before.clone(); - let mut selected = app.ui.bake_baker; - ui.label(caption(tr("Mesh map bakers"))); - if ui.selectable_label(selected.is_none(), format!("{} {}", ic::GEAR, tr("Common parameters"))).clicked() { - selected = None; - } - for m in BakedMap::ALL { - ui.horizontal(|ui| { - let mut on = b.maps.contains(&m); - if ui.checkbox(&mut on, "").changed() { - if on { - b.maps.insert(m); - } else { - b.maps.remove(&m); - } - } - if ui.selectable_label(selected == Some(m), tr(m.label())).clicked() { - selected = Some(m); - } - }); - } - app.ui.bake_baker = selected; - ui.separator(); - match selected { - None => common_params(app, ui, &mut b), - Some(m) => { - let mut auto = app.session.auto_rebake.map == Some(m); - if ui - .checkbox(&mut auto, tr("Auto-rebake")) - .on_hover_text(tr("Bake this map again by itself when its bake settings, the low poly or the high polys change")) - .changed() - { - app.run("bake.autoRebake", if auto { json!({ "map": m.id() }) } else { json!({ "off": true }) }); - } - map_params(ui, m, &mut b) - } - } - if b.direction == [0.0; 3] { - b.direction = before.direction; - } - if b != before { - let mut p = bake_cmds::settings_params(&b); - p["ts"] = ts.into(); - app.run("bake.settings", p); - } -} - -fn hint(ui: &mut Ui, text: &str) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(text).color(tk.text_dim).size(11.0)); -} - -fn common_params(app: &mut TextureCraftApp, ui: &mut Ui, b: &mut BakeSettings) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Common parameters"))); - combo(ui, tr("Output size"), format!("{}", b.resolution), |ui| { - for r in [256u32, 512, 1024, 2048, 4096, 8192] { - ui.selectable_value(&mut b.resolution, r, format!("{r}")); - } - }); - combo( - ui, - tr("Antialiasing"), - match b.antialiasing { - 2 => tr("Subsampling 2x2"), - 4 => tr("Subsampling 4x4"), - 8 => tr("Subsampling 8x8"), - _ => tr("None"), - }, - |ui| { - for (v, l) in [(1u32, tr("None")), (2, tr("Subsampling 2x2")), (4, tr("Subsampling 4x4")), (8, tr("Subsampling 8x8"))] { - ui.selectable_value(&mut b.antialiasing, v, l); - } - }, - ); - let mut dil = b.dilation as f32; - if slider(ui, tr("Dilation width"), &mut dil, 0.0..=64.0, 0).changed() { - b.dilation = dil as u32; - } - - ui.add_space(6.0); - ui.label(RichText::new(tr("High definition meshes")).strong().color(tk.text_strong)); - let ctx = ui.ctx().clone(); - let highs: Vec<(String, usize)> = app.session.bake_meshes.high.iter().map(|h| (h.name.clone(), h.mesh.triangle_count())).collect(); - let mut remove = None; - for (i, (name, tris)) in highs.iter().enumerate() { - ui.horizontal(|ui| { - ui.label(trf("{name} ({n} triangles)", &[("name", name), ("n", tris)])); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button(ui, ic::TRASH, tr("Remove"), false, 18.0).clicked() { - remove = Some(i); - } - }); - }); - } - if highs.is_empty() { - hint(ui, tr("None: the low poly is its own high poly.")); - } - if let Some(i) = remove { - app.run("bake.highPoly.remove", json!({ "index": i })); - } - if ui.button(format!("{} {}", ic::PLUS, tr("Add high definition meshes"))).clicked() { - crate::web_files::import_bake_mesh(app, &ctx, false); - } - ui.checkbox(&mut b.use_low_as_high, tr("Use low poly mesh as high poly mesh")); - choice(ui, tr("Match"), &mut b.matching, &[(BakeMatch::Always, tr("Always")), (BakeMatch::ByMeshName, tr("By mesh name"))]); - if b.matching == BakeMatch::ByMeshName { - for (label, suffix) in [(tr("Low poly mesh suffix"), &mut b.low_suffix), (tr("High poly mesh suffix"), &mut b.high_suffix)] { - ui.horizontal(|ui| { - ui.label(label); - ui.add(egui::TextEdit::singleline(suffix).desired_width(80.0)); - }); - } - } - slider(ui, tr("Max frontal distance"), &mut b.max_frontal, 0.0..=0.2, 3); - slider(ui, tr("Max rear distance"), &mut b.max_rear, 0.0..=0.2, 3); - hint(ui, tr("Relative to the bounding box diagonal.")); - ui.checkbox(&mut b.average_normals, tr("Average normals")); - - ui.add_space(6.0); - let cage = app.session.bake_meshes.cage.as_ref().map(|c| c.name.clone()); - ui.horizontal(|ui| { - ui.label(trf("Cage: {name}", &[("name", &cage.as_deref().unwrap_or(tr("none")))])); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if cage.is_some() && icon_button(ui, ic::TRASH, tr("Remove the cage"), false, 18.0).clicked() { - app.run("bake.cage.clear", json!({})); - } - if icon_button(ui, ic::FOLDER_OPEN, tr("Load a cage (the low poly, inflated)"), false, 18.0).clicked() { - crate::web_files::import_bake_mesh(app, &ctx, true); - } - }); - }); - - ui.add_space(6.0); - skew_section(app, ui); - - ui.add_space(6.0); - if ui.button(tr("Apply to all texture sets")).on_hover_text(tr("Copy these bake settings to every texture set")).clicked() { - let mut p = bake_cmds::settings_params(b); - p["ts"] = "all".into(); - if let Some(o) = p.as_object_mut() { - o.remove("enabled"); - } - app.run("bake.settings", p); - } -} - -/// Skew correction: paint a map over the UV atlas that turns the bake rays onto the base normal. -fn skew_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Skew correction"))); - let has = app.session.bake_meshes.skew.is_some(); - let mut brush = app.ui.skew_brush; - ui.checkbox(&mut brush.on, tr("Paint skew in the 2D view")) - .on_hover_text(tr("Drag in the 2D view to paint where the bake rays turn onto the base normal; paint with a value of 0 to erase")); - if brush.on { - slider(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); - slider(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); - slider(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); - } - if brush.on && !app.ui.skew_brush.on && app.ui.layout == crate::state::ViewLayout::Only3D { - app.ui.layout = crate::state::ViewLayout::Split; - } - app.ui.skew_brush = brush; - if has && ui.button(tr("Remove skew correction")).clicked() { - app.run("bake.skew.clear", json!({})); - } -} - -/// A combo box picking one of `options` (value, label). -fn choice(ui: &mut Ui, label: &str, value: &mut T, options: &[(T, &str)]) { - let shown = options.iter().find(|(v, _)| v == value).map_or("", |(_, l)| *l); - combo(ui, label, shown, |ui| { - for (v, l) in options { - ui.selectable_value(value, *v, *l); - } - }); -} - -/// Ray count and length of a secondary-ray map; its cone too when `cone`. -fn ray_params(ui: &mut Ui, r: &mut RaySettings, cone: bool) { - let mut rays = r.rays as f32; - if slider(ui, tr("Secondary rays"), &mut rays, 4.0..=256.0, 0).changed() { - r.rays = rays as u32; - } - slider(ui, tr("Max occluder distance"), &mut r.max_distance, 0.01..=1.0, 2); - if cone { - slider(ui, tr("Spread angle"), &mut r.spread, 0.0..=180.0, 0); - } -} - -fn map_params(ui: &mut Ui, m: BakedMap, b: &mut BakeSettings) { - ui.label(caption(tr(m.label()))); - match m { - BakedMap::AmbientOcclusion => { - ray_params(ui, &mut b.ao, true); - choice(ui, tr("Distribution"), &mut b.ao.distribution, &[(RayDistribution::Cosine, tr("Cosine")), (RayDistribution::Uniform, tr("Uniform"))]); - ui.checkbox(&mut b.ao_ignore_backface, tr("Ignore backface")); - choice( - ui, - tr("Self occlusion"), - &mut b.ao_self_occlusion, - &[(SelfOcclusion::Always, tr("Always")), (SelfOcclusion::SameMeshName, tr("Only same mesh name"))], - ); - } - BakedMap::Thickness => ray_params(ui, &mut b.thickness, true), - BakedMap::BentNormal => { - ray_params(ui, &mut b.bent_normal, false); - hint(ui, tr("Bent normal rays follow the ambient occlusion's occluder settings.")); - } - BakedMap::Curvature => { - slider(ui, tr("Strength"), &mut b.curvature_strength, 0.1..=4.0, 2); - ui.checkbox(&mut b.curvature_from_normal, tr("From normal map")); - if b.curvature_from_normal { - let mut radius = b.curvature_radius as f32; - if slider(ui, tr("Sampling radius"), &mut radius, 0.0..=16.0, 0).changed() { - b.curvature_radius = radius as u32; - } - hint(ui, tr("0 picks a radius from the output size.")); - } - hint(ui, tr("From normal map: curvature of the baked normal map's detail instead of the mesh.")); - } - BakedMap::WorldDirection => { - for (axis, v) in ["X", "Y", "Z"].iter().zip(b.direction.iter_mut()) { - slider(ui, &trf("Direction {axis}", &[("axis", axis)]), v, -1.0..=1.0, 2); - } - choice( - ui, - tr("Encoding"), - &mut b.direction_mode, - &[(DirectionMode::Signed, tr("Signed (-1..1)")), (DirectionMode::Positive, tr("Positive (0..1)"))], - ); - hint(ui, tr("White where the surface faces the direction, black where it faces away.")); - } - BakedMap::Position => { - choice( - ui, - tr("Normalization"), - &mut b.position_mode, - &[(PositionMode::BoundingBox, tr("Bounding box")), (PositionMode::BoundingSphere, tr("Bounding sphere"))], - ); - hint(ui, tr("Position normalized to the low poly's bounding box or sphere.")); - } - BakedMap::Normal => hint(ui, tr("Tangent-space normals of the high definition meshes.")), - BakedMap::WorldNormal => hint(ui, tr("World-space normals of the high poly (or the low poly).")), - BakedMap::Id => hint(ui, tr("One color per mesh part.")), - BakedMap::Height => hint(ui, tr("High poly height between the max rear (black) and max frontal (white) distances.")), - BakedMap::Opacity => hint(ui, tr("White where the high poly covers the low poly, times its alpha.")), - BakedMap::ColorMap => hint(ui, tr("Base colors (textures, factors) and vertex colors of the high definition meshes.")), - } -} - -fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context) { - egui::Area::new(egui::Id::unique("bake_bar")).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -40.0)).show(ctx, |ui| { - ui.horizontal(|ui| { - if let Some(p) = app.bake_progress() { - ui.add(egui::ProgressBar::new(p).desired_width(220.0).show_percentage()); - if ui.button(tr("Cancel")).clicked() { - app.cancel_bake(); - } - } else { - let sets: Vec = app.session.doc.project.texture_sets.iter().enumerate().filter(|(_, t)| t.bake.enabled).map(|(i, _)| i).collect(); - let label = trf("Bake selected textures ({n})", &[("n", &sets.len())]); - if ui.add_enabled(!sets.is_empty(), primary_button(ui, &label)).clicked() { - app.start_bake(sets); - } - } - if ui.button(tr("Return to painting mode")).clicked() { - app.ui.mode = Mode::Painting; - } - }); - }); -} - // --------------------------------------------------------------------------------------------- // Files (wired to texturecraft-formats once it lands) diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs new file mode 100644 index 00000000..c39a1162 --- /dev/null +++ b/crates/ui-egui/tests/bake_mode.rs @@ -0,0 +1,119 @@ +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +fn harness(map: Option) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake = Default::default(); + session.doc.project.texture_sets[0].bake.common.resolution = BakeResolution::R64; + session.doc.project.texture_sets[0].bake.maps.select(map); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.run_steps(3); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +#[test] +fn output_axes_unlock_independently_and_relock_to_width() { + let mut harness = harness(None); + harness.get_by_label("Texture Sets"); + harness.get_by_label("Bake Maps"); + harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.run_steps(3); + let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); + assert!(harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); + + click(&mut harness, "Lock Output Size"); + assert!(!harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); + harness.get_all_by_value(&width).next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128"); + let settings = &harness.state().session.doc.project.texture_sets[0].bake.common; + assert_eq!(settings.resolution, BakeResolution::R128); + assert_eq!(settings.resolution_height.map(BakeResolution::pixels), Some(width.parse().unwrap())); + + click(&mut harness, "Lock Output Size"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.common.output_size(), (128, 128)); + assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); + harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.run_steps(3); + harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.run_steps(3); + assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); + + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(3); + assert!(!harness.state().ui.dock.is_open(Panel::BakeSettings)); + assert!(harness.state().ui.dock.is_open(Panel::Assets)); +} + +#[test] +fn height_controls_follow_enablement_and_manual_normalization() { + let mut harness = harness(None); + assert!(harness.query_by_label("Normalization").is_none()); + click(&mut harness, "Height"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + assert!(harness.query_by_label("Scaling Divisor").is_none()); + click(&mut harness, "Normalization"); + click(&mut harness, "Manual"); + harness.get_by_label("Scaling Divisor"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); + + click(&mut harness, "Restore Defaults"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); + assert!(harness.query_by_label("Scaling Divisor").is_none()); + click(&mut harness, "Height"); + assert!(harness.query_by_label("Normalization").is_none()); +} + +#[test] +fn curvature_controls_follow_the_method_and_notes_visibility_rules() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.get_by_label("Details"); + harness.get_by_label("Seams Intensity"); + click(&mut harness, "Enable Seams"); + assert!(harness.query_by_label("Seams Intensity").is_none()); + click(&mut harness, "Method"); + click(&mut harness, "Generate from Mesh"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.method, CurvatureMethod::Mesh); + assert!(harness.query_by_label("Details").is_none()); + harness.get_by_label("Sampling Radius"); + harness.get_by_label("Value Bounds Min"); + harness.get_by_label("Value Bounds Max"); + click(&mut harness, "Auto Tonemapping"); + assert!(harness.query_by_label("Value Bounds Min").is_none()); + assert!(harness.query_by_label("Value Bounds Max").is_none()); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.mesh.auto_tonemapping); +} + +#[test] +fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.run_steps(3); + assert!(harness.query_by_label("Cage Type").is_none()); + assert!(harness.query_by_label("Skew Correction").is_none()); + harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + harness.run_steps(3); + harness.get_by_label("Max Frontal Distance"); + harness.get_by_label("Skew Correction"); + click(&mut harness, "Cage Type"); + click(&mut harness, "Custom File"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); + harness.get_by_label("Cage Scene"); + assert!(harness.query_by_label("Max Frontal Distance").is_none()); + assert!(harness.query_by_label("Skew Correction").is_none()); +} diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/skew_paint.rs index 891c1f25..8228f1bc 100644 --- a/crates/ui-egui/tests/skew_paint.rs +++ b/crates/ui-egui/tests/skew_paint.rs @@ -7,18 +7,21 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; fn harness() -> Harness<'static, TextureCraftApp> { - let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::BakeSettings); + h.run_steps(3); h } #[test] fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { let mut h = harness(); - h.get_by_label("Skew correction"); + h.get_by_label("Skew Correction"); assert!(h.state().session.bake_meshes.skew.is_none() && !h.state().ui.skew_brush.on); // Off: a drag in the view paints nothing. h.drag_at(egui::pos2(600.0, 500.0)); @@ -28,7 +31,9 @@ fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { assert!(h.state().session.bake_meshes.skew.is_none(), "the brush is off"); // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke. - h.get_by_label("Paint skew in the 2D view").click(); + h.get_by_label("Paint Skew Correction").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Paint Skew Correction").click(); h.run_steps(3); assert!(h.state().ui.skew_brush.on); h.get_by_label("Radius"); @@ -43,7 +48,9 @@ fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); // Removing it from the panel clears the map. - h.get_by_label("Remove skew correction").click(); + h.get_by_label("Remove Skew Correction").scroll_to_me(); + h.run_steps(3); + h.get_by_label("Remove Skew Correction").click(); h.run_steps(3); assert!(h.state().session.bake_meshes.skew.is_none()); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 2f716340..0f42158f 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -1,20 +1,16 @@ -//! Offscreen pictures of the whole window, for checking layout and design without a visible -//! screen (locked machines, CI, agents): +//! Offscreen UI snapshots at 1600x960, except the taller mesh-map panel +//! Requires a GPU adapter //! -//! ```sh -//! TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored -//! ``` -//! -//! Writes `/.png` at 1600x960: the default layout in each brightness, the strip as the -//! app-drawn title bar (Windows) and with the macOS traffic lights' inset, a floating panel and the -//! main windows. Ignored by default: it needs a GPU adapter and takes a few -//! seconds. +//! Run with TC_UI_SNAPSHOTS= cargo test -p texturecraft-ui-egui --release --test ui_snapshots -- --ignored use std::path::{Path, PathBuf}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; use texturecraft_ui_egui::theme::Brightness; use texturecraft_ui_egui::titlebar::TitleBar; @@ -29,80 +25,136 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { #[test] #[ignore] fn window_snapshots() { - let Some(dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); return; }; - std::fs::create_dir_all(&dir).unwrap(); + + std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(1024, 256).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); - for (b, name) in [(Brightness::MediumDark, "main"), (Brightness::Dark, "brightness-dark"), (Brightness::Light, "brightness-light")] { - h.state_mut().ui.prefs.brightness = b; - save(&mut h, &dir, name); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + for (brightness, name) in [(Brightness::MediumDark, "main"), (Brightness::Dark, "brightness-dark"), (Brightness::Light, "brightness-light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, name); } - h.state_mut().ui.prefs.brightness = Brightness::MediumDark; - h.state_mut().title_bar = TitleBar::Integrated; - save(&mut h, &dir, "titlebar-macos"); - h.state_mut().title_bar = TitleBar::App(craft_window::Layout::default()); - save(&mut h, &dir, "titlebar-app"); - // The close button under the pointer, and the glyphs at a fractional scale. - h.hover_at(egui::pos2(1600.0 - 23.0, 14.0)); - save(&mut h, &dir, "titlebar-app-close-hover"); - h.hover_at(egui::pos2(800.0, 500.0)); - h.set_pixels_per_point(1.5); - save(&mut h, &dir, "titlebar-app-150"); - h.set_pixels_per_point(1.0); - h.state_mut().title_bar = TitleBar::System; - h.state_mut().ui.dock.focus(Panel::Display); - save(&mut h, &dir, "panel-display"); - h.state_mut().ui.dock.close(Panel::Display); - h.state_mut().ui.windows.export = true; - save(&mut h, &dir, "window-export"); - h.state_mut().ui.windows.export = false; - h.state_mut().ui.windows.settings = true; - save(&mut h, &dir, "window-settings"); - h.state_mut().ui.windows.settings = false; - // The mesh map slots, each with its menu of images (a tall window shows them all). - h.state_mut().ui.dock.focus(Panel::TextureSetSettings); - h.set_size(egui::vec2(1600.0, 1800.0)); - save(&mut h, &dir, "panel-texture-set-settings"); - h.set_size(egui::vec2(1600.0, 960.0)); - // A mask's levels effect over clouds: the histogram in Properties. - let s = &mut h.state_mut().session; - for (id, p) in [ + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.state_mut().title_bar = TitleBar::Integrated; + save(&mut harness, &output_dir, "titlebar-macos"); + harness.state_mut().title_bar = TitleBar::App(craft_window::Layout::default()); + save(&mut harness, &output_dir, "titlebar-app"); + + // Check hover feedback and fractional scaling + harness.hover_at(egui::pos2(1600.0 - 23.0, 14.0)); + save(&mut harness, &output_dir, "titlebar-app-close-hover"); + harness.hover_at(egui::pos2(800.0, 500.0)); + harness.set_pixels_per_point(1.5); + save(&mut harness, &output_dir, "titlebar-app-150"); + harness.set_pixels_per_point(1.0); + harness.state_mut().title_bar = TitleBar::System; + + for texture_set in &mut harness.state_mut().session.doc.project.texture_sets { + texture_set.bake = Default::default(); + } + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, &output_dir, "mode-bake"); + harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.run_steps(3); + harness.get_by_label("Ambient Occlusion").scroll_to_me(); + save(&mut harness, &output_dir, "mode-bake-maps"); + harness.state_mut().ui.prefs.brightness = Brightness::Light; + save(&mut harness, &output_dir, "mode-bake-maps-light"); + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_label("Opacity").scroll_to_me(); + save(&mut harness, &output_dir, "mode-bake-unchecked"); + harness.state_mut().ui.dock.focus(Panel::TextureSetList); + save(&mut harness, &output_dir, "bake-texture-sets"); + harness.state_mut().ui.dock.focus(Panel::BakeSettings); + save(&mut harness, &output_dir, "bake-settings"); + harness.state_mut().session.add_high_poly_bytes("High Poly.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + save(&mut harness, &output_dir, "bake-settings-high-poly"); + harness.get_by_label("Cage").scroll_to_me(); + save(&mut harness, &output_dir, "bake-settings-cage-skew"); + harness.get_by_label("Edge Contrast").scroll_to_me(); + save(&mut harness, &output_dir, "bake-settings-skew"); + harness.get_by_label("Output Size").scroll_to_me(); + harness.state_mut().session.doc.project.texture_sets[0].bake.common.resolution_height = Some(BakeResolution::R1024); + save(&mut harness, &output_dir, "bake-settings-unlocked"); + harness.set_pixels_per_point(1.5); + save(&mut harness, &output_dir, "bake-settings-150"); + harness.set_pixels_per_point(1.0); + { + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + settings.maps.select([BakedMap::Curvature, BakedMap::Height]); + settings.maps.curvature.parameters.method = CurvatureMethod::Mesh; + settings.maps.height.parameters.normalization = HeightNormalization::Manual; + settings.maps.height.parameters.scaling_divisor = 100.0; + } + harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.run_steps(3); + harness.get_by_label("Curvature").scroll_to_me(); + save(&mut harness, &output_dir, "bake-curvature-mesh"); + harness.get_by_label("Scaling Divisor").scroll_to_me(); + save(&mut harness, &output_dir, "bake-height-manual"); + harness.state_mut().session.bake_meshes.high.clear(); + harness.state_mut().ui.mode = Mode::Painting; + save(&mut harness, &output_dir, "painting-restored"); + + harness.state_mut().ui.dock.focus(Panel::Display); + save(&mut harness, &output_dir, "panel-display"); + harness.state_mut().ui.dock.close(Panel::Display); + harness.state_mut().ui.windows.export = true; + save(&mut harness, &output_dir, "window-export"); + harness.state_mut().ui.windows.export = false; + harness.state_mut().ui.windows.settings = true; + save(&mut harness, &output_dir, "window-settings"); + harness.state_mut().ui.windows.settings = false; + + // A taller window exposes every mesh-map slot + harness.state_mut().ui.dock.focus(Panel::TextureSetSettings); + harness.set_size(egui::vec2(1600.0, 1800.0)); + save(&mut harness, &output_dir, "panel-texture-set-settings"); + harness.set_size(egui::vec2(1600.0, 960.0)); + + // Show the mask histogram in Properties + let session = &mut harness.state_mut().session; + for (id, params) in [ ("layer.add.fill", serde_json::json!({"color": [0.8, 0.3, 0.1]})), ("mask.add.black", serde_json::Value::Null), ("effect.add.fill", serde_json::json!({"target": "mask", "procedural": "clouds"})), ("effect.add.levels", serde_json::json!({"target": "mask", "inLow": 0.3, "inHigh": 0.8})), ] { - texturecraft_engine::execute(s, id, &p).unwrap(); + texturecraft_engine::execute(session, id, ¶ms).unwrap(); } - save(&mut h, &dir, "properties-levels"); - // A path sublayer: its paths listed in Properties, the second one being edited. - let s = &mut h.state_mut().session; - for (id, p) in [ + save(&mut harness, &output_dir, "properties-levels"); + + // Show the second path selected in Properties + let session = &mut harness.state_mut().session; + for (id, params) in [ ("layer.add.paint", serde_json::Value::Null), ("tool.path", serde_json::json!({"uvPoints": [[0.2, 0.5], [0.5, 0.4], [0.8, 0.5]], "commit": true})), ("tool.path", serde_json::json!({"uvPoints": [[0.3, 0.7], [0.7, 0.7], [0.7, 0.9]], "closed": true, "fill": true, "commit": true})), ] { - texturecraft_engine::execute(s, id, &p).unwrap(); + texturecraft_engine::execute(session, id, ¶ms).unwrap(); } - let effect = match s.target { + + let effect = match session.target { texturecraft_engine::StackTarget::Effect(e) => e.0, _ => 0, }; - texturecraft_engine::execute(s, "path.edit", &serde_json::json!({"effect": effect, "index": 1})).unwrap(); - save(&mut h, &dir, "properties-paths"); - // Ctrl+right drag in the 3D view: the brush cursor where it began and the readout. - let c = h.state().viewport_rect.center(); - let (m, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); - h.event(egui::Event::ModifiersChanged(m)); - h.event(egui::Event::PointerButton { pos: c, button, pressed: true, modifiers: m }); - for k in 1..=4 { - h.hover_at(c + egui::vec2(15.0 * k as f32, -8.0 * k as f32)); - h.run_steps(1); + texturecraft_engine::execute(session, "path.edit", &serde_json::json!({"effect": effect, "index": 1})).unwrap(); + save(&mut harness, &output_dir, "properties-paths"); + + // Show the brush cursor and readout during Ctrl+right drag + let cursor_position = harness.state().viewport_rect.center(); + let (modifiers, button) = (egui::Modifiers::COMMAND, egui::PointerButton::Secondary); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: true, modifiers }); + for step in 1..=4 { + harness.hover_at(cursor_position + egui::vec2(15.0 * step as f32, -8.0 * step as f32)); + harness.run_steps(1); } - save(&mut h, &dir, "brush-ctrl-drag"); - h.event(egui::Event::PointerButton { pos: c, button, pressed: false, modifiers: m }); - h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + save(&mut harness, &output_dir, "brush-ctrl-drag"); + harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: false, modifiers }); + harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } diff --git a/pr-review-guidelines.md b/pr-review-guidelines.md new file mode 100644 index 00000000..eebcb242 --- /dev/null +++ b/pr-review-guidelines.md @@ -0,0 +1,68 @@ +# My PR review standards + +Review and improve the PR using these preferences. Follow the repository's instructions and keep changes focused on the problem being solved. + +## Correctness + +- Verify the claimed fix against the actual code and its callers +- Look for missed edge cases, incomplete fixes, and regressions +- Reproduce suspicious behavior locally when practical +- Make regression tests fail before the fix and pass afterward +- Confirm tests exercise the intended path, especially fallbacks and error handling + +## Optimization and simplicity + +- Prefer the smallest complete solution that is efficient and easy to understand +- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost +- Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads +- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations +- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity + +## Clarity, naming, and spacing + +- Clean up the methods being changed, including their tests +- Use descriptive names that explain purpose; include units where useful +- Avoid cryptic abbreviations, misleading names, and unexplained production constants +- Keep control flow direct and share repeated logic when it makes the code simpler +- Separate logical steps with sensible blank lines so code is easy to scan +- Put a blank line after a multiline `let ... else` guard before the next statement; never place the next `let` directly after its closing `};` +- Keep related statements together and follow the repository's formatter + +## Source organization + +- Keep each class, enum, or struct in its own source file, with its implementation beside it +- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust +- Use singular folder names, such as `map`, `setting`, or `tracing` +- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file + +## Comments + +- Use short, single-line comments or concise adjacent comments +- Avoid block comments and prose wrapped across multiple comment lines +- Explain intent or a non-obvious constraint rather than narrating the code +- No trailing punctuation on ordinary code comments +- Avoid overexplaining and remove stale or redundant comments +- Apply these standards to both production code and tests + +## Validation and reporting + +- Run relevant tests and required repository checks with the project's expected toolchain +- For comments or spacing alone, verify formatting and that executable code is unchanged +- Report concrete findings with locations, reproduction details, and practical impact +- Separate confirmed problems from hypotheses and optional improvements +- Give measured optimization results with workload and environment details +- State remaining limitations and distinguish existing failures from new ones + +## Review and commit workflow + +- Preserve unrelated work and leave changes unstaged for my manual review unless I ask otherwise +- Stage only when requested +- Wait for my explicit commit command before committing +- Do not push or post reviews or comments without explicit instructions +- When requested, provide a simple ready-to-post Markdown summary outside the repository and exclude it from the commit + +## Scope of method fixes + +- Whenever a method needs a fix, apply all of my review standards across the entire method, including existing code outside the immediate fix +- Ensure the whole method has sensible spacing between logical steps and concise, useful comments that follow the standards above From 18a3c98176743a3b9ed5c6188363fc00a2e35c7f Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 03:55:50 -0500 Subject: [PATCH 015/275] Implement clean-room bake settings and improve map accuracy --- ROADMAP.md | 11 +- crates/bake/README.md | 78 ++-- .../{skew/skew_map.rs => bake_paint_map.rs} | 43 +- crates/bake/src/bake_request.rs | 9 +- crates/bake/src/high_poly.rs | 1 + crates/bake/src/lib.rs | 72 +++- crates/bake/src/map.rs | 7 + crates/bake/src/map/bake_context.rs | 145 ++++--- crates/bake/src/map/curvature.rs | 79 ++-- crates/bake/src/map/diffusion.rs | 89 ++++ crates/bake/src/map/normal_curvature.rs | 30 +- crates/bake/src/map/normalization.rs | 91 +++++ crates/bake/src/map/position_projection.rs | 45 ++ crates/bake/src/map/sampling.rs | 2 +- crates/bake/src/map/seam.rs | 64 +++ crates/bake/src/map/source.rs | 79 +++- crates/bake/src/skew.rs | 62 +-- crates/bake/src/skew/prepared_skew.rs | 29 +- crates/bake/src/test/setting.rs | 199 +++++++++ crates/bake/src/tests.rs | 196 +++++++-- crates/bake/src/tracing/cpu_scene.rs | 13 +- crates/bake/src/tracing/hemisphere.rs | 52 ++- crates/bake/src/tracing/ray_scene.rs | 2 +- crates/bake/src/tracing/trace_mesh.rs | 1 + crates/compose/src/display.rs | 4 +- crates/compose/src/eval.rs | 4 +- crates/compose/src/store.rs | 28 +- crates/core/src/bake.rs | 6 + crates/core/src/bake/bake_paint_target.rs | 8 + crates/core/src/bake/high_poly_settings.rs | 3 + .../core/src/bake/mesh_curvature_settings.rs | 2 +- crates/core/src/bake/mesh_match_mode.rs | 8 + crates/core/src/bake/position_mode.rs | 2 +- .../core/src/bake/skew_correction_method.rs | 8 + crates/core/src/bake/skew_settings.rs | 4 +- crates/core/src/lib.rs | 9 +- crates/core/tests/bake_settings.rs | 8 +- crates/engine/src/bake/bake_mesh.rs | 12 + crates/engine/src/bake/bake_meshes.rs | 29 ++ crates/engine/src/bake/bake_task.rs | 49 +++ crates/engine/src/bake/merged_high.rs | 11 + crates/engine/src/bake/mod.rs | 11 + crates/engine/src/bake_cmds.rs | 383 ++++++------------ crates/engine/src/bake_paint_cmds.rs | 147 +++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/file_cmds.rs | 7 +- crates/engine/src/lib.rs | 5 +- crates/engine/src/material_lib.rs | 6 +- crates/engine/src/meshmap_cmds.rs | 5 +- crates/engine/src/session.rs | 7 +- crates/engine/src/uv_tile_cmds.rs | 96 ++++- crates/engine/tests/bake.rs | 102 ++++- crates/engine/tests/painter_gaps.rs | 4 +- crates/formats/src/export/mod.rs | 2 +- crates/formats/src/lib.rs | 2 +- crates/formats/src/mesh_import/fbx.rs | 10 +- crates/formats/src/mesh_import/scene_tests.rs | 17 + .../src/project_file/bake_paint_data.rs | 6 + crates/formats/src/project_file/mod.rs | 88 ++-- crates/formats/src/project_file/tests.rs | 5 +- crates/render/src/gpu_bake.rs | 75 +++- crates/render/src/mesh_maps.rs | 5 +- crates/render/src/shaders/bake.wgsl | 40 +- crates/texel/src/dilate.rs | 32 +- crates/ui-egui/src/bake_mode.rs | 2 + .../ui-egui/src/bake_mode/bake_paint_brush.rs | 17 + .../ui-egui/src/bake_mode/common_settings.rs | 57 ++- crates/ui-egui/src/bake_mode/map_settings.rs | 2 +- crates/ui-egui/src/i18n/ar.rs | 6 + crates/ui-egui/src/i18n/de.rs | 6 + crates/ui-egui/src/i18n/es.rs | 6 + crates/ui-egui/src/i18n/fr.rs | 6 + crates/ui-egui/src/i18n/it.rs | 6 + crates/ui-egui/src/i18n/ja.rs | 6 + crates/ui-egui/src/i18n/ko.rs | 6 + crates/ui-egui/src/i18n/pt_br.rs | 6 + crates/ui-egui/src/i18n/zh_hans.rs | 6 + crates/ui-egui/src/state.rs | 20 +- crates/ui-egui/src/viewport.rs | 56 +-- crates/ui-egui/tests/bake_mode.rs | 6 +- crates/ui-egui/tests/skew_paint.rs | 12 +- 81 files changed, 2105 insertions(+), 771 deletions(-) rename crates/bake/src/{skew/skew_map.rs => bake_paint_map.rs} (74%) create mode 100644 crates/bake/src/map/diffusion.rs create mode 100644 crates/bake/src/map/normalization.rs create mode 100644 crates/bake/src/map/position_projection.rs create mode 100644 crates/bake/src/map/seam.rs create mode 100644 crates/bake/src/test/setting.rs create mode 100644 crates/core/src/bake/bake_paint_target.rs create mode 100644 crates/core/src/bake/mesh_match_mode.rs create mode 100644 crates/core/src/bake/skew_correction_method.rs create mode 100644 crates/engine/src/bake/bake_mesh.rs create mode 100644 crates/engine/src/bake/bake_meshes.rs create mode 100644 crates/engine/src/bake/bake_task.rs create mode 100644 crates/engine/src/bake/merged_high.rs create mode 100644 crates/engine/src/bake/mod.rs create mode 100644 crates/engine/src/bake_paint_cmds.rs create mode 100644 crates/formats/src/project_file/bake_paint_data.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_paint_brush.rs diff --git a/ROADMAP.md b/ROADMAP.md index 4bb4209b..654f5c35 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing wor performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and builds for Windows, macOS, Linux, FreeBSD and the web. -## Honest parity estimate (2026-11-02) +## Honest parity estimate (2026-11-04) Weighted by how much of a professional's daily work each area carries. "Done" counts what works end to end today (engine + UI + automation + tests), not what is planned. @@ -16,13 +16,16 @@ end to end today (engine + UI + automation + tests), not what is planned. | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | Partial | AO, curvature (also from the normal map), thickness, world normal, position, ID, normal, height, **bent normals and opacity**; **high-poly meshes**, cage, frontal/rear distances, average normals, **skew correction** (`bake.skew.set`, painted in the 2D view with `bake.skew.paint` and saved in the project: a greyscale map over the atlas that turns the transfer rays onto the base normal, with hard-edge protection); per-texture-set selection, common and per-map parameters, progress and cancel; **mesh maps from images** (baked elsewhere or edited) dropped on a slot; high-poly base color textures embedded or in files beside a `.gltf`, FBX or USD layer | Reference settings have typed, persistent controls in left-hand Texture Sets / Settings / Bake Maps tabs, numeric limits and section resets; added baker behavior and Paint Cage remain pending | +| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | | Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | | Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | | Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | | UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | | Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **Under review** | Baking parity is being reassessed | | +| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | | + +Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation +paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified. Beyond the reference app: every command is available to agents through MCP, the CLI and the app's control channel (MCP workspace tools cover every file action: projects, meshes, high polys and @@ -38,7 +41,7 @@ parallel on separate crates: | M1 Layer stack depth | Done | 0 h | | M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h | | M3 Assets | Done | 0 h | -| M4 Baking | Integrate the reference settings with commands, UI and baking | TBD | +| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD | | M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h | | M6 Shader | Done | 0 h | | M7 Formats | Done | 0 h | diff --git a/crates/bake/README.md b/crates/bake/README.md index da72f0d3..0eac65cc 100644 --- a/crates/bake/README.md +++ b/crates/bake/README.md @@ -1,63 +1,41 @@ # texturecraft-bake -Mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (usually 0..1, rows top → bottom), supersampled, padded and deterministic. The supersamples are processed in batches: their high-poly transfer rays, then the secondary rays of ambient occlusion, bent normals and thickness go to a `tracing::Tracer`, then all requested maps are evaluated per sample (rayon over rows). +Clean-room mesh-map baking from low-poly UVs and optional high-poly meshes. Persisted settings live in `texturecraft-core`; localized controls live in `texturecraft-ui-egui`. Types have individual files, with singular module folders. -The rays run on the CPU (`tracing::CpuTracer`, the oracle) or, through `bake_on(&BakeRequest, &Progress, &dyn Tracer)`, on a GPU tracer (the render crate's `gpu_bake::GpuBaker`, wgpu compute shaders on the path tracer's BVH traversal). The GPU receives the same rays and per-sample rotations and casts the same secondary-ray directions, so both agree up to float rounding; when the tracer fails (no adapter, a mesh too large for it, a lost device) `bake_on` bakes again on the CPU. `BakeOutput::tracer` says where the rays ran. +`bake(&BakeRequest, &Progress)` runs the CPU oracle. `bake_on` accepts a `tracing::Tracer` such as the render crate's GPU baker, and retries on the CPU if that tracer fails. Both receive identical transfer rays and secondary-ray samples. Output is deterministic, floating point, and stored in rows from top to bottom. Cancellation is checked between bounded batches and before returning the result. -With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. Every map then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly). +## Projection and common settings -Ambient occlusion, thickness and bent normals each have their own `RaySettings`: ray count, max distance (relative to the bounding-box diagonal), spread angle (the full cone around the normal; 180° = the hemisphere) and distribution (cosine-weighted or uniform over the cone). Ambient occlusion can ignore back faces and limit occluders to parts of the same mesh name (`SelfOcclusion::SameMeshName`); bent normals follow those occluder rules and share the AO rays when their settings match. +- Independent output width and height, antialiasing, per-UV-tile dilation, and optional background diffusion +- High-to-low matching: Always by default, or By Mesh Name using the configured low/high suffixes +- Transfer-ray backface filtering, distance-based or custom-file cages, frontal/rear distances, and averaged normals +- Relative distances use the longest bounding-box extent; absolute distances use imported mesh units +- Painted cage values multiply the frontal distance; painted skew values blend toward mesh or face normals, with optional hard-edge protection -| Map | Meaning | Range | -| --- | --- | --- | -| Ambient occlusion | How open the surface is (rays over the cone, distance falloff) | 0 occluded … 1 open | -| Bent normals | Mean unoccluded direction of the bent-normal rays, world space | packed ·0.5+0.5 | -| Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick | -| Curvature | Short-ray mesh curvature, or (`CurvatureMethod::NormalMap`) the divergence of the baked normal map over a texel radius derived from the output resolution | 0 concave … 0.5 flat … 1 convex | -| Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 | -| Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front | -| World normal | Shading normal in world space | packed ·0.5+0.5 | -| Position | Bounding-box or bounding-sphere normalization; None preserves mesh coordinates | 0 … 1, or mesh units for None | -| ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 | -| Opacity | 1 where the high poly was found (times its vertex and base color alpha), 0 where the ray missed | 0 … 1 | +`BakePaintMap` contains pixel data only. Cage and skew settings remain in their respective model containers. The engine stores paint maps per texture set in document snapshots and project files. The shared 2D brush supports undo, redo, reset, and UV-layout changes. -Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmarks (2K, the 7 default maps at 64 rays): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench` (CPU, per-map breakdown) and `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed` (CPU vs GPU). +## Map settings -## Settings model +| Map | Implemented behavior | +| --- | --- | +| Normal | Tangent-space high-poly normal, internally OpenGL; flat without a high-poly transfer | +| World Normal | World-space shading normal | +| ID | Vertex Color, Material Color, Mesh ID, Submesh ID, or File ID; Hue Shift, Random, and Grayscale generation | +| Ambient Occlusion | Independent ray count, distance interval, units, cone and distribution; backface and self-occlusion modes; None, Linear or Smooth attenuation; optional ground plane | +| Bent Normal | Independent occlusion settings and mean visible direction, encoded in world space | +| Thickness | Inward ray distances with self-occlusion filtering; raw, ray-distance or per-UV-tile min/max normalization | +| Curvature | Mesh-ray curvature with radius, ray count, self-intersection and automatic/manual tonemapping; normal-map curvature with detail strength and corresponding UV-edge seam blending | +| Position | All axes or a selected axis; scene or material bounds; box, uniform sphere-style or raw coordinates | +| Height | Signed high-poly displacement with low-mesh, min/max, ray-distance or manual normalization | +| Opacity | High-poly hit coverage multiplied by source vertex/material/texture alpha | -The clean-room `core::BakeSettings` model contains separate common, high-poly, cage, skew and per-map -settings containers. Each map uses `MapSettings` to keep `is_enabled` beside its typed -parameters; bake selection and UI control visibility read that same flag. Curvature groups its method-specific settings; -AO groups its ground-plane settings. Each container owns its defaults. New projects use the reference defaults: 2048 square output, dilation 1, 64 AO / -thickness / bent-normal rays, curvature from the normal map, and bounding-sphere position -normalization. Old project representations are not preserved. +ID Material Color reads the material factor independently of textures and vertex colors. A source without material colors uses neutral gray (0.6). Generated IDs are deterministic. Normal maps are stored in OpenGL convention; display/export apply the project's normal format. -New model options include rectangular output (`common.resolution_height: None` locks the axes), -diffusion, high-poly backface filtering and suffix, cage distance units, skew edge protection, -ID source/generator, minimum occluder distance and ray units, AO attenuation/ground plane, -independent bent-normal and thickness occlusion, both curvature methods' detailed controls, -position axis/scope/no-normalization, and thickness/height normalization. AO backface handling -and position normalization each use one enum field. Curvature methods also store named -choices (`NormalMap`/`Mesh`). All dropdowns use enums, -including resolution and antialiasing. Map display labels belong to the localized UI; the -model contains identities and values. `BakedMap::id()` uses the shared MaterialCraft mesh-map -identifiers in commands, project entries and mesh-map exports; `BakedMap::parse()` is their -single parser. +All dropdowns use enums. `BakedMap::id()` and `BakedMap::parse()` provide the shared MaterialCraft mesh-map identifiers. `bake.settings` accepts the complete nested model. No legacy Color or World Orientation map migration is provided. -Bake Mode exposes the model through Texture Sets, Settings and Bake Maps tabs on the left, -with collapsible sections, conditional controls, reference numeric ranges, section resets, and a lockable -output-size pair. Paint and Bake Mode keep separate panel layouts; texture sets use visibility -buttons in Paint Mode and bake-inclusion checkboxes in Bake Mode. -`bake.settings` accepts the complete nested model; edits persist with the project. -Algorithm integration for the added options remains a subsequent stage, including by-mesh-name -backface filtering. Paint Cage is a disabled placeholder. The current command path preserves -the full AO backface and position enums; position None returns mesh coordinates. -The algorithms described above still apply. Color map and World space direction have been -removed without legacy-map migration. +## Validation and limits -## Code organization +Regression tests cover projection, matching, ray filters, normalization, rectangular maps, painting, persistence, and CPU/GPU agreement. The supplied 2048² high-to-low reference is evaluated separately, outside the repository, on UV-covered pixels. Numerical differences remain, especially in curvature and occlusion; exact Painter parity is not claimed. Painted cage control currently uses the 2D UV brush; it does not provide a 3D cage-editing overlay. -Types and their implementations live in individual files named after the full type. Module -folders are singular (`map`, `tracing`, `skew`). Shared sampling and ray-setting logic has one -implementation. Persisted settings live in `core`; Bake Mode controls and localized labels -live in `ui-egui`. The baker has no localization dependency. +CPU benchmark: `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`. +GPU comparison: `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture gpu_bake_speed`. diff --git a/crates/bake/src/skew/skew_map.rs b/crates/bake/src/bake_paint_map.rs similarity index 74% rename from crates/bake/src/skew/skew_map.rs rename to crates/bake/src/bake_paint_map.rs index be6a7bcc..cf6f0b4d 100644 --- a/crates/bake/src/skew/skew_map.rs +++ b/crates/bake/src/bake_paint_map.rs @@ -7,54 +7,49 @@ pub const MAX_DABS: usize = 200_000; pub const MAX_PAINT_TEXELS: u64 = 1 << 26; #[derive(Clone, Debug, PartialEq)] -pub struct SkewMap { +pub struct BakePaintMap { pub width: u32, pub height: u32, - /// Atlas values: 0 keeps the cage direction; 1 uses the base normal + /// Values in 0..=1 over the texture set UV atlas pub values: Vec, - pub edge_distance: f32, - pub edge_contrast: f32, } -impl SkewMap { - pub fn constant(value: f32) -> SkewMap { - SkewMap { width: 1, height: 1, values: vec![value], edge_distance: 0.0, edge_contrast: 1.0 } +impl BakePaintMap { + pub fn constant(value: f32) -> BakePaintMap { + BakePaintMap { width: 1, height: 1, values: vec![value] } } pub fn validate(&self) -> Result<(), BakeError> { let invalid = |m: &str| Err(BakeError::Invalid(m.into())); let texels = u64::from(self.width) * u64::from(self.height); if self.width == 0 || self.height == 0 || texels > MAX_TEXELS || self.values.len() as u64 != texels { - return invalid("the skew map's size doesn't match its values"); - } - if !(self.edge_distance.is_finite() && self.edge_distance >= 0.0 && self.edge_contrast.is_finite() && self.edge_contrast > 0.0) { - return invalid("the skew edge distance must be 0 or more and the contrast above 0"); + return invalid("the bake paint map's size doesn't match its values"); } if self.values.iter().any(|v| !v.is_finite()) { - return invalid("the skew map has a value that is not a finite number"); + return invalid("the bake paint map has a value that is not a finite number"); } Ok(()) } - pub fn resized(&self, width: u32, height: u32) -> Result { + pub fn resized(&self, width: u32, height: u32) -> Result { let texels = u64::from(width) * u64::from(height); if width == 0 || height == 0 || texels > MAX_TEXELS { - return Err(BakeError::Invalid(format!("a {width} × {height} skew map is outside the supported size"))); + return Err(BakeError::Invalid(format!("a {width} × {height} bake paint map is outside the supported size"))); } let mut values = Vec::with_capacity(texels as usize); for y in 0..height { - let v = 1.0 - (y as f32 + 0.5) / height as f32; + let v = (y as f32 + 0.5) / height as f32; for x in 0..width { - values.push(self.at(Vec2::new((x as f32 + 0.5) / width as f32, v))); + values.push(self.sample(Vec2::new((x as f32 + 0.5) / width as f32, v))); } } - Ok(SkewMap { width, height, values, ..self.clone() }) + Ok(BakePaintMap { width, height, values }) } pub fn paint(&mut self, points: &[Vec2], radius: f32, value: f32, hardness: f32, strength: f32) -> Result<(), BakeError> { let ok = radius.is_finite() && radius > 0.0 && value.is_finite() && hardness.is_finite() && strength.is_finite(); if !ok || points.iter().any(|p| !p.is_finite()) { - return Err(BakeError::Invalid("the skew brush needs finite numbers and a radius above 0".into())); + return Err(BakeError::Invalid("the bake brush needs finite numbers and a radius above 0".into())); } self.validate()?; let (value, hardness, strength) = (value.clamp(0.0, 1.0), hardness.clamp(0.0, 0.999), strength.clamp(0.0, 1.0)); @@ -69,15 +64,15 @@ impl SkewMap { None => dabs.push(*p), } if dabs.len() > MAX_DABS { - return Err(BakeError::Invalid(format!("a skew stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); + return Err(BakeError::Invalid(format!("a bake stroke is limited to {MAX_DABS} dabs; use a larger radius or fewer points"))); } } let (w, h) = (self.width as usize, self.height as usize); let span = |c: Vec2| { let x0 = (((c.x - radius) * w as f32).floor().max(0.0)) as usize; let x1 = (((c.x + radius) * w as f32).ceil().min(w as f32)).max(0.0) as usize; - let y0 = ((((1.0 - c.y) - radius) * h as f32).floor().max(0.0)) as usize; - let y1 = ((((1.0 - c.y) + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; + let y0 = (((c.y - radius) * h as f32).floor().max(0.0)) as usize; + let y1 = (((c.y + radius) * h as f32).ceil().min(h as f32)).max(0.0) as usize; (x0, x1, y0, y1) }; let work: u64 = dabs @@ -95,7 +90,7 @@ impl SkewMap { for c in dabs { let (x0, x1, y0, y1) = span(c); for y in y0..y1 { - let dv = (1.0 - (y as f32 + 0.5) / h as f32) - c.y; + let dv = (y as f32 + 0.5) / h as f32 - c.y; for x in x0..x1 { let du = (x as f32 + 0.5) / w as f32 - c.x; let t = (du * du + dv * dv).sqrt() / radius; @@ -117,13 +112,13 @@ impl SkewMap { Ok(()) } - pub(crate) fn at(&self, uv: Vec2) -> f32 { + pub fn sample(&self, uv: Vec2) -> f32 { let (w, h) = (self.width.max(1) as usize, self.height.max(1) as usize); if !uv.is_finite() { return 0.0; } let x = (uv.x.clamp(0.0, 1.0) * w as f32 - 0.5).clamp(0.0, w as f32 - 1.0); - let y = ((1.0 - uv.y).clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); + let y = (uv.y.clamp(0.0, 1.0) * h as f32 - 0.5).clamp(0.0, h as f32 - 1.0); let (x0, y0) = (x.floor() as usize, y.floor() as usize); let (x1, y1) = ((x0 + 1).min(w - 1), (y0 + 1).min(h - 1)); let (fx, fy) = (x - x0 as f32, y - y0 as f32); diff --git a/crates/bake/src/bake_request.rs b/crates/bake/src/bake_request.rs index 22919aa3..69925325 100644 --- a/crates/bake/src/bake_request.rs +++ b/crates/bake/src/bake_request.rs @@ -1,16 +1,19 @@ -use crate::{HighPoly, SkewMap}; +use crate::{BakePaintMap, HighPoly}; +use std::sync::Arc; use texturecraft_core::BakeSettings; -use texturecraft_geom::{Bvh, Mesh}; +use texturecraft_geom::{BaseColor, Bvh, Mesh}; #[derive(Clone, Copy, Debug)] pub struct BakeRequest<'a> { pub mesh: &'a Mesh, pub bvh: &'a Bvh, pub material: usize, + pub low_base_color: &'a [Option>], pub settings: &'a BakeSettings, pub high: Option>, pub cage: Option<&'a Mesh>, - pub skew: Option<&'a SkewMap>, + pub skew: Option<&'a BakePaintMap>, + pub cage_paint: Option<&'a BakePaintMap>, /// UV atlas grid; each tile uses the configured output resolution pub tiles: (u32, u32), } diff --git a/crates/bake/src/high_poly.rs b/crates/bake/src/high_poly.rs index 5c59ee0e..9901f0e7 100644 --- a/crates/bake/src/high_poly.rs +++ b/crates/bake/src/high_poly.rs @@ -3,6 +3,7 @@ use texturecraft_geom::{BaseColor, Bvh, Mesh}; #[derive(Clone, Copy, Debug)] pub struct HighPoly<'a> { + pub file_ids: &'a [u32], pub mesh: &'a Mesh, pub bvh: &'a Bvh, pub base_color: &'a [Option>], diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 18742e90..0b315cdb 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -30,8 +30,9 @@ use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; use texturecraft_texel::DilationMap; -pub use crate::skew::SkewMap; +mod bake_paint_map; use crate::tracing::{CpuTracer, RayScene, Tracer}; +pub use bake_paint_map::BakePaintMap; pub const MAX_RESOLUTION: u32 = 8192; pub const MAX_RAYS: u32 = 4096; @@ -45,11 +46,11 @@ const CURVATURE_BATCH: usize = 1 << 15; fn validate(request: &BakeRequest) -> Result<(), BakeError> { let settings = request.settings; let invalid = |message: String| Err(BakeError::Invalid(message)); - let resolution = settings.common.resolution.pixels(); + let (resolution, resolution_height) = settings.common.output_size(); let (columns, rows) = request.tiles; let width = u64::from(resolution) * u64::from(columns); - let height = u64::from(resolution) * u64::from(rows); + let height = u64::from(resolution_height) * u64::from(rows); if columns == 0 || rows == 0 || width.saturating_mul(height) > MAX_TEXELS { return invalid(format!("{columns} × {rows} UV tiles at {} exceed {MAX_TEXELS} texels", resolution)); } @@ -71,7 +72,10 @@ fn validate(request: &BakeRequest) -> Result<(), BakeError> { return invalid(format!("{} max distance {} must be positive", map.id(), ray_settings.max_distance)); } - if !ray_settings.spread.is_finite() { + if !(ray_settings.min_distance.is_finite() && ray_settings.min_distance >= 0.0 && ray_settings.min_distance <= ray_settings.max_distance) { + return invalid(format!("{} minimum distance must be finite and between zero and its maximum distance", map.id())); + } + if !ray_settings.spread.is_finite() || !(0.0..=180.0).contains(&ray_settings.spread) { return invalid(format!("{} spread angle is not finite", map.id())); } } @@ -79,6 +83,36 @@ fn validate(request: &BakeRequest) -> Result<(), BakeError> { if !(settings.cage.max_frontal.is_finite() && settings.cage.max_frontal >= 0.0 && settings.cage.max_rear.is_finite() && settings.cage.max_rear >= 0.0) { return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", settings.cage.max_frontal, settings.cage.max_rear)); } + let curvature = settings.maps.curvature.parameters; + if settings.maps.curvature.is_enabled { + if curvature.mesh.rays == 0 || curvature.mesh.rays > MAX_RAYS || !curvature.mesh.sampling_radius.is_finite() || curvature.mesh.sampling_radius <= 0.0 { + return invalid("curvature requires a positive finite radius and a supported ray count".into()); + } + if !curvature.mesh.value_min.is_finite() + || !curvature.mesh.value_max.is_finite() + || (!curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max) + { + return invalid("curvature bounds must be finite, with minimum below maximum".into()); + } + } + for (name, value) in [ + ("edge distance", settings.skew.edge_distance), + ("edge contrast", settings.skew.edge_contrast), + ("curvature details", curvature.normal_map.details), + ("seam intensity", curvature.normal_map.seams_intensity), + ] { + if !value.is_finite() || !(0.0..=1.0).contains(&value) { + return invalid(format!("{name} must be finite and in 0..=1")); + } + } + if settings.maps.height.is_enabled + && (!settings.maps.height.parameters.scaling_divisor.is_finite() || settings.maps.height.parameters.scaling_divisor <= 0.0) + { + return invalid("height scaling divisor must be finite and positive".into()); + } + if !settings.maps.ao.parameters.ground_plane.offset.is_finite() || settings.maps.ao.parameters.ground_plane.offset < 0.0 { + return invalid("ground plane offset must be finite and nonnegative".into()); + } request.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?; if request.material >= request.mesh.materials.len().max(1) { return invalid(format!("material {} out of range ({} materials)", request.material, request.mesh.materials.len())); @@ -88,6 +122,9 @@ fn validate(request: &BakeRequest) -> Result<(), BakeError> { high.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?; } + if let Some(map) = request.cage_paint { + map.validate()?; + } if let Some(cage) = request.cage { cage.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?; if cage.indices.len() != request.mesh.indices.len() { @@ -126,8 +163,10 @@ type OutRow<'a> = Vec<&'a mut [f32]>; fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { validate(request)?; let settings = request.settings; - let (tile_resolution, samples_per_axis) = (settings.common.resolution.pixels() as usize, settings.common.antialiasing.samples_per_axis() as usize); - let (width, height) = (tile_resolution * request.tiles.0 as usize, tile_resolution * request.tiles.1 as usize); + let (tile_width, tile_height) = settings.common.output_size(); + let tile_size = (tile_width as usize, tile_height as usize); + let samples_per_axis = settings.common.antialiasing.samples_per_axis() as usize; + let (width, height) = (tile_size.0 * request.tiles.0 as usize, tile_size.1 * request.tiles.1 as usize); let context = map::BakeContext::new(request)?; let tracer = if context.casts_rays() { tracer } else { &CpuTracer }; let meshes = context.trace_meshes(); @@ -203,10 +242,11 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz } Ok(()) }; - if strip_start + rows < height || settings.common.dilation == 0 { + if strip_start + rows < height || (settings.common.dilation == 0 && !settings.common.apply_diffusion) { bake_strip()?; } else { - let padding = || DilationMap::in_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), settings.common.resolution.pixels()); + let padding = + || DilationMap::in_rectangular_blocks(&covered, width as u32, height as u32, Some(settings.common.dilation), (tile_width, tile_height)); let (padding, baked) = rayon::join(padding, bake_strip); baked?; padding_map = Some(padding); @@ -217,14 +257,26 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz if from_normal { let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) }; if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) { - map::curvature_from_normal(&normal, &covered, width, tile_resolution, curvature_pixels); + let parameters = settings.maps.curvature.parameters.normal_map; + map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels); + if parameters.enable_seams { + map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels); + } } } + let (bounds_min, bounds_max) = request.mesh.bounds(); + map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); if let Some(padding_map) = padding_map { for (map, data) in output.iter_mut() { padding_map.apply(data, map.components()); + if settings.common.apply_diffusion { + map::diffuse(data, map.components(), &padding_map, tile_size); + } } } + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } progress.done.store(10_000, Relaxed); Ok(BakeOutput { resolution: width as u32, height: height as u32, maps: output, tracer: tracer.name() }) } @@ -273,7 +325,7 @@ fn bake_rows( let transfers = match context.has_high() { true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); - let hits = scene.closest(1, &rays)?; + let hits = scene.closest(1, &rays, context.ignore_transfer_backface())?; hits.into_par_iter().zip(frontal_distances).map(|(hit, front)| context.transfer(hit, front)).collect() } false => Vec::new(), diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 30bb29d0..9638a140 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -1,8 +1,15 @@ mod bake_context; mod curvature; mod curvature_tuning; +mod diffusion; mod normal_curvature; +mod normalization; +pub(crate) use diffusion::diffuse; +pub(crate) use normalization::normalize; mod sample; +mod seam; +pub(crate) use seam::fix_seams; +mod position_projection; mod sampling; mod source; mod traced; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index c359350f..21fed094 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,12 +1,14 @@ -use super::curvature::{Curvature, RAYS_PER_RING, RING_COUNT}; -use super::sampling::{interpolate, material_color, pack, splitmix64, tangent_normal, welded}; -use super::{source::Source, traced::Traced, transfer::Transfer}; +use super::curvature::Curvature; +use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; use crate::skew::PreparedSkew; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest}; use rayon::prelude::*; use std::collections::HashMap; -use texturecraft_core::{BackfaceMode, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion}; +use texturecraft_core::{ + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, +}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; @@ -17,13 +19,13 @@ pub(crate) struct BakeContext<'a> { high: Option>, cage: Option<&'a Mesh>, skew: Option>, + cage_paint: Option<&'a crate::BakePaintMap>, ray_normals: Vec, - lo: Vec3, - extent: Vec3, + settings: &'a BakeSettings, eps: f32, frontal: f32, rear: f32, - position_mode: PositionMode, + position: PositionProjection, curvature_method: CurvatureMethod, curvature: Curvature, pub ao: Option, @@ -40,10 +42,20 @@ impl<'a> BakeContext<'a> { return Err(BakeError::Invalid("mesh bounds are too large".into())); } + let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, &[], &settings.high_poly.low_suffix, &mut name_keys); - let high = - request.high.map(|high_mesh| Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, &settings.high_poly.high_suffix, &mut name_keys)); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new( + high_mesh.mesh, + high_mesh.bvh, + high_mesh.base_color, + high_mesh.file_ids, + &settings.high_poly.high_suffix, + &settings.high_poly, + &mut name_keys, + ) + }); let ray_normals = match settings.cage.average_normals && high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); @@ -52,44 +64,69 @@ impl<'a> BakeContext<'a> { false => Vec::new(), }; - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_diagonal)).transpose()?; - let ray_epsilon = 1e-4 * mesh_diagonal; + let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; + let ray_epsilon = 1e-6 * mesh_diagonal; let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); - let occlusion = kind == RayKind::Occlusion; + let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; settings.maps.is_enabled(map).then_some(Hemisphere { kind, rays: ray_settings.rays, - dmax: ray_settings.max_distance * mesh_diagonal, + dmax: ray_settings.max_distance * units, + min_distance: ray_settings.min_distance * units, + attenuation: AmbientOcclusionAttenuation::None, + ground_height: None, eps: ray_epsilon, cos_max: half_angle_radians.cos(), sin_max: half_angle_radians.sin(), uniform: ray_settings.distribution == RayDistribution::Uniform, - ignore_backface: occlusion && settings.maps.ao.parameters.ignore_backface != BackfaceMode::Never, - same_key: occlusion && settings.maps.ao.parameters.self_occlusion == SelfOcclusion::SameMeshName, + ignore_backface: BackfaceMode::Never, + same_key: false, }) }; + let mut ao = pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion); + if let Some(pass) = &mut ao { + let parameters = settings.maps.ao.parameters; + pass.ignore_backface = parameters.ignore_backface; + pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; + pass.attenuation = parameters.attenuation; + pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); + if let Some(pass) = &mut bent { + pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; + pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; + } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); + if let Some(pass) = &mut thickness { + pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; + } + let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; Ok(BakeContext { low, high, - cage: request.cage, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, skew, + cage_paint: request.cage_paint, ray_normals, - lo: bounds_min, - extent: bounds_max - bounds_min, + settings, eps: ray_epsilon, - frontal: settings.cage.max_frontal * mesh_diagonal, - rear: settings.cage.max_rear * mesh_diagonal, - position_mode: settings.maps.position.parameters.normalization, + frontal: settings.cage.max_frontal * cage_units, + rear: settings.cage.max_rear * cage_units, + position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), curvature_method: settings.maps.curvature.parameters.method, - curvature: Curvature::new(settings, request.mesh, mesh_diagonal, request.tiles), - ao: pass(BakedMap::AmbientOcclusion, &settings.maps.ao.parameters.rays, RayKind::Occlusion), - bent: pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion), - thickness: pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness), + curvature: Curvature::new(settings, request.mesh, mesh_scale, request.tiles), + ao, + bent, + thickness, }) } + pub(crate) fn ignore_transfer_backface(&self) -> bool { + self.settings.high_poly.ignore_backface + } + pub(crate) fn has_high(&self) -> bool { self.high.is_some() } @@ -109,6 +146,7 @@ impl<'a> BakeContext<'a> { .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) .map(|cage_position| surface.pos - cage_position) .filter(|offset| offset.length() > self.eps); + let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); let (origin, direction, front) = match cage { Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), None => { @@ -116,10 +154,14 @@ impl<'a> BakeContext<'a> { Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), None => averaged_normal, }; - (surface.pos + up * self.frontal, -up, self.frontal) + (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) } }; - (Ray { origin, direction, max_distance: front + self.rear, key: ANY }, front) + let key = match self.settings.high_poly.match_mode { + MeshMatchMode::Always => ANY, + MeshMatchMode::ByMeshName => self.low.key.get(surface.tri as usize).copied().unwrap_or(ANY), + }; + (Ray { origin, direction, max_distance: front + self.rear, key }, front) } pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { @@ -161,22 +203,33 @@ impl<'a> BakeContext<'a> { Some((sample_index, surface, curvature.texel(low_surface.tri))) }) .collect(); - let rays_per_sample = RING_COUNT * RAYS_PER_RING; - for chunk in chosen.chunks(CURVATURE_CHUNK) { + let rays_per_sample = curvature.rays_per_sample.max(1); + let key_for = |surface: &Surface| { + if self.settings.maps.curvature.parameters.mesh.self_intersection == SelfOcclusion::SameMeshName { + source.key.get(surface.tri as usize).copied().unwrap_or(ANY) + } else { + ANY + } + }; + let chunk_size = CURVATURE_CHUNK.min((1_048_576 / rays_per_sample).max(1)); + for chunk in chosen.chunks(chunk_size) { let mut rays: Vec = bytemuck::zeroed_vec(chunk.len() * rays_per_sample); - rays.par_chunks_mut(rays_per_sample).zip(chunk).for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, ANY, output)); - let hits = scene.closest(mesh, &rays)?; - let walls = |chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + RAYS_PER_RING).unwrap_or_default(); + rays.par_chunks_mut(rays_per_sample) + .zip(chunk) + .for_each(|(output, (_, surface, texel))| curvature.rays(tuning, surface, *texel, key_for(surface), output)); + let hits = scene.closest(mesh, &rays, false)?; + let walls = + |chunk_index: usize| hits.get(chunk_index * rays_per_sample..chunk_index * rays_per_sample + curvature.wall_count).unwrap_or_default(); let grounds: Vec = chunk .par_iter() .enumerate() .flat_map_iter(|(chunk_index, (_, surface, texel))| { let mut value = Vec::new(); - curvature.ground_rays(surface, *texel, ANY, walls(chunk_index), &mut value); + curvature.ground_rays(surface, *texel, key_for(surface), walls(chunk_index), &mut value); value }) .collect(); - let ground_hits = scene.closest(mesh, &grounds)?; + let ground_hits = scene.closest(mesh, &grounds, false)?; let ground_offsets: Vec = (0..chunk.len()) .scan(0, |first, chunk_index| { let offset = *first; @@ -228,23 +281,19 @@ impl<'a> BakeContext<'a> { BakedMap::Curvature if self.curvature_method == CurvatureMethod::NormalMap => [0.5; 3], BakedMap::Curvature => [traced.curvature; 3], BakedMap::WorldNormal => pack(surface.nrm), - BakedMap::Position => self.position(surface.pos), - BakedMap::Id => material_color(source.part.get(surface.tri as usize).copied().unwrap_or(0) as usize), + BakedMap::Position => self.position.evaluate(surface.pos), + BakedMap::Id => source.id_color(surface, source_barycentric, self.settings.maps.id.parameters), BakedMap::Normal => transfer.map_or(map.neutral(), |hit| tangent_normal(low_surface, hit.surface.nrm)), - BakedMap::Height => [transfer.map_or(0.5, |hit| (0.5 + (hit.front - hit.t) / (hit.front + self.rear)).clamp(0.0, 1.0)); 3], + BakedMap::Height => { + let relative_to_rays = self.settings.maps.height.parameters.normalization == texturecraft_core::HeightNormalization::RelativeToRayDistances; + [transfer.map_or(if relative_to_rays { 0.5 } else { 0.0 }, |hit| { + let height = hit.front - hit.t; + if relative_to_rays { (0.5 + height / (hit.front + self.rear).max(1e-20)).clamp(0.0, 1.0) } else { height } + }); 3] + } BakedMap::Opacity if missed => [0.0; 3], BakedMap::Opacity => [source.color(surface, source_barycentric).w; 3], }; } } - - fn position(&self, position: Vec3) -> [f32; 3] { - let normalized = match self.position_mode { - PositionMode::BoundingBox => (position - self.lo) / self.extent.max(Vec3::splat(1e-20)), - PositionMode::BoundingSphere => (position - (self.lo + self.extent * 0.5)) / self.extent.length().max(1e-20) + 0.5, - PositionMode::None => return position.to_array(), - }; - - normalized.clamp(Vec3::ZERO, Vec3::ONE).to_array() - } } diff --git a/crates/bake/src/map/curvature.rs b/crates/bake/src/map/curvature.rs index 6aa74776..eac8dd52 100644 --- a/crates/bake/src/map/curvature.rs +++ b/crates/bake/src/map/curvature.rs @@ -5,8 +5,7 @@ use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Hit, Mesh, Surface}; -pub(super) const RAYS_PER_RING: usize = 8; -pub(super) const RING_COUNT: usize = 4; +const RING_COUNT: usize = 4; const WALL_RADIUS_TEXELS: f32 = 1.5; const CONCAVE_WEIGHT: f32 = 1.5; const LOW_POLY_CONVEX_WEIGHT: f32 = 1.5; @@ -24,15 +23,18 @@ pub(super) struct Curvature { spread: f32, fallback: f32, texels: Vec, - ring: [(f32, f32); RAYS_PER_RING], + ring: [Vec<(f32, f32)>; RING_COUNT], + pub(super) rays_per_sample: usize, + pub(super) wall_count: usize, pub(super) low: CurvatureTuning, pub(super) high: CurvatureTuning, } impl Curvature { - pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_diagonal: f32, tiles: (u32, u32)) -> Curvature { + pub(super) fn new(settings: &BakeSettings, low: &Mesh, mesh_scale: f32, tiles: (u32, u32)) -> Curvature { let is_enabled = settings.maps.is_enabled(BakedMap::Curvature) && settings.maps.curvature.parameters.method == CurvatureMethod::Mesh; - let resolution = settings.common.resolution.pixels() as f32 * ((tiles.0.max(1) * tiles.1.max(1)) as f32).sqrt(); + let (width, height) = settings.common.output_size(); + let resolution = (width as f32 * height as f32 * tiles.0.max(1) as f32 * tiles.1.max(1) as f32).sqrt(); let texel = |triangle: usize| { let [a, b, c] = low.tri(triangle)?; let (position_a, position_b, position_c) = (*low.positions.get(a)?, *low.positions.get(b)?, *low.positions.get(c)?); @@ -41,29 +43,41 @@ impl Curvature { let uv_area = (uv_b - uv_a).perp_dot(uv_c - uv_a).abs(); (uv_area > 1e-12 && world_area > 0.0).then(|| (world_area / uv_area).sqrt() / resolution) }; - let fallback = mesh_diagonal * 1e-3; + let fallback = mesh_scale * 1e-3; let triangle_count = if is_enabled { low.triangle_count() } else { 0 }; - let walls = WALL_RADIUS_TEXELS; + let parameters = settings.maps.curvature.parameters.mesh; + let radius = parameters.sampling_radius * if parameters.relative_to_bounding_box { mesh_scale } else { 1.0 }; + let radius_scale = radius / (mesh_scale * 0.001); + let walls = WALL_RADIUS_TEXELS * radius_scale; + let rays_per_sample = parameters.rays as usize; + let ring: [Vec<(f32, f32)>; RING_COUNT] = std::array::from_fn(|ring_index| { + let count = rays_per_sample / RING_COUNT + usize::from(ring_index < rays_per_sample % RING_COUNT); + (0..count) + .map(|index| { + let angle = std::f32::consts::TAU * index as f32 / count.max(1) as f32; + (angle.cos(), angle.sin()) + }) + .collect() + }); Curvature { is_enabled, + rays_per_sample, + wall_count: ring.first().map_or(0, Vec::len), walls, spread: walls * 4.0 / 3.0, fallback, texels: (0..triangle_count).into_par_iter().map(|t| texel(t).filter(|v| v.is_finite()).unwrap_or(fallback)).collect(), low: CurvatureTuning { convex: LOW_POLY_CONVEX_WEIGHT, - true_radius: mesh_diagonal * LOW_POLY_CURVATURE_RADIUS_RATIO, + true_radius: mesh_scale * LOW_POLY_CURVATURE_RADIUS_RATIO * radius_scale, true_strength: LOW_POLY_CURVATURE_WEIGHT, }, high: CurvatureTuning { convex: HIGH_POLY_CONVEX_WEIGHT, - true_radius: mesh_diagonal * HIGH_POLY_CURVATURE_RADIUS_RATIO, + true_radius: mesh_scale * HIGH_POLY_CURVATURE_RADIUS_RATIO * radius_scale, true_strength: HIGH_POLY_CURVATURE_WEIGHT, }, - ring: std::array::from_fn(|i| { - let a = std::f32::consts::TAU * i as f32 / RAYS_PER_RING as f32; - (a.cos(), a.sin()) - }), + ring, } } @@ -76,16 +90,18 @@ impl Curvature { [r, r, self.spread * texel, tuning.true_radius] } - fn directions(&self, tangent: Vec3, bitangent: Vec3) -> [Vec3; RAYS_PER_RING] { - self.ring.map(|(cos, sin)| tangent * cos + bitangent * sin) + fn directions(&self, ring: usize, tangent: Vec3, bitangent: Vec3) -> impl Iterator + '_ { + self.ring.get(ring).into_iter().flatten().map(move |(cosine, sine)| tangent * *cosine + bitangent * *sine) } pub(super) fn rays(&self, tuning: &CurvatureTuning, surface: &Surface, texel_size: f32, key: u32, output: &mut [Ray]) { let (geometric_normal, tangent, bitangent) = surface_frame(surface); - let directions = self.directions(tangent, bitangent); - let radii = self.radii(tuning, texel_size); - for (ring, (rays, radius)) in output.chunks_exact_mut(RAYS_PER_RING).zip(radii).enumerate() { - for (ray, direction) in rays.iter_mut().zip(directions) { + let mut output = output.iter_mut(); + for (ring, radius) in self.radii(tuning, texel_size).into_iter().enumerate() { + for direction in self.directions(ring, tangent, bitangent) { + let Some(ray) = output.next() else { + return; + }; *ray = match ring { 0 => Ray { origin: surface.pos + geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, 1 => Ray { origin: surface.pos - geometric_normal * (0.15 * radius), direction, max_distance: radius, key }, @@ -103,7 +119,7 @@ impl Curvature { pub(super) fn ground_rays(&self, surface: &Surface, texel_size: f32, key: u32, walls: &[Option], output: &mut Vec) { let (geometric_normal, tangent, bitangent) = surface_frame(surface); let radius = self.walls * texel_size; - for (w, direction) in walls.iter().zip(self.directions(tangent, bitangent)) { + for (w, direction) in walls.iter().zip(self.directions(0, tangent, bitangent)) { if let Some(hit) = w { output.push(Ray { origin: surface.pos + geometric_normal * (0.15 * radius) + direction * (hit.t * 0.85), @@ -126,7 +142,7 @@ impl Curvature { let hard = ((1.0 - shaded.dot(surface.nrm)) / HARD_EDGE_NORMAL_CHANGE_THRESHOLD).clamp(0.0, 1.0); sum += (1.0 - hit.t / radius) * upright * hard; } - sum / RAYS_PER_RING as f32 + sum / hits.len().max(1) as f32 } fn spread( @@ -134,7 +150,7 @@ impl Curvature { source: &Source, surface: &Surface, geometric_normal: Vec3, - directions: &[Vec3; RAYS_PER_RING], + directions: impl Iterator, hits: &[Option], turn: f32, ) -> (f32, f32) { @@ -143,14 +159,14 @@ impl Curvature { let Some(hit) = hit else { continue }; let normal = interpolate(source.mesh, &source.mesh.normals, hit.tri, [hit.u, hit.v]).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); if 1.0 - normal.dot(surface.nrm) <= turn { - shading += (normal - surface.nrm).dot(*direction); + shading += (normal - surface.nrm).dot(direction); if let Some(f) = triangle_normal(source.mesh, hit.tri) { let f = if f.dot(geometric_normal) < 0.0 { -f } else { f }; - faces += (f - geometric_normal).dot(*direction); + faces += (f - geometric_normal).dot(direction); } } } - (shading / RAYS_PER_RING as f32, faces / RAYS_PER_RING as f32) + (shading / hits.len().max(1) as f32, faces / hits.len().max(1) as f32) } pub(super) fn value( @@ -163,17 +179,20 @@ impl Curvature { ground_hits: &[Option], ) -> f32 { let (geometric_normal, tangent, bitangent) = surface_frame(surface); - let directions = self.directions(tangent, bitangent); - let ring = |ring_index: usize| hits.get(ring_index * RAYS_PER_RING..(ring_index + 1) * RAYS_PER_RING).unwrap_or_default(); + let ring = |ring_index: usize| { + let start: usize = self.ring.iter().take(ring_index).map(Vec::len).sum(); + let count = self.ring.get(ring_index).map_or(0, Vec::len); + hits.get(start..start + count).unwrap_or_default() + }; let radius = self.walls * texel_size; let mut next = ground_hits.iter(); let above = self.wall(source, surface, geometric_normal, radius, ring(0), &mut || next.next().copied().flatten().is_some_and(|g| g.t < 0.3 * radius)); let below = self.wall(source, surface, geometric_normal, radius, ring(1), &mut || true); - let (shading, _) = self.spread(source, surface, geometric_normal, &directions, ring(2), 2.0); - let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, &directions, ring(3), 2.0); + let (shading, _) = self.spread(source, surface, geometric_normal, self.directions(2, tangent, bitangent), ring(2), 2.0); + let (true_shading, true_faces) = self.spread(source, surface, geometric_normal, self.directions(3, tangent, bitangent), ring(3), 2.0); let value = -above * CONCAVE_WEIGHT + (below - above).max(0.0) * tuning.convex + shading * 0.5 + tight(agreed(true_shading, true_faces) * tuning.true_strength); - (0.5 + value).clamp(0.0, 1.0) + (value * 2.0).clamp(-1.0, 1.0) } } diff --git a/crates/bake/src/map/diffusion.rs b/crates/bake/src/map/diffusion.rs new file mode 100644 index 00000000..eb59801f --- /dev/null +++ b/crates/bake/src/map/diffusion.rs @@ -0,0 +1,89 @@ +use texturecraft_texel::DilationMap; + +pub(crate) fn diffuse(pixels: &mut [f32], components: usize, padding: &DilationMap, tile_size: (usize, usize)) { + let width = padding.width as usize; + let height = padding.height as usize; + for start_y in (0..height).step_by(tile_size.1) { + for start_x in (0..width).step_by(tile_size.0) { + let tile_width = tile_size.0.min(width - start_x); + let tile_height = tile_size.1.min(height - start_y); + let mut values = vec![0.0; tile_width * tile_height * components]; + let mut valid = vec![false; tile_width * tile_height]; + for (index, covered) in valid.iter_mut().enumerate() { + let source = (start_y + index / tile_width) * width + start_x + index % tile_width; + *covered = padding.src.get(source).is_some_and(|source| *source != u32::MAX); + if let (Some(destination), Some(pixel)) = + (values.get_mut(index * components..(index + 1) * components), pixels.get(source * components..(source + 1) * components)) + { + destination.copy_from_slice(pixel); + } + } + if !valid.iter().any(|covered| *covered) { + continue; + } + fill(&mut values, &valid, tile_width, tile_height, components); + for (index, covered) in valid.iter().enumerate() { + if *covered { + continue; + } + let destination = (start_y + index / tile_width) * width + start_x + index % tile_width; + if let (Some(pixel), Some(value)) = + (pixels.get_mut(destination * components..(destination + 1) * components), values.get(index * components..(index + 1) * components)) + { + pixel.copy_from_slice(value); + } + } + } + } +} + +fn fill(values: &mut [f32], valid: &[bool], width: usize, height: usize, components: usize) { + if width == 1 && height == 1 { + return; + } + let (small_width, small_height) = (width.div_ceil(2), height.div_ceil(2)); + let mut small = vec![0.0; small_width * small_height * components]; + let mut small_valid = vec![false; small_width * small_height]; + for (index, covered) in small_valid.iter_mut().enumerate() { + let (x, y) = (index % small_width * 2, index / small_width * 2); + let mut count = 0; + for child_y in y..(y + 2).min(height) { + for child_x in x..(x + 2).min(width) { + let child = child_y * width + child_x; + if valid.get(child) != Some(&true) { + continue; + } + count += 1; + for component in 0..components { + if let Some(value) = small.get_mut(index * components + component) { + *value += values.get(child * components + component).copied().unwrap_or(0.0); + } + } + } + } + *covered = count > 0; + if let Some(pixel) = small.get_mut(index * components..(index + 1) * components) { + pixel.iter_mut().for_each(|value| *value /= count.max(1) as f32); + } + } + fill(&mut small, &small_valid, small_width, small_height, components); + for (index, covered) in valid.iter().enumerate() { + if *covered { + continue; + } + let (x, y) = ((index % width) as f32 * 0.5 - 0.25, (index / width) as f32 * 0.5 - 0.25); + let (fraction_x, fraction_y) = (x - x.floor(), y - y.floor()); + let sample = |offset_x: i32, offset_y: i32, component: usize| { + let sample_x = (x.floor() as i32 + offset_x).clamp(0, small_width as i32 - 1) as usize; + let sample_y = (y.floor() as i32 + offset_y).clamp(0, small_height as i32 - 1) as usize; + small.get((sample_y * small_width + sample_x) * components + component).copied().unwrap_or(0.0) + }; + for component in 0..components { + let top = sample(0, 0, component) * (1.0 - fraction_x) + sample(1, 0, component) * fraction_x; + let bottom = sample(0, 1, component) * (1.0 - fraction_x) + sample(1, 1, component) * fraction_x; + if let Some(value) = values.get_mut(index * components + component) { + *value = top * (1.0 - fraction_y) + bottom * fraction_y; + } + } + } +} diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs index 2507ff9c..2cc6bfc5 100644 --- a/crates/bake/src/map/normal_curvature.rs +++ b/crates/bake/src/map/normal_curvature.rs @@ -1,7 +1,15 @@ /// Divergence of the tangent-space normal map; positive curvature is convex -pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], width: usize, tile_resolution: usize, output: &mut [f32]) { +pub(crate) fn curvature_from_normal( + normal: &[f32], + covered: &[bool], + width: usize, + tile_size: (usize, usize), + settings: texturecraft_core::NormalMapCurvatureSettings, + output: &mut [f32], +) { use rayon::prelude::*; - let radius_texels = (tile_resolution / 512).max(1); + let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1); + let strength = 2.0f32.powf((settings.details - 0.5) * 4.0); let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) { Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback), _ => fallback, @@ -13,14 +21,22 @@ pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], width: usi } let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5)); let (left, right) = ( - normal_component(x.saturating_sub(radius_texels), y, 0, center_x), - if x + radius_texels < width { normal_component(x + radius_texels, y, 0, center_x) } else { center_x }, + if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x }, + if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width { + normal_component(x + radius_texels, y, 0, center_x) + } else { + center_x + }, ); let (up, down) = ( - normal_component(x, y.saturating_sub(radius_texels), 1, center_y), - if y + radius_texels < width { normal_component(x, y + radius_texels, 1, center_y) } else { center_y }, + if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y }, + if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) { + normal_component(x, y + radius_texels, 1, center_y) + } else { + center_y + }, ); - *value = (0.5 + (right - left) + (up - down)).clamp(0.0, 1.0); + *value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0); } }); } diff --git a/crates/bake/src/map/normalization.rs b/crates/bake/src/map/normalization.rs new file mode 100644 index 00000000..b1de9812 --- /dev/null +++ b/crates/bake/src/map/normalization.rs @@ -0,0 +1,91 @@ +use rayon::prelude::*; +use std::collections::BTreeMap; +use texturecraft_core::{BakeSettings, BakedMap, CurvatureMethod, HeightNormalization, ThicknessNormalization}; + +pub(crate) fn normalize( + maps: &mut BTreeMap>, + covered: &[bool], + width: usize, + tile_size: (usize, usize), + settings: &BakeSettings, + mesh_scale: f32, +) { + for (map, pixels) in maps { + if !matches!(map, BakedMap::Curvature | BakedMap::Height | BakedMap::Thickness) { + continue; + } + if *map == BakedMap::Height && settings.maps.height.parameters.normalization == HeightNormalization::RelativeToRayDistances { + continue; + } + if *map == BakedMap::Curvature && settings.maps.curvature.parameters.method != CurvatureMethod::Mesh { + continue; + } + pixels.par_chunks_mut(width * tile_size.1).enumerate().for_each(|(tile_row, rows)| { + let coverage = covered.get(tile_row * width * tile_size.1..).unwrap_or_default(); + for start_x in (0..width).step_by(tile_size.0) { + let end_x = (start_x + tile_size.0).min(width); + let mut minimum = f32::INFINITY; + let mut maximum = f32::NEG_INFINITY; + for (row_index, row) in rows.chunks(width).enumerate() { + for (x, value) in row.iter().enumerate().take(end_x).skip(start_x) { + if coverage.get(row_index * width + x) == Some(&true) && value.is_finite() { + minimum = minimum.min(*value); + maximum = maximum.max(*value); + } + } + } + if !minimum.is_finite() { + continue; + } + let (lower, upper, flat, raw) = match map { + BakedMap::Thickness => { + let parameters = settings.maps.thickness.parameters; + match parameters.normalization { + ThicknessNormalization::RelativeToMinMax => (minimum, maximum, 1.0, false), + ThicknessNormalization::RelativeToRayDistances => { + let units = if parameters.rays.relative_to_bounding_box { mesh_scale } else { 1.0 }; + (parameters.rays.min_distance * units, parameters.rays.max_distance * units, 1.0, false) + } + ThicknessNormalization::None => (0.0, 1.0, 1.0, true), + } + } + BakedMap::Height => match settings.maps.height.parameters.normalization { + HeightNormalization::RelativeToRayDistances => { + let units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + (-settings.cage.max_rear * units, settings.cage.max_frontal * units, 0.5, false) + } + HeightNormalization::RelativeToMinMax => (minimum, maximum, 0.5, false), + HeightNormalization::RelativeToLowMesh => { + let magnitude = minimum.abs().max(maximum.abs()); + (-magnitude, magnitude, 0.5, false) + } + HeightNormalization::Manual => { + let half_range = settings.maps.height.parameters.scaling_divisor * 0.5; + (-half_range, half_range, 0.5, false) + } + }, + _ => { + let parameters = settings.maps.curvature.parameters.mesh; + if parameters.auto_tonemapping { + let magnitude = minimum.abs().max(maximum.abs()); + (-magnitude, magnitude, 0.5, false) + } else { + (parameters.value_min, parameters.value_max, 0.5, false) + } + } + }; + if raw { + continue; + } + let range = upper - lower; + for (row_index, row) in rows.chunks_mut(width).enumerate() { + for (x, value) in row.iter_mut().enumerate().take(end_x).skip(start_x) { + if coverage.get(row_index * width + x) == Some(&true) { + *value = if range > f32::EPSILON { ((*value - lower) / range).clamp(0.0, 1.0) } else { flat }; + } + } + } + } + }); + } +} diff --git a/crates/bake/src/map/position_projection.rs b/crates/bake/src/map/position_projection.rs new file mode 100644 index 00000000..eccff2eb --- /dev/null +++ b/crates/bake/src/map/position_projection.rs @@ -0,0 +1,45 @@ +use texturecraft_core::{PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings}; +use texturecraft_geom::{Mesh, glam::Vec3}; + +pub(super) struct PositionProjection { + settings: PositionSettings, + minimum: Vec3, + extent: Vec3, + center: Vec3, + diameter: f32, +} + +impl PositionProjection { + pub(super) fn new(mesh: &Mesh, material: usize, settings: PositionSettings) -> Self { + let initial = (Vec3::splat(f32::INFINITY), Vec3::splat(f32::NEG_INFINITY)); + let expand = |(minimum, maximum): (Vec3, Vec3), position: &Vec3| (minimum.min(*position), maximum.max(*position)); + let (minimum, maximum) = match settings.scale { + PositionNormalizationScale::FullScene => mesh.positions.iter().fold(initial, expand), + PositionNormalizationScale::PerMaterial => mesh + .triangles_of(material) + .filter_map(|triangle| mesh.tri(triangle)) + .flatten() + .filter_map(|index| mesh.positions.get(index)) + .fold(initial, expand), + }; + let minimum = if minimum.is_finite() { minimum } else { Vec3::ZERO }; + let maximum = if maximum.is_finite() { maximum } else { Vec3::ZERO }; + let center = (minimum + maximum) * 0.5; + let extent = maximum - minimum; + Self { settings, minimum, extent, center, diameter: extent.max_element().max(1e-20) } + } + + pub(super) fn evaluate(&self, position: Vec3) -> [f32; 3] { + let value = match self.settings.normalization { + PositionMode::BoundingBox => ((position - self.minimum) / self.extent.max(Vec3::splat(1e-20))).clamp(Vec3::ZERO, Vec3::ONE), + PositionMode::BoundingSphere => ((position - self.center) / self.diameter + 0.5).clamp(Vec3::ZERO, Vec3::ONE), + PositionMode::None => position, + }; + match self.settings.axis { + PositionAxis::All => value.to_array(), + PositionAxis::X => [value.x; 3], + PositionAxis::Y => [value.y; 3], + PositionAxis::Z => [value.z; 3], + } + } +} diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index ab5f187d..d19e4afa 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -44,7 +44,7 @@ pub(super) fn pack(v: Vec3) -> [f32; 3] { (v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array() } -pub(super) fn material_color(part: usize) -> [f32; 3] { +pub(super) fn generated_hue(part: usize) -> [f32; 3] { let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32; let (s, v) = (0.7f32, 0.95f32); let f = h.fract(); diff --git a/crates/bake/src/map/seam.rs b/crates/bake/src/map/seam.rs new file mode 100644 index 00000000..4065fd52 --- /dev/null +++ b/crates/bake/src/map/seam.rs @@ -0,0 +1,64 @@ +use std::collections::HashMap; +use texturecraft_geom::{Mesh, glam::Vec2}; + +pub(crate) fn fix_seams(mesh: &Mesh, material: usize, covered: &[bool], size: (usize, usize), intensity: f32, pixels: &mut [f32]) { + if intensity <= 0.0 { + return; + } + let (minimum, maximum) = mesh.bounds(); + let tolerance = (maximum - minimum).length().max(1e-6) * 1e-6; + let position_key = |index: usize| mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64)); + let mut edges = HashMap::new(); + let source = pixels.to_vec(); + let texel_scale = Vec2::new(size.0 as f32, size.1 as f32); + let texel = |point: Vec2| { + if point.x < 0.0 || point.y < 0.0 || point.x >= size.0 as f32 || point.y >= size.1 as f32 { + return None; + } + let index = point.y.floor() as usize * size.0 + point.x.floor() as usize; + (covered.get(index) == Some(&true)).then_some(index) + }; + for triangle in mesh.triangles_of(material) { + let Some(corners) = mesh.tri(triangle) else { + continue; + }; + for edge in 0..3 { + let (Some(&first), Some(&second), Some(&third)) = (corners.get(edge), corners.get((edge + 1) % 3), corners.get((edge + 2) % 3)) else { + continue; + }; + let (Some(first_key), Some(second_key)) = (position_key(first), position_key(second)) else { + continue; + }; + let (first, second, key) = + if first_key <= second_key { (first, second, (first_key, second_key)) } else { (second, first, (second_key, first_key)) }; + let (Some(start), Some(end), Some(interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { + continue; + }; + let (start, end, interior) = (*start * texel_scale, *end * texel_scale, *interior * texel_scale); + let inward = (interior - (start + end) * 0.5).try_normalize().unwrap_or(Vec2::ZERO) * 0.75; + let Some((other_start, other_end, other_inward)) = edges.insert(key, (start, end, inward)) else { + continue; + }; + if start.distance_squared(other_start) + end.distance_squared(other_end) < 0.25 { + continue; + } + let steps = start.distance(end).max(other_start.distance(other_end)).ceil().clamp(1.0, size.0.max(size.1) as f32 * 2.0) as usize; + for step in 0..=steps { + let fraction = step as f32 / steps as f32; + let (Some(first), Some(second)) = (texel(start.lerp(end, fraction) + inward), texel(other_start.lerp(other_end, fraction) + other_inward)) + else { + continue; + }; + let (Some(&first_value), Some(&second_value)) = (source.get(first), source.get(second)) else { + continue; + }; + let average = (first_value + second_value) * 0.5; + for (index, value) in [(first, first_value), (second, second_value)] { + if let Some(destination) = pixels.get_mut(index) { + *destination = value + (average - value) * intensity; + } + } + } + } + } +} diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 6760df57..0e1f9164 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,7 +1,8 @@ -use super::sampling::interpolate; +use super::sampling::{generated_hue, interpolate, splitmix64}; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; +use texturecraft_core::{HighPolySettings, IdColorGenerator, IdColorSource, IdSettings}; use texturecraft_geom::glam::{Vec2, Vec4}; use texturecraft_geom::{BaseColor, Bvh, Mesh, Surface}; use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; @@ -11,24 +12,88 @@ pub(super) struct Source<'a> { bvh: &'a Bvh, pub(super) part: Vec, pub(super) key: Vec, + backface_culling: Vec, + file_ids: &'a [u32], + mesh_ids: Vec, + file_count: u32, + mesh_count: u32, base_color: &'a [Option>], } impl<'a> Source<'a> { - pub(super) fn new(mesh: &'a Mesh, bvh: &'a Bvh, base_color: &'a [Option>], suffix: &str, keys: &mut HashMap) -> Source<'a> { + pub(super) fn new( + mesh: &'a Mesh, + bvh: &'a Bvh, + base_color: &'a [Option>], + file_ids: &'a [u32], + suffix: &str, + settings: &HighPolySettings, + keys: &mut HashMap, + ) -> Source<'a> { let triangle_count = mesh.triangle_count(); let mut part = vec![ANY; triangle_count]; + let mut backface_culling = vec![false; triangle_count]; + let mut mesh_keys = HashMap::new(); + let mut mesh_ids = Vec::with_capacity(mesh.submeshes.len()); + let mut part_keys = Vec::with_capacity(mesh.submeshes.len()); + let backface_suffix = settings.ignore_backface_suffix.trim().to_lowercase(); for (part_index, submesh) in mesh.submeshes.iter().enumerate() { - let (first_triangle, last_triangle) = ((submesh.start / 3) as usize, (submesh.start.saturating_add(submesh.count) / 3) as usize); - part.get_mut(first_triangle.min(last_triangle)..last_triangle.min(triangle_count)).unwrap_or_default().fill(part_index as u32); + let first_triangle = (submesh.start / 3) as usize; + let last_triangle = (submesh.start.saturating_add(submesh.count) / 3) as usize; + let range = first_triangle.min(last_triangle)..last_triangle.min(triangle_count); + part.get_mut(range.clone()).unwrap_or_default().fill(part_index as u32); + let name = submesh.name.trim().to_lowercase(); + let ignore_backface = !backface_suffix.is_empty() && name.ends_with(&backface_suffix); + backface_culling.get_mut(range).unwrap_or_default().fill(ignore_backface); + let name = if ignore_backface { name.strip_suffix(&backface_suffix).unwrap_or(&name) } else { &name }; + part_keys.push(match_key(name, suffix, keys)); + let next = mesh_keys.len() as u32; + let file_id = file_ids.get(part_index).copied().unwrap_or(0); + mesh_ids.push(*mesh_keys.entry((file_id, name.to_owned())).or_insert(next)); } - let part_keys: Vec = mesh.submeshes.iter().map(|submesh| match_key(&submesh.name, suffix, keys)).collect(); let key = part.iter().map(|part_index| part_keys.get(*part_index as usize).copied().unwrap_or(ANY)).collect(); - Source { mesh, bvh, part, key, base_color } + Source { + mesh, + bvh, + part, + key, + backface_culling, + file_ids, + file_count: file_ids.iter().copied().max().unwrap_or(0).saturating_add(1), + mesh_count: mesh_keys.len() as u32, + mesh_ids, + base_color, + } } pub(super) fn trace(&self) -> TraceMesh<'_> { - TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key } + TraceMesh { mesh: self.mesh, bvh: self.bvh, keys: &self.key, backface_culling: &self.backface_culling } + } + + pub(super) fn id_color(&self, surface: &Surface, barycentric: [f32; 2], settings: IdSettings) -> [f32; 3] { + let part_index = self.part.get(surface.tri as usize).copied().unwrap_or(0) as usize; + match settings.source { + IdColorSource::VertexColor => interpolate(self.mesh, &self.mesh.colors, surface.tri, barycentric).unwrap_or(Vec4::ONE).truncate().to_array(), + IdColorSource::MaterialColor => { + let material = self.mesh.submeshes.get(part_index).map(|part| part.material); + material.and_then(|index| self.base_color.get(index)?.as_ref()).map_or([0.6; 3], |color| color.factor.truncate().to_array()) + } + source => { + let (identity, count) = match source { + IdColorSource::FileId => (self.file_ids.get(part_index).copied().unwrap_or(0), self.file_count), + IdColorSource::MeshId => (self.mesh_ids.get(part_index).copied().unwrap_or(0), self.mesh_count), + _ => (part_index as u32, self.mesh.submeshes.len() as u32), + }; + match settings.generator { + IdColorGenerator::HueShift => generated_hue(identity as usize), + IdColorGenerator::Grayscale => [(identity + 1) as f32 / count.max(1) as f32; 3], + IdColorGenerator::Random => { + let seed = splitmix64(u64::from(identity)); + [0, 16, 32].map(|shift| ((seed >> shift) & 0xffff) as f32 / 65535.0) + } + } + } + } } pub(super) fn color(&self, surface: &Surface, barycentric: [f32; 2]) -> Vec4 { diff --git a/crates/bake/src/skew.rs b/crates/bake/src/skew.rs index 780c396d..61104cb7 100644 --- a/crates/bake/src/skew.rs +++ b/crates/bake/src/skew.rs @@ -1,10 +1,10 @@ //! Skew correction adapted from SurfaceCraft's baker (MIT OR Apache-2.0) mod prepared_skew; -mod skew_map; +#[cfg(test)] +use crate::BakePaintMap; pub(crate) use prepared_skew::PreparedSkew; -pub use skew_map::SkewMap; #[cfg(test)] mod tests { @@ -28,19 +28,19 @@ mod tests { #[test] fn maps_sample_bilinearly_and_bad_ones_are_refused() { - let map = SkewMap { width: 2, height: 1, values: vec![0.0, 1.0], ..SkewMap::constant(0.0) }; + let map = BakePaintMap { width: 2, height: 1, values: vec![0.0, 1.0] }; assert!(map.validate().is_ok()); assert!( - map.at(Vec2::new(0.0, 0.5)).abs() < 1e-6 && (map.at(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 && (map.at(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6 + map.sample(Vec2::new(0.0, 0.5)).abs() < 1e-6 + && (map.sample(Vec2::new(1.0, 0.5)) - 1.0).abs() < 1e-6 + && (map.sample(Vec2::new(0.5, 0.5)) - 0.5).abs() < 1e-6 ); - assert!(map.at(Vec2::new(-3.0, 9.0)).is_finite() && map.at(Vec2::new(f32::NAN, 0.0)) == 0.0); + assert!(map.sample(Vec2::new(-3.0, 9.0)).is_finite() && map.sample(Vec2::new(f32::NAN, 0.0)) == 0.0); for bad in [ - SkewMap { values: vec![0.0], ..map.clone() }, - SkewMap { width: 0, values: vec![], ..map.clone() }, - SkewMap { values: vec![0.0, f32::NAN], ..map.clone() }, - SkewMap { edge_distance: -1.0, ..map.clone() }, - SkewMap { edge_contrast: 0.0, ..map.clone() }, - SkewMap { width: u32::MAX, height: u32::MAX, ..map.clone() }, + BakePaintMap { values: vec![0.0], ..map.clone() }, + BakePaintMap { width: 0, values: vec![], ..map.clone() }, + BakePaintMap { values: vec![0.0, f32::NAN], ..map.clone() }, + BakePaintMap { width: u32::MAX, height: u32::MAX, ..map.clone() }, ] { assert!(bad.validate().is_err()); } @@ -51,45 +51,51 @@ mod tests { let mesh = fold(); let up = Vec3::new(0.6, 0.8, 0.0); let base = Vec3::Y; - let go = |map: &SkewMap, pos: Vec3| { + let go = |map: &BakePaintMap, pos: Vec3, edge_distance: f32| { let s = Surface { pos, nrm: base, geo_nrm: base, tangent: Default::default(), uv: Vec2::splat(0.5), tri: 0 }; - PreparedSkew::new(map, &mesh, 1.0).unwrap().correct(&mesh, &s, up) + PreparedSkew::new( + map, + &mesh, + 1.0, + texturecraft_core::SkewSettings { edge_protection: edge_distance > 0.0, edge_distance, edge_contrast: 1.0, ..Default::default() }, + ) + .unwrap() + .correct(&mesh, &s, up) }; - assert!((go(&SkewMap::constant(0.0), Vec3::ZERO) - up).length() < 1e-6, "black leaves the ray alone"); - assert!((go(&SkewMap::constant(1.0), Vec3::ZERO) - base).length() < 1e-6, "white turns it onto the base normal"); - let half = go(&SkewMap::constant(0.5), Vec3::ZERO); + assert!((go(&BakePaintMap::constant(0.0), Vec3::ZERO, 0.0) - up).length() < 1e-6, "black leaves the ray alone"); + assert!((go(&BakePaintMap::constant(1.0), Vec3::ZERO, 0.0) - base).length() < 1e-6, "white turns it onto the base normal"); + let half = go(&BakePaintMap::constant(0.5), Vec3::ZERO, 0.0); assert!(half.x > 0.0 && half.x < up.x && (half.length() - 1.0).abs() < 1e-5, "grey is in between and still unit: {half}"); - let guarded = SkewMap { edge_distance: 0.5, ..SkewMap::constant(1.0) }; - assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0)) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction"); - assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0)) - base).length() < 1e-6, "away from every hard edge the correction is full"); + let guarded = BakePaintMap::constant(1.0); + assert!((go(&guarded, Vec3::new(0.5, 0.0, 0.0), 0.5) - up).length() < 1e-6, "on the hard edge the ray stays on the cage direction"); + assert!((go(&guarded, Vec3::new(0.3, 0.9, 0.0), 0.5) - base).length() < 1e-6, "away from every hard edge the correction is full"); } #[test] fn painting_blends_dabs_in_and_resizing_keeps_the_picture() { - let mut map = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut map = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); assert!(map.values.iter().all(|v| *v == 0.0)); map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 1.0, 1.0, 1.0).unwrap(); - let at = |m: &SkewMap, u: f32, v: f32| m.at(Vec2::new(u, v)); + let at = |m: &BakePaintMap, u: f32, v: f32| m.sample(Vec2::new(u, v)); assert!(at(&map, 0.5, 0.5) > 0.99 && at(&map, 0.95, 0.95) == 0.0, "{} {}", at(&map, 0.5, 0.5), at(&map, 0.95, 0.95)); - let mut dab = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut dab = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); dab.paint(&[Vec2::new(0.5, 0.5)], 0.1, 0.8, 1.0, 0.5).unwrap(); assert!((at(&dab, 0.5, 0.5) - 0.4).abs() < 0.02, "{}", at(&dab, 0.5, 0.5)); - let mut line = SkewMap::constant(0.0).resized(64, 64).unwrap(); + let mut line = BakePaintMap::constant(0.0).resized(64, 64).unwrap(); line.paint(&[Vec2::new(0.1, 0.9), Vec2::new(0.9, 0.9)], 0.05, 0.5, 1.0, 0.5).unwrap(); assert!(at(&line, 0.5, 0.9) > 0.45 && at(&line, 0.5, 0.9) <= 0.5 + 1e-4, "{}", at(&line, 0.5, 0.9)); assert!(at(&line, 0.5, 0.1) == 0.0, "the other end of v is untouched"); map.paint(&[Vec2::new(0.5, 0.5)], 0.2, 0.0, 1.0, 1.0).unwrap(); assert!(at(&map, 0.5, 0.5) < 0.01); - let mut small = SkewMap { edge_distance: 0.1, ..SkewMap::constant(0.0).resized(8, 8).unwrap() }; + let mut small = BakePaintMap::constant(0.0).resized(8, 8).unwrap(); small.paint(&[Vec2::new(0.25, 0.75)], 0.2, 1.0, 1.0, 1.0).unwrap(); let big = small.resized(32, 32).unwrap(); - assert_eq!(big.edge_distance, 0.1); assert!((at(&big, 0.25, 0.75) - at(&small, 0.25, 0.75)).abs() < 0.1 && at(&big, 0.9, 0.1) == 0.0); } #[test] fn hostile_brushes_are_refused_and_change_nothing() { - let mut map = SkewMap::constant(0.3).resized(16, 16).unwrap(); + let mut map = BakePaintMap::constant(0.3).resized(16, 16).unwrap(); let before = map.clone(); let c = [Vec2::new(0.5, 0.5)]; for (pts, r, v) in @@ -101,11 +107,11 @@ mod tests { assert_eq!(map, before); assert!(map.paint(&[Vec2::ZERO, Vec2::new(1e6, 1e6)], 1e-4, 1.0, 0.5, 1.0).is_err()); assert_eq!(map, before); - let mut big = SkewMap::constant(0.0).resized(4096, 4096).unwrap(); + let mut big = BakePaintMap::constant(0.0).resized(4096, 4096).unwrap(); let untouched = big.clone(); assert!(big.paint(&[Vec2::splat(0.5); 8], 1.0, 1.0, 0.5, 1.0).is_err()); assert_eq!(big, untouched, "nothing was painted before the refusal"); assert!(big.paint(&[Vec2::splat(0.5)], 1.0, 1.0, 0.5, 1.0).is_ok(), "one such dab is within the budget"); - assert!(SkewMap::constant(0.0).resized(0, 4).is_err() && SkewMap::constant(0.0).resized(100_000, 100_000).is_err()); + assert!(BakePaintMap::constant(0.0).resized(0, 4).is_err() && BakePaintMap::constant(0.0).resized(100_000, 100_000).is_err()); } } diff --git a/crates/bake/src/skew/prepared_skew.rs b/crates/bake/src/skew/prepared_skew.rs index b287c2d3..e6cce826 100644 --- a/crates/bake/src/skew/prepared_skew.rs +++ b/crates/bake/src/skew/prepared_skew.rs @@ -1,26 +1,28 @@ -use super::SkewMap; use crate::BakeError; +use crate::BakePaintMap; use std::collections::HashMap; +use texturecraft_core::{SkewCorrectionMethod, SkewSettings}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; const HARD_EDGE_COS: f32 = 0.866; pub(crate) struct PreparedSkew<'a> { - map: &'a SkewMap, + map: &'a BakePaintMap, + settings: SkewSettings, hard: Vec<[bool; 3]>, - mesh_diagonal: f32, + mesh_scale: f32, } impl<'a> PreparedSkew<'a> { - pub(crate) fn new(map: &'a SkewMap, mesh: &Mesh, mesh_diagonal: f32) -> Result, BakeError> { + pub(crate) fn new(map: &'a BakePaintMap, mesh: &Mesh, mesh_scale: f32, settings: SkewSettings) -> Result, BakeError> { map.validate()?; - let hard = if map.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; - Ok(PreparedSkew { map, hard, mesh_diagonal }) + let hard = if settings.edge_protection && settings.edge_distance > 0.0 { hard_edges(mesh) } else { Vec::new() }; + Ok(PreparedSkew { map, settings, hard, mesh_scale }) } pub(crate) fn correct(&self, mesh: &Mesh, surface: &Surface, up: Vec3) -> Vec3 { - let amount = self.map.at(surface.uv); + let amount = self.map.sample(surface.uv); if amount <= 0.0 { return up; } @@ -34,11 +36,20 @@ impl<'a> PreparedSkew<'a> { Some(segment_distance(surface.pos, *edge_start, *edge_end)) }) .fold(f32::INFINITY, f32::min); - (nearest_edge_distance / (self.map.edge_distance * self.mesh_diagonal).max(1e-9)).clamp(0.0, 1.0).powf(self.map.edge_contrast) + (nearest_edge_distance / (self.settings.edge_distance * self.mesh_scale).max(1e-9)).clamp(0.0, 1.0).powf(self.settings.edge_contrast.max(1e-6)) } _ => 1.0, }; - let base = surface.nrm; + let base = match self.settings.method { + SkewCorrectionMethod::MeshNormalsBased => surface.nrm, + SkewCorrectionMethod::FaceNormalsBased => { + if surface.geo_nrm.dot(surface.nrm) < 0.0 { + -surface.geo_nrm + } else { + surface.geo_nrm + } + } + }; let blend = amount * protection; (up * (1.0 - blend) + base * blend).try_normalize().unwrap_or(up) } diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs new file mode 100644 index 00000000..b490655d --- /dev/null +++ b/crates/bake/src/test/setting.rs @@ -0,0 +1,199 @@ +use super::*; +use texturecraft_core::{ + AmbientOcclusionAttenuation, HeightNormalization, IdColorSource, MeshMatchMode, PositionAxis, PositionNormalizationScale, ThicknessNormalization, +}; + +#[test] +fn rectangular_bakes_and_diffusion_preserve_surface_pixels() { + let mut mesh = quad(); + for uv in &mut mesh.uvs { + uv.x *= 0.5; + } + let mut parameters = settings(64, &[BakedMap::Position]); + parameters.common.resolution_height = Some(BakeResolution::R32); + let plain = run(&mesh, ¶meters).unwrap(); + assert_eq!((plain.resolution, plain.height), (64, 32)); + assert_eq!(plain.maps[&BakedMap::Position].len(), 64 * 32 * 3); + parameters.common.apply_diffusion = true; + let diffused = run(&mesh, ¶meters).unwrap(); + for row in 0..32 { + let covered = row * 64 * 3..(row * 64 + 32) * 3; + assert_eq!(plain.maps[&BakedMap::Position][covered.clone()], diffused.maps[&BakedMap::Position][covered]); + } + let background = (20 * 64 + 50) * 3; + assert_eq!(plain.maps[&BakedMap::Position][background], 0.0); + assert!(diffused.maps[&BakedMap::Position][background] > 0.0); +} + +#[test] +fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() { + let mut low = quad(); + low.submeshes[0].name = "Panel_low".into(); + let mut high = quad(); + high.submeshes[0].name = "Panel_high".into(); + high.positions.iter_mut().for_each(|position| position.y = 0.02); + let mut unrelated = quad(); + unrelated.submeshes[0].name = "Other_high".into(); + unrelated.positions.iter_mut().for_each(|position| position.y = 0.04); + high.append(&unrelated); + let mut parameters = settings(16, &[BakedMap::Height]); + parameters.cage.max_frontal = 0.1; + parameters.cage.relative_to_bounding_box = false; + parameters.maps.height.parameters.normalization = HeightNormalization::Manual; + let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128]; + assert!((height(¶meters, &high) - 0.54).abs() < 1e-5); + parameters.high_poly.match_mode = MeshMatchMode::ByMeshName; + assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); + for triangle in high.indices.chunks_exact_mut(3) { + triangle.swap(1, 2); + } + assert_eq!(height(¶meters, &high), 0.5); + parameters.high_poly.ignore_backface = false; + assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); +} + +#[test] +fn occlusion_honors_minimum_distance_units_attenuation_and_named_backfaces() { + let mut mesh = quad(); + let mut ceiling = quad(); + ceiling.positions.iter_mut().for_each(|position| position.y = 0.1); + ceiling.submeshes[0].name = "Roof_ignorebf".into(); + mesh.append(&ceiling); + let mut parameters = settings(16, &[BakedMap::AmbientOcclusion]); + parameters.maps.ao.parameters.rays = + RaySettings { rays: 1, spread: 0.0, min_distance: 0.0, max_distance: 1.0, relative_to_bounding_box: false, ..Default::default() }; + let value = |parameters: &BakeSettings| run(&mesh, parameters).unwrap().maps[&BakedMap::AmbientOcclusion][128]; + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None; + assert_eq!(value(¶meters), 0.0); + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Linear; + assert!((value(¶meters) - 0.1).abs() < 1e-4); + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::Smooth; + assert!((value(¶meters) - 0.028).abs() < 1e-4); + parameters.maps.ao.parameters.rays.min_distance = 0.15; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.rays.min_distance = 0.0; + parameters.maps.ao.parameters.rays.max_distance = 0.075; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.rays.relative_to_bounding_box = true; + assert!(value(¶meters) < 0.8); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + assert_eq!(value(¶meters), 1.0); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Never; + parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + assert_eq!(value(¶meters), 1.0); +} + +#[test] +fn bent_normal_settings_are_independent_of_ambient_occlusion() { + let mesh = primitives::material_ball(); + let mut parameters = settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]); + let original = run(&mesh, ¶meters).unwrap(); + parameters.maps.ao.parameters.ignore_backface = BackfaceMode::Always; + parameters.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + parameters.maps.ao.parameters.attenuation = AmbientOcclusionAttenuation::None; + let changed = run(&mesh, ¶meters).unwrap(); + assert_eq!(original.maps[&BakedMap::BentNormal], changed.maps[&BakedMap::BentNormal]); +} + +#[test] +fn id_sources_keep_material_color_separate_from_vertex_color_and_textures() { + let low = quad(); + let mut high = quad(); + high.colors = vec![Vec4::new(0.8, 0.1, 0.3, 1.0); high.vertex_count()]; + let colors = vec![Some(Arc::new(BaseColor { factor: Vec4::new(0.2, 0.4, 0.7, 1.0), width: 1, height: 1, texels: vec![[255, 0, 0, 255]] }))]; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let mut parameters = settings(16, &[BakedMap::Id]); + for (source, expected) in [(IdColorSource::MaterialColor, [0.2, 0.4, 0.7]), (IdColorSource::VertexColor, [0.8, 0.1, 0.3])] { + parameters.maps.id.parameters.source = source; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: ¶meters, + high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &colors, file_ids: &[0] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let output = bake(&request, &Progress::new()).unwrap(); + for (value, expected) in output.maps[&BakedMap::Id][128 * 3..129 * 3].iter().zip(expected) { + assert!((value - expected).abs() < 1e-6); + } + } +} + +#[test] +fn painted_cage_limits_frontal_projection() { + let low = quad(); + let mut high = quad(); + high.positions.iter_mut().for_each(|position| position.y = 0.08); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let mut parameters = settings(16, &[BakedMap::Opacity]); + parameters.cage.max_frontal = 0.1; + parameters.cage.relative_to_bounding_box = false; + let reduced = BakePaintMap::constant(0.5); + let mut request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: ¶meters, + high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &[], file_ids: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 1.0); + request.cage_paint = Some(&reduced); + assert_eq!(bake(&request, &Progress::new()).unwrap().maps[&BakedMap::Opacity][128], 0.0); +} + +#[test] +fn position_axis_and_material_bounds_change_only_the_requested_space() { + let mut mesh = quad(); + let mut distant = quad(); + distant.positions.iter_mut().for_each(|position| position.x += 10.0); + mesh.append(&distant); + let mut parameters = settings(16, &[BakedMap::Position]); + parameters.maps.position.parameters.axis = PositionAxis::X; + let global = run(&mesh, ¶meters).unwrap(); + parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial; + let local = run(&mesh, ¶meters).unwrap(); + assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2)); + assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9)); + assert!(local.maps[&BakedMap::Position].chunks_exact(3).all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); +} + +#[test] +fn curvature_radius_and_manual_bounds_control_edge_response() { + let mesh = primitives::cube(2.0); + let mut parameters = settings(64, &[BakedMap::Curvature]); + let narrow = run(&mesh, ¶meters).unwrap(); + parameters.maps.curvature.parameters.mesh.sampling_radius *= 4.0; + let wide = run(&mesh, ¶meters).unwrap(); + let edge_count = |output: &BakeOutput| covered_values(&mesh, output, BakedMap::Curvature).iter().filter(|(_, value)| *value > 0.6).count(); + assert!(edge_count(&wide) > edge_count(&narrow)); + parameters.maps.curvature.parameters.mesh.value_min = -2.0; + parameters.maps.curvature.parameters.mesh.value_max = 2.0; + let reduced = run(&mesh, ¶meters).unwrap(); + assert!(reduced.maps[&BakedMap::Curvature].iter().all(|value| (0.25..=0.75).contains(value))); +} + +#[test] +fn thickness_can_preserve_distance_or_normalize_each_tile() { + let mesh = primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0); + let mut parameters = settings(32, &[BakedMap::Thickness]); + parameters.maps.thickness.parameters.normalization = ThicknessNormalization::None; + parameters.maps.thickness.parameters.rays.relative_to_bounding_box = false; + parameters.maps.thickness.parameters.rays.max_distance = 0.3; + let distance = run(&mesh, ¶meters).unwrap(); + assert!(covered_values(&mesh, &distance, BakedMap::Thickness).iter().all(|(_, value)| *value <= 0.30001)); + parameters.maps.thickness.parameters.normalization = ThicknessNormalization::RelativeToMinMax; + let normalized = run(&mesh, ¶meters).unwrap(); + let values = covered_values(&mesh, &normalized, BakedMap::Thickness); + assert!(values.iter().any(|(_, value)| *value == 0.0)); + assert!(values.iter().any(|(_, value)| *value == 1.0)); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 2259aa95..96a8cc4f 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,13 +14,20 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/setting.rs"] +mod setting; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { let mut base = BakeSettings::default(); - base.common = CommonBakeSettings { resolution: BakeResolution::from_pixels(resolution).unwrap(), dilation: 0, ..base.common }; + base.common = + CommonBakeSettings { resolution: BakeResolution::from_pixels(resolution).unwrap(), dilation: 0, apply_diffusion: false, ..base.common }; base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::Mesh, ..base.maps.curvature.parameters }; base.maps.position.parameters = PositionSettings { normalization: PositionMode::BoundingBox, ..base.maps.position.parameters }; + base.maps.curvature.parameters.mesh.auto_tonemapping = false; + base.maps.height.parameters.normalization = texturecraft_core::HeightNormalization::RelativeToRayDistances; + base.maps.thickness.parameters.normalization = texturecraft_core::ThicknessNormalization::RelativeToRayDistances; base.maps.select(maps.iter().copied()); base }, @@ -38,7 +45,10 @@ fn with_rays(mut s: BakeSettings, rays: u32, max_distance: f32) -> BakeSettings fn run(mesh: &Mesh, s: &BakeSettings) -> Result { let bvh = Bvh::new(mesh); - bake(&BakeRequest { mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()) + bake( + &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }, + &Progress::new(), + ) } fn covered_values(mesh: &Mesh, out: &BakeOutput, map: BakedMap) -> Vec<(Vec3, f32)> { @@ -284,7 +294,18 @@ fn strips_match_a_single_pass() { 4, 0.25, ); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let whole = bake(&req, &Progress::new()).unwrap(); let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap(); for (map, a) in &whole.maps { @@ -299,7 +320,18 @@ fn cancel_and_progress() { let m = primitives::sphere(1.0, 16, 8); let bvh = Bvh::new(&m); let s = settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Position]); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let p = Progress::new(); p.cancel(); assert!(matches!(bake(&req, &p), Err(BakeError::Cancelled))); @@ -314,7 +346,18 @@ fn a_curvature_bake_can_be_cancelled_midway_and_reports_progress() { let m = primitives::rounded_box(Vec3::ONE, 0.15); let bvh = Bvh::new(&m); let s = settings(2048, &[BakedMap::Curvature]); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let p = Progress::new(); std::thread::scope(|t| { let baking = t.spawn(|| bake(&req, &p)); @@ -337,7 +380,18 @@ fn hostile_tile_dimensions_are_rejected() { let settings = settings(16, &[BakedMap::Position]); for tiles in [(1 << 31, 1 << 31), (u32::MAX, u32::MAX), (MAX_TEXELS as u32, 1), (0, 1), (1, 0)] { - let request = BakeRequest { mesh: &mesh, bvh: &bvh, material: 0, settings: &settings, high: None, cage: None, skew: None, tiles }; + let request = BakeRequest { + low_base_color: &[], + mesh: &mesh, + bvh: &bvh, + material: 0, + settings: &settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles, + }; assert!(matches!(validate(&request), Err(BakeError::Invalid(_))), "{tiles:?}"); assert!(matches!(bake(&request, &Progress::new()), Err(BakeError::Invalid(_))), "{tiles:?}"); @@ -389,7 +443,10 @@ fn invalid_requests_are_errors() { } let bvh = Bvh::new(&m); let req = |mesh: &Mesh, material| { - bake(&BakeRequest { mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()) + bake( + &BakeRequest { low_base_color: &[], mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }, + &Progress::new(), + ) }; assert!(matches!(req(&m, 1), Err(BakeError::Invalid(_)))); let mut broken = m.clone(); @@ -440,13 +497,15 @@ fn normal_and_height_transfer_from_a_high_poly() { let s = settings(16, &[BakedMap::Normal, BakedMap::Height]); let out = bake( &BakeRequest { + low_base_color: &[], mesh: &low, bvh: &lb, material: 0, settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }), + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }), cage: None, skew: None, + cage_paint: None, tiles: (1, 1), }, &Progress::new(), @@ -455,7 +514,7 @@ fn normal_and_height_transfer_from_a_high_poly() { let i = 8 * 16 + 8; let n = &out.maps[&BakedMap::Normal][i * 3..i * 3 + 3]; assert!((n[0] - (0.5 + 0.5 * tilt.x)).abs() < 1e-3 && (n[1] - 0.5).abs() < 1e-3 && (n[2] - (0.5 + 0.5 * tilt.y)).abs() < 1e-3, "{n:?}"); - let diag = 8.0f32.sqrt(); + let diag = 2.0; let expected = 0.5 + 0.005 / (0.02 * diag); assert!((out.maps[&BakedMap::Height][i] - expected).abs() < 1e-3, "{}", out.maps[&BakedMap::Height][i]); let flat = run(&low, &s).unwrap(); @@ -465,15 +524,21 @@ fn normal_and_height_transfer_from_a_high_poly() { fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> Result { let (lb, hb) = (Bvh::new(low), Bvh::new(high)); + let mut settings = s.clone(); + if cage.is_some() { + settings.cage.kind = texturecraft_core::CageType::CustomFile; + } bake( &BakeRequest { + low_base_color: &[], mesh: low, bvh: &lb, material: 0, - settings: s, - high: Some(HighPoly { mesh: high, bvh: &hb, base_color: &[] }), + settings: &settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &hb, base_color: &[] }), cage, skew: None, + cage_paint: None, tiles: (1, 1), }, &Progress::new(), @@ -631,7 +696,7 @@ fn ray_distances_and_the_cage_limit_hits() { let low = quad(); let mut high = quad(); high.positions.iter_mut().for_each(|p| p.y += 0.2); - let diag = 8.0f32.sqrt(); + let diag = 2.0; let opacity = |s: &BakeSettings, cage: Option<&Mesh>| transfer(&low, &high, cage, s).map(|o| o.maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]); let near = settings(16, &[BakedMap::Opacity]); assert_eq!(opacity(&near, None).unwrap(), 0.0, "0.2 above is beyond the default frontal distance"); @@ -689,8 +754,22 @@ fn bench_material_ball_2k() { base }; let t = std::time::Instant::now(); - let out = - bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }, &Progress::new()).unwrap(); + let out = bake( + &BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }, + &Progress::new(), + ) + .unwrap(); println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.maps.ao.parameters.rays.rays, t.elapsed()); } } @@ -706,8 +785,22 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() { base }; let bvh = Bvh::new(&m); - let out = - bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (2, 1) }, &Progress::new()).unwrap(); + let out = bake( + &BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (2, 1), + }, + &Progress::new(), + ) + .unwrap(); assert_eq!((out.resolution, out.height), (64, 32)); let pos = &out.maps[&BakedMap::Position]; assert_eq!(pos.len(), 64 * 32 * 3); @@ -716,7 +809,18 @@ fn uv_tiles_bake_side_by_side_in_one_atlas() { assert!(x_at(2, y) < 0.3 && x_at(29, y) < 0.5, "tile 1001 holds the left plane"); assert!(x_at(34, y) > 0.5 && x_at(62, y) > 0.7, "tile 1002 holds the right plane"); } - let too_many = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (0, 1) }; + let too_many = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (0, 1), + }; assert!(bake(&too_many, &Progress::new()).is_err()); } @@ -732,7 +836,11 @@ fn curvature_on_uv_tiles_matches_a_single_tile() { }; let bake_tiles = |m: &Mesh, tiles| { let bvh = Bvh::new(m); - bake(&BakeRequest { mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles }, &Progress::new()).unwrap() + bake( + &BakeRequest { low_base_color: &[], mesh: m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, cage_paint: None, tiles }, + &Progress::new(), + ) + .unwrap() }; let (a, b) = (bake_tiles(&one, (1, 1)), bake_tiles(&two, (2, 1))); let (a, b) = (&a.maps[&BakedMap::Curvature], &b.maps[&BakedMap::Curvature]); @@ -767,7 +875,9 @@ fn near_wall(m: &Mesh, s: &BakeSettings, map: BakedMap) -> f32 { #[test] fn ambient_occlusion_settings_shape_the_occlusion() { let mesh = floor_and_wall(false); - let base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0); + let mut base = with_rays(settings(32, &[BakedMap::AmbientOcclusion]), 64, 2.0); + base.maps.ao.parameters.rays.relative_to_bounding_box = false; + base.maps.ao.parameters.rays.max_distance = (mesh.bounds().1 - mesh.bounds().0).length() * 2.0; let ao = |configure: &dyn Fn(&mut BakeSettings)| { let mut bake_settings = base.clone(); configure(&mut bake_settings); @@ -865,7 +975,7 @@ fn position_modes() { let (box_positions, sphere_positions) = (positions(PositionMode::BoundingBox), positions(PositionMode::BoundingSphere)); assert!(box_positions.iter().all(|p| p[1] == 0.0) && box_positions.iter().any(|p| p[0] < 0.05) && box_positions.iter().any(|p| p[0] > 0.95)); - let unit_scale = 0.5 / 8.0f32.sqrt(); + let unit_scale = 0.25; assert!(sphere_positions.iter().all(|p| p[1] == 0.5 && (p[0] - 0.5).abs() <= 2.0 * unit_scale + 1e-4 && (p[2] - 0.5).abs() <= 2.0 * unit_scale + 1e-4)); let raw_settings = { @@ -898,13 +1008,15 @@ fn opacity_samples_the_high_poly_base_color_texture() { let bake_with = |base_color: BaseColor| { let base_color = [Some(Arc::new(base_color))]; let request = BakeRequest { + low_base_color: &[], mesh: &low, bvh: &low_bvh, material: 0, settings: &bake_settings, - high: Some(HighPoly { mesh: &high, bvh: &high_bvh, base_color: &base_color }), + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &base_color }), cage: None, skew: None, + cage_paint: None, tiles: (1, 1), }; bake(&request, &Progress::new()).unwrap() @@ -937,7 +1049,18 @@ fn a_failing_tracer_falls_back_to_the_cpu() { let m = floor_and_wall(false); let bvh = Bvh::new(&m); let s = with_rays(settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Thickness]), 8, 1.0); - let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None, skew: None, tiles: (1, 1) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &m, + bvh: &bvh, + material: 0, + settings: &s, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; let out = bake_on(&req, &Progress::new(), &Broken).unwrap(); assert_eq!(out.tracer, "CPU (Broken unavailable: no device)"); assert_eq!(out.maps, bake(&req, &Progress::new()).unwrap().maps); @@ -946,7 +1069,7 @@ fn a_failing_tracer_falls_back_to_the_cpu() { base.maps.select([BakedMap::Position]); base }; - assert_eq!(bake_on(&BakeRequest { settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU"); + assert_eq!(bake_on(&BakeRequest { low_base_color: &[], settings: &flat, ..req }, &Progress::new(), &Broken).unwrap().tracer, "CPU"); } fn plane(y: f32, half: f32, n: Vec3) -> Mesh { @@ -970,17 +1093,19 @@ fn skew_correction_preserves_uniform_mesh_normals_and_rejects_invalid_values() { base.cage = CageSettings { max_frontal: 0.5, max_rear: 0.1, average_normals: true, ..base.cage }; base }; - let diag = (low.bounds().1 - low.bounds().0).length(); + let diag = (low.bounds().1 - low.bounds().0).max_element(); let (front, rear) = (0.5 * diag, 0.1 * diag); - let height = |skew: Option<&SkewMap>| { + let height = |skew: Option<&BakePaintMap>| { let req = BakeRequest { + low_base_color: &[], mesh: &low, bvh: &lb, material: 0, settings: &s, - high: Some(HighPoly { mesh: &high, bvh: &hb, base_color: &[] }), + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &hb, base_color: &[] }), cage: None, skew, + cage_paint: None, tiles: (1, 1), }; bake(&req, &Progress::new()).unwrap().maps[&BakedMap::Height][8 * 16 + 8] @@ -988,9 +1113,20 @@ fn skew_correction_preserves_uniform_mesh_normals_and_rejects_invalid_values() { let expect = |c: f32| 0.5 + (0.3 / c) / (front + rear); let plain = height(None); assert!((plain - expect(0.8)).abs() < 1e-3, "leaning rays: {plain} vs {}", expect(0.8)); - assert!((height(Some(&SkewMap::constant(0.0))) - plain).abs() < 1e-6, "black leaves the rays alone"); - assert!((height(Some(&SkewMap::constant(1.0))) - plain).abs() < 1e-4); - let bad = SkewMap { values: vec![f32::NAN], ..SkewMap::constant(0.0) }; - let req = BakeRequest { mesh: &low, bvh: &lb, material: 0, settings: &s, high: None, cage: None, skew: Some(&bad), tiles: (1, 1) }; + assert!((height(Some(&BakePaintMap::constant(0.0))) - plain).abs() < 1e-6, "black leaves the rays alone"); + assert!((height(Some(&BakePaintMap::constant(1.0))) - plain).abs() < 1e-4); + let bad = BakePaintMap { values: vec![f32::NAN], ..BakePaintMap::constant(0.0) }; + let req = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &lb, + material: 0, + settings: &s, + high: None, + cage: None, + skew: Some(&bad), + cage_paint: None, + tiles: (1, 1), + }; assert!(matches!(bake(&req, &Progress::new()), Err(BakeError::Invalid(_)))); } diff --git a/crates/bake/src/tracing/cpu_scene.rs b/crates/bake/src/tracing/cpu_scene.rs index 125e5a48..12f85f8b 100644 --- a/crates/bake/src/tracing/cpu_scene.rs +++ b/crates/bake/src/tracing/cpu_scene.rs @@ -12,13 +12,18 @@ impl CpuScene<'_> { } impl RayScene for CpuScene<'_> { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError> { let trace_mesh = self.mesh(mesh)?; Ok(rays .par_iter() - .map(|ray| match ray.key { - ANY => trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance), - key => trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| trace_mesh.key_matches(triangle, key)), + .map(|ray| { + if ray.key == ANY && !ignore_backface { + trace_mesh.bvh.closest(ray.origin, ray.direction, ray.max_distance) + } else { + trace_mesh.bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| { + trace_mesh.key_matches(triangle, ray.key) && !(ignore_backface && trace_mesh.back_facing(triangle, ray.direction)) + }) + } }) .collect()) } diff --git a/crates/bake/src/tracing/hemisphere.rs b/crates/bake/src/tracing/hemisphere.rs index a6f96e00..25d63e0c 100644 --- a/crates/bake/src/tracing/hemisphere.rs +++ b/crates/bake/src/tracing/hemisphere.rs @@ -1,5 +1,6 @@ use super::{ANY, Query, RayKind, TraceMesh}; use std::f32::consts::TAU; +use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode}; use texturecraft_geom::glam::Vec3; #[derive(Clone, Copy, Debug, PartialEq)] @@ -8,12 +9,15 @@ pub struct Hemisphere { pub rays: u32, /// Maximum ray distance in mesh units pub dmax: f32, + pub min_distance: f32, + pub attenuation: AmbientOcclusionAttenuation, + pub ground_height: Option, /// Ray origin offset along the geometric normal pub eps: f32, pub cos_max: f32, pub sin_max: f32, pub uniform: bool, - pub ignore_backface: bool, + pub ignore_backface: BackfaceMode, pub same_key: bool, } @@ -43,27 +47,42 @@ impl Hemisphere { pub fn evaluate(&self, mesh: &TraceMesh, query: &Query) -> [f32; 4] { let (axis, geometric_normal, origin) = self.frame(query); let (tangent, bitangent) = axis.any_orthonormal_pair(); - let key = if self.same_key && self.kind == RayKind::Occlusion { query.key } else { ANY }; - let filtered = key != ANY || (self.ignore_backface && self.kind == RayKind::Occlusion); + let key = if self.same_key { query.key } else { ANY }; + let filtered = key != ANY || self.ignore_backface != BackfaceMode::Never; let (mut accumulated, mut bent_normal, mut accepted_ray_count) = (0.0f32, Vec3::ZERO, 0u32); for ray_index in 0..self.rays { let direction = self.direction((tangent, bitangent, axis), ray_index, query.rot); if direction.dot(geometric_normal) <= 0.0 { continue; } - let hit = match filtered { - true => mesh.bvh.closest_filtered(origin, direction, self.dmax, &|tri| { - mesh.key_matches(tri, key) && !(self.ignore_backface && mesh.back_facing(tri, direction)) - }), - false => mesh.bvh.closest(origin, direction, self.dmax), + let ray_origin = origin + direction * self.min_distance; + let ray_length = (self.dmax - self.min_distance).max(0.0); + let hit = if filtered { + mesh.bvh.closest_filtered(ray_origin, direction, ray_length, &|triangle| { + let ignore_backface = match self.ignore_backface { + BackfaceMode::Never => false, + BackfaceMode::Always => true, + BackfaceMode::ByMeshName => mesh.backface_culling.get(triangle as usize).copied().unwrap_or(false), + }; + mesh.key_matches(triangle, key) && !(ignore_backface && mesh.back_facing(triangle, direction)) + }) + } else { + mesh.bvh.closest(ray_origin, direction, ray_length) }; + let mut distance = hit.map(|hit| hit.t + self.min_distance); + if let Some(height) = self.ground_height.filter(|_| direction.y < -1e-8) { + let ground_distance = (height - origin.y) / direction.y; + if (self.min_distance..=self.dmax).contains(&ground_distance) { + distance = Some(distance.map_or(ground_distance, |distance| distance.min(ground_distance))); + } + } match self.kind { RayKind::Occlusion => { - let occlusion = hit.map_or(0.0, |hit| 1.0 - (hit.t / self.dmax).powi(2)); + let occlusion = distance.map_or(0.0, |distance| self.occlusion(distance)); accumulated += occlusion; bent_normal += direction * (1.0 - occlusion); } - RayKind::Thickness => accumulated += hit.map_or(self.dmax, |hit| hit.t), + RayKind::Thickness => accumulated += distance.unwrap_or(self.dmax), } accepted_ray_count += 1; } @@ -73,9 +92,16 @@ impl Hemisphere { let bent_normal = bent_normal.try_normalize().unwrap_or(query.nrm); [ambient_occlusion, bent_normal.x, bent_normal.y, bent_normal.z] } - RayKind::Thickness => { - [if accepted_ray_count == 0 { 1.0 } else { (accumulated / accepted_ray_count as f32 / self.dmax).clamp(0.0, 1.0) }, 0.0, 0.0, 0.0] - } + RayKind::Thickness => [if accepted_ray_count == 0 { self.dmax } else { accumulated / accepted_ray_count as f32 }, 0.0, 0.0, 0.0], + } + } + + fn occlusion(&self, distance: f32) -> f32 { + let fraction = ((distance - self.min_distance) / (self.dmax - self.min_distance).max(f32::EPSILON)).clamp(0.0, 1.0); + match self.attenuation { + AmbientOcclusionAttenuation::None => 1.0, + AmbientOcclusionAttenuation::Linear => 1.0 - fraction, + AmbientOcclusionAttenuation::Smooth => 1.0 - fraction * fraction * (3.0 - 2.0 * fraction), } } } diff --git a/crates/bake/src/tracing/ray_scene.rs b/crates/bake/src/tracing/ray_scene.rs index 6249e241..9a800452 100644 --- a/crates/bake/src/tracing/ray_scene.rs +++ b/crates/bake/src/tracing/ray_scene.rs @@ -3,6 +3,6 @@ use crate::BakeError; use texturecraft_geom::Hit; pub trait RayScene: Send { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError>; + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError>; fn hemispheres(&mut self, passes: &[Hemisphere], queries: &[Query]) -> Result>, BakeError>; } diff --git a/crates/bake/src/tracing/trace_mesh.rs b/crates/bake/src/tracing/trace_mesh.rs index 7ad6010b..f4db3b14 100644 --- a/crates/bake/src/tracing/trace_mesh.rs +++ b/crates/bake/src/tracing/trace_mesh.rs @@ -8,6 +8,7 @@ pub struct TraceMesh<'a> { pub bvh: &'a Bvh, /// Part key per triangle in original mesh order pub keys: &'a [u32], + pub backface_culling: &'a [bool], } impl TraceMesh<'_> { diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 56a4d4e1..f78e9470 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, res).unwrap_or(1.0); + let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let px = &mut out[i * 4..i * 4 + 4]; px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; @@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let px = &mut out[i * 4..i * 4 + 4]; // The baked normal is the base the painted normal details sit on (as in export). let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample(BakedMap::Normal, x, y, res); + let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height)); match (n, base) { (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index de26d5bd..6c642b75 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1043,7 +1043,7 @@ impl<'a, 'b> Texel<'a, 'b> { } fn baked(&self, m: BakedMap) -> Option { - self.inp.baked.scalar(m, self.x, self.y, self.res) + self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height)) } /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its @@ -1179,7 +1179,7 @@ impl<'a, 'b> Texel<'a, 'b> { v += (val - v) * o; } EffectKind::ColorSelection { colors, tolerance } => { - let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, self.res); + let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height)); let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); let val = if hit { 1.0 } else { 0.0 }; v += (blend1(e.blend, v, val) - v) * o; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index 0924c351..cf640e0a 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -57,8 +57,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 { } /// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The -/// maps cover the texture set's texels at another density: `resolution` wide, and as tall as -/// the set's aspect makes them (square for classic sets, the UV tile grid's aspect otherwise). +/// width is `resolution`; height follows the output size and UV tile grid #[derive(Clone, Debug, Default, PartialEq)] pub struct BakedMaps { /// Width in texels. @@ -72,20 +71,21 @@ impl BakedMaps { self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) } - /// Sample map `m` at texel (x, y) of an image `res` wide with the same aspect (nearest texel - /// of the bake). - pub fn sample(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<[f32; 3]> { - let data = self.maps.get(&m)?; - let r = self.resolution.max(1) as u64; - let (bx, by) = ((x as u64 * r / res.max(1) as u64).min(r - 1), (y as u64 * r / res.max(1) as u64).min(self.height(m).max(1) as u64 - 1)); - let comps = m.components(); - let i = ((by * r + bx) as usize) * comps; - let s = data.get(i..i + comps)?; - Some(if comps == 3 { [s[0], s[1], s[2]] } else { [s[0]; 3] }) + /// Sample the corresponding texel of an image with the supplied output size + pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { + let data = self.maps.get(&map)?; + let width = u64::from(self.resolution.max(1)); + let height = u64::from(self.height(map).max(1)); + let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); + let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); + let component_count = map.components(); + let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; + let texel = data.get(offset..offset.checked_add(component_count)?)?; + Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) } - pub fn scalar(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option { - self.sample(m, x, y, res).map(|v| v[0]) + pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { + self.sample(m, x, y, size).map(|v| v[0]) } } diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index df3ddf46..4b21a20d 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -4,8 +4,12 @@ mod ambient_occlusion_attenuation; mod ambient_occlusion_settings; mod backface_mode; mod bake_antialiasing; +mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod mesh_match_mode; +mod skew_correction_method; +pub use bake_paint_target::BakePaintTarget; mod baked_map; mod bent_normal_settings; mod cage_settings; @@ -58,6 +62,7 @@ pub use id_settings::IdSettings; pub use map_settings::MapSettings; pub use mesh_curvature_settings::MeshCurvatureSettings; pub use mesh_map_settings::MeshMapSettings; +pub use mesh_match_mode::MeshMatchMode; pub use normal_map_curvature_settings::NormalMapCurvatureSettings; pub use position_axis::PositionAxis; pub use position_mode::PositionMode; @@ -66,6 +71,7 @@ pub use position_settings::PositionSettings; pub use ray_distribution::RayDistribution; pub use ray_settings::RaySettings; pub use self_occlusion::SelfOcclusion; +pub use skew_correction_method::SkewCorrectionMethod; pub use skew_settings::SkewSettings; pub use thickness_normalization::ThicknessNormalization; pub use thickness_settings::ThicknessSettings; diff --git a/crates/core/src/bake/bake_paint_target.rs b/crates/core/src/bake/bake_paint_target.rs new file mode 100644 index 00000000..ed59c5c6 --- /dev/null +++ b/crates/core/src/bake/bake_paint_target.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum BakePaintTarget { + Cage, + #[default] + Skew, +} diff --git a/crates/core/src/bake/high_poly_settings.rs b/crates/core/src/bake/high_poly_settings.rs index 414989cc..5c27f5d1 100644 --- a/crates/core/src/bake/high_poly_settings.rs +++ b/crates/core/src/bake/high_poly_settings.rs @@ -1,3 +1,4 @@ +use super::MeshMatchMode; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -5,6 +6,7 @@ use serde::{Deserialize, Serialize}; pub struct HighPolySettings { pub use_low_as_high: bool, pub ignore_backface: bool, + pub match_mode: MeshMatchMode, pub low_suffix: String, pub high_suffix: String, pub ignore_backface_suffix: String, @@ -15,6 +17,7 @@ impl Default for HighPolySettings { Self { use_low_as_high: false, ignore_backface: true, + match_mode: MeshMatchMode::Always, low_suffix: "_low".into(), high_suffix: "_high".into(), ignore_backface_suffix: "_ignorebf".into(), diff --git a/crates/core/src/bake/mesh_curvature_settings.rs b/crates/core/src/bake/mesh_curvature_settings.rs index c1c61c05..55860ecb 100644 --- a/crates/core/src/bake/mesh_curvature_settings.rs +++ b/crates/core/src/bake/mesh_curvature_settings.rs @@ -24,7 +24,7 @@ impl Default for MeshCurvatureSettings { self_intersection: SelfOcclusion::Always, auto_tonemapping: true, value_min: -1.0, - value_max: -1.0, + value_max: 1.0, } } } diff --git a/crates/core/src/bake/mesh_match_mode.rs b/crates/core/src/bake/mesh_match_mode.rs new file mode 100644 index 00000000..7030f640 --- /dev/null +++ b/crates/core/src/bake/mesh_match_mode.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum MeshMatchMode { + #[default] + Always, + ByMeshName, +} diff --git a/crates/core/src/bake/position_mode.rs b/crates/core/src/bake/position_mode.rs index b2f85005..dbba5e73 100644 --- a/crates/core/src/bake/position_mode.rs +++ b/crates/core/src/bake/position_mode.rs @@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize}; pub enum PositionMode { /// Each axis spans the bounding box (0..1 per axis) BoundingBox, - /// One scale for every axis: the bounding sphere around the box centre (keeps proportions) + /// One scale for every axis: the largest extent around the box centre (keeps proportions) #[default] BoundingSphere, /// Keep mesh coordinates without normalization diff --git a/crates/core/src/bake/skew_correction_method.rs b/crates/core/src/bake/skew_correction_method.rs new file mode 100644 index 00000000..82e0a41e --- /dev/null +++ b/crates/core/src/bake/skew_correction_method.rs @@ -0,0 +1,8 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SkewCorrectionMethod { + #[default] + MeshNormalsBased, + FaceNormalsBased, +} diff --git a/crates/core/src/bake/skew_settings.rs b/crates/core/src/bake/skew_settings.rs index 296bacbf..8a42b0fc 100644 --- a/crates/core/src/bake/skew_settings.rs +++ b/crates/core/src/bake/skew_settings.rs @@ -1,9 +1,11 @@ +use super::SkewCorrectionMethod; use serde::{Deserialize, Serialize}; /// Skew controls independent of the painted pixel asset #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct SkewSettings { + pub method: SkewCorrectionMethod, pub edge_protection: bool, /// Edge protection distance (0..=1), retained while protection is disabled pub edge_distance: f32, @@ -13,6 +15,6 @@ pub struct SkewSettings { impl Default for SkewSettings { fn default() -> Self { - Self { edge_protection: false, edge_distance: 0.15, edge_contrast: 0.5 } + Self { method: SkewCorrectionMethod::MeshNormalsBased, edge_protection: false, edge_distance: 0.15, edge_contrast: 0.5 } } } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ae96b85e..ddaa6045 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -14,10 +14,11 @@ pub mod layer; pub mod project; pub use bake::{ - AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, BentNormalSettings, - CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, HeightSettings, HighPolySettings, - IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, NormalMapCurvatureSettings, PositionAxis, PositionMode, - PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, SkewSettings, ThicknessNormalization, ThicknessSettings, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakedMap, + BentNormalSettings, CageSettings, CageType, CommonBakeSettings, CurvatureMethod, CurvatureSettings, GroundPlaneSettings, HeightNormalization, + HeightSettings, HighPolySettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshCurvatureSettings, MeshMapSettings, MeshMatchMode, + NormalMapCurvatureSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, RayDistribution, RaySettings, SelfOcclusion, + SkewCorrectionMethod, SkewSettings, ThicknessNormalization, ThicknessSettings, }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 9264e3f4..708560f0 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -14,15 +14,15 @@ fn reference_defaults_cover_common_and_per_map_settings() { thickness_rays["max_distance"] = json!(0.1); let mut expected = json!({ "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 1, "apply_diffusion": true}, - "high_poly": {"use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, + "high_poly": {"match_mode": "Always", "use_low_as_high": false, "ignore_backface": true, "low_suffix": "_low", "high_suffix": "_high", "ignore_backface_suffix": "_ignorebf"}, "cage": {"kind": "DistanceBased", "max_frontal": 0.01, "max_rear": 0.01, "relative_to_bounding_box": true, "average_normals": true}, - "skew": {"edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "skew": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { "method": "NormalMap", "normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0}, - "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": -1.0} + "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0} }, "position": {"axis": "All", "normalization": "BoundingSphere", "scale": "FullScene"}, "thickness": {"rays": thickness_rays, "self_occlusion": "Always", "normalization": "RelativeToMinMax"}, @@ -75,6 +75,8 @@ fn assert_choices>, + pub mesh: Arc, + pub base_color: Vec>>, +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs new file mode 100644 index 00000000..260002db --- /dev/null +++ b/crates/engine/src/bake/bake_meshes.rs @@ -0,0 +1,29 @@ +use super::{BakeMesh, MergedHigh}; +use std::sync::{Arc, OnceLock}; +use texturecraft_geom::{Bvh, Mesh}; + +/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the +/// undo history. +#[derive(Clone, Debug, Default)] +pub struct BakeMeshes { + pub(crate) low_base_color: OnceLock>, + pub high: Vec, + pub cage: Option, + /// Every high poly appended into one mesh (rebuilt when the list changes). + pub(crate) merged: Option, +} + +impl BakeMeshes { + pub(crate) fn rebuild(&mut self) { + self.merged = (!self.high.is_empty()).then(|| { + let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); + for (file_index, source) in self.high.iter().enumerate() { + file_ids.extend(std::iter::repeat_n(file_index as u32, source.mesh.submeshes.len())); + mesh.append(&source.mesh); + base_color.extend(source.base_color.iter().cloned().chain(std::iter::repeat(None)).take(source.mesh.materials.len())); + } + let bvh = Bvh::new(&mesh); + MergedHigh { file_ids: Arc::new(file_ids), mesh: Arc::new(mesh), bvh: Arc::new(bvh), base_color: Arc::new(base_color) } + }); + } +} diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs new file mode 100644 index 00000000..831a7abc --- /dev/null +++ b/crates/engine/src/bake/bake_task.rs @@ -0,0 +1,49 @@ +use super::MergedHigh; +use crate::{EngineError, Result}; +use std::sync::Arc; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// A self-contained bake task that can run on another thread. +pub struct BakeTask { + pub low_base_color: super::MaterialColors, + pub ts: usize, + pub mesh: Arc, + pub bvh: Arc, + pub material: usize, + pub settings: BakeSettings, + /// The merged high polys, unless the set bakes from the low poly. + pub high: Option, + pub cage: Option>, + pub skew: Option>, + pub cage_paint: Option>, + /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. + pub tiles: (u32, u32), + /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). + pub tracer: Option>, +} + +impl BakeTask { + pub fn run(&self, progress: &Progress) -> Result { + let high = + self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); + let request = BakeRequest { + low_base_color: &self.low_base_color, + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high, + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: self.tiles, + }; + match &self.tracer { + Some(tracer) => bake_on(&request, progress, tracer.as_ref()), + None => bake(&request, progress), + } + .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) + } +} diff --git a/crates/engine/src/bake/merged_high.rs b/crates/engine/src/bake/merged_high.rs new file mode 100644 index 00000000..317bb592 --- /dev/null +++ b/crates/engine/src/bake/merged_high.rs @@ -0,0 +1,11 @@ +use std::sync::Arc; +use texturecraft_geom::{Bvh, Mesh}; + +/// Every high poly appended into one mesh, its BVH and per-material base colors. +#[derive(Clone, Debug)] +pub struct MergedHigh { + pub file_ids: Arc>, + pub mesh: Arc, + pub bvh: Arc, + pub base_color: super::MaterialColors, +} diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs new file mode 100644 index 00000000..075943b3 --- /dev/null +++ b/crates/engine/src/bake/mod.rs @@ -0,0 +1,11 @@ +mod bake_mesh; +mod bake_meshes; +mod bake_task; +mod merged_high; + +pub use bake_mesh::BakeMesh; +pub use bake_meshes::BakeMeshes; +pub use bake_task::BakeTask; +pub use merged_high::MergedHigh; + +type MaterialColors = std::sync::Arc>>>; diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake_cmds.rs index 158d74f0..d56a2bc0 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake_cmds.rs @@ -2,16 +2,17 @@ //! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU //! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise. -use std::collections::BTreeSet; +use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; +use texturecraft_core::BakePaintTarget; +use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; -use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, MAX_RAYS, Progress, SkewMap, bake, bake_on}; +use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::{BaseColor, Bvh, Mesh}; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; @@ -53,54 +54,12 @@ pub fn specs() -> Vec { s.modified = true; Ok(meshes_json(s)) }), - cmd!( - "bake.skew.set", - "Set skew correction", - [], - None, - "{value?: 0..1 (a constant map, default 1) | path: a greyscale image over the UV atlas (white turns the rays onto the base normal, black keeps the cage's averaged direction), edgeDistance?: fraction of the mesh diagonal over which hard edges hold the correction back (default 0), edgeContrast?: falloff exponent (default 1)} → {skew}. Applies to the transfer rays of a bake from the built-in distance cage; a cage mesh ignores it", - always, - skew_set - ), - cmd!( - "bake.skew.paint", - "Paint skew correction", - [], - None, - "{points: [[u, v], ...] (atlas uv, a stroke), radius?: uv units (default 0.03), value?: 0..1 (1 turns rays onto the base normal, 0 erases; default 1), hardness?: 0..1 (default 0.5), strength?: 0..1 per dab (default 1), size?: px of a new or constant map (default 1024, 16..4096)} → {skew}. Paints into the skew map; a missing or constant map is first widened to `size`", - always, - skew_paint - ), - cmd!("bake.skew.clear", "Remove skew correction", [], None, "{}", always, |s, _| { - s.bake_meshes.skew = None; - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) - }), ] } /// A mesh file as saved in a project: (file name, bytes). type MeshFile = (String, Vec); -/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the -/// project), parsed mesh and its materials' base colors (high polys). -#[derive(Clone, Debug)] -pub struct BakeMesh { - pub name: String, - pub bytes: Arc>, - pub mesh: Arc, - pub base_color: Vec>>, -} - -/// Every high poly appended into one mesh, its BVH and per-material base colors. -#[derive(Clone, Debug)] -pub struct MergedHigh { - pub mesh: Arc, - pub bvh: Arc, - pub base_color: Arc>>>, -} - static GPU_TRACER: OnceLock> = OnceLock::new(); /// Cast bake rays with `tracer` (the apps install the render crate's GPU baker at start-up); @@ -109,74 +68,6 @@ pub fn install_gpu_tracer(tracer: Arc) { let _ = GPU_TRACER.set(tracer); } -/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the -/// undo history. -#[derive(Clone, Debug, Default)] -pub struct BakeMeshes { - pub high: Vec, - pub cage: Option, - /// Skew correction of the transfer rays (saved in the project as `skew.bin`). - pub skew: Option>, - /// Counts changes to `skew`, so a view knows when to redraw it. - pub skew_rev: u64, - /// Every high poly appended into one mesh (rebuilt when the list changes). - merged: Option, -} - -impl BakeMeshes { - // shortcut: the merged copy doubles high-poly memory; build the BVH over the parts in place if - // multi-million-triangle sets run out of memory. - fn rebuild(&mut self) { - self.merged = (!self.high.is_empty()).then(|| { - let (mut all, mut base_color) = (Mesh::default(), Vec::new()); - for h in &self.high { - all.append(&h.mesh); - base_color.extend(h.base_color.iter().cloned().chain(std::iter::repeat(None)).take(h.mesh.materials.len())); - } - let bvh = Bvh::new(&all); - MergedHigh { mesh: Arc::new(all), bvh: Arc::new(bvh), base_color: Arc::new(base_color) } - }); - } -} - -/// A self-contained bake task that can run on another thread. -pub struct BakeTask { - pub ts: usize, - pub mesh: Arc, - pub bvh: Arc, - pub material: usize, - pub settings: BakeSettings, - /// The merged high polys, unless the set bakes from the low poly. - pub high: Option, - pub cage: Option>, - pub skew: Option>, - /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. - pub tiles: (u32, u32), - /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). - pub tracer: Option>, -} - -impl BakeTask { - pub fn run(&self, progress: &Progress) -> Result { - let high = self.high.as_ref().map(|h| HighPoly { mesh: &h.mesh, bvh: &h.bvh, base_color: &h.base_color }); - let req = BakeRequest { - mesh: &self.mesh, - bvh: &self.bvh, - material: self.material, - settings: &self.settings, - high, - cage: self.cage.as_deref(), - skew: self.skew.as_deref(), - tiles: self.tiles, - }; - match &self.tracer { - Some(t) => bake_on(&req, progress, t.as_ref()), - None => bake(&req, progress), - } - .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) - } -} - /// A mesh file name made unique among `taken` (and safe as a project file entry). fn unique_name(file_name: &str, taken: &[&str]) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh"); @@ -199,27 +90,66 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { impl Session { pub fn bake_task(&self, ts: usize) -> Result { let set = self.doc.project.texture_set(ts)?; + let needs_low_color = set.bake.maps.opacity.is_enabled + || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); + let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) { + self.bake_meshes + .low_base_color + .get_or_init(|| match &self.mesh_source { + Some((extension, bytes)) => texturecraft_formats::import_high_poly_bytes(&format!("mesh.{extension}"), bytes) + .map(|imported| Arc::new(imported.base_color.into_iter().map(|color| color.map(Arc::new)).collect())) + .map_err(|error| error.to_string()), + None => Ok(Arc::new(Vec::new())), + }) + .clone() + .map_err(EngineError::Other)? + } else { + Arc::new(Vec::new()) + }; let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = high.as_ref().and(self.bake_meshes.cage.as_ref()).map(|c| c.mesh.clone()); - let skew = high.as_ref().and(self.bake_meshes.skew.clone()); + let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { + Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) + } else { + None + }; + let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned()); + let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned()); let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); let tracer = GPU_TRACER.get().cloned(); - Ok(BakeTask { ts, mesh: self.mesh.clone(), bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), high, cage, skew, tiles, tracer }) + Ok(BakeTask { + low_base_color, + ts, + mesh: self.mesh.clone(), + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew, + cage_paint, + tiles, + tracer, + }) } - /// Store a finished bake (one undo step). - pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> { - self.log.push(format!("Baked texture set {ts} ({})", out.tracer)); - self.edit("Bake mesh maps", |s| { - let maps: BTreeSet = out.maps.keys().copied().collect(); - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = out.resolution; - for (m, data) in out.maps { - entry.maps.insert(m, Arc::new(data)); - } - s.doc.project.texture_set_mut(ts)?.baked.extend(maps); - Ok(()) - })?; + /// Store a finished bake as one undo step + pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + let tracer = output.tracer.clone(); + self.edit("Bake mesh maps", |session| session.store_bake(texture_set, output))?; + self.log.push(format!("Baked texture set {texture_set} ({tracer})")); + Ok(()) + } + + fn store_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { + let entry = self.doc.baked.entry(texture_set).or_default(); + if entry.resolution != output.resolution || entry.maps.keys().any(|map| entry.height(*map) != output.height) { + entry.maps.clear(); + } + entry.resolution = output.resolution; + for (map, pixels) in output.maps { + entry.maps.insert(map, Arc::new(pixels)); + } + self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); Ok(()) } @@ -306,29 +236,28 @@ impl Session { } } - /// The skew map of a project file, if it passes the baker's checks. - pub(crate) fn load_skew(&mut self, skew: Option) { - let Some(k) = skew else { return }; - let map = SkewMap { width: k.width, height: k.height, values: k.values, edge_distance: k.edge_distance, edge_contrast: k.edge_contrast }; - match map.validate() { - Ok(()) => { - self.bake_meshes.skew = Some(Arc::new(map)); - self.bake_meshes.skew_rev += 1; + pub(crate) fn load_bake_paint(&mut self, maps: BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData>) { + for (key, data) in maps { + if key.0 >= self.doc.project.texture_sets.len() { + self.log.push(format!("skipped bake paint map for missing texture set {}", key.0)); + continue; + } + let map = BakePaintMap { width: data.width, height: data.height, values: data.values }; + match map.validate() { + Ok(()) => { + self.doc.bake_paint.insert(key, Arc::new(map)); + } + Err(error) => self.log.push(format!("skipped bake paint map: {error}")), } - Err(e) => self.log.push(format!("skipped skew map: {e}")), } } - /// The skew map for a project file. - pub(crate) fn saved_skew(&self) -> Option { - let k = self.bake_meshes.skew.as_ref()?; - Some(texturecraft_formats::SkewData { - width: k.width, - height: k.height, - values: k.values.clone(), - edge_distance: k.edge_distance, - edge_contrast: k.edge_contrast, - }) + pub(crate) fn saved_bake_paint(&self) -> BTreeMap<(usize, BakePaintTarget), texturecraft_formats::BakePaintData> { + self.doc + .bake_paint + .iter() + .map(|(key, map)| (*key, texturecraft_formats::BakePaintData { width: map.width, height: map.height, values: map.values.clone() })) + .collect() } /// The bake meshes for a project file: (high polys, cage). @@ -341,9 +270,11 @@ impl Session { /// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`). pub fn meshes_json(s: &Session) -> Value { let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::>() }); - let skew = - s.bake_meshes.skew.as_ref().map(|k| json!({ "width": k.width, "height": k.height, "edgeDistance": k.edge_distance, "edgeContrast": k.edge_contrast })); - json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": skew }) + let painted = |target| s.doc.bake_paint.get(&(s.ts(), target)).map(|map| json!({ "width": map.width, "height": map.height })); + json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::>(), "cage": s.bake_meshes.cage.as_ref().map(one), "skew": painted(BakePaintTarget::Skew), "paintedCage": painted(BakePaintTarget::Cage), "paintMaps": s.doc.bake_paint.iter().map(|((texture_set, target), map)| { + let default = match target { BakePaintTarget::Cage => 1.0, BakePaintTarget::Skew => 0.0 }; + json!({"textureSet": texture_set, "target": target, "width": map.width, "height": map.height, "paintedTexels": map.values.iter().filter(|value| **value != default).count()}) + }).collect::>() }) } #[cfg(not(target_arch = "wasm32"))] @@ -377,44 +308,6 @@ fn high_remove(s: &mut Session, p: &Value) -> Result { Ok(meshes_json(s)) } -/// The greyscale skew map of an image file (the mean of its colour channels, as stored). -#[cfg(not(target_arch = "wasm32"))] -fn skew_image(path: &str) -> Result<(u32, u32, Vec)> { - const MAX_BYTES: u64 = 256 << 20; - let cmd = "bake.skew.set"; - let len = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?.len(); - if len > MAX_BYTES { - return Err(bad(cmd, format!("{path} is over 256 MiB"))); - } - let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; - // The size is checked from the header, before the pixels are decoded. - let img = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|e| bad(cmd, format!("{path}: {e}")))?; - Ok((img.width, img.height, img.rgba.iter().map(|p| (p[0] + p[1] + p[2]) / 3.0).collect())) -} - -#[cfg(target_arch = "wasm32")] -fn skew_image(_: &str) -> Result<(u32, u32, Vec)> { - Err(EngineError::Other("file paths are not available in the browser".into())) -} - -fn skew_set(s: &mut Session, p: &Value) -> Result { - let cmd = "bake.skew.set"; - let mut map = match strp(p, "path") { - Some(path) => { - let (width, height, values) = skew_image(path)?; - SkewMap { width, height, values: values.into_iter().map(|v| v.clamp(0.0, 1.0)).collect(), ..SkewMap::constant(0.0) } - } - None => SkewMap::constant(f32p(p, "value").unwrap_or(1.0).clamp(0.0, 1.0)), - }; - map.edge_distance = f32p(p, "edgeDistance").unwrap_or(0.0); - map.edge_contrast = f32p(p, "edgeContrast").unwrap_or(1.0); - map.validate().map_err(|e| bad(cmd, e.to_string()))?; - s.bake_meshes.skew = Some(Arc::new(map)); - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) -} - fn cage_set(s: &mut Session, p: &Value) -> Result { s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) } @@ -603,11 +496,17 @@ fn validate_model_settings(settings: &BakeSettings, command: &str) -> Result<()> range("minimum occluder distance", rays.min_distance, 0.00001, 1.0)?; range("maximum occluder distance", rays.max_distance, 0.00001, if rays.relative_to_bounding_box { 1.0 } else { 10.0 })?; range("spread angle", rays.spread, 0.0, 180.0)?; + if rays.min_distance > rays.max_distance { + return Err(bad(command, "minimum occluder distance must not exceed maximum distance")); + } } let curvature = &settings.maps.curvature.parameters; if !(1..=256).contains(&curvature.mesh.rays) { return Err(bad(command, "curvature rays must be in 1..=256")); } + if !curvature.mesh.auto_tonemapping && curvature.mesh.value_min >= curvature.mesh.value_max { + return Err(bad(command, "curvature minimum must be below maximum")); + } range("sampling radius", curvature.mesh.sampling_radius, 0.00001, if curvature.mesh.relative_to_bounding_box { 10.0 } else { 1.0 })?; for (name, value, minimum, maximum) in [ ("frontal distance", settings.cage.max_frontal, 0.0, 0.05), @@ -662,24 +561,28 @@ fn apply_rays(settings: &mut RaySettings, params: &Value, command: &str) -> Resu Ok(()) } -/// Validate every target before applying settings +fn updated_settings(session: &Session, params: &Value, command: &str) -> Result> { + sets_param(session, command, params)? + .into_iter() + .map(|index| { + let mut settings = session.doc.project.texture_set(index)?.bake.clone(); + apply_settings(&mut settings, params, command)?; + Ok((index, settings)) + }) + .collect() +} + fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { - let sets = sets_param(session, command, params)?; - let mut next = Vec::with_capacity(sets.len()); - for &set_index in &sets { - let mut settings = session.doc.project.texture_set(set_index)?.bake.clone(); - apply_settings(&mut settings, params, command)?; - next.push((set_index, settings)); + let next = updated_settings(session, params, command)?; + let sets = next.iter().map(|(index, _)| *index).collect(); + if next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)) { + session.edit("Bake Settings", |session| { + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + } + Ok(()) + })?; } - - for (set_index, settings) in next { - let texture_set = session.doc.project.texture_set_mut(set_index)?; - if texture_set.bake != settings { - texture_set.bake = settings; - session.modified = true; - } - } - Ok(sets) } @@ -700,57 +603,27 @@ fn settings(session: &mut Session, params: &Value) -> Result { Ok(json!(result)) } -fn bake_run(s: &mut Session, p: &Value) -> Result { - let sets = set_settings(s, p, "bake.run")?; - let cpu = boolp(p, "cpu") == Some(true); - let tracer = sets.iter().map(|&ts| s.bake_now(ts, cpu)).collect::>>()?; - s.update(); - Ok(json!({ "baked": sets, "tracer": tracer })) -} - -fn skew_paint(s: &mut Session, p: &Value) -> Result { - use texturecraft_geom::glam::Vec2; - let cmd = "bake.skew.paint"; - const MAX_POINTS: usize = 100_000; - let points: Vec = p - .get("points") - .and_then(Value::as_array) - .ok_or_else(|| bad(cmd, "`points` is required: [[u, v], ...]"))? - .iter() - .map(|q| match (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) { - (Some(u), Some(v)) => Ok(Vec2::new(u as f32, v as f32)), - _ => Err(bad(cmd, "each point is [u, v]")), - }) - .collect::>()?; - if points.is_empty() || points.len() > MAX_POINTS { - return Err(bad(cmd, format!("give 1 to {MAX_POINTS} points"))); - } - let size = p.get("size").and_then(Value::as_u64).unwrap_or(1024); - if !(16..=4096).contains(&size) { - return Err(bad(cmd, "`size` is 16 to 4096")); - } - let (value, radius) = (f32p(p, "value").unwrap_or(1.0), f32p(p, "radius").unwrap_or(0.03)); - if !(radius.is_finite() && radius > 0.0 && radius <= 1.0) { - return Err(bad(cmd, "`radius` is above 0 and at most 1 (uv units)")); - } - let (hardness, strength) = (f32p(p, "hardness").unwrap_or(0.5), f32p(p, "strength").unwrap_or(1.0)); - let stroke = |m: &mut SkewMap| m.paint(&points, radius, value, hardness, strength).map_err(|e| bad(cmd, e.to_string())); - match s.bake_meshes.skew.as_mut() { - // In place: the map is copied only while a running bake still holds it, and `paint` - // refuses a stroke before it changes a texel. - Some(k) if k.values.len() > 1 => stroke(Arc::make_mut(k))?, - // A constant map has no resolution to paint at: widen it, keeping its value everywhere. - k => { - let mut map = match k { - Some(k) => k.resized(size as u32, size as u32), - None => SkewMap::constant(0.0).resized(size as u32, size as u32), +fn bake_run(session: &mut Session, params: &Value) -> Result { + let next = updated_settings(session, params, "bake.run")?; + let sets: Vec = next.iter().map(|(index, _)| *index).collect(); + let cpu = boolp(params, "cpu") == Some(true); + let tracers = session.edit("Bake mesh maps", |session| { + let mut tracers = Vec::with_capacity(next.len()); + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + let mut task = session.bake_task(index)?; + if cpu { + task.tracer = None; } - .map_err(|e| bad(cmd, e.to_string()))?; - stroke(&mut map)?; - s.bake_meshes.skew = Some(Arc::new(map)); + let output = task.run(&Progress::new())?; + tracers.push(output.tracer.clone()); + session.store_bake(index, output)?; } + Ok(tracers) + })?; + for (index, tracer) in sets.iter().zip(&tracers) { + session.log.push(format!("Baked texture set {index} ({tracer})")); } - s.bake_meshes.skew_rev += 1; - s.modified = true; - Ok(meshes_json(s)) + session.update(); + Ok(json!({ "baked": sets, "tracer": tracers })) } diff --git a/crates/engine/src/bake_paint_cmds.rs b/crates/engine/src/bake_paint_cmds.rs new file mode 100644 index 00000000..80cf4852 --- /dev/null +++ b/crates/engine/src/bake_paint_cmds.rs @@ -0,0 +1,147 @@ +use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; +use crate::{Result, Session, cmd}; +use serde_json::Value; +use std::sync::Arc; +use texturecraft_bake::BakePaintMap; +use texturecraft_core::BakePaintTarget; +use texturecraft_geom::glam::Vec2; + +pub fn specs() -> Vec { + vec![ + cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set( + session, + parameters, + BakePaintTarget::Skew + )), + cmd!( + "bake.skew.paint", + "Paint Skew Correction", + [], + None, + "{ts?, points: [[u,v],...], radius?: 0.03, value?: 1, hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}", + always, + |session, parameters| paint(session, parameters, BakePaintTarget::Skew) + ), + cmd!("bake.skew.clear", "Remove Skew Correction", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Skew)), + cmd!( + "bake.cage.paint", + "Paint Cage", + [], + None, + "{ts?, points: [[u,v],...], radius?: 0.03, value?: 1 (frontal distance multiplier, 0..1), hardness?: 0.5, strength?: 1, size?: 1024, continue?: false}", + always, + |session, parameters| paint(session, parameters, BakePaintTarget::Cage) + ), + cmd!("bake.cage.reset", "Reset Painted Cage", [], None, "{ts?}", always, |session, parameters| clear(session, parameters, BakePaintTarget::Cage)), + ] +} + +fn texture_set(session: &Session, parameters: &Value) -> Result { + let index = match parameters.get("ts") { + None => session.ts(), + Some(value) => value.as_u64().and_then(|value| usize::try_from(value).ok()).ok_or_else(|| bad("bake.paint", "ts must be a texture set index"))?, + }; + session.doc.project.texture_set(index)?; + Ok(index) +} + +fn number(parameters: &Value, name: &str, default: f32, minimum: f32, maximum: f32) -> Result { + if parameters.get(name).is_none() { + return Ok(default); + } + f32p(parameters, name) + .filter(|value| (minimum..=maximum).contains(value)) + .ok_or_else(|| bad("bake.paint", format!("{name} must be in {minimum}..={maximum}"))) +} + +fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + let texture_set = texture_set(session, parameters)?; + let map = match strp(parameters, "path") { + Some(path) => load_image(path)?, + None => BakePaintMap::constant(number(parameters, "value", 1.0, 0.0, 1.0)?), + }; + map.validate().map_err(|error| bad("bake.paint", error.to_string()))?; + session.edit("Set Bake Paint Map", |session| { + session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); + Ok(()) + })?; + Ok(crate::bake_cmds::meshes_json(session)) +} + +fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + let texture_set = texture_set(session, parameters)?; + if session.doc.bake_paint.contains_key(&(texture_set, target)) { + session.edit("Clear Bake Paint Map", |session| { + session.doc.bake_paint.remove(&(texture_set, target)); + Ok(()) + })?; + } + Ok(crate::bake_cmds::meshes_json(session)) +} + +fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { + const MAX_POINTS: usize = 100_000; + let texture_set = texture_set(session, parameters)?; + let points = parameters + .get("points") + .and_then(Value::as_array) + .filter(|points| !points.is_empty() && points.len() <= MAX_POINTS) + .ok_or_else(|| bad("bake.paint", "points must contain 1 to 100000 UV coordinates"))?; + let points = points + .iter() + .map(|point| { + let coordinate = |index| point.get(index).and_then(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()); + match (coordinate(0), coordinate(1)) { + (Some(u), Some(v)) => Ok(Vec2::new(u, v)), + _ => Err(bad("bake.paint", "each point must contain two finite UV coordinates")), + } + }) + .collect::>>()?; + let value = number(parameters, "value", 1.0, 0.0, 1.0)?; + let radius = number(parameters, "radius", 0.03, 0.00001, 1.0)?; + let hardness = number(parameters, "hardness", 0.5, 0.0, 1.0)?; + let strength = number(parameters, "strength", 1.0, 0.0, 1.0)?; + let size = match parameters.get("size") { + None => 1024, + Some(_) => u64p(parameters, "size").ok_or_else(|| bad("bake.paint", "size must be an integer"))?, + }; + if !(16..=4096).contains(&size) { + return Err(bad("bake.paint", "size must be between 16 and 4096")); + } + let default = match target { + BakePaintTarget::Cage => 1.0, + BakePaintTarget::Skew => 0.0, + }; + let label = match target { + BakePaintTarget::Cage => "Paint Cage", + BakePaintTarget::Skew => "Paint Skew Correction", + }; + session.edit_merging(label, boolp(parameters, "continue") == Some(true), |session| { + let map = session.doc.bake_paint.entry((texture_set, target)).or_insert_with(|| Arc::new(BakePaintMap::constant(default))); + if map.values.len() == 1 { + *map = Arc::new(map.resized(size as u32, size as u32).map_err(|error| bad("bake.paint", error.to_string()))?); + } + Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) + })?; + Ok(crate::bake_cmds::meshes_json(session)) +} + +#[cfg(not(target_arch = "wasm32"))] +fn load_image(path: &str) -> Result { + let length = std::fs::metadata(path).map_err(|error| bad("bake.paint", error.to_string()))?.len(); + if length > 256 << 20 { + return Err(bad("bake.paint", "image exceeds 256 MiB")); + } + let bytes = std::fs::read(path).map_err(|error| bad("bake.paint", error.to_string()))?; + let image = texturecraft_formats::decode_image_within(&bytes, texturecraft_bake::MAX_TEXELS).map_err(|error| bad("bake.paint", error.to_string()))?; + Ok(BakePaintMap { + width: image.width, + height: image.height, + values: image.rgba.iter().map(|pixel| ((pixel[0] + pixel[1] + pixel[2]) / 3.0).clamp(0.0, 1.0)).collect(), + }) +} + +#[cfg(target_arch = "wasm32")] +fn load_image(_: &str) -> Result { + Err(bad("bake.paint", "file paths are unavailable in the browser")) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 6dbc5ce6..94bb350c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -69,6 +69,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::bake_paint_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 78916328..25b6c91d 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -177,10 +177,11 @@ impl Session { check_materials(&pf.project, &mesh)?; let source = pf.mesh.clone(); let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); - let mut s = Session::new(Document { project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + let mut s = + Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; s.sync_images(); s.load_bake_meshes(pf.high_poly, pf.cage); - s.load_skew(pf.skew); + s.load_bake_paint(pf.bake_paint); Ok(s) } @@ -208,7 +209,7 @@ impl Session { mesh: self.mesh_source.clone(), high_poly, cage, - skew: self.saved_skew(), + bake_paint: self.saved_bake_paint(), thumbnail: None, resources: self.doc.resources.iter().map(|(k, v)| (k.clone(), v.as_ref().clone())).collect(), } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e5fca41e..ed07d645 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -9,6 +9,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_cmds; +#[path = "bake/mod.rs"] +mod bake_data; +mod bake_paint_cmds; pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; @@ -45,7 +48,7 @@ pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_cmds::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use path_tool::PathState; pub use project_cmds::sample_session; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 8a59b186..23144a61 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -71,7 +71,7 @@ impl Session { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); - let mut mini = Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }; + let mut mini = Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }; let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?; if let Ok(l) = mini.project.layer_mut(new) { l.name = name.to_string(); @@ -86,7 +86,7 @@ impl Session { mesh: None, high_poly: Vec::new(), cage: None, - skew: None, + bake_paint: BTreeMap::new(), thumbnail: None, resources, }; @@ -112,7 +112,7 @@ impl Session { .and_then(|t| t.stack.last().copied()) .ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?; let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); - let src = Document { project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() }; + let src = Document { bake_paint: BTreeMap::new(), project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() }; let id = self.edit("Add smart material", |s| { for (k, v) in &resources { s.doc.resources.entry(k.clone()).or_insert_with(|| v.clone()); diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 5f2c5069..2220df34 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -46,7 +46,10 @@ fn set(s: &mut Session, p: &Value) -> Result { let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => (set.bake.common.resolution.pixels().saturating_mul(cols), set.bake.common.resolution.pixels().saturating_mul(rows)), + None => { + let (width, height) = set.bake.common.output_size(); + (width.saturating_mul(cols), height.saturating_mul(rows)) + } }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 28843881..7ec12739 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -24,6 +24,7 @@ pub struct Document { pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap, + pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>, /// Imported image resources by name: original file bytes. pub resources: BTreeMap>>, } @@ -448,7 +449,11 @@ impl Session { ts.stack.push(id); project.texture_sets.push(ts); } - let mut s = Session::new(Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, mesh, mesh_source)?; + let mut s = Session::new( + Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, + mesh, + mesh_source, + )?; s.log.extend(log); Ok(s) } diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index c6b49a7c..d4659943 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -131,6 +131,7 @@ pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mu // Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the // map is affine (or None) over each destination tile. crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true)); + remap_bake_paint(doc, ts, old, &new, &map)?; if let Some(baked) = doc.baked.get(&ts) { match remap_baked(baked, old, &new, &map) { Some(b) => { @@ -186,32 +187,68 @@ pub(crate) fn remap_image( /// Baked maps of layout `old` resampled (nearest texel) into layout `new` at the same density /// per UV tile; None when that is beyond what bakes may hold. -fn remap_baked(b: &BakedMaps, old: &TextureSet, new: &TextureSet, map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync)) -> Option { - let grid = |t: &TextureSet| t.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); - let ((ocols, _), (ncols, nrows)) = (grid(old), grid(new)); - let per_tile = b.resolution / ocols.max(1); - let (w, h) = (per_tile.checked_mul(ncols)?, per_tile.checked_mul(nrows)?); - if w == 0 || u64::from(w) * u64::from(h) > texturecraft_bake::MAX_TEXELS { - return None; - } - let mut out = BakedMaps { resolution: w, ..b.clone() }; - for (m, data) in &b.maps { - let (comps, ow, oh) = (m.components(), b.resolution as usize, b.height(*m) as usize); - let neutral = m.neutral(); - let mut texels = vec![0.0f32; w as usize * h as usize * comps]; - texels.par_chunks_mut(w as usize * comps).enumerate().for_each(|(y, row)| { - for (x, px) in row.chunks_mut(comps).enumerate() { - let src = map([(x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32]).and_then(|o| { - let (sx, sy) = (((o[0] * ow as f32) as usize).min(ow.saturating_sub(1)), ((o[1] * oh as f32) as usize).min(oh.saturating_sub(1))); - let i = (sy * ow + sx) * comps; - data.get(i..i + comps) +fn remap_baked(baked: &BakedMaps, old: &TextureSet, new: &TextureSet, map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync)) -> Option { + let first_map = baked.maps.keys().next()?; + let (width, height) = remapped_size((baked.resolution, baked.height(*first_map)), old, new)?; + let mut output = BakedMaps { resolution: width, ..BakedMaps::default() }; + for (kind, data) in &baked.maps { + let (component_count, old_width, old_height) = (kind.components(), baked.resolution as usize, baked.height(*kind) as usize); + let neutral = kind.neutral(); + let mut texels = vec![0.0f32; width as usize * height as usize * component_count]; + texels.par_chunks_mut(width as usize * component_count).enumerate().for_each(|(y, row)| { + for (x, pixel) in row.chunks_mut(component_count).enumerate() { + let source = map([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]).and_then(|uv| { + let source_x = ((uv[0] * old_width as f32) as usize).min(old_width.saturating_sub(1)); + let source_y = ((uv[1] * old_height as f32) as usize).min(old_height.saturating_sub(1)); + let offset = (source_y * old_width + source_x) * component_count; + data.get(offset..offset + component_count) }); - px.copy_from_slice(src.unwrap_or(&neutral[..comps])); + pixel.copy_from_slice(source.unwrap_or(&neutral[..component_count])); } }); - out.maps.insert(*m, Arc::new(texels)); + output.maps.insert(*kind, Arc::new(texels)); } - Some(out) + Some(output) +} + +fn remapped_size((width, height): (u32, u32), old: &TextureSet, new: &TextureSet) -> Option<(u32, u32)> { + let grid = |set: &TextureSet| set.tile_grid().map_or((1, 1), |grid| (grid.cols, grid.rows)); + let ((old_columns, old_rows), (new_columns, new_rows)) = (grid(old), grid(new)); + let width = (width / old_columns.max(1)).max(1).checked_mul(new_columns)?; + let height = (height / old_rows.max(1)).max(1).checked_mul(new_rows)?; + (u64::from(width) * u64::from(height) <= texturecraft_bake::MAX_TEXELS).then_some((width, height)) +} + +fn remap_bake_paint( + document: &mut Document, + texture_set: usize, + old: &TextureSet, + new: &TextureSet, + map: &(dyn Fn([f32; 2]) -> Option<[f32; 2]> + Sync), +) -> Result<()> { + use texturecraft_bake::BakePaintMap; + use texturecraft_core::BakePaintTarget; + for ((index, target), painted) in &mut document.bake_paint { + if *index != texture_set { + continue; + } + let (width, height) = remapped_size((painted.width, painted.height), old, new) + .ok_or_else(|| bad("textureSet.uvTiles", "painted bake maps would exceed the supported size"))?; + let empty = match target { + BakePaintTarget::Cage => 1.0, + BakePaintTarget::Skew => 0.0, + }; + let mut values = vec![empty; width as usize * height as usize]; + values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + if let Some(uv) = map([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]) { + *value = painted.sample(texturecraft_geom::glam::Vec2::from_array(uv)); + } + } + }); + *painted = Arc::new(BakePaintMap { width, height, values }); + } + Ok(()) } #[cfg(test)] @@ -397,3 +434,18 @@ mod tests { assert!(execute(&mut s, "textureSet.uvTiles", &json!({})).is_err()); } } + +#[test] +fn bake_maps_follow_uv_layout_without_losing_rectangular_dimensions() { + use texturecraft_core::{BakePaintTarget, BakedMap}; + let mut session = Session::new_project("UV", texturecraft_geom::primitives::builtin("udim_plane").unwrap(), "builtin:udim_plane", None, 256).unwrap(); + crate::execute(&mut session, "bake.settings", &json!({"model": {"common": {"resolution": "R64", "resolution_height": "R128"}}})).unwrap(); + crate::execute(&mut session, "bake.run", &json!({"maps": ["normal"]})).unwrap(); + crate::execute(&mut session, "bake.skew.paint", &json!({"points": [[0.125, 0.25]], "radius": 0.06, "size": 64})).unwrap(); + crate::execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap(); + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::Normal)), (64, 128)); + let painted = &session.doc.bake_paint[&(0, BakePaintTarget::Skew)]; + assert!(painted.sample(texturecraft_geom::glam::Vec2::new(0.25, 0.25)) > 0.9); + assert_eq!(painted.sample(texturecraft_geom::glam::Vec2::new(0.75, 0.75)), 0.0); +} diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index 2375fca3..0e3642f8 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -485,17 +485,22 @@ fn leaning_session(lean: bool) -> Session { #[test] fn the_skew_map_is_saved_with_the_project() { let mut s = leaning_session(false); - execute(&mut s, "bake.skew.set", &json!({ "value": 0.25, "edgeDistance": 0.1, "edgeContrast": 3.0 })).unwrap(); + execute(&mut s, "bake.skew.set", &json!({ "value": 0.25 })).unwrap(); let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.skew, s.bake_meshes.skew); + assert_eq!(back.doc.bake_paint, s.doc.bake_paint); // No skew: none comes back. execute(&mut s, "bake.skew.clear", &Value::Null).unwrap(); - assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().bake_meshes.skew.is_none()); + assert!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.bake_paint.is_empty()); // A map with a non-finite value is skipped with a log line, and the project still opens. let mut pf = s.project_file(); - pf.skew = Some(texturecraft_formats::SkewData { width: 1, height: 1, values: vec![f32::NAN], edge_distance: 0.0, edge_contrast: 1.0 }); + pf.bake_paint.insert((0, texturecraft_core::BakePaintTarget::Skew), texturecraft_formats::BakePaintData { width: 1, height: 1, values: vec![f32::NAN] }); let opened = Session::from_project_file(pf).unwrap(); - assert!(opened.bake_meshes.skew.is_none() && opened.log.iter().any(|l| l.contains("skew")), "{:?}", opened.log); + assert!( + !opened.doc.bake_paint.contains_key(&(0, texturecraft_core::BakePaintTarget::Skew)) + && opened.log.iter().any(|line| line.contains("skipped bake paint map")), + "{:?}", + opened.log + ); } #[test] @@ -504,22 +509,22 @@ fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { // Painting with no map makes a black one at `size` and puts the dab in it. let r = execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 })).unwrap(); assert_eq!(r["skew"]["width"], 64); - let map = s.bake_meshes.skew.clone().unwrap(); + let map = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert!(map.values.iter().any(|v| *v > 0.99) && map.values.contains(&0.0)); - let rev = s.bake_meshes.skew_rev; + let rev = s.revision; // Erasing with value 0 brings it back down; the size stays. execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.5, 0.5]], "radius": 0.2, "value": 0.0, "hardness": 1.0 })).unwrap(); - let after = s.bake_meshes.skew.clone().unwrap(); + let after = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert_eq!(after.width, 64); - assert!(after.values.iter().all(|v| *v < 0.01) && s.bake_meshes.skew_rev > rev); + assert!(after.values.iter().all(|v| *v < 0.01) && s.revision > rev); // A constant map is widened, keeping its value where nothing is painted. execute(&mut s, "bake.skew.set", &json!({ "value": 0.5 })).unwrap(); execute(&mut s, "bake.skew.paint", &json!({ "points": [[0.1, 0.1]], "radius": 0.05, "size": 32 })).unwrap(); - let wide = s.bake_meshes.skew.clone().unwrap(); + let wide = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned().unwrap(); assert_eq!(wide.width, 32); assert!((wide.values[wide.values.len() / 2] - 0.5).abs() < 1e-5, "{}", wide.values[wide.values.len() / 2]); // Hostile input is an error and leaves the map alone. - let before = s.bake_meshes.skew.clone(); + let before = s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(); for bad in [ json!({}), json!({ "points": [] }), @@ -534,18 +539,75 @@ fn painting_skew_widens_a_map_and_bad_strokes_change_nothing() { ] { assert!(execute(&mut s, "bake.skew.paint", &bad).is_err(), "{bad}"); } - assert_eq!(s.bake_meshes.skew, before); + assert_eq!(s.doc.bake_paint.get(&(0, texturecraft_core::BakePaintTarget::Skew)).cloned(), before); // And the painted map is saved with the project. let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); - assert_eq!(back.bake_meshes.skew, s.bake_meshes.skew); + assert_eq!(back.doc.bake_paint, s.doc.bake_paint); } #[test] -fn a_stroke_paints_the_skew_map_in_place() { - let mut s = plane_session(); - let stroke = json!({ "points": [[0.5, 0.5]], "radius": 0.1, "size": 64 }); - execute(&mut s, "bake.skew.paint", &stroke).unwrap(); - let first = s.bake_meshes.skew.as_ref().map(std::sync::Arc::as_ptr); - execute(&mut s, "bake.skew.paint", &stroke).unwrap(); - assert_eq!(s.bake_meshes.skew.as_ref().map(std::sync::Arc::as_ptr), first, "a stroke step doesn't copy the whole map"); +fn bake_brush_strokes_are_undoable_and_continuations_merge() { + use texturecraft_core::BakePaintTarget; + let mut session = plane_session(); + let key = (0, BakePaintTarget::Skew); + execute(&mut session, "bake.skew.paint", &json!({"points": [[0.2, 0.2]], "radius": 0.1, "size": 64})).unwrap(); + execute(&mut session, "bake.skew.paint", &json!({"points": [[0.2, 0.2], [0.8, 0.8]], "radius": 0.1, "continue": true})).unwrap(); + let painted = session.doc.bake_paint.get(&key).cloned().unwrap(); + session.undo().unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); + session.redo().unwrap(); + assert_eq!(session.doc.bake_paint.get(&key), Some(&painted)); +} + +#[test] +fn cage_paint_is_scoped_saved_and_undoable() { + use texturecraft_core::BakePaintTarget; + let mut session = plane_session(); + let mut second_set = session.doc.project.texture_sets[0].clone(); + second_set.stack.clear(); + session.doc.project.texture_sets.push(second_set); + execute(&mut session, "bake.cage.paint", &json!({"ts": 1, "points": [[0.25, 0.25]], "radius": 0.1, "value": 0.2, "size": 32})).unwrap(); + let key = (1, BakePaintTarget::Cage); + let painted = session.doc.bake_paint[&key].clone(); + assert!(painted.values.iter().any(|value| *value < 0.5)); + assert!(painted.values.contains(&1.0)); + assert!(!session.doc.bake_paint.contains_key(&(0, BakePaintTarget::Cage))); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.bake_paint[&key], painted); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert_eq!(session.doc.bake_paint[&key], painted); + execute(&mut session, "bake.cage.reset", &json!({"ts": 1})).unwrap(); + assert!(!session.doc.bake_paint.contains_key(&key)); +} + +#[test] +fn changing_bake_aspect_replaces_incompatible_maps() { + let mut session = plane_session(); + execute(&mut session, "bake.run", &json!({"resolution": 64, "maps": ["normal", "id"]})).unwrap(); + execute(&mut session, "bake.settings", &json!({"model": {"common": {"resolution": "R64", "resolution_height": "R128"}}})).unwrap(); + execute(&mut session, "bake.run", &json!({"maps": ["id"]})).unwrap(); + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::Id)), (64, 128)); + assert_eq!(baked.maps.len(), 1); + assert_eq!(session.doc.project.texture_sets[0].baked.len(), 1); + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reloaded.doc.baked[&0], *baked); +} + +#[test] +fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { + let mut session = leaning_session(false); + let mut second = session.doc.project.texture_sets[0].clone(); + second.stack.clear(); + second.bake.cage.kind = texturecraft_core::CageType::CustomFile; + session.doc.project.texture_sets.push(second); + let original = session.doc.clone(); + let history = session.history_labels(); + let error = execute(&mut session, "bake.run", &json!({"ts": "all", "resolution": 64, "maps": ["id"]})).unwrap_err(); + assert!(error.to_string().contains("requires a cage"), "{error}"); + assert_eq!(session.doc.project, original.project); + assert_eq!(session.doc.baked, original.baked); + assert_eq!(session.history_labels(), history); } diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 56118b01..814ea08b 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -386,7 +386,7 @@ fn images_fill_mesh_map_slots() { let res = s.doc.project.texture_sets[0].bake.common.resolution.pixels(); assert_eq!(r, json!({"map": "ambientOcclusion", "resolution": res})); assert!(s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); - let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, 100).unwrap(); + let sample = |s: &Session, m: BakedMap, x: u32| s.baked(0).unwrap().sample(m, x, 50, (100, 100)).unwrap(); assert!((sample(&s, BakedMap::AmbientOcclusion, 10)[0] - 64.0 / 255.0).abs() < 1e-3, "raw file values, not linearized"); assert!((sample(&s, BakedMap::AmbientOcclusion, 90)[0] - 192.0 / 255.0).abs() < 1e-3); // A normal map is read in the project's normal format (DirectX: green flipped). @@ -397,7 +397,7 @@ fn images_fill_mesh_map_slots() { assert!((v[1] - (1.0 - 64.0 / 255.0)).abs() < 1e-3 && (v[2] - 1.0).abs() < 1e-3, "{v:?}"); // Clearing empties the slot (one undo step); bad params are errors. execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).unwrap(); - assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, 100).is_none()); + assert!(s.baked(0).unwrap().sample(BakedMap::AmbientOcclusion, 0, 0, (100, 100)).is_none()); assert!(!s.doc.project.texture_sets[0].baked.contains(&BakedMap::AmbientOcclusion)); assert!(execute(&mut s, "textureSet.meshMap.clear", &json!({"map": "ambientOcclusion"})).is_err(), "already empty"); execute(&mut s, "edit.undo", &Value::Null).unwrap(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index bba40729..f8fc1b97 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -596,7 +596,7 @@ impl Sampler<'_> { fn baked(&self, m: BakedMap, at: At) -> [f32; 3] { match at { - At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, self.res).unwrap_or(m.neutral()), + At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, (self.res, self.comp.height)).unwrap_or(m.neutral()), _ => m.neutral(), } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 31a6daea..d504072a 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -47,7 +47,7 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; -pub use project_file::{ProjectFile, SkewData, load_project_bytes, sanitize_resource_name, save_project_bytes}; +pub use project_file::{BakePaintData, ProjectFile, load_project_bytes, sanitize_resource_name, save_project_bytes}; #[cfg(not(target_arch = "wasm32"))] pub use export::write_files; diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d7dd46fc..2ea62770 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -598,8 +598,7 @@ fn material_name(id: &str, m: &Node) -> String { if name.is_empty() { format!("Material_{id}") } else { name.to_string() } } -/// Each material's diffuse color (× diffuse factor) or, when one is connected and embedded, -/// its diffuse texture (the texture replaces the color, as in most FBX viewers). +/// Preserve material colors independently of textures for ID baking fn base_colors( materials: &HashMap, textures: &HashMap, @@ -632,14 +631,15 @@ fn base_colors( let (video, tex) = (texture.and_then(|t| video_of.get(t)).and_then(|v| videos.get(v)), texture.and_then(|t| textures.get(t))); // Embedded content first, then the file the texture (or its video) names. let image = video.or(tex).and_then(|n| n.content()).or_else(|| [tex, video].into_iter().flatten().find_map(|n| texture_file(n, files))); - let factor = match (&image, m.property("DiffuseColor").as_deref()) { - (None, Some([r, g, b, ..])) => { + let diffuse_color = m.property("DiffuseColor"); + let factor = match diffuse_color.as_deref() { + Some([r, g, b, ..]) => { let f = m.number("DiffuseFactor").unwrap_or(1.0); Vec4::new((r * f) as f32, (g * f) as f32, (b * f) as f32, 1.0) } _ => Vec4::ONE, }; - (image.is_some() || (factor != Vec4::ONE && factor.is_finite())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) + (factor.is_finite() && (image.is_some() || diffuse_color.is_some())).then(|| RawBaseColor { material: material_name(id, m), factor, image }) }) .collect(); out.sort_by(|a, b| a.material.cmp(&b.material)); diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 08609687..5c5f4b5a 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -338,6 +338,23 @@ fn fbx_diffuse_colors_and_embedded_textures_reach_high_polys() { hammer("x.fbx", &binary_fbx(&nodes, 7500, false)); } +#[test] +fn fbx_retains_white_materials_and_colors_beside_textures() { + let mut nodes = textured_scene(&tiny_png()); + let objects = nodes.iter_mut().find(|node| node.name == "Objects").unwrap(); + let red = objects.children.iter_mut().find(|node| matches!(node.props.first(), Some(P::L(30)))).unwrap(); + red.children = vec![props70(vec![prop("DiffuseColor", &[1.0, 1.0, 1.0])])]; + let blue = objects.children.iter_mut().find(|node| matches!(node.props.first(), Some(P::L(31)))).unwrap(); + blue.children.push(props70(vec![prop("DiffuseColor", &[0.1, 0.2, 0.3])])); + + let imported = import_high_poly_bytes("colors.fbx", &binary_fbx(&nodes, 7500, true)).unwrap(); + let white = imported.base_color[0].as_ref().unwrap(); + let textured = imported.base_color[1].as_ref().unwrap(); + assert_eq!(white.factor, texturecraft_geom::glam::Vec4::ONE); + assert_eq!(textured.factor, texturecraft_geom::glam::Vec4::new(0.1, 0.2, 0.3, 1.0)); + assert_eq!(textured.texels.len(), 4); +} + /// [`textured_scene`] with Blue's texture kept as a file: `tex/wood.png` relative to the FBX, or /// only an absolute path elsewhere (found by its file name next to the FBX). fn texture_file_scene(relative: &'static str) -> Vec { diff --git a/crates/formats/src/project_file/bake_paint_data.rs b/crates/formats/src/project_file/bake_paint_data.rs new file mode 100644 index 00000000..e4797bed --- /dev/null +++ b/crates/formats/src/project_file/bake_paint_data.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Debug, PartialEq)] +pub struct BakePaintData { + pub width: u32, + pub height: u32, + pub values: Vec, +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 589b217a..496c34f5 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -6,7 +6,7 @@ //! | `mesh.` | the original imported mesh file (absent for built-in meshes, `Project.mesh = "builtin:"`) | //! | `highpoly/` | a high-definition mesh file for baking, in list order | //! | `cage/` | the baking cage mesh file | -//! | `skew.bin` | the skew correction map of the bake (magic `TCSK`, version, width, height, edge distance, edge contrast, method byte (0 mesh normals, 1 triangle normals); then `width × height` f32 LE) | +//! | `bake_paint/_.bin` | cage or skew paint, stored as a one-component baked map | //! | `pixels/layer__.bin` | painted pixels of a paint layer (or content paint effect) channel | //! | `pixels/mask_.bin` | painted pixels of a mask paint effect | //! | `baked/_.bin` | a baked mesh map of texture set `` | @@ -23,7 +23,7 @@ use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; -use texturecraft_core::{BakedMap, Channel, FORMAT_VERSION, LayerId, Project}; +use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project}; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; @@ -34,7 +34,6 @@ const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; /// Version of the `.bin` layout. const BIN_VERSION: u32 = 1; -const SKEW_MAGIC: &[u8; 4] = b"TCSK"; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; const MAX_RESOURCE: u64 = 512 << 20; @@ -44,16 +43,8 @@ const MAX_TOTAL: u64 = 8 << 30; /// Largest image (texels) of a texture set or baked map: UV-tiled sets hold several tiles. const MAX_TEXELS: u64 = 1 << 28; -/// The skew correction map of a bake, as stored (the baker's `SkewMap` without its type). -#[derive(Clone, Debug, PartialEq)] -pub struct SkewData { - pub width: u32, - pub height: u32, - /// `width * height` values, row 0 at the top. - pub values: Vec, - pub edge_distance: f32, - pub edge_contrast: f32, -} +mod bake_paint_data; +pub use bake_paint_data::BakePaintData; /// Everything a project file holds. #[derive(Clone, Debug)] @@ -69,8 +60,7 @@ pub struct ProjectFile { pub high_poly: Vec<(String, Vec)>, /// Baking cage mesh file: (file name, bytes). pub cage: Option<(String, Vec)>, - /// Skew correction of the bake rays. - pub skew: Option, + pub bake_paint: BTreeMap<(usize, BakePaintTarget), BakePaintData>, pub thumbnail: Option>, /// Imported resources (images used by fills, alphas, stencils), by name: original bytes. pub resources: BTreeMap>, @@ -179,18 +169,19 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?; zip.write_all(bytes)?; } - if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { - zip.start_file("skew.bin", deflate).map_err(zip_err)?; - let mut b = SKEW_MAGIC.to_vec(); - b.extend_from_slice(&BIN_VERSION.to_le_bytes()); - for v in [k.width, k.height] { - b.extend_from_slice(&v.to_le_bytes()); + for ((texture_set, target), map) in &pf.bake_paint { + if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) { + return Err(FormatError::Invalid("bake paint map dimensions do not match its values".into())); } - for v in [k.edge_distance, k.edge_contrast] { - b.extend_from_slice(&v.to_le_bytes()); + let target_name = match target { + BakePaintTarget::Cage => "cage", + BakePaintTarget::Skew => "skew", + }; + zip.start_file(format!("bake_paint/{texture_set}_{target_name}.bin"), deflate).map_err(zip_err)?; + zip.write_all(&header(map.width, map.height, 1, 0))?; + for value in &map.values { + zip.write_all(&value.to_le_bytes())?; } - b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); - zip.write_all(&b)?; } let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); @@ -339,36 +330,6 @@ fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) } -/// Decode the skew header and pixel values -fn read_skew(reader: &mut impl Read, budget: &mut Budget, entry: &str) -> Result { - let mut header = [0u8; 24]; - read_exact(reader, &mut header, entry)?; - if header.get(..4) != Some(SKEW_MAGIC.as_slice()) { - return Err(malformed(KIND, format!("{entry}: bad magic"))); - } - - let version = u32_at(&header, 1); - if version > BIN_VERSION { - return Err(FormatError::NewerVersion { found: version, supported: BIN_VERSION }); - } - - let (width, height) = (u32_at(&header, 2), u32_at(&header, 3)); - let (edge_distance, edge_contrast) = (f32::from_bits(u32_at(&header, 4)), f32::from_bits(u32_at(&header, 5))); - if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS { - return Err(malformed(KIND, format!("{entry}: bad size {width}×{height}"))); - } - - let pixel_count = (width as usize) * (height as usize); - budget.take(pixel_count as u64 * 4)?; - let mut bytes = vec![0u8; pixel_count * 4]; - read_exact(reader, &mut bytes, entry)?; - expect_end(reader, entry)?; - - // The caller validates pixel values after decoding - let values = bytes.chunks_exact(4).map(|bytes| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])).collect(); - Ok(SkewData { width, height, values, edge_distance, edge_contrast }) -} - /// Texture set holding a paint layer, a content effect or a mask effect id. fn texture_set_of(project: &Project, id: LayerId) -> Option { let owner = if project.layers.contains_key(&id) { id } else { project.effect(id)?.0 }; @@ -403,7 +364,7 @@ fn load(reader: R) -> Result { mesh: None, high_poly: Vec::new(), cage: None, - skew: None, + bake_paint: BTreeMap::new(), thumbnail: None, resources: BTreeMap::new(), project, @@ -429,8 +390,19 @@ fn load(reader: R) -> Result { "cage" => pf.cage = Some(entry), _ => pf.high_poly.push(entry), } - } else if name == "skew.bin" { - pf.skew = Some(read_skew(&mut f, &mut budget, &name)?); + } else if let Some(rest) = name.strip_prefix("bake_paint/").and_then(|name| name.strip_suffix(".bin")) { + let (texture_set, target) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry {name}")))?; + let texture_set: usize = texture_set.parse().map_err(|_| malformed(KIND, format!("bad entry {name}")))?; + if texture_set >= pf.project.texture_sets.len() { + return Err(malformed(KIND, format!("unknown texture set in {name}"))); + } + let target = match target { + "cage" => BakePaintTarget::Cage, + "skew" => BakePaintTarget::Skew, + _ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))), + }; + let (width, height, values) = read_baked(&mut f, 1, &mut budget, &name)?; + pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; pf.mesh = Some((ext.to_string(), bytes)); diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 34d9de7b..e33eed29 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -34,7 +34,8 @@ fn sample() -> Sample { mesh: Some(("glb".into(), vec![1, 2, 3, 4, 5])), high_poly: vec![("b_high.obj".into(), vec![7; 9]), ("a_high.ply".into(), vec![6])], cage: Some(("cage.obj".into(), vec![5, 5])), - skew: Some(SkewData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125], edge_distance: 0.05, edge_contrast: 2.0 }), + bake_paint: [((0, texturecraft_core::BakePaintTarget::Skew), BakePaintData { width: 3, height: 2, values: vec![0.0, 0.25, 0.5, 0.75, 1.0, 0.125] })] + .into(), thumbnail: Some(vec![137, 80, 78, 71]), resources: [("bricks.png".to_string(), vec![9, 8, 7])].into(), }; @@ -54,7 +55,7 @@ fn assert_same(a: &ProjectFile, b: &ProjectFile) { assert_eq!(a.baked, b.baked); assert_eq!(a.mesh, b.mesh); assert_eq!((&a.high_poly, &a.cage), (&b.high_poly, &b.cage), "bake meshes keep their order"); - assert_eq!(a.skew, b.skew); + assert_eq!(a.bake_paint, b.bake_paint); assert_eq!(a.thumbnail, b.thumbnail); assert_eq!(a.resources, b.resources); } diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 028d91de..f478f77a 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -11,6 +11,7 @@ use bytemuck::{Pod, Zeroable}; use rayon::prelude::*; use texturecraft_bake::BakeError; use texturecraft_bake::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh, Tracer}; +use texturecraft_core::{AmbientOcclusionAttenuation, BackfaceMode}; use texturecraft_geom::Hit; use texturecraft_geom::glam::Vec3; @@ -42,6 +43,10 @@ struct Params { lanes: u32, /// First result row of the pass. out: u32, + min_distance: f32, + attenuation: u32, + ground_height: f32, + backface_mode: u32, } struct Gpu { @@ -152,7 +157,9 @@ impl Tracer for GpuBaker { } let base = ((nodes.len() / 2) as u32, (tris.len() / 4) as u32); roots.push(base.0); - let (n, t) = bvh_rows(m.bvh, base, |o| ([m.keys.get(o).copied().unwrap_or(ANY), 0, 0], [0, 0, 0, o as u32])); + let (n, t) = bvh_rows(m.bvh, base, |o| { + ([m.keys.get(o).copied().unwrap_or(ANY), u32::from(m.backface_culling.get(o).copied().unwrap_or(false)), 0], [0, 0, 0, o as u32]) + }); nodes.extend(n); tris.extend(t); } @@ -300,8 +307,12 @@ fn row(v: Vec3, w: u32) -> [u32; 4] { } impl RayScene for GpuScene<'_> { - fn closest(&mut self, mesh: usize, rays: &[Ray]) -> Result>, BakeError> { - let pass = Pass { params: Params { root: self.root(mesh)?, ..Params::default() }, per_dispatch: RAYS_PER_DISPATCH, per_group: WORKGROUP as usize }; + fn closest(&mut self, mesh: usize, rays: &[Ray], ignore_backface: bool) -> Result>, BakeError> { + let pass = Pass { + params: Params { root: self.root(mesh)?, flags: u32::from(ignore_backface) * IGNORE_BACKFACE, ..Params::default() }, + per_dispatch: RAYS_PER_DISPATCH, + per_group: WORKGROUP as usize, + }; let gpu = self.gpu; self.run(&gpu.transfer, bytemuck::cast_slice(rays), rays.len(), &[pass], |out| { out.par_iter().map(|&[t, u, v, tri]| (tri != NONE).then(|| Hit { t: f32::from_bits(t), tri, u: f32::from_bits(u), v: f32::from_bits(v) })).collect() @@ -323,14 +334,24 @@ impl RayScene for GpuScene<'_> { .map(|h| { // A sample's rays spread over `lanes` threads of a workgroup (a power of two). let lanes = h.rays.clamp(1, WORKGROUP).next_power_of_two(); - let flags = [(h.uniform, UNIFORM), (h.ignore_backface, IGNORE_BACKFACE), (h.same_key, SAME_KEY)] - .iter() - .filter(|(on, _)| *on) - .fold(0, |f, (_, b)| f | b); + let flags = + [(h.uniform, UNIFORM), (h.ground_height.is_some(), 8), (h.same_key, SAME_KEY)].iter().filter(|(on, _)| *on).fold(0, |f, (_, b)| f | b); let params = Params { kind: u32::from(h.kind == RayKind::Thickness), rays: h.rays, dmax: h.dmax, + min_distance: h.min_distance, + attenuation: match h.attenuation { + AmbientOcclusionAttenuation::None => 0, + AmbientOcclusionAttenuation::Linear => 1, + AmbientOcclusionAttenuation::Smooth => 2, + }, + ground_height: h.ground_height.unwrap_or(0.0), + backface_mode: match h.ignore_backface { + BackfaceMode::Never => 0, + BackfaceMode::Always => 1, + BackfaceMode::ByMeshName => 2, + }, eps: h.eps, cos_max: h.cos_max, sin_max: h.sin_max, @@ -376,8 +397,9 @@ mod tests { fn run(low: &Mesh, high: Option<&Mesh>, s: &BakeSettings, tracer: Option<&GpuBaker>) -> BakeOutput { let (lb, hb) = (Bvh::new(low), high.map(Bvh::new)); - let high = high.zip(hb.as_ref()).map(|(mesh, bvh)| HighPoly { mesh, bvh, base_color: &[] }); - let req = BakeRequest { mesh: low, bvh: &lb, material: 0, settings: s, high, cage: None, skew: None, tiles: (1, 1) }; + let high = high.zip(hb.as_ref()).map(|(mesh, bvh)| HighPoly { file_ids: &[], mesh, bvh, base_color: &[] }); + let req = + BakeRequest { low_base_color: &[], mesh: low, bvh: &lb, material: 0, settings: s, high, cage: None, skew: None, cage_paint: None, tiles: (1, 1) }; match tracer { Some(t) => bake_on(&req, &Progress::new(), t).unwrap(), None => bake(&req, &Progress::new()).unwrap(), @@ -399,6 +421,34 @@ mod tests { } } + #[test] + fn gpu_respects_secondary_ray_filters_and_ground_plane() { + let Some(gpu) = gpu() else { return }; + + let mut mesh = primitives::material_ball(); + for part in &mut mesh.submeshes { + part.name.push_str("_ignorebf"); + } + let mut settings = BakeSettings::default(); + settings.common.resolution = BakeResolution::R64; + settings.common.apply_diffusion = false; + settings.maps.select([BakedMap::AmbientOcclusion, BakedMap::BentNormal, BakedMap::Thickness]); + settings.high_poly.ignore_backface_suffix = "_ignorebf".into(); + settings.maps.ao.parameters.rays.min_distance = 0.02; + settings.maps.ao.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.ao.parameters.self_occlusion = SelfOcclusion::SameMeshName; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.maps.ao.parameters.ground_plane.offset = 0.1; + settings.maps.bent_normal.parameters.rays.min_distance = 0.02; + settings.maps.bent_normal.parameters.ignore_backface = BackfaceMode::ByMeshName; + settings.maps.thickness.parameters.rays.min_distance = 0.02; + settings.maps.thickness.parameters.self_occlusion = SelfOcclusion::SameMeshName; + for attenuation in [AmbientOcclusionAttenuation::None, AmbientOcclusionAttenuation::Smooth] { + settings.maps.ao.parameters.attenuation = attenuation; + assert_agree(&run(&mesh, None, &settings, None), &run(&mesh, None, &settings, Some(&gpu))); + } + } + #[test] fn gpu_bake_matches_the_cpu() { let Some(gpu) = gpu() else { return }; @@ -447,7 +497,12 @@ mod tests { BakedMap::Curvature, ]); base.cage = CageSettings { max_frontal: 0.02, max_rear: 0.02, ..base.cage }; - base.high_poly = HighPolySettings { low_suffix: String::new(), use_low_as_high: false, ..base.high_poly }; + base.high_poly = HighPolySettings { + match_mode: texturecraft_core::MeshMatchMode::ByMeshName, + low_suffix: String::new(), + use_low_as_high: false, + ..base.high_poly + }; base.maps.ao.parameters = AmbientOcclusionSettings { rays: RaySettings { rays: 16, ..RaySettings::default() }, self_occlusion: SelfOcclusion::SameMeshName, diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index e9ed9424..bf811478 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -11,12 +11,9 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec P: Params; @@ -36,12 +40,13 @@ struct Params { var want_key: u32; var skip_back: bool; +var backface_by_name: bool; fn accept(i: u32, d: vec3) -> bool { if (want_key != NONE && tris[i * 4u].w != want_key) { return false; } - if (skip_back) { + if (skip_back || (backface_by_name && tris[i * 4u + 1u].w != 0u)) { let p0 = tri_p(i, 0u); return dot(cross(tri_p(i, 1u) - p0, tri_p(i, 2u) - p0), d) <= 0.0; } @@ -57,7 +62,8 @@ fn transfer_main(@builtin(global_invocation_id) gid: vec3) { let a = items[k * 2u]; let b = items[k * 2u + 1u]; want_key = b.w; - skip_back = false; + skip_back = (P.flags & IGNORE_BACKFACE) != 0u; + backface_by_name = false; let h = traverse_from(P.root, bitcast>(a.xyz), bitcast>(b.xyz), bitcast(a.w), false); var out = vec4(0u, 0u, 0u, NONE); if (h.idx != NONE) { @@ -88,8 +94,9 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati let o = bitcast>(r0.xyz) + geo * P.eps; let t = onb_t(axis); let b = onb_b(axis); - want_key = select(NONE, r2.w, occlusion && (P.flags & SAME_KEY) != 0u); - skip_back = occlusion && (P.flags & IGNORE_BACKFACE) != 0u; + want_key = select(NONE, r2.w, (P.flags & SAME_KEY) != 0u); + skip_back = P.backface_mode == 1u; + backface_by_name = P.backface_mode == 2u; var sum = 0.0; var bent = vec3(0.0); var n = 0u; @@ -110,15 +117,26 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati if (dot(d, geo) <= 0.0) { continue; } - let h = traverse_from(root, o, d, P.dmax, false); - let hit = h.idx != NONE; + let h = traverse_from(root, o + d * P.min_distance, d, max(0.0, P.dmax - P.min_distance), false); + var hit = h.idx != NONE; + var distance = select(P.dmax, h.t + P.min_distance, hit); + if ((P.flags & 8u) != 0u && d.y < -1e-8) { + let ground_distance = (P.ground_height - o.y) / d.y; + if (ground_distance >= P.min_distance && ground_distance <= P.dmax) { + distance = min(distance, ground_distance); + hit = true; + } + } if (occlusion) { - let f = h.t / P.dmax; - let v = select(0.0, 1.0 - f * f, hit); + let fraction = clamp((distance - P.min_distance) / max(P.dmax - P.min_distance, 1.1920929e-7), 0.0, 1.0); + var attenuation = 1.0; + if (P.attenuation == 1u) { attenuation = 1.0 - fraction; } + if (P.attenuation == 2u) { attenuation = 1.0 - fraction * fraction * (3.0 - 2.0 * fraction); } + let v = select(0.0, attenuation, hit); sum += v; bent += d * (1.0 - v); } else { - sum += select(P.dmax, h.t, hit); + sum += distance; } n += 1u; } @@ -142,8 +160,8 @@ fn hemisphere_main(@builtin(workgroup_id) wg: vec3, @builtin(local_invocati let l2 = dot(bent, bent); let bn = select(nrm, bent * inverseSqrt(l2), l2 > 1e-30); out = vec4(select(1.0, clamp(1.0 - sum / f32(n), 0.0, 1.0), n > 0u), bn); - } else if (n > 0u) { - out.x = clamp(sum / f32(n) / P.dmax, 0.0, 1.0); + } else { + out.x = select(P.dmax, sum / f32(n), n > 0u); } results[P.out + k] = bitcast>(out); } diff --git a/crates/texel/src/dilate.rs b/crates/texel/src/dilate.rs index d1f8aeb2..c1c24fce 100644 --- a/crates/texel/src/dilate.rs +++ b/crates/texel/src/dilate.rs @@ -23,9 +23,13 @@ impl DilationMap { /// [`DilationMap::new`] that never pads across the borders of `block × block` squares (the /// UV tiles of an atlas); 0 means one block. pub fn in_blocks(covered: &[bool], width: u32, height: u32, max_dist: Option, block: u32) -> DilationMap { + Self::in_rectangular_blocks(covered, width, height, max_dist, (block, block)) + } + + pub fn in_rectangular_blocks(covered: &[bool], width: u32, height: u32, max_dist: Option, block: (u32, u32)) -> DilationMap { let n = (width as usize).saturating_mul(height as usize); let mut src = vec![NONE; n]; - let bsz = if block == 0 { u32::MAX } else { block }; + let bsz = (if block.0 == 0 { u32::MAX } else { block.0 }, if block.1 == 0 { u32::MAX } else { block.1 }); let is_covered = |i: usize| covered.get(i).copied().unwrap_or(false); // Breadth first, one distance at a time; only island borders seed it (interior texels // have nothing to spread to, so the result is the same at a fraction of the work). @@ -89,12 +93,12 @@ impl DilationMap { /// The 8-neighbours of texel `i` of a `w × h` image inside the image and inside its `bsz` /// square block. -fn neighbours(i: usize, w: u32, h: u32, bsz: u32) -> impl Iterator { +fn neighbours(i: usize, w: u32, h: u32, bsz: (u32, u32)) -> impl Iterator { let (wu, x, y) = (w as usize, (i % w.max(1) as usize) as u32, (i / w.max(1) as usize) as u32); - let left = x > 0 && x % bsz != 0; - let right = x + 1 < w && (x + 1) % bsz != 0; - let up = y > 0 && y % bsz != 0; - let down = y + 1 < h && (y + 1) % bsz != 0; + let left = x > 0 && x % bsz.0 != 0; + let right = x + 1 < w && (x + 1) % bsz.0 != 0; + let up = y > 0 && y % bsz.1 != 0; + let down = y + 1 < h && (y + 1) % bsz.1 != 0; [ (left, i.wrapping_sub(1)), (right, i + 1), @@ -200,3 +204,19 @@ mod tests { assert_eq!(data, [3u16; 16]); } } + +#[cfg(test)] +mod rectangular_test { + use super::*; + #[test] + fn rectangular_tiles_keep_padding_within_both_axes() { + let mut covered = vec![false; 8 * 6]; + covered[2 * 8 + 3] = true; + let padding = DilationMap::in_rectangular_blocks(&covered, 8, 6, None, (4, 3)); + for y in 0..6 { + for x in 0..8 { + assert_eq!(padding.source(x, y).is_some(), x < 4 && y < 3); + } + } + } +} diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs index 6d4f0e1b..c0397a49 100644 --- a/crates/ui-egui/src/bake_mode.rs +++ b/crates/ui-egui/src/bake_mode.rs @@ -1,6 +1,8 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands +mod bake_paint_brush; mod common_settings; +pub use bake_paint_brush::BakePaintBrush; mod controls; mod map_settings; diff --git a/crates/ui-egui/src/bake_mode/bake_paint_brush.rs b/crates/ui-egui/src/bake_mode/bake_paint_brush.rs new file mode 100644 index 00000000..ee2c977a --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_paint_brush.rs @@ -0,0 +1,17 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_engine::core::BakePaintTarget; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct BakePaintBrush { + pub on: bool, + pub target: BakePaintTarget, + pub radius: f32, + pub value: f32, + pub hardness: f32, +} + +impl Default for BakePaintBrush { + fn default() -> Self { + Self { on: false, target: BakePaintTarget::Skew, radius: 0.03, value: 1.0, hardness: 0.5 } + } +} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index ac666c04..d96fdc85 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -5,7 +5,9 @@ use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; use serde_json::json; -use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, CageType, CommonBakeSettings}; +use texturecraft_engine::core::{ + BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, +}; pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { @@ -36,6 +38,12 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe high_poly_files(app, ui); if !app.session.bake_meshes.high.is_empty() { ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + choice( + ui, + tr("Match"), + &mut settings.high_poly.match_mode, + &[(MeshMatchMode::Always, tr("Always")), (MeshMatchMode::ByMeshName, tr("By Mesh Name"))], + ); text_input(ui, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); text_input(ui, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); text_input(ui, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); @@ -56,7 +64,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ); match settings.cage.kind { CageType::DistanceBased => { - ui.add_enabled(false, egui::Button::new(tr("Paint Cage"))); + paint_brush(app, ui, BakePaintTarget::Cage); number(ui, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=0.05, 4); number(ui, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=0.05, 4); ui.checkbox(&mut settings.cage.relative_to_bounding_box, tr("Relative to Bounding Box")); @@ -72,7 +80,16 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.add_space(8.0); ui.push_id("skew", |ui| { if section(ui, tr("Skew Correction"), None, |ui| { - skew_brush(app, ui); + choice( + ui, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[ + (SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), + (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based")), + ], + ); + paint_brush(app, ui, BakePaintTarget::Skew); ui.checkbox(&mut settings.skew.edge_protection, tr("Edge Protection")); number(ui, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); @@ -145,21 +162,33 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -fn skew_brush(app: &mut TextureCraftApp, ui: &mut Ui) { - let mut brush = app.ui.skew_brush; - if ui.add(egui::Button::new(tr("Paint Skew Correction")).selected(brush.on)).clicked() { - brush.on = !brush.on; +fn paint_brush(app: &mut TextureCraftApp, ui: &mut Ui, target: BakePaintTarget) { + let (label, clear_label, clear_command) = match target { + BakePaintTarget::Cage => ("Paint Cage", "Reset Painted Cage", "bake.cage.reset"), + BakePaintTarget::Skew => ("Paint Skew Correction", "Remove Skew Correction", "bake.skew.clear"), + }; + let mut brush = app.ui.bake_paint_brush; + let active = brush.on && brush.target == target; + if ui.add(egui::Button::new(tr(label)).selected(active)).clicked() { + brush.on = !active; + if brush.target != target { + brush.value = match target { + BakePaintTarget::Cage => 0.5, + BakePaintTarget::Skew => 1.0, + }; + } + brush.target = target; } - if brush.on { + if brush.on && brush.target == target { number(ui, tr("Radius"), &mut brush.radius, 0.002..=0.2, 3); number(ui, tr("Value"), &mut brush.value, 0.0..=1.0, 2); number(ui, tr("Hardness"), &mut brush.hardness, 0.0..=1.0, 2); + if app.ui.layout == crate::state::ViewLayout::Only3D { + app.ui.layout = crate::state::ViewLayout::Split; + } } - if brush.on && !app.ui.skew_brush.on && app.ui.layout == crate::state::ViewLayout::Only3D { - app.ui.layout = crate::state::ViewLayout::Split; - } - app.ui.skew_brush = brush; - if app.session.bake_meshes.skew.is_some() && ui.button(tr("Remove Skew Correction")).clicked() { - app.run("bake.skew.clear", json!({})); + app.ui.bake_paint_brush = brush; + if app.session.doc.bake_paint.contains_key(&(app.session.ts(), target)) && ui.button(tr(clear_label)).clicked() { + app.run(clear_command, json!({})); } } diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 2a07ce3d..a8cb2d48 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -121,7 +121,7 @@ fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { } occlusion(ui, tr("Self Intersection"), &mut mesh.self_intersection); ui.checkbox(&mut mesh.auto_tonemapping, tr("Auto Tonemapping")); - if mesh.auto_tonemapping { + if !mesh.auto_tonemapping { number(ui, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); number(ui, tr("Value Bounds Max"), &mut mesh.value_max, -10.0..=10.0, 2); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 2ca825e0..6ef517e9 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "سحب بـ Alt + زر الفأرة الأيسر"), ("Always", "دائماً"), ("Ambient Occlusion", "الانسداد المحيطي (AO)"), + ("Ambient occlusion", "الانسداد المحيطي (AO)"), ("Ambient occlusion intensity", "شدة الانسداد المحيطي"), ("Amount", "المقدار"), ("Anchor point", "نقطة ارتكاز"), @@ -1009,6 +1010,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "نوع التطبيع"), ("Only Same Mesh Name", "نفس اسم المجسم فقط"), ("Output Size", "حجم المخرج"), + ("Match", "المطابقة"), + ("Skew Correction Method", "طريقة تصحيح الانحراف"), + ("Mesh Normals Based", "استنادًا إلى متجهات الشبكة العمودية"), + ("Face Normals Based", "استنادًا إلى متجهات الأوجه العمودية"), + ("Reset Painted Cage", "إعادة تعيين القفص المرسوم"), ("Paint Cage", "رسم القفص"), ("Paint Skew Correction", "رسم تصحيح الميل"), ("Per Material", "لكل مادة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 7e626046..caaabb14 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + LMT ziehen"), ("Always", "Immer"), ("Ambient Occlusion", "Ambient Occlusion"), + ("Ambient occlusion", "Ambient occlusion"), ("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"), ("Amount", "Stärke"), ("Anchor point", "Ankerpunkt"), @@ -1058,6 +1059,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "Normalisierungstyp"), ("Only Same Mesh Name", "Nur gleicher Mesh-Name"), ("Output Size", "Ausgabegröße"), + ("Match", "Zuordnung"), + ("Skew Correction Method", "Methode der Verzerrungskorrektur"), + ("Mesh Normals Based", "Basierend auf Mesh-Normalen"), + ("Face Normals Based", "Basierend auf Flächennormalen"), + ("Reset Painted Cage", "Gemalten Käfig Zurücksetzen"), ("Paint Cage", "Käfig malen"), ("Paint Skew Correction", "Verzerrungskorrektur malen"), ("Per Material", "Pro Material"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index d681e213..6c8ccccb 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + arrastrar con botón izq."), ("Always", "Siempre"), ("Ambient Occlusion", "Oclusión ambiental"), + ("Ambient occlusion", "Oclusión ambiental"), ("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"), ("Amount", "Cantidad"), ("Anchor point", "Punto de anclaje"), @@ -1043,6 +1044,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "Tipo de normalización"), ("Only Same Mesh Name", "Solo el mismo nombre de malla"), ("Output Size", "Tamaño de salida"), + ("Match", "Coincidencia"), + ("Skew Correction Method", "Método de Corrección de Sesgo"), + ("Mesh Normals Based", "Basado en Normales de Malla"), + ("Face Normals Based", "Basado en Normales de Cara"), + ("Reset Painted Cage", "Restablecer Jaula Pintada"), ("Paint Cage", "Pintar jaula"), ("Paint Skew Correction", "Pintar corrección de inclinación"), ("Per Material", "Por material"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 24ef92ea..f10bba8d 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + glisser (clic gauche)"), ("Always", "Toujours"), ("Ambient Occlusion", "Occlusion ambiante"), + ("Ambient occlusion", "Occlusion ambiante"), ("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"), ("Amount", "Quantité"), ("Anchor point", "Point d'ancrage"), @@ -1067,6 +1068,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "Type de normalisation"), ("Only Same Mesh Name", "Seulement le même nom de maillage"), ("Output Size", "Taille de sortie"), + ("Match", "Correspondance"), + ("Skew Correction Method", "Méthode de Correction de Déformation"), + ("Mesh Normals Based", "Basée sur les Normales du Maillage"), + ("Face Normals Based", "Basée sur les Normales des Faces"), + ("Reset Painted Cage", "Réinitialiser la Cage Peinte"), ("Paint Cage", "Peindre la cage"), ("Paint Skew Correction", "Peindre la correction d'inclinaison"), ("Per Material", "Par matériau"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index f3bcbaf3..1c19d597 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + trascina (tasto sinistro)"), ("Always", "Sempre"), ("Ambient Occlusion", "Occlusione ambientale"), + ("Ambient occlusion", "Occlusione ambientale"), ("Ambient occlusion intensity", "Intensità occlusione ambientale"), ("Amount", "Quantità"), ("Anchor point", "Punto di ancoraggio"), @@ -1052,6 +1053,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "Tipo di normalizzazione"), ("Only Same Mesh Name", "Solo stesso nome mesh"), ("Output Size", "Dimensione output"), + ("Match", "Corrispondenza"), + ("Skew Correction Method", "Metodo di Correzione della Distorsione"), + ("Mesh Normals Based", "Basato sulle Normali della Mesh"), + ("Face Normals Based", "Basato sulle Normali delle Facce"), + ("Reset Painted Cage", "Ripristina Gabbia Dipinta"), ("Paint Cage", "Dipingi gabbia"), ("Paint Skew Correction", "Dipingi correzione dell'inclinazione"), ("Per Material", "Per materiale"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index a376e6e3..068603b5 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + 左ドラッグ"), ("Always", "常に"), ("Ambient Occlusion", "アンビエントオクルージョン"), + ("Ambient occlusion", "アンビエントオクルージョン"), ("Ambient occlusion intensity", "アンビエントオクルージョンの強度"), ("Amount", "量"), ("Anchor point", "アンカーポイント"), @@ -1037,6 +1038,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "正規化の種類"), ("Only Same Mesh Name", "同じメッシュ名のみ"), ("Output Size", "出力サイズ"), + ("Match", "マッチング"), + ("Skew Correction Method", "スキュー補正方法"), + ("Mesh Normals Based", "メッシュ法線ベース"), + ("Face Normals Based", "面法線ベース"), + ("Reset Painted Cage", "ペイントしたケージをリセット"), ("Paint Cage", "ケージをペイント"), ("Paint Skew Correction", "スキュー補正をペイント"), ("Per Material", "マテリアルごと"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 39f2dfad..137d6177 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + 왼쪽 드래그"), ("Always", "항상"), ("Ambient Occlusion", "앰비언트 오클루전"), + ("Ambient occlusion", "앰비언트 오클루전"), ("Ambient occlusion intensity", "앰비언트 오클루전 강도"), ("Amount", "양"), ("Anchor point", "앵커 포인트"), @@ -1022,6 +1023,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "정규화 유형"), ("Only Same Mesh Name", "같은 메시 이름만"), ("Output Size", "출력 크기"), + ("Match", "일치"), + ("Skew Correction Method", "왜곡 보정 방법"), + ("Mesh Normals Based", "메시 법선 기반"), + ("Face Normals Based", "면 법선 기반"), + ("Reset Painted Cage", "페인트한 케이지 초기화"), ("Paint Cage", "케이지 페인트"), ("Paint Skew Correction", "기울기 보정 페인트"), ("Per Material", "재질별"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 82a838a9..99627b25 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + arrastar com botão esquerdo"), ("Always", "Sempre"), ("Ambient Occlusion", "Oclusão de ambiente"), + ("Ambient occlusion", "Oclusão de ambiente"), ("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"), ("Amount", "Quantidade"), ("Anchor point", "Ponto de ancoragem"), @@ -1040,6 +1041,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "Tipo de normalização"), ("Only Same Mesh Name", "Somente o mesmo nome de malha"), ("Output Size", "Tamanho de saída"), + ("Match", "Correspondência"), + ("Skew Correction Method", "Método de Correção de Distorção"), + ("Mesh Normals Based", "Baseado nas Normais da Malha"), + ("Face Normals Based", "Baseado nas Normais das Faces"), + ("Reset Painted Cage", "Redefinir Gaiola Pintada"), ("Paint Cage", "Pintar gaiola"), ("Paint Skew Correction", "Pintar correção de inclinação"), ("Per Material", "Por material"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 20c9e258..18623ce3 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -65,6 +65,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Alt + LMB drag", "Alt + 左键拖动"), ("Always", "始终"), ("Ambient Occlusion", "环境光遮蔽"), + ("Ambient occlusion", "环境光遮蔽"), ("Ambient occlusion intensity", "环境光遮蔽强度"), ("Amount", "数量"), ("Anchor point", "锚点"), @@ -968,6 +969,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Normalization Type", "归一化类型"), ("Only Same Mesh Name", "仅相同网格名称"), ("Output Size", "输出尺寸"), + ("Match", "匹配"), + ("Skew Correction Method", "偏斜校正方法"), + ("Mesh Normals Based", "基于网格法线"), + ("Face Normals Based", "基于面法线"), + ("Reset Painted Cage", "重置绘制的笼形"), ("Paint Cage", "绘制笼形"), ("Paint Skew Correction", "绘制倾斜校正"), ("Per Material", "按材质"), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0947b2fd..89c12bb0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -279,23 +279,7 @@ pub struct UiState { pub keymap: Keymap, /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] - pub skew_brush: SkewBrush, -} - -/// Settings of the skew correction brush (radius in UV units). -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -pub struct SkewBrush { - pub on: bool, - pub radius: f32, - /// 1 turns the rays onto the base normal, 0 erases. - pub value: f32, - pub hardness: f32, -} - -impl Default for SkewBrush { - fn default() -> Self { - SkewBrush { on: false, radius: 0.03, value: 1.0, hardness: 0.5 } - } + pub bake_paint_brush: crate::bake_mode::BakePaintBrush, } impl UiState { @@ -347,7 +331,7 @@ impl Default for UiState { export: ExportUi::default(), recent: Vec::new(), keymap: Keymap::new(), - skew_brush: SkewBrush::default(), + bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 38767838..db50b2db 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -36,17 +36,13 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; - let skew_painting = mode == crate::state::Mode::Baking - && app.ui.skew_brush.on + let bake_painting = mode == crate::state::Mode::Baking + && app.ui.bake_paint_brush.on && !app.session.bake_meshes.high.is_empty() - && app - .session - .doc - .project - .texture_sets - .get(app.session.ts()) - .is_some_and(|texture_set| texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased); - app.ui.skew_brush.on = skew_painting; + && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { + !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased + }); + app.ui.bake_paint_brush.on = bake_painting; if mode == crate::state::Mode::Painting && !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } @@ -62,7 +58,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let full = ui.available_rect_before_wrap(); path_keys(app, ui); // Skew painting needs the 2D view alongside the 3D Bake preview - let layout = if mode == crate::state::Mode::Painting || skew_painting { app.ui.layout } else { ViewLayout::Only3D }; + let layout = if mode == crate::state::Mode::Painting || bake_painting { app.ui.layout } else { ViewLayout::Only3D }; match layout { ViewLayout::Only3D => view_3d(app, ui, full, &mut sync), ViewLayout::Only2D => view_2d(app, ui, full, &mut sync), @@ -1008,9 +1004,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let uv = to_uv(p); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } - let skew_on = app.ui.mode == crate::state::Mode::Baking && app.ui.skew_brush.on && !alt; - if skew_on { - skew_input(app, ui, &resp, &to_uv); + let bake_paint_on = app.ui.mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on && !alt; + if bake_paint_on { + bake_paint_input(app, ui, &resp, &to_uv); } let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; if painting && path_tool { @@ -1076,9 +1072,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &resp, true, show); } if app.ui.mode == crate::state::Mode::Baking { - skew_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); - if skew_on && let Some(hover) = resp.hover_pos() { - let r = (to(app.ui.skew_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0); + bake_paint_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); + if bake_paint_on && let Some(hover) = resp.hover_pos() { + let r = (to(app.ui.bake_paint_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0); painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); } } @@ -1091,9 +1087,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). -fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { - let last = ui.scope_id().with("skew_last"); - let brush = app.ui.skew_brush; +fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); + let brush = app.ui.bake_paint_brush; let started = resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary); if !(started || resp.dragged_by(PointerButton::Primary)) { return; @@ -1102,16 +1098,20 @@ fn skew_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: let uv = to_uv(p); let previous: Option<[f32; 2]> = if started { None } else { ui.data(|d| d.get_temp(last)) }; let points: Vec<[f32; 2]> = previous.into_iter().chain([[uv.x, uv.y]]).collect(); - if app.run("bake.skew.paint", json!({"points": points, "radius": brush.radius, "value": brush.value, "hardness": brush.hardness})).is_some() { + let command = match brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => "bake.skew.paint", + texturecraft_engine::core::BakePaintTarget::Cage => "bake.cage.paint", + }; + if app.run(command, json!({"points": points, "radius": brush.radius, "value": brush.value, "hardness": brush.hardness, "continue": !started})).is_some() { ui.data_mut(|d| d.insert_temp(last, [uv.x, uv.y])); } } /// The skew map as a translucent orange layer over the UV square from `top_left` to `bottom_right`. -fn skew_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_left: egui::Pos2, bottom_right: egui::Pos2) { - let Some(k) = app.session.bake_meshes.skew.as_ref().filter(|k| k.values.len() > 1) else { return }; - let key = (app.session.bake_meshes.skew_rev, std::sync::Arc::as_ptr(k) as usize); - let id = ui.scope_id().with("skew_overlay_texture"); +fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_left: egui::Pos2, bottom_right: egui::Pos2) { + let Some(k) = app.session.doc.bake_paint.get(&(app.session.ts(), app.ui.bake_paint_brush.target)).filter(|k| k.values.len() > 1) else { return }; + let key = (app.session.revision, std::sync::Arc::as_ptr(k) as usize); + let id = ui.scope_id().with("bake_paint_overlay_texture"); let cached: Option<((u64, usize), egui::TextureHandle)> = ui.data(|d| d.get_temp(id)); let tex = match cached { Some((c, t)) if c == key => t, @@ -1123,10 +1123,14 @@ fn skew_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, top_lef for y in 0..oh { for x in 0..ow { let v = k.values.get((y * h / oh) * w + x * w / ow).copied().unwrap_or(0.0).clamp(0.0, 1.0); + let v = match app.ui.bake_paint_brush.target { + texturecraft_engine::core::BakePaintTarget::Skew => v, + texturecraft_engine::core::BakePaintTarget::Cage => 1.0 - v, + }; rgba.extend_from_slice(&[255, 140, 40, (v * 170.0) as u8]); } } - let tex = ui.ctx().load_texture("skew_overlay", egui::ColorImage::from_rgba_unmultiplied([ow, oh], &rgba), egui::TextureOptions::NEAREST); + let tex = ui.ctx().load_texture("bake_paint_overlay", egui::ColorImage::from_rgba_unmultiplied([ow, oh], &rgba), egui::TextureOptions::NEAREST); ui.data_mut(|d| d.insert_temp(id, (key, tex.clone()))); tex } diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index c39a1162..409966c6 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -91,11 +91,11 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.method, CurvatureMethod::Mesh); assert!(harness.query_by_label("Details").is_none()); harness.get_by_label("Sampling Radius"); - harness.get_by_label("Value Bounds Min"); - harness.get_by_label("Value Bounds Max"); - click(&mut harness, "Auto Tonemapping"); assert!(harness.query_by_label("Value Bounds Min").is_none()); assert!(harness.query_by_label("Value Bounds Max").is_none()); + click(&mut harness, "Auto Tonemapping"); + harness.get_by_label("Value Bounds Min"); + harness.get_by_label("Value Bounds Max"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.mesh.auto_tonemapping); } diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/skew_paint.rs index 8228f1bc..1fd92400 100644 --- a/crates/ui-egui/tests/skew_paint.rs +++ b/crates/ui-egui/tests/skew_paint.rs @@ -19,23 +19,23 @@ fn harness() -> Harness<'static, TextureCraftApp> { } #[test] -fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { +fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); h.get_by_label("Skew Correction"); - assert!(h.state().session.bake_meshes.skew.is_none() && !h.state().ui.skew_brush.on); + assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); // Off: a drag in the view paints nothing. h.drag_at(egui::pos2(600.0, 500.0)); h.hover_at(egui::pos2(800.0, 500.0)); h.drop_at(egui::pos2(800.0, 500.0)); h.run_steps(3); - assert!(h.state().session.bake_meshes.skew.is_none(), "the brush is off"); + assert!(h.state().session.doc.bake_paint.is_empty(), "the brush is off"); // On: the checkbox turns it on, and the same drag makes a map with paint along the stroke. h.get_by_label("Paint Skew Correction").scroll_to_me(); h.run_steps(3); h.get_by_label("Paint Skew Correction").click(); h.run_steps(3); - assert!(h.state().ui.skew_brush.on); + assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); h.drag_at(egui::pos2(600.0, 500.0)); h.run_steps(2); @@ -43,7 +43,7 @@ fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { h.run_steps(2); h.drop_at(egui::pos2(800.0, 500.0)); h.run_steps(3); - let map = h.state().session.bake_meshes.skew.clone().expect("the stroke made a skew map"); + let map = h.state().session.doc.bake_paint.get(&(0, texturecraft_engine::core::BakePaintTarget::Skew)).cloned().expect("the stroke made a skew map"); let painted = map.values.iter().filter(|v| **v > 0.5).count(); assert!(painted > 50 && painted < map.values.len() / 2, "a stroke, not the whole map: {painted} of {}", map.values.len()); @@ -52,5 +52,5 @@ fn the_bake_panel_has_the_skew_brush_and_dragging_paints_the_map() { h.run_steps(3); h.get_by_label("Remove Skew Correction").click(); h.run_steps(3); - assert!(h.state().session.bake_meshes.skew.is_none()); + assert!(h.state().session.doc.bake_paint.is_empty()); } From 799a4c8908eb02fd557066221f3dd24a8415f040 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 04:05:05 -0500 Subject: [PATCH 016/275] Keep PR review guidelines local --- pr-review-guidelines.md | 68 ----------------------------------------- 1 file changed, 68 deletions(-) delete mode 100644 pr-review-guidelines.md diff --git a/pr-review-guidelines.md b/pr-review-guidelines.md deleted file mode 100644 index eebcb242..00000000 --- a/pr-review-guidelines.md +++ /dev/null @@ -1,68 +0,0 @@ -# My PR review standards - -Review and improve the PR using these preferences. Follow the repository's instructions and keep changes focused on the problem being solved. - -## Correctness - -- Verify the claimed fix against the actual code and its callers -- Look for missed edge cases, incomplete fixes, and regressions -- Reproduce suspicious behavior locally when practical -- Make regression tests fail before the fix and pass afterward -- Confirm tests exercise the intended path, especially fallbacks and error handling - -## Optimization and simplicity - -- Prefer the smallest complete solution that is efficient and easy to understand -- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access -- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost -- Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads -- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations -- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity - -## Clarity, naming, and spacing - -- Clean up the methods being changed, including their tests -- Use descriptive names that explain purpose; include units where useful -- Avoid cryptic abbreviations, misleading names, and unexplained production constants -- Keep control flow direct and share repeated logic when it makes the code simpler -- Separate logical steps with sensible blank lines so code is easy to scan -- Put a blank line after a multiline `let ... else` guard before the next statement; never place the next `let` directly after its closing `};` -- Keep related statements together and follow the repository's formatter - -## Source organization - -- Keep each class, enum, or struct in its own source file, with its implementation beside it -- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust -- Use singular folder names, such as `map`, `setting`, or `tracing` -- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file - -## Comments - -- Use short, single-line comments or concise adjacent comments -- Avoid block comments and prose wrapped across multiple comment lines -- Explain intent or a non-obvious constraint rather than narrating the code -- No trailing punctuation on ordinary code comments -- Avoid overexplaining and remove stale or redundant comments -- Apply these standards to both production code and tests - -## Validation and reporting - -- Run relevant tests and required repository checks with the project's expected toolchain -- For comments or spacing alone, verify formatting and that executable code is unchanged -- Report concrete findings with locations, reproduction details, and practical impact -- Separate confirmed problems from hypotheses and optional improvements -- Give measured optimization results with workload and environment details -- State remaining limitations and distinguish existing failures from new ones - -## Review and commit workflow - -- Preserve unrelated work and leave changes unstaged for my manual review unless I ask otherwise -- Stage only when requested -- Wait for my explicit commit command before committing -- Do not push or post reviews or comments without explicit instructions -- When requested, provide a simple ready-to-post Markdown summary outside the repository and exclude it from the commit - -## Scope of method fixes - -- Whenever a method needs a fix, apply all of my review standards across the entire method, including existing code outside the immediate fix -- Ensure the whole method has sensible spacing between logical steps and concise, useful comments that follow the standards above From e0d11e022707838b12b4087f190257f92482f1b7 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 05:02:13 -0500 Subject: [PATCH 017/275] docs: restore Adobe Painter references in agent guidance --- AGENTS.md | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 08975836..53aa71df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # AGENTS.md: guide for AI agents and contributors TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the -workflow of the reference app, written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview +workflow known from Adobe Substance 3D Painter, written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a dependency, build step or packaging target. The product name is always written **TextureCraft** @@ -15,7 +15,7 @@ to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a standards, and contribute reusable learnings back there. Shared code goes only in craft-libs (`standards/shared-libraries.md`); otherwise copy, don't depend. -The goal is 1:1 parity with the reference app's workflow (same panels, menus, shortcuts, layer +The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer stack semantics and export conventions) with better performance, every feature drivable by agents, and builds for Windows, macOS, Linux, FreeBSD and the web. Read this file first, then `docs/`. @@ -26,7 +26,7 @@ and builds for Windows, macOS, Linux, FreeBSD and the web. Read this file first, | `docs/architecture.md` | Crate map, layers, the CPU texel engine + GPU viewport split, data flow | | `docs/control-protocol.md` | The JSON control channel and MCP: how agents drive the running app | | `ROADMAP.md` | Honest parity estimate, milestones, **current focus** | -| `docs/parity.md` | Generated list of menu items in the reference app: live or missing | +| `docs/parity.md` | Generated list of Painter menu items: live or missing | | `docs/releasing.md` | Versioning (`cargo xtask version`), the `release` branch, packaging | | `ATTRIBUTION.md` | Every bundled asset with author, source, license | | `crates//README.md` (where present) | Public API of that crate | @@ -58,18 +58,10 @@ replace it without touching the engine. ## 3. Golden rules -### Never name the reference product (absolutely essential) - -- The repository never names the commercial product TextureCraft is modeled on, nor its vendor, - in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference - app", "the professional model-painter workflow" or describe the feature itself. -- Notes that name it may live only in the gitignored `plan/` folder. - ### Assets, icons and images (absolutely essential) - **Never use any icon, image, logo, texture, material, brush, environment, font or other asset - from the reference app, any other products from its vendor, or Avid, Image-Line or Autodesk - products**, and never copy files from any installed + from Adobe, Avid, Image-Line or Autodesk products**, and never copy files from any installed commercial application (proprietary formats such as `.sbsar`, `.spexp`, `.sppr` or `.spsm`, HDR environments, UI icons). Not as reference files in the repo either. - Every image or icon must be **open source, public domain, Creative Commons (CC0/CC-BY), or @@ -92,8 +84,8 @@ workflow. Work from public documentation, general domain knowledge, public algor (GGX/Smith/Schlick, split-sum IBL, MikkTSpace, jump-flood/BFS dilation, Möller–Trumbore, SAH BVH, spherical harmonics, reoriented normal mapping, W3C blend modes) and public engine conventions (glTF, Unreal, Unity packing). Never copy proprietary code, shaders, presets or file formats; -File compatibility with the reference app (`.spp`, `.spexp`, `.sbsar`) is a non-goal. Always describe -TextureCraft as a clean-room implementation, in code, docs and commits. +Painter file compatibility (`.spp`, `.spexp`, `.sbsar`) is a non-goal. Always describe TextureCraft +as a clean-room implementation, in code, docs and commits. ### Never crash (outranks feature work) @@ -176,7 +168,7 @@ after every arc of work that builds and passes. ## 7. Where things are tracked - `ROADMAP.md`: milestones, parity estimate and remaining effort. -- `docs/parity.md`: generated menu coverage for the reference app. +- `docs/parity.md`: generated Painter menu coverage. - `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. - `plan/` (local, gitignored): execution plan and notes. - `log/` (local, gitignored): the dev log. From 60cc555daecf62fa6432d3b7fdb2cc8515601517 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 05:14:40 -0500 Subject: [PATCH 018/275] Little helper for AGENTS.md to prevent any application name leakage --- AGENTS.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 53aa71df..5882a81c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,6 +58,13 @@ replace it without touching the engine. ## 3. Golden rules +### Never name the reference product (absolutely essential) + +- The repository never names the commercial product TextureCraft is modeled on, nor its vendor, + in code, comments, docs, commit messages, test names, file names or UI text. Say "the reference + app", "the professional model-painter workflow" or describe the feature itself. +- Notes that name it may live only in the gitignored `plan/` folder or in this `AGENTS.md` file + ### Assets, icons and images (absolutely essential) - **Never use any icon, image, logo, texture, material, brush, environment, font or other asset From 37ad2112ca97d95e54c9e688048edb865533f74b Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 09:47:51 -0500 Subject: [PATCH 019/275] ci: add SonarCloud analysis --- .github/workflows/sonarcloud.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/sonarcloud.yml diff --git a/.github/workflows/sonarcloud.yml b/.github/workflows/sonarcloud.yml new file mode 100644 index 00000000..8ab024cf --- /dev/null +++ b/.github/workflows/sonarcloud.yml @@ -0,0 +1,19 @@ +name: SonarCloud + +on: + push: + branches: [main] + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + +concurrency: + group: sonarcloud-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +jobs: + sonarcloud: + uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main + secrets: inherit From faa698a70f7dcb936c9fe4da2d9571ea2e573e0d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 12:29:02 -0500 Subject: [PATCH 020/275] Enable Flatpak OCI publishing --- packaging/linux/flatpak-bundle.sh | 23 ++++++++++- packaging/linux/flatpak-oci.sh | 66 +++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100755 packaging/linux/flatpak-oci.sh diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 3f9e4e07..29601bea 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -18,12 +18,18 @@ set -euo pipefail HERE="$ROOT/packaging/linux" APP_ID=ai.storyteller.texturecraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo +# The OCI repository serves only the latest stable release, so a prerelease bundle gets no update +# source: Flatpak would otherwise replace it with that older stable build. +OCI_REPO=oci+https://getartcraft.com +if [[ "$VERSION" == *-* ]]; then OCI_REPO=""; fi TEST=1 +OCI=0 TARBALL="" while [ $# -gt 0 ]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -58,9 +64,24 @@ flatpak-builder --user --install-deps-from=flathub --disable-rofiles-fuse --forc --default-branch=stable --repo="$WORK/repo" --state-dir="$WORK/state" "$WORK/build" "$WORK/$APP_ID.yml" OUT="$DIST/$BASENAME.flatpak" +# A release build (the shared release workflow sets SIGNING_FPR, SIGNING_PUBKEY and GNUPGHOME) +# signs the commit and embeds the public key, so Flatpak verifies the bundle when installing it. +GPG_KEYS=() +if [[ -n "${SIGNING_FPR:-}" ]]; then + flatpak build-sign "$WORK/repo" "$APP_ID" stable --gpg-sign="$SIGNING_FPR" --gpg-homedir="${GNUPGHOME:?}" + GPG_KEYS=(--gpg-keys="${SIGNING_PUBKEY:?}") + if [[ "${OCI_SIGNATURES_READY:-}" != 1 ]]; then OCI_REPO=""; fi +fi # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. -flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable +# --repo-url makes the installed origin update from the ArtCraft OCI repository. +flatpak build-bundle --runtime-repo="$FLATHUB" ${OCI_REPO:+--repo-url="$OCI_REPO"} "${GPG_KEYS[@]}" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi if [ "$TEST" = 1 ]; then flatpak install --user -y --noninteractive --reinstall "$OUT" diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 00000000..d905eda4 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Build texturecraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/texturecraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="texturecraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/texturecraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Only a stable release-branch build may move the stable tag. + if [[ "$VERSION" != *-* && "${GITHUB_REF:-}" == refs/heads/release ]]; then + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + fi + + echo "==> Push complete" +fi From 4c4f71330fad0ac657230109bebe183773094220 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 12:30:01 -0500 Subject: [PATCH 021/275] Honor release version in packaging --- packaging/env.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/env.sh b/packaging/env.sh index 4fe93776..9ca7ca2c 100644 --- a/packaging/env.sh +++ b/packaging/env.sh @@ -21,7 +21,7 @@ workspace_version() { ' "$ROOT/Cargo.toml" } -VERSION="${TEXTURECRAFT_VERSION:-$(workspace_version)}" +VERSION="${TEXTURECRAFT_VERSION:-${RELEASE_VERSION:-$(workspace_version)}}" if [ -z "$VERSION" ]; then echo "error: could not read [workspace.package] version from $ROOT/Cargo.toml" >&2 exit 1 From 347bda840d640d4ad42cf5e0b25e3635fe37c664 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 12:34:09 -0500 Subject: [PATCH 022/275] Release TextureCraft 0.3.1 --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c4fab2f1..7a9453c3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3812,7 +3812,7 @@ dependencies = [ [[package]] name = "texturecraft" -version = "0.3.0" +version = "0.3.1" dependencies = [ "eframe", "egui", @@ -3831,7 +3831,7 @@ dependencies = [ [[package]] name = "texturecraft-automation" -version = "0.3.0" +version = "0.3.1" dependencies = [ "base64 0.22.1", "cap-std", @@ -3852,7 +3852,7 @@ dependencies = [ [[package]] name = "texturecraft-bake" -version = "0.3.0" +version = "0.3.1" dependencies = [ "bytemuck", "rayon", @@ -3864,7 +3864,7 @@ dependencies = [ [[package]] name = "texturecraft-cli" -version = "0.3.0" +version = "0.3.1" dependencies = [ "image", "serde_json", @@ -3876,7 +3876,7 @@ dependencies = [ [[package]] name = "texturecraft-compose" -version = "0.3.0" +version = "0.3.1" dependencies = [ "half", "rayon", @@ -3887,7 +3887,7 @@ dependencies = [ [[package]] name = "texturecraft-core" -version = "0.3.0" +version = "0.3.1" dependencies = [ "serde", "serde_json", @@ -3896,7 +3896,7 @@ dependencies = [ [[package]] name = "texturecraft-engine" -version = "0.3.0" +version = "0.3.1" dependencies = [ "epaint_default_fonts", "image", @@ -3916,7 +3916,7 @@ dependencies = [ [[package]] name = "texturecraft-formats" -version = "0.3.0" +version = "0.3.1" dependencies = [ "base64 0.22.1", "exr", @@ -3940,7 +3940,7 @@ dependencies = [ [[package]] name = "texturecraft-geom" -version = "0.3.0" +version = "0.3.1" dependencies = [ "glam 0.30.10", "mikktspace", @@ -3951,7 +3951,7 @@ dependencies = [ [[package]] name = "texturecraft-paint" -version = "0.3.0" +version = "0.3.1" dependencies = [ "epaint_default_fonts", "harfrust", @@ -3966,7 +3966,7 @@ dependencies = [ [[package]] name = "texturecraft-render" -version = "0.3.0" +version = "0.3.1" dependencies = [ "bytemuck", "half", @@ -3985,11 +3985,11 @@ dependencies = [ [[package]] name = "texturecraft-texel" -version = "0.3.0" +version = "0.3.1" [[package]] name = "texturecraft-ui-egui" -version = "0.3.0" +version = "0.3.1" dependencies = [ "base64 0.22.1", "craft-ui", @@ -4018,7 +4018,7 @@ dependencies = [ [[package]] name = "texturecraft-web" -version = "0.3.0" +version = "0.3.1" dependencies = [ "eframe", "js-sys", @@ -5282,7 +5282,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.3.0" +version = "0.3.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index d6259b75..02b5a6dc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["vendor"] default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"] [workspace.package] -version = "0.3.0" +version = "0.3.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From a09297feb9a97b2fbd3c04949b9823c8f5c24518 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 4 Nov 2026 17:45:29 -0500 Subject: [PATCH 023/275] Pass the Linux signing key to the release workflow (#242) --- .github/workflows/release.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3ed14bca..69e0384b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,3 +43,4 @@ jobs: AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} From b978bc952523c718c64e4029a7686bca24aee6ed Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 18:57:05 -0500 Subject: [PATCH 024/275] Recover older project settings --- crates/engine/src/file_cmds.rs | 8 +- crates/engine/src/material_lib.rs | 1 + crates/engine/tests/project_recovery.rs | 35 +++++ crates/formats/README.md | 6 + crates/formats/src/project_file/mod.rs | 34 +++- crates/formats/src/project_file/recovery.rs | 75 +++++++++ crates/formats/src/project_file/tests.rs | 163 +++++++++++++++++++- 7 files changed, 315 insertions(+), 7 deletions(-) create mode 100644 crates/engine/tests/project_recovery.rs create mode 100644 crates/formats/src/project_file/recovery.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 25b6c91d..48d4e8b2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -174,21 +174,25 @@ impl Session { (Some((ext, bytes)), None) => read_stored_mesh(&pf.project, ext, bytes)?.mesh, (None, None) => return Err(EngineError::Other("the project has no mesh".into())), }; + check_materials(&pf.project, &mesh)?; let source = pf.mesh.clone(); let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect(); let mut s = Session::new(Document { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + s.sync_images(); s.load_bake_meshes(pf.high_poly, pf.cage); s.load_bake_paint(pf.bake_paint); + s.log.extend(pf.warnings); + Ok(s) } /// The project as a `ProjectFile` (for saving). pub fn project_file(&self) -> ProjectFile { let mut pixels = self.doc.pixels.clone(); - // Drop pixel images whose size no longer matches their texture set (never unloadable). + // Drop pixel images whose size no longer matches their texture set let size_of = |id: texturecraft_core::LayerId| { self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(TextureSet::size).or_else(|| { self.doc @@ -201,6 +205,7 @@ impl Session { }; pixels.layers.retain(|(id, _), img| size_of(*id) == Some((img.width(), img.height()))); pixels.masks.retain(|id, img| size_of(*id) == Some((img.width(), img.height()))); + let (high_poly, cage) = self.saved_bake_meshes(); ProjectFile { project: self.doc.project.clone(), @@ -212,6 +217,7 @@ impl Session { bake_paint: self.saved_bake_paint(), thumbnail: None, resources: self.doc.resources.iter().map(|(k, v)| (k.clone(), v.as_ref().clone())).collect(), + warnings: Vec::new(), } } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 23144a61..bdd2fbdd 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -89,6 +89,7 @@ impl Session { bake_paint: BTreeMap::new(), thumbnail: None, resources, + warnings: Vec::new(), }; texturecraft_formats::save_project_bytes(&pf).map_err(fe) } diff --git a/crates/engine/tests/project_recovery.rs b/crates/engine/tests/project_recovery.rs new file mode 100644 index 00000000..90612b56 --- /dev/null +++ b/crates/engine/tests/project_recovery.rs @@ -0,0 +1,35 @@ +use std::io::{Cursor, Write}; + +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; +use zip::{ZipWriter, write::SimpleFileOptions}; + +#[test] +fn recovered_project_opens_with_a_warning_in_the_session_log() { + let mut original = Session::new_project("Recovery", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + execute(&mut original, "layer.add.fill", &json!({"color": "#336699"})).unwrap(); + let mut json = serde_json::to_value(&original.doc.project).unwrap(); + json["texture_sets"][0]["bake"]["maps"] = json!(["Normal", "AmbientOcclusion"]); + let mut archive = ZipWriter::new(Cursor::new(Vec::new())); + archive.start_file("project.json", SimpleFileOptions::default()).unwrap(); + archive.write_all(&serde_json::to_vec(&json).unwrap()).unwrap(); + let bytes = archive.finish().unwrap().into_inner(); + + let recovered = Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(recovered.doc.project, original.doc.project); + let warnings: Vec<_> = recovered.log.iter().filter(|message| message.starts_with("Warning:")).collect(); + assert_eq!(warnings.len(), 1); + assert!(warnings[0].contains("could not be imported")); + assert!(warnings[0].contains("recovered what it could")); + + let reopened = Session::from_project_bytes(&recovered.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, original.doc.project); + assert!(!reopened.log.iter().any(|message| message.starts_with("Warning:"))); + + let path = std::env::temp_dir().join(format!("texturecraft-recovery-{}.tcraft", std::process::id())); + std::fs::write(&path, &bytes).unwrap(); + execute(&mut original, "file.open", &json!({"path": path})).unwrap(); + assert_eq!(original.log, recovered.log); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + std::fs::remove_file(path).unwrap(); +} diff --git a/crates/formats/README.md b/crates/formats/README.md index 70f8429b..7b28004e 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -122,6 +122,7 @@ Built-in presets: pub struct ProjectFile { pub project: Project, pub pixels: PixelStore, pub baked: BTreeMap, pub mesh: Option<(String /* ext */, Vec)>, pub thumbnail: Option>, + pub warnings: Vec, // Import warnings, never saved } pub fn save_project_bytes(pf: &ProjectFile) -> Result>; pub fn load_project_bytes(bytes: &[u8]) -> Result; @@ -148,3 +149,8 @@ Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError checks every tile against its texture set's resolution and component count, rejects repeated or out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the total decompressed size at 8 GiB. + +Unreadable bake settings fall back to defaults field by field while readable settings and project +content are retained. Legacy baked-map filenames remain readable; unsupported baked-map types are +skipped. Recovery adds a warning to `ProjectFile::warnings`, displayed in the session log when the +project opens. Structural errors and corrupt pixel data still fail validation. diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 496c34f5..045dd0da 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -23,7 +23,7 @@ use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; use texturecraft_compose::{BakedMaps, PixelStore}; -use texturecraft_core::{BakePaintTarget, BakedMap, Channel, FORMAT_VERSION, LayerId, Project}; +use texturecraft_core::{BakePaintTarget, Channel, FORMAT_VERSION, LayerId, Project}; use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; @@ -44,6 +44,7 @@ const MAX_TOTAL: u64 = 8 << 30; const MAX_TEXELS: u64 = 1 << 28; mod bake_paint_data; +mod recovery; pub use bake_paint_data::BakePaintData; /// Everything a project file holds. @@ -64,6 +65,8 @@ pub struct ProjectFile { pub thumbnail: Option>, /// Imported resources (images used by fills, alphas, stencils), by name: original bytes. pub resources: BTreeMap>, + /// Import warnings for the caller's log; never saved in the archive + pub warnings: Vec, } /// A resource name safe as a zip entry and a file name: `[A-Za-z0-9_.-]`, at most 120 chars. @@ -341,6 +344,7 @@ fn load(reader: R) -> Result { if zip.len() > MAX_ENTRIES { return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); } + let mut budget = Budget(0); let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; #[derive(serde::Deserialize)] @@ -351,7 +355,8 @@ fn load(reader: R) -> Result { if v.format_version > FORMAT_VERSION { return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION }); } - let project: Project = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; + + let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?; project.validate()?; let too_large = |t: &texturecraft_core::TextureSet| u64::from(t.size().0) * u64::from(t.size().1) > MAX_TEXELS; if let Some(ts) = project.texture_sets.iter().find(|t| t.resolution == 0 || t.resolution > MAX_IMAGE_SIZE || too_large(t)) { @@ -367,8 +372,10 @@ fn load(reader: R) -> Result { bake_paint: BTreeMap::new(), thumbnail: None, resources: BTreeMap::new(), + warnings: Vec::new(), project, }; + for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; let name = f.name().map_err(zip_err)?.into_owned(); @@ -379,12 +386,14 @@ fn load(reader: R) -> Result { if res_name.is_empty() || sanitize_resource_name(res_name) != res_name { return Err(malformed(KIND, format!("bad resource name {name}"))); } + let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?; pf.resources.insert(res_name.to_string(), bytes); } else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") { if file.is_empty() || sanitize_resource_name(file) != file { return Err(malformed(KIND, format!("bad mesh name {name}"))); } + let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?); match dir { "cage" => pf.cage = Some(entry), @@ -396,6 +405,7 @@ fn load(reader: R) -> Result { if texture_set >= pf.project.texture_sets.len() { return Err(malformed(KIND, format!("unknown texture set in {name}"))); } + let target = match target { "cage" => BakePaintTarget::Cage, "skew" => BakePaintTarget::Skew, @@ -410,22 +420,29 @@ fn load(reader: R) -> Result { let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let id = LayerId(id.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let c = Channel::ALL.into_iter().find(|c| c.id() == chan).ok_or_else(|| malformed(KIND, format!("unknown channel in {name}")))?; - // Pixels of layers that are no longer in any stack are dropped. + // Drop pixels of layers that are no longer in any stack let Some(size) = size_of(id) else { continue }; + let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?; pf.pixels.layers.insert((id, c), img); } else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) { let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let Some(size) = size_of(id) else { continue }; + let img = read_tiles(&mut f, size, 2, &mut budget, &name)?; pf.pixels.masks.insert(id, img); } else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) { let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; let ts: usize = ts.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?; - let m = BakedMap::parse(map).ok_or_else(|| malformed(KIND, format!("unknown baked map in {name}")))?; + let Some(m) = recovery::baked_map(map) else { + recovered = true; + continue; + }; + if ts >= pf.project.texture_sets.len() { continue; } + let (res, height, data) = read_baked(&mut f, m.components(), &mut budget, &name)?; let maps = pf.baked.entry(ts).or_default(); if maps.maps.is_empty() { @@ -435,8 +452,15 @@ fn load(reader: R) -> Result { } maps.maps.insert(m, Arc::new(data)); } - // Other entries (from newer minor revisions) are ignored. + // Ignore other entries from newer minor revisions } + + if recovered { + pf.warnings.push( + "Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(), + ); + } + Ok(pf) } diff --git a/crates/formats/src/project_file/recovery.rs b/crates/formats/src/project_file/recovery.rs new file mode 100644 index 00000000..8b488051 --- /dev/null +++ b/crates/formats/src/project_file/recovery.rs @@ -0,0 +1,75 @@ +use serde::Deserialize; +use serde_json::Value; +use texturecraft_core::{BakeSettings, BakedMap, Project}; + +pub(super) fn read_project(json: &[u8]) -> serde_json::Result<(Project, bool)> { + let error = match serde_json::from_slice(json) { + Ok(project) => return Ok((project, false)), + Err(error) => error, + }; + + let mut project: Value = serde_json::from_slice(json)?; + let mut recovered = false; + if let Some(texture_sets) = project.get_mut("texture_sets").and_then(Value::as_array_mut) { + for texture_set in texture_sets { + if let Some(bake) = texture_set.get_mut("bake") + && BakeSettings::deserialize(&*bake).is_err() + { + let mut settings = serde_json::to_value(BakeSettings::default())?; + recover_bake_fields(&mut settings, bake, ""); + *bake = settings; + recovered = true; + } + + if let Some(baked) = texture_set.get_mut("baked") { + if let Some(maps) = baked.as_array_mut() { + let count = maps.len(); + maps.retain(|map| BakedMap::deserialize(map).is_ok()); + recovered |= maps.len() != count; + } else { + *baked = Value::Array(Vec::new()); + recovered = true; + } + } + } + } + + if !recovered { + return Err(error); + } + + Ok((serde_json::from_value(project)?, true)) +} + +// Walk the default schema so unknown fields and input nesting cannot expand recovery +fn recover_bake_fields(recovered: &mut Value, original: &Value, path: &str) { + let Some(fields) = recovered.pointer(path).and_then(Value::as_object) else { + return; + }; + + let keys: Vec<_> = fields.keys().cloned().collect(); + for key in keys { + let Some(value) = original.get(&key) else { continue }; + let field_path = format!("{path}/{key}"); + let Some(field) = recovered.pointer_mut(&field_path) else { continue }; + let previous = std::mem::replace(field, value.clone()); + if BakeSettings::deserialize(&*recovered).is_err() { + if let Some(field) = recovered.pointer_mut(&field_path) { + *field = previous; + } + + // A bad nested field must not discard its readable siblings + recover_bake_fields(recovered, value, &field_path); + } + } +} + +pub(super) fn baked_map(name: &str) -> Option { + match name { + "normal_base" => Some(BakedMap::Normal), + "world_space_normals" => Some(BakedMap::WorldNormal), + "ambient_occlusion" => Some(BakedMap::AmbientOcclusion), + "bent_normals" => Some(BakedMap::BentNormal), + _ => BakedMap::parse(name), + } +} diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index e33eed29..0a3c5067 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use texturecraft_core::{Effect, EffectKind, Fill, Layer, LayerKind, Mask, MaskBackground, TextureSet}; +use texturecraft_core::{BakedMap, Effect, EffectKind, Fill, Layer, LayerKind, Mask, MaskBackground, TextureSet}; use super::*; @@ -38,6 +38,7 @@ fn sample() -> Sample { .into(), thumbnail: Some(vec![137, 80, 78, 71]), resources: [("bricks.png".to_string(), vec![9, 8, 7])].into(), + warnings: Vec::new(), }; Sample { pf, paint } } @@ -69,6 +70,7 @@ fn round_trip_is_identical_and_deterministic() { let s = sample(); let bytes = save_project_bytes(&s.pf).unwrap(); let back = load_project_bytes(&bytes).unwrap(); + assert!(back.warnings.is_empty()); assert_same(&s.pf, &back); assert_eq!(back.pixels.layer(s.paint, Channel::BaseColor).unwrap().get(127, 127), [65535, 0, 9, 65535]); assert_eq!(save_project_bytes(&back).unwrap(), bytes); @@ -226,3 +228,162 @@ fn bake_model_options_survive_the_project_archive() { let bytes = save_project_bytes(&project_file).unwrap(); assert_same(&project_file, &load_project_bytes(&bytes).unwrap()); } + +fn edit_archive(project_file: &ProjectFile, mut edit: impl FnMut(&mut String, &mut Vec)) -> Vec { + let bytes = save_project_bytes(project_file).unwrap(); + let mut source = ZipArchive::new(Cursor::new(bytes)).unwrap(); + let mut output = ZipWriter::new(Cursor::new(Vec::new())); + + for index in 0..source.len() { + let mut entry = source.by_index(index).unwrap(); + let mut name = entry.name().unwrap().into_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + edit(&mut name, &mut data); + output.start_file(name, SimpleFileOptions::default()).unwrap(); + output.write_all(&data).unwrap(); + } + + output.finish().unwrap().into_inner() +} + +fn edit_project_json(project_file: &ProjectFile, mut edit: impl FnMut(&mut serde_json::Value)) -> Vec { + edit_archive(project_file, |name, data| { + if name == "project.json" { + let mut json = serde_json::from_slice(data).unwrap(); + edit(&mut json); + *data = serde_json::to_vec(&json).unwrap(); + } + }) +} + +#[test] +fn recovery_loads_legacy_bake_settings_and_map_names() { + let mut expected = sample().pf; + let maps = expected.baked.get_mut(&0).unwrap(); + maps.maps.insert(BakedMap::WorldNormal, Arc::new(vec![0.5; 16 * 16 * 3])); + maps.maps.insert(BakedMap::BentNormal, Arc::new(vec![0.5; 16 * 16 * 3])); + expected.project.texture_sets[0].baked = maps.maps.keys().copied().collect(); + expected.project.texture_sets[1].bake.common.dilation = 12; + + let bytes = edit_archive(&expected, |name, data| { + if name == "project.json" { + let mut json: serde_json::Value = serde_json::from_slice(data).unwrap(); + json["texture_sets"][0]["bake"] = serde_json::json!({ + "enabled": true, "resolution": 1024, "antialiasing": 1, "dilation": 16, + "maps": ["Normal", "WorldNormal", "Id", "AmbientOcclusion", "Curvature", "Position", "Thickness"], + "ao": {"rays": 64, "max_distance": 0.1}, "use_low_as_high": true + }); + json["texture_sets"][0]["baked"].as_array_mut().unwrap().extend(serde_json::json!(["ColorMap", "WorldDirection"]).as_array().unwrap().clone()); + *data = serde_json::to_vec(&json).unwrap(); + } + + *name = name + .replace("_normal.bin", "_normal_base.bin") + .replace("_worldNormal.bin", "_world_space_normals.bin") + .replace("_ambientOcclusion.bin", "_ambient_occlusion.bin") + .replace("_bentNormal.bin", "_bent_normals.bin"); + }); + + let recovered = load_project_bytes(&bytes).unwrap(); + assert_eq!(recovered.warnings.len(), 1); + assert_same(&expected, &recovered); + let reopened = load_project_bytes(&save_project_bytes(&recovered).unwrap()).unwrap(); + assert_same(&expected, &reopened); + assert!(reopened.warnings.is_empty()); +} + +#[test] +fn recovery_keeps_readable_bake_fields_and_project_content() { + let mut expected = sample().pf; + let settings = &mut expected.project.texture_sets[0].bake; + settings.common.dilation = 19; + settings.maps.height.is_enabled = true; + settings.maps.ao.parameters.rays.rays = 96; + settings.maps.ao.parameters.ground_plane.enabled = true; + settings.high_poly.low_suffix = "_lo".into(); + expected.project.texture_sets[1].bake.common.dilation = 7; + + let bytes = edit_project_json(&expected, |json| { + let bake = &mut json["texture_sets"][0]["bake"]; + bake["common"]["antialiasing"] = serde_json::json!("unknown"); + bake["common"]["resolution_height"] = serde_json::json!(false); + bake["maps"]["normal"] = serde_json::json!("Normal"); + bake["maps"]["ao"]["parameters"]["rays"]["max_distance"] = serde_json::json!("bad"); + bake["maps"]["opacity"]["is_enabled"] = serde_json::json!(null); + bake["cage"] = serde_json::json!([1, 2]); + }); + + assert_same(&expected, &load_project_bytes(&bytes).unwrap()); +} + +#[test] +fn recovery_defaults_unreadable_bake_blocks() { + let expected = sample().pf; + for invalid in [serde_json::Value::Null, serde_json::json!(false), serde_json::json!("old"), serde_json::json!(["Normal"])] { + let bytes = edit_project_json(&expected, |json| json["texture_sets"][0]["bake"] = invalid.clone()); + assert_same(&expected, &load_project_bytes(&bytes).unwrap()); + } +} + +#[test] +fn recovery_skips_unsupported_baked_map_entries() { + let expected = sample().pf; + let bytes = edit_archive(&expected, |name, _| { + if name == "thumbnail.png" { + *name = "baked/0_color_map.bin".into(); + } + }); + let mut expected = expected; + expected.thumbnail = None; + let recovered = load_project_bytes(&bytes).unwrap(); + assert_same(&expected, &recovered); + assert_eq!(recovered.warnings.len(), 1); +} + +#[test] +fn recovery_does_not_hide_invalid_project_structure_or_newer_versions() { + let project_file = sample().pf; + for (field, value) in [("resolution", serde_json::json!("bad")), ("stack", serde_json::json!([999])), ("channels", serde_json::json!(null))] { + let bytes = edit_project_json(&project_file, |json| { + json["texture_sets"][0]["bake"] = serde_json::json!("old"); + json["texture_sets"][0][field] = value.clone(); + }); + assert!(load_project_bytes(&bytes).is_err(), "{field}"); + } + + let bytes = edit_project_json(&project_file, |json| { + json["format_version"] = serde_json::json!(FORMAT_VERSION + 1); + json["texture_sets"][0]["bake"] = serde_json::json!("old"); + }); + assert!(matches!(load_project_bytes(&bytes), Err(FormatError::NewerVersion { .. }))); +} + +#[test] +fn recovery_still_rejects_corrupt_pixels() { + let project_file = sample().pf; + let bytes = edit_archive(&project_file, |name, data| { + if name == "project.json" { + let mut json: serde_json::Value = serde_json::from_slice(data).unwrap(); + json["texture_sets"][0]["bake"]["maps"] = serde_json::json!(["Normal"]); + *data = serde_json::to_vec(&json).unwrap(); + } else if name.starts_with("pixels/") { + data.truncate(10); + } + }); + + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(error.to_string().contains("pixels/"), "{error}"); +} + +#[test] +fn recovery_does_not_accept_unrelated_json_errors() { + let bytes = edit_archive(&sample().pf, |name, data| { + if name == "project.json" { + data.splice(1..1, br#""name":"duplicate", "#.iter().copied()); + } + }); + + let error = load_project_bytes(&bytes).unwrap_err(); + assert!(error.to_string().contains("duplicate field"), "{error}"); +} From f41eda63ddf472a089b405345ee1c2f53284ab30 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 01:05:40 +0000 Subject: [PATCH 025/275] UI: mode buttons at the right end of the top bar, tool controls scroll when they don't fit The Painting, Bake and Render buttons move from the left tool shelf to the right end of the top bar, which now shows in every mode. The view and mode buttons keep their place; the tool controls scroll in their own strip with arrow buttons and the horizontal wheel instead of drawing over them. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/toolbar.rs | 243 ++++++++++++++++++++------------- crates/ui-egui/src/viewport.rs | 2 +- crates/ui-egui/src/widgets.rs | 14 +- 3 files changed, 160 insertions(+), 99 deletions(-) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 2c900ed3..49553015 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,5 +1,5 @@ //! The context tool bar (brush size, flow, stroke opacity, spacing, lazy mouse, symmetry, view -//! toggles), the vertical tool shelf, the right icon rail and the status bar. +//! toggles, mode buttons), the vertical tool shelf, the right icon rail and the status bar. use egui::{RichText, vec2}; use egui_phosphor::regular as ic; @@ -12,7 +12,7 @@ use crate::i18n::{tr, trf}; use crate::keymap::tip; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button}; +use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; pub fn tool_icon(t: Tool) -> &'static str { match t { @@ -34,84 +34,15 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { ui.horizontal_centered(|ui| { ui.spacing_mut().item_spacing.x = 10.0; - let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(15.0).color(tokens.text_strong)).on_hover_text(tool.label()); - let brush = &mut app.session.tool.brush; - match tool { - Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = brush.size / 0.25 * 100.0; - if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - brush.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); - } - let mut flow = brush.flow * 100.0; - if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - brush.flow = flow / 100.0; - } - let mut opacity = brush.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { - brush.opacity = opacity / 100.0; - } - let mut spacing = brush.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { - brush.spacing = spacing / 100.0; - } - ui.separator(); - let lazy_on = brush.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - brush.lazy = if lazy_on { 0.0 } else { 20.0 }; - } - if lazy_on { - let mut distance = brush.lazy; - if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { - brush.lazy = distance; - } - } - ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { - brush.symmetry.x = !brush.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { - brush.symmetry.y = !brush.symmetry.y; - } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { - brush.particles.enabled = !brush.particles.enabled; - } - if tool == Tool::Smudge { - ui.separator(); - let mut strength = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); - } - } - if tool == Tool::Clone && app.session.tool.clone_source.is_none() { - ui.separator(); - ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); - } - if tool == Tool::Path { - ui.separator(); - path_controls(app, ui); - } - } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - for (fill_mode, icon, tip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } - Tool::ColorPicker => { - ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); - } - Tool::GeometryMask => { - ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); - } - } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + mode_buttons(app, ui); + + // Bake and Render modes have no brush, so their bar holds only the mode buttons + if app.ui.mode != Mode::Painting { + return; + } + + ui.separator(); if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, 24.0).clicked() { app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); } @@ -131,12 +62,153 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let mode = if checker { "material" } else { "uvChecker" }; app.run("viewport.view", json!({"mode": mode})); } + ui.separator(); + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| scrolling_tool_controls(app, ui, &tokens)); }); }); }); }); } +/// The tool's controls, in a strip with scroll arrows when they don't fit +fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { + let strip_width = ui.available_width(); + let overflow_id = egui::Id::unique("tool_controls_overflow"); + let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); + + // A positive delta moves the content right, revealing its start + let arrow_scroll_step = strip_width / 2.0; + let mut scroll_delta = 0.0; + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, 24.0).clicked() { + scroll_delta = arrow_scroll_step; + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, 24.0).clicked() { + scroll_delta = -arrow_scroll_step; + } + + let scroll_area = egui::ScrollArea::horizontal().id_salt("tool_controls").scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); + let output = ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scroll_area.show(ui, |ui| { + ui.scroll_with_delta(vec2(scroll_delta, 0.0)); + ui.horizontal_centered(|ui| tool_controls(app, ui, tokens)); + }) + }); + + // The arrows take room from the strip, so measure the overflow against its full width + let overflows_now = output.inner.content_size.x > strip_width; + if overflows_now != overflowing { + ui.data_mut(|data| data.insert_temp(overflow_id, overflows_now)); + ui.ctx().request_repaint(); + } + }); +} + +/// The selected tool's icon and its settings +fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { + // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 + const MAX_BRUSH_SIZE: f32 = 0.25; + const MIN_BRUSH_SIZE: f32 = 0.0005; + const DEFAULT_LAZY_DISTANCE: f32 = 20.0; + const TOOL_ICON_SIZE: f32 = 15.0; + + let tool = app.session.tool.tool; + ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); + + let brush = &mut app.session.tool.brush; + match tool { + Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { + let mut size = brush.size / MAX_BRUSH_SIZE * 100.0; + if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { + brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + let mut flow = brush.flow * 100.0; + if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { + brush.flow = flow / 100.0; + } + let mut opacity = brush.opacity * 100.0; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { + brush.opacity = opacity / 100.0; + } + let mut spacing = brush.spacing * 100.0; + if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { + brush.spacing = spacing / 100.0; + } + + ui.separator(); + let lazy_on = brush.lazy > 0.0; + if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { + brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE }; + } + if lazy_on { + let mut distance = brush.lazy; + if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + brush.lazy = distance; + } + } + + ui.separator(); + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { + brush.symmetry.x = !brush.symmetry.x; + } + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { + brush.symmetry.y = !brush.symmetry.y; + } + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { + brush.particles.enabled = !brush.particles.enabled; + } + + if tool == Tool::Smudge { + ui.separator(); + let mut strength = app.session.tool.smudge_strength * 100.0; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { + app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); + } + } + if tool == Tool::Clone && app.session.tool.clone_source.is_none() { + ui.separator(); + ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); + } + if tool == Tool::Path { + ui.separator(); + path_controls(app, ui); + } + } + Tool::PolygonFill => { + use texturecraft_engine::FillMode; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), + (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } + } + Tool::ColorPicker => { + ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); + } + Tool::GeometryMask => { + ui.label(RichText::new(tr("Click a mesh part to show or hide the selected layer on it.")).color(tokens.text_dim)); + } + } +} + +/// Bake, Painting and Rendering mode buttons for a right-to-left layout, so Rendering is added first +fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + for (mode, icon, label, command) in [ + (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), + (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), + (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 24.0).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } + } +} + /// Path tool options and actions (top bar and properties). pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let path = &mut app.session.tool.path; @@ -165,19 +237,6 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { egui::Panel::left("tool_shelf").resizable(false).exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { left: GUTTER, right: 0, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { ui.spacing_mut().item_spacing.y = 3.0; - for (mode, icon, label, command) in [ - (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), - (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), - (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 28.0).clicked() { - crate::menus::invoke(app, &ui.ctx().clone(), command); - } - } - - ui.add_space(6.0); - ui.separator(); - ui.add_space(6.0); ui.add_enabled_ui(app.ui.mode == Mode::Painting, |ui| { for tool in Tool::ALL { let selected = app.ui.mode == Mode::Painting && app.session.tool.tool == tool; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index db50b2db..da60a42d 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -43,7 +43,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased }); app.ui.bake_paint_brush.on = bake_painting; - if mode == crate::state::Mode::Painting && !app.ui.hide_ui { + if !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index eb3a8eb4..1dd4046e 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -177,6 +177,11 @@ pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color /// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent /// tinted well (the shared Craft icon button, `craft_ui::buttons`). pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response { + icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) +} + +/// An `icon_button` with no tooltip, whose `label` still names it for screen readers +pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { let tk = Tokens::get(ui.ctx()); let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; let style = IconButtonStyle { @@ -187,12 +192,9 @@ pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: corner_radius: CornerRadius::same(6), focus_stroke: Stroke::new(1.0, tk.accent), }; - IconButton::new(tooltip, vec2(size, size), &style) - .selected(selected) - .show(ui, |ui, rect, color| { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); - }) - .on_hover_text(tooltip) + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); + }) } /// A flat button filled with the accent, white lettering (a dialog's main action). From e072a6a5465552378a2b71c22973c4601160ca5a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 01:22:59 +0000 Subject: [PATCH 026/275] Document the top bar function Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/toolbar.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 49553015..9f04df4c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -28,6 +28,7 @@ pub fn tool_icon(t: Tool) -> &'static str { } } +/// The top bar: the tool's controls, the view buttons and the mode buttons (only the mode buttons outside Painting) pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { From 1f07beeb431e68d979a37da156a1e1d64800eee4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:44:41 +0100 Subject: [PATCH 027/275] Drop unused Body import after merge Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index f9cad66d..7a8a39fa 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -28,7 +28,7 @@ use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; -use self::entries::{Body, Entry}; +use self::entries::Entry; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; From 8eb2c83e04a4185cc1f6276e0e03a3124bd2e6ac Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:57:27 +0100 Subject: [PATCH 028/275] Restore #[test] attribute lost in merge Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 93863a5f..b16d2f02 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -232,6 +232,7 @@ fn load_size_matches_what_load_counts() { } } +#[test] fn bake_model_options_survive_the_project_archive() { use texturecraft_core::{BackfaceMode, CageType, HeightNormalization}; From 70b7029b662b7b2debeed93c6a6a0ec8d5d39226 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:06:18 -0500 Subject: [PATCH 029/275] Fix toolbar overflow in narrow viewports Keep mode buttons accessible while view controls join the scrolling strip when space is tight. Respect the remaining clip width, simplify the layout, translate view hints, and add toolbar interaction and visual checks. --- crates/ui-egui/src/toolbar.rs | 123 +++++++++++++++-------- crates/ui-egui/src/widgets.rs | 16 +-- crates/ui-egui/tests/toolbar.rs | 171 ++++++++++++++++++++++++++++++++ 3 files changed, 260 insertions(+), 50 deletions(-) create mode 100644 crates/ui-egui/tests/toolbar.rs diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 9f04df4c..a075840d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1,5 +1,4 @@ -//! The context tool bar (brush size, flow, stroke opacity, spacing, lazy mouse, symmetry, view -//! toggles, mode buttons), the vertical tool shelf, the right icon rail and the status bar. +//! Context controls, view and mode buttons, tool shelf, icon rail and status bar use egui::{RichText, vec2}; use egui_phosphor::regular as ic; @@ -14,6 +13,11 @@ use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; +const BAR_BUTTON_SIZE: f32 = 24.0; +const BAR_SPACING: f32 = 10.0; +const COMPACT_BAR_SPACING: f32 = 4.0; +const BAR_SEPARATOR_WIDTH: f32 = 6.0; + pub fn tool_icon(t: Tool) -> &'static str { match t { Tool::Paint => ic::PAINT_BRUSH, @@ -28,51 +32,70 @@ pub fn tool_icon(t: Tool) -> &'static str { } } -/// The top bar: the tool's controls, the view buttons and the mode buttons (only the mode buttons outside Painting) +/// Keep mode buttons visible, with painting controls scrolling as space runs out pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let tokens = Tokens::get(ui.ctx()); egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { - ui.horizontal_centered(|ui| { - ui.spacing_mut().item_spacing.x = 10.0; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - mode_buttons(app, ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mode_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; + // Leave room for both scroll arrows and at least one button of content + let minimum_strip_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let scroll_views = ui.available_width() < mode_width + view_buttons_width(BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; + ui.spacing_mut().item_spacing.x = if scroll_views { COMPACT_BAR_SPACING } else { BAR_SPACING }; + mode_buttons(app, ui); - // Bake and Render modes have no brush, so their bar holds only the mode buttons - if app.ui.mode != Mode::Painting { - return; - } + if app.ui.mode != Mode::Painting { + return; + } - ui.separator(); - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, 24.0).clicked() { - app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); - } - ui.separator(); - for (layout, icon, label, id) in [ - (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), - (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), - (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, id), app.ui.layout == layout, 24.0).clicked() { - app.ui.layout = layout; - } - } - ui.separator(); - let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, 24.0).clicked() { - let mode = if checker { "material" } else { "uvChecker" }; - app.run("viewport.view", json!({"mode": mode})); - } - ui.separator(); - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| scrolling_tool_controls(app, ui, &tokens)); + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + if !scroll_views { + view_buttons(app, ui); + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + } + + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + scrolling_tool_controls(app, ui, &tokens, scroll_views); }); }); }); }); } -/// The tool's controls, in a strip with scroll arrows when they don't fit -fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { +fn view_buttons_width(spacing: f32) -> f32 { + // Five icons, two separators and the six gaps between them + 5.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing +} + +/// View buttons in a right-to-left layout, with the screenshot button at the end +fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, BAR_BUTTON_SIZE).clicked() { + app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); + } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + for (layout, icon, label, command) in [ + (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), + (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), + (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), + ] { + if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, BAR_BUTTON_SIZE).clicked() { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } + } + + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, BAR_BUTTON_SIZE).clicked() { + let mode = if checker { "material" } else { "uvChecker" }; + app.run("viewport.view", json!({"mode": mode})); + } +} + +/// Scroll tool controls and, in narrow viewports, the view buttons +fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { let strip_width = ui.available_width(); let overflow_id = egui::Id::unique("tool_controls_overflow"); let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); @@ -80,20 +103,30 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: // A positive delta moves the content right, revealing its start let arrow_scroll_step = strip_width / 2.0; let mut scroll_delta = 0.0; - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, 24.0).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, BAR_BUTTON_SIZE).clicked() { scroll_delta = arrow_scroll_step; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, 24.0).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, BAR_BUTTON_SIZE).clicked() { scroll_delta = -arrow_scroll_step; } - let scroll_area = egui::ScrollArea::horizontal().id_salt("tool_controls").scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); + let scroll_area = egui::ScrollArea::horizontal() + .id_salt("tool_controls") + .min_scrolled_width(0.0) + .scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysHidden); let output = ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { scroll_area.show(ui, |ui| { ui.scroll_with_delta(vec2(scroll_delta, 0.0)); - ui.horizontal_centered(|ui| tool_controls(app, ui, tokens)); + ui.horizontal_centered(|ui| { + tool_controls(app, ui, tokens); + if scroll_views { + ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); + let size = vec2(view_buttons_width(ui.spacing().item_spacing.x), ui.available_height()); + ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); + } + }); }) }); @@ -111,7 +144,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 const MAX_BRUSH_SIZE: f32 = 0.25; const MIN_BRUSH_SIZE: f32 = 0.0005; - const DEFAULT_LAZY_DISTANCE: f32 = 20.0; + const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; let tool = app.session.tool.tool; @@ -124,14 +157,17 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } + let mut flow = brush.flow * 100.0; if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { brush.flow = flow / 100.0; } + let mut opacity = brush.opacity * 100.0; if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { brush.opacity = opacity / 100.0; } + let mut spacing = brush.spacing * 100.0; if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { brush.spacing = spacing / 100.0; @@ -140,7 +176,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) ui.separator(); let lazy_on = brush.lazy > 0.0; if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { - brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE }; + brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE_PX }; } if lazy_on { let mut distance = brush.lazy; @@ -167,10 +203,12 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); } } + if tool == Tool::Clone && app.session.tool.clone_source.is_none() { ui.separator(); ui.label(RichText::new(tr("Hold V and click the mesh to set the clone source")).color(tokens.text_dim)); } + if tool == Tool::Path { ui.separator(); path_controls(app, ui); @@ -178,6 +216,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } Tool::PolygonFill => { use texturecraft_engine::FillMode; + for (fill_mode, icon, tooltip) in [ (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), @@ -204,7 +243,7 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, 24.0).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, BAR_BUTTON_SIZE).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 1dd4046e..72853550 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -174,24 +174,24 @@ pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color painter.layout_job(job) } -/// A square icon button (Phosphor glyph) in a rounded tool well: `selected` sits in the accent -/// tinted well (the shared Craft icon button, `craft_ui::buttons`). +/// A square Phosphor icon button with a tooltip and an accent well when selected pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: f32) -> Response { icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) } /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; let style = IconButtonStyle { - normal: well(Color32::TRANSPARENT, tk.text), - hovered: well(tk.row_hover, tk.text_strong), - pressed: Some(well(tk.tool_active, tk.text_strong)), - selected: well(tk.tool_active, tk.text_strong), + normal: well(Color32::TRANSPARENT, tokens.text), + hovered: well(tokens.row_hover, tokens.text_strong), + pressed: Some(well(tokens.tool_active, tokens.text_strong)), + selected: well(tokens.tool_active, tokens.text_strong), corner_radius: CornerRadius::same(6), - focus_stroke: Stroke::new(1.0, tk.accent), + focus_stroke: Stroke::new(1.0, tokens.accent), }; + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); }) diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs new file mode 100644 index 00000000..fc5c295a --- /dev/null +++ b/crates/ui-egui/tests/toolbar.rs @@ -0,0 +1,171 @@ +//! Toolbar layout and input coverage + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, Tool}; +use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; + +fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let mut app = TextureCraftApp::new(&context, session); + app.session.tool.tool = tool; + app.session.tool.brush.lazy = 20.0; + let mut harness = + Harness::builder().with_size(egui::vec2(width, 200.0)).with_context_setup(theme::install).build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + harness.run_steps(4); + harness +} + +fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + _ => None, + }) + .unwrap() +} + +#[test] +fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { + let mut harness = toolbar_harness(700.0, Tool::Path); + for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { + harness.set_size(egui::vec2(width, 200.0)); + harness.run_steps(4); + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let (_, clip) = size_label(&harness); + assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); + assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); + assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); + assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + } +} + +#[test] +fn arrows_and_wheel_scroll_without_changing_the_brush() { + let mut harness = toolbar_harness(700.0, Tool::Path); + let brush = harness.state().session.tool.brush.clone(); + let start = size_label(&harness).0.x; + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + let scrolled = size_label(&harness).0.x; + assert!(scrolled < start - 50.0); + + harness.get_by_label("Scroll left").click(); + harness.run_steps(30); + assert!((size_label(&harness).0.x - start).abs() < 1.0); + + let (_, clip) = size_label(&harness); + harness.hover_at(clip.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(-100.0, 0.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(30); + assert!(size_label(&harness).0.x < start - 50.0); + assert_eq!(harness.state().session.tool.brush, brush); +} + +#[test] +fn shorter_tools_and_wider_windows_remove_the_arrows() { + let mut harness = toolbar_harness(700.0, Tool::Path); + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.state_mut().session.tool.fill_mode = texturecraft_engine::FillMode::Mesh; + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let triangle = harness.get_by_label("Triangle fill").rect(); + harness.get_by_label("Triangle fill").click(); + harness.run_steps(2); + assert!(harness.ctx.content_rect().contains_rect(triangle)); + assert_eq!(harness.state().session.tool.fill_mode, texturecraft_engine::FillMode::Triangle); + + harness.state_mut().session.tool.tool = Tool::Path; + harness.set_size(egui::vec2(1600.0, 200.0)); + harness.run_steps(4); + assert!(harness.query_by_label("Scroll right").is_none()); + let (position, clip) = size_label(&harness); + assert!(clip.contains(position)); +} + +#[test] +fn compact_view_buttons_can_be_scrolled_into_view_and_clicked() { + let mut harness = toolbar_harness(400.0, Tool::Path); + for _ in 0..20 { + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let visible = harness.query_by_label("UV checker").is_some_and(|node| node.rect().left() > left.right() && node.rect().right() < right.left()); + if visible { + harness.get_by_label("UV checker").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::UvChecker); + return; + } + + harness.get_by_label("Scroll right").click(); + harness.run_steps(30); + } + + panic!("the view buttons never became accessible"); +} + +#[test] +fn mode_buttons_keep_their_order_and_dispatch_commands() { + let mut harness = toolbar_harness(700.0, Tool::Paint); + for (label, mode) in [("Bake Mesh Maps (F8)", Mode::Baking), ("Rendering (path traced) (F10)", Mode::Rendering), ("Painting (F9)", Mode::Painting)] { + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let paint = harness.get_by_label("Painting (F9)").rect(); + let render = harness.get_by_label("Rendering (path traced) (F10)").rect(); + assert!(bake.right() < paint.left() && paint.right() < render.left()); + harness.get_by_label(label).click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.mode, mode); + } +} + +#[test] +#[ignore] +fn toolbar_frame_timing() { + for width in [1600.0, 1000.0, 400.0] { + let mut harness = toolbar_harness(width, Tool::Path); + harness.run_steps(100); + let mut timings = [0.0_f64; 5]; + for timing in &mut timings { + let start = std::time::Instant::now(); + harness.run_steps(1000); + *timing = start.elapsed().as_secs_f64() * 1000.0; + } + timings.sort_by(f64::total_cmp); + eprintln!("Path + lazy mouse, width {width}: {:.2} us/frame median, batches {timings:?}", timings[2]); + } +} + +#[test] +#[ignore] +fn toolbar_window_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { + return; + }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().session.tool.tool = Tool::Path; + harness.state_mut().session.tool.brush.lazy = 20.0; + for (width, scale) in [(1600.0, 1.0), (960.0, 1.0), (960.0, 1.5)] { + harness.set_size(egui::vec2(width, 960.0)); + harness.state_mut().ui.prefs.ui_scale = scale; + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("toolbar-{width}-{scale}.png"))).unwrap(); + } +} From 97880c7f05ef86e07e62a1c42106511b4bd25958 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:22:46 -0500 Subject: [PATCH 030/275] Derive standard control sizes from the active theme Use theme control heights for toolbar, path, asset, property, bake and browser export controls. Keep width calculations in sync with the rendered controls and verify narrow toolbars at three theme sizes. --- .../ui-egui/src/bake_mode/common_settings.rs | 22 ++++++--- crates/ui-egui/src/dock.rs | 40 ++++++++------- crates/ui-egui/src/shelf.rs | 15 ++++-- crates/ui-egui/src/toolbar.rs | 49 +++++++++++-------- crates/ui-egui/src/windows.rs | 15 +++--- crates/ui-egui/tests/toolbar.rs | 39 ++++++++++----- 6 files changed, 110 insertions(+), 70 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index d96fdc85..7680903b 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,6 +9,8 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; +const FILE_BUTTON_SIZE: f32 = 20.0; + pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { let is_enabled = settings.common.is_enabled; @@ -104,7 +106,8 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { ui.label(tr("Output Size")); ui.horizontal(|ui| { - let dropdown_width = ((ui.available_width() - 24.0 - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); + let button_size = ui.spacing().interact_size.y; + let dropdown_width = ((ui.available_width() - button_size - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { for resolution in BakeResolution::ALL { @@ -112,6 +115,7 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { } }); }; + resolution(ui, "output_width", &mut settings.resolution); let locked = settings.resolution_height.is_none(); let mut height = settings.resolution_height.unwrap_or(settings.resolution); @@ -119,7 +123,8 @@ fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { if !locked { settings.resolution_height = Some(height); } - if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, 24.0).clicked() { + + if icon_button(ui, if locked { icon::LOCK_SIMPLE } else { icon::LOCK_SIMPLE_OPEN }, tr("Lock Output Size"), locked, button_size).clicked() { settings.resolution_height = if locked { Some(settings.resolution) } else { None }; } }); @@ -131,12 +136,14 @@ fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { let mut remove = None; for (index, name) in meshes.iter().enumerate() { ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 24.0, 24.0], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, 20.0).clicked() { + let label_width = (ui.available_width() - FILE_BUTTON_SIZE - ui.spacing().item_spacing.x).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); + if icon_button(ui, icon::TRASH, tr("Remove"), false, FILE_BUTTON_SIZE).clicked() { remove = Some(index); } }); } + if meshes.is_empty() { hint(ui, tr("No High-Poly Meshes")); } @@ -152,11 +159,12 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr("Cage Scene")); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { - ui.add_sized([ui.available_width() - 52.0, 24.0], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, 20.0).clicked() { + let label_width = (ui.available_width() - 2.0 * (FILE_BUTTON_SIZE + ui.spacing().item_spacing.x)).max(0.0); + ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, FILE_BUTTON_SIZE).clicked() { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); } - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, 20.0).clicked() { + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, FILE_BUTTON_SIZE).clicked() { app.run("bake.cage.clear", json!({})); } }); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..4d5a1d06 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -990,38 +990,43 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - // Brush preview: a stroke and a sphere with the tool's material. + let tokens = Tokens::get(ui.ctx()); + // Brush preview: a stroke and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 88.0), Sense::hover()); - let p = ui.painter(); - p.rect_filled(rect, 2.0, tk.viewport); - let half = rect.width() * 0.5; - let b = &app.session.tool.brush; - let mut pts = Vec::new(); - for k in 0..=40 { - let t = k as f32 / 40.0; - pts.push(pos2(rect.left() + 14.0 + t * (half - 28.0), rect.center().y + (t * 9.0).sin() * 18.0)); + let painter = ui.painter(); + painter.rect_filled(rect, 2.0, tokens.viewport); + let half_width = rect.width() * 0.5; + let brush = &app.session.tool.brush; + let mut points = Vec::new(); + for step in 0..=40 { + let fraction = step as f32 / 40.0; + points.push(pos2(rect.left() + 14.0 + fraction * (half_width - 28.0), rect.center().y + (fraction * 9.0).sin() * 18.0)); } - let w = (b.size / 0.25 * 60.0).clamp(2.0, 30.0); - let a = (b.flow * b.opacity * 255.0) as u8; - p.add(egui::Shape::line(pts, Stroke::new(w, Color32::from_white_alpha(a.max(30))))); - let base = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); - crate::thumbs::paint_sphere(p, pos2(rect.left() + half * 1.5, rect.center().y), 36.0, base); + + let stroke_width = (brush.size / 0.25 * 60.0).clamp(2.0, 30.0); + let alpha = (brush.flow * brush.opacity * 255.0) as u8; + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(30))))); + let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([0.8; 3]); + crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), 36.0, base_color); ui.add_space(4.0); + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; for (tab, icon, tip) in [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, ic::SPHERE, tr("Material"))] { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, 24.0).clicked() { + if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { app.ui.props_tab = tab; } } }); ui.separator(); + if app.session.quick_mask.editing { - ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tk.text_dim)); + ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } + let tool_section: Option = match app.session.tool.tool { Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), @@ -1034,6 +1039,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } + match app.ui.props_tab { PropsTab::Brush => brush_section(app, ui), PropsTab::Alpha => alpha_section(app, ui), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index f2aaeb65..351219b9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -156,34 +156,39 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response } } -/// The Assets panel body (a dock tab). +/// The Assets panel body (a dock tab) pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); let mut tab = app.ui.shelf_tab.min(TABS.len() - 1); let searching = !app.ui.shelf_filter.is_empty(); + ui.horizontal_wrapped(|ui| { + let button_size = ui.spacing().interact_size.y; ui.spacing_mut().item_spacing = vec2(2.0, 2.0); for (i, (_, icon, label)) in TABS.iter().enumerate() { - if icon_button(ui, icon, tr(label), i == tab && !searching, 24.0).clicked() { + if icon_button(ui, icon, tr(label), i == tab && !searching, button_size).clicked() { tab = i; app.ui.shelf_filter.clear(); } } }); app.ui.shelf_tab = tab; + ui.horizontal(|ui| { - ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tk.text_dim)); + ui.label(RichText::new(ic::MAGNIFYING_GLASS).color(tokens.text_dim)); ui.add(egui::TextEdit::singleline(&mut app.ui.shelf_filter).hint_text(tr("Search all assets")).desired_width(f32::INFINITY)); }); ui.add_space(4.0); + let filter = app.ui.shelf_filter.to_lowercase(); egui::ScrollArea::vertical().id_salt("shelf_scroll").auto_shrink([false, false]).show(ui, |ui| { - // Searching shows matches from every tab, each under its tab's name. + // Searching shows matches from every tab, each under its tab's name for (i, (t, _, title)) in TABS.iter().enumerate() { if filter.is_empty() && i != tab { continue; } + let title = tr(title); match t { Tab::Materials => materials(app, ui, &ctx, &filter, false, title), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a075840d..b2e4d83e 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -13,7 +13,6 @@ use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; -const BAR_BUTTON_SIZE: f32 = 24.0; const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; const BAR_SEPARATOR_WIDTH: f32 = 6.0; @@ -38,11 +37,13 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { egui::Panel::top("paint_bar").exact_size(40.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { card(ui, &tokens, egui::Margin { bottom: GUTTER, ..Default::default() }, egui::Margin::symmetric(8, 0), |ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mode_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; + let button_size = ui.spacing().interact_size.y; + let mode_width = 3.0 * button_size + 2.0 * BAR_SPACING; let separator_width = BAR_SEPARATOR_WIDTH + 2.0 * BAR_SPACING; // Leave room for both scroll arrows and at least one button of content - let minimum_strip_width = 3.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SPACING; - let scroll_views = ui.available_width() < mode_width + view_buttons_width(BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; + let minimum_strip_width = 3.0 * button_size + 2.0 * BAR_SPACING; + let scroll_views = + ui.available_width() < mode_width + view_buttons_width(button_size, BAR_SPACING) + 2.0 * separator_width + minimum_strip_width; ui.spacing_mut().item_spacing.x = if scroll_views { COMPACT_BAR_SPACING } else { BAR_SPACING }; mode_buttons(app, ui); @@ -64,14 +65,15 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } -fn view_buttons_width(spacing: f32) -> f32 { +fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { // Five icons, two separators and the six gaps between them - 5.0 * BAR_BUTTON_SIZE + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing + 5.0 * button_size + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing } /// View buttons in a right-to-left layout, with the screenshot button at the end fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, BAR_BUTTON_SIZE).clicked() { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); } @@ -81,14 +83,14 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, button_size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { let mode = if checker { "material" } else { "uvChecker" }; app.run("viewport.view", json!({"mode": mode})); } @@ -96,6 +98,7 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Scroll tool controls and, in narrow viewports, the view buttons fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { + let button_size = ui.spacing().interact_size.y; let strip_width = ui.available_width(); let overflow_id = egui::Id::unique("tool_controls_overflow"); let overflowing = ui.data(|data| data.get_temp::(overflow_id)).unwrap_or(false); @@ -103,12 +106,12 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: // A positive delta moves the content right, revealing its start let arrow_scroll_step = strip_width / 2.0; let mut scroll_delta = 0.0; - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, BAR_BUTTON_SIZE).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_LEFT, "Scroll left", false, button_size).clicked() { scroll_delta = arrow_scroll_step; } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, BAR_BUTTON_SIZE).clicked() { + if overflowing && icon_button_without_tooltip(ui, ic::CARET_DOUBLE_RIGHT, "Scroll right", false, button_size).clicked() { scroll_delta = -arrow_scroll_step; } @@ -123,7 +126,7 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: tool_controls(app, ui, tokens); if scroll_views { ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - let size = vec2(view_buttons_width(ui.spacing().item_spacing.x), ui.available_height()); + let size = vec2(view_buttons_width(button_size, ui.spacing().item_spacing.x), ui.available_height()); ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| view_buttons(app, ui)); } }); @@ -147,6 +150,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; + let button_size = ui.spacing().interact_size.y; let tool = app.session.tool.tool; ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); @@ -175,7 +179,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) ui.separator(); let lazy_on = brush.lazy > 0.0; - if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, 24.0).clicked() { + if icon_button(ui, ic::SCRIBBLE, tr("Lazy mouse"), lazy_on, button_size).clicked() { brush.lazy = if lazy_on { 0.0 } else { DEFAULT_LAZY_DISTANCE_PX }; } if lazy_on { @@ -186,13 +190,13 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, 24.0).clicked() { + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, button_size).clicked() { brush.symmetry.x = !brush.symmetry.x; } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, 24.0).clicked() { + if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, button_size).clicked() { brush.symmetry.y = !brush.symmetry.y; } - if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, 24.0).clicked() { + if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { brush.particles.enabled = !brush.particles.enabled; } @@ -222,7 +226,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), ] { - if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, 24.0).clicked() { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { app.session.tool.fill_mode = fill_mode; } } @@ -238,27 +242,30 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) /// Bake, Painting and Rendering mode buttons for a right-to-left layout, so Rendering is added first fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; for (mode, icon, label, command) in [ (Mode::Rendering, ic::APERTURE, tr("Rendering (path traced)"), "ui.mode.render"), (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, BAR_BUTTON_SIZE).clicked() { + if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size).clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } } -/// Path tool options and actions (top bar and properties). +/// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let button_size = ui.spacing().interact_size.y; let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, 24.0).clicked() { + if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { path.closed = !path.closed; } let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, 24.0).clicked() { + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { path.fill = !path.fill; } + let has_points = !path.points.is_empty(); if ui .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c8bd72c5..3672ad45 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -615,8 +615,7 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.settings = open; } -/// Browser File › Export Mesh: pick the download format (the desktop picks it in the save -/// dialog). +/// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { let formats = [ @@ -627,18 +626,20 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export_mesh { return; } + let mut open = true; let mut picked = None; dialog("export_mesh", tr("Export mesh"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Download as"))); - for (ext, label, hint) in formats { - if ui.add_sized(vec2(220.0, 24.0), egui::Button::new(label)).on_hover_text(hint).clicked() { - picked = Some(ext); + for (extension, label, hint) in formats { + if ui.add_sized(vec2(220.0, ui.spacing().interact_size.y), egui::Button::new(label)).on_hover_text(hint).clicked() { + picked = Some(extension); } } }); - if let Some(ext) = picked { - crate::web_files::export_mesh(app, ext); + + if let Some(extension) = picked { + crate::web_files::export_mesh(app, extension); open = false; } app.ui.windows.export_mesh = open; diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs index fc5c295a..76b0053d 100644 --- a/crates/ui-egui/tests/toolbar.rs +++ b/crates/ui-egui/tests/toolbar.rs @@ -12,8 +12,13 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> let mut app = TextureCraftApp::new(&context, session); app.session.tool.tool = tool; app.session.tool.brush.lazy = 20.0; - let mut harness = - Harness::builder().with_size(egui::vec2(width, 200.0)).with_context_setup(theme::install).build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); + let mut harness = Harness::builder() + .with_size(egui::vec2(width, 200.0)) + .with_context_setup(|context| { + theme::install(context); + theme::apply(context, theme::Brightness::default(), theme::Accent::default()); + }) + .build_ui_state(|ui, app| toolbar::paint_bar(app, ui), app); harness.run_steps(4); harness } @@ -33,17 +38,25 @@ fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect #[test] fn narrow_toolbars_keep_scroll_arrows_and_mode_buttons_separate() { let mut harness = toolbar_harness(700.0, Tool::Path); - for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { - harness.set_size(egui::vec2(width, 200.0)); - harness.run_steps(4); - let left = harness.get_by_label("Scroll left").rect(); - let right = harness.get_by_label("Scroll right").rect(); - let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); - let (_, clip) = size_label(&harness); - assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); - assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); - assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); - assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + for button_size in [20.0, 24.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + for width in [500.0, 450.0, 400.0, 350.0, 240.0, 200.0] { + let width = width * button_size / 24.0; + harness.set_size(egui::vec2(width, 200.0)); + harness.run_steps(4); + let left = harness.get_by_label("Scroll left").rect(); + let right = harness.get_by_label("Scroll right").rect(); + let bake = harness.get_by_label("Bake Mesh Maps (F8)").rect(); + let (_, clip) = size_label(&harness); + for button in [left, right, bake] { + assert_eq!(button.size(), egui::Vec2::splat(button_size)); + } + + assert!(left.right() <= right.left(), "arrows overlap at width {width}: {left:?}, {right:?}"); + assert!(right.right() < bake.left(), "scrolling overlaps the mode buttons at width {width}"); + assert!(clip.left() >= left.right() && clip.right() <= right.left(), "content covers an arrow at width {width}: {clip:?}"); + assert!(harness.ctx.content_rect().contains_rect(left) && harness.ctx.content_rect().contains_rect(bake)); + } } } From 6b31b9e376b519c18fabad32efec2cbc98d26b8b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 4 Nov 2026 21:49:36 -0500 Subject: [PATCH 031/275] Derive bake file button sizes from the active UI Use the UI control height for high-poly and cage file buttons and their row-width reservations. Cover smaller and larger control sizes in the bake UI regression test. --- crates/ui-egui/src/bake_mode/common_settings.rs | 14 +++++++------- crates/ui-egui/tests/bake_mode.rs | 10 ++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 7680903b..d6710290 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,8 +9,6 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -const FILE_BUTTON_SIZE: f32 = 20.0; - pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { let is_enabled = settings.common.is_enabled; @@ -136,9 +134,10 @@ fn high_poly_files(app: &mut TextureCraftApp, ui: &mut Ui) { let mut remove = None; for (index, name) in meshes.iter().enumerate() { ui.horizontal(|ui| { - let label_width = (ui.available_width() - FILE_BUTTON_SIZE - ui.spacing().item_spacing.x).max(0.0); + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(name).truncate()).on_hover_text(name); - if icon_button(ui, icon::TRASH, tr("Remove"), false, FILE_BUTTON_SIZE).clicked() { + if icon_button(ui, icon::TRASH, tr("Remove"), false, button_size).clicked() { remove = Some(index); } }); @@ -159,12 +158,13 @@ fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr("Cage Scene")); let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); ui.horizontal(|ui| { - let label_width = (ui.available_width() - 2.0 * (FILE_BUTTON_SIZE + ui.spacing().item_spacing.x)).max(0.0); + let button_size = ui.spacing().interact_size.y; + let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, FILE_BUTTON_SIZE).clicked() { + if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); } - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, FILE_BUTTON_SIZE).clicked() { + if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { app.run("bake.cage.clear", json!({})); } }); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 409966c6..acd1135c 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -106,14 +106,24 @@ fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { harness.run_steps(3); assert!(harness.query_by_label("Cage Type").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); + harness.state_mut().session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); harness.run_steps(3); harness.get_by_label("Max Frontal Distance"); harness.get_by_label("Skew Correction"); + click(&mut harness, "Cage Type"); click(&mut harness, "Custom File"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::CustomFile); harness.get_by_label("Cage Scene"); assert!(harness.query_by_label("Max Frontal Distance").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); + + for button_size in [20.0, 28.0] { + harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); + harness.run_steps(3); + for label in ["Remove", "Load Cage"] { + assert_eq!(harness.get_by_label(label).rect().size(), egui::Vec2::splat(button_size)); + } + } } From e26f196888dcc181fccfe3b45808c13bdb1f4097 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:34 +0400 Subject: [PATCH 032/275] Camera bookmarks: Ctrl+1..9 shortcuts, smooth glide in the UI, docs Saved cameras (Project.cameras) already act as bookmarks; add camera.bookmark1..9 commands, a short viewport glide when going to a camera from the UI, a test and a control-protocol section. --- crates/engine/src/camera_cmds.rs | 36 ++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 48 +++++++++++++++++++++++++++++++- docs/control-protocol.md | 9 ++++++ 3 files changed, 92 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index af94815c..9c44c06e 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -28,6 +28,15 @@ pub fn specs() -> Vec { ), cmd!("camera.remove", "Remove camera", [], None, "{index? | name?}", has_cameras, remove), cmd!("camera.rename", "Rename camera", [], None, "{index? | name?, to}", has_cameras, rename), + cmd!("camera.bookmark1", "Go to camera 1", ["Viewport"], Some("Ctrl+1"), "{}", always, |s, _| bookmark(s, 0)), + cmd!("camera.bookmark2", "Go to camera 2", ["Viewport"], Some("Ctrl+2"), "{}", always, |s, _| bookmark(s, 1)), + cmd!("camera.bookmark3", "Go to camera 3", ["Viewport"], Some("Ctrl+3"), "{}", always, |s, _| bookmark(s, 2)), + cmd!("camera.bookmark4", "Go to camera 4", ["Viewport"], Some("Ctrl+4"), "{}", always, |s, _| bookmark(s, 3)), + cmd!("camera.bookmark5", "Go to camera 5", ["Viewport"], Some("Ctrl+5"), "{}", always, |s, _| bookmark(s, 4)), + cmd!("camera.bookmark6", "Go to camera 6", ["Viewport"], Some("Ctrl+6"), "{}", always, |s, _| bookmark(s, 5)), + cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)), + cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)), + cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -132,6 +141,14 @@ fn select(s: &mut Session, p: &Value) -> Result { Ok(crate::view_cmds::camera_json(s)) } +/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order. +fn bookmark(s: &mut Session, slot: usize) -> Result { + if slot >= s.doc.project.cameras.len() { + return Err(bad("camera.bookmark", "no saved camera in that slot (see camera.list)")); + } + select(s, &json!({ "index": slot })) +} + fn remove(s: &mut Session, p: &Value) -> Result { let i = which(s, "camera.remove", p)?; s.edit("Remove camera", |s| { @@ -202,6 +219,25 @@ mod tests { assert_eq!(s.doc.project.cameras.len(), 2, "removing is undoable"); } + #[test] + fn number_shortcuts_go_to_the_first_nine_cameras() { + let mut s = session(); + assert!(execute(&mut s, "camera.bookmark1", &Value::Null).is_err(), "no cameras yet"); + execute(&mut s, "camera.set", &json!({"yaw": 30})).unwrap(); + let first = s.camera; + execute(&mut s, "camera.add", &json!({"name": "A"})).unwrap(); + execute(&mut s, "camera.orbit", &json!({"dx": 50})).unwrap(); + execute(&mut s, "camera.add", &json!({"name": "B"})).unwrap(); + execute(&mut s, "camera.bookmark1", &Value::Null).unwrap(); + assert_eq!(s.camera, first); + execute(&mut s, "camera.bookmark2", &Value::Null).unwrap(); + assert_eq!(execute(&mut s, "camera.list", &Value::Null).unwrap()["current"], 1); + assert!(execute(&mut s, "camera.bookmark3", &Value::Null).is_err(), "empty slot"); + let ids: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.bookmark")).collect(); + assert_eq!(ids.len(), 9); + assert!(ids.iter().all(|c| c.shortcut.is_some())); + } + #[test] fn cameras_round_trip_through_the_project_file() { let mut s = session(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..c6112eb3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -75,6 +75,8 @@ pub struct Toast { pub struct TextureCraftApp { pub session: Session, + /// A smooth move to a saved camera in progress. + camera_glide: Option, pub ui: UiState, pub gpu: Option, pub control: Option>, @@ -135,6 +137,7 @@ impl TextureCraftApp { }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; let mut app = TextureCraftApp { + camera_glide: None, session, ui, gpu, @@ -183,8 +186,16 @@ impl TextureCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { + // Going to a saved camera glides there; the control channel and CLI jump straight away. + let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { - Ok(v) => Some(v), + Ok(v) => { + if let Some(from) = glide_from.filter(|f| *f != self.session.camera) { + self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); + self.session.camera = from; + } + Some(v) + } Err(e) => { self.toast(e.to_string(), true); None @@ -418,6 +429,40 @@ impl TextureCraftApp { } } +/// A smooth move of the viewport camera (see [`TextureCraftApp::run`]). +struct CameraGlide { + from: texturecraft_engine::geom::OrbitCamera, + to: texturecraft_engine::geom::OrbitCamera, + start: f64, +} + +const GLIDE_SECONDS: f64 = 0.35; + +impl TextureCraftApp { + /// Advance the camera glide by one frame. + fn step_camera_glide(&mut self, ctx: &egui::Context) { + let Some(g) = &self.camera_glide else { return }; + let t = ((self.last_time - g.start) / GLIDE_SECONDS).clamp(0.0, 1.0) as f32; + let e = t * t * (3.0 - 2.0 * t); + let (a, b) = (g.from, g.to); + let mix = |x: f32, y: f32| x + (y - x) * e; + let mut c = b; + c.target = a.target.lerp(b.target, e); + c.yaw = mix(a.yaw, b.yaw); + c.pitch = mix(a.pitch, b.pitch); + c.distance = mix(a.distance, b.distance); + c.fov = mix(a.fov, b.fov); + // Orthographic switches at the end (the projections cannot be blended). + c.ortho = if t >= 1.0 { b.ortho } else { a.ortho }; + self.session.camera = c; + self.session.revision = self.session.revision.wrapping_add(1); + if t >= 1.0 { + self.camera_glide = None; + } + ctx.request_repaint(); + } +} + impl eframe::App for TextureCraftApp { /// The browser never tells eframe the page is closing, so save often there. fn auto_save_interval(&self) -> std::time::Duration { @@ -442,6 +487,7 @@ impl eframe::App for TextureCraftApp { theme::apply(ctx, style.0, style.1); self.styled = Some(style); } + self.step_camera_glide(ctx); control::poll(self, ctx); web_files::poll(self); let dropped = ctx.input(|i| i.raw.dropped_files.clone()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..74322c74 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -223,6 +223,15 @@ printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","para '{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve ``` +## Camera bookmarks + +Saved cameras (`Project.cameras`, stored in the `.tcraft` file) are the camera bookmarks. +`camera.add {name?}` saves the current view, `camera.list` lists them (`current` is the one the view +is at), `camera.select {index? | name?}` restores one, `camera.rename {index? | name?, to}` and +`camera.remove {index? | name?}` edit them. `camera.bookmark1` … `camera.bookmark9` (Ctrl+1 … Ctrl+9) +go to the first nine. Commands jump straight to the view; the desktop UI glides there over about a third +of a second. + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is From 3f3bf357f3c107b4ac7fa4ce093ad4d4d0088848 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:42:54 +0400 Subject: [PATCH 033/275] Camera bookmarks: translate the Go to camera commands --- crates/ui-egui/src/i18n/ar.rs | 9 +++++++++ crates/ui-egui/src/i18n/de.rs | 9 +++++++++ crates/ui-egui/src/i18n/es.rs | 9 +++++++++ crates/ui-egui/src/i18n/fr.rs | 9 +++++++++ crates/ui-egui/src/i18n/it.rs | 9 +++++++++ crates/ui-egui/src/i18n/ja.rs | 9 +++++++++ crates/ui-egui/src/i18n/ko.rs | 9 +++++++++ crates/ui-egui/src/i18n/pt_br.rs | 9 +++++++++ crates/ui-egui/src/i18n/zh_hans.rs | 9 +++++++++ 9 files changed, 81 insertions(+) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..543ce315 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "مدمج: {mesh}"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), + ("Go to camera 1", "الانتقال إلى الكاميرا 1"), + ("Go to camera 2", "الانتقال إلى الكاميرا 2"), + ("Go to camera 3", "الانتقال إلى الكاميرا 3"), + ("Go to camera 4", "الانتقال إلى الكاميرا 4"), + ("Go to camera 5", "الانتقال إلى الكاميرا 5"), + ("Go to camera 6", "الانتقال إلى الكاميرا 6"), + ("Go to camera 7", "الانتقال إلى الكاميرا 7"), + ("Go to camera 8", "الانتقال إلى الكاميرا 8"), + ("Go to camera 9", "الانتقال إلى الكاميرا 9"), ("Camera settings", "إعدادات الكاميرا"), ("Cancel", "إلغاء"), ("Cancel the stroke", "إلغاء ضربة الفرشاة"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..ff21513c 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integriert: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), + ("Go to camera 1", "Zu Kamera 1 wechseln"), + ("Go to camera 2", "Zu Kamera 2 wechseln"), + ("Go to camera 3", "Zu Kamera 3 wechseln"), + ("Go to camera 4", "Zu Kamera 4 wechseln"), + ("Go to camera 5", "Zu Kamera 5 wechseln"), + ("Go to camera 6", "Zu Kamera 6 wechseln"), + ("Go to camera 7", "Zu Kamera 7 wechseln"), + ("Go to camera 8", "Zu Kamera 8 wechseln"), + ("Go to camera 9", "Zu Kamera 9 wechseln"), ("Camera settings", "Kameraeinstellungen"), ("Cancel", "Abbrechen"), ("Cancel the stroke", "Strich abbrechen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..512953cc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrada: {mesh}"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), + ("Go to camera 1", "Ir a la cámara 1"), + ("Go to camera 2", "Ir a la cámara 2"), + ("Go to camera 3", "Ir a la cámara 3"), + ("Go to camera 4", "Ir a la cámara 4"), + ("Go to camera 5", "Ir a la cámara 5"), + ("Go to camera 6", "Ir a la cámara 6"), + ("Go to camera 7", "Ir a la cámara 7"), + ("Go to camera 8", "Ir a la cámara 8"), + ("Go to camera 9", "Ir a la cámara 9"), ("Camera settings", "Ajustes de cámara"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar el trazo"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..9921d701 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -149,6 +149,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Intégré : {mesh}"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), + ("Go to camera 1", "Aller à la caméra 1"), + ("Go to camera 2", "Aller à la caméra 2"), + ("Go to camera 3", "Aller à la caméra 3"), + ("Go to camera 4", "Aller à la caméra 4"), + ("Go to camera 5", "Aller à la caméra 5"), + ("Go to camera 6", "Aller à la caméra 6"), + ("Go to camera 7", "Aller à la caméra 7"), + ("Go to camera 8", "Aller à la caméra 8"), + ("Go to camera 9", "Aller à la caméra 9"), ("Camera settings", "Paramètres de la caméra"), ("Cancel", "Annuler"), ("Cancel the stroke", "Annuler le trait"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..0516b8ac 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -146,6 +146,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrata: {mesh}"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), + ("Go to camera 1", "Vai alla camera 1"), + ("Go to camera 2", "Vai alla camera 2"), + ("Go to camera 3", "Vai alla camera 3"), + ("Go to camera 4", "Vai alla camera 4"), + ("Go to camera 5", "Vai alla camera 5"), + ("Go to camera 6", "Vai alla camera 6"), + ("Go to camera 7", "Vai alla camera 7"), + ("Go to camera 8", "Vai alla camera 8"), + ("Go to camera 9", "Vai alla camera 9"), ("Camera settings", "Impostazioni camera"), ("Cancel", "Annulla"), ("Cancel the stroke", "Annulla il tratto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..09e69594 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -149,6 +149,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "組み込み: {mesh}"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), + ("Go to camera 1", "カメラ 1 に移動"), + ("Go to camera 2", "カメラ 2 に移動"), + ("Go to camera 3", "カメラ 3 に移動"), + ("Go to camera 4", "カメラ 4 に移動"), + ("Go to camera 5", "カメラ 5 に移動"), + ("Go to camera 6", "カメラ 6 に移動"), + ("Go to camera 7", "カメラ 7 に移動"), + ("Go to camera 8", "カメラ 8 に移動"), + ("Go to camera 9", "カメラ 9 に移動"), ("Camera settings", "カメラ設定"), ("Cancel", "キャンセル"), ("Cancel the stroke", "ストロークをキャンセル"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..165a8584 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -143,6 +143,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "기본 제공: {mesh}"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), + ("Go to camera 1", "카메라 1 보기"), + ("Go to camera 2", "카메라 2 보기"), + ("Go to camera 3", "카메라 3 보기"), + ("Go to camera 4", "카메라 4 보기"), + ("Go to camera 5", "카메라 5 보기"), + ("Go to camera 6", "카메라 6 보기"), + ("Go to camera 7", "카메라 7 보기"), + ("Go to camera 8", "카메라 8 보기"), + ("Go to camera 9", "카메라 9 보기"), ("Camera settings", "카메라 설정"), ("Cancel", "취소"), ("Cancel the stroke", "스트로크 취소"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..1a058da9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -146,6 +146,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Embutida: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), + ("Go to camera 1", "Ir para a câmera 1"), + ("Go to camera 2", "Ir para a câmera 2"), + ("Go to camera 3", "Ir para a câmera 3"), + ("Go to camera 4", "Ir para a câmera 4"), + ("Go to camera 5", "Ir para a câmera 5"), + ("Go to camera 6", "Ir para a câmera 6"), + ("Go to camera 7", "Ir para a câmera 7"), + ("Go to camera 8", "Ir para a câmera 8"), + ("Go to camera 9", "Ir para a câmera 9"), ("Camera settings", "Configurações da câmera"), ("Cancel", "Cancelar"), ("Cancel the stroke", "Cancelar o traço"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..e86ef6ef 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -125,6 +125,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "内置:{mesh}"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), + ("Go to camera 1", "转到相机 1"), + ("Go to camera 2", "转到相机 2"), + ("Go to camera 3", "转到相机 3"), + ("Go to camera 4", "转到相机 4"), + ("Go to camera 5", "转到相机 5"), + ("Go to camera 6", "转到相机 6"), + ("Go to camera 7", "转到相机 7"), + ("Go to camera 8", "转到相机 8"), + ("Go to camera 9", "转到相机 9"), ("Camera settings", "相机设置"), ("Cancel", "取消"), ("Cancel the stroke", "取消笔画"), From d4ea67703de986eb907138148751d9561ed84f7b Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 034/275] Add an asynchronous thumbnail service for layer contents, masks and effect stages The compositor renders a one-layer cut of the stack at 64 px (content in a channel, mask, or the stack up to an effect); the engine keeps an immutable snapshot, a worker thread, an LRU cache and stale-result rejection. --- crates/compose/src/lib.rs | 2 + crates/compose/src/thumb.rs | 155 +++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/thumbs.rs | 396 ++++++++++++++++++++++++++++++++++ crates/engine/tests/thumbs.rs | 294 +++++++++++++++++++++++++ 5 files changed, 848 insertions(+) create mode 100644 crates/compose/src/thumb.rs create mode 100644 crates/engine/src/thumbs.rs create mode 100644 crates/engine/tests/thumbs.rs diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..a72c0922 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -12,6 +12,7 @@ pub mod display; pub mod eval; pub mod pattern; pub mod store; +pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; @@ -20,3 +21,4 @@ pub use eval::{ mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; +pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs new file mode 100644 index 00000000..a5a817e0 --- /dev/null +++ b/crates/compose/src/thumb.rs @@ -0,0 +1,155 @@ +//! Small previews of one layer's content, one mask, or one effect stage, computed without +//! touching the main composite. +//! +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: the texture +//! set's stack is replaced by the one layer, the layer is forced visible at Normal / 100 %, and +//! the layer's effect list is truncated after the effect being previewed. The evaluator is the +//! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with +//! what the stack really computes. Nothing here mutates the caller's project. + +use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; +use texturecraft_texel::linear_to_srgb; + +use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; + +/// Edge length (texels) the thumbnails are computed at. +pub const THUMB_TEXELS: u32 = 64; + +/// What a thumbnail shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ThumbTarget { + /// The content of a layer (content effects included, mask ignored) in `channel`. + Content { layer: LayerId, channel: Channel }, + /// The mask of a layer (an instance without its own mask shows its source's). + Mask { layer: LayerId }, + /// The result up to and including `effect`, in the layer's content (`channel`) or in its + /// mask (the channel is ignored). An effect that is hidden shows the bypassed result. + Stage { effect: LayerId, channel: Channel }, +} + +/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view +/// paints its own background there) and 255 elsewhere. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ThumbImage { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// The thumbnail of `target`, computed at `inp.gbuf`'s size, which must be square (use a +/// [`THUMB_TEXELS`] G-buffer; None otherwise). None for an unknown layer or effect, a layer without that channel, or a +/// mask that does not exist. +pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { + if inp.gbuf.width != inp.gbuf.height { + return None; + } + match target { + ThumbTarget::Content { layer, channel } => content(inp, layer, channel, None), + ThumbTarget::Mask { layer } => mask(inp, layer, None), + ThumbTarget::Stage { effect, channel } => { + let (owner, _) = inp.project.effect(effect)?; + let in_mask = inp.project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect)); + if in_mask { mask(inp, owner, Some(effect)) } else { content(inp, owner, channel, Some(effect)) } + } + } +} + +/// `project` cut down to the single layer `id` of texture set `ts`: only that layer is drawn, +/// visible, Normal at full opacity in `channel` (when given). +fn solo(project: &Project, ts: usize, id: LayerId, channel: Option) -> Option { + let mut cut = project.clone(); + cut.texture_sets.get_mut(ts)?.stack = vec![id]; + let l = cut.layers.get_mut(&id)?; + l.visible = true; + if let Some(c) = channel { + *l.channels.get_mut(&c)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + Some(cut) +} + +/// Keep the effects of `list` up to and including `last`. +fn truncate_after(list: &mut Vec, last: LayerId) -> bool { + match list.iter().position(|e| e.id == last) { + Some(k) => { + list.truncate(k + 1); + true + } + None => false, + } +} + +fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option) -> Option { + let set = inp.project.texture_set(inp.ts).ok()?; + if !set.channel_list().contains(&channel) { + return None; + } + // The layer whose content is drawn: an instance draws its source's effects. + let mut cut = solo(inp.project, inp.ts, layer, Some(channel))?; + let owner = cut.content_layer(layer)?.id; + for id in [layer, owner] { + let l = cut.layers.get_mut(&id)?; + l.mask = None; + l.visible = true; + if let Some(b) = l.channels.get_mut(&channel) { + *b = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + } + if let Some(effect) = upto + && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let mut comp = Composite::with_size(&set.channel_list(), w, h); + composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); + Some(encode_channel(&comp, channel, inp)) +} + +fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { + let mut cut = solo(inp.project, inp.ts, layer, None)?; + let owner = cut.mask_owner(layer); + let m = cut.layers.get_mut(&owner)?.mask.as_mut()?; + m.enabled = true; + if let Some(effect) = upto + && !truncate_after(&mut m.effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let gray = mask_image(&cut_inp, layer, w)?; + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let i = (y * w + x) as usize; + let g = gray.get(i).copied().unwrap_or(0); + rgba.extend_from_slice(&[g, g, g, if inp.gbuf.covered(i) { 255 } else { 0 }]); + } + } + Some(ThumbImage { width: w, height: h, rgba }) +} + +/// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid +/// gray, normal maps and scalars as stored (data channels raw). +fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImage { + let (w, h) = (comp.resolution, comp.height); + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + }; + let covered = inp.gbuf.covered((y * w + x) as usize); + rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); + } + } + ThumbImage { width: w, height: h, rgba } +} + +fn to_byte(v: f32) -> u8 { + if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 } else { 0 } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..20aa19f9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -44,6 +44,7 @@ pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; +pub mod thumbs; pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs new file mode 100644 index 00000000..6ee7dda4 --- /dev/null +++ b/crates/engine/src/thumbs.rs @@ -0,0 +1,396 @@ +//! Asynchronous layer-panel thumbnails. +//! +//! The panel asks for small previews of layer contents, masks and effect stages +//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite: +//! +//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the +//! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer. +//! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds +//! (a slider drag renders at that pace, not once per frame). +//! * A **worker thread** evaluates one target at a time from a snapshot with +//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per +//! [`ThumbService::poll`] instead. +//! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an +//! older snapshot than the current one is dropped, so a slow job can never overwrite a newer +//! thumbnail. An entry that is out of date keeps showing until its replacement arrives. +//! * Only targets requested during the current frame are rendered: a row that scrolled away +//! before its turn is dropped from the queue. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb}; +use texturecraft_core::Project; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer}; + +use crate::Session; + +/// Thumbnails kept. +pub const CACHE_ENTRIES: usize = 96; +/// Seconds between checks for a changed document while it keeps changing. +pub const DEBOUNCE: f64 = 0.12; +/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped). +const IN_FLIGHT: usize = 2; + +/// An immutable copy of everything the thumbnails of one texture set read. +pub struct ThumbSnapshot { + ts: usize, + mesh_id: u64, + project: Project, + pixels: PixelStore, + baked: BakedMaps, + images: ImageStore, + mesh: Arc, + gbuf: Arc, + bounds: (Vec3, Vec3), +} + +impl ThumbSnapshot { + /// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss). + pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option { + let material = s.doc.project.texture_set(ts).ok()?.material; + let gbuf = gbufs.get(&s.mesh, s.mesh_id, material); + Some(ThumbSnapshot { + ts, + mesh_id: s.mesh_id, + project: s.doc.project.clone(), + pixels: s.doc.pixels.clone(), + baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: s.images.clone(), + mesh: s.mesh.clone(), + gbuf, + bounds: s.mesh.bounds(), + }) + } + + /// Whether `s` would give the same thumbnails as this snapshot. + fn matches(&self, s: &Session, ts: usize) -> bool { + let same_pixels = self.pixels.layers.len() == s.doc.pixels.layers.len() + && self.pixels.masks.len() == s.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(k, v)| s.doc.pixels.layers.get(k) == Some(v)) + && self.pixels.masks.iter().all(|(k, v)| s.doc.pixels.masks.get(k) == Some(v)); + let none = BakedMaps::default(); + let baked = s.doc.baked.get(&ts).unwrap_or(&none); + self.ts == ts + && self.mesh_id == s.mesh_id + && self.project == s.doc.project + && same_pixels + && self.baked == *baked + && self.images.len() == s.images.len() + && self.images.iter().all(|(k, v)| s.images.get(k).is_some_and(|o| Arc::ptr_eq(o, v))) + } + + /// Render `target`: the work of one job. + pub fn render(&self, target: ThumbTarget) -> Option { + let inp = Inputs { + project: &self.project, + ts: self.ts, + mesh: &self.mesh, + gbuf: &self.gbuf, + pixels: &self.pixels, + baked: &self.baked, + preview: None, + images: &self.images, + bounds: self.bounds, + }; + thumb::render(&inp, target) + } + + /// Whether the layer or effect `target` shows still exists in the snapshot's project. + fn has(&self, target: ThumbTarget) -> bool { + has_target(&self.project, target) + } +} + +fn has_target(p: &Project, target: ThumbTarget) -> bool { + match target { + ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer), + ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(), + } +} + +/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a +/// snapshot that is not just copying handles). +#[derive(Default)] +pub struct GbufCache { + map: HashMap<(u64, usize), Arc>, +} + +impl GbufCache { + fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc { + if self.map.len() > 16 { + self.map.clear(); + } + self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone() + } +} + +struct Entry { + /// None: the target has nothing to show (a layer without that channel). + image: Option>, + /// Snapshot generation it was rendered from. + generation: u64, + /// Changes whenever `image` does (views key their GPU textures on it). + version: u64, + used: u64, +} + +/// What the panel draws for one target. +#[derive(Clone)] +pub struct ThumbView { + pub image: Option>, + /// Identifies `image`; changes when a new picture arrives. + pub version: u64, + /// A newer picture is on its way. + pub pending: bool, +} + +struct Job { + snapshot: Arc, + generation: u64, + target: ThumbTarget, +} + +struct Done { + generation: u64, + target: ThumbTarget, + image: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct Worker { + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn_worker() -> Option { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("layer-thumbs".into()) + .spawn(move || { + while let Ok(job) = jobs.recv() { + let image = job.snapshot.render(job.target); + if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() { + break; + } + } + }) + .ok()?; + Some(Worker { tx, rx }) +} + +/// The thumbnail cache and its worker. One lives in the UI; see the module documentation. +pub struct ThumbService { + snapshot: Option>, + /// Bumps whenever the snapshot's content changes; entries and jobs carry it. + generation: u64, + /// The session revision the snapshot was last compared with. + seen: Option, + last_check: f64, + cache: HashMap, + tick: u64, + versions: u64, + queue: VecDeque, + in_flight: HashSet, + wanted: HashSet, + gbufs: GbufCache, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, + #[cfg(not(target_arch = "wasm32"))] + spawned: bool, + /// Jobs run inline (wasm32, or no worker thread could start). + inline: VecDeque, + /// Pictures computed (tests, benchmarks). + pub rendered: u64, +} + +impl Default for ThumbService { + fn default() -> Self { + ThumbService { + snapshot: None, + generation: 0, + seen: None, + last_check: f64::NEG_INFINITY, + cache: HashMap::new(), + tick: 0, + versions: 0, + queue: VecDeque::new(), + in_flight: HashSet::new(), + wanted: HashSet::new(), + gbufs: GbufCache::default(), + #[cfg(not(target_arch = "wasm32"))] + worker: None, + #[cfg(not(target_arch = "wasm32"))] + spawned: false, + inline: VecDeque::new(), + rendered: 0, + } + } +} + +impl ThumbService { + pub fn new() -> ThumbService { + ThumbService::default() + } + + /// Start of a frame: forget what the last frame asked for and notice document changes. + pub fn begin_frame(&mut self, s: &Session, now: f64) { + self.wanted.clear(); + let ts = s.ts(); + if self.seen == Some(s.revision) && self.snapshot.as_ref().is_some_and(|sn| sn.ts == ts && sn.mesh_id == s.mesh_id) { + return; + } + // While the document keeps changing, compare at the debounce pace (the first look is immediate). + if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { + return; + } + self.last_check = now; + if self.snapshot.as_ref().is_some_and(|sn| sn.matches(s, ts)) { + self.seen = Some(s.revision); + return; + } + self.snapshot = ThumbSnapshot::new(s, ts, &mut self.gbufs).map(Arc::new); + self.seen = Some(s.revision); + self.generation += 1; + // Jobs of the old snapshot are not worth running (those in flight are dropped on arrival). + self.queue.clear(); + self.inline.clear(); + self.in_flight.clear(); + if let Some(sn) = &self.snapshot { + self.cache.retain(|t, _| sn.has(*t)); + } else { + self.cache.clear(); + } + } + + /// Whether the displayed pictures wait for a document comparison that is still debounced. + fn checked(&self, s: &Session) -> bool { + self.seen == Some(s.revision) + } + + /// The picture for `target` (call for the rows on screen only). Queues work when the + /// picture is missing or out of date. + pub fn get(&mut self, s: &Session, target: ThumbTarget) -> ThumbView { + self.wanted.insert(target); + self.tick += 1; + let fresh = self.cache.get(&target).is_some_and(|e| e.generation == self.generation); + let checked = self.checked(s); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&target) && !self.queue.contains(&target) { + self.queue.push_back(target); + } + let tick = self.tick; + match self.cache.get_mut(&target) { + Some(e) => { + e.used = tick; + ThumbView { image: e.image.clone(), version: e.version, pending: !(fresh && checked) } + } + None => ThumbView { image: None, version: 0, pending: true }, + } + } + + /// End of a frame: take finished pictures, drop queued rows nobody asked for, hand the worker + /// its next jobs. Returns whether more work is outstanding (ask for another frame). + pub fn poll(&mut self, s: &Session) -> bool { + self.collect(); + let wanted = &self.wanted; + self.queue.retain(|t| wanted.contains(t)); + self.dispatch(); + self.trim(); + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() || !self.checked(s) + } + + fn dispatch(&mut self) { + let Some(snapshot) = self.snapshot.clone() else { return }; + while self.in_flight.len() + self.inline.len() < IN_FLIGHT { + let Some(target) = self.queue.pop_front() else { break }; + let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; + self.in_flight.insert(target); + if !self.send(job) { + break; + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn send(&mut self, job: Job) -> bool { + if !self.spawned { + self.spawned = true; + self.worker = spawn_worker(); + } + match &self.worker { + Some(w) => match w.tx.send(job) { + Ok(()) => true, + Err(e) => { + // The worker is gone: run this and the rest here. + self.worker = None; + self.inline.push_back(e.0); + true + } + }, + None => { + self.inline.push_back(job); + true + } + } + } + + #[cfg(target_arch = "wasm32")] + fn send(&mut self, job: Job) -> bool { + self.inline.push_back(job); + true + } + + fn collect(&mut self) { + let mut done: Vec = Vec::new(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = &self.worker { + while let Ok(d) = w.rx.try_recv() { + done.push(d); + } + } + // Without a thread one job runs per frame, so the interface keeps its pace. + if let Some(job) = self.inline.pop_front() { + let image = job.snapshot.render(job.target); + done.push(Done { generation: job.generation, target: job.target, image }); + } + for d in done { + self.rendered += 1; + // A picture of an older snapshot never replaces a newer one. + if d.generation != self.generation { + continue; + } + self.in_flight.remove(&d.target); + if !self.snapshot.as_ref().is_some_and(|sn| sn.has(d.target)) { + continue; + } + self.versions += 1; + let entry = Entry { image: d.image.map(Arc::new), generation: d.generation, version: self.versions, used: self.tick }; + self.cache.insert(d.target, entry); + } + } + + fn trim(&mut self) { + while self.cache.len() > CACHE_ENTRIES { + let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break }; + self.cache.remove(&oldest); + } + } + + /// Entries held (tests). + pub fn cached(&self) -> usize { + self.cache.len() + } + + /// Whether `target` has a picture of the current snapshot (tests). + pub fn is_fresh(&self, target: ThumbTarget) -> bool { + self.cache.get(&target).is_some_and(|e| e.generation == self.generation) + } + + /// Whether any work is queued or running (tests). + pub fn busy(&self) -> bool { + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() + } +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs new file mode 100644 index 00000000..05fb52ba --- /dev/null +++ b/crates/engine/tests/thumbs.rs @@ -0,0 +1,294 @@ +//! Layer-panel thumbnails: they equal a plain CPU evaluation of the same sub-stack at 64 px, +//! follow edits, drop stale and vanished work, and only render what was asked for. + +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; +use texturecraft_engine::geom::UvGBuffer; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; +use texturecraft_engine::{Session, execute}; + +const N: u32 = 64; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 256).unwrap() +} + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +/// A fill layer with two content effects (invert, then posterize) and a masked generator. +struct Stack { + layer: LayerId, + invert: LayerId, + posterize: LayerId, + gen_: LayerId, +} + +fn stack(s: &mut Session) -> Stack { + let layer = id(execute(s, "layer.add.fill", &json!({"color": "#336699", "roughness": 0.2})).unwrap(), "layer"); + let invert = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let posterize = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "posterize"})).unwrap(), "effect"); + execute(s, "mask.add.black", &Value::Null).unwrap(); + let gen_ = id(execute(s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + Stack { layer, invert, posterize, gen_ } +} + +fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { + let none = Default::default(); + // Leaked: the oracle only lives for the test. + let baked: &'a _ = Box::leak(Box::new(s.doc.baked.get(&0).cloned().unwrap_or(none))); + Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } +} + +/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary +/// evaluator, then encoded for display. +fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { + let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); + let mut p = s.doc.project.clone(); + let (layer, upto, channel) = match target { + ThumbTarget::Content { layer, channel } => (layer, None, channel), + ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), + ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), + }; + p.texture_sets[0].stack = vec![layer]; + let l = p.layers.get_mut(&layer).unwrap(); + l.visible = true; + let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); + if in_mask { + let m = l.mask.as_mut().unwrap(); + m.enabled = true; + if let Some(e) = upto { + let k = m.effects.iter().position(|x| x.id == e).unwrap(); + m.effects.truncate(k + 1); + } + let gray = mask_image(&inputs(s, &p, &gbuf), layer, N).unwrap(); + let rgba = gray.iter().enumerate().flat_map(|(i, g)| [*g, *g, *g, if gbuf.covered(i) { 255 } else { 0 }]).collect(); + return ThumbImage { width: N, height: N, rgba }; + } + l.mask = None; + l.channels.insert(channel, texturecraft_engine::core::ChannelBlend::default()); + if let Some(e) = upto { + let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); + l.content_effects.truncate(k + 1); + } + let channels = p.texture_set(0).unwrap().channel_list(); + let mut comp = Composite::new(&channels, N); + composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut rgba = Vec::new(); + for y in 0..N { + for x in 0..N { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), + _ => v.map(byte), + }; + rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + } + } + ThumbImage { width: N, height: N, rgba } +} + +/// Frames of `svc` until every target is current (or a timeout). +fn settle(svc: &mut ThumbService, s: &Session, targets: &[ThumbTarget], clock: &mut f64) { + let t0 = Instant::now(); + loop { + *clock += 0.2; + svc.begin_frame(s, *clock); + for t in targets { + svc.get(s, *t); + } + svc.poll(s); + if targets.iter().all(|t| svc.is_fresh(*t)) { + return; + } + assert!(t0.elapsed() < Duration::from_secs(60), "thumbnails never settled"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { + (*svc.get(s, t).image.expect("a picture")).clone() +} + +#[test] +fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let targets = [ + ThumbTarget::Content { layer: st.layer, channel: base }, + ThumbTarget::Content { layer: st.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: st.layer }, + ThumbTarget::Stage { effect: st.invert, channel: base }, + ThumbTarget::Stage { effect: st.posterize, channel: base }, + ThumbTarget::Stage { effect: st.gen_, channel: base }, + ]; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &targets, &mut clock); + for t in targets { + assert_eq!(image(&mut svc, &s, t), oracle(&s, t), "{t:?}"); + } + // Sanity on the values themselves: the first stage is #336699 inverted (in linear light). + let inv = image(&mut svc, &s, targets[3]); + let px = inv.rgba.chunks_exact(4).find(|p| p[3] == 255).unwrap(); + let expect = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((px[0] as i32 - expect(51.0)).abs() <= 1 && (px[2] as i32 - expect(153.0)).abs() <= 1, "{px:?}"); + // The mask thumbnail is gray and not flat (a position gradient on a black mask). + let m = image(&mut svc, &s, targets[2]); + let grays: Vec = m.rgba.chunks_exact(4).filter(|p| p[3] == 255).map(|p| p[0]).collect(); + assert!(grays.iter().max() != grays.iter().min()); +} + +#[test] +fn earlier_stages_never_show_later_effects_and_hidden_effects_are_bypassed() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let (first, second) = (ThumbTarget::Stage { effect: st.invert, channel: base }, ThumbTarget::Stage { effect: st.posterize, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[first, second], &mut clock); + let (a, b) = (image(&mut svc, &s, first), image(&mut svc, &s, second)); + // Hide the second effect: its stage now shows the first one's result; the first is unchanged. + execute(&mut s, "effect.set", &json!({"effect": st.posterize.0, "visible": false})).unwrap(); + settle(&mut svc, &s, &[first, second], &mut clock); + assert_eq!(image(&mut svc, &s, first), a); + assert_eq!(image(&mut svc, &s, second), a); + assert_ne!(a, b, "posterize should change something for the test to mean anything"); + // And the content thumbnail (everything) follows. + let all = ThumbTarget::Content { layer: st.layer, channel: base }; + settle(&mut svc, &s, &[all], &mut clock); + assert_eq!(image(&mut svc, &s, all), a); +} + +#[test] +fn editing_invalidates_and_unrelated_changes_do_not() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[t], &mut clock); + let before = image(&mut svc, &s, t); + let rendered = svc.rendered; + // A camera move changes the session revision but no thumbnail input: nothing is re-rendered. + execute(&mut s, "camera.set", &json!({"yaw": 0.7})).ok(); + s.revision += 1; + for _ in 0..3 { + clock += 0.3; + svc.begin_frame(&s, clock); + svc.get(&s, t); + svc.poll(&s); + } + assert!(svc.is_fresh(t)); + assert_eq!(svc.rendered, rendered, "an unrelated change re-rendered a thumbnail"); + // An edit of the layer re-renders it, and the new picture is the new oracle. + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + clock += 0.3; + svc.begin_frame(&s, clock); + assert!(!svc.is_fresh(t)); + settle(&mut svc, &s, &[t], &mut clock); + let after = image(&mut svc, &s, t); + assert_ne!(before, after); + assert_eq!(after, oracle(&s, t)); + // Undo brings the first picture back. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + settle(&mut svc, &s, &[t], &mut clock); + assert_eq!(image(&mut svc, &s, t), before); +} + +#[test] +fn deleting_a_layer_with_a_pending_thumbnail_is_harmless() { + let mut s = session(); + let st = stack(&mut s); + let (a, b) = (ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }, ThumbTarget::Mask { layer: st.layer }); + let mut svc = ThumbService::new(); + // Queue the work and hand it to the worker, then delete the layer before collecting. + svc.begin_frame(&s, 1.0); + svc.get(&s, a); + svc.get(&s, b); + svc.poll(&s); + execute(&mut s, "layer.remove", &json!({"layer": st.layer.0})).unwrap(); + let mut clock = 2.0; + for _ in 0..200 { + clock += 0.2; + svc.begin_frame(&s, clock); + // The row is gone, so nobody asks for it any more; the pending result is dropped. + svc.poll(&s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!svc.is_fresh(a) && !svc.is_fresh(b)); + assert_eq!(svc.cached(), 0); + assert!(!svc.busy()); + // Asking for a layer that no longer exists renders nothing and does not panic either. + settle_gone(&mut svc, &s, a, &mut clock); +} + +fn settle_gone(svc: &mut ThumbService, s: &Session, t: ThumbTarget, clock: &mut f64) { + for _ in 0..20 { + *clock += 0.2; + svc.begin_frame(s, *clock); + svc.get(s, t); + svc.poll(s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(svc.get(s, t).image.is_none()); +} + +#[test] +fn a_result_of_an_older_document_never_replaces_a_newer_one() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + svc.begin_frame(&s, 1.0); + svc.get(&s, t); + svc.poll(&s); // the job of the first document is running + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + let mut clock = 2.0; + settle(&mut svc, &s, &[t], &mut clock); + // Whatever the first job returned, what is shown is the current document. + assert_eq!(image(&mut svc, &s, t), oracle(&s, t)); +} + +#[test] +fn only_requested_rows_render_and_the_cache_is_bounded() { + let mut s = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |l: LayerId| ThumbTarget::Content { layer: l, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + // A frame asks for six rows, the next frame (scrolled) for only one of them. + svc.begin_frame(&s, 1.0); + for l in &layers[..6] { + svc.get(&s, target(*l)); + } + svc.poll(&s); + let mut clock = 2.0; + for _ in 0..300 { + clock += 0.2; + svc.begin_frame(&s, clock); + svc.get(&s, target(layers[0])); + svc.poll(&s); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(svc.is_fresh(target(layers[0]))); + // At most the rows already on their way (the in-flight limit) finished besides it. + let done = layers[..6].iter().filter(|l| svc.is_fresh(target(**l))).count(); + assert!(done <= 3, "{done} of the scrolled-away rows were rendered"); + // Scrolling through every layer keeps the cache within its limit. + for chunk in layers.chunks(12) { + let ts: Vec = chunk.iter().map(|l| target(*l)).collect(); + settle(&mut svc, &s, &ts, &mut clock); + assert!(svc.cached() <= CACHE_ENTRIES + 12, "{}", svc.cached()); + } + clock += 0.2; + svc.begin_frame(&s, clock); + svc.poll(&s); + assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); +} From 11d889dbf57c0ffb8e775a9086610e964b1d91a7 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 035/275] Redesign the Layers panel rows with live thumbnails Layer rows are 48 points tall with alternating shades, hover, an accent edge on the selected row and a divider under each layer. Each row shows its content thumbnail (the layer's own result in the displayed channel) and its mask thumbnail, each selectable on its own; a subtitle names the layer type and effect count; blend mode and opacity stack on the right. Effects hang under their layer on tree lines in "Content effects" and "Mask effects" groups that fold without touching the document, each with a thumbnail of the stack up to and including it (a hidden effect shows what it bypasses, struck through). Folder contents indent with lines. Paint and fill thumbnails show their own coverage over a checkerboard; folders composite their children. Every size derives from layer_panel::layer_preview_size, so a preview size setting plugs in there. New strings are translated in every shipped language. --- crates/compose/src/thumb.rs | 61 ++++- crates/engine/tests/perf.rs | 47 ++++ crates/engine/tests/thumbs.rs | 47 +++- crates/ui-egui/src/dock.rs | 326 ++++++++++++++++++++------- crates/ui-egui/src/i18n/ar.rs | 8 + crates/ui-egui/src/i18n/de.rs | 8 + crates/ui-egui/src/i18n/es.rs | 8 + crates/ui-egui/src/i18n/fr.rs | 8 + crates/ui-egui/src/i18n/it.rs | 8 + crates/ui-egui/src/i18n/ja.rs | 8 + crates/ui-egui/src/i18n/ko.rs | 8 + crates/ui-egui/src/i18n/pt_br.rs | 8 + crates/ui-egui/src/i18n/zh_hans.rs | 8 + crates/ui-egui/src/layer_panel.rs | 87 +++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/layers_panel.rs | 96 ++++++++ crates/ui-egui/tests/ui_snapshots.rs | 35 ++- docs/architecture.md | 20 ++ 18 files changed, 693 insertions(+), 102 deletions(-) create mode 100644 crates/ui-egui/src/layer_panel.rs create mode 100644 crates/ui-egui/tests/layers_panel.rs diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index a5a817e0..6a246d79 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -8,9 +8,9 @@ //! what the stack really computes. Nothing here mutates the caller's project. use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; -use texturecraft_texel::linear_to_srgb; +use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; -use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, composite_tiles, flatten_layer, mask_image}; /// Edge length (texels) the thumbnails are computed at. pub const THUMB_TEXELS: u32 = 64; @@ -27,8 +27,9 @@ pub enum ThumbTarget { Stage { effect: LayerId, channel: Channel }, } -/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view -/// paints its own background there) and 255 elsewhere. +/// An 8-bit RGBA thumbnail (straight alpha). Alpha is 0 where the mesh does not cover the +/// texture and, for a paint or fill layer's content, where the layer has nothing; the view +/// paints its own background there. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ThumbImage { pub width: u32, @@ -101,11 +102,57 @@ fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option } let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; let (w, h) = (inp.gbuf.width, inp.gbuf.height); + // A paint or fill layer shows its own coverage (transparent where nothing is painted); a + // folder shows its children composited over the channel's default. + if !cut.layers.get(&owner)?.is_group() { + let flat = flatten_layer(&cut_inp, layer, &all_tiles(w, h))?; + return Some(encode_flat(&flat, channel, w, h)); + } let mut comp = Composite::with_size(&set.channel_list(), w, h); composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); Some(encode_channel(&comp, channel, inp)) } +/// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. +fn encode_flat(flat: &[FlatTile], channel: Channel, w: u32, h: u32) -> ThumbImage { + let mut rgba = vec![0u8; (w * h) as usize * 4]; + let comps = channel.components(); + let signed = channel.kind() == ChannelKind::Signed; + for (c, (tx, ty), buf) in flat { + if *c != channel { + continue; + } + for (o, px) in buf.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE); + let a = px.get(comps).map_or(0.0, |v| from_u16(*v)); + if x >= w || y >= h || a <= 0.0 { + continue; + } + let mut v = [0.0f32; 3]; + for (k, slot) in v.iter_mut().enumerate() { + let raw = px.get(k.min(comps - 1)).copied().unwrap_or(0); + *slot = if signed { from_u16_signed(raw) } else { from_u16(raw) } / a; + } + let p = display(channel, v); + let i = ((y * w + x) * 4) as usize; + if let Some(d) = rgba.get_mut(i..i + 4) { + d.copy_from_slice(&[p[0], p[1], p[2], to_byte(a)]); + } + } + } + ThumbImage { width: w, height: h, rgba } +} + +/// A channel value as display bytes: colors linear → sRGB, signed values with 0 at mid gray, +/// normal maps and scalars as stored. +fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { + match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + } +} + fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { let mut cut = solo(inp.project, inp.ts, layer, None)?; let owner = cut.mask_owner(layer); @@ -138,11 +185,7 @@ fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImag for y in 0..h { for x in 0..w { let v = comp.value(channel, x, y); - let px = match channel.kind() { - ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), - ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), - ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), - }; + let px = display(channel, v); let covered = inp.gbuf.covered((y * w + x) as usize); rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); } diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index eeee7662..e4691b6a 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -350,3 +350,50 @@ fn bench_8k_resize() { println!("[resize] dilation {:.2?}", t.elapsed()); drop(d); } + +/// Layer-panel thumbnails on the 4K stack: the snapshot, each kind of picture, and a whole panel. +#[test] +#[ignore] +fn bench_layer_thumbs_4k() { + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::core::Channel; + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + let s = stack(4096); + let ts = s.ts(); + let mut gbufs = GbufCache::default(); + let t = Instant::now(); + let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let first = t.elapsed(); + let t = Instant::now(); + let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let cached = t.elapsed(); + let p = &s.doc.project; + let mut targets = Vec::new(); + for l in p.layers.values() { + targets.push(("content", ThumbTarget::Content { layer: l.id, channel: Channel::BaseColor })); + if l.mask.is_some() { + targets.push(("mask", ThumbTarget::Mask { layer: l.id })); + } + for e in l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()) { + targets.push(("stage", ThumbTarget::Stage { effect: e.id, channel: Channel::BaseColor })); + } + } + let mut per: std::collections::BTreeMap<&str, (Duration, usize, Duration)> = Default::default(); + let all = Instant::now(); + for (kind, target) in &targets { + let t = Instant::now(); + let _ = snap.render(*target); + let d = t.elapsed(); + let e = per.entry(kind).or_default(); + e.0 += d; + e.1 += 1; + e.2 = e.2.max(d); + } + let total = all.elapsed(); + eprintln!("layer thumbnails, 4096 set, {} layers, 64 px:", p.layers.len()); + eprintln!(" snapshot: {:.2} ms first (with the 64 px G-buffer), {:.2} ms after", first.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3); + for (kind, (sum, n, max)) in per { + eprintln!(" {kind:8} {n:3} × avg {:.2} ms, max {:.2} ms", sum.as_secs_f64() * 1e3 / n as f64, max.as_secs_f64() * 1e3); + } + eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs index 05fb52ba..ff164cee 100644 --- a/crates/engine/tests/thumbs.rs +++ b/crates/engine/tests/thumbs.rs @@ -4,11 +4,11 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; -use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::compose::{Inputs, ThumbImage, ThumbTarget, all_tiles, flatten_layer, mask_image}; use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; use texturecraft_engine::geom::UvGBuffer; use texturecraft_engine::geom::primitives; -use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::texel::{from_u16, from_u16_signed, linear_to_srgb}; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use texturecraft_engine::{Session, execute}; @@ -46,8 +46,8 @@ fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, g Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } } -/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary -/// evaluator, then encoded for display. +/// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU +/// evaluator (the mask with `mask_image`, the content with `flatten_layer`), then encoded. fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); let mut p = s.doc.project.clone(); @@ -77,20 +77,27 @@ fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); l.content_effects.truncate(k + 1); } - let channels = p.texture_set(0).unwrap().channel_list(); - let mut comp = Composite::new(&channels, N); - composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + // A paint or fill layer: its own (premultiplied value, coverage), coverage as alpha. + let flat = flatten_layer(&inputs(s, &p, &gbuf), layer, &all_tiles(N, N)).unwrap(); let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let mut rgba = Vec::new(); - for y in 0..N { - for x in 0..N { - let v = comp.value(channel, x, y); + let mut rgba = vec![0u8; (N * N * 4) as usize]; + let comps = channel.components(); + for (_, _, buf) in flat.iter().filter(|(c, _, _)| *c == channel) { + for (i, px) in buf.chunks_exact(comps + 1).enumerate() { + let a = from_u16(px[comps]); + if a <= 0.0 { + continue; + } + let v: [f32; 3] = std::array::from_fn(|k| { + let raw = px[k.min(comps - 1)]; + (if channel.kind() == ChannelKind::Signed { from_u16_signed(raw) } else { from_u16(raw) }) / a + }); let px = match channel.kind() { ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), _ => v.map(byte), }; - rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + rgba[i * 4..i * 4 + 4].copy_from_slice(&[px[0], px[1], px[2], byte(a)]); } } ThumbImage { width: N, height: N, rgba } @@ -292,3 +299,19 @@ fn only_requested_rows_render_and_the_cache_is_bounded() { svc.poll(&s); assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); } + +#[test] +fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { + let mut s = session(); + let paint = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let base = Channel::BaseColor; + let (p, f) = (ThumbTarget::Content { layer: paint, channel: base }, ThumbTarget::Content { layer: folder, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[p, f], &mut clock); + assert!(image(&mut svc, &s, p).rgba.chunks_exact(4).all(|px| px[3] == 0), "nothing painted: nothing shown"); + let folder_img = image(&mut svc, &s, f); + let px = folder_img.rgba.chunks_exact(4).find(|px| px[3] == 255).unwrap(); + assert!((px[0] as i32 - 51).abs() <= 1 && (px[2] as i32 - 153).abs() <= 1, "{px:?}"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..23b73dcb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -4,6 +4,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Source, @@ -14,6 +15,7 @@ use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; +use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; @@ -168,9 +170,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|i| i.time); + app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { + let mut count = 0; for id in stack { - layer_tree(app, ui, id, 0); + layer_tree(app, ui, id, 0, &mut count); } // Click on empty space deselects nothing; the space below the rows drops at the bottom. let free = ui.available_height(); @@ -195,6 +200,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); } }); + app.layer_panel.end(ui.ctx(), &app.session); } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -252,49 +258,108 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } -fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { +/// Layer rows alternate between two shades so neighbours read as separate items. +fn row_shade(tk: &Tokens, index: usize) -> Color32 { + if index.is_multiple_of(2) { tk.row } else { tk.row.lerp_to_gamma(tk.row_hover, 0.45) } +} + +/// Width of the blend mode / opacity column at the right of a layer row. +const RIGHT_COLUMN: f32 = 58.0; +/// Indent per folder level, and per level of the effect tree. +const INDENT: f32 = 14.0; +/// Height of the "Content effects" / "Mask effects" header rows. +const GROUP_HEADER_H: f32 = 20.0; + +/// X of the centre of the eye column at indent `level` in a row spanning from `left`. +fn level_x(left: f32, level: usize) -> f32 { + left + 7.0 + level as f32 * INDENT + 8.0 +} + +fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; - layer_row(app, ui, &layer, depth); - for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); + let index = *count; + *count += 1; + layer_row(app, ui, &layer, depth, index); + let mask_effects = layer.mask.as_ref().map_or(0, |m| m.effects.len()); + if !layer.content_effects.is_empty() { + effect_group(app, ui, &layer, depth, false, mask_effects > 0); } - if let Some(m) = &layer.mask { - for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); - } + if mask_effects > 0 { + effect_group(app, ui, &layer, depth, true, false); } + // A line under the layer and its effects separates it from the next layer. + let tk = Tokens::get(ui.ctx()); + let r = ui.available_rect_before_wrap(); + ui.painter().hline(r.x_range(), r.top() - 0.5, Stroke::new(1.0, tk.separator)); if let LayerKind::Group { children, collapsed } = &layer.kind && !collapsed && depth < 12 { for c in children.iter().rev() { - layer_tree(app, ui, *c, depth + 1); + layer_tree(app, ui, *c, depth + 1, count); } } } -fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize) { +/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet. +fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool { + let tk = Tokens::get(ui.ctx()); + let p = ui.painter(); + p.rect_filled(rect, 2.0, tk.field); + // A checkerboard shows through where the layer has nothing (transparent texels). + let cells = 4; + let cell = rect.width() / cells as f32; + let check = tk.field.lerp_to_gamma(tk.row_hover, 0.6); + for y in 0..cells { + for x in (0..cells).filter(|x| (x + y) % 2 == 0) { + p.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)), 0.0, check); + } + } + // Only rows on screen ask for a picture. + if ui.is_rect_visible(rect) + && let Some(tex) = app.layer_panel.texture(ui.ctx(), &app.session, target) + { + let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE }; + ui.painter().image(tex, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + return true; + } + false +} + +fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { let tk = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); - let h = 38.0; + let content_target = selected && targets_content(app); + let size = layer_preview_size(app); + let h = layer_row_height(size); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); let p = ui.painter().clone(); - let bg = if selected && app.session.target == StackTarget::Content { + let bg = if selected { tk.row_selected } else if resp.hovered() { tk.row_hover } else { - tk.row + row_shade(&tk, index) }; - p.rect_filled(rect.shrink2(vec2(0.0, 1.0)), 2.0, bg); + p.rect_filled(rect, 0.0, bg); + // Folder contents hang off lines down the left. + let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + for level in 0..depth { + let x = level_x(rect.left(), level); + p.vline(x, rect.y_range(), line); + } + if depth > 0 { + let x = level_x(rect.left(), depth - 1); + p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + } if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); } if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(0.0, 1.0), vec2(3.0, h - 2.0)), 0.0, *tag); + p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + depth as f32 * INDENT; // Eye. let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); @@ -327,29 +392,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x += 14.0; } - // Thumbnail. - let thumb = Rect::from_min_size(pos2(x, rect.top() + 5.0), vec2(28.0, 28.0)); - p.rect_filled(thumb, 2.0, tk.field); - match &layer.kind { - LayerKind::Fill(f) => { - let c = match f.source(Channel::BaseColor) { - Source::Uniform(v) => v, - Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], - Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], - }; - crate::thumbs::paint_sphere(&p, thumb.center(), 12.0, c); - } - LayerKind::Paint => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(15.0), tk.text); - } - LayerKind::Group { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(16.0), tk.text); - } - LayerKind::Instance { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(16.0), tk.accent); - } + // Content thumbnail: the layer's own result in the displayed channel. + let ch = app.ui.layer_channel; + let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); + if !drawn { + content_glyph(&p, &tk, thumb, layer); } - x = thumb.right() + 8.0; + p.rect_stroke( + thumb, + 2.0, + Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), + egui::StrokeKind::Outside, + ); + let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_resp.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); + } + x = thumb.right() + 4.0; // An instance draws its source's content, blending and (unless it has its own) mask. let project = &app.session.doc.project; let source = layer.instance_source().map(|src| { @@ -357,26 +417,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) }); let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(app.ui.layer_channel)); - // Mask thumbnail. - let right_w = 46.0; - let mask_rect = Rect::from_min_size(pos2(rect.right() - right_w - 30.0, rect.top() + 7.0), vec2(24.0, 24.0)); + let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); + // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask_rect; if let Some(m) = &mask { let mask_sel = selected && !targets_content(app); - p.rect_filled( - mask_rect, - 1.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); + if !drawn { + p.rect_filled( + mask_rect, + 2.0, + if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, + ); + if !m.effects.is_empty() { + p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + } + } p.rect_stroke( mask_rect, - 1.0, + 2.0, Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), egui::StrokeKind::Outside, ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(11.0), tk.text_dim); - } if !m.enabled { p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); } @@ -392,19 +455,25 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); } + x = mask_rect.right() + 8.0; } else { // The empty slot adds a mask to this layer. + mask_rect = Rect::from_center_size(pos2(x + 9.0, rect.center().y), vec2(18.0, 18.0)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); if slot.hovered() { p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); + x = mask_rect.right() + 8.0; } - // Name (or rename editor). - let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); + // Blend mode and opacity of the displayed channel, stacked at the right. + let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); + let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); + // Name (or rename editor) with the quieter subtitle under it. + let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2((blend_rect.left() - 4.0).max(x + 20.0), rect.bottom() - 4.0)); let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); if renaming { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); @@ -428,20 +497,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } } else { - let galley = elided(&p, layer.name.clone(), 12.0, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - let y = if source.is_some() { rect.center().y - 7.0 } else { rect.center().y }; - p.galley(pos2(name_rect.left(), y - galley.size().y * 0.5), galley, tk.text); - if let Some(src) = source { - let src = elided(&p, format!("{} {src}", ic::LINK_SIMPLE), 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 7.0 - src.size().y * 0.5), src, tk.text_dim); - } + let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let kind = tr(match &layer.kind { + LayerKind::Paint => "Paint layer", + LayerKind::Fill(_) => "Fill layer", + LayerKind::Group { .. } => "Folder", + LayerKind::Instance { .. } => "Instance", + }); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let subtitle = match (source, effects) { + (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (None, 0) => kind.to_string(), + (None, 1) => format!("{kind} · {}", tr("1 effect")), + (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + }; + let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); } - // Blend mode and opacity of the displayed channel. - let ch = app.ui.layer_channel; - let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0)); if let Some(b) = blend { let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); + if br.hovered() { + p.rect_filled(blend_rect, 2.0, tk.row_hover); + } p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); egui::Popup::menu(&br).show(|ui| { @@ -466,7 +544,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize child.spacing_mut().interact_size.y = op_rect.height(); child.spacing_mut().button_padding = vec2(4.0, 0.0); child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0)); + let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); if r.changed() { app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); } @@ -474,10 +552,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); } // Interaction: select, rename, drag & drop, context menu. - if resp.clicked() && !eye_resp.clicked() && !renaming { + let on_control = eye_resp.clicked() || content_resp.clicked(); + if resp.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !eye_resp.clicked() && !renaming { + if resp.double_clicked() && !on_control && !renaming { app.ui.rename = Some((layer.id.0, layer.name.clone())); } if resp.drag_started() && !renaming { @@ -523,20 +602,94 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } +/// What a content thumbnail shows until its picture arrives (or where the layer has none). +fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { + match &layer.kind { + LayerKind::Fill(f) => { + let c = match f.source(Channel::BaseColor) { + Source::Uniform(v) => v, + Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], + Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], + }; + crate::thumbs::paint_sphere(p, thumb.center(), thumb.width() * 0.34, c); + } + LayerKind::Paint => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(thumb.width() * 0.45), tk.text_dim); + } + LayerKind::Group { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(thumb.width() * 0.5), tk.text); + } + LayerKind::Instance { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(thumb.width() * 0.45), tk.accent); + } + } +} + +/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows +/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on. +fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) { + let tk = Tokens::get(ui.ctx()); + let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |m| &m.effects) } else { &layer.content_effects }; + let key = (layer.id.0, mask); + let folded = app.layer_panel.folded.contains(&key); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); + let label = if mask { tr("Mask effects") } else { tr("Content effects") }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let p = ui.painter().clone(); + p.rect_filled(rect, 0.0, if resp.hovered() { tk.row_hover } else { tk.panel }); + tree_lines(&p, &tk, rect, depth + 1, &[], more_below); + let x = level_x(rect.left(), depth + 1); + p.text( + pos2(x, rect.center().y), + egui::Align2::CENTER_CENTER, + if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, + egui::FontId::proportional(10.0), + tk.text_dim, + ); + p.text(pos2(x + 10.0, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(10.5), tk.text_dim); + p.text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, stack.len().to_string(), egui::FontId::proportional(10.0), tk.text_dim); + if resp.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { + app.layer_panel.folded.insert(key); + } + if folded { + return; + } + let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; + for (i, e) in stack.iter().rev().enumerate() { + effect_row(app, ui, layer, stack, e, depth + 2, &trunks, i + 1 == stack.len(), mask); + } +} + +/// Tree connector of a row at indent `level`: a line down from the parent's column (to the middle +/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with +/// lines straight through for the `trunks` of ancestors that continue. +fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, level: usize, trunks: &[usize], more: bool) { + let stroke = Stroke::new(1.0, tk.button_border); + for t in trunks { + p.vline(level_x(rect.left(), *t), rect.y_range(), stroke); + } + let x = level_x(rect.left(), level.saturating_sub(1)); + let end = if more { rect.bottom() } else { rect.center().y }; + p.vline(x, rect.top()..=end, stroke); + p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke); +} + /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { +/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +#[allow(clippy::too_many_arguments)] +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { let tk = Tokens::get(ui.ctx()); let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + let size = effect_preview_size(layer_preview_size(app)); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( - rect.shrink2(vec2(0.0, 1.0)), - 2.0, + rect, + 0.0, if selected { tk.row_selected } else if resp.hovered() { @@ -545,15 +698,28 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef tk.panel }, ); + tree_lines(&p, &tk, rect, level, trunks, !last); if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + level as f32 * INDENT; let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); + // The stack as it is up to and including this effect; a hidden one shows what it bypasses. + let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); + let ch = app.ui.layer_channel; + if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; + p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + } + p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + if !visible { + p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + } + let name_x = thumb.right() + 8.0; + let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); + p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..5e8c266f 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1041,4 +1041,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Select the layer content", "تحديد محتوى الطبقة"), + ("Paint layer", "طبقة رسم"), + ("Fill layer", "طبقة تعبئة"), + ("1 effect", "تأثير واحد"), + ("{count} effects", "{count} تأثيرات"), + ("Mask effects", "تأثيرات القناع"), + ("Content effects", "تأثيرات المحتوى"), + ("Fold or unfold these effects", "طيّ هذه التأثيرات أو فردها"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..30693118 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1090,4 +1090,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Select the layer content", "Ebeneninhalt auswählen"), + ("Paint layer", "Malebene"), + ("Fill layer", "Füllebene"), + ("1 effect", "1 Effekt"), + ("{count} effects", "{count} Effekte"), + ("Mask effects", "Maskeneffekte"), + ("Content effects", "Inhaltseffekte"), + ("Fold or unfold these effects", "Diese Effekte ein- oder ausklappen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..bc8ace33 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1075,4 +1075,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Select the layer content", "Seleccionar el contenido de la capa"), + ("Paint layer", "Capa de pintura"), + ("Fill layer", "Capa de relleno"), + ("1 effect", "1 efecto"), + ("{count} effects", "{count} efectos"), + ("Mask effects", "Efectos de la máscara"), + ("Content effects", "Efectos del contenido"), + ("Fold or unfold these effects", "Plegar o desplegar estos efectos"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..336621e9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1099,4 +1099,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Select the layer content", "Sélectionner le contenu du calque"), + ("Paint layer", "Calque de peinture"), + ("Fill layer", "Calque de remplissage"), + ("1 effect", "1 effet"), + ("{count} effects", "{count} effets"), + ("Mask effects", "Effets du masque"), + ("Content effects", "Effets du contenu"), + ("Fold or unfold these effects", "Replier ou déplier ces effets"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..8f92b26c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1084,4 +1084,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Select the layer content", "Seleziona il contenuto del livello"), + ("Paint layer", "Livello di pittura"), + ("Fill layer", "Livello di riempimento"), + ("1 effect", "1 effetto"), + ("{count} effects", "{count} effetti"), + ("Mask effects", "Effetti della maschera"), + ("Content effects", "Effetti del contenuto"), + ("Fold or unfold these effects", "Comprimi o espandi questi effetti"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..52166e4a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1069,4 +1069,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Select the layer content", "レイヤーの内容を選択"), + ("Paint layer", "ペイントレイヤー"), + ("Fill layer", "塗りつぶしレイヤー"), + ("1 effect", "エフェクト 1 件"), + ("{count} effects", "エフェクト {count} 件"), + ("Mask effects", "マスクのエフェクト"), + ("Content effects", "コンテンツのエフェクト"), + ("Fold or unfold these effects", "これらのエフェクトを折りたたむ/展開する"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..18bf30a6 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1054,4 +1054,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Select the layer content", "레이어 내용 선택"), + ("Paint layer", "페인트 레이어"), + ("Fill layer", "채우기 레이어"), + ("1 effect", "효과 1개"), + ("{count} effects", "효과 {count}개"), + ("Mask effects", "마스크 효과"), + ("Content effects", "콘텐츠 효과"), + ("Fold or unfold these effects", "이 효과들 접기/펼치기"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..17d7cc2e 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1072,4 +1072,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Select the layer content", "Selecionar o conteúdo da camada"), + ("Paint layer", "Camada de pintura"), + ("Fill layer", "Camada de preenchimento"), + ("1 effect", "1 efeito"), + ("{count} effects", "{count} efeitos"), + ("Mask effects", "Efeitos da máscara"), + ("Content effects", "Efeitos do conteúdo"), + ("Fold or unfold these effects", "Recolher ou expandir estes efeitos"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..4bb8705e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1000,4 +1000,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Select the layer content", "选择图层内容"), + ("Paint layer", "绘画图层"), + ("Fill layer", "填充图层"), + ("1 effect", "1 个效果"), + ("{count} effects", "{count} 个效果"), + ("Mask effects", "蒙版效果"), + ("Content effects", "内容效果"), + ("Fold or unfold these effects", "折叠或展开这些效果"), ]; diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs new file mode 100644 index 00000000..a29fa288 --- /dev/null +++ b/crates/ui-egui/src/layer_panel.rs @@ -0,0 +1,87 @@ +//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures, +//! which effect groups are folded, and the one place the preview size is decided. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; + +use egui::{Context, TextureHandle, TextureId, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; + +use crate::TextureCraftApp; + +/// Edge (points) of a layer's content and mask thumbnails. The Layers "Preview size" setting +/// plugs in by changing [`layer_preview_size`]; every row measure below derives from it. +pub(crate) const LAYER_PREVIEW_SIZE: f32 = 36.0; + +/// The thumbnail edge in points, read once per row. +pub(crate) fn layer_preview_size(_app: &TextureCraftApp) -> f32 { + LAYER_PREVIEW_SIZE +} + +/// Height of a layer row for thumbnails of `size`. +pub(crate) fn layer_row_height(size: f32) -> f32 { + (size + 12.0).max(48.0) +} + +/// Edge of an effect's stage thumbnail for layer thumbnails of `size` (18 to 28 points). +pub(crate) fn effect_preview_size(size: f32) -> f32 { + (size * 0.6).clamp(18.0, 28.0) +} + +/// Height of an effect row. +pub(crate) fn effect_row_height(size: f32) -> f32 { + (effect_preview_size(size) + 4.0).max(26.0) +} + +#[derive(Default)] +pub struct LayerPanel { + service: ThumbService, + textures: HashMap, + frame: u64, + /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. + pub(crate) folded: HashSet<(u64, bool)>, +} + +impl LayerPanel { + /// Start drawing the panel for this frame. + pub(crate) fn begin(&mut self, session: &Session, now: f64) { + self.frame += 1; + self.service.begin_frame(session, now); + } + + /// The texture of `target`, queuing its render (call only for rows that are on screen). + pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + let view = self.service.get(session, target); + let image = view.image?; + let frame = self.frame; + if let Some((version, tex, used)) = self.textures.get_mut(&target) + && *version == view.version + { + *used = frame; + return Some(tex.id()); + } + let pixels = egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &image.rgba); + let tex = ctx.load_texture("layer-thumb", pixels, TextureOptions::LINEAR); + let id = tex.id(); + self.textures.insert(target, (view.version, tex, frame)); + Some(id) + } + + /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if self.service.poll(session) { + ctx.request_repaint_after(Duration::from_millis(40)); + } + if self.textures.len() > CACHE_ENTRIES * 2 { + let frame = self.frame; + self.textures.retain(|_, (_, _, used)| *used + 1 >= frame); + } + } + + /// The service, for tests. + pub fn service(&self) -> &ThumbService { + &self.service + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..d82bea69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +pub mod layer_panel; pub mod menus; pub mod parity; pub mod profile; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { pub resize: Option, pub link_cooks: Vec, pub thumbs: thumbs::Thumbs, + /// The Layers panel's thumbnails and folded groups. + pub layer_panel: layer_panel::LayerPanel, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -145,6 +148,7 @@ impl TextureCraftApp { resize: None, link_cooks: Vec::new(), thumbs: thumbs::Thumbs::default(), + layer_panel: layer_panel::LayerPanel::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, diff --git a/crates/ui-egui/tests/layers_panel.rs b/crates/ui-egui/tests/layers_panel.rs new file mode 100644 index 00000000..facf2ab3 --- /dev/null +++ b/crates/ui-egui/tests/layers_panel.rs @@ -0,0 +1,96 @@ +//! The Layers panel rows: content and mask thumbnails select their own target, effect groups +//! fold without touching the document, and the thumbnails arrive from the worker. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// A session whose top layer, "Masked fill", has one content effect and a mask with one effect. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); + execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Masked fill"})).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, layer) +} + +/// Centre of the content (`mask` false) or mask thumbnail of the top-level, non-folder row +/// labelled `name`: after the 7-point edge, the 20-point eye column, then 36-point squares 4 apart. +fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 { + let row = h.get_by_label(name).rect(); + let x = row.left() + 7.0 + 20.0 + 18.0 + if mask { 40.0 } else { 0.0 }; + egui::pos2(x, row.center().y) +} + +/// The `label` header that follows the "Masked fill" row (other layers have groups too). +fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let top = h.get_by_label("Masked fill").rect().top(); + let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center(); + click(h, at); +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.drag_at(at); + h.drop_at(at); + h.run_steps(3); +} + +#[test] +fn mask_and_content_thumbnails_select_their_own_target() { + let (mut h, layer) = harness(); + let at = thumb(&h, "Masked fill", true); + click(&mut h, at); + assert_eq!(h.state().session.selected_layer(), Some(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask"); + let at = thumb(&h, "Masked fill", false); + click(&mut h, at); + assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); + // Clicking an effect row still selects that effect. + let r = h.get_by_label("Effect A").rect(); + click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); +} + +#[test] +fn folding_an_effect_group_hides_its_rows_without_changing_the_document() { + let (mut h, _) = harness(); + let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision); + assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some()); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden"); + assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open"); + header(&mut h, "Mask effects"); + assert!(h.query_by_label("Effect M").is_none()); + assert_eq!(h.state().session.doc.project, project); + assert_eq!(h.state().session.revision, undo, "folding is not an edit"); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_some(), "unfolds again"); +} + +#[test] +fn visible_rows_get_their_thumbnails() { + let (mut h, layer) = harness(); + let content = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mask = ThumbTarget::Mask { layer }; + let t0 = std::time::Instant::now(); + while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived"); + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Rows, mask, and every effect stage on screen were asked for: well under the cache size. + assert!(h.state().layer_panel.service().cached() >= 4); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..f180af43 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -127,7 +127,40 @@ fn window_snapshots() { texturecraft_engine::execute(session, id, ¶ms).unwrap(); } save(&mut harness, &output_dir, "properties-levels"); - + // Show the Layers panel thumbnails with a hidden content effect, a folder and a mask + let session = &mut harness.state_mut().session; + for (id, params) in [ + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "hsl"})), + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "invert"})), + ("layer.add.paint", serde_json::Value::Null), + ("layer.group", serde_json::Value::Null), + ] { + texturecraft_engine::execute(session, id, ¶ms).unwrap(); + } + let hidden = harness + .state() + .session + .doc + .project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .find(|effect| effect.name == "Invert") + .map(|effect| effect.id.0); + if let Some(effect) = hidden { + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &serde_json::json!({"effect": effect, "visible": false})).unwrap(); + } + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.set_size(egui::vec2(1600.0, 1400.0)); + for _ in 0..400 { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + if !harness.state().layer_panel.service().busy() { + break; + } + } + save(&mut harness, &output_dir, "panel-layers"); + harness.set_size(egui::vec2(1600.0, 960.0)); // Show the second path selected in Properties let session = &mut harness.state_mut().session; for (id, params) in [ diff --git a/docs/architecture.md b/docs/architecture.md index 5eda226c..2756a942 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,6 +69,26 @@ The CPU compositor is the reference for everything users see and export. Export (`formats::export`) reads the same composite, adds height-to-normal (Sobel) combined with the normal channel and baked normals by reoriented normal mapping, and packs channels per preset. +### Layer-panel thumbnails + +The Layers panel shows each layer's content (in the displayed channel), its mask and every effect +stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the +project: the set's stack becomes the one layer, forced visible at Normal / 100 %, without its mask +for the content, and with its effect list truncated after the previewed effect (a hidden effect +shows the result it bypasses). Paint and fill layers are flattened to (value, coverage), so empty +texels are transparent; folders composite their children. Colors are encoded linear to sRGB, data +channels raw. Everything is evaluated on a 64 px G-buffer of the mesh (painted tiles are +resampled), never at the set's resolution, and the main composite is never touched. + +`engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the +project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt +only when the document really differs (compared at most every 120 ms while it keeps changing), a +worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older +snapshot are dropped, and an LRU of 96 pictures keeps the out-of-date picture on screen until its +replacement arrives. Only rows on screen ask for pictures; queued rows that scrolled away are +dropped. On a 4096 set (`perf::bench_layer_thumbs_4k`) a snapshot costs 0.02 ms, a content picture +about 2.5 ms and a whole ten-layer panel (20 pictures) about 42 ms of worker time. + ## Undo `Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a From d5aaea9331adb9658c9ac61fc996a968742fbc5d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 05:24:31 +0000 Subject: [PATCH 036/275] Bake mode: mesh map bakers list and per-map settings Lay bake mode out as texture sets over a Mesh Map Bakers list, then Common Settings | Mesh Map Settings tabs, with the log under both columns. A row's checkbox enables a map for baking; clicking the row selects it, and Mesh Map Settings shows only the selected map behind a texture set / map breadcrumb with dropdowns. Selecting never changes what bakes. Saved bake docks from before this layout, or that cannot be read, load as the bake layout instead of the painting default. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/bake_mode.rs | 31 +++-- crates/ui-egui/src/bake_mode/breadcrumb.rs | 35 +++++ .../ui-egui/src/bake_mode/common_settings.rs | 13 +- crates/ui-egui/src/bake_mode/controls.rs | 62 +++------ crates/ui-egui/src/bake_mode/map_settings.rs | 40 +++--- .../ui-egui/src/bake_mode/mesh_map_bakers.rs | 75 +++++++++++ crates/ui-egui/src/docking.rs | 121 ++++++++++++------ crates/ui-egui/src/i18n/ar.rs | 6 +- crates/ui-egui/src/i18n/de.rs | 6 +- crates/ui-egui/src/i18n/es.rs | 6 +- crates/ui-egui/src/i18n/fr.rs | 6 +- crates/ui-egui/src/i18n/it.rs | 6 +- crates/ui-egui/src/i18n/ja.rs | 6 +- crates/ui-egui/src/i18n/ko.rs | 6 +- crates/ui-egui/src/i18n/pt_br.rs | 6 +- crates/ui-egui/src/i18n/zh_hans.rs | 6 +- crates/ui-egui/src/menus.rs | 5 +- crates/ui-egui/src/state.rs | 95 +++++++++++++- crates/ui-egui/tests/bake_mode.rs | 96 ++++++++++++-- crates/ui-egui/tests/skew_paint.rs | 5 +- crates/ui-egui/tests/ui_snapshots.rs | 20 +-- docs/parity.md | 7 +- 22 files changed, 508 insertions(+), 151 deletions(-) create mode 100644 crates/ui-egui/src/bake_mode/breadcrumb.rs create mode 100644 crates/ui-egui/src/bake_mode/mesh_map_bakers.rs diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs index c0397a49..a5ee88f4 100644 --- a/crates/ui-egui/src/bake_mode.rs +++ b/crates/ui-egui/src/bake_mode.rs @@ -1,10 +1,12 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; mod controls; mod map_settings; +mod mesh_map_bakers; use egui::{Ui, vec2}; use serde_json::json; @@ -37,19 +39,32 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { }); } -pub fn bake_body(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_maps", |_, ui, settings| { - for map in BakedMap::ALL { - ui.push_id(map, |ui| map_settings::show(ui, map, &mut settings.maps)); - ui.add_space(6.0); - } - }); +/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows +pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "mesh_map_bakers", mesh_map_bakers::show); } -pub fn settings_body(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters +pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; + + let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); + breadcrumb::show(app, ui, selected); + ui.separator(); + edit_settings(app, ui, "mesh_map_settings", |_, ui, settings| ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner); +} + +/// The Common Settings panel: output, high poly, cage and skew settings +pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { edit_settings(app, ui, "bake_common_settings", common_settings::show); } +/// The map whose settings show: the chosen one, else the first enabled map, else Normal +fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { + selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) +} + +/// Draw `contents` over a copy of the active set's bake settings and run `bake.settings` on change fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { let set_index = app.session.ts(); let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs new file mode 100644 index 00000000..14dc7fd5 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -0,0 +1,35 @@ +use egui::{RichText, Ui}; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::BakedMap; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr}; + +/// The texture set and selected map above Mesh Map Settings, each behind a dropdown to switch it +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap) { + let active_set = app.session.ts(); + let set_names: Vec = app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.name.clone()).collect(); + + ui.horizontal(|ui| { + ui.menu_button(icon::CARET_RIGHT, |ui| { + for (set_index, name) in set_names.iter().enumerate() { + if ui.selectable_label(set_index == active_set, name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + ui.close(); + } + } + }); + ui.label(set_names.get(active_set).map_or("", String::as_str)); + + ui.menu_button(icon::CARET_RIGHT, |ui| { + for map in BakedMap::ALL { + if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { + app.ui.selected_baked_map = Some(map); + ui.close(); + } + } + }); + ui.label(RichText::new(tr(baked_map_label(selected))).strong()); + }); +} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index d96fdc85..7df96827 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -9,10 +9,12 @@ use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; +/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { ui.push_id("common", |ui| { + // Restore Defaults keeps whether the texture set is included in the bake let is_enabled = settings.common.is_enabled; - if section(ui, tr("Common Parameters"), None, |ui| { + if section(ui, tr("Common Parameters"), |ui| { output_size(ui, &mut settings.common); choice( ui, @@ -31,9 +33,10 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; } }); + ui.add_space(8.0); ui.push_id("high_poly", |ui| { - if section(ui, tr("High-Poly Parameters"), None, |ui| { + if section(ui, tr("High-Poly Parameters"), |ui| { ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); high_poly_files(app, ui); if !app.session.bake_meshes.high.is_empty() { @@ -52,10 +55,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.high_poly = Default::default(); } }); + if !app.session.bake_meshes.high.is_empty() { ui.add_space(8.0); ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), None, |ui| { + if section(ui, tr("Cage"), |ui| { choice( ui, tr("Cage Type"), @@ -76,10 +80,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe settings.cage = Default::default(); } }); + if settings.cage.kind == CageType::DistanceBased { ui.add_space(8.0); ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), None, |ui| { + if section(ui, tr("Skew Correction"), |ui| { choice( ui, tr("Skew Correction Method"), diff --git a/crates/ui-egui/src/bake_mode/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index 4c2e6b88..f260bf7c 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -3,63 +3,35 @@ use crate::theme::{Tokens, caption}; use egui::collapsing_header::CollapsingState; use egui::{RichText, Ui}; -pub(super) fn section_header(ui: &mut Ui, title: &str, mut is_enabled: Option<&mut bool>, collapsing_state: Option<&mut CollapsingState>) -> bool { +/// A section's title bar with its chevron; clicking it opens or closes the section +fn section_header(ui: &mut Ui, title: &str, collapsing_state: &mut CollapsingState) { let tokens = Tokens::get(ui.ctx()); - let text_color = if is_enabled.as_deref().copied().unwrap_or(true) { tokens.text_strong } else { tokens.text_dim }; - let mut checkbox_rect = None; - let mut arrow_rect = None; - let header = egui::Frame::NONE.fill(tokens.row).corner_radius(tokens.cr()).inner_margin(egui::Margin::symmetric(8, 4)).show(ui, |ui| { ui.set_min_width(ui.available_width()); ui.horizontal(|ui| { ui.set_min_height(ui.spacing().interact_size.y); - let checkbox = is_enabled.as_deref_mut().map(|is_enabled| ui.checkbox(is_enabled, "")); - let title_response = ui.add(egui::Label::new(caption(title).color(text_color)).selectable(false)); - if let Some(checkbox) = checkbox { - checkbox_rect = Some(checkbox.rect); - checkbox.labelled_by(title_response.id); - } - - if collapsing_state.is_some() { - arrow_rect = Some( - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 - }) - .inner, - ); - } - }); + ui.add(egui::Label::new(caption(title).color(tokens.text_strong)).selectable(false)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 + }) + .inner + }) + .inner }); - if let (Some(collapsing_state), Some(arrow_rect)) = (collapsing_state, arrow_rect) { - let mut toggle_rect = header.response.rect; - if let Some(checkbox_rect) = checkbox_rect { - let checkbox_margin = ui.spacing().item_spacing.x * 0.5; - if ui.style().right_to_left { - toggle_rect.max.x = checkbox_rect.left() - checkbox_margin; - } else { - toggle_rect.min.x = checkbox_rect.right() + checkbox_margin; - } - } - - let response = ui.interact(toggle_rect, ui.make_persistent_id("section_header"), egui::Sense::click()); - if response.clicked() { - collapsing_state.toggle(ui); - } - - let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); - ui.put(arrow_rect, egui::Label::new(chevron).selectable(false)); + let response = ui.interact(header.response.rect, ui.make_persistent_id("section_header"), egui::Sense::click()); + if response.clicked() { + collapsing_state.toggle(ui); } - is_enabled.as_deref().copied().unwrap_or(true) + let chevron = crate::widgets::section_chevron(ui, collapsing_state.is_open()); + ui.put(header.inner, egui::Label::new(chevron).selectable(false)); } -pub(super) fn section(ui: &mut Ui, title: &str, is_enabled: Option<&mut bool>, contents: impl FnOnce(&mut Ui)) -> bool { +/// A collapsible section with `contents` and Restore Defaults; returns whether that was clicked +pub(super) fn section(ui: &mut Ui, title: &str, contents: impl FnOnce(&mut Ui)) -> bool { let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); - if !section_header(ui, title, is_enabled, Some(&mut collapsing_state)) { - collapsing_state.store(ui.ctx()); - return false; - } + section_header(ui, title, &mut collapsing_state); collapsing_state .show_body_unindented(ui, |ui| { diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index a8cb2d48..0b5ac9e0 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,32 +1,34 @@ -use super::controls::{choice, integer, number, section, section_header}; -use crate::i18n::{baked_map_label, tr}; +use super::controls::{choice, hint, integer, number}; +use crate::i18n::tr; use egui::Ui; use texturecraft_engine::core::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, - HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MapSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, - PositionSettings, RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, + HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, + RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, }; +/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { match map { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - let mut is_enabled = settings.is_enabled(map); - section_header(ui, tr(baked_map_label(map)), Some(&mut is_enabled), None); - settings.set_enabled(map, is_enabled); - } - BakedMap::Id => baker(ui, map, &mut settings.id, id), - BakedMap::AmbientOcclusion => baker(ui, map, &mut settings.ao, ambient_occlusion), - BakedMap::Curvature => baker(ui, map, &mut settings.curvature, curvature), - BakedMap::Position => baker(ui, map, &mut settings.position, position), - BakedMap::Thickness => baker(ui, map, &mut settings.thickness, thickness), - BakedMap::Height => baker(ui, map, &mut settings.height, height), - BakedMap::BentNormal => baker(ui, map, &mut settings.bent_normal, bent_normal), + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => hint(ui, tr("No Parameters")), + BakedMap::Id => parameters(ui, &mut settings.id.parameters, id), + BakedMap::AmbientOcclusion => parameters(ui, &mut settings.ao.parameters, ambient_occlusion), + BakedMap::Curvature => parameters(ui, &mut settings.curvature.parameters, curvature), + BakedMap::Position => parameters(ui, &mut settings.position.parameters, position), + BakedMap::Thickness => parameters(ui, &mut settings.thickness.parameters, thickness), + BakedMap::Height => parameters(ui, &mut settings.height.parameters, height), + BakedMap::BentNormal => parameters(ui, &mut settings.bent_normal.parameters, bent_normal), } } -fn baker(ui: &mut Ui, map: BakedMap, settings: &mut MapSettings, controls: impl FnOnce(&mut Ui, &mut T)) { - if section(ui, tr(baked_map_label(map)), Some(&mut settings.is_enabled), |ui| controls(ui, &mut settings.parameters)) { - settings.parameters = T::default(); +/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters +fn parameters(ui: &mut Ui, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) { + controls(ui, parameters); + ui.add_space(6.0); + + let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; + if restore.clicked() { + *parameters = T::default(); } } diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs new file mode 100644 index 00000000..b9101e93 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -0,0 +1,75 @@ +use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr}; +use crate::theme::Tokens; + +/// Height of one baker row, in points +const ROW_HEIGHT: f32 = 24.0; +/// Inset of a row's checkbox and name from its left edge, in points +const ROW_INSET: f32 = 6.0; + +/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + if ui.button(format!("{} {}", icon::GEAR, tr("Common Settings"))).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + + ui.add_space(4.0); + check_all(ui, settings); + ui.separator(); + + let selected = super::selected_map(app.ui.selected_baked_map, settings); + for map in BakedMap::ALL { + if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + app.ui.selected_baked_map = Some(map); + app.ui.dock.focus(Panel::MeshMapSettings); + } + } +} + +/// Enable every map, or disable them all when every map is already enabled +fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { + let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); + let mut all_enabled = enabled_count == BakedMap::ALL.len(); + let some_enabled = enabled_count > 0 && !all_enabled; + + if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, all_enabled); + } + } +} + +/// One baker row; returns whether the row (not its checkbox) was clicked +fn row(ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); + let name = tr(baked_map_label(map)); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); + + let painter = ui.painter(); + if is_selected { + painter.rect_filled(rect, tokens.cr(), tokens.row_selected); + painter.rect_stroke(rect, tokens.cr(), Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, tokens.cr(), tokens.row_hover); + } + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + + // Added after the row's own response, so the checkbox takes the clicks over it + let content_rect = rect.shrink2(vec2(ROW_INSET, 0.0)); + let mut content = ui.new_child(UiBuilder::new().max_rect(content_rect).layout(Layout::left_to_right(Align::Center))); + let mut is_enabled = settings.maps.is_enabled(map); + let checkbox = content.checkbox(&mut is_enabled, ""); + let text = if is_selected { RichText::new(name).strong() } else { RichText::new(name) }; + let label = content.add(egui::Label::new(text).selectable(false).truncate()); + if checkbox.labelled_by(label.id).changed() { + settings.maps.set_enabled(map, is_enabled); + } + + response.clicked() +} diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 11de63af..789ddc51 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -24,8 +24,12 @@ use crate::theme::Tokens; pub enum Panel { Viewport, Assets, - BakeMaps, - BakeSettings, + // Saved layouts name the bake panels by their earlier names + #[serde(rename = "BakeMaps")] + MeshMapSettings, + #[serde(rename = "BakeSettings")] + CommonSettings, + MeshMapBakers, TextureSetList, Layers, TextureSetSettings, @@ -37,14 +41,15 @@ pub enum Panel { } /// Window ▸ Views items and the panels they show or hide. -pub const VIEWS: [(&str, Panel); 11] = [ +pub const VIEWS: [(&str, Panel); 12] = [ ("ui.view.assets", Panel::Assets), - ("ui.view.bakeMaps", Panel::BakeMaps), - ("ui.view.bakeSettings", Panel::BakeSettings), + ("ui.view.bakeMaps", Panel::MeshMapSettings), + ("ui.view.bakeSettings", Panel::CommonSettings), ("ui.view.display", Panel::Display), ("ui.view.history", Panel::History), ("ui.view.layers", Panel::Layers), ("ui.view.log", Panel::Log), + ("ui.view.meshMapBakers", Panel::MeshMapBakers), ("ui.view.properties", Panel::Properties), ("ui.view.shader", Panel::Shader), ("ui.view.textureSetList", Panel::TextureSetList), @@ -59,17 +64,18 @@ pub fn view_panel(id: &str) -> Option { impl Panel { pub(crate) fn available_in(self, mode: crate::state::Mode) -> bool { match self { - Self::BakeMaps | Self::BakeSettings => mode == crate::state::Mode::Baking, + Self::MeshMapSettings | Self::CommonSettings | Self::MeshMapBakers => mode == crate::state::Mode::Baking, Self::Assets | Self::Layers | Self::Properties | Self::TextureSetSettings => mode != crate::state::Mode::Baking, _ => true, } } - pub const ALL: [Panel; 12] = [ + pub const ALL: [Panel; 13] = [ Panel::Viewport, Panel::Assets, - Panel::BakeMaps, - Panel::BakeSettings, + Panel::MeshMapSettings, + Panel::CommonSettings, + Panel::MeshMapBakers, Panel::TextureSetList, Panel::Layers, Panel::TextureSetSettings, @@ -84,8 +90,9 @@ impl Panel { match self { Panel::Viewport => "Viewport", Panel::Assets => "Assets", - Panel::BakeMaps => "Bake Maps", - Panel::BakeSettings => "Settings", + Panel::MeshMapSettings => "Mesh Map Settings", + Panel::CommonSettings => "Common Settings", + Panel::MeshMapBakers => "Mesh Map Bakers", Panel::TextureSetList => "Texture Sets", Panel::Layers => "Layers", Panel::TextureSetSettings => "Texture Set Settings", @@ -122,8 +129,8 @@ fn tabs(panels: &[Panel]) -> Node { Node::Tabs { panels: panels.to_vec(), active: 0 } } -fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) -> Node { - Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) } +fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node) -> Node { + Node::Split { axis, size, first: Box::new(first), second: Box::new(second) } } /// The default: assets left of the viewport; texture set list, layers (tabbed with the texture @@ -131,9 +138,14 @@ fn split(axis: SplitAxis, ratio: f32, first: Node, second: Node) - /// shader, history and log are closed and open as floating windows. pub fn default_workspace() -> Workspace { use Panel::*; - let column = - split(SplitAxis::Vertical, 0.125, tabs(&[TextureSetList]), split(SplitAxis::Vertical, 0.57, tabs(&[Layers, TextureSetSettings]), tabs(&[Properties]))); - let root = split(SplitAxis::Horizontal, 0.115, tabs(&[Assets]), split(SplitAxis::Horizontal, 0.78, tabs(&[Viewport]), column)); + let column = split( + SplitAxis::Vertical, + SplitSize::Ratio(0.125), + tabs(&[TextureSetList]), + split(SplitAxis::Vertical, SplitSize::Ratio(0.57), tabs(&[Layers, TextureSetSettings]), tabs(&[Properties])), + ); + let root = + split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); for panel in Panel::ALL { if let Some(rect) = panel.float_rect() { @@ -149,7 +161,7 @@ pub fn default_workspace() -> Workspace { workspace.hidden.push((panel, location)); } } - for panel in [BakeMaps, BakeSettings] { + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { workspace.hidden.push(( panel, Location { @@ -206,17 +218,28 @@ pub fn validate(workspace: &Workspace) -> Result<(), String> { // --------------------------------------------------------------------------------------------- // The live dock +/// Width of the bake layout's texture set and mesh map bakers column, in points +const BAKERS_COLUMN_WIDTH: f32 = 200.0; +/// Width of the bake layout's common and mesh map settings column, in points +const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Height of the log under the bake layout's columns, in points +const BAKING_LOG_HEIGHT: f32 = 160.0; +/// Share of the first bake column the texture set list takes above the mesh map bakers +const TEXTURE_SET_LIST_SHARE: f32 = 0.4; + /// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`). #[derive(Clone, Debug)] pub struct Dock { workspace: Workspace, /// A panel to bring in front of the other floating windows on the next frame. raise: Option, + /// A saved layout could not be read, so this is the painting default in its place + replaced_unreadable: bool, } impl Default for Dock { fn default() -> Self { - Dock { workspace: default_workspace(), raise: None } + Dock { workspace: default_workspace(), raise: None, replaced_unreadable: false } } } @@ -240,18 +263,27 @@ impl<'de> Deserialize<'de> for Dock { } impl Dock { - /// The dock for a saved layout; the default when it is not a valid workspace. + /// The dock for a saved layout; the default, marked as a replacement, when it is not a valid workspace pub fn from_value(value: Value) -> Dock { + let unreadable = Dock { replaced_unreadable: true, ..Dock::default() }; let default = default_workspace(); let loaded = serde_json::from_value::(value).ok(); - let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() }; + let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return unreadable }; + workspace.reconcile(|_| true, permissions, &default); if validate(&workspace).is_err() { - return Dock::default(); + return unreadable; } - Dock { workspace, raise: None } + + Dock { workspace, raise: None, replaced_unreadable: false } } + /// Whether a saved layout could not be read and this dock is the painting default instead + pub(crate) fn replaced_unreadable(&self) -> bool { + self.replaced_unreadable + } + + /// Texture sets over the bakers, the two settings tabs, the log under both, then the viewport pub(crate) fn for_baking() -> Self { let mut workspace = default_workspace(); for panel in [Panel::Assets, Panel::Layers, Panel::TextureSetSettings, Panel::Properties] { @@ -259,17 +291,19 @@ impl Dock { workspace.hidden.push((panel, location)); } } - workspace.hidden.retain(|(panel, _)| !matches!(panel, Panel::BakeMaps | Panel::BakeSettings)); - workspace.layout = Layout { - root: Some(Node::Split { - axis: SplitAxis::Horizontal, - size: SplitSize::FixedFirst(320.0), - first: Box::new(tabs(&[Panel::TextureSetList, Panel::BakeSettings, Panel::BakeMaps])), - second: Box::new(tabs(&[Panel::Viewport])), - }), - floating: Vec::new(), - }; - Dock { workspace, raise: None } + + let bake_panels = [Panel::MeshMapSettings, Panel::CommonSettings, Panel::MeshMapBakers, Panel::Log]; + workspace.hidden.retain(|(panel, _)| !bake_panels.contains(panel)); + + let gutter_width = f32::from(crate::theme::GUTTER); + let list_column = split(SplitAxis::Vertical, SplitSize::Ratio(TEXTURE_SET_LIST_SHARE), tabs(&[Panel::TextureSetList]), tabs(&[Panel::MeshMapBakers])); + let settings_column = tabs(&[Panel::CommonSettings, Panel::MeshMapSettings]); + let columns = split(SplitAxis::Horizontal, SplitSize::FixedFirst(BAKERS_COLUMN_WIDTH), list_column, settings_column); + let columns_over_log = split(SplitAxis::Vertical, SplitSize::FixedSecond(BAKING_LOG_HEIGHT), columns, tabs(&[Panel::Log])); + let columns_width = BAKERS_COLUMN_WIDTH + gutter_width + SETTINGS_COLUMN_WIDTH; + let root = split(SplitAxis::Horizontal, SplitSize::FixedFirst(columns_width), columns_over_log, tabs(&[Panel::Viewport])); + workspace.layout = Layout { root: Some(root), floating: Vec::new() }; + Dock { workspace, raise: None, replaced_unreadable: false } } pub fn workspace(&self) -> &Workspace { @@ -401,9 +435,10 @@ impl DockContent for Panels<'_> { return; } egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::BakeMaps => crate::bake_mode::bake_body(app, ui), + Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), - Panel::BakeSettings => crate::bake_mode::settings_body(app, ui), + Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), + Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), Panel::TextureSetList => crate::dock::texture_set_list(app, ui), Panel::Layers => crate::dock::layers(app, ui), @@ -425,8 +460,6 @@ impl DockContent for Panels<'_> { fn logical_label(&self, panel: &Panel) -> String { match panel { Panel::Properties => crate::dock::properties_title(self.app), - Panel::BakeMaps => tr("Bake Maps").to_string(), - Panel::BakeSettings => tr("Settings").to_string(), p => tr(p.name()).to_string(), } } @@ -475,6 +508,20 @@ mod tests { assert_eq!(back, dock); } + #[test] + fn the_bake_dock_round_trips_with_the_log_under_both_settings_columns() { + let dock = Dock::for_baking(); + assert!(validate(dock.workspace()).is_ok()); + assert_eq!( + panels_of(dock.workspace()), + [Panel::TextureSetList, Panel::MeshMapBakers, Panel::CommonSettings, Panel::MeshMapSettings, Panel::Log, Panel::Viewport] + ); + assert!(dock.is_visible(Panel::CommonSettings) && !dock.is_visible(Panel::MeshMapSettings)); + + let back: Dock = serde_json::from_str(&serde_json::to_string(&dock).unwrap()).unwrap(); + assert_eq!(back, dock); + } + #[test] fn unreadable_layouts_become_the_default() { for text in [ diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..405ee0b7 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -963,7 +963,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "توسيط النواظم"), ("BBox", "صندوق الإحاطة"), ("BSphere", "كرة الإحاطة"), - ("Bake Maps", "خبز الخرائط"), + ("Mesh Map Bakers", "مُخبِزات خرائط المجسم"), + ("Common Settings", "الإعدادات المشتركة"), + ("Mesh Map Settings", "إعدادات خرائط المجسم"), + ("Check All", "تحديد الكل"), + ("No Parameters", "لا توجد معلمات"), ("Bake Selected Textures ({n})", "خبز الخامات المحددة ({n})"), ("By Mesh Name", "حسب اسم المجسم"), ("Cage", "القفص"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..05778fa7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1012,7 +1012,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normalen mitteln"), ("BBox", "Begrenzungsrahmen"), ("BSphere", "Begrenzungskugel"), - ("Bake Maps", "Maps backen"), + ("Mesh Map Bakers", "Mesh-Map-Baker"), + ("Common Settings", "Allgemeine Einstellungen"), + ("Mesh Map Settings", "Mesh-Map-Einstellungen"), + ("Check All", "Alle auswählen"), + ("No Parameters", "Keine Parameter"), ("Bake Selected Textures ({n})", "Ausgewählte Texturen backen ({n})"), ("By Mesh Name", "Nach Mesh-Name"), ("Cage", "Käfig"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..8c1945f9 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -997,7 +997,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Promediar normales"), ("BBox", "Caja delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Hornear mapas"), + ("Mesh Map Bakers", "Horneadores de mapas de malla"), + ("Common Settings", "Ajustes comunes"), + ("Mesh Map Settings", "Ajustes de mapas de malla"), + ("Check All", "Marcar todo"), + ("No Parameters", "Sin parámetros"), ("Bake Selected Textures ({n})", "Hornear texturas seleccionadas ({n})"), ("By Mesh Name", "Por nombre de malla"), ("Cage", "Jaula"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..a55060c5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1021,7 +1021,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Moyenne des normales"), ("BBox", "Boîte englobante"), ("BSphere", "Sphère englobante"), - ("Bake Maps", "Précalculer les cartes"), + ("Mesh Map Bakers", "Précalculateurs de cartes de maillage"), + ("Common Settings", "Paramètres communs"), + ("Mesh Map Settings", "Paramètres des cartes de maillage"), + ("Check All", "Tout cocher"), + ("No Parameters", "Aucun paramètre"), ("Bake Selected Textures ({n})", "Précalculer les textures sélectionnées ({n})"), ("By Mesh Name", "Par nom de maillage"), ("Cage", "Cage"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..2467f2e7 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1006,7 +1006,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normali medie"), ("BBox", "Riquadro di delimitazione"), ("BSphere", "Sfera di delimitazione"), - ("Bake Maps", "Bake delle mappe"), + ("Mesh Map Bakers", "Baker delle mappe mesh"), + ("Common Settings", "Impostazioni comuni"), + ("Mesh Map Settings", "Impostazioni mappe mesh"), + ("Check All", "Seleziona tutto"), + ("No Parameters", "Nessun parametro"), ("Bake Selected Textures ({n})", "Bake texture selezionate ({n})"), ("By Mesh Name", "Per nome della mesh"), ("Cage", "Gabbia"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..f6237ce4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -991,7 +991,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "法線を平均化"), ("BBox", "バウンディングボックス"), ("BSphere", "バウンディングスフィア"), - ("Bake Maps", "マップをベイク"), + ("Mesh Map Bakers", "メッシュマップベイカー"), + ("Common Settings", "共通設定"), + ("Mesh Map Settings", "メッシュマップ設定"), + ("Check All", "すべてチェック"), + ("No Parameters", "パラメーターなし"), ("Bake Selected Textures ({n})", "選択したテクスチャをベイク ({n})"), ("By Mesh Name", "メッシュ名で"), ("Cage", "ケージ"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..e1b9d52a 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -976,7 +976,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "노멀 평균화"), ("BBox", "경계 상자"), ("BSphere", "경계 구"), - ("Bake Maps", "맵 베이크"), + ("Mesh Map Bakers", "메시 맵 베이커"), + ("Common Settings", "공통 설정"), + ("Mesh Map Settings", "메시 맵 설정"), + ("Check All", "모두 선택"), + ("No Parameters", "매개변수 없음"), ("Bake Selected Textures ({n})", "선택한 텍스처 베이크 ({n})"), ("By Mesh Name", "메시 이름으로"), ("Cage", "케이지"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..0a8fbfcd 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -994,7 +994,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "Normais médias"), ("BBox", "Caixa delimitadora"), ("BSphere", "Esfera delimitadora"), - ("Bake Maps", "Bake de mapas"), + ("Mesh Map Bakers", "Bakers de mapas de malha"), + ("Common Settings", "Configurações comuns"), + ("Mesh Map Settings", "Configurações de mapas de malha"), + ("Check All", "Marcar todos"), + ("No Parameters", "Sem parâmetros"), ("Bake Selected Textures ({n})", "Fazer bake das texturas selecionadas ({n})"), ("By Mesh Name", "Por nome da malha"), ("Cage", "Gaiola"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..ec87af5d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -922,7 +922,11 @@ pub const TABLE: &[(&str, &str)] = &[ ("Average Normals", "平均法线"), ("BBox", "包围盒"), ("BSphere", "包围球"), - ("Bake Maps", "烘焙贴图"), + ("Mesh Map Bakers", "网格贴图烘焙器"), + ("Common Settings", "通用设置"), + ("Mesh Map Settings", "网格贴图设置"), + ("Check All", "全选"), + ("No Parameters", "无参数"), ("Bake Selected Textures ({n})", "烘焙所选纹理({n})"), ("By Mesh Name", "按网格名称"), ("Cage", "笼形"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a2e85bf7..7890d436 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -61,12 +61,13 @@ pub const CATALOG: &[Item] = &[ it("Mode", "Painting", "ui.mode.paint", Some("F9")), it("Mode", "Rendering (path traced)", "ui.mode.render", Some("F10")), sub("Window", "Views", "Assets", "ui.view.assets", None), - sub("Window", "Views", "Bake Maps", "ui.view.bakeMaps", None), - sub("Window", "Views", "Settings", "ui.view.bakeSettings", None), + sub("Window", "Views", "Common Settings", "ui.view.bakeSettings", None), sub("Window", "Views", "Display Settings", "ui.view.display", None), sub("Window", "Views", "History", "ui.view.history", None), sub("Window", "Views", "Layers", "ui.view.layers", None), sub("Window", "Views", "Log", "ui.view.log", None), + sub("Window", "Views", "Mesh Map Bakers", "ui.view.meshMapBakers", None), + sub("Window", "Views", "Mesh Map Settings", "ui.view.bakeMaps", None), sub("Window", "Views", "Properties", "ui.view.properties", None), sub("Window", "Views", "Shader Settings", "ui.view.shader", None), sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89c12bb0..64f65fd3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{BakedMap, Channel}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -232,6 +232,9 @@ fn default_export_dir() -> String { } } +/// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` +const BAKE_LAYOUT_VERSION: u32 = 1; + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub mode: Mode, @@ -243,6 +246,12 @@ pub struct UiState { pub(crate) inactive_mode_dock: Dock, #[serde(default)] pub(crate) dock_is_baking: bool, + /// The bake layout version the bake dock was saved with; 0 before versions existed. + #[serde(default)] + pub(crate) bake_layout_version: u32, + /// The mesh map whose settings Mesh Map Settings shows; `None` follows the first enabled map. + #[serde(default)] + pub(crate) selected_baked_map: Option, /// Window ▸ Hide UI (Tab): only the viewport. pub hide_ui: bool, pub windows: Windows, @@ -283,7 +292,10 @@ pub struct UiState { } impl UiState { + /// Replace an outdated or unreadable saved bake dock by the bake layout, then give the mode its dock pub(crate) fn sync_mode_dock(&mut self) { + self.reset_outdated_bake_dock(); + let baking = self.mode == Mode::Baking; if baking != self.dock_is_baking { std::mem::swap(&mut self.dock, &mut self.inactive_mode_dock); @@ -291,6 +303,17 @@ impl UiState { } } + /// Replace a bake dock saved with an older bake layout, or one that could not be read, by the bake default + fn reset_outdated_bake_dock(&mut self) { + let bake_dock = if self.dock_is_baking { &mut self.dock } else { &mut self.inactive_mode_dock }; + if self.bake_layout_version >= BAKE_LAYOUT_VERSION && !bake_dock.replaced_unreadable() { + return; + } + + *bake_dock = Dock::for_baking(); + self.bake_layout_version = BAKE_LAYOUT_VERSION; + } + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, export /// settings and recent files. pub fn adopt_layout(&mut self, layout: UiState) { @@ -313,6 +336,8 @@ impl Default for UiState { dock: Dock::default(), inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, + bake_layout_version: BAKE_LAYOUT_VERSION, + selected_baked_map: None, hide_ui: false, windows: Windows::default(), uv_zoom: 1.0, @@ -364,6 +389,74 @@ mod tests { assert_eq!(Prefs::default().data_folder, "", "the default is no choice"); } + #[test] + fn a_bake_dock_saved_before_the_bake_layout_version_loads_the_current_bake_layout() { + let old_bake_dock = serde_json::json!({"version": 2, "layout": {"root": {"Split": {"axis": "Horizontal", "size": {"FixedFirst": 320.0}, + "first": {"Tabs": {"panels": ["TextureSetList", "BakeSettings", "BakeMaps"], "active": 0}}, + "second": {"Tabs": {"panels": ["Viewport"], "active": 0}}}}, "floating": []}}); + for dock_is_baking in [false, true] { + let mut painting_dock = Dock::default(); + painting_dock.close(crate::docking::Panel::Assets); + let (bake_field, painting_field) = if dock_is_baking { ("dock", "inactive_mode_dock") } else { ("inactive_mode_dock", "dock") }; + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + let fields = saved.as_object_mut().unwrap(); + fields.remove("bake_layout_version"); + fields.insert("dock_is_baking".into(), serde_json::json!(dock_is_baking)); + fields.insert("mode".into(), serde_json::to_value(if dock_is_baking { Mode::Baking } else { Mode::Painting }).unwrap()); + fields.insert(bake_field.into(), old_bake_dock.clone()); + fields.insert(painting_field.into(), serde_json::to_value(&painting_dock).unwrap()); + + let mut ui: UiState = serde_json::from_value(saved).unwrap(); + let loaded_bake_dock = if dock_is_baking { &ui.dock } else { &ui.inactive_mode_dock }; + assert!(!loaded_bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "the old layout loads without the bakers list"); + + ui.sync_mode_dock(); + let (bake_dock, painting) = if dock_is_baking { (&ui.dock, &ui.inactive_mode_dock) } else { (&ui.inactive_mode_dock, &ui.dock) }; + assert_eq!(*bake_dock, Dock::for_baking()); + assert_eq!(*painting, painting_dock, "the painting layout is kept"); + + let mut reloaded: UiState = serde_json::from_value(serde_json::to_value(&ui).unwrap()).unwrap(); + reloaded.sync_mode_dock(); + assert_eq!(reloaded, ui, "a current layout is not reset again"); + } + } + + /// The app's own settings store: eframe keeps `UiState` as RON text under a key + #[derive(Default)] + struct MemoryStorage(std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_string(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + #[test] + fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { + for mode in [Mode::Painting, Mode::Baking] { + let mut ui = UiState { mode, ..UiState::default() }; + ui.sync_mode_dock(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, "ui", &ui); + + let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + restarted.sync_mode_dock(); + let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; + assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); + assert!(bake_dock.is_open(crate::docking::Panel::MeshMapBakers), "{mode:?}"); + } + } + #[test] fn older_saved_state_without_a_dock_loads_the_default_layout() { let mut v = serde_json::to_value(UiState::default()).unwrap(); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 409966c6..7f2020a0 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -1,3 +1,4 @@ +use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; @@ -5,6 +6,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; +/// A bake-mode app with only `map` enabled and Mesh Map Settings in front fn harness(map: Option) -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.doc.project.texture_sets[0].bake = Default::default(); @@ -13,11 +15,29 @@ fn harness(map: Option) -> Harness<'static, TextureCraftApp> { let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; harness.run_steps(4); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); harness.run_steps(3); harness } +/// The maps the first texture set will bake +fn enabled_maps(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets[0].bake.maps.enabled().collect() +} + +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::Button, name).click(); + harness.run_steps(3); +} + +/// Click a checkbox in Mesh Map Bakers: a map's row or Check All +fn click_checkbox(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(Role::CheckBox, name).click(); + harness.run_steps(3); +} + +/// Scroll the widget labelled `label` into view and click it fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.get_by_label(label).scroll_to_me(); harness.run_steps(3); @@ -29,8 +49,8 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { fn output_axes_unlock_independently_and_relock_to_width() { let mut harness = harness(None); harness.get_by_label("Texture Sets"); - harness.get_by_label("Bake Maps"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.get_by_label("Mesh Map Settings"); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); let width = harness.state().session.doc.project.texture_sets[0].bake.common.resolution.pixels().to_string(); assert!(harness.get_all_by_value(&width).nth(1).unwrap().accesskit_node().is_disabled()); @@ -47,36 +67,86 @@ fn output_axes_unlock_independently_and_relock_to_width() { click(&mut harness, "Lock Output Size"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.common.output_size(), (128, 128)); assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); harness.run_steps(3); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); assert!(harness.get_all_by_value("128").nth(1).unwrap().accesskit_node().is_disabled()); harness.state_mut().ui.mode = Mode::Painting; harness.run_steps(3); - assert!(!harness.state().ui.dock.is_open(Panel::BakeSettings)); + assert!(!harness.state().ui.dock.is_open(Panel::CommonSettings)); assert!(harness.state().ui.dock.is_open(Panel::Assets)); } #[test] -fn height_controls_follow_enablement_and_manual_normalization() { +fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_height() { let mut harness = harness(None); assert!(harness.query_by_label("Normalization").is_none()); - click(&mut harness, "Height"); - assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + select_map(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "selecting is not enabling"); assert!(harness.query_by_label("Scaling Divisor").is_none()); click(&mut harness, "Normalization"); click(&mut harness, "Manual"); harness.get_by_label("Scaling Divisor"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); - click(&mut harness, "Restore Defaults"); + click_checkbox(&mut harness, "Height"); assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); + click(&mut harness, "Restore Defaults"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "Restore Defaults keeps the map enabled"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); assert!(harness.query_by_label("Scaling Divisor").is_none()); - click(&mut harness, "Height"); - assert!(harness.query_by_label("Normalization").is_none()); + click_checkbox(&mut harness, "Height"); + assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); +} + +#[test] +fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + let before = enabled_maps(&harness); + + select_map(&mut harness, "Ambient Occlusion"); + assert!(harness.state().ui.dock.is_visible(Panel::MeshMapSettings), "selecting a map fronts its settings"); + harness.get_by_label("Attenuation"); + assert!(harness.query_by_label("Method").is_none()); + select_map(&mut harness, "Opacity"); + harness.get_by_label("No Parameters"); + assert!(harness.query_by_label("Attenuation").is_none()); + assert_eq!(enabled_maps(&harness), before); + + click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); + assert_eq!(enabled_maps(&harness), before); +} + +#[test] +fn check_all_enables_every_map_then_disables_them_all() { + let mut harness = harness(Some(BakedMap::Curvature)); + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + click_checkbox(&mut harness, "Check All"); + assert!(enabled_maps(&harness).is_empty()); +} + +#[test] +fn the_breadcrumb_switches_the_shown_map() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.get_by_label("Details"); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); + let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); + let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; + map_dropdown.click(); + harness.run_steps(3); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); + // The menu draws its items after the list rows + harness.get_all_by_role_and_label(Role::Button, "Position").last().unwrap().click(); + harness.run_steps(3); + harness.get_by_label("Normalization Scale"); + assert!(harness.query_by_label("Details").is_none()); + assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } #[test] @@ -102,7 +172,7 @@ fn curvature_controls_follow_the_method_and_notes_visibility_rules() { #[test] fn cage_and_skew_controls_require_a_high_poly_and_follow_cage_type() { let mut harness = harness(None); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); assert!(harness.query_by_label("Cage Type").is_none()); assert!(harness.query_by_label("Skew Correction").is_none()); diff --git a/crates/ui-egui/tests/skew_paint.rs b/crates/ui-egui/tests/skew_paint.rs index 1fd92400..bfcc3e3e 100644 --- a/crates/ui-egui/tests/skew_paint.rs +++ b/crates/ui-egui/tests/skew_paint.rs @@ -1,11 +1,12 @@ //! Bake mode: with the skew brush on, dragging in the 2D view paints the skew map, and the -//! brush controls are in the Bake panel. +//! brush controls are in Common Settings. use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; +/// A bake-mode app with a high poly, the 2D view, and Common Settings in front fn harness() -> Harness<'static, TextureCraftApp> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); @@ -13,7 +14,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h.state_mut().ui.mode = Mode::Baking; h.state_mut().ui.layout = ViewLayout::Only2D; h.run_steps(4); - h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::BakeSettings); + h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::CommonSettings); h.run_steps(3); h } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..cbcb769b 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -14,6 +14,12 @@ use texturecraft_ui_egui::state::Mode; use texturecraft_ui_egui::theme::Brightness; use texturecraft_ui_egui::titlebar::TitleBar; +/// Click a map's row in Mesh Map Bakers, which shows its settings +fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + harness.get_by_role_and_label(egui::Role::Button, name).click(); + harness.run_steps(3); +} + fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { h.run_steps(6); let img = h.render().unwrap_or_else(|e| panic!("{name}: {e}")); @@ -58,18 +64,16 @@ fn window_snapshots() { } harness.state_mut().ui.mode = Mode::Baking; save(&mut harness, &output_dir, "mode-bake"); - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Ambient Occlusion").scroll_to_me(); + select_map(&mut harness, "Ambient Occlusion"); save(&mut harness, &output_dir, "mode-bake-maps"); harness.state_mut().ui.prefs.brightness = Brightness::Light; save(&mut harness, &output_dir, "mode-bake-maps-light"); harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - harness.get_by_label("Opacity").scroll_to_me(); + select_map(&mut harness, "Opacity"); save(&mut harness, &output_dir, "mode-bake-unchecked"); harness.state_mut().ui.dock.focus(Panel::TextureSetList); save(&mut harness, &output_dir, "bake-texture-sets"); - harness.state_mut().ui.dock.focus(Panel::BakeSettings); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); save(&mut harness, &output_dir, "bake-settings"); harness.state_mut().session.add_high_poly_bytes("High Poly.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); save(&mut harness, &output_dir, "bake-settings-high-poly"); @@ -90,11 +94,9 @@ fn window_snapshots() { settings.maps.height.parameters.normalization = HeightNormalization::Manual; settings.maps.height.parameters.scaling_divisor = 100.0; } - harness.state_mut().ui.dock.focus(Panel::BakeMaps); - harness.run_steps(3); - harness.get_by_label("Curvature").scroll_to_me(); + select_map(&mut harness, "Curvature"); save(&mut harness, &output_dir, "bake-curvature-mesh"); - harness.get_by_label("Scaling Divisor").scroll_to_me(); + select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); harness.state_mut().session.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; diff --git a/docs/parity.md b/docs/parity.md index d6543d54..652b84a9 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**55 of 55 menu items live (100%).** +**58 of 58 menu items live (100%).** ## File @@ -46,13 +46,16 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Item | Id | Shortcut | Status | |---|---|---|---| | Views ▸ Assets | `ui.view.assets` | | live | +| Views ▸ Common Settings | `ui.view.bakeSettings` | | live | | Views ▸ Display Settings | `ui.view.display` | | live | | Views ▸ History | `ui.view.history` | | live | | Views ▸ Layers | `ui.view.layers` | | live | | Views ▸ Log | `ui.view.log` | | live | +| Views ▸ Mesh Map Bakers | `ui.view.meshMapBakers` | | live | +| Views ▸ Mesh Map Settings | `ui.view.bakeMaps` | | live | | Views ▸ Properties | `ui.view.properties` | | live | | Views ▸ Shader Settings | `ui.view.shader` | | live | -| Views ▸ Texture Set List | `ui.view.textureSetList` | | live | +| Views ▸ Texture Sets | `ui.view.textureSetList` | | live | | Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | | Save UI Layout ▸ Save current layout... | `ui.layout.save` | | live | | Load UI Layout | `ui.layout.load` | | live | From 62da832811f89cd55461e50d6084192c4f858cf6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 08:16:45 +0000 Subject: [PATCH 037/275] Draggable divider between the 3D and 2D views In the split layout the line between the views was fixed at the centre. It can now be dragged to resize both views live; the position is saved in UiState::split_ratio (serde default 0.5, so older states load). - Grab zone of 8 pt around the unchanged 2 pt line, claimed after the views so a press there never paints, orbits or pans. Resize cursor on hover and drag, no highlight. Left button only. - Either view can shrink to a 16 pt sliver. A view narrower than its 300 pt camera and view pickers hides them, and each view is clipped to its side of the divider. - Dragging keeps the 2D texture's on-screen size and offset from the view's centre (zoom and horizontal pan are compensated), stopping where that zoom would leave the 0.1-40 range the wheel uses. - The 2D view's edges sit on whole pixels and views render at the pixel size egui draws them at, so rounding can't nudge the texture's size. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/state.rs | 9 ++ crates/ui-egui/src/viewport.rs | 191 +++++++++++++++++++---- crates/ui-egui/tests/split_divider.rs | 209 ++++++++++++++++++++++++++ 3 files changed, 380 insertions(+), 29 deletions(-) create mode 100644 crates/ui-egui/tests/split_divider.rs diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89c12bb0..8673fda0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -232,10 +232,18 @@ fn default_export_dir() -> String { } } +/// The split layout starts with the 3D and 2D views at equal width +fn default_split_ratio() -> f32 { + 0.5 +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { pub mode: Mode, pub layout: ViewLayout, + /// The 3D view's share of the viewport width in the split layout + #[serde(default = "default_split_ratio")] + pub split_ratio: f32, /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, @@ -310,6 +318,7 @@ impl Default for UiState { UiState { mode: Mode::Painting, layout: ViewLayout::Split, + split_ratio: default_split_ratio(), dock: Dock::default(), inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da60a42d..78618f1e 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -3,6 +3,7 @@ use std::sync::Mutex; +use egui::emath::GuiRounding as _; use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; @@ -34,6 +35,7 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on)); } +/// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking @@ -43,6 +45,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { !texture_set.bake.high_poly.use_low_as_high && texture_set.bake.cage.kind == texturecraft_engine::core::CageType::DistanceBased }); app.ui.bake_paint_brush.on = bake_painting; + if !app.ui.hide_ui { crate::toolbar::paint_bar(app, ui); } @@ -50,27 +53,39 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let aux = match app.session.view { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(m) => Some(crate::gpu::AuxView::MeshMap(m)), + ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; let mut sync = PendingSync(Some(aux)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); + // Skew painting needs the 2D view alongside the 3D Bake preview let layout = if mode == crate::state::Mode::Painting || bake_painting { app.ui.layout } else { ViewLayout::Only3D }; match layout { ViewLayout::Only3D => view_3d(app, ui, full, &mut sync), ViewLayout::Only2D => view_2d(app, ui, full, &mut sync), ViewLayout::Split => { - let midpoint = full.center().x; - let left = Rect::from_min_max(full.min, pos2(midpoint - 1.0, full.max.y)); - let right = Rect::from_min_max(pos2(midpoint + 1.0, full.min.y), full.max); + // The 2D view's edges sit on whole pixels, so rounding can't nudge a texture its zoom keeps at one size + let pixels_per_point = ui.ctx().pixels_per_point(); + let full = full.with_max_x(full.right().round_to_pixels(pixels_per_point)); + let divider_x = split_divider_x(app, ui, full); + let left = Rect::from_min_max(full.min, pos2(divider_x - SPLIT_LINE_HALF_WIDTH, full.max.y)); + let right = Rect::from_min_max(pos2(divider_x + SPLIT_LINE_HALF_WIDTH, full.min.y), full.max); + // Each view draws only on its side, so overlays such as the texture set name stay out of a narrow neighbour + let clip = ui.clip_rect(); + ui.set_clip_rect(left.intersect(clip)); view_3d(app, ui, left, &mut sync); + ui.set_clip_rect(right.intersect(clip)); view_2d(app, ui, right, &mut sync); - ui.painter().line_segment([pos2(midpoint, full.top()), pos2(midpoint, full.bottom())], Stroke::new(2.0, tokens.chrome)); + ui.set_clip_rect(clip); + split_divider_grab(ui, full, divider_x); + let line = Stroke::new(SPLIT_LINE_HALF_WIDTH * 2.0, tokens.chrome); + ui.painter().line_segment([pos2(divider_x, full.top()), pos2(divider_x, full.bottom())], line); } } + if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); } else if app.render.is_active() { @@ -79,17 +94,109 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { if mode == crate::state::Mode::Baking { crate::bake_mode::bake_bar(app, ui.ctx(), full); } + // Keep drawing until the 3D view finishes accumulating anti-aliasing samples let accumulating = layout != ViewLayout::Only2D - && app - .render_state - .as_ref() - .is_some_and(|rs| rs.renderer.read().callback_resources.get::().is_some_and(|g| g.renderer.accumulating(VIEW_3D))); + && app.render_state.as_ref().is_some_and(|render_state| { + render_state.renderer.read().callback_resources.get::().is_some_and(|gpu| gpu.renderer.accumulating(VIEW_3D)) + }); if app.session.stroke_active() || accumulating { ui.ctx().request_repaint(); } } +/// Half the split divider's line width: each view starts this far from the line's centre +const SPLIT_LINE_HALF_WIDTH: f32 = 1.0; + +/// Narrowest a split view may get: a sliver that is still easy to grab and drag back out +const MIN_SPLIT_VIEW_WIDTH: f32 = 16.0; + +/// Width of the split divider's grab zone, centred on its line +const SPLIT_DIVIDER_GRAB_WIDTH: f32 = 8.0; + +/// The split divider's widget id, shared by its drag read and its grab zone +fn split_divider_id(ui: &Ui) -> egui::Id { + ui.scope_id().with("split_divider") +} + +/// The 3D view's share of `width`, keeping both views at least [`MIN_SPLIT_VIEW_WIDTH`] wide when they fit +fn clamp_split_ratio(ratio: f32, width: f32) -> f32 { + let min_ratio = (MIN_SPLIT_VIEW_WIDTH / width).min(0.5); + let ratio = if ratio.is_finite() { ratio } else { 0.5 }; + ratio.clamp(min_ratio, 1.0 - min_ratio) +} + +/// The split divider's x position: while it is dragged it follows the pointer and changes the 2D zoom so the texture keeps its size on screen +fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { + // The 2D view's left edge, beside the line, sits on a whole pixel + let pixels_per_point = ui.ctx().pixels_per_point(); + let divider_x = |ratio: f32| { + let unsnapped = full.left() + full.width() * clamp_split_ratio(ratio, full.width()); + (unsnapped + SPLIT_LINE_HALF_WIDTH).round_to_pixels(pixels_per_point) - SPLIT_LINE_HALF_WIDTH + }; + let old_x = divider_x(app.ui.split_ratio); + + // Read the drag before the views lay out so they follow the pointer in the same frame + let ctx = ui.ctx(); + if ctx.is_being_dragged(split_divider_id(ui)) + && ctx.input(|i| i.pointer.primary_down()) + && let Some(pointer) = ctx.pointer_interact_pos() + { + // `max` and `min` rather than `clamp`, so a NaN bound from a corrupt saved zoom can't panic + let (min_x, max_x) = divider_range_keeping_uv_size(&app.ui, full, old_x, pixels_per_point); + let target_x = pointer.x.max(min_x).min(max_x); + app.ui.split_ratio = clamp_split_ratio((target_x - full.left()) / full.width(), full.width()); + let new_x = divider_x(app.ui.split_ratio); + keep_uv_view_on_screen(&mut app.ui, full, old_x, new_x); + } + + divider_x(app.ui.split_ratio) +} + +/// Lowest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 0.05) +const UV_VIEW_MIN_ZOOM: f32 = 0.1; + +/// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) +const UV_VIEW_MAX_ZOOM: f32 = 40.0; + +/// The 2D view's width when the split divider is at `divider_x` +fn uv_view_width(full: Rect, divider_x: f32) -> f32 { + (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) +} + +/// The share of the 2D view's height that a zoom of 1 fills at `width`: the view fits the texture to its narrower side +fn uv_view_fit(full: Rect, width: f32) -> f32 { + (width / full.height().max(1.0)).min(1.0) +} + +/// The divider positions where the 2D zoom that keeps the texture's screen size stays inside the 2D zoom range +fn divider_range_keeping_uv_size(ui_state: &crate::state::UiState, full: Rect, old_x: f32, pixels_per_point: f32) -> (f32, f32) { + // The zoom times the fit is the texture's screen size, which a divider drag keeps + let screen_zoom = ui_state.uv_zoom * uv_view_fit(full, uv_view_width(full, old_x)); + + // Whole pixels, rounded inward, so snapping the divider to a pixel can't step past the range + let narrowest_view = (full.height() * screen_zoom / UV_VIEW_MAX_ZOOM * pixels_per_point).ceil() / pixels_per_point; + let widest_view = (full.height() * screen_zoom / UV_VIEW_MIN_ZOOM * pixels_per_point).floor() / pixels_per_point; + + let edge = full.right() - SPLIT_LINE_HALF_WIDTH; + (edge - widest_view, edge - narrowest_view) +} + +/// Keeps the 2D view's texture at the same size and offset from the view's centre when the divider moves its left edge from `old_x` to `new_x` +fn keep_uv_view_on_screen(ui_state: &mut crate::state::UiState, full: Rect, old_x: f32, new_x: f32) { + let (old_width, new_width) = (uv_view_width(full, old_x), uv_view_width(full, new_x)); + ui_state.uv_zoom *= uv_view_fit(full, old_width) / uv_view_fit(full, new_width); + + // The horizontal pan is in half view widths + ui_state.uv_pan[0] *= old_width / new_width; +} + +/// The split divider's grab zone with a resize cursor, claimed after the views so it wins the pointer over them +fn split_divider_grab(ui: &Ui, full: Rect, divider_x: f32) { + let zone = Rect::from_x_y_ranges(divider_x - SPLIT_DIVIDER_GRAB_WIDTH * 0.5..=divider_x + SPLIT_DIVIDER_GRAB_WIDTH * 0.5, full.y_range()); + ui.interact(zone, split_divider_id(ui), Sense::drag()).on_hover_and_drag_cursor(egui::CursorIcon::ResizeHorizontal); +} + fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing => (2, 0), @@ -167,6 +274,13 @@ const MAX_NAME_CHARS: usize = 32; /// that view handled its input: a stroke shows in the frame it is painted, not the next. pub struct PendingSync(Option>); +/// A view's render size in pixels, rounded as egui rounds the rect it draws the frame into, so the frame is never stretched +fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { + let pixels_per_point = ui.ctx().pixels_per_point(); + let pixels = |from: f32, to: f32| ((to * pixels_per_point).round() - (from * pixels_per_point).round()).max(1.0) as u32; + [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] +} + fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { let tk = Tokens::get(ui.ctx()); let scene = match (sync.0.take(), app.gpu.as_mut()) { @@ -192,20 +306,38 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sy ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); } -/// The view-mode dropdown shown at the top of each view. +/// Width of the camera and view pickers centred at the top of a view +const VIEW_HEADER_WIDTH: f32 = 300.0; + +/// Height of the view pickers' row +const VIEW_HEADER_HEIGHT: f32 = 22.0; + +/// Gap between the view's top edge and its pickers +const VIEW_HEADER_TOP_GAP: f32 = 8.0; + +/// Width of each of the two pickers +const VIEW_PICKER_WIDTH: f32 = 130.0; + +/// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - let header = Rect::from_min_size(rect.min + vec2(rect.width() * 0.5 - 150.0, 8.0), vec2(300.0, 22.0)); + if rect.width() < VIEW_HEADER_WIDTH { + return; + } + + let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); + let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); + let current = texturecraft_engine::camera_cmds::current(&app.session); - let names: Vec = app.session.doc.project.cameras.iter().map(|c| c.name.clone()).collect(); - let shown = current.and_then(|i| names.get(i)).map_or(tr(DEFAULT_CAMERA), String::as_str); - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(130.0).selected_text(shown).show_ui(&mut child, |ui| { + let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); + let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); + egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } - for (i, name) in names.iter().enumerate() { - if ui.selectable_label(current == Some(i), name).clicked() { - app.run("camera.select", json!({"index": i})); + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); } } ui.separator(); @@ -213,26 +345,27 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + let label = match app.session.view { ViewMode::MeshMap(map) => crate::i18n::baked_map_label(map).to_owned(), _ => app.session.view.label(), }; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(130.0).selected_text(tr(&label)).show_ui(&mut child, |ui| { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut child, |ui| { if ui.selectable_label(app.session.view == ViewMode::Material, tr("Material")).clicked() { app.run("viewport.view", json!({"mode": "material"})); } ui.separator(); - for c in channels { - if ui.selectable_label(app.session.view == ViewMode::Channel(c), tr(c.label())).clicked() { - app.run("viewport.view", json!({"mode": c.id()})); + for channel in channels { + if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { + app.run("viewport.view", json!({"mode": channel.id()})); } } ui.separator(); - for m in BakedMap::ALL { - if ui.selectable_label(app.session.view == ViewMode::MeshMap(m), trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(m)))])).clicked() - { - app.run("viewport.view", json!({"mode": format!("map:{}", m.id())})); + for map in BakedMap::ALL { + let map_label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.selectable_label(app.session.view == ViewMode::MeshMap(map), map_label).clicked() { + app.run("viewport.view", json!({"mode": format!("map:{}", map.id())})); } } ui.separator(); @@ -429,7 +562,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let frame = Frame { view_id: crate::viewport::VIEW_3D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, shade: shade(app), @@ -968,7 +1101,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let scroll = ui.input(|i| i.smooth_scroll_delta.y); if scroll != 0.0 { let old = app.ui.uv_zoom; - let new = (old * (1.0 + scroll * 0.002)).clamp(0.1, 40.0); + let new = (old * (1.0 + scroll * 0.002)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); // Zoom about the cursor. if let Some(hp) = resp.hover_pos() { let c = [(hp.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hp.y - rect.top()) / size.y * 2.0]; @@ -1042,7 +1175,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } let frame = Frame { view_id: VIEW_2D, - size: [(size.x * ui.ctx().pixels_per_point()).max(1.0) as u32, (size.y * ui.ctx().pixels_per_point()).max(1.0) as u32], + size: frame_size_in_pixels(ui, rect), kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs new file mode 100644 index 00000000..d5af8c8f --- /dev/null +++ b/crates/ui-egui/tests/split_divider.rs @@ -0,0 +1,209 @@ +//! The divider between the 3D and 2D views in the split layout resizes them and keeps the pointer from the views + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::UiState; + +/// Narrowest a split view may get, as in `viewport.rs` +const MIN_VIEW_WIDTH: f32 = 16.0; + +/// A press clear of the divider's 8 point grab zone and egui's 5 point interact radius +const BESIDE_DIVIDER: f32 = 16.0; + +/// App storage held in memory, saved the way the app saves its state between runs +#[derive(Default)] +struct MemoryStorage(std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} + +/// The sample project in the default split layout at 1600 x 960 +fn split_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Drag with `button` from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// The divider's x position: the 3D view ends 1 point left of it +fn divider_x(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.state().viewport_rect.right() + 1.0 +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The 2D view's texture as drawn: its centre's offset from the view's centre and its half width and height, in pixels at 1 point per pixel +fn uv_texture_on_screen(harness: &Harness<'_, TextureCraftApp>, views_right: f32) -> [f32; 4] { + let app = harness.state(); + + // egui draws the view's frame into its rect rounded to whole pixels + let width = views_right.round() - (divider_x(harness) + 1.0).round(); + let height = app.viewport_rect.bottom().round() - app.viewport_rect.top().round(); + let texture_size = app.session.doc.project.texture_sets[app.session.ts()].size(); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(width / height, app.ui.uv_zoom, texture_size); + let [pan_x, pan_y] = app.ui.uv_pan; + [pan_x * width * 0.5, pan_y * height * 0.5, scale_x * width * 0.5, scale_y * height * 0.5] +} + +/// The 3D camera's yaw and pitch +fn camera_angles(harness: &Harness<'_, TextureCraftApp>) -> (f32, f32) { + let camera = &harness.state().session.camera; + (camera.yaw, camera.pitch) +} + +#[test] +fn dragging_the_divider_resizes_the_views_within_their_minimum_width() { + let mut harness = split_app(); + let views_left = harness.state().viewport_rect.left(); + let start_x = divider_x(&harness); + let views_width = (start_x - views_left) * 2.0; + let views_right = views_left + views_width; + let y = harness.state().viewport_rect.center().y; + assert_eq!(harness.state().ui.split_ratio, 0.5); + + drag(&mut harness, PointerButton::Primary, pos2(start_x, y), pos2(start_x - 200.0, y)); + assert!((divider_x(&harness) - (start_x - 200.0)).abs() < 0.5, "follows the pointer: {}", divider_x(&harness)); + assert!((harness.state().ui.split_ratio - (start_x - 200.0 - views_left) / views_width).abs() < 1e-3); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_left + 10.0, y)); + assert!((divider_x(&harness) - views_left - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the left: {}", divider_x(&harness)); + + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(views_right - 10.0, y)); + assert!((views_right - divider_x(&harness) - MIN_VIEW_WIDTH).abs() < 0.5, "clamped on the right: {}", divider_x(&harness)); +} + +#[test] +fn pressing_on_the_divider_neither_paints_nor_moves_the_camera() { + let mut harness = split_app(); + + // Pan the texture's centre under the divider so a press there would paint if the 2D view got it + harness.state_mut().ui.uv_pan[0] = -1.0; + harness.run_steps(2); + let x = divider_x(&harness); + let y = harness.state().viewport_rect.center().y; + let (tiles, angles) = (painted_tiles(&harness), camera_angles(&harness)); + + harness.hover_at(pos2(x, y)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: pos2(x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(x, y + 120.0)); + drag(&mut harness, PointerButton::Secondary, pos2(x, y), pos2(x + 120.0, y)); + assert_eq!(painted_tiles(&harness), tiles, "nothing painted"); + assert_eq!(camera_angles(&harness), angles, "no orbit"); + assert_eq!(divider_x(&harness), x, "a vertical or right-button drag leaves the divider in place"); + + // Beside the divider the views get the same input again + drag(&mut harness, PointerButton::Primary, pos2(x + BESIDE_DIVIDER, y), pos2(x + BESIDE_DIVIDER, y + 40.0)); + assert!(painted_tiles(&harness) > tiles, "the 2D view paints"); + drag(&mut harness, PointerButton::Secondary, pos2(x - BESIDE_DIVIDER, y), pos2(x - BESIDE_DIVIDER - 120.0, y)); + assert_ne!(camera_angles(&harness), angles, "the 3D view orbits"); +} + +#[test] +fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { + let mut storage = MemoryStorage::default(); + let mut ui_state = UiState::default(); + ui_state.split_ratio = 0.3; + eframe::set_value(&mut storage, "ui", &ui_state); + let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + assert_eq!(restored.split_ratio, 0.3); + + // A state saved before the divider existed has no ratio + let saved = storage.0.get("ui").cloned().unwrap(); + let without_ratio = saved.replace("split_ratio:0.3,", ""); + assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); + storage.0.insert("ui".to_owned(), without_ratio); + let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + assert_eq!(restored.split_ratio, 0.5); +} + +#[test] +fn dragging_the_divider_keeps_the_uv_texture_size_and_offset_on_screen() { + // Zoomed in, a 2D sliver needs a zoom far past the one the view starts with + for zoom in [1.0, 4.0] { + let mut harness = split_app(); + harness.state_mut().ui.uv_zoom = zoom; + harness.state_mut().ui.uv_pan = [0.2, 0.1]; + harness.run_steps(2); + // The split starts centred, so the views end as far right of the divider as they start left of it + let views_left = harness.state().viewport_rect.left(); + let views_right = views_left + (divider_x(&harness) - views_left) * 2.0; + let y = harness.state().viewport_rect.center().y; + let before = uv_texture_on_screen(&harness, views_right); + + let assert_unchanged = |harness: &Harness<'_, TextureCraftApp>| { + let after = uv_texture_on_screen(harness, views_right); + for (was, is) in before.iter().zip(after) { + assert!((was - is).abs() < 0.5, "zoom {zoom}, divider at {}: {before:?} became {after:?}", divider_x(harness)); + } + }; + + for to in [views_left + 300.0, views_right - 150.0, views_right - 10.0, views_left + 500.0] { + let x = divider_x(&harness); + drag(&mut harness, PointerButton::Primary, pos2(x, y), pos2(to, y)); + assert_unchanged(&harness); + } + + // A slow drag past the right end, checked every frame for a nudge at the pixel rounding or the stop + let from = pos2(divider_x(&harness), y); + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + let mut pointer_x = from.x; + while pointer_x < views_right + 20.0 { + // Not a whole number of pixels, so the divider lands at every kind of rounding + pointer_x += 3.3; + harness.hover_at(pos2(pointer_x, y)); + harness.run_steps(1); + assert_unchanged(&harness); + } + harness.event(Event::PointerButton { pos: pos2(pointer_x, y), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert_unchanged(&harness); + + // Inside the wheel's 0.1 to 40 range, so the next scroll in the narrow view can't snap the zoom + let stopped_zoom = harness.state().ui.uv_zoom; + assert!((0.1..=40.0).contains(&stopped_zoom), "zoom {zoom} stopped at {stopped_zoom}"); + } +} From d60fb856c900113f7245a7563d0a549c4e2a4ee6 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:24 +0400 Subject: [PATCH 038/275] Live bake preview: the 3D view shows each mesh map as it finishes A bake started in the app bakes the set's maps one after another (BakeTask::run_streaming, one bake per map, same pixels as a single bake) and streams each finished map from the worker thread. One map is installed per UI poll into the session's bake preview (not the document); the 3D view follows the newest map raw on the model, with maps and sets not baked yet shown neutral, and the bake bar names the stage. The bake bar picks Follow Newest Map, a finished map or Material. The previous view mode comes back when the bake ends, is cancelled or Bake mode is left; painting is paused while a bake is shown. bake.preview, ui.bake.start and ui.bake.cancel expose it on the control channel. New strings are translated in every shipped language. --- crates/engine/src/bake/bake_task.rs | 61 ++++++- crates/engine/src/bake/mod.rs | 2 +- crates/engine/src/bake_preview.rs | 243 +++++++++++++++++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/inspect.rs | 1 + crates/engine/src/lib.rs | 4 +- crates/engine/src/painting.rs | 12 ++ crates/engine/src/session.rs | 3 + crates/engine/src/view_cmds.rs | 8 +- crates/engine/tests/bake_preview.rs | 183 ++++++++++++++++++++ crates/render/src/mesh_maps.rs | 13 ++ crates/ui-egui/src/bake_mode.rs | 43 +++++ crates/ui-egui/src/control.rs | 35 ++++ crates/ui-egui/src/gpu.rs | 15 +- crates/ui-egui/src/i18n/ar.rs | 11 ++ crates/ui-egui/src/i18n/de.rs | 11 ++ crates/ui-egui/src/i18n/es.rs | 11 ++ crates/ui-egui/src/i18n/fr.rs | 11 ++ crates/ui-egui/src/i18n/it.rs | 11 ++ crates/ui-egui/src/i18n/ja.rs | 11 ++ crates/ui-egui/src/i18n/ko.rs | 11 ++ crates/ui-egui/src/i18n/pt_br.rs | 11 ++ crates/ui-egui/src/i18n/zh_hans.rs | 8 + crates/ui-egui/src/lib.rs | 92 ++++++++-- crates/ui-egui/src/viewport.rs | 4 +- crates/ui-egui/tests/bake_preview.rs | 98 +++++++++++ docs/control-protocol.md | 36 +++- docs/features.md | 2 + 28 files changed, 931 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/bake_preview.rs create mode 100644 crates/engine/tests/bake_preview.rs create mode 100644 crates/ui-egui/tests/bake_preview.rs diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 831a7abc..efe2a635 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -2,7 +2,7 @@ use super::MergedHigh; use crate::{EngineError, Result}; use std::sync::Arc; use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; -use texturecraft_core::BakeSettings; +use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; /// A self-contained bake task that can run on another thread. @@ -24,8 +24,65 @@ pub struct BakeTask { pub tracer: Option>, } +/// One finished map of a streamed bake (see [`BakeTask::run_streaming`]). +#[derive(Clone, Debug)] +pub struct StreamedMap { + pub map: BakedMap, + /// Position among the maps this bake makes, from 0, and how many there are. + pub index: usize, + pub total: usize, + /// Width and height in texels. + pub resolution: u32, + pub height: u32, + /// Row-major, `map.components()` floats per texel, padded. + pub data: Arc>, +} + impl BakeTask { + /// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them. + pub fn maps(&self) -> Vec { + self.settings.maps.enabled().collect() + } + + /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, + /// and return all of them together. Each map is a bake of its own, so with a high poly + /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several + /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. + /// A cancel or an error leaves the maps already handed over whole. + pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { + let maps = self.maps(); + let total = maps.len(); + let mut combined: Option = None; + for (index, map) in maps.into_iter().enumerate() { + let mut settings = self.settings.clone(); + settings.maps.select([map]); + let mut output = self.run_with(&settings, progress)?; + let Some(data) = output.maps.remove(&map) else { continue }; + let data = Arc::new(data); + on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() }); + let pixels = Arc::try_unwrap(data).unwrap_or_else(|shared| shared.as_ref().clone()); + match &mut combined { + Some(all) => { + all.maps.insert(map, pixels); + } + None => { + output.maps.clear(); + output.maps.insert(map, pixels); + combined = Some(output); + } + } + } + match combined { + Some(output) => Ok(output), + None => self.run(progress), + } + } + pub fn run(&self, progress: &Progress) -> Result { + self.run_with(&self.settings, progress) + } + + fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result { let high = self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); let request = BakeRequest { @@ -33,7 +90,7 @@ impl BakeTask { mesh: &self.mesh, bvh: &self.bvh, material: self.material, - settings: &self.settings, + settings, high, cage: self.cage.as_deref(), skew: self.skew.as_deref(), diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 075943b3..ef4cffcf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -5,7 +5,7 @@ mod merged_high; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; -pub use bake_task::BakeTask; +pub use bake_task::{BakeTask, StreamedMap}; pub use merged_high::MergedHigh; type MaterialColors = std::sync::Arc>>>; diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs new file mode 100644 index 00000000..4ff8822c --- /dev/null +++ b/crates/engine/src/bake_preview.rs @@ -0,0 +1,243 @@ +//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon +//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in +//! the document: nothing enters the undo history until a texture set's bake is applied +//! ([`Session::apply_bake`]), and a cancelled bake leaves the document as it was. The preview +//! shows one map at a time, raw on the model; maps and texture sets not baked yet show their +//! neutral value. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +use crate::bake_data::StreamedMap; +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::session::ViewMode; +use crate::{Result, Session, cmd}; + +/// What painting says while a bake preview shows (the app translates it). +pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.preview", + "Bake preview", + [], + None, + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + always, + preview + )] +} + +/// What the 3D view shows while a bake runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewShow { + /// The newest finished map (the first one, still neutral, before any is done). + Follow, + /// One map, pinned: neutral until it is baked. + Pin(BakedMap), + /// The lit material. + Material, +} + +impl PreviewShow { + pub fn id(self) -> String { + match self { + PreviewShow::Follow => "follow".into(), + PreviewShow::Pin(map) => format!("map:{}", map.id()), + PreviewShow::Material => "material".into(), + } + } + + pub fn parse(text: &str) -> Option { + match text { + "follow" => Some(PreviewShow::Follow), + "material" => Some(PreviewShow::Material), + _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin), + } + } +} + +/// The maps of one texture set streamed so far. +#[derive(Clone, Debug, Default)] +pub struct PreviewSet { + pub baked: BakedMaps, + /// The maps this set's bake makes, in the order they arrive. + pub order: Vec, +} + +/// The map a bake is working on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stage { + pub texture_set: usize, + pub map: BakedMap, + /// 1-based position among the set's maps, and how many there are. + pub position: usize, + pub total: usize, +} + +#[derive(Clone, Debug)] +pub struct BakePreview { + /// The view mode to put back when the preview ends. + pub restore: ViewMode, + pub show: PreviewShow, + pub sets: BTreeMap, + /// The texture set being baked. + pub current: Option, + /// The last map that finished. + pub newest: Option, +} + +impl BakePreview { + /// The map the view shows, None for the material. + pub fn shown(&self) -> Option { + match self.show { + PreviewShow::Material => None, + PreviewShow::Pin(map) => Some(map), + PreviewShow::Follow => self + .newest + .or_else(|| self.current_set().and_then(|set| set.order.first().copied())) + .or_else(|| self.sets.values().find_map(|set| set.order.first().copied())), + } + } + + pub fn current_set(&self) -> Option<&PreviewSet> { + self.sets.get(&self.current?) + } + + /// The map being baked now (None between sets and once the set's maps are all in). + pub fn stage(&self) -> Option { + let texture_set = self.current?; + let set = self.sets.get(&texture_set)?; + let done = set.baked.maps.len(); + Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() }) + } +} + +impl Session { + /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view + /// follows the newest map and every set shows neutral values until its maps arrive. The + /// view mode in use comes back with [`Session::bake_preview_end`]. + pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) { + let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore); + let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect(); + self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None }); + self.bake_preview_refresh(); + } + + /// The texture set whose maps stream in now. + pub fn bake_preview_set_current(&mut self, texture_set: usize) { + if let Some(preview) = &mut self.bake_preview { + preview.current = Some(texture_set); + } + self.bake_preview_refresh(); + } + + /// Install one finished map of set `texture_set`. Returns false when no preview shows. + pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool { + let Some(preview) = &mut self.bake_preview else { return false }; + let set = preview.sets.entry(texture_set).or_default(); + // A new bake of the set starts from nothing (the baker never repeats a map) + if streamed.index == 0 { + set.baked = BakedMaps::default(); + } + set.baked.resolution = streamed.resolution; + set.baked.maps.insert(streamed.map, streamed.data); + preview.newest = Some(streamed.map); + self.bake_preview_refresh(); + true + } + + /// Choose what the view shows (Follow, a pinned map or the material). + pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> { + let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) }; + preview.show = show; + self.bake_preview_refresh(); + Ok(()) + } + + /// The user picked a view mode during a bake: a mesh map pins it, any other mode shows + /// the material and is what comes back when the bake ends. + pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) { + let Some(preview) = &mut self.bake_preview else { return }; + match view { + ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map), + other => { + preview.show = PreviewShow::Material; + preview.restore = other; + } + } + self.bake_preview_refresh(); + if !matches!(view, ViewMode::MeshMap(_)) { + self.view = view; + } + } + + /// The bake is over, cancelled or no longer shown: put the previous view mode back. + pub fn bake_preview_end(&mut self) { + if let Some(preview) = self.bake_preview.take() { + self.view = preview.restore; + self.revision = self.revision.wrapping_add(1); + } + } + + pub fn bake_preview_active(&self) -> bool { + self.bake_preview.is_some() + } + + /// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked + /// yet: neutral values), None when the document's baked maps are what shows. + pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> { + self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked) + } + + /// Why painting is not possible now, when a bake preview shows. + pub fn painting_blocked(&self) -> Option<&'static str> { + self.bake_preview.as_ref().map(|_| PAINTING_PAUSED) + } + + fn bake_preview_refresh(&mut self) { + let Some(preview) = &self.bake_preview else { return }; + self.view = match preview.shown() { + Some(map) => ViewMode::MeshMap(map), + None => ViewMode::Material, + }; + self.revision = self.revision.wrapping_add(1); + } +} + +/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`. +pub fn preview_json(session: &Session) -> Value { + let Some(preview) = &session.bake_preview else { return json!({ "active": false }) }; + let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total })); + let sets: Vec = preview + .sets + .iter() + .map(|(texture_set, set)| { + json!({ + "set": texture_set, + "order": set.order.iter().map(|map| map.id()).collect::>(), + "done": set.baked.maps.keys().map(|map| map.id()).collect::>(), + }) + }) + .collect(); + json!({ + "active": true, + "show": preview.show.id(), + "shown": preview.shown().map(|map| map.id()), + "newest": preview.newest.map(|map| map.id()), + "restore": preview.restore.label(), + "stage": stage, + "sets": sets, + }) +} + +fn preview(session: &mut Session, params: &Value) -> Result { + if let Some(show) = strp(params, "show") { + let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?; + session.bake_preview_show(show)?; + } + Ok(preview_json(session)) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 94bb350c..31d2f692 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -69,6 +69,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::bake_preview::specs()); v.extend(crate::bake_paint_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..5f40a62c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -168,6 +168,7 @@ pub fn session(s: &Session) -> Value { "layers": stack(s, ts), "tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) }, "view": s.view.label(), + "bakePreview": crate::bake_preview::preview_json(s), "camera": crate::view_cmds::camera_json(s), "display": s.doc.project.display, "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..9478de8f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod bake_cmds; #[path = "bake/mod.rs"] mod bake_data; mod bake_paint_cmds; +pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; @@ -48,7 +49,8 @@ pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake_data::{BakeMesh, BakeMeshes, BakeTask, StreamedMap}; +pub use bake_preview::{BakePreview, PreviewShow}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use path_tool::PathState; pub use project_cmds::sample_session; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..f4e93f40 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -135,6 +135,7 @@ impl Session { /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh /// (the Clone tool's destination anchor). fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; @@ -276,9 +277,18 @@ impl Session { Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) } + /// Painting is paused while a bake preview shows the baked maps instead of the material. + fn refuse_while_baking(&self) -> Result<()> { + match self.painting_blocked() { + Some(why) => Err(EngineError::Other(why.into())), + None => Ok(()), + } + } + /// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the /// mesh (the stroke starts anyway and resumes when the cursor enters the mesh). pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result { + self.refuse_while_baking()?; self.cancel_stroke(); match self.tool.tool { Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true), @@ -293,6 +303,7 @@ impl Session { /// Start a stroke in the 2D view at texture coordinate `uv`. pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { + self.refuse_while_baking()?; self.cancel_stroke(); if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) { return Err(EngineError::Other("use this tool in the 3D view".into())); @@ -474,6 +485,7 @@ impl Session { /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + self.refuse_while_baking()?; let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; let ts = self.ts(); let material = self.doc.project.texture_set(ts)?.material; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..31cd5519 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -334,6 +334,8 @@ pub struct Session { pub target: StackTarget, pub camera: OrbitCamera, pub view: ViewMode, + /// The live bake preview while the app bakes (see [`crate::bake_preview`]). + pub bake_preview: Option, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -393,6 +395,7 @@ impl Session { target: StackTarget::Content, camera, view: ViewMode::Material, + bake_preview: None, viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index b39c876d..9fb03ecf 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result { } fn set_view(s: &mut Session, v: ViewMode) -> Result { - s.view = v; + if s.bake_preview.is_some() { + // During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards + s.bake_preview_user_view(v); + } else { + s.view = v; + } + let v = s.view; s.revision = s.revision.wrapping_add(1); Ok(json!({ "view": v.label() })) } diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs new file mode 100644 index 00000000..b2330721 --- /dev/null +++ b/crates/engine/tests/bake_preview.rs @@ -0,0 +1,183 @@ +//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, +//! painting is paused, a cancelled bake leaves the document alone, and the streamed pixels are +//! the ones a single bake makes. + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeResolution, BakedMap, Channel}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute}; + +const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height]; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + session +} + +fn task(session: &Session) -> BakeTask { + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + task +} + +fn order(session: &Session) -> Vec { + task(session).maps() +} + +#[test] +fn streamed_maps_are_the_pixels_of_one_bake() { + let session = session(); + let task = task(&session); + let whole = task.run(&Progress::new()).unwrap(); + let mut streamed = Vec::new(); + let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), order(&session)); + assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::>()); + assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height)); + assert_eq!(combined.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert!(combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake"); + } + for map in &streamed { + assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map); + } +} + +#[test] +fn the_view_follows_each_map_and_the_previous_mode_comes_back() { + let mut session = session(); + session.view = ViewMode::Channel(Channel::Roughness); + let before = session.view; + let baked_before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + // Nothing is baked yet: the first map shows, neutral + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty())); + + let task = task(&session); + let mut shown = Vec::new(); + let mut stages = Vec::new(); + let output = task + .run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + shown.push(session.view); + stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total))); + }) + .unwrap(); + assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::>(), "the view follows the newest map"); + assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map"); + assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied"); + let undo_before = session.undo_label().map(str::to_owned); + + session.apply_bake(0, output).unwrap(); + assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step"); + session.bake_preview_end(); + assert_eq!(session.view, before, "the previous view mode is restored"); + assert!(!session.bake_preview_active()); + assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn pinning_material_and_follow() { + let mut session = session(); + let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let task = task(&session); + let mut count = 0; + task.run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + count += 1; + match count { + // Pin the finished map: later maps do not take the view + 1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(), + 2 => { + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + session.bake_preview_show(PreviewShow::Material).unwrap(); + } + 3 => { + assert_eq!(session.view, ViewMode::Material); + session.bake_preview_show(PreviewShow::Follow).unwrap(); + assert_eq!(session.view, ViewMode::MeshMap(maps[2])); + } + _ => {} + } + }) + .unwrap(); + // A mesh map picked in the viewport pins it; another mode is what comes back at the end + execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap(); + assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height))); + execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap(); + assert_eq!(session.view, ViewMode::UvChecker); + session.bake_preview_end(); + assert_eq!(session.view, ViewMode::UvChecker); +} + +#[test] +fn unbaked_sets_show_neutral_and_the_control_command_reports() { + let mut session = session(); + assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs"); + session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]); + session.bake_preview_set_current(0); + assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet"); + assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps"); + let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap(); + assert_eq!( + (reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()), + (json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion")) + ); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err()); + assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true); +} + +#[test] +fn painting_is_refused_while_a_bake_shows() { + let mut session = session(); + session.bake_preview_begin(vec![(0, order(&session))]); + let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string(); + assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED); + assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err()); + assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err()); + assert!(!session.stroke_active()); + session.bake_preview_end(); + assert!(session.painting_blocked().is_none()); +} + +#[test] +fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { + let mut session = session(); + let before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + let full = task(&session).run(&Progress::new()).unwrap(); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let progress = Progress::new(); + let task = task(&session); + let result = task.run_streaming(&progress, &mut |map| { + if map.index == 1 { + progress.cancel(); + } + session.bake_preview_map(0, map); + }); + assert!(result.is_err(), "a cancelled bake fails"); + // The two maps that landed are whole and equal to a full bake's; the others are still neutral + let shown = session.bake_preview_baked(0).unwrap(); + assert_eq!(shown.maps.len(), 2); + for (map, data) in &shown.maps { + assert!(**data == full.maps[map], "{map:?}"); + } + // What the app does on cancel: end the preview; the document keeps what it had + session.bake_preview_end(); + assert_eq!(session.doc.baked.get(&0).cloned(), before); + assert!(session.bake_preview_baked(0).is_none()); +} diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index bf811478..8c246ee6 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -25,3 +25,16 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec Vec { + let value = m.neutral(); + let pixel = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + let size = size.max(1); + let mut out = Vec::with_capacity((size * size * 4) as usize); + for _ in 0..size * size { + out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]); + } + out +} diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs index c0397a49..dd47102a 100644 --- a/crates/ui-egui/src/bake_mode.rs +++ b/crates/ui-egui/src/bake_mode.rs @@ -61,16 +61,59 @@ fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, conten } } +/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material +fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::PreviewShow; + let Some(preview) = app.session.bake_preview.as_ref() else { return }; + let show = preview.show; + // Finished maps of the set baking now can be pinned; the others are still neutral + let rows: Vec<(BakedMap, bool)> = + preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default(); + let text = match show { + PreviewShow::Follow => tr("Follow Newest Map").to_owned(), + PreviewShow::Material => tr("Material").to_owned(), + PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]), + }; + let mut choice = None; + egui::ComboBox::from_id_salt("bake_preview_show") + .selected_text(text) + .show_ui(ui, |ui| { + if ui.selectable_label(show == PreviewShow::Follow, tr("Follow Newest Map")).clicked() { + choice = Some(PreviewShow::Follow); + } + for (map, done) in rows { + let label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.add_enabled(done, egui::Button::selectable(show == PreviewShow::Pin(map), label)).clicked() { + choice = Some(PreviewShow::Pin(map)); + } + } + if ui.selectable_label(show == PreviewShow::Material, tr("Material")).clicked() { + choice = Some(PreviewShow::Material); + } + }) + .response + .on_hover_text(tr( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + )); + if let Some(show) = choice { + app.run("bake.preview", json!({ "show": show.id() })); + } +} + pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( ctx, |ui| { + if let Some(status) = app.bake_status() { + ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong())); + } ui.horizontal(|ui| { if let Some(progress) = app.bake_progress() { ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); if ui.button(tr("Cancel")).clicked() { app.cancel_bake(); } + preview_control(app, ui); } else { let texture_sets: Vec = app .session diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 167b9754..fa73e485 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -110,9 +110,44 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "uiMs": app.ui_ms, "titleBar": app.title_bar.name(), "baking": app.bake_progress(), + "bakeStatus": app.bake_status(), + "bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session), "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), })) } + "ui.bake.start" => { + // Bake in the background like the Bake button: the 3D view shows the maps as they finish + let count = app.session.doc.project.texture_sets.len(); + let sets: Vec = match p.get("ts") { + Some(value) => match serde_json::from_value::>(if value.is_array() { value.clone() } else { json!([value]) }) { + Ok(list) if list.iter().all(|&index| index < count) => list, + _ => return err(format!("`ts` must be texture set indices below {count}")), + }, + None => app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) + .map(|(index, _)| index) + .collect(), + }; + if app.bake.is_some() { + return err("a bake is already running"); + } + if sets.is_empty() { + return err("no texture set to bake: tick one in Bake mode or pass `ts`"); + } + app.ui.mode = crate::state::Mode::Baking; + app.start_bake(sets); + ok(texturecraft_engine::bake_preview::preview_json(&app.session)) + } + "ui.bake.cancel" => { + app.cancel_bake(); + ok(Value::Null) + } "ui.menu.list" => ok(json!( crate::menus::CATALOG .iter() diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..d33cfad5 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -211,13 +211,22 @@ impl GpuLink { match aux_map { Some(AuxView::MeshMap(m)) => { for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); + // While a bake shows, its streamed maps (neutral where not baked yet) replace the document's + let preview = s.bake_preview_baked(ts); + let baked = preview.or_else(|| s.doc.baked.get(&ts)); + let have = baked.and_then(|b| b.maps.get(&m)); + let rev = have.map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); + let key = (format!("{m:?}{}", if preview.is_some() { "~" } else { "" }), rev); if self.aux.get(&ts) == Some(&key) { continue; } let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res))); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(m, res) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, m, res) + }; + out.aux.push((ts, res, rgba)); self.aux.insert(ts, key); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..8d49896a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1,6 +1,17 @@ //! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "جارٍ خبز {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "جارٍ خبز {map} ({n}/{total})، مجموعة الخامات {set} من {sets}"), + ("Follow Newest Map", "تتبّع أحدث خريطة"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "الرسم متوقف مؤقتًا أثناء عرض عملية الخبز. ألغِ الخبز أو انتظر حتى ينتهي.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ما يعرضه العرض ثلاثي الأبعاد أثناء الخبز: أحدث خريطة مكتملة، أو أي خريطة مكتملة تختارها، أو الخامة. الخرائط التي لم تُخبز بعد تعرض قيمة محايدة.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), ("2D view only", "عرض ثنائي الأبعاد فقط"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..0272179e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1,6 +1,17 @@ //! German UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} wird gebacken ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} wird gebacken ({n}/{total}), Texturset {set} von {sets}"), + ("Follow Newest Map", "Neueste Map verfolgen"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "Das Malen ist pausiert, solange ein Bake angezeigt wird. Brich den Bake ab oder warte, bis er fertig ist.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Was die 3D-Ansicht während des Backens zeigt: die zuletzt fertige Map, eine fertige Map deiner Wahl oder das Material. Noch nicht gebackene Maps zeigen einen neutralen Wert.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), ("2D view only", "Nur 2D-Ansicht"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..c1b91d79 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1,6 +1,17 @@ //! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Horneando {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Horneando {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir el mapa más reciente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pintura está en pausa mientras se muestra un horneado. Cancela el horneado o espera a que termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Lo que muestra la vista 3D mientras se hornea: el último mapa terminado, un mapa terminado a elección o el material. Los mapas aún sin hornear muestran un valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), ("2D view only", "Solo vista 2D"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..e47e5c17 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,6 +1,17 @@ //! French UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Cuisson de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Cuisson de {map} ({n}/{total}), jeu de textures {set} sur {sets}"), + ("Follow Newest Map", "Suivre la dernière carte"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La peinture est suspendue tant qu'une cuisson est affichée. Annulez la cuisson ou attendez qu'elle se termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Ce que la vue 3D affiche pendant la cuisson : la dernière carte terminée, une carte terminée au choix ou le matériau. Les cartes pas encore cuites affichent une valeur neutre.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..f851dfc5 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1,6 +1,17 @@ //! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Bake di {map} in corso ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Bake di {map} in corso ({n}/{total}), set di texture {set} di {sets}"), + ("Follow Newest Map", "Segui la mappa più recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pittura è in pausa finché viene mostrato un bake. Annulla il bake o attendi che finisca.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Cosa mostra la vista 3D durante il bake: l'ultima mappa completata, una mappa completata a scelta o il materiale. Le mappe non ancora create mostrano un valore neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), ("2D view only", "Solo vista 2D"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..b190dc04 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1,6 +1,17 @@ //! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} をベイク中 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} をベイク中 ({n}/{total})、テクスチャセット {set}/{sets}"), + ("Follow Newest Map", "最新のマップを追う"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "ベイクの表示中はペイントを一時停止しています。ベイクをキャンセルするか、終わるまでお待ちください。", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ベイク中に3Dビューが表示するもの:最後に完成したマップ、完成済みの好きなマップ、またはマテリアル。まだベイクされていないマップは中立値で表示されます。", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..d9d1fcda 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1,6 +1,17 @@ //! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} 베이크 중 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} 베이크 중 ({n}/{total}), 텍스처 세트 {set}/{sets}"), + ("Follow Newest Map", "최신 맵 따라가기"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "베이크를 표시하는 동안에는 페인팅이 일시 중지됩니다. 베이크를 취소하거나 끝날 때까지 기다리세요.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "베이크하는 동안 3D 뷰가 보여 주는 것: 가장 최근에 완료된 맵, 완료된 맵 중 선택한 하나, 또는 머티리얼. 아직 베이크되지 않은 맵은 중립 값으로 표시됩니다.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..ae44b364 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1,6 +1,17 @@ //! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Fazendo o bake de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Fazendo o bake de {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir o mapa mais recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "A pintura fica em pausa enquanto um bake é exibido. Cancele o bake ou espere ele terminar.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "O que a vista 3D mostra durante o bake: o último mapa concluído, um mapa concluído à escolha ou o material. Mapas ainda não gerados mostram um valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), ("2D view only", "Apenas vista 2D"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..552242b4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1,6 +1,14 @@ //! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "正在烘焙{map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "正在烘焙{map} ({n}/{total}),纹理集 {set}/{sets}"), + ("Follow Newest Map", "跟随最新贴图"), + ("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", "显示烘焙时已暂停绘制。请取消烘焙,或等待其完成。"), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "烘焙过程中 3D 视图显示的内容:最新完成的贴图、任意已完成的贴图,或材质。尚未烘焙的贴图显示中性值。", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), ("2D view only", "仅 2D 视图"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..b4ed93d0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -47,10 +47,22 @@ pub struct ResizeJob { pub rx: std::sync::mpsc::Receiver>, } +/// The texture set baking on a worker thread: its progress, its result and the maps it finishes +/// on the way (the 3D view shows one per UI poll). +pub struct RunningBake { + pub set_index: usize, + pub progress: Arc, + pub receiver: std::sync::mpsc::Receiver>, + pub maps: std::sync::mpsc::Receiver, + /// Maps finished so far, and how many the set makes. + pub maps_done: Arc, + pub maps_total: usize, +} + /// A background bake of one or more texture sets. pub struct BakeJob { pub queue: Vec, - pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, + pub current: Option, pub total: usize, } @@ -62,6 +74,9 @@ pub struct LinkCook { pub rx: std::sync::mpsc::Receiver>>, } +/// The engine's refusal to paint while a bake shows (translated where it is toasted). +pub const PAINTING_PAUSED: &str = i18n::n_("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."); + /// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2. pub const WEBGL_NOTICE: &str = i18n::n_( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", @@ -208,6 +223,16 @@ impl TextureCraftApp { return; } let total = sets.len(); + // The 3D view shows the maps landing on the model while they bake + let orders = sets + .iter() + .map(|&set_index| { + let maps = + self.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.maps.enabled().collect()).unwrap_or_default(); + (set_index, maps) + }) + .collect(); + self.session.bake_preview_begin(orders); self.bake = Some(BakeJob { queue: sets, current: None, total }); } @@ -261,13 +286,27 @@ impl TextureCraftApp { } fn poll_bake(&mut self, ctx: &egui::Context) { - let Some(job) = self.bake.as_mut() else { return }; + // Leaving Bake mode puts the view mode back; the bake goes on + if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { + self.session.bake_preview_end(); + } + let Some(job) = self.bake.as_mut() else { + // A preview whose bake is gone must not keep the view + self.session.bake_preview_end(); + return; + }; ctx.request_repaint_after(std::time::Duration::from_millis(50)); - if let Some((set_index, _, receiver)) = &job.current { - match receiver.try_recv() { + if let Some(running) = &job.current { + let set_index = running.set_index; + // One streamed map per poll, so each lands on the model in its own frame. The worker + // sends every map before its result, so the last map shows before the bake is applied + if let Ok(map) = running.maps.try_recv() { + self.session.bake_preview_map(set_index, map); + return; + } + match running.receiver.try_recv() { Ok(Ok(output)) => { - let set_index = *set_index; job.current = None; if let Err(error) = self.session.apply_bake(set_index, output) { self.toast(error.to_string(), true); @@ -290,17 +329,28 @@ impl TextureCraftApp { if job.queue.is_empty() { self.bake = None; + self.session.bake_preview_end(); self.toast(i18n::tr("Mesh maps baked"), false); return; } let set_index = job.queue.remove(0); + self.session.bake_preview_set_current(set_index); match self.session.bake_task(set_index) { Ok(task) => { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); - let receiver = spawn_worker("texturecraft-bake", move || task.run(&worker_progress)); + let maps_total = task.maps().len(); + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let worker_done = maps_done.clone(); + let (sender, maps) = std::sync::mpsc::channel(); + let receiver = spawn_worker("texturecraft-bake", move || { + task.run_streaming(&worker_progress, &mut |map| { + worker_done.fetch_add(1, Ordering::Relaxed); + let _ = sender.send(map); + }) + }); if let Some(job) = self.bake.as_mut() { - job.current = Some((set_index, progress, receiver)); + job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); } } Err(error) => self.toast(error.to_string(), true), @@ -311,9 +361,11 @@ impl TextureCraftApp { pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - if let Some((_, progress, _)) = job.current { - progress.cancel.store(true, Ordering::Relaxed); + if let Some(running) = job.current { + running.progress.cancel.store(true, Ordering::Relaxed); } + // The streamed maps were only shown: the document keeps the maps it had + self.session.bake_preview_end(); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when @@ -351,10 +403,30 @@ impl TextureCraftApp { } /// Bake progress 0..1 across all queued sets. + pub fn bake_status(&self) -> Option { + let job = self.bake.as_ref()?; + let stage = self.session.bake_preview.as_ref()?.stage()?; + let map = i18n::tr(i18n::baked_map_label(stage.map)); + let (n, total) = (stage.position, stage.total); + if job.total > 1 { + let set = job.total - job.queue.len(); + return Some(i18n::trf( + "Baking {map} ({n}/{total}), texture set {set} of {sets}", + &[("map", &map), ("n", &n), ("total", &total), ("set", &set.max(1)), ("sets", &job.total)], + )); + } + Some(i18n::trf("Baking {map} ({n}/{total})", &[("map", &map), ("n", &n), ("total", &total)])) + } + pub fn bake_progress(&self) -> Option { let job = self.bake.as_ref()?; let done = job.total - job.queue.len() - usize::from(job.current.is_some()); - let cur = job.current.as_ref().map(|(_, p, _)| p.fraction()).unwrap_or(0.0); + // Each map is a bake of its own: its progress runs from 0 to 1 within the set's share + let cur = job + .current + .as_ref() + .map(|running| (running.maps_done.load(Ordering::Relaxed) as f32 + running.progress.fraction()) / running.maps_total.max(1) as f32) + .unwrap_or(0.0); Some(((done as f32 + cur) / job.total.max(1) as f32).clamp(0.0, 1.0)) } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da60a42d..1ce473dd 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -405,7 +405,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } app.last_paint_point = Some(local(p)); } - Err(e) => app.toast(e.to_string(), true), + Err(e) => app.toast(tr(&e.to_string()).to_string(), true), } } if resp.clicked_by(PointerButton::Primary) @@ -1017,7 +1017,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if let Some(p) = resp.interact_pointer_pos() && let Err(e) = app.session.begin_stroke_uv(to_uv(p), pressure) { - app.toast(e.to_string(), true); + app.toast(tr(&e.to_string()).to_string(), true); } if resp.clicked_by(PointerButton::Primary) && let Err(e) = app.session.end_stroke() diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs new file mode 100644 index 00000000..a24b2352 --- /dev/null +++ b/crates/ui-egui/tests/bake_preview.rs @@ -0,0 +1,98 @@ +//! Bake mode: while a bake runs the 3D view shows the maps landing on the model, the previous view +//! mode comes back when the bake ends, is cancelled or Bake mode is left, and painting is paused. + +use egui_kittest::Harness; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +const MAPS: [BakedMap; 3] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Height]; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + session.view = ViewMode::UvChecker; + let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + harness +} + +/// Frames until the bake is gone, with the view mode after each one. +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) -> Vec { + let mut seen = Vec::new(); + for _ in 0..4000 { + harness.run_steps(1); + seen.push(harness.state().session.view); + if harness.state().bake.is_none() { + return seen; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + // Right away: the first map shows, still neutral + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[0])); + harness.run_steps(1); + assert!(harness.state().bake_status().is_some_and(|status| status.contains("/3")), "the status line names the stage"); + let seen = run_to_the_end(&mut harness); + // Every requested map was shown at some frame, in request order + let mut shown: Vec = Vec::new(); + for view in seen { + if let ViewMode::MeshMap(map) = view + && shown.last() != Some(&map) + { + shown.push(map); + } + } + assert_eq!(shown, MAPS); + assert_eq!(harness.state().session.view, ViewMode::UvChecker, "the mode in use before the bake is back"); + assert!(!harness.state().session.bake_preview_active()); + assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn cancelling_restores_the_view_and_leaves_the_document_alone() { + let mut harness = harness(); + let before = harness.state().session.doc.baked.get(&0).cloned(); + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + assert!(harness.state().session.bake_preview_active()); + let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); + assert!(harness.state_mut().session.begin_stroke(at, viewport, 1.0).is_err(), "painting is paused"); + harness.state_mut().cancel_bake(); + harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); + assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); +} + +#[test] +fn leaving_bake_mode_closes_the_preview_but_the_bake_goes_on() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active()); + run_to_the_end(&mut harness); + assert!(harness.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Height), "the bake finished and was applied"); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); +} + +#[test] +fn the_painting_message_is_a_translated_key() { + assert_eq!(texturecraft_ui_egui::PAINTING_PAUSED, texturecraft_engine::bake_preview::PAINTING_PAUSED); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..07fd17e5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -62,9 +62,11 @@ keeps its state in a throwaway file. | `command.run` | `{id, params?}` | the command's JSON result | | `command.list` | `{filter?}` | `[{id, label, menu, shortcut, params, enabled}]` | | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | -| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | +| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window) | +| `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | +| `ui.bake.cancel` | | Stops the running bake; the document keeps the maps it had and the previous view mode comes back | | `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -85,6 +87,38 @@ Example session: < {"id":3,"ok":true,"result":{"width":1210,"height":788,"png":"iVBORw0KGgo…"}} ``` +### Live bake preview + +A bake started in the app (`ui.bake.start`, or the Bake button) makes the mesh maps one after +another, in the `BakedMap` order of the set's enabled maps, and shows each one on the model as +soon as it is finished and padded: the 3D view displays the newest finished map raw (normals as +RGB, scalar maps as gray, ID maps as their colors), maps and texture sets not baked yet show their +neutral value, and the bake bar names the stage (`Baking Ambient Occlusion (2/4)`). Each map is a +bake of its own, so with a high poly the transfer rays are cast once per map; the pixels are the +same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. + +The streamed maps are held by the session, not the document: nothing enters the undo history +until a texture set's bake is applied (one undo step), and a cancelled bake changes nothing. When +the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. +**Painting is paused while a bake is shown**: strokes fail with "Painting is paused while a bake +is shown. Cancel the bake or wait for it to finish." + +`bake.preview` `{show?: "follow" \| "material" \| "map:"}` reads and sets what the view shows +(also the control in the bake bar): `follow` (default) the newest finished map, `material` the lit +material, `map:` one map pinned (neutral until it is baked). Picking a mesh map with +`viewport.view` during a bake pins it; any other view mode is kept for when the bake ends. Result, +also `session.inspect`'s `bakePreview`: + +```json +{"active": true, "show": "follow", "shown": "ambientOcclusion", "newest": "ambientOcclusion", + "restore": "Material", "stage": {"set": 0, "map": "curvature", "n": 3, "total": 4}, + "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} +``` + +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + A minimal client (Python, for illustration): ```python diff --git a/docs/features.md b/docs/features.md index fcbaca5f..a51352da 100644 --- a/docs/features.md +++ b/docs/features.md @@ -103,6 +103,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from the slot's menu. A UV-tiled set takes one image per tile, named with its tile number (`ao.1001.png`, `ao.1002.png`…): drop or pick any one of them. +- **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is + finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in From 23a752156cf29c0afef624e5373dadee74b41d55 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 09:47:51 +0000 Subject: [PATCH 039/275] UI: view layout and projection dropdowns in the top bar The 3D/2D, 3D-only and 2D-only buttons become one dropdown showing the current layout's icon, with the same commands and F1-F3 shortcuts. Beside it, a Perspective / Orthographic dropdown sets the camera through camera.set, so orthographic no longer hides in the Display Settings panel. Both use a new icon button with a caret, sharing the icon button style, and the bar's overflow width counts them. Test: picking a layout and Orthographic from the menus sets ui.layout and camera.ortho, and a second click on a dropdown closes its menu. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/toolbar.rs | 86 +++++++++++++++++++++++++----- crates/ui-egui/src/widgets.rs | 43 ++++++++++++--- crates/ui-egui/tests/toolbar.rs | 27 +++++++++- 12 files changed, 144 insertions(+), 21 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..89626724 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -556,6 +556,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "مدار"), ("Orthographic", "متوازي (إملائي)"), + ("Perspective", "منظوري"), ("Output directory", "دليل الإخراج"), ("Output high", "المخرج العالي"), ("Output low", "المخرج المنخفض"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..581cfc2b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -589,6 +589,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbit"), ("Orthographic", "Orthografisch"), + ("Perspective", "Perspektivisch"), ("Output directory", "Ausgabeverzeichnis"), ("Output high", "Ausgabe hoch"), ("Output low", "Ausgabe tief"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..2543cf6e 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -580,6 +580,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Directorio de salida"), ("Output high", "Salida alta"), ("Output low", "Salida baja"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..66093168 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -595,6 +595,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbite"), ("Orthographic", "Orthographique"), + ("Perspective", "Perspective"), ("Output directory", "Dossier de sortie"), ("Output high", "Sortie haute"), ("Output low", "Sortie basse"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..6766d794 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -586,6 +586,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbita"), ("Orthographic", "Ortografica"), + ("Perspective", "Prospettica"), ("Output directory", "Cartella di output"), ("Output high", "Output alto"), ("Output low", "Output basso"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..41bd24a1 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -574,6 +574,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "オービット"), ("Orthographic", "平行投影"), + ("Perspective", "透視投影"), ("Output directory", "出力先フォルダー"), ("Output high", "出力の上限"), ("Output low", "出力の下限"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..62548c58 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -565,6 +565,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "궤도 회전"), ("Orthographic", "직교"), + ("Perspective", "원근"), ("Output directory", "출력 디렉터리"), ("Output high", "출력 상한"), ("Output low", "출력 하한"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..dc86a021 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -577,6 +577,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "Orbitar"), ("Orthographic", "Ortográfica"), + ("Perspective", "Perspectiva"), ("Output directory", "Pasta de saída"), ("Output high", "Saída alta"), ("Output low", "Saída baixa"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..961a09e5 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -520,6 +520,7 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("Orbit", "环绕"), ("Orthographic", "正交"), + ("Perspective", "透视"), ("Output directory", "输出目录"), ("Output high", "输出高"), ("Output low", "输出低"), diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index b2e4d83e..897d305f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -8,10 +8,10 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{tr, trf}; -use crate::keymap::tip; +use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip}; +use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip, icon_dropdown_button, icon_dropdown_button_width}; const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; @@ -65,9 +65,10 @@ pub fn paint_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } +/// Width of `view_buttons`, so the bar knows when to move them into the scrolling strip fn view_buttons_width(button_size: f32, spacing: f32) -> f32 { - // Five icons, two separators and the six gaps between them - 5.0 * button_size + 2.0 * BAR_SEPARATOR_WIDTH + 6.0 * spacing + // Two icons, two dropdowns, two separators and the five gaps between them + 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + 2.0 * BAR_SEPARATOR_WIDTH + 5.0 * spacing } /// View buttons in a right-to-left layout, with the screenshot button at the end @@ -78,15 +79,8 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - for (layout, icon, label, command) in [ - (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), - (ViewLayout::Only3D, ic::CUBE, "3D view only", "ui.layout.3d"), - (ViewLayout::Split, ic::COLUMNS, "3D/2D views", "ui.layout.split"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(label), command), app.ui.layout == layout, button_size).clicked() { - crate::menus::invoke(app, &ui.ctx().clone(), command); - } - } + projection_dropdown(app, ui); + layout_dropdown(app, ui); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; @@ -96,6 +90,72 @@ fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon +fn layout_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + const LAYOUTS: [(ViewLayout, &str, &str, &str); 3] = [ + (ViewLayout::Split, ic::SQUARE_SPLIT_HORIZONTAL, "3D/2D views", "ui.layout.split"), + (ViewLayout::Only3D, ic::SPHERE, "3D view only", "ui.layout.3d"), + (ViewLayout::Only2D, ic::SQUARE, "2D view only", "ui.layout.2d"), + ]; + + let (_, icon, label, command) = LAYOUTS.iter().find(|(layout, ..)| *layout == app.ui.layout).unwrap_or(&LAYOUTS[0]); + let tooltip = tip(&app.ui.keymap, tr(label), command); + let mut chosen = None; + icon_dropdown(ui, "view_layout", icon, &tooltip, |ui| { + for (layout, icon, label, command) in LAYOUTS { + if dropdown_row(ui, icon, tr(label), shortcut_of(&app.ui.keymap, command), app.ui.layout == layout) { + chosen = Some(command); + } + } + }); + + if let Some(command) = chosen { + crate::menus::invoke(app, &ui.ctx().clone(), command); + } +} + +/// Perspective or orthographic projection, the same setting as the Display Settings checkbox +fn projection_dropdown(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + let projections = [(false, ic::PERSPECTIVE, tr("Perspective")), (true, ic::CUBE, tr("Orthographic"))]; + let ortho = app.session.camera.ortho; + let (_, icon, label) = projections.iter().find(|(choice, ..)| *choice == ortho).unwrap_or(&projections[0]); + let mut chosen = None; + icon_dropdown(ui, "view_projection", icon, label, |ui| { + for (choice, icon, label) in projections { + if dropdown_row(ui, icon, label, None, ortho == choice) { + chosen = Some(choice); + } + } + }); + + if let Some(choice) = chosen.filter(|choice| *choice != ortho) { + app.run("camera.set", json!({"ortho": choice})); + } +} + +/// An icon button with a caret that opens `menu` below it, highlighted while open +fn icon_dropdown(ui: &mut egui::Ui, id_salt: &str, icon: &str, tooltip: &str, menu: impl FnOnce(&mut egui::Ui)) { + let button_size = ui.spacing().interact_size.y; + let popup_id = ui.make_persistent_id(id_salt); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id); + let mut response = icon_dropdown_button(ui, icon, tooltip, open, button_size); + if !open { + response = response.on_hover_text(tooltip); + } + + egui::Popup::menu(&response).id(popup_id).show(menu); +} + +/// One dropdown entry: icon, label and shortcut. Returns true when clicked +fn dropdown_row(ui: &mut egui::Ui, icon: &str, label: &str, shortcut: Option<&str>, selected: bool) -> bool { + let mut button = egui::Button::new(format!("{icon} {label}")).selected(selected); + if let Some(shortcut) = shortcut { + button = button.shortcut_text(shortcut); + } + + ui.add(button).clicked() +} + /// Scroll tool controls and, in narrow viewports, the view buttons fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens, scroll_views: bool) { let button_size = ui.spacing().interact_size.y; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 72853550..79aa7eab 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -179,22 +179,51 @@ pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) } +/// Icon glyph size as a fraction of the button height +const ICON_SCALE: f32 = 0.62; + +/// Extra width an `icon_dropdown_button` gives its caret, as a fraction of the button height +const CARET_STRIP_SCALE: f32 = 0.34; + /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - let tokens = Tokens::get(ui.ctx()); + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + }) +} + +/// Width of an `icon_dropdown_button` `size` high: the square icon and the caret strip after it +pub fn icon_dropdown_button_width(size: f32) -> f32 { + size * (1.0 + CARET_STRIP_SCALE) +} + +/// An `icon_button_without_tooltip` with a dropdown caret after the icon, drawn in the icon's color +pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { + // Caret glyph size, and how far its center sits from the right edge, as fractions of the height + const CARET_SCALE: f32 = 0.34; + const CARET_INSET_SCALE: f32 = 0.25; + + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { + let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text(icon_center, egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * ICON_SCALE), color); + ui.painter().text(caret_center, egui::Align2::CENTER_CENTER, egui_phosphor::regular::CARET_DOWN, egui::FontId::proportional(size * CARET_SCALE), color); + }) +} + +/// Transparent at rest, a hover well, and the active-tool well when pressed or selected +fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; - let style = IconButtonStyle { + IconButtonStyle { normal: well(Color32::TRANSPARENT, tokens.text), hovered: well(tokens.row_hover, tokens.text_strong), pressed: Some(well(tokens.tool_active, tokens.text_strong)), selected: well(tokens.tool_active, tokens.text_strong), corner_radius: CornerRadius::same(6), focus_stroke: Stroke::new(1.0, tokens.accent), - }; - - IconButton::new(label, vec2(size, size), &style).selected(selected).show(ui, |ui, rect, color| { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, icon, egui::FontId::proportional(size * 0.62), color); - }) + } } /// A flat button filled with the accent, white lettering (a dialog's main action). diff --git a/crates/ui-egui/tests/toolbar.rs b/crates/ui-egui/tests/toolbar.rs index 76b0053d..7d91e558 100644 --- a/crates/ui-egui/tests/toolbar.rs +++ b/crates/ui-egui/tests/toolbar.rs @@ -3,7 +3,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use texturecraft_engine::{Session, Tool}; -use texturecraft_ui_egui::state::Mode; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { @@ -146,6 +146,31 @@ fn mode_buttons_keep_their_order_and_dispatch_commands() { } } +#[test] +fn view_dropdowns_set_the_layout_and_projection() { + let mut harness = toolbar_harness(1600.0, Tool::Paint); + harness.get_by_label("3D/2D views (F1)").click(); + harness.run_steps(3); + harness.get_by_label_contains("3D view only").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.layout, ViewLayout::Only3D); + assert!(harness.query_by_label_contains("2D view only").is_none(), "the layout menu stays open"); + assert!(harness.query_by_label("3D view only (F2)").is_some()); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + assert!(harness.query_by_label_contains("Orthographic").is_none(), "a second click keeps the projection menu open"); + + harness.get_by_label("Perspective").click(); + harness.run_steps(3); + harness.get_by_label_contains("Orthographic").click(); + harness.run_steps(3); + assert!(harness.state().session.camera.ortho); + assert!(harness.query_by_label("Orthographic").is_some()); +} + #[test] #[ignore] fn toolbar_frame_timing() { From 169221ea4c0e1f1b3fd70d97c6822713eefaa77c Mon Sep 17 00:00:00 2001 From: Agapenor <120006055+Agapenordev@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:30:59 +0000 Subject: [PATCH 040/275] Mark reimported projects as modified Mark successfully reimported projects as modified so closing them prompts to save. Keep failed reimports atomic and add saved-project regression coverage. Thanks @Agapenordev for the fix and regression test. --- crates/engine/src/file_cmds.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 48d4e8b2..0744aca2 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -448,6 +448,7 @@ impl Session { let mut next = Session::new(doc, mesh, source)?; next.log.extend(warnings); next.path = self.path.clone(); + next.modified = true; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); self.switch_to(next); Ok(preserved.map_or(Value::Null, |n| json!({ "preserved": n }))) @@ -610,6 +611,16 @@ fn close(s: &mut Session, _: &Value) -> Result { mod tests { use super::*; + #[test] + fn reimporting_a_saved_project_marks_it_modified() { + let obj = b"v -1 -1 0\nv 1 -1 0\nv 1 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nf 1/1 2/2 3/3\n"; + let original = Session::from_mesh_bytes("mesh.obj", obj, 128, "mesh").unwrap(); + let mut saved = Session::from_project_bytes(&original.to_project_bytes().unwrap()).unwrap(); + assert!(!saved.modified); + crate::execute(&mut saved, "file.reimportMesh", &Value::Null).unwrap(); + assert!(saved.modified, "reimport must trigger the unsaved-changes prompt"); + } + #[test] fn export_mesh_writes_obj_by_default_and_textured_glb() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); From adcc43b077ecf61d0e6c6541ace51d220ae9fa42 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH 041/275] Smart mask previews that show the mask Shelf thumbnails now show each smart mask applied with mask.smart.apply to a baked preview shape (geom::primitives::preview_orb) and read back from the compositor (compose::mask_at, a sparse read sharing mask_image's per-tile code), shaded flat white over a softly lit near-black surface. The shape bakes once on a worker; preview::smart_mask's world-noise approximation is removed. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 121 ++++++++++++++++-- crates/compose/src/lib.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_preview.rs | 163 ++++++++++++++++++++++++ crates/engine/src/mask_preview_pixel.rs | 14 ++ crates/engine/src/preview.rs | 20 +-- crates/engine/src/session.rs | 7 + crates/geom/src/primitives.rs | 158 ++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_previews.rs | 104 +++++++++++++++ crates/ui-egui/src/thumbs.rs | 30 +++-- 11 files changed, 579 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/mask_preview_pixel.rs create mode 100644 crates/ui-egui/src/mask_previews.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..56b32cd8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1843,31 +1843,25 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { let (w, h) = (inp.gbuf.width, inp.gbuf.height); let all = all_tiles(w, h); let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all + let tiles: HashMap<(u32, u32), Vec> = all .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); + .map(|&tile| { let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } + for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + *b = (v * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, buf) }) .collect(); + let size = size.max(1); let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); for y in 0..size { for x in 0..size { let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) + if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) && let Some(d) = out.get_mut((y * size + x) as usize) { @@ -1878,6 +1872,68 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the +/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a +/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no +/// enabled mask. +pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; + let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover + // every tile, as in `mask_image` + let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); + + // Per tile: offset in the tile -> indices in `texels` asking for it + let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); + for (i, &(x, y)) in texels.iter().enumerate() { + let offset = ((y % TILE) * TILE + x % TILE) as usize; + wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + } + let values: Vec<(usize, f32)> = wanted + .par_iter() + .flat_map_iter(|(&tile, offsets)| { + mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) + .into_iter() + .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + }) + .collect(); + + let mut out = vec![0.0; texels.len()]; + for (i, v) in values { + if let Some(d) = out.get_mut(i) { + *d = v; + } + } + Some(out) +} + +/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes +/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. +fn mask_tile( + inp: &Inputs, + id: LayerId, + mask: &Mask, + channels: &[Channel], + fields: &Fields, + (tx, ty): (u32, u32), + wanted: impl Fn(usize) -> bool, +) -> Vec<(usize, f32)> { + let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + + // Masks that read anchor points need the stack below the layer + let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); + tile_texels(inp.gbuf, tx, ty) + .filter(|&(_, _, o)| wanted(o)) + .map(|(x, y, o)| { + let mut texel = Texel::new(inp, x, y, o, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, id); + } + (o, texel.mask(&plan)) + }) + .collect() +} + /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; @@ -2175,6 +2231,45 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); + let eid = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + eid, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + f.project.layer_mut(id).unwrap().mask = Some(mask); + let maskless = f.project.alloc_id(); + let images = Default::default(); + let inp = Inputs { + project: &f.project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + + // Scattered texels, one twice, one outside the texture + let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; + let sparse = mask_at(&inp, id, &texels).unwrap(); + let image = mask_image(&inp, id, 64).unwrap(); + for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { + let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; + assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + } + assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); + assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); + assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..ee940e06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..ca7cdeea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,6 +25,8 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +pub mod mask_preview; +mod mask_preview_pixel; pub mod material_lib; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs new file mode 100644 index 00000000..e7116d9d --- /dev/null +++ b/crates/engine/src/mask_preview.rs @@ -0,0 +1,163 @@ +//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape +//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with +//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::{primitives, surface_at}; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +use crate::{EngineError, Result, Session}; + +/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +const TEXTURE_PX: u32 = 512; +/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +const SUPERSAMPLE: usize = 2; +/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +const OCCLUSION_RAYS: u32 = 12; +/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +const CURVATURE_RAYS: u32 = 12; +/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as +/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read. +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the +/// view-space normal there (None where the ray misses). +type CameraSample = Option<(usize, Vec3)>; + +/// The baked preview shape and what each thumbnail sub-pixel sees. +pub struct MaskPreview { + session: Session, + layer: LayerId, + size: usize, + /// The texels (x, y) the camera sees, each once. + texels: Vec<(u32, u32)>, + /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. + samples: Vec, +} + +impl MaskPreview { + /// Bake the preview shape once and aim the camera for `size²` thumbnails. + pub fn new(size: usize) -> Result { + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(0)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(0, false)?; + + let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); + Ok(MaskPreview { session, layer, size, texels, samples }) + } + + /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// (None for an unknown id). + pub fn render(&mut self, id: &str) -> Option>> { + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Nothing is undone here; the snapshots would pile up over the presets + self.session.undo.clear(); + let values = self.session.mask_at(self.layer, &self.texels)?; + + let fine = self.size * SUPERSAMPLE; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..self.size * self.size) + .map(|i| { + let (x, y) = (i % self.size, i / self.size); + let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); + for sy in 0..SUPERSAMPLE { + for sx in 0..SUPERSAMPLE { + let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + + mask += values.get(texel).copied().unwrap_or(0.0); + normal += n; + hits += 1.0; + } + } + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } +} + +/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and +/// per pixel (row-major) its sample. +fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = TEXTURE_PX - 1; + + let mut texels = Vec::new(); + let mut index_of = std::collections::HashMap::new(); + let samples = (0..size * size) + .map(|i| { + let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + (texels, samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see. + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + #[test] + fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + let size = 24; + let mut preview = MaskPreview::new(size).unwrap(); + for sm in crate::smart_masks::SMART_MASKS { + let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + assert_eq!(px.len(), size * size, "{}", sm.id); + assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); + let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); + for p in seen { + assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); + assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); + } + } + + let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.render("nope").is_none()); + } +} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..bcde5629 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..1dc33631 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,6 +1,7 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or +//! baked maps (generators that need mesh maps are approximated with world-space noise), and +//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked +//! preview ([`crate::mask_preview`]). use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ @@ -183,13 +184,6 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; @@ -202,11 +196,7 @@ mod tests { assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); assert!(px[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); - } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); + assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); for f in crate::filter_lib::FILTERS { let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..214bd69f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,6 +829,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a + /// mask); evaluates only those texels. + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..29bad947 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..3253a7a9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod mask_previews; pub mod menus; pub mod parity; pub mod profile; diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs new file mode 100644 index 00000000..fc6018e4 --- /dev/null +++ b/crates/ui-egui/src/mask_previews.rs @@ -0,0 +1,104 @@ +//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on +//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on +//! the CPU; on the web the work runs inline). + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; +/// How often the shelf checks for the thumbnails while they render. +const POLL: Duration = Duration::from_millis(100); + +/// Smart mask thumbnails by id, as the worker sends them. +type Thumbnails = Vec<(&'static str, ColorImage)>; + +/// Where the smart mask thumbnails are. +#[derive(Default)] +pub enum MaskPreviews { + #[default] + NotStarted, + Rendering(Receiver), + /// Handed out (or the worker failed; the tiles keep their placeholder). + Finished, +} + +impl MaskPreviews { + /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call + /// that finds them done (None before and after). + pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { + if matches!(self, MaskPreviews::NotStarted) { + *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); + } + let MaskPreviews::Rendering(rx) = self else { return None }; + + match rx.try_recv() { + Ok(thumbnails) => { + *self = MaskPreviews::Finished; + Some(thumbnails) + } + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(POLL); + None + } + // The worker stopped without a result + Err(TryRecvError::Disconnected) => { + *self = MaskPreviews::Finished; + None + } + } + } +} + +/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). +fn render(size: usize) -> Thumbnails { + let mut preview = match MaskPreview::new(size) { + Ok(p) => p, + Err(e) => { + log::warn!("smart mask previews: {e}"); + return Vec::new(); + } + }; + SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() +} + +/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): +/// the mask as white over a near-black surface lit softly from the upper left. No environment +/// reflections. +fn image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..f5590b31 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,7 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches +//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New +//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a +//! frame; the smart mask previews render together on a worker. use std::collections::HashMap; @@ -11,6 +12,8 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; +use crate::mask_previews::MaskPreviews; + /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; /// Shelf sphere thumbnail size in pixels. @@ -24,6 +27,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), + mask_previews: MaskPreviews, } fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -161,14 +165,20 @@ impl Thumbs { self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. + /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails + /// render; they all arrive together). pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + let key = format!("mask:{id}"); + if let Some(t) = self.shelf.get(&key) { + return Some(t.clone()); + } + + for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { + let mask_key = format!("mask:{mask_id}"); + let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); + self.shelf.insert(mask_key, t); + } + self.shelf.get(&key).cloned() } /// Sphere thumbnail of library filter `id` applied to a sample material. From 34ba091e8a2e6049ca50be177fcb21500ca01743 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Thu, 5 Nov 2026 20:44:48 +0000 Subject: [PATCH 042/275] Smart mask previews that show the mask Shelf thumbnails now show each smart mask applied with mask.smart.apply to a baked preview shape (geom::primitives::preview_orb) and read back from the compositor (compose::mask_at, a sparse read sharing mask_image's per-tile code), shaded flat white over a softly lit near-black surface. The shape bakes once on a worker; preview::smart_mask's world-noise approximation is removed. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 121 ++++++++++++++++-- crates/compose/src/lib.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/mask_preview.rs | 163 ++++++++++++++++++++++++ crates/engine/src/mask_preview_pixel.rs | 14 ++ crates/engine/src/preview.rs | 20 +-- crates/engine/src/session.rs | 7 + crates/geom/src/primitives.rs | 158 ++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/mask_previews.rs | 104 +++++++++++++++ crates/ui-egui/src/thumbs.rs | 30 +++-- 11 files changed, 579 insertions(+), 43 deletions(-) create mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/mask_preview_pixel.rs create mode 100644 crates/ui-egui/src/mask_previews.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 6c642b75..56b32cd8 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1843,31 +1843,25 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { let (w, h) = (inp.gbuf.width, inp.gbuf.height); let all = all_tiles(w, h); let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: Vec<(u32, u32, Vec)> = all + let tiles: HashMap<(u32, u32), Vec> = all .par_iter() - .filter_map(|&(tx, ty)| { - let mp = mask_plan(inp, id, mask, tx, ty, Some(&fields))?; - let full = anchor_plan(inp, id, &channels, tx, ty, Some(&fields)); + .map(|&tile| { let mut buf = vec![0u8; TILE_AREA]; - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - tex.anchors_below(&full, id); - } + for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { if let Some(b) = buf.get_mut(o) { - *b = (tex.mask(&mp) * 255.0 + 0.5) as u8; + *b = (v * 255.0 + 0.5) as u8; } } - Some((tx, ty, buf)) + (tile, buf) }) .collect(); + let size = size.max(1); let mut out = vec![0u8; (size * size) as usize]; - let lookup: std::collections::HashMap<(u32, u32), &Vec> = tiles.iter().map(|(x, y, b)| ((*x, *y), b)).collect(); for y in 0..size { for x in 0..size { let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = lookup.get(&(sx / TILE, sy / TILE)) + if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) && let Some(d) = out.get_mut((y * size + x) as usize) { @@ -1878,6 +1872,68 @@ pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { Some(out) } +/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the +/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a +/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no +/// enabled mask. +pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; + let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover + // every tile, as in `mask_image` + let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); + + // Per tile: offset in the tile -> indices in `texels` asking for it + let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); + for (i, &(x, y)) in texels.iter().enumerate() { + let offset = ((y % TILE) * TILE + x % TILE) as usize; + wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + } + let values: Vec<(usize, f32)> = wanted + .par_iter() + .flat_map_iter(|(&tile, offsets)| { + mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) + .into_iter() + .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + }) + .collect(); + + let mut out = vec![0.0; texels.len()]; + for (i, v) in values { + if let Some(d) = out.get_mut(i) { + *d = v; + } + } + Some(out) +} + +/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes +/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. +fn mask_tile( + inp: &Inputs, + id: LayerId, + mask: &Mask, + channels: &[Channel], + fields: &Fields, + (tx, ty): (u32, u32), + wanted: impl Fn(usize) -> bool, +) -> Vec<(usize, f32)> { + let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + + // Masks that read anchor points need the stack below the layer + let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); + tile_texels(inp.gbuf, tx, ty) + .filter(|&(_, _, o)| wanted(o)) + .map(|(x, y, o)| { + let mut texel = Texel::new(inp, x, y, o, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, id); + } + (o, texel.mask(&plan)) + }) + .collect() +} + /// Tiles [`effect_histogram`] samples at most (a million texels). const HISTOGRAM_TILES: usize = 256; @@ -2175,6 +2231,45 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + #[test] + fn mask_at_reads_the_same_values_as_the_mask_image() { + let mut f = fixture(); + let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); + let eid = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + let pattern = Procedural::new(ProceduralKind::Checker); + mask.effects.push(Effect::new( + eid, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + )); + f.project.layer_mut(id).unwrap().mask = Some(mask); + let maskless = f.project.alloc_id(); + let images = Default::default(); + let inp = Inputs { + project: &f.project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + + // Scattered texels, one twice, one outside the texture + let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; + let sparse = mask_at(&inp, id, &texels).unwrap(); + let image = mask_image(&inp, id, 64).unwrap(); + for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { + let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; + assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + } + assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); + assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); + assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..ee940e06 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -17,6 +17,6 @@ pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_image, pad_tiles, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..ca7cdeea 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -25,6 +25,8 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; +pub mod mask_preview; +mod mask_preview_pixel; pub mod material_lib; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs new file mode 100644 index 00000000..e7116d9d --- /dev/null +++ b/crates/engine/src/mask_preview.rs @@ -0,0 +1,163 @@ +//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape +//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with +//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::{primitives, surface_at}; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +use crate::{EngineError, Result, Session}; + +/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +const TEXTURE_PX: u32 = 512; +/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +const SUPERSAMPLE: usize = 2; +/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +const OCCLUSION_RAYS: u32 = 12; +/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +const CURVATURE_RAYS: u32 = 12; +/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as +/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read. +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the +/// view-space normal there (None where the ray misses). +type CameraSample = Option<(usize, Vec3)>; + +/// The baked preview shape and what each thumbnail sub-pixel sees. +pub struct MaskPreview { + session: Session, + layer: LayerId, + size: usize, + /// The texels (x, y) the camera sees, each once. + texels: Vec<(u32, u32)>, + /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. + samples: Vec, +} + +impl MaskPreview { + /// Bake the preview shape once and aim the camera for `size²` thumbnails. + pub fn new(size: usize) -> Result { + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(0)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(0, false)?; + + let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); + Ok(MaskPreview { session, layer, size, texels, samples }) + } + + /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// (None for an unknown id). + pub fn render(&mut self, id: &str) -> Option>> { + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Nothing is undone here; the snapshots would pile up over the presets + self.session.undo.clear(); + let values = self.session.mask_at(self.layer, &self.texels)?; + + let fine = self.size * SUPERSAMPLE; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..self.size * self.size) + .map(|i| { + let (x, y) = (i % self.size, i / self.size); + let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); + for sy in 0..SUPERSAMPLE { + for sx in 0..SUPERSAMPLE { + let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + + mask += values.get(texel).copied().unwrap_or(0.0); + normal += n; + hits += 1.0; + } + } + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } +} + +/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and +/// per pixel (row-major) its sample. +fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = TEXTURE_PX - 1; + + let mut texels = Vec::new(); + let mut index_of = std::collections::HashMap::new(); + let samples = (0..size * size) + .map(|i| { + let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + (texels, samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see. + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + #[test] + fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + let size = 24; + let mut preview = MaskPreview::new(size).unwrap(); + for sm in crate::smart_masks::SMART_MASKS { + let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + assert_eq!(px.len(), size * size, "{}", sm.id); + assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); + let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); + for p in seen { + assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); + assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); + } + } + + let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.render("nope").is_none()); + } +} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs new file mode 100644 index 00000000..bcde5629 --- /dev/null +++ b/crates/engine/src/mask_preview_pixel.rs @@ -0,0 +1,14 @@ +//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). + +use texturecraft_geom::glam::Vec3; + +/// The smart mask value seen at a preview pixel, with what a display needs to shade the shape. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaskPreviewPixel { + /// Mask value (0..=1). + pub mask: f32, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer). + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline). + pub coverage: f32, +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 3c3aa130..1dc33631 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,6 +1,7 @@ -//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z, -//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space -//! noise). Cheap enough for lazily rendered thumbnails. +//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or +//! baked maps (generators that need mesh maps are approximated with world-space noise), and +//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked +//! preview ([`crate::mask_preview`]). use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ @@ -183,13 +184,6 @@ pub fn filter(id: &str, size: usize) -> Option>> { ) } -/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id). -pub fn smart_mask(id: &str, size: usize) -> Option>> { - let (bg, fx) = crate::smart_masks::preset(id)?; - let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx); - Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect()) -} - #[cfg(test)] mod tests { use super::*; @@ -202,11 +196,7 @@ mod tests { assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); assert!(px[0].is_none(), "corners are outside the sphere"); } - for sm in crate::smart_masks::SMART_MASKS { - let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id)); - assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id); - } - assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none() && filter("nope", 8).is_none()); + assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); for f in crate::filter_lib::FILTERS { let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..214bd69f 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,6 +829,13 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } + /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a + /// mask); evaluates only those texels. + pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let (ts, _, _) = self.doc.project.locate(id)?; + self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + } + /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 6403faed..29bad947 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -63,9 +63,17 @@ impl Builder { } } + /// The mesh of one material, with tangents. fn finish(self, material: &str) -> Mesh { + let mut m = self.into_mesh(material); + m.compute_tangents(); + m + } + + /// The mesh of one material, without tangents. + fn into_mesh(self, material: &str) -> Mesh { let count = self.idx.len() as u32; - let mut m = Mesh { + Mesh { positions: self.p, normals: self.n, uvs: self.uv, @@ -75,9 +83,7 @@ impl Builder { submeshes: vec![SubMesh { name: material.into(), material: 0, start: 0, count }], materials: vec![material.into()], diagonals: self.diag, - }; - m.compute_tangents(); - m + } } } @@ -189,6 +195,132 @@ fn lathe_into(b: &mut Builder, center: Vec3, profile: &[(f32, f32)], segs: usize }); } +/// [`preview_orb`]: half-size of the cube that cuts the unit sphere flat (each face rim is the +/// circle where they meet). +const ORB_CUT: f32 = 0.8; +/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. +const ORB_PANEL_VALLEY: f32 = 0.88; + +/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly +/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys +/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it +/// meets the body) and plain rounded corners (gradients). Faces +Z (front), -X (left) and +Y (top) +/// carry the panels, so the shape is made to be seen from the front left, slightly from above. +/// The body takes the top 79 % of the UV square, the base the bottom 19 %. +pub fn preview_orb() -> Mesh { + // Grid rows (columns: twice as many); fewer blur the panel walls, more cost bake time + const ROWS: usize = 300; + const BODY_UV_HEIGHT: f32 = 0.79; + const BASE_UV: UvRect = UvRect { o: Vec2::new(0.0, 0.81), s: Vec2::new(1.0, 0.19) }; + const BASE_RADIUS: f32 = 0.95; + const BASE_HALF_HEIGHT: f32 = 0.025; + const BASE_Y: f32 = -0.6; + const BASE_RIM_STEPS: usize = 12; + const BASE_SEGMENTS: usize = 256; + + let mut b = Builder::default(); + b.grid(ROWS, ROWS * 2, |i, j| { + let (u, v) = (j as f32 / (ROWS * 2) as f32, i as f32 / ROWS as f32); + let (theta, phi) = (v * PI, u * TAU + PI * 1.5); + let dir = Vec3::new(theta.sin() * phi.cos(), theta.cos(), -theta.sin() * phi.sin()); + (dir * preview_orb_radius(dir), dir, Vec2::new(u, v * BODY_UV_HEIGHT)) + }); + + // Base: a thin disc with a rounded rim (a half circle from its top face to its bottom face) + let mut profile = vec![(0.0, BASE_HALF_HEIGHT)]; + for k in 0..=BASE_RIM_STEPS { + let a = k as f32 / BASE_RIM_STEPS as f32 * PI; + profile.push((BASE_RADIUS - BASE_HALF_HEIGHT + BASE_HALF_HEIGHT * a.sin(), BASE_HALF_HEIGHT * a.cos())); + } + profile.push((0.0, -BASE_HALF_HEIGHT)); + lathe_into(&mut b, Vec3::Y * BASE_Y, &profile, BASE_SEGMENTS, BASE_UV); + + let mut m = b.into_mesh("Preview"); + // Normals from the triangles: the panel walls are too steep for the sphere's directions + m.compute_normals(); + // Body and base both run U around the vertical axis, so the tangent is that direction (a + // fraction of the cost of the general tangent pass on this many triangles) + m.tangents = m + .positions + .iter() + .zip(&m.normals) + .map(|(p, n)| { + let around = Vec3::new(p.z, 0.0, -p.x).try_normalize().unwrap_or(Vec3::X); + (around - *n * n.dot(around)).try_normalize().unwrap_or_else(|| n.any_orthonormal_vector()).extend(1.0) + }) + .collect(); + m +} + +/// Distance from the centre of the [`preview_orb`] body along unit direction `d`. +fn preview_orb_radius(d: Vec3) -> f32 { + // Rim blends: the sharp faces, and the softly blended left face + const SHARP_BLEND: f32 = 0.035; + const SOFT_BLEND: f32 = 0.18; + // Domed panels: valley depth below the face, dome rise past it; the left panel is smaller + const PANEL_DEPTH: f32 = 0.11; + const PANEL_BULGE: f32 = 0.04; + const LEFT_PANEL_SCALE: f32 = 0.9; + // Slot around the middle: centre height, half-width, edge rounding, depth; it fades out over + // this fraction of the left panel's rim + const SLOT_Y: f32 = -0.03; + const SLOT_HALF_WIDTH: f32 = 0.05; + const SLOT_ROUNDING: f32 = 0.015; + const SLOT_DEPTH: f32 = 0.12; + const SLOT_FADE: f32 = 0.04; + + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let smooth = |a: f32, b: f32, x: f32| { + let t = ((x - a) / (b - a)).clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) + }; + // Polynomial smooth minimum with blend radius k + let smin = |a: f32, b: f32, k: f32| { + let h = (0.5 + 0.5 * (b - a) / k).clamp(0.0, 1.0); + b + (a - b) * h - k * h * (1.0 - h) + }; + // Domed panel at `rho` (radius in face units) inside a face of rim `rim`: a steep wall from + // the rim into a valley, then a dome rising slightly past the face over the middle + let panel = |rho: f32, rim: f32| { + let valley = rim * ORB_PANEL_VALLEY; + if rho < valley { + PANEL_BULGE - (PANEL_BULGE + PANEL_DEPTH) * (rho / valley).powi(3) + } else { + -PANEL_DEPTH * (1.0 - ((rho - valley) / (rim - valley)).min(1.0)) + } + }; + let face_rho = |along: f32, u: f32, v: f32| (u * u + v * v).sqrt() / along.max(1e-3); + + // The cut: sharp rims except the softly blended left face + let mut radius = 1.0f32; + for (along, blend) in [(d.x, SHARP_BLEND), (-d.x, SOFT_BLEND), (d.y, SHARP_BLEND), (-d.y, SHARP_BLEND), (d.z, SHARP_BLEND), (-d.z, SHARP_BLEND)] { + // Directions facing away from a face stay on the sphere (9 = far past it) + let to_face = if along > 1e-3 { ORB_CUT / along } else { 9.0 }; + radius = smin(radius, to_face, blend); + } + + let a = d.abs(); + let left_rim = rim * LEFT_PANEL_SCALE; + let mut relief = 0.0; + if d.z > 0.0 && a.z >= a.x && a.z >= a.y { + relief += panel(face_rho(d.z, d.x, d.y), rim); + } + if d.x < 0.0 && a.x >= a.y && a.x >= a.z { + relief += panel(face_rho(-d.x, d.y, d.z), left_rim); + } + if d.y > 0.0 && a.y >= a.x && a.y >= a.z { + relief += panel(face_rho(d.y, d.x, d.z), rim); + } + + // Slot around the middle, stopping at the left panel + let in_left_panel = if d.x < 0.0 { 1.0 - smooth(left_rim * (1.0 - SLOT_FADE), left_rim * (1.0 + SLOT_FADE), face_rho(-d.x, d.y, d.z)) } else { 0.0 }; + let slot_band = 1.0 - smooth(SLOT_HALF_WIDTH - SLOT_ROUNDING, SLOT_HALF_WIDTH + SLOT_ROUNDING, (d.y - SLOT_Y).abs()); + relief -= SLOT_DEPTH * slot_band * (1.0 - in_left_panel); + + radius + relief +} + /// A flat disk facing up (+Y) or down, with planar UVs inside `r`. fn disk_into(b: &mut Builder, center: Vec3, radius: f32, up: bool, segs: usize, r: UvRect) { let n = if up { Vec3::Y } else { Vec3::NEG_Y }; @@ -340,6 +472,8 @@ pub fn builtin(id: &str) -> Option { "plane" => plane(2.0, 16), "crate" => crate_scene(), "udim_plane" | "udimplane" => udim_plane(), + // Not offered for new projects (not in BUILTINS): the smart mask preview session's mesh + "preview_orb" => preview_orb(), _ => return None, }) } @@ -396,6 +530,22 @@ mod tests { assert_eq!(udim_plane().uv_tiles(0).into_iter().collect::>(), vec![(0, 0), (1, 0)]); } + #[test] + fn preview_orb_is_well_formed_with_domed_panels() { + let m = preview_orb(); + check(&m, 1.0); + + // Above the middle slot, the front panel's dome rises past the cut face and its valley + // sits below it + let front_depth = |rho: f32| { + let d = Vec3::new(0.0, rho, 1.0).normalize(); + preview_orb_radius(d) * d.z + }; + let rim = (1.0 - ORB_CUT * ORB_CUT).sqrt() / ORB_CUT; + let (dome, valley) = (front_depth(0.2), front_depth(rim * ORB_PANEL_VALLEY)); + assert!(dome > ORB_CUT && valley < ORB_CUT - 0.05, "dome {dome}, valley {valley}"); + } + #[test] fn material_ball_has_two_materials() { let m = material_ball(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c6112eb3..df2d1c7a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod mask_previews; pub mod menus; pub mod parity; pub mod profile; diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs new file mode 100644 index 00000000..fc6018e4 --- /dev/null +++ b/crates/ui-egui/src/mask_previews.rs @@ -0,0 +1,104 @@ +//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on +//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on +//! the CPU; on the web the work runs inline). + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; +use texturecraft_engine::smart_masks::SMART_MASKS; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; +/// How often the shelf checks for the thumbnails while they render. +const POLL: Duration = Duration::from_millis(100); + +/// Smart mask thumbnails by id, as the worker sends them. +type Thumbnails = Vec<(&'static str, ColorImage)>; + +/// Where the smart mask thumbnails are. +#[derive(Default)] +pub enum MaskPreviews { + #[default] + NotStarted, + Rendering(Receiver), + /// Handed out (or the worker failed; the tiles keep their placeholder). + Finished, +} + +impl MaskPreviews { + /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call + /// that finds them done (None before and after). + pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { + if matches!(self, MaskPreviews::NotStarted) { + *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); + } + let MaskPreviews::Rendering(rx) = self else { return None }; + + match rx.try_recv() { + Ok(thumbnails) => { + *self = MaskPreviews::Finished; + Some(thumbnails) + } + Err(TryRecvError::Empty) => { + ctx.request_repaint_after(POLL); + None + } + // The worker stopped without a result + Err(TryRecvError::Disconnected) => { + *self = MaskPreviews::Finished; + None + } + } + } +} + +/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). +fn render(size: usize) -> Thumbnails { + let mut preview = match MaskPreview::new(size) { + Ok(p) => p, + Err(e) => { + log::warn!("smart mask previews: {e}"); + return Vec::new(); + } + }; + SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() +} + +/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): +/// the mask as white over a near-black surface lit softly from the upper left. No environment +/// reflections. +fn image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index a2d85712..f5590b31 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,7 @@ -//! Thumbnails: shaded material spheres, smart mask spheres, procedural swatches and brush alpha -//! previews, rendered on the CPU into cached egui textures (no image assets). New shelf -//! thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a frame. +//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches +//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New +//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a +//! frame; the smart mask previews render together on a worker. use std::collections::HashMap; @@ -11,6 +12,8 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; +use crate::mask_previews::MaskPreviews; + /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; /// Shelf sphere thumbnail size in pixels. @@ -24,6 +27,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), + mask_previews: MaskPreviews, } fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -161,14 +165,20 @@ impl Thumbs { self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) } - /// Sphere thumbnail of smart mask `id`: white where the mask applies, over dark gray. + /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails + /// render; they all arrive together). pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mask:{id}"), || { - let px = preview::smart_mask(id, SPHERE_PX).unwrap_or_default(); - let samples: Vec> = - px.iter().map(|m| m.map(|m| Sample { base: [0.04 + 0.76 * m; 3], metallic: 0.0, roughness: 0.6, height: 0.0 })).collect(); - sphere_image(SPHERE_PX, &samples) - }) + let key = format!("mask:{id}"); + if let Some(t) = self.shelf.get(&key) { + return Some(t.clone()); + } + + for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { + let mask_key = format!("mask:{mask_id}"); + let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); + self.shelf.insert(mask_key, t); + } + self.shelf.get(&key).cloned() } /// Sphere thumbnail of library filter `id` applied to a sample material. From 476d5ecc8be8648dde71c613964a3a04fb132758 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 5 Nov 2026 18:54:07 -0500 Subject: [PATCH 043/275] Guard preview inputs and optimize sparse mask reads --- crates/compose/src/eval.rs | 270 +++++++++++++++++---------- crates/engine/src/mask_preview.rs | 41 ++-- crates/engine/src/session.rs | 8 +- crates/ui-egui/tests/ui_snapshots.rs | 29 +++ 4 files changed, 235 insertions(+), 113 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 56b32cd8..ec75cd97 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1835,103 +1835,115 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) written } -/// The mask of layer `id` as an 8-bit grayscale image of `size × size` stretched over the -/// texture set (nearest texel; uncovered texels black). None when the layer has no enabled mask. -pub fn mask_image(inp: &Inputs, id: LayerId, size: u32) -> Option> { - let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; - let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - let all = all_tiles(w, h); - let fields = neighbourhood_fields(inp, &channels, &all); - let tiles: HashMap<(u32, u32), Vec> = all +/// The layer mask as a square grayscale image, using nearest texels and black outside the mesh +/// Returns None without an enabled mask +pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let coordinates = all_tiles(width, height); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() .map(|&tile| { - let mut buf = vec![0u8; TILE_AREA]; - for (o, v) in mask_tile(inp, id, mask, &channels, &fields, tile, |_| true) { - if let Some(b) = buf.get_mut(o) { - *b = (v * 255.0 + 0.5) as u8; + let mut values = vec![0u8; TILE_AREA]; + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) { + if let Some(destination) = values.get_mut(offset) { + *destination = (value * 255.0 + 0.5) as u8; } } - (tile, buf) + (tile, values) }) .collect(); let size = size.max(1); - let mut out = vec![0u8; (size * size) as usize]; + let mut output = vec![0u8; (size * size) as usize]; for y in 0..size { for x in 0..size { - let (sx, sy) = ((x as u64 * w as u64 / size as u64) as u32, (y as u64 * h as u64 / size as u64) as u32); - if let Some(t) = tiles.get(&(sx / TILE, sy / TILE)) - && let Some(v) = t.get(((sy % TILE) * TILE + sx % TILE) as usize) - && let Some(d) = out.get_mut((y * size + x) as usize) + let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32; + let sample_y = (u64::from(y) * u64::from(height) / u64::from(size)) as u32; + if let Some(tile) = tiles.get(&(sample_x / TILE, sample_y / TILE)) + && let Some(value) = tile.get(((sample_y % TILE) * TILE + sample_x % TILE) as usize) + && let Some(destination) = output.get_mut((y * size + x) as usize) { - *d = *v; + *destination = *value; } } } - Some(out) + Some(output) } -/// The mask of layer `id` (0..=1) at `texels` (x, y) of the texture set, in order; 0 where the -/// mesh does not cover a texel. Only the requested texels are evaluated, so a sparse read (a -/// preview's visible texels) costs a fraction of [`mask_image`]. None when the layer has no -/// enabled mask. -pub fn mask_at(inp: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { - let mask = layer_mask(inp.project, id).filter(|m| m.enabled)?; - let channels = inp.project.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); - // Neighbourhood effects (blur, warp) read past the requested texels, so their fields cover - // every tile, as in `mask_image` - let fields = neighbourhood_fields(inp, &channels, &all_tiles(inp.gbuf.width, inp.gbuf.height)); +/// Mask values at texture-set coordinates, in request order; None without an enabled mask +/// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels +pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let mut output = vec![0.0; texels.len()]; + + // Group valid requests before planning effects, which may resample painted tiles + let mut requested: HashMap<(u32, u32), Vec<(usize, usize)>> = HashMap::new(); + for (index, &(x, y)) in texels.iter().enumerate() { + if x >= inputs.gbuf.width || y >= inputs.gbuf.height { + continue; + } - // Per tile: offset in the tile -> indices in `texels` asking for it - let mut wanted: HashMap<(u32, u32), HashMap>> = HashMap::new(); - for (i, &(x, y)) in texels.iter().enumerate() { let offset = ((y % TILE) * TILE + x % TILE) as usize; - wanted.entry((x / TILE, y / TILE)).or_default().entry(offset).or_default().push(i); + requested.entry((x / TILE, y / TILE)).or_default().push((offset, index)); } - let values: Vec<(usize, f32)> = wanted - .par_iter() - .flat_map_iter(|(&tile, offsets)| { - mask_tile(inp, id, mask, &channels, &fields, tile, |o| offsets.contains_key(&o)) - .into_iter() - .flat_map(move |(o, v)| offsets.get(&o).into_iter().flatten().map(move |&i| (i, v))) + + if requested.is_empty() { + return Some(output); + } + + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + // Filters and anchors can depend on texels outside the requested tiles + let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height)); + let values: Vec<(usize, f32)> = requested + .par_iter_mut() + .flat_map_iter(|(&tile, requests)| { + requests.sort_unstable_by_key(|&(offset, _)| offset); + let groups = requests.chunk_by(|left, right| left.0 == right.0); + let offsets = groups.clone().filter_map(|group| group.first().map(|&(offset, _)| offset)); + mask_tile(inputs, id, mask, &channels, &fields, tile, offsets) + .zip(groups) + .flat_map(|((_, value), group)| group.iter().map(move |&(_, index)| (index, value))) }) .collect(); - let mut out = vec![0.0; texels.len()]; - for (i, v) in values { - if let Some(d) = out.get_mut(i) { - *d = v; + for (index, value) in values { + if let Some(destination) = output.get_mut(index) { + *destination = value; } } - Some(out) + Some(output) } -/// Layer `id`'s enabled `mask` at the covered texels of `tile` whose offset in the tile passes -/// `wanted`, as (offset, value 0..=1); empty for a tile the mask has no plan for. -fn mask_tile( - inp: &Inputs, +/// Mask values in offset order, including zeros for uncovered texels so request groups stay aligned +fn mask_tile<'a>( + inputs: &'a Inputs<'a>, id: LayerId, - mask: &Mask, + mask: &'a Mask, channels: &[Channel], - fields: &Fields, - (tx, ty): (u32, u32), - wanted: impl Fn(usize) -> bool, -) -> Vec<(usize, f32)> { - let Some(plan) = mask_plan(inp, id, mask, tx, ty, Some(fields)) else { return Vec::new() }; + fields: &'a Fields, + (tile_x, tile_y): (u32, u32), + offsets: impl Iterator + 'a, +) -> impl Iterator + 'a { + let plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields)); + let anchor_stack = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(fields)); + offsets.map(move |offset| { + let Some(plan) = plan.as_ref() else { return (offset, 0.0) }; - // Masks that read anchor points need the stack below the layer - let full = anchor_plan(inp, id, channels, tx, ty, Some(fields)); - tile_texels(inp.gbuf, tx, ty) - .filter(|&(_, _, o)| wanted(o)) - .map(|(x, y, o)| { - let mut texel = Texel::new(inp, x, y, o, 0.0); - if !full.is_empty() { - texel.anchors_below(&full, id); - } - (o, texel.mask(&plan)) - }) - .collect() + let x = tile_x * TILE + (offset % TILE as usize) as u32; + let y = tile_y * TILE + (offset / TILE as usize) as u32; + if x >= inputs.gbuf.width || y >= inputs.gbuf.height || inputs.gbuf.tri.get((y * inputs.gbuf.width + x) as usize).is_none_or(|tri| *tri == NO_TRI) { + return (offset, 0.0); + } + + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + if !anchor_stack.is_empty() { + texel.anchors_below(&anchor_stack, id); + } + (offset, texel.mask(plan)) + }) } /// Tiles [`effect_histogram`] samples at most (a million texels). @@ -2231,43 +2243,109 @@ mod tests { assert!(vals.iter().any(|v| *v > 0.99) && vals.iter().any(|v| *v < 0.51), "{vals:?}"); } + fn assert_sparse_mask_matches_image(fixture: &Fixture, layer: LayerId, texels: &[(u32, u32)]) -> Option> { + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let sparse = mask_at(&inputs, layer, texels); + let image = mask_image(&inputs, layer, fixture.gbuf.width); + assert_eq!(sparse.is_some(), image.is_some()); + let values = sparse?; + let image = image?; + assert_eq!(values.len(), texels.len()); + + for (&(x, y), &value) in texels.iter().zip(&values) { + let expected = + if x < fixture.gbuf.width && y < fixture.gbuf.height { f32::from(image[(y * fixture.gbuf.width + x) as usize]) / 255.0 } else { 0.0 }; + assert!((value - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {value} vs {expected}"); + } + Some(values) + } + #[test] fn mask_at_reads_the_same_values_as_the_mask_image() { - let mut f = fixture(); - let id = fill_layer(&mut f.project, [1.0, 1.0, 1.0], 1.0); - let eid = f.project.alloc_id(); + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + fixture.gbuf.tri[30 * 128 + 90] = NO_TRI; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let maskless = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let effect = fixture.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( - eid, + effect, EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, )); - f.project.layer_mut(id).unwrap().mask = Some(mask); - let maskless = f.project.alloc_id(); - let images = Default::default(); - let inp = Inputs { - project: &f.project, - ts: 0, - mesh: &f.mesh, - gbuf: &f.gbuf, - pixels: &f.pixels, - baked: &f.baked, - preview: None, - images: &images, - bounds: f.mesh.bounds(), - }; + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); - // Scattered texels, one twice, one outside the texture - let texels = [(0, 0), (13, 20), (63, 63), (40, 7), (13, 20), (64, 64)]; - let sparse = mask_at(&inp, id, &texels).unwrap(); - let image = mask_image(&inp, id, 64).unwrap(); - for (&(x, y), v) in texels.iter().zip(&sparse).take(5) { - let expected = f32::from(image[(y * 64 + x) as usize]) / 255.0; - assert!((v - expected).abs() <= 0.5 / 255.0 + 1e-6, "({x}, {y}): {v} vs {expected}"); + // Cross tile boundaries and include duplicates, a UV hole and invalid coordinates + let texels = [(0, 0), (0, 40), (63, 63), (64, 64), (127, 127), (0, 40), (90, 30), (128, 0), (0, 128), (u32::MAX, u32::MAX)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values.iter().any(|value| *value > 0.99) && values.iter().take(6).any(|value| *value < 0.01)); + assert_eq!(&values[6..], &[0.0; 4]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &[]), Some(Vec::new())); + assert!(assert_sparse_mask_matches_image(&fixture, maskless, &texels).is_none()); + let missing = fixture.project.alloc_id(); + assert!(assert_sparse_mask_matches_image(&fixture, missing, &texels).is_none()); + fixture.project.layer_mut(layer).unwrap().mask.as_mut().unwrap().enabled = false; + assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none()); + } + + #[test] + fn mask_at_ignores_out_of_range_texels_before_resampling_paint() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let paint = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(paint, EffectKind::Paint)); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + fixture.pixels.mask_mut(paint, (32, 32)).set(4, 5, &[u16::MAX; 2]); + + let texels = [(8, 10), (u32::MAX, 0), (0, u32::MAX), (u32::MAX, u32::MAX), (64, 0), (0, 64)]; + let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap(); + assert!(values[0] > 0.5, "valid texels still read resampled paint"); + assert_eq!(&values[1..], &[0.0; 5]); + assert_eq!(assert_sparse_mask_matches_image(&fixture, layer, &texels[1..]), Some(vec![0.0; 5])); + } + + #[test] + fn mask_at_preserves_anchors_and_neighbourhood_filters_across_tiles() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let upper = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new( + fixture.project.alloc_id(), + EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor }, projection: Projection::default() }, + )); + fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let original = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(original.iter().any(|value| *value > 0.99) && original.iter().any(|value| *value < 0.01), "the anchor supplies the checker"); + + for filter in [Filter::Blur { radius: 64.0 }, Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }] { + let mut filtered = mask.clone(); + filtered.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter))); + fixture.project.layer_mut(upper).unwrap().mask = Some(filtered); + let values = assert_sparse_mask_matches_image(&fixture, upper, &texels).unwrap(); + assert!(values.iter().zip(&original).any(|(value, original)| (value - original).abs() > 0.1), "the filter changes the anchor values"); } - assert_eq!(sparse[5], 0.0, "uncovered texels read 0"); - assert!(sparse.iter().any(|v| *v > 0.99) && sparse.iter().take(5).any(|v| *v < 0.01), "{sparse:?}"); - assert!(mask_at(&inp, maskless, &texels).is_none(), "no mask, no values"); } #[test] diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index e7116d9d..9f7673c4 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -14,6 +14,8 @@ use crate::{EngineError, Result, Session}; const TEXTURE_PX: u32 = 512; /// Camera rays per thumbnail pixel along each axis (anti-aliased outline). const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for this thumbnail-only renderer +const MAX_PREVIEW_SIZE_PX: usize = 512; /// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). const OCCLUSION_RAYS: u32 = 12; /// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). @@ -43,21 +45,27 @@ pub struct MaskPreview { } impl MaskPreview { - /// Bake the preview shape once and aim the camera for `size²` thumbnails. + /// Bake the preview shape for square thumbnails with sides of 1..=512 pixels pub fn new(size: usize) -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); + if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { + return Err(EngineError::Other(format!("mask preview size must be between 1 and {MAX_PREVIEW_SIZE_PX} pixels"))); } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + + let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let settings = &mut session.doc.project.texture_set_mut(0)?.bake; + settings.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + settings.high_poly.use_low_as_high = true; + settings.maps.curvature.parameters.method = CurvatureMethod::Mesh; + settings.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + settings.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + settings.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + settings.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + + for map in BakedMap::ALL { + settings.maps.set_enabled(map, MAPS.contains(&map)); + } + + let layer = *session.doc.project.texture_set(0)?.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; session.bake_now(0, false)?; let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); @@ -138,6 +146,13 @@ mod tests { pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 } + #[test] + fn invalid_preview_sizes_return_errors() { + for size in [usize::MAX / 2 + 1, 0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX] { + assert!(MaskPreview::new(size).is_err(), "size {size} should be rejected before baking"); + } + } + #[test] fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { let size = 24; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 214bd69f..aeaa5550 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -829,11 +829,11 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } - /// Layer `id`'s mask (0..=1) at `texels` (x, y) of its texture set, in order (None without a - /// mask); evaluates only those texels. + /// Mask values at texture-set coordinates in request order; None without an enabled mask + /// Uncovered and out-of-range texels read zero; neighbourhood filters also read surrounding texels pub fn mask_at(&self, id: LayerId, texels: &[(u32, u32)]) -> Option> { - let (ts, _, _) = self.doc.project.locate(id)?; - self.with_inputs(ts, |inp| texturecraft_compose::mask_at(inp, id, texels)) + let (texture_set, _, _) = self.doc.project.locate(id)?; + self.with_inputs(texture_set, |inputs| texturecraft_compose::mask_at(inputs, id, texels)) } /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..07a9b9fb 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -158,3 +158,32 @@ fn window_snapshots() { harness.event(egui::Event::PointerButton { pos: cursor_position, button, pressed: false, modifiers }); harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } + +#[test] +#[ignore] +fn smart_mask_shelf_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the picture"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = + texturecraft_engine::Session::new_project("Mask previews", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = 2; + let context = harness.ctx.clone(); + let started = std::time::Instant::now(); + loop { + harness.run_steps(1); + let thumbnails = &mut harness.state_mut().thumbs; + if texturecraft_engine::smart_masks::SMART_MASKS.iter().all(|preset| thumbnails.smart_mask(&context, preset.id).is_some()) { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(60), "smart mask thumbnails did not arrive"); + std::thread::sleep(std::time::Duration::from_millis(20)); + } + eprintln!("all smart mask thumbnails ready after {:.3} s", started.elapsed().as_secs_f64()); + save(&mut harness, &output_dir, "smart-mask-shelf"); +} From d9bc1ef6d8885dd3920c8aea37680122592cf1e7 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 00:04:49 +0000 Subject: [PATCH 044/275] UI: fit the unsaved-changes dialog to its contents The button row was a right-to-left layout placed straight in the dialog body, which centres its contents in all the remaining height, so the auto-sized window grew to 420 px. Wrapping it in a horizontal row (as the New project dialog does) brings it to 119 px. Adds a regression test on the dialog's window height. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/windows.rs | 49 ++++++++++++++++----------- crates/ui-egui/tests/close_unsaved.rs | 14 ++++++++ 2 files changed, 44 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 3672ad45..0c35d957 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -40,48 +40,59 @@ pub(crate) fn ask_to_save(app: &mut TextureCraftApp, then: crate::state::Unsaved /// (in the browser, Save downloads the project). fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { use crate::state::Unsaved; + if ctx.input(|i| i.viewport().close_requested()) && ask_to_save(app, Unsaved::Quit) { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); } - let Some(then) = app.ui.windows.unsaved.clone() else { return }; + let Some(pending) = app.ui.windows.unsaved.clone() else { return }; + let mut open = true; - let mut save = None; + let mut save_first = None; let mut cancel = false; - let name: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; - let question = - if then == Unsaved::Quit { trf("Save the changes to {name} before closing?", &name) } else { trf("Save the changes to {name} first?", &name) }; + let question_args: [(&str, &dyn std::fmt::Display); 1] = [("name", &app.session.doc.project.name)]; + let question = if pending == Unsaved::Quit { + trf("Save the changes to {name} before closing?", &question_args) + } else { + trf("Save the changes to {name} first?", &question_args) + }; dialog("unsaved", tr("Unsaved changes"), &mut open).show(ctx, |ui| { ui.label(question); ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add(primary_button(ui, tr("Save"))).clicked() { - save = Some(true); - } - if ui.button(tr("Don't save")).clicked() { - save = Some(false); - } - if ui.button(tr("Cancel")).clicked() { - cancel = true; - } + + // One row keeps the window to its contents; a bare right-to-left layout fills the screen height + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(primary_button(ui, tr("Save"))).clicked() { + save_first = Some(true); + } + if ui.button(tr("Don't save")).clicked() { + save_first = Some(false); + } + if ui.button(tr("Cancel")).clicked() { + cancel = true; + } + }); }); }); if !open || cancel { app.ui.windows.unsaved = None; } - match save { + + match save_first { Some(true) => { file_action(app, ctx, "file.save"); } - // Going ahead anyway: the changes are let go. + // Going ahead anyway: the changes are let go Some(false) => app.session.modified = false, None => return, } - // A cancelled or failed save keeps the project and this dialog open. + + // A cancelled or failed save keeps the project and this dialog open if app.session.modified { return; } app.ui.windows.unsaved = None; - match then { + match pending { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/tests/close_unsaved.rs b/crates/ui-egui/tests/close_unsaved.rs index 9f518f18..a0c5481d 100644 --- a/crates/ui-egui/tests/close_unsaved.rs +++ b/crates/ui-egui/tests/close_unsaved.rs @@ -90,3 +90,17 @@ fn closing_the_project_with_changes_asks_first() { assert_ne!(name(&h), "Edited", "Don't save closes the project"); assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } + +/// The dialog fits one sentence and one button row instead of growing to the screen height +#[test] +fn the_dialog_fits_its_contents() { + // The title bar, one line, one button row and margins take 119 px at 1x and the bug made it 420; the 31 px left over absorbs font and theme tweaks + const MAX_HEIGHT: f32 = 150.0; + + let mut h = harness(true); + request_close(&mut h); + h.run_steps(2); + + let dialog = h.ctx.memory(|m| m.area_rect(egui::Id::unique("unsaved"))).expect("the dialog is shown"); + assert!(dialog.height() < MAX_HEIGHT, "the dialog is {} px tall", dialog.height()); +} From 63df2b56e3ec98f0a80038ea4d86976dffb692bb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 02:13:28 +0000 Subject: [PATCH 045/275] Shelf hover preview: a big version of the thumbnail Hovering a shelf tile shows a 256 pt preview of the asset over its name, rendered on a long-lived worker (its own thread pool) once the pointer rests on the tile, newest hover first. The smart mask thumbnails and the big mask previews share one bake. Renderers take their size as a parameter; the shelf thumbnails are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 1 + crates/engine/src/mask_preview.rs | 110 +++---- crates/engine/src/mask_preview_camera.rs | 64 +++++ crates/engine/src/preview.rs | 47 +-- crates/ui-egui/src/i18n/ar.rs | 23 -- crates/ui-egui/src/i18n/de.rs | 29 -- crates/ui-egui/src/i18n/es.rs | 29 -- crates/ui-egui/src/i18n/fr.rs | 29 -- crates/ui-egui/src/i18n/it.rs | 29 -- crates/ui-egui/src/i18n/ja.rs | 29 -- crates/ui-egui/src/i18n/ko.rs | 26 -- crates/ui-egui/src/i18n/pt_br.rs | 29 -- crates/ui-egui/src/i18n/zh_hans.rs | 14 - crates/ui-egui/src/lib.rs | 8 +- crates/ui-egui/src/mask_preview_image.rs | 44 +++ crates/ui-egui/src/mask_previews.rs | 104 ------- crates/ui-egui/src/mask_shape.rs | 33 +++ crates/ui-egui/src/preview_image.rs | 168 +++++++++++ crates/ui-egui/src/preview_request.rs | 29 ++ crates/ui-egui/src/preview_worker.rs | 207 +++++++++++++ crates/ui-egui/src/shelf.rs | 119 +++++--- crates/ui-egui/src/shelf_preview.rs | 102 +++++++ crates/ui-egui/src/thumbs.rs | 303 ++++++++------------ crates/ui-egui/src/worker_preview.rs | 13 + crates/ui-egui/tests/shelf_hover_preview.rs | 110 +++++++ 25 files changed, 1065 insertions(+), 634 deletions(-) create mode 100644 crates/engine/src/mask_preview_camera.rs create mode 100644 crates/ui-egui/src/mask_preview_image.rs delete mode 100644 crates/ui-egui/src/mask_previews.rs create mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/preview_image.rs create mode 100644 crates/ui-egui/src/preview_request.rs create mode 100644 crates/ui-egui/src/preview_worker.rs create mode 100644 crates/ui-egui/src/shelf_preview.rs create mode 100644 crates/ui-egui/src/worker_preview.rs create mode 100644 crates/ui-egui/tests/shelf_hover_preview.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7cdeea..201d0eb1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -26,6 +26,7 @@ pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; pub mod mask_preview; +mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; pub mod materials; diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index e7116d9d..a8e2d1e2 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -4,15 +4,16 @@ use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; -use texturecraft_geom::{primitives, surface_at}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; /// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). const TEXTURE_PX: u32 = 512; -/// Camera rays per thumbnail pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline). const SUPERSAMPLE: usize = 2; /// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). const OCCLUSION_RAYS: u32 = 12; @@ -23,28 +24,20 @@ const CURVATURE_RAYS: u32 = 12; const CURVATURE_RADIUS: f32 = 0.005; /// The mesh maps the smart mask generators read. const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera: looking down by this angle, turned to show the front, left and top panels. -const CAMERA_PITCH_DEG: f32 = 35.0; -const CAMERA_YAW_DEG: f32 = -34.4; +/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +const CAMERAS_KEPT: usize = 2; -/// What one camera sub-pixel sees: the index of its texel in the preview's texel list and the -/// view-space normal there (None where the ray misses). -type CameraSample = Option<(usize, Vec3)>; - -/// The baked preview shape and what each thumbnail sub-pixel sees. +/// The baked preview shape and, per preview size, what its camera sees. pub struct MaskPreview { session: Session, layer: LayerId, - size: usize, - /// The texels (x, y) the camera sees, each once. - texels: Vec<(u32, u32)>, - /// Per sub-pixel, row-major `(size · SUPERSAMPLE)²`. - samples: Vec, + /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once and aim the camera for `size²` thumbnails. - pub fn new(size: usize) -> Result { + /// Bake the preview shape once (previews of any size reuse it). + pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; @@ -60,27 +53,28 @@ impl MaskPreview { let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; session.bake_now(0, false)?; - let (texels, samples) = camera_samples(&session, size * SUPERSAMPLE); - Ok(MaskPreview { session, layer, size, texels, samples }) + Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per thumbnail pixel, row-major `size²`, None where the shape is not seen + /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen /// (None for an unknown id). - pub fn render(&mut self, id: &str) -> Option>> { + pub fn render(&mut self, id: &str, size: usize) -> Option>> { crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; // Nothing is undone here; the snapshots would pile up over the presets self.session.undo.clear(); - let values = self.session.mask_at(self.layer, &self.texels)?; - let fine = self.size * SUPERSAMPLE; + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..self.size * self.size) + let pixels = (0..size * size) .map(|i| { - let (x, y) = (i % self.size, i / self.size); + let (x, y) = (i % size, i / size); let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); for sy in 0..SUPERSAMPLE { for sx in 0..SUPERSAMPLE { - let Some(&Some((texel, n))) = self.samples.get((y * SUPERSAMPLE + sy) * fine + x * SUPERSAMPLE + sx) else { continue }; + let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; + let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; mask += values.get(texel).copied().unwrap_or(0.0); normal += n; @@ -94,38 +88,20 @@ impl MaskPreview { } } -/// What each pixel of a `size²` orthographic view of the shape sees: the distinct texels hit, and -/// per pixel (row-major) its sample. -fn camera_samples(session: &Session, size: usize) -> (Vec<(u32, u32)>, Vec) { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); - let pitch = CAMERA_PITCH_DEG.to_radians(); - let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); - let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); - let right = turn * Vec3::X; - let up = right.cross(forward); - let max_texel = TEXTURE_PX - 1; +/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end +/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { + Some(i) => cameras.remove(i), + None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } - let mut texels = Vec::new(); - let mut index_of = std::collections::HashMap::new(); - let samples = (0..size * size) - .map(|i| { - let ndc = Vec2::new(((i % size) as f32 + 0.5) / size as f32 * 2.0 - 1.0, 1.0 - ((i / size) as f32 + 0.5) / size as f32 * 2.0); - // Start well outside the shape so every ray enters it from the front - let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; - let hit = session.bvh.closest(origin, forward, radius * 8.0)?; - let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; - let texel = (((surface.uv.x * TEXTURE_PX as f32) as u32).min(max_texel), ((surface.uv.y * TEXTURE_PX as f32) as u32).min(max_texel)); - let index = *index_of.entry(texel).or_insert_with(|| { - texels.push(texel); - texels.len() - 1 - }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) - }) - .collect(); - (texels, samples) + cameras.push(camera); + cameras.last() } #[cfg(test)] @@ -139,11 +115,11 @@ mod tests { } #[test] - fn smart_mask_previews_are_in_range_and_tell_edges_from_cavities() { + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { let size = 24; - let mut preview = MaskPreview::new(size).unwrap(); + let mut preview = MaskPreview::new().unwrap(); for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id).unwrap_or_else(|| panic!("{}", sm.id)); + let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); assert_eq!(px.len(), size * size, "{}", sm.id); assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); @@ -154,10 +130,18 @@ mod tests { } } - let (edges, cavities) = (preview.render("edges_sharp").unwrap(), preview.render("dirt_cavities").unwrap()); + let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope").is_none()); + assert!(preview.render("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.render("edges_sharp", size * 3).unwrap(); + let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; + assert_eq!(big.len(), size * size * 9); + assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); + preview.render("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); } } diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs new file mode 100644 index 00000000..9787accb --- /dev/null +++ b/crates/engine/src/mask_preview_camera.rs @@ -0,0 +1,64 @@ +//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one +//! image size. + +use std::collections::HashMap; + +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::surface_at; + +use crate::Session; + +/// Camera: looking down by this angle, turned to show the front, left and top panels. +const CAMERA_PITCH_DEG: f32 = 35.0; +const CAMERA_YAW_DEG: f32 = -34.4; + +/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the +/// view-space normal there (None where the ray misses). +pub(crate) type CameraSample = Option<(usize, Vec3)>; + +/// What each ray of a square orthographic view of the preview shape sees. +pub(crate) struct MaskPreviewCamera { + /// Rays along each side of the view. + pub rays_per_side: usize, + /// The texels (x, y) the camera sees, each once. + pub texels: Vec<(u32, u32)>, + /// Per ray, row-major `rays_per_side²`. + pub samples: Vec, +} + +impl MaskPreviewCamera { + /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` + /// square. + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { + let (lo, hi) = session.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + let pitch = CAMERA_PITCH_DEG.to_radians(); + let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); + let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); + let right = turn * Vec3::X; + let up = right.cross(forward); + let max_texel = texture_px.saturating_sub(1); + + let mut texels = Vec::new(); + let mut index_of = HashMap::new(); + let samples = (0..rays_per_side * rays_per_side) + .map(|i| { + let side = rays_per_side as f32; + let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + // Start well outside the shape so every ray enters it from the front + let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; + let hit = session.bvh.closest(origin, forward, radius * 8.0)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + let texel = (((surface.uv.x * texture_px as f32) as u32).min(max_texel), ((surface.uv.y * texture_px as f32) as u32).min(max_texel)); + let index = *index_of.entry(texel).or_insert_with(|| { + texels.push(texel); + texels.len() - 1 + }); + let n = surface.nrm; + Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + }) + .collect(); + MaskPreviewCamera { rays_per_side, texels, samples } + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 1dc33631..8882b6d8 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -3,6 +3,7 @@ //! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked //! preview ([`crate::mask_preview`]). +use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural, world_noise}; use texturecraft_core::{ Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, @@ -95,28 +96,34 @@ const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel:: /// Preview of built-in material `id` (None for an unknown id). pub fn material(id: &str, size: usize) -> Option>> { - let mut p = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?; - Some( - sphere_normals(size) - .map(|n| { - let c = coords(n?); - let mut acc = CHANNELS.map(Channel::default_value); - for l in layers.iter().filter(|l| l.visible) { - let LayerKind::Fill(f) = &l.kind else { continue }; - let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c)); - for (a, ch) in acc.iter_mut().zip(CHANNELS) { - if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) { - let t = w * b.opacity.clamp(0.0, 1.0); - *a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t); - } + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + + // Pixels evaluate independently and big previews take long on one core + let normals: Vec<_> = sphere_normals(size).collect(); + let samples = normals + .into_par_iter() + .map(|normal| { + let at = coords(normal?); + let mut values = CHANNELS.map(Channel::default_value); + for layer in layers.iter().filter(|l| l.visible) { + let LayerKind::Fill(fill) = &layer.kind else { continue }; + + let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); + for (value, channel) in values.iter_mut().zip(CHANNELS) { + let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { + let weight = coverage * blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); } } - let [base, metal, rough, height] = acc; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) - }) - .collect(), - ) + } + + let [base, metal, rough, height] = values; + Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + }) + .collect(); + Some(samples) } /// `f` with its reach in texels multiplied by `k` (previews show at a fraction of 2K). diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 294e8964..6146d6d5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "شدة الانسداد المحيطي (AO)"), ("About TextureCraft", "حول TextureCraft"), ("About TextureCraft...", "حول TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "إضافة طبقة تعبئة بهذه الصورة (أو اسحبها إلى العرض ثلاثي الأبعاد لوضعها كملصق)", - ), - ("Add a fill layer using this pattern", "إضافة طبقة تعبئة بهذا النمط"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "إضافة طبقة تعبئة بهذه المادة فوق الطبقة المحددة (أو اسحبها إلى مكدس الطبقات)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "أضف نقطة ارتكاز إلى طبقة سفلية لاستخدام مكدسها كقناع."), ("Add anchor point", "إضافة نقطة ارتكاز"), ("Add as decal (view center)", "إضافة كملصق (مركز العرض)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "إضافة رسم"), ("Add paint layer", "إضافة طبقة رسم"), ("Add smart material from the shelf", "إضافة مادة ذكية من الرف"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "إضافة مجلد المادة الذكية فوق الطبقة المحددة (أو اسحبه إلى مكدس الطبقات)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "إضافة هذه اللمسة النهائية إلى خشونة وارتفاع الطبقة المحددة (أو اسحبها إلى طبقة)", - ), ("Add to the layer content", "إضافة إلى محتوى الطبقة"), ("Add to the mask", "إضافة إلى القناع"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "إضافة إلى محتوى الطبقة المحددة، أو إلى قناعها عند تحديد القناع (أو اسحبها إلى طبقة)", - ), ("Add white mask", "إضافة قناع أبيض"), ("Adjustments", "تعديلات"), ( @@ -663,7 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "التصيير، بتتبع المسار"), ("Replace", "استبدال"), ("Replace Color", "استبدال اللون"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "استبدال قناع الطبقة المحددة بهذا القناع الذكي (أو اسحبه إلى طبقة)"), ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), @@ -824,7 +802,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "تراجع"), ("Uniform value", "قيمة موحدة"), ("Use an equirectangular .hdr or .exr image as the environment", "استخدم صورة .hdr أو .exr متساوية المستطيلات كبيئة"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "استخدم كألفا للفرشاة (أو اسحبها إلى منفذ العرض أو خصائص الفرشاة)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "استخدم قناة التحكم أو الأمر `texturecraft-cli render` لالتقاط لقطات الشاشة"), ("Value", "القيمة"), ("Version {version}", "الإصدار {version}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 3155e6ce..5ceb5dd5 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO-Intensität"), ("About TextureCraft", "Über TextureCraft"), ("About TextureCraft...", "Über TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Füllebene mit diesem Bild hinzufügen (oder in die 3D-Ansicht ziehen, um es als Decal zu platzieren)", - ), - ("Add a fill layer using this pattern", "Füllebene mit diesem Muster hinzufügen"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Füllebene mit diesem Material über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Einer darunterliegenden Ebene einen Ankerpunkt hinzufügen, um ihren Stapel als Maske zu verwenden.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Malen hinzufügen"), ("Add paint layer", "Malebene hinzufügen"), ("Add smart material from the shelf", "Smart-Material aus der Ablage hinzufügen"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Smart-Material-Ordner über der ausgewählten Ebene hinzufügen (oder in den Ebenenstapel ziehen)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Diese Oberfläche zu Rauheit und Höhe der ausgewählten Ebene hinzufügen (oder auf eine Ebene ziehen)", - ), ("Add to the layer content", "Zum Ebeneninhalt hinzufügen"), ("Add to the mask", "Zur Maske hinzufügen"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Zum Inhalt der ausgewählten Ebene hinzufügen oder zu ihrer Maske, wenn die Maske ausgewählt ist (oder auf eine Ebene ziehen)", - ), ("Add white mask", "Weiße Maske hinzufügen"), ("Adjustments", "Korrekturen"), ( @@ -702,10 +681,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, Path Tracing"), ("Replace", "Ersetzen"), ("Replace Color", "Farbe ersetzen"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Maske der ausgewählten Ebene durch diese Smart-Maske ersetzen (oder auf eine Ebene ziehen)", - ), ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), @@ -866,10 +841,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Rückgängig"), ("Uniform value", "Einheitlicher Wert"), ("Use an equirectangular .hdr or .exr image as the environment", "Ein equirektangulares .hdr- oder .exr-Bild als Umgebung verwenden"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Als Pinsel-Alpha verwenden (oder in das Ansichtsfenster oder die Pinseleigenschaften ziehen)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Für Screenshots den Steuerkanal oder `texturecraft-cli render` verwenden"), ("Value", "Wert"), ("Version {version}", "Version {version}"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 7ba164a9..f9f42e49 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidad de AO"), ("About TextureCraft", "Acerca de TextureCraft"), ("About TextureCraft...", "Acerca de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Añadir una capa de relleno con esta imagen (o arrastrarla a la vista 3D para colocarla como calcomanía)", - ), - ("Add a fill layer using this pattern", "Añadir una capa de relleno con este patrón"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Añadir una capa de relleno con este material sobre la capa seleccionada (o arrastrarlo a la pila de capas)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "Añade un punto de anclaje a una capa inferior para usar su pila como máscara."), ("Add anchor point", "Añadir punto de anclaje"), ("Add as decal (view center)", "Añadir como calcomanía (centro de la vista)"), @@ -51,20 +42,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Añadir pintura"), ("Add paint layer", "Añadir capa de pintura"), ("Add smart material from the shelf", "Añadir material inteligente desde la biblioteca"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Añadir la carpeta del material inteligente sobre la capa seleccionada (o arrastrarla a la pila de capas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Añadir este acabado a la rugosidad y la altura de la capa seleccionada (o arrastrarlo a una capa)", - ), ("Add to the layer content", "Añadir al contenido de la capa"), ("Add to the mask", "Añadir a la máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Añadir al contenido de la capa seleccionada, o a su máscara si está seleccionada (o arrastrarlo a una capa)", - ), ("Add white mask", "Añadir máscara blanca"), ("Adjustments", "Ajustes de imagen"), ( @@ -690,10 +669,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderizado con trazado de trayectorias"), ("Replace", "Reemplazar"), ("Replace Color", "Reemplazar color"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Reemplazar la máscara de la capa seleccionada por esta máscara inteligente (o arrastrarla a una capa)", - ), ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), @@ -854,10 +829,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Deshacer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar una imagen equirrectangular .hdr o .exr como entorno"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alfa del pincel (o arrastrarlo a la ventana gráfica o a las propiedades del pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa el canal de control o `texturecraft-cli render` para las capturas"), ("Value", "Valor"), ("Version {version}", "Versión {version}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 034d78b5..57c7194f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensité de l'AO"), ("About TextureCraft", "À propos de TextureCraft"), ("About TextureCraft...", "À propos de TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Ajouter un calque de remplissage avec cette image (ou la glisser sur la vue 3D pour la placer comme décalque)", - ), - ("Add a fill layer using this pattern", "Ajouter un calque de remplissage avec ce motif"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Ajouter un calque de remplissage avec ce matériau au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa pile comme masque.", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Ajouter de la peinture"), ("Add paint layer", "Ajouter un calque de peinture"), ("Add smart material from the shelf", "Ajouter un matériau intelligent depuis la bibliothèque"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Ajouter le dossier du matériau intelligent au-dessus du calque sélectionné (ou le glisser dans la pile de calques)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Ajouter cette finition à la rugosité et à la hauteur du calque sélectionné (ou la glisser sur un calque)", - ), ("Add to the layer content", "Ajouter au contenu du calque"), ("Add to the mask", "Ajouter au masque"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Ajouter au contenu du calque sélectionné, ou à son masque si le masque est sélectionné (ou le glisser sur un calque)", - ), ("Add white mask", "Ajouter un masque blanc"), ("Adjustments", "Réglages"), ( @@ -705,10 +684,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendu, tracé de chemins"), ("Replace", "Remplacer"), ("Replace Color", "Remplacer la couleur"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Remplacer le masque du calque sélectionné par ce masque intelligent (ou le glisser sur un calque)", - ), ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), @@ -872,10 +847,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annuler"), ("Uniform value", "Valeur uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Utiliser une image équirectangulaire .hdr ou .exr comme environnement"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Utiliser comme alpha du pinceau (ou le glisser sur la fenêtre d'affichage ou les propriétés du pinceau)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "Utilisez le canal de contrôle ou `texturecraft-cli render` pour les captures d'écran", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07ce31ea..34abc28a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensità AO"), ("About TextureCraft", "Informazioni su TextureCraft"), ("About TextureCraft...", "Informazioni su TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Aggiungi un livello di riempimento con questa immagine (o trascinala nella vista 3D per posizionarla come decal)", - ), - ("Add a fill layer using this pattern", "Aggiungi un livello di riempimento con questo motivo"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Aggiungi un livello di riempimento con questo materiale sopra il livello selezionato (o trascinalo nella pila dei livelli)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Aggiungi un punto di ancoraggio a un livello sottostante per usarne la pila come maschera.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Aggiungi pittura"), ("Add paint layer", "Aggiungi livello di pittura"), ("Add smart material from the shelf", "Aggiungi un materiale intelligente dalla libreria"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Aggiungi la cartella del materiale intelligente sopra il livello selezionato (o trascinala nella pila dei livelli)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Aggiungi questa finitura alla rugosità e all'altezza del livello selezionato (o trascinala su un livello)", - ), ("Add to the layer content", "Aggiungi al contenuto del livello"), ("Add to the mask", "Aggiungi alla maschera"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Aggiungi al contenuto del livello selezionato, o alla sua maschera se è selezionata (o trascinalo su un livello)", - ), ("Add white mask", "Aggiungi maschera bianca"), ("Adjustments", "Regolazioni"), ( @@ -699,10 +678,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Rendering, path tracing"), ("Replace", "Sostituisci"), ("Replace Color", "Sostituisci colore"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Sostituisci la maschera del livello selezionato con questa maschera intelligente (o trascinala su un livello)", - ), ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), @@ -863,10 +838,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Annulla"), ("Uniform value", "Valore uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usa un'immagine equirettangolare .hdr o .exr come ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usa come alpha del pennello (o trascinala nella viewport o nelle proprietà del pennello)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Usa il canale di controllo o `texturecraft-cli render` per gli screenshot"), ("Value", "Valore"), ("Version {version}", "Versione {version}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ac768443..2c91d7ce 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO強度"), ("About TextureCraft", "TextureCraftについて"), ("About TextureCraft...", "TextureCraftについて..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "この画像で塗りつぶしレイヤーを追加 (3Dビューにドラッグするとデカールとして配置)", - ), - ("Add a fill layer using this pattern", "このパターンで塗りつぶしレイヤーを追加"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "このマテリアルの塗りつぶしレイヤーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "下のレイヤーにアンカーポイントを追加すると、そのスタックをマスクとして使用できます。", @@ -57,20 +48,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "ペイントを追加"), ("Add paint layer", "ペイントレイヤーを追加"), ("Add smart material from the shelf", "シェルフからスマートマテリアルを追加"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "スマートマテリアルのフォルダーを選択中のレイヤーの上に追加 (レイヤースタックへのドラッグも可)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "この仕上げを選択中のレイヤーのラフネスとハイトに追加 (レイヤーへのドラッグも可)", - ), ("Add to the layer content", "レイヤーのコンテンツに追加"), ("Add to the mask", "マスクに追加"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "選択中のレイヤーのコンテンツ (マスク選択時はマスク) に追加 (レイヤーへのドラッグも可)", - ), ("Add white mask", "白マスクを追加"), ("Adjustments", "色調補正"), ( @@ -681,10 +660,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "パストレースによるレンダリング"), ("Replace", "置換"), ("Replace Color", "色の置き換え"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "選択中のレイヤーのマスクをこのスマートマスクで置換 (レイヤーへのドラッグも可)", - ), ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), @@ -845,10 +820,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "元に戻す"), ("Uniform value", "均一値"), ("Use an equirectangular .hdr or .exr image as the environment", "正距円筒図法の .hdr または .exr 画像を環境として使用"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "ブラシのアルファとして使用 (ビューポートやブラシプロパティへのドラッグも可)", - ), ( "Use the control channel or `texturecraft-cli render` for screenshots", "スクリーンショットにはコントロールチャンネルまたは `texturecraft-cli render` を使用", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8fa260be..58a80560 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -25,15 +25,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 강도"), ("About TextureCraft", "TextureCraft 정보"), ("About TextureCraft...", "TextureCraft 정보..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "이 이미지로 채우기 레이어를 추가합니다 (또는 3D 뷰로 드래그하여 데칼로 배치)", - ), - ("Add a fill layer using this pattern", "이 패턴으로 채우기 레이어를 추가합니다"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 이 머티리얼로 채우기 레이어를 추가합니다 (또는 레이어 스택으로 드래그)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "아래 레이어에 앵커 포인트를 추가하면 해당 스택을 마스크로 사용할 수 있습니다."), ("Add anchor point", "앵커 포인트 추가"), ("Add as decal (view center)", "데칼로 추가 (뷰 중앙)"), @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "페인트 추가"), ("Add paint layer", "페인트 레이어 추가"), ("Add smart material from the shelf", "셸프에서 스마트 머티리얼 추가"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "선택한 레이어 위에 스마트 머티리얼 폴더를 추가합니다 (또는 레이어 스택으로 드래그)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "선택한 레이어의 러프니스와 높이에 이 마감을 추가합니다 (또는 레이어로 드래그)", - ), ("Add to the layer content", "레이어 콘텐츠에 추가"), ("Add to the mask", "마스크에 추가"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "선택한 레이어의 콘텐츠에 추가하거나, 마스크가 선택된 경우 마스크에 추가합니다 (또는 레이어로 드래그)", - ), ("Add white mask", "흰색 마스크 추가"), ("Adjustments", "조정"), ( @@ -672,10 +651,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "렌더링, 패스 트레이싱"), ("Replace", "대체"), ("Replace Color", "색상 바꾸기"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "선택한 레이어의 마스크를 이 스마트 마스크로 대체합니다 (또는 레이어로 드래그)", - ), ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), @@ -836,7 +811,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "실행 취소"), ("Uniform value", "균일 값"), ("Use an equirectangular .hdr or .exr image as the environment", "등장방형 .hdr 또는 .exr 이미지를 환경으로 사용합니다"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "브러시 알파로 사용합니다 (또는 뷰포트나 브러시 속성으로 드래그)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "스크린샷은 제어 채널 또는 `texturecraft-cli render`를 사용하세요"), ("Value", "값"), ("Version {version}", "버전 {version}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 203a94de..47e49c9c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -22,15 +22,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "Intensidade de AO"), ("About TextureCraft", "Sobre o TextureCraft"), ("About TextureCraft...", "Sobre o TextureCraft..."), - ( - "Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", - "Adicionar uma camada de preenchimento com esta imagem (ou arraste-a para a vista 3D para posicioná-la como decalque)", - ), - ("Add a fill layer using this pattern", "Adicionar uma camada de preenchimento com este padrão"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "Adicionar uma camada de preenchimento com este material acima da camada selecionada (ou arraste-o para a pilha de camadas)", - ), ( "Add an anchor point to a layer below to use its stack as a mask.", "Adicione um ponto de ancoragem a uma camada abaixo para usar sua pilha como máscara.", @@ -54,20 +45,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "Adicionar pintura"), ("Add paint layer", "Adicionar camada de pintura"), ("Add smart material from the shelf", "Adicionar material inteligente da prateleira"), - ( - "Add the smart material folder above the selected layer (or drag it into the layer stack)", - "Adicionar a pasta do material inteligente acima da camada selecionada (ou arraste-a para a pilha de camadas)", - ), - ( - "Add this finish to the selected layer's roughness and height (or drag it onto a layer)", - "Adicionar este acabamento à rugosidade e à altura da camada selecionada (ou arraste-o para uma camada)", - ), ("Add to the layer content", "Adicionar ao conteúdo da camada"), ("Add to the mask", "Adicionar à máscara"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "Adicionar ao conteúdo da camada selecionada, ou à sua máscara quando a máscara estiver selecionada (ou arraste-o para uma camada)", - ), ("Add white mask", "Adicionar máscara branca"), ("Adjustments", "Ajustes"), ( @@ -687,10 +666,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "Renderização com path tracing"), ("Replace", "Substituir"), ("Replace Color", "Substituir cor"), - ( - "Replace the selected layer's mask with this smart mask (or drag it onto a layer)", - "Substituir a máscara da camada selecionada por esta máscara inteligente (ou arraste-a para uma camada)", - ), ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), @@ -851,10 +826,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "Desfazer"), ("Uniform value", "Valor uniforme"), ("Use an equirectangular .hdr or .exr image as the environment", "Usar uma imagem equirretangular .hdr ou .exr como ambiente"), - ( - "Use as the brush alpha (or drag it onto the viewport or brush properties)", - "Usar como alpha do pincel (ou arraste-o para a viewport ou para as propriedades do pincel)", - ), ("Use the control channel or `texturecraft-cli render` for screenshots", "Use o canal de controle ou `texturecraft-cli render` para capturas de tela"), ("Value", "Valor"), ("Version {version}", "Versão {version}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d651ba67..8b66aead 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -19,12 +19,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("AO intensity", "AO 强度"), ("About TextureCraft", "关于 TextureCraft"), ("About TextureCraft...", "关于 TextureCraft..."), - ("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)", "使用此图像添加填充图层(或将其拖到 3D 视图中作为贴花放置)"), - ("Add a fill layer using this pattern", "使用此图案添加填充图层"), - ( - "Add a fill layer with this material above the selected layer (or drag it into the layer stack)", - "在所选图层上方添加使用此材质的填充图层(或将其拖入图层堆栈)", - ), ("Add an anchor point to a layer below to use its stack as a mask.", "在下方图层上添加锚点,以将其堆栈用作遮罩。"), ("Add anchor point", "添加锚点"), ("Add as decal (view center)", "添加为贴花(视图中心)"), @@ -45,14 +39,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Add paint", "添加绘画"), ("Add paint layer", "添加绘画图层"), ("Add smart material from the shelf", "从资产架添加智能材质"), - ("Add the smart material folder above the selected layer (or drag it into the layer stack)", "在所选图层上方添加智能材质文件夹(或将其拖入图层堆栈)"), - ("Add this finish to the selected layer's roughness and height (or drag it onto a layer)", "将此表面处理添加到所选图层的粗糙度和高度(或将其拖到图层上)"), ("Add to the layer content", "添加到图层内容"), ("Add to the mask", "添加到遮罩"), - ( - "Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)", - "添加到所选图层的内容,选中遮罩时则添加到遮罩(或将其拖到图层上)", - ), ("Add white mask", "添加白色遮罩"), ("Adjustments", "调整"), ("Aligned: the offset set by the first stroke is kept. V + click sets a new source.", "对齐:保留第一笔设定的偏移。按住 V 并单击可设置新的源。"), @@ -624,7 +612,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rendering, path traced", "渲染,路径追踪"), ("Replace", "替换"), ("Replace Color", "替换颜色"), - ("Replace the selected layer's mask with this smart mask (or drag it onto a layer)", "用此智能遮罩替换所选图层的遮罩(或将其拖到图层上)"), ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), @@ -785,7 +772,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Undo", "撤销"), ("Uniform value", "统一值"), ("Use an equirectangular .hdr or .exr image as the environment", "使用等距柱状投影的 .hdr 或 .exr 图像作为环境"), - ("Use as the brush alpha (or drag it onto the viewport or brush properties)", "用作笔刷 Alpha(或将其拖到视口或笔刷属性上)"), ("Use the control channel or `texturecraft-cli render` for screenshots", "截图请使用控制通道或 `texturecraft-cli render`"), ("Value", "值"), ("Version {version}", "版本 {version}"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df2d1c7a..59c6f40c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,12 +16,17 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; -mod mask_previews; +mod mask_preview_image; +mod mask_shape; pub mod menus; pub mod parity; +mod preview_image; +mod preview_request; +mod preview_worker; pub mod profile; pub mod render_mode; pub mod shelf; +pub mod shelf_preview; pub mod state; pub mod theme; pub mod thumbs; @@ -31,6 +36,7 @@ pub mod viewport; pub mod web_files; pub mod widgets; pub mod windows; +mod worker_preview; use std::sync::Arc; use std::sync::atomic::Ordering; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs new file mode 100644 index 00000000..49fe70f7 --- /dev/null +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -0,0 +1,44 @@ +//! Shading of the smart mask previews: the mask as white over a near-black surface. + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +/// View-space directions of the key light (upper left) and a weaker fill (right), and how much +/// each lights the surface. +const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; +const FILL: [f32; 3] = [0.7, -0.1, 0.7]; +const AMBIENT: f32 = 0.1; +const KEY_STRENGTH: f32 = 0.8; +const FILL_STRENGTH: f32 = 0.35; +/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the +/// shape reads without looking glossy. +const UNMASKED_ALBEDO: f32 = 0.006; +const SHEEN: f32 = 0.1; +const SHEEN_EXPONENT: f32 = 40.0; +/// Where the mask is full: white, darkened at most this much where unlit. +const WHITE_SHADING: f32 = 0.2; + +/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major +/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No +/// environment reflections. +pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let key = Vec3::from(KEY).normalize(); + let fill = Vec3::from(FILL).normalize(); + let half = (key + Vec3::Z).normalize(); + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (out, p) in img.pixels.iter_mut().zip(pixels) { + let Some(p) = p else { continue }; + + let n = p.normal; + let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); + let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); + let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); + let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); + let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + } + img +} diff --git a/crates/ui-egui/src/mask_previews.rs b/crates/ui-egui/src/mask_previews.rs deleted file mode 100644 index fc6018e4..00000000 --- a/crates/ui-egui/src/mask_previews.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! Smart mask shelf thumbnails: every smart mask on the baked preview shape, rendered together on -//! a worker the first time the shelf asks for one (baking the shape takes about two seconds on -//! the CPU; on the web the work runs inline). - -use std::sync::mpsc::{Receiver, TryRecvError}; -use std::time::Duration; - -use egui::{Color32, ColorImage}; -use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::{MaskPreview, MaskPreviewPixel}; -use texturecraft_engine::smart_masks::SMART_MASKS; -use texturecraft_engine::texel::linear_to_srgb; - -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. -const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; -const FILL: [f32; 3] = [0.7, -0.1, 0.7]; -const AMBIENT: f32 = 0.1; -const KEY_STRENGTH: f32 = 0.8; -const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. -const UNMASKED_ALBEDO: f32 = 0.006; -const SHEEN: f32 = 0.1; -const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. -const WHITE_SHADING: f32 = 0.2; -/// How often the shelf checks for the thumbnails while they render. -const POLL: Duration = Duration::from_millis(100); - -/// Smart mask thumbnails by id, as the worker sends them. -type Thumbnails = Vec<(&'static str, ColorImage)>; - -/// Where the smart mask thumbnails are. -#[derive(Default)] -pub enum MaskPreviews { - #[default] - NotStarted, - Rendering(Receiver), - /// Handed out (or the worker failed; the tiles keep their placeholder). - Finished, -} - -impl MaskPreviews { - /// Start rendering `size²` thumbnails on the first call; the finished thumbnails on the call - /// that finds them done (None before and after). - pub fn poll(&mut self, ctx: &egui::Context, size: usize) -> Option { - if matches!(self, MaskPreviews::NotStarted) { - *self = MaskPreviews::Rendering(crate::spawn_worker("texturecraft-mask-previews", move || render(size))); - } - let MaskPreviews::Rendering(rx) = self else { return None }; - - match rx.try_recv() { - Ok(thumbnails) => { - *self = MaskPreviews::Finished; - Some(thumbnails) - } - Err(TryRecvError::Empty) => { - ctx.request_repaint_after(POLL); - None - } - // The worker stopped without a result - Err(TryRecvError::Disconnected) => { - *self = MaskPreviews::Finished; - None - } - } - } -} - -/// Every smart mask's `size²` thumbnail (empty when the preview shape fails to bake). -fn render(size: usize) -> Thumbnails { - let mut preview = match MaskPreview::new(size) { - Ok(p) => p, - Err(e) => { - log::warn!("smart mask previews: {e}"); - return Vec::new(); - } - }; - SMART_MASKS.iter().filter_map(|m| Some((m.id, image(size, &preview.render(m.id)?)))).collect() -} - -/// A thumbnail (sRGB, transparent outside the shape) from preview pixels (row-major `size²`): -/// the mask as white over a near-black surface lit softly from the upper left. No environment -/// reflections. -fn image(size: usize, pixels: &[Option]) -> ColorImage { - let key = Vec3::from(KEY).normalize(); - let fill = Vec3::from(FILL).normalize(); - let half = (key + Vec3::Z).normalize(); - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - - for (out, p) in img.pixels.iter_mut().zip(pixels) { - let Some(p) = p else { continue }; - - let n = p.normal; - let shading = AMBIENT + KEY_STRENGTH * n.dot(key).max(0.0) + FILL_STRENGTH * n.dot(fill).max(0.0); - let unmasked = UNMASKED_ALBEDO * shading + SHEEN * n.dot(half).max(0.0).powf(SHEEN_EXPONENT); - let masked = 1.0 - WHITE_SHADING * (1.0 - shading.min(1.0)); - let linear = unmasked + (masked - unmasked) * p.mask.clamp(0.0, 1.0); - let gray = (linear_to_srgb(linear.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8; - *out = Color32::from_rgba_unmultiplied(gray, gray, gray, (p.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - } - img -} diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs new file mode 100644 index 00000000..e34c5a7e --- /dev/null +++ b/crates/ui-egui/src/mask_shape.rs @@ -0,0 +1,33 @@ +//! The smart mask preview shape, baked on first use. + +use texturecraft_engine::mask_preview::MaskPreview; + +/// Whether the smart mask preview shape is baked. +#[derive(Default)] +pub enum MaskShape { + #[default] + NotBaked, + /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + Baked(Box), + /// The bake failed; smart mask previews stay empty. + Failed, +} + +impl MaskShape { + /// The baked shape, baking it on the first call (about two seconds; None when it fails). + pub fn get(&mut self) -> Option<&mut MaskPreview> { + if matches!(self, MaskShape::NotBaked) { + *self = match MaskPreview::new() { + Ok(preview) => MaskShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("smart mask previews: {e}"); + MaskShape::Failed + } + }; + } + match self { + MaskShape::Baked(preview) => Some(preview), + MaskShape::NotBaked | MaskShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs new file mode 100644 index 00000000..3f2321dc --- /dev/null +++ b/crates/ui-egui/src/preview_image.rs @@ -0,0 +1,168 @@ +//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural +//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). + +use egui::{Color32, ColorImage}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; +use texturecraft_engine::paint::{BrushSettings, Shape}; +use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::texel::linear_to_srgb; + +/// Pattern scale of the procedural swatches (repeats across the swatch). +const PROCEDURAL_SCALE: f32 = 3.0; +/// Samples per pixel along each axis of the alpha swatches. +const ALPHA_SUPERSAMPLE: usize = 2; + +/// Linear color of a surface with view-space normal `n` and these material values, lit by a key +/// light and a studio environment, seen along +Z. +pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { + let l = [0.45f32, 0.7, 0.55]; + let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); + let l = l.map(|v| v / len); + let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); + let ndv = n[2].max(0.0); + // View along +Z: half vector between light and view. + let h = [l[0], l[1], l[2] + 1.0]; + let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); + let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); + let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; + let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; + // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that + // blurs (and the whole environment averages out) as roughness grows. + let ry = 2.0 * ndv * n[1]; + let w = 0.06 + rough * 0.9; + let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); + let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); + let env = sharp + (0.28 - sharp) * (rough * rough); + let fres = (1.0 - ndv).powi(5); + let sky = 0.35 + 0.25 * n[1]; + let mut out = [0.0; 3]; + for k in 0..3 { + let f0 = 0.04 + (base[k] - 0.04) * metal; + let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; + let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); + out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; + } + out +} + +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +pub fn aces(x: f32) -> f32 { + let v = x * 0.6; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) +} + +/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major +/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { + let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); + let r = (size as f32 * 0.5 - 1.0).max(0.5); + let h = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) + }; + for (i, n) in preview::sphere_normals(size).enumerate() { + let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); + let c = s.height; + // Central differences (image y points down). + let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); + let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); + let k = r * 0.5 * 1.5; + let b = [n.x - dx * k, n.y - dy * k, n.z]; + let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); + let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); + let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); + img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + } + img +} + +/// Grayscale `size²` swatch of procedural `kind`. +pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { + use texturecraft_engine::compose::pattern::{Coords, procedural}; + use texturecraft_engine::core::{Procedural, Projection}; + use texturecraft_engine::geom::glam::{Vec2, Vec3}; + + let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; + let mut img = ColorImage::filled([size, size], Color32::BLACK); + for (i, px) in img.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); + let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + } + img +} + +/// White-on-black `size²` swatch of library alpha `alpha`. +pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { + let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); + ColorImage::new([size, size], pixels) +} + +/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black +/// where it is transparent. +pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { + let aspect = img.width as f32 / img.height.max(1) as f32; + let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; + let mut preview = ColorImage::filled([size, size], Color32::BLACK); + for y in 0..size { + for x in 0..size { + let u = ((x as f32 + 0.5) / size as f32 - 0.5) * scale_u + 0.5; + let v = ((y as f32 + 0.5) / size as f32 - 0.5) * scale_v + 0.5; + if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { + continue; + } + + let sample = img.sample(u, v); + let alpha = sample[3]; + let encode = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * alpha.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * alpha) * 255.0) as u8 }; + preview.pixels[y * size + x] = Color32::from_rgb(encode(sample[0]), encode(sample[1]), encode(sample[2])); + } + } + preview +} + +/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across +/// an `n`-pixel square, white on black. +pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { + let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let radius = n as f32 * 0.11; + let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); + let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); + let mut cover = vec![0f32; n * n]; + // Deterministic jitter per stamp. + let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; + let step = (b.spacing * 2.0 * radius).max(0.5); + let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + let mut last = curve(0.0); + while t <= 1.0 && i < 2000 { + let p = curve(t); + travelled += (p.0 - last.0).hypot(p.1 - last.1); + last = p; + t += 0.002; + if travelled < step { + continue; + } + travelled = 0.0; + i += 1; + let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); + let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; + let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); + let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); + let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); + let (sin, cos) = angle.sin_cos(); + let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); + let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); + for y in y0..y1 { + for x in x0..x1 { + let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); + let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; + let c = &mut cover[y * n + x]; + *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); + } + } + } + ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +} diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs new file mode 100644 index 00000000..56e2e3b3 --- /dev/null +++ b/crates/ui-egui/src/preview_request.rs @@ -0,0 +1,29 @@ +//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). + +use egui::ColorImage; + +use crate::mask_preview_image::mask_preview_image; +use crate::mask_shape::MaskShape; +use crate::shelf_preview::ShelfPreview; + +/// Render `preview` at `size_px²`; the answer comes back under `key`. +pub struct PreviewRequest { + pub key: String, + pub preview: ShelfPreview, + pub size_px: usize, + /// A hover preview: the worker renders the newest of these before anything else. + // The web renders each request at once, so nothing is reordered there + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub hover: bool, +} + +impl PreviewRequest { + /// The requested image (None for an unknown asset, or a smart mask when the shape fails to + /// bake); smart masks bake `shape` on first use. + pub fn render(&self, shape: &mut MaskShape) -> Option { + match &self.preview { + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + preview => preview.image(self.size_px), + } + } +} diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs new file mode 100644 index 00000000..cf51812e --- /dev/null +++ b/crates/ui-egui/src/preview_worker.rs @@ -0,0 +1,207 @@ +//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): +//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders +//! inline on the UI thread (the window pauses for it). + +#[cfg(target_arch = "wasm32")] +use crate::mask_shape::MaskShape; +use crate::preview_request::PreviewRequest; + +/// A rendered preview: the request's key and its image (None when it could not be rendered). +pub type PreviewResult = (String, Option); + +/// The preview worker, started by the first request. +#[derive(Default)] +pub enum PreviewWorker { + #[default] + NotStarted, + /// The worker thread: requests go in, results come out (it ends when the requests sender is + /// dropped). + #[cfg(not(target_arch = "wasm32"))] + Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, + /// The web: requests render as they are made. + #[cfg(target_arch = "wasm32")] + Inline { shape: MaskShape, results: Vec }, + /// The worker could not start or stopped; requests are refused. + // The web has no thread to stop + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + Stopped, +} + +impl PreviewWorker { + /// Queue `request`, starting the worker first if needed; false when the worker is stopped. + /// The worker repaints `ctx` when a result is ready. + pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { + if matches!(self, PreviewWorker::NotStarted) { + *self = PreviewWorker::start(ctx); + } + + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { requests, .. } => { + if requests.send(request).is_ok() { + return true; + } + *self = PreviewWorker::Stopped; + false + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { shape, results } => { + results.push((request.key.clone(), request.render(shape))); + true + } + PreviewWorker::NotStarted | PreviewWorker::Stopped => false, + } + } + + /// The results ready since the last call. + pub fn poll(&mut self) -> Vec { + match self { + #[cfg(not(target_arch = "wasm32"))] + PreviewWorker::Running { results, .. } => { + use std::sync::mpsc::TryRecvError; + + let mut ready = Vec::new(); + loop { + match results.try_recv() { + Ok(result) => ready.push(result), + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + log::warn!("the shelf preview worker stopped"); + *self = PreviewWorker::Stopped; + break; + } + } + } + ready + } + #[cfg(target_arch = "wasm32")] + PreviewWorker::Inline { results, .. } => std::mem::take(results), + PreviewWorker::NotStarted | PreviewWorker::Stopped => Vec::new(), + } + } + + /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + pub fn is_stopped(&self) -> bool { + matches!(self, PreviewWorker::Stopped) + } + + /// Start the worker thread (Stopped when it cannot start). + #[cfg(not(target_arch = "wasm32"))] + fn start(ctx: &egui::Context) -> PreviewWorker { + use std::collections::VecDeque; + use std::sync::mpsc::channel; + + use crate::mask_shape::MaskShape; + + let (requests, request_rx) = channel::(); + let (result_tx, results) = channel(); + let ctx = ctx.clone(); + let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { + // Its own threads: on the global pool a big render would hold up the UI thread's work + let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); + if let Err(e) = &pool { + log::warn!("shelf previews share the global thread pool: {e}"); + } + let mut shape = MaskShape::default(); + let mut queue = VecDeque::new(); + loop { + // Wait for work, then take in everything sent meanwhile + if queue.is_empty() { + let Ok(request) = request_rx.recv() else { break }; + + queue.push_back(request); + } + queue.extend(request_rx.try_iter()); + + let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { + Ok(pool) => pool.install(|| request.render(&mut shape)), + Err(_) => request.render(&mut shape), + }; + if result_tx.send((request.key, image)).is_err() { + break; + } + ctx.request_repaint(); + } + }); + + match spawned { + Ok(_) => PreviewWorker::Running { requests, results }, + Err(e) => { + log::warn!("could not start the shelf preview worker: {e}"); + PreviewWorker::Stopped + } + } + } + + /// Render inline (no threads on the web). + #[cfg(target_arch = "wasm32")] + fn start(_ctx: &egui::Context) -> PreviewWorker { + PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + } +} + +/// The request to render next: the newest hover preview (the one under the pointer), else the +/// oldest request. +#[cfg(not(target_arch = "wasm32"))] +fn next_request(queue: &mut std::collections::VecDeque) -> Option { + match queue.iter().rposition(|request| request.hover) { + Some(newest_hover) => queue.remove(newest_hover), + None => queue.pop_front(), + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::time::{Duration, Instant}; + + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::smart_masks::SMART_MASKS; + + use super::*; + use crate::shelf_preview::ShelfPreview; + + #[test] + fn requests_are_answered_and_unknown_assets_get_none() { + let ctx = egui::Context::default(); + let mut worker = PreviewWorker::default(); + let size_px = 32; + let requests = [ + ("material", ShelfPreview::Material(MATERIALS[0].id)), + ("unknown material", ShelfPreview::Material("nope")), + ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), + ("unknown mask", ShelfPreview::SmartMask("nope")), + ]; + for (key, preview) in requests { + assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); + } + + let mut answers = HashMap::new(); + let start = Instant::now(); + while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + answers.extend(worker.poll()); + std::thread::sleep(Duration::from_millis(10)); + } + + for key in ["material", "mask"] { + let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); + assert_eq!(image.size, [size_px, size_px], "{key}"); + } + for key in ["unknown material", "unknown mask"] { + assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); + } + assert!(!worker.is_stopped()); + } + + #[test] + fn the_newest_hover_preview_goes_first_then_the_oldest_request() { + let request = |key: &str, hover| PreviewRequest { key: key.into(), preview: ShelfPreview::Material("steel"), size_px: 8, hover }; + let mut queue: std::collections::VecDeque<_> = + [request("thumbnail 1", false), request("old hover", true), request("thumbnail 2", false), request("new hover", true)].into(); + + let order: Vec = std::iter::from_fn(|| next_request(&mut queue)).map(|r| r.key).collect(); + assert_eq!(order, ["new hover", "old hover", "thumbnail 1", "thumbnail 2"]); + } +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 351219b9..27309ca9 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -19,9 +19,32 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; +use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; +/// A shelf tile's size in points. +const TILE_WIDTH: f32 = 72.0; +const TILE_HEIGHT: f32 = 86.0; +/// Corner radius of a tile's hover and selection highlights, in points. +const TILE_ROUNDING: f32 = 3.0; +/// The thumbnail's size in a tile and its center below the tile's top, in points. +const THUMBNAIL_SIZE: f32 = 56.0; +const THUMBNAIL_CENTER_Y: f32 = 32.0; +/// A placeholder disc's radius relative to the thumbnail's width. +const PLACEHOLDER_RADIUS: f32 = 0.45; +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +const LABEL_FONT_SIZE: f32 = 9.5; +const LABEL_GAP: f32 = 3.0; +const LABEL_MARGIN: f32 = 4.0; +/// The hover preview's size and its gap above the label, in points. +const BIG_PREVIEW_SIZE: f32 = 256.0; +const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; +/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside +/// the popup's delay). +const BIG_PREVIEW_DWELL: f32 = 0.1; + #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Tab { Materials, @@ -267,13 +290,8 @@ fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter tiles(ui, |ui| { for m in shown.iter().filter(|m| m.category == cat) { let tex = app.thumbs.material(ctx, m.id); - let hint = if m.smart { - tr("Add the smart material folder above the selected layer (or drag it into the layer stack)") - } else { - tr("Add a fill layer with this material above the selected layer (or drag it into the layer stack)") - }; let asset = Asset::Material(m.id); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -340,8 +358,7 @@ fn smart_masks(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt for m in shown { let tex = app.thumbs.smart_mask(ctx, m.id); let asset = Asset::SmartMask(m.id); - let hint = tr("Replace the selected layer's mask with this smart mask (or drag it onto a layer)"); - if tile(ui, tex.as_ref(), m.label, hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::SmartMask(m.id), m.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -361,13 +378,8 @@ fn filters(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for f in shown.iter().filter(|f| f.group == group) { let tex = app.thumbs.filter(ctx, f.id); - let hint = if f.mask { - tr("Add to the selected layer's content, or its mask when the mask is selected (or drag it onto a layer)") - } else { - tr("Add this finish to the selected layer's roughness and height (or drag it onto a layer)") - }; let asset = Asset::Filter(f.id); - if tile(ui, tex.as_ref(), tr(f.label), hint, Some(&asset)).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Filter(f.id), tr(f.label), Some(&asset)).clicked() { apply(app, &asset); } } @@ -386,7 +398,7 @@ fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for p in shown.iter().filter(|p| p.category == cat) { let tex = app.thumbs.brush_preset(ctx, p); - if tile(ui, tex.as_ref(), p.label, tr("Use this brush (keeps its size)"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Brush(p), p.label, None).clicked() { app.run("brush.preset.apply", json!({"preset": p.id})); } } @@ -467,9 +479,9 @@ fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, fi for &a in shown.iter().filter(|a| a.category == cat) { let tex = app.thumbs.alpha(ctx, a); let asset = Asset::Alpha(&a.id); - let r = tile(ui, tex.as_ref(), &a.label, tr("Use as the brush alpha (or drag it onto the viewport or brush properties)"), Some(&asset)); + let r = tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Alpha(a), &a.label, Some(&asset)); if current.as_deref() == Some(a.id.as_str()) { - ui.painter().rect_stroke(r.rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(r.rect, TILE_ROUNDING, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } if r.clicked() { apply(app, &asset); @@ -488,7 +500,7 @@ fn procedurals(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filt tiles(ui, |ui| { for k in shown { let tex = app.thumbs.procedural(ctx, k); - if tile(ui, tex.as_ref(), tr(k.label()), tr("Add a fill layer using this pattern"), None).clicked() { + if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Procedural(k), tr(k.label()), None).clicked() { app.run("layer.add.fill", json!({"name": k.label()})); app.run("layer.fill.set", json!({"channel": "baseColor", "procedural": k.label(), "low": [0.1, 0.1, 0.1], "high": [0.9, 0.9, 0.9]})); } @@ -531,7 +543,8 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: let Some(img) = app.session.images.get(&name).cloned() else { continue }; let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); - let r = tile(ui, Some(&tex), &name, tr("Add a fill layer using this image (or drag it onto the 3D view to place it as a decal)"), Some(&asset)); + let preview = || ShelfPreview::Image(name.clone(), img); + let r = tile(ui, &mut app.thumbs, Some(&tex), preview, &name, Some(&asset)); if r.clicked() { apply(app, &asset); } @@ -550,32 +563,74 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. -fn tile(ui: &mut Ui, tex: Option<&egui::TextureHandle>, label: &str, hint: &str, drag: Option<&Asset>) -> egui::Response { +/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +fn tile( + ui: &mut Ui, + thumbs: &mut Thumbs, + tex: Option<&egui::TextureHandle>, + preview: impl FnOnce() -> ShelfPreview, + label: &str, + drag: Option<&Asset>, +) -> egui::Response { let tk = Tokens::get(ui.ctx()); let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; - let (rect, resp) = ui.allocate_exact_size(vec2(72.0, 86.0), sense); + let (rect, resp) = ui.allocate_exact_size(vec2(TILE_WIDTH, TILE_HEIGHT), sense); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); if let Some(asset) = drag && resp.drag_started() { resp.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label: label.to_string() }); } - let p = ui.painter(); + + let painter = ui.painter(); if resp.hovered() || resp.dragged() { - p.rect_filled(rect, 3.0, tk.row_hover); + painter.rect_filled(rect, TILE_ROUNDING, tk.row_hover); } - let img = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, 32.0), vec2(56.0, 56.0)); + let image_rect = egui::Rect::from_center_size(rect.center_top() + vec2(0.0, THUMBNAIL_CENTER_Y), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(painter, tex, image_rect, &tk); + let galley = painter.layout(label.to_string(), egui::FontId::proportional(LABEL_FONT_SIZE), tk.text, rect.width() - LABEL_MARGIN); + painter.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, image_rect.bottom() + LABEL_GAP), galley, tk.text); + + let big = if resp.hovered() { big_preview(ui, thumbs, preview) } else { None }; + resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) +} + +/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so +/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the +/// worker renders it). +fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { + let ctx = ui.ctx(); + let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + let still_for = ui.input(|i| i.pointer.time_since_last_movement()); + if still_for >= BIG_PREVIEW_DWELL { + return thumbs.big(ctx, preview(), size_px); + } + + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + thumbs.rendered_big(ctx, &preview(), size_px) +} + +/// `tex` drawn into `rect`, or a placeholder disc while it renders. +fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { - p.image(t.id(), img, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - p.circle_filled(img.center(), img.width() * 0.45, tk.row_hover); + painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); } } - let galley = p.layout(label.to_string(), egui::FontId::proportional(9.5), tk.text, rect.width() - 4.0); - p.galley(egui::pos2(rect.center().x - galley.size().x * 0.5, img.bottom() + 3.0), galley, tk.text); - resp.on_hover_ui(|ui| { - ui.label(format!("{label}: {hint}")); - }) +} + +/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it +/// renders) over the label. +fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { + let tk = Tokens::get(ui.ctx()); + ui.set_max_width(BIG_PREVIEW_SIZE); + ui.vertical_centered(|ui| { + let (rect, _) = ui.allocate_exact_size(vec2(BIG_PREVIEW_SIZE, BIG_PREVIEW_SIZE), Sense::hover()); + thumbnail(ui.painter(), big.or(small), rect, &tk); + ui.add_space(BIG_PREVIEW_LABEL_GAP); + ui.label(label); + }); } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs new file mode 100644 index 00000000..f8cc7e3b --- /dev/null +++ b/crates/ui-egui/src/shelf_preview.rs @@ -0,0 +1,102 @@ +//! What a shelf preview shows, and how to render it at any size. + +use std::sync::Arc; + +use egui::ColorImage; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::paint::BrushSettings; +use texturecraft_engine::paint::alphas::LibraryAlpha; +use texturecraft_engine::paint::presets::BrushPreset; +use texturecraft_engine::preview; + +use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; + +/// The asset a shelf tile previews. +pub enum ShelfPreview { + /// A built-in material or smart material on a sphere. + Material(&'static str), + /// A smart mask on the baked preview shape (only the preview worker can render it: see + /// [`crate::preview_request::PreviewRequest::render`]). + SmartMask(&'static str), + /// A library filter on a sample material on a sphere. + Filter(&'static str), + /// A procedural pattern as a grayscale swatch. + Procedural(ProceduralKind), + /// A library brush alpha, white on black. + Alpha(&'static LibraryAlpha), + /// A brush preset's stroke along an S curve. + Brush(&'static BrushPreset), + /// An image resource by name. + Image(String, Arc), +} + +impl ShelfPreview { + /// The cache key of the preview (one per asset). + pub fn key(&self) -> String { + match self { + ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMask(id) => format!("mask:{id}"), + ShelfPreview::Filter(id) => format!("filter:{id}"), + ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), + ShelfPreview::Alpha(alpha) => format!("alpha:{}", alpha.id), + ShelfPreview::Brush(preset) => format!("brush:{}", preset.id), + ShelfPreview::Image(name, _) => format!("image:{name}"), + } + } + + /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are + /// None here: they need the baked preview shape, which only the preview worker holds, so the + /// UI thread never bakes. + pub fn image(&self, size: usize) -> Option { + match self { + ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), + ShelfPreview::SmartMask(_) => None, + ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), + ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), + ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), + ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size)), + ShelfPreview::Image(_, image) => Some(image_preview(image, size)), + } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::filter_lib::FILTERS; + use texturecraft_engine::materials::MATERIALS; + use texturecraft_engine::paint::alphas; + use texturecraft_engine::paint::presets::PRESETS; + + use super::*; + + /// The hover preview's size at 100 % scale. + const BIG_PX: usize = 256; + + #[test] + fn every_tab_renders_a_big_preview() { + let image = ImageRes { width: 4, height: 2, rgba: vec![[0.8, 0.4, 0.2, 1.0]; 8], srgb: true }; + let previews = [ + ShelfPreview::Material(MATERIALS[0].id), + ShelfPreview::Filter(FILTERS[0].id), + ShelfPreview::Procedural(ProceduralKind::ALL[0]), + ShelfPreview::Alpha(&alphas::library()[0]), + ShelfPreview::Brush(&PRESETS[0]), + ShelfPreview::Image("image".into(), Arc::new(image)), + ]; + for preview in previews { + let key = preview.key(); + let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); + assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); + assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + } + + // The shaded spheres come from finite material values + let finite = |samples: Vec>| { + samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + }; + assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); + assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + } +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index f5590b31..982caa17 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,95 +1,51 @@ -//! Thumbnails: shaded material spheres, smart masks on a baked preview shape, procedural swatches -//! and brush alpha previews, rendered on the CPU into cached egui textures (no image assets). New -//! shelf thumbnails are rendered lazily, a few per frame, so opening the shelf never stalls a -//! frame; the smart mask previews render together on a worker. +//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small +//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a +//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big +//! hover previews render on a worker. -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::paint::presets::BrushPreset; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, Shape, alphas}; -use texturecraft_engine::preview::{self, Sample}; +use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::texel::linear_to_srgb; -use crate::mask_previews::MaskPreviews; +use crate::preview_image::{aces, image_preview, shade}; +use crate::preview_request::PreviewRequest; +use crate::preview_worker::PreviewWorker; +use crate::shelf_preview::ShelfPreview; +use crate::worker_preview::WorkerPreview; /// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). const PER_FRAME: usize = 2; -/// Shelf sphere thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels. const SPHERE_PX: usize = 72; +/// Shelf procedural swatch size in pixels. +const PROCEDURAL_PX: usize = 56; +/// Shelf alpha and brush stroke swatch size in pixels. +const SWATCH_PX: usize = 64; +/// Image resource preview size in pixels. +const IMAGE_PX: usize = 64; +/// Big hover previews kept at most (the least recently shown go first). +const BIG_PREVIEWS_KEPT: usize = 32; +/// The shelf's and the brush panel's preview textures. #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by key (`mat:`, `mask:`, `filter:`, `proc:`, `alpha:`, - /// `brush:`). + /// Shelf thumbnails by [`ShelfPreview::key`]. shelf: HashMap, images: HashMap, /// (frame, thumbnails rendered in it). budget: (u64, usize), - mask_previews: MaskPreviews, -} - -fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { - let l = [0.45f32, 0.7, 0.55]; - let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); - let l = l.map(|v| v / len); - let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); - let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. - let h = [l[0], l[1], l[2] + 1.0]; - let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); - let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); - let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; - let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. - let ry = 2.0 * ndv * n[1]; - let w = 0.06 + rough * 0.9; - let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); - let sharp = 0.04 + 0.03 * (ry + 1.0) + (0.2 + 0.55 * ry.max(0.0)) * t * t * (3.0 - 2.0 * t); - let env = sharp + (0.28 - sharp) * (rough * rough); - let fres = (1.0 - ndv).powi(5); - let sky = 0.35 + 0.25 * n[1]; - let mut out = [0.0; 3]; - for k in 0..3 { - let f0 = 0.04 + (base[k] - 0.04) * metal; - let f = f0 + ((1.0 - rough).max(f0) - f0) * fres; - let diffuse = base[k] * (1.0 - metal) * (ndl * 0.85 + sky * 0.5); - out[k] = diffuse * (1.0 - f) + f * env + f0 * spec_amt * ndl * 1.5; - } - out -} - -fn aces(x: f32) -> f32 { - let v = x * 0.6; - ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) -} - -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. -pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; - let (x, y) = (i % size, i / size); - let c = s.height; - // Central differences (image y points down). - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); - } - img + /// Renders the smart mask thumbnails and the big previews. + worker: PreviewWorker, + /// Worker-rendered previews by [`worker_key`]. + rendered: HashMap, + /// The keys of the big previews in `rendered`, least recently shown first. + big_shown: VecDeque, + /// The frame that last took in the worker's results. + received_in_pass: u64, } impl Thumbs { @@ -114,38 +70,24 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, nearest downsample). + /// Cached preview of an image resource (64 px, letterboxed). pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); } - let n = 64usize; - // Letterboxed to keep its proportions, over black where it is transparent. - let aspect = img.width as f32 / img.height.max(1) as f32; - let (sx, sy) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; - let mut ci = ColorImage::filled([n, n], Color32::BLACK); - for y in 0..n { - for x in 0..n { - let (u, v) = (((x as f32 + 0.5) / n as f32 - 0.5) * sx + 0.5, ((y as f32 + 0.5) / n as f32 - 0.5) * sy + 0.5); - if !((0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v)) { - continue; - } - let s = img.sample(u, v); - let enc = |c: f32| if img.srgb { (c.clamp(0.0, 1.0) * s[3].clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(c * s[3]) * 255.0) as u8 }; - ci.pixels[y * n + x] = Color32::from_rgb(enc(s[0]), enc(s[1]), enc(s[2])); - } - } - let t = ctx.load_texture(format!("res_{name}"), ci, TextureOptions::LINEAR); + let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR); self.images.insert(name.to_string(), t.clone()); t } - /// A cached shelf thumbnail, rendering it with `render` if this frame's budget allows (None - /// until then; a repaint is requested so it follows shortly). - fn shelf(&mut self, ctx: &egui::Context, key: String, render: impl FnOnce() -> ColorImage) -> Option { + /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget + /// allows (None until then; a repaint is requested so it follows shortly). + fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = preview.key(); if let Some(t) = self.shelf.get(&key) { return Some(t.clone()); } + let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); @@ -155,110 +97,117 @@ impl Thumbs { return None; } self.budget.1 += 1; - let t = ctx.load_texture(format!("thumb_{key}"), render(), TextureOptions::LINEAR); + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); self.shelf.insert(key, t.clone()); Some(t) } - /// Sphere thumbnail of built-in material `id`. - pub fn material(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("mat:{id}"), || sphere_image(SPHERE_PX, &preview::material(id, SPHERE_PX).unwrap_or_default())) + /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it + /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { + self.receive(ctx); + + let key = worker_key(&preview, size_px); + if !self.rendered.contains_key(&key) { + let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); + self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); + } + self.ready(&key) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the thumbnails - /// render; they all arrive together). - pub fn smart_mask(&mut self, ctx: &egui::Context, id: &str) -> Option { - let key = format!("mask:{id}"); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + /// The worker-rendered preview under `key` if it arrived. + fn ready(&self, key: &str) -> Option { + match self.rendered.get(key) { + Some(WorkerPreview::Ready(t)) => Some(t.clone()), + Some(WorkerPreview::Rendering | WorkerPreview::Failed) | None => None, + } + } + + /// Take in the worker's finished previews, once per frame (dropping the ones no longer + /// wanted). + fn receive(&mut self, ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + if self.received_in_pass == pass { + return; + } + self.received_in_pass = pass; + + for (key, image) in self.worker.poll() { + let Some(entry) = self.rendered.get_mut(&key) else { continue }; + + *entry = match image { + Some(image) => WorkerPreview::Ready(ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR)), + None => WorkerPreview::Failed, + }; } - for (mask_id, image) in self.mask_previews.poll(ctx, SPHERE_PX).unwrap_or_default() { - let mask_key = format!("mask:{mask_id}"); - let t = ctx.load_texture(format!("thumb_{mask_key}"), image, TextureOptions::LINEAR); - self.shelf.insert(mask_key, t); + // A stopped worker never answers the rest + if self.worker.is_stopped() { + for entry in self.rendered.values_mut().filter(|e| matches!(e, WorkerPreview::Rendering)) { + *entry = WorkerPreview::Failed; + } } - self.shelf.get(&key).cloned() + } + + /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the + /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { + let key = worker_key(&preview, size_px); + self.big_shown.retain(|k| *k != key); + self.big_shown.push_back(key); + while self.big_shown.len() > BIG_PREVIEWS_KEPT { + if let Some(oldest) = self.big_shown.pop_front() { + self.rendered.remove(&oldest); + } + } + + self.worker_rendered(ctx, preview, size_px, true) + } + + /// The big preview of `preview` if the worker already rendered it (requests nothing). + pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { + self.receive(ctx); + self.ready(&worker_key(preview, size_px)) + } + + /// Sphere thumbnail of built-in material `id`. + pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + } + + /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders + /// it). + pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } /// Sphere thumbnail of library filter `id` applied to a sample material. - pub fn filter(&mut self, ctx: &egui::Context, id: &str) -> Option { - self.shelf(ctx, format!("filter:{id}"), || sphere_image(SPHERE_PX, &preview::filter(id, SPHERE_PX).unwrap_or_default())) + pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { + self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `k`. - pub fn procedural(&mut self, ctx: &egui::Context, k: ProceduralKind) -> Option { - use texturecraft_engine::compose::pattern::{Coords, procedural}; - use texturecraft_engine::core::{Procedural, Projection}; - use texturecraft_engine::geom::glam::{Vec2, Vec3}; - self.shelf(ctx, format!("proc:{k:?}"), || { - let n = 56usize; - let pr = Procedural { scale: 3.0, ..Procedural::new(k) }; - let mut img = ColorImage::filled([n, n], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % n) as f32 + 0.5) / n as f32, ((i / n) as f32 + 0.5) / n as f32); - let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); - } - img - }) + /// Grayscale swatch of procedural `kind`. + pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { + self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `a`. - pub fn alpha(&mut self, ctx: &egui::Context, a: &alphas::LibraryAlpha) -> Option { - self.shelf(ctx, format!("alpha:{}", a.id), || { - let n = 64usize; - ColorImage::new([n, n], a.render(n, 2).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect()) - }) + /// White-on-black swatch of library alpha `alpha`. + pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { + self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } /// A brush preset's stroke along an S curve. - pub fn brush_preset(&mut self, ctx: &egui::Context, p: &BrushPreset) -> Option { - self.shelf(ctx, format!("brush:{}", p.id), || stroke_preview(&p.applied(&BrushSettings::default()), 64)) + pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { + self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. -fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { - let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = n as f32 * 0.11; - let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); - let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); - let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. - let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; - let step = (b.spacing * 2.0 * radius).max(0.5); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); - let mut last = curve(0.0); - while t <= 1.0 && i < 2000 { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; - t += 0.002; - if travelled < step { - continue; - } - travelled = 0.0; - i += 1; - let r = radius * (1.0 - b.jitter_size * rnd(i, 1)); - let tangent = if b.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = b.angle.to_radians() + tangent + b.jitter_angle * std::f32::consts::TAU * rnd(i, 2); - let (cx, cy) = (p.0 + b.jitter_position * radius * (rnd(i, 3) * 2.0 - 1.0), p.1 + b.jitter_position * radius * (rnd(i, 4) * 2.0 - 1.0)); - let flow = b.flow * (1.0 - b.jitter_flow * rnd(i, 5)); - let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - r).floor().max(0.0) as usize, ((cx + r).ceil() as usize).min(n)); - let (y0, y1) = ((cy - r).floor().max(0.0) as usize, ((cy + r).ceil() as usize).min(n)); - for y in y0..y1 { - for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); - let a = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, b.hardness, i) * flow; - let c = &mut cover[y * n + x]; - *c = 1.0 - (1.0 - *c) * (1.0 - a.clamp(0.0, 1.0)); - } - } - } - ColorImage::new([n, n], cover.into_iter().map(|v| Color32::from_gray((v * b.opacity * 255.0 + 0.5) as u8)).collect()) +/// The key of a worker-rendered preview: one per asset and size. +fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { + format!("{}@{size_px}", preview.key()) } /// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs new file mode 100644 index 00000000..0252d69f --- /dev/null +++ b/crates/ui-egui/src/worker_preview.rs @@ -0,0 +1,13 @@ +//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache +//! tracks it. + +use egui::TextureHandle; + +/// Where a worker-rendered preview is. +pub enum WorkerPreview { + /// Requested; the worker has not answered yet. + Rendering, + Ready(TextureHandle), + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + Failed, +} diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs new file mode 100644 index 00000000..4dbaaa7b --- /dev/null +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -0,0 +1,110 @@ +//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer +//! rests on the tile. + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf_preview::ShelfPreview; + +/// The shelf's Materials tab. +const MATERIALS_TAB: usize = 0; +/// The hover preview's size in points (pixels at this scale). +const BIG_PREVIEW_SIZE: f32 = 256.0; +/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +const STEP_SECONDS: f32 = 0.001; +/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +const POPUP_DELAY: f32 = 0.5; +const REST: f32 = 0.1; +/// Real time the worker gets to render. +const WORKER_TIMEOUT: Duration = Duration::from_secs(60); + +/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show +/// nowhere else. +fn materials_shelf(step_seconds: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(step_seconds).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.shelf_tab = MATERIALS_TAB; + h.run_steps(4); + + let unique: Vec<_> = MATERIALS.iter().filter(|m| !m.smart && h.query_all_by_label(m.label).count() == 1).take(2).collect(); + assert_eq!(unique.len(), 2, "two materials with unique names"); + (h, unique) +} + +/// The pixel size of the largest texture (not the font atlas) the last frame drew at least +/// `min_width` points wide. +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { + let textures = h.ctx.tex_manager(); + let textures = textures.read(); + h.output() + .shapes + .iter() + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) + .max() +} + +/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { + let ctx = h.ctx.clone(); + h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() +} + +#[test] +fn hovering_a_shelf_tile_shows_its_big_preview() { + let (mut h, materials) = materials_shelf(1.0 / 4.0); + let material = materials[0]; + let tile = h.get_by_label(material.label).rect(); + assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); + h.get_by_label(material.label).hover(); + + // The popup's delay, then the worker + let big_px = BIG_PREVIEW_SIZE as usize; + let start = Instant::now(); + while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { + h.run_steps(1); + std::thread::sleep(Duration::from_millis(20)); + } + + assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); + // The popup's name sits under the big image, below the tile + let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); + assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); +} + +#[test] +fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { + let (mut h, materials) = materials_shelf(STEP_SECONDS); + let (first, second) = (materials[0], materials[1]); + let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); + + // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + let sweep_frames = 40; + for frame in 0..=sweep_frames { + h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); + h.run_steps(1); + } + h.hover_at(egui::pos2(900.0, 500.0)); + h.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + h.run_steps(1); + assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); + + // A rest: the preview renders before the popup opens + h.hover_at(from); + h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); + let start = Instant::now(); + let headroom_frames = ((POPUP_DELAY - REST * 1.2) / STEP_SECONDS) as usize - 1; + for _ in 0..headroom_frames { + if big_preview_ready(&mut h, first) || start.elapsed() > WORKER_TIMEOUT { + break; + } + h.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut h, first), "the preview rendered during the popup's delay"); + assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); +} From a4b62d6e0895e75085ed4fa406215fa84e6ced70 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 03:05:46 +0000 Subject: [PATCH 046/275] Drop a shelf material on the texture set under the cursor While a material or smart material is dragged over the 3D view, the texture set under the cursor shows its mesh edges in the accent color; a drop selects that set and applies the material there. A drop on the background does nothing. The whole-view outline is gone for materials in the 3D view; image drops, the 2D view and the brush zone are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/file_cmds.rs | 2 +- crates/engine/src/painting.rs | 12 +++- crates/render/src/lib.rs | 2 + crates/render/src/renderer.rs | 106 ++++++++++++++++++++++++---- crates/render/src/set_highlight.rs | 61 ++++++++++++++++ crates/render/src/shaders/mesh.wgsl | 24 ++++++- crates/ui-egui/src/shelf.rs | 52 ++++++++++---- crates/ui-egui/src/viewport.rs | 14 +++- crates/ui-egui/tests/shelf_drop.rs | 72 +++++++++++++++++++ 9 files changed, 308 insertions(+), 37 deletions(-) create mode 100644 crates/render/src/set_highlight.rs create mode 100644 crates/ui-egui/tests/shelf_drop.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 0744aca2..f2b95e03 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -132,7 +132,7 @@ impl Session { fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result>> { let opts = ExportOptions { atlas: true, ..opts }; (0..materials) - .map(|m| match self.doc.project.texture_sets.iter().position(|t| t.material == m) { + .map(|m| match self.texture_set_of_material(m) { Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts), _ => Ok(Vec::new()), }) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..6f2a74ff 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -35,6 +35,16 @@ impl Session { pick(&ctx, screen) } + /// The texture set that paints mesh material `material` (a [`SurfaceHit::material`]) + pub fn texture_set_of_material(&self, material: usize) -> Option { + self.doc.project.texture_sets.iter().position(|t| t.material == material) + } + + /// The texture set of the surface under viewport pixel `screen` + pub fn texture_set_at(&self, screen: Vec2, viewport: Vec2) -> Option { + self.pick(screen, viewport).and_then(|hit| self.texture_set_of_material(hit.material)) + } + /// Resolve what a stroke on the selected layer paints into, creating the mask paint effect /// when painting a mask. Must run inside the stroke's history snapshot. fn paint_target(&mut self) -> Result { @@ -560,7 +570,7 @@ impl Session { /// Color picker: copy the material under the cursor into the tool's paint values. pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts()); + let ts = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; let (w, h) = (cache.size.0 as f32, cache.size.1 as f32); let (x, y) = ((hit.uv.x * w).clamp(0.0, w - 1.0) as u32, (hit.uv.y * h).clamp(0.0, h - 1.0) as u32); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 01df6c30..c5ca2221 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -23,8 +23,10 @@ pub mod ibl; pub mod mesh_maps; pub mod readback; pub mod renderer; +pub mod set_highlight; mod subdivide; pub mod trace; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; +pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ea4757d5..4ce9dac3 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -32,6 +32,7 @@ use texturecraft_texel::TILE; use crate::gpu_trace::{Checked, checked}; use crate::ibl; +use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; pub const MSAA: u32 = 4; @@ -76,6 +77,8 @@ struct GlobalsRaw { fwd: [f32; 4], disp: [f32; 4], refr: [f32; 4], + highlight: [f32; 4], + highlight_shift: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -96,6 +99,15 @@ struct BlitRaw { dst: [f32; 4], } +/// Width of the highlighted set's edge lines, in pixels +const HIGHLIGHT_WIDTH_PX: f32 = 1.5; + +/// Opacity of the highlighted set's edge lines +const HIGHLIGHT_OPACITY: f32 = 0.9; + +/// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`) +const HIGHLIGHT_SHIFTS: u32 = 4; + /// How the material is shaded (from the project's display settings and the view mode). #[derive(Clone, Copy, Debug, PartialEq)] pub struct Shade { @@ -134,6 +146,8 @@ pub struct Shade { pub grain: f32, /// Draw the mesh edges over the shaded 3D view (depth tested). pub wireframe_3d: bool, + /// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag) + pub highlight: Option, /// Specular/glossiness shading: base color is the diffuse color and the Specular channel the /// F0 color (roughness arrives as 1 - glossiness from the display conversion). pub spec_gloss: bool, @@ -235,6 +249,7 @@ impl Default for Shade { sharpen: 0.0, grain: 0.0, wireframe_3d: false, + highlight: None, spec_gloss: false, parallax: false, taa: false, @@ -513,6 +528,8 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + /// The highlighted set's mesh edges, wider and in the highlight color + highlight_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -886,7 +903,9 @@ impl Renderer { let blend = Some(wgpu::BlendState::ALPHA_BLENDING); let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth); + let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = + pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); @@ -994,6 +1013,7 @@ impl Renderer { uv_pipeline, wire_pipeline, wire3d_pipeline, + highlight_pipeline, bg_pipeline, blit_pipeline, post_pipeline, @@ -1531,13 +1551,7 @@ impl Renderer { visible: &'a [bool], only: Option, ) -> impl Iterator, &'a SetGpu)> + 'a { - ranges.iter().filter_map(move |&(start, count, material)| { - let ts = self.material_sets.get(material).copied().flatten()?; - if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { - return None; - } - Some((start..start + count, self.sets.get(ts)?)) - }) + drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?))) } /// Keep the key-light shadow map current; returns its view-projection. `light` points to @@ -1707,6 +1721,8 @@ impl Renderer { fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], + highlight: highlight_globals(s, data), + highlight_shift: highlight_shift(frame.size), }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; let post = PostRaw { @@ -1805,7 +1821,7 @@ impl Renderer { /// The scene without transmissive surfaces into `b` (MSAA resolved into mip 0), then its mips. fn behind_pass(&self, encoder: &mut wgpu::CommandEncoder, v: &ViewTargets, b: &Behind, globals_bg: &wgpu::BindGroup, frame: &Frame) { - self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, &self.refr_black); + self.draw_scene(encoder, v, &b.level0, globals_bg, frame, &self.opaque_pipeline, None, None, &self.refr_black); let Some(pipe) = self.mip_pipelines.get(&self.hdr_format) else { return }; for (dst, bg) in &b.mips { fullscreen(encoder, "tc_behind_mip", dst, CLEAR, pipe, bg); @@ -1869,10 +1885,11 @@ impl Renderer { }; // Transmissive surfaces refract what the behind pass rendered this frame. let refr = v.behind.as_ref().filter(|_| frame.shade.refraction).map_or(&self.refr_black, |b| &b.bg); - self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, refr); + let highlight = frame.shade.highlight.filter(|_| uv_ts.is_none()).map(|highlight| (&self.highlight_pipeline, highlight.set)); + self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe` and the wireframe with `wire`. + /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, @@ -1883,6 +1900,7 @@ impl Renderer { frame: &Frame, pipe: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, + highlight: Option<(&wgpu::RenderPipeline, usize)>, refr: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -1912,15 +1930,21 @@ impl Renderer { }; pass.set_bind_group(2, refr, &[]); let geo = self.geometry(m, frame); - // The wireframe draws the mesh's own edges (displaced in the vertex shader too). - for (pipe, vb, ib, ranges) in [(Some(pipe), &geo.vb, &geo.ib, &geo.draws), (wire, &m.geo.vb, &m.lines, &m.line_draws)] { + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + let (highlight, highlight_set) = highlight.unzip(); + let passes = [ + (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), + (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), + (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + ]; + for (pipe, vb, ib, ranges, only, instances) in passes { let Some(pipe) = pipe else { continue }; pass.set_pipeline(pipe); pass.set_vertex_buffer(0, vb.slice(..)); pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, uv_ts) { + for (range, set) in self.drawable(ranges, &frame.visible, only) { pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..1); + pass.draw_indexed(range, 0, 0..instances); } } } @@ -1963,6 +1987,39 @@ impl Renderer { } } +/// Index ranges of `ranges` (first, count, material) whose texture set (from `material_sets`) is visible and is `only`, when given, with that set's index +fn drawable_ranges<'a>( + ranges: &'a [(u32, u32, usize)], + material_sets: &'a [Option], + visible: &'a [bool], + only: Option, +) -> impl Iterator, usize)> + 'a { + ranges.iter().filter_map(move |&(start, count, material)| { + let ts = material_sets.get(material).copied().flatten()?; + if only.is_some_and(|o| o != ts) || !visible.get(ts).copied().unwrap_or(true) { + return None; + } + + Some((start..start + count, ts)) + }) +} + +/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is +fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { + let Some(highlight) = shade.highlight else { return [0.0; 4] }; + + let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) }; + [r, g, b, HIGHLIGHT_OPACITY] +} + +/// Globals `highlight_shift`: how far each of the highlight's line copies moves sideways, in clip units of a `size` pixel target +fn highlight_shift(size: [u32; 2]) -> [f32; 4] { + let half_extra_width = (HIGHLIGHT_WIDTH_PX - 1.0) * 0.5; + let clip_per_pixel = size.map(|pixels| 2.0 / pixels.max(1) as f32); + + [half_extra_width * clip_per_pixel[0], half_extra_width * clip_per_pixel[1], 0.0, 0.0] +} + #[cfg(test)] mod tests { use super::*; @@ -2026,6 +2083,25 @@ mod tests { assert!(!h.renderer.awaiting_gpu()); } + #[test] + fn the_highlight_draws_only_the_highlighted_sets_edges() { + let line_draws = [(0, 4, 0), (4, 6, 1), (10, 2, 2)]; + let material_sets = [Some(0), Some(1), Some(2)]; + let highlighted = |visible: &[bool]| drawable_ranges(&line_draws, &material_sets, visible, Some(1)).collect::>(); + + assert_eq!(highlighted(&[true; 3]), vec![(4..10, 1)]); + assert_eq!(highlighted(&[true, false, true]), vec![], "a hidden set shows no highlight"); + } + + #[test] + fn a_data_view_takes_the_highlight_color_as_it_is() { + let color = [0.8, 0.25, 0.08]; + let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() }; + + assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); + assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping"); + } + #[test] fn a_verdict_that_never_comes_counts_as_a_failure() { let Some((mut h, tx)) = awaiting() else { return }; diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs new file mode 100644 index 00000000..878968c1 --- /dev/null +++ b/crates/render/src/set_highlight.rs @@ -0,0 +1,61 @@ +//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag) + +/// Brightest on-screen value the tone curve can reach without an infinite scene value +const MAX_ACES_SCREEN_VALUE: f32 = 0.99; + +/// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl) +const ACES_INPUT_SCALE: f32 = 0.6; + +/// Draw texture set `set`'s mesh edges over the 3D view in `color` +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SetHighlight { + pub set: usize, + /// The lines' color on screen, linear RGB + pub color: [f32; 3], +} + +impl SetHighlight { + /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] + pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + self.color.map(|screen| { + let screen = screen.max(0.0); + let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; + + exposed / exposure + }) + } +} + +/// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input +fn inverse_aces(screen: f32) -> f32 { + let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen); + let scaled = (-b - (b * b - 4.0 * a * c).max(0.0).sqrt()) / (2.0 * a); + + scaled / ACES_INPUT_SCALE +} + +#[cfg(test)] +mod tests { + use super::*; + + /// post.wgsl's `aces` with exposure `exposure_ev` + fn tone_mapped(scene: f32, exposure_ev: f32) -> f32 { + let v = scene * 2f32.powf(exposure_ev) * ACES_INPUT_SCALE; + ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) + } + + #[test] + fn the_scene_color_shows_the_highlight_color_on_screen() { + let highlight = SetHighlight { set: 0, color: [0.9, 0.3, 0.05] }; + for exposure_ev in [-2.0, 0.0, 1.5] { + let scene = highlight.scene_color(exposure_ev, true); + for (scene, screen) in scene.iter().zip(highlight.color) { + assert!((tone_mapped(*scene, exposure_ev) - screen).abs() < 1e-4, "{exposure_ev} EV: {scene} → {screen}"); + } + } + + assert_eq!(highlight.scene_color(1.0, false), [0.45, 0.15, 0.025], "linear: exposure only"); + } +} diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index cd2e8d80..863d6eae 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -24,6 +24,8 @@ struct Globals { fwd: vec4, // xyz camera view direction (unit), w - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - + highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity + highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - }; @group(0) @binding(0) var g: Globals; @@ -659,8 +661,7 @@ fn fs_wire(i: VOut) -> @location(0) vec4 { // 3D wireframe over the shaded mesh: depth-tested, pulled slightly toward the camera so the // lines win against their own triangles. -@vertex -fn vs_wire3d(v: VIn) -> VOut { +fn wire3d(v: VIn) -> VOut { var o: VOut; o.wpos = v.pos; o.nrm = v.nrm; @@ -671,7 +672,26 @@ fn vs_wire3d(v: VIn) -> VOut { return o; } +@vertex +fn vs_wire3d(v: VIn) -> VOut { + return wire3d(v); +} + @fragment fn fs_wire3d(i: VOut) -> @location(0) vec4 { return vec4(0.35, 0.35, 0.35, 0.45); } + +// The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel +@vertex +fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut { + var o = wire3d(v); + let corner = vec2(f32(copy & 1u), f32((copy >> 1u) & 1u)) * 2.0 - 1.0; + o.clip = vec4(o.clip.xy + corner * g.highlight_shift.xy * o.clip.w, o.clip.zw); + return o; +} + +@fragment +fn fs_wire_highlight(i: VOut) -> @location(0) vec4 { + return g.highlight; +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 351219b9..ea50b11e 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -11,6 +11,7 @@ use texturecraft_engine::core::ProceduralKind; use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; +use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; @@ -119,11 +120,27 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). View3d, } -/// Highlight accepted shelf assets on hover and apply them on drop +/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to +pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + if app.ui.mode != crate::state::Mode::Painting { + return None; + } + + response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + set_under_pointer(app, ui, response) +} + +/// The texture set of the surface under the pointer in the 3D view `response` +fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let local_position = ui.input(|input| input.pointer.interact_pos())? - response.rect.min; + app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) +} + +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; @@ -136,23 +153,28 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag)) { + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } + let pointer = ui.input(|input| input.pointer.interact_pos()); - if let Some(drag) = dnd_release::(response) - && accepts(&drag) - { - match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run( - "layer.add.decal", - json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]}), - ); - } - (asset, _) => apply(app, asset), + let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; + + match (&drag.asset, pointer) { + (Asset::Texture(name), Some(position)) => { + let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); + app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); } + // The background takes nothing + (asset, _) if onto_set(asset) => { + let Some(ts) = set_under_pointer(app, ui, response) else { return }; + + if app.run("textureSet.select", json!({"ts": ts})).is_some() { + apply(app, asset); + } + } + (asset, _) => apply(app, asset), } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 78618f1e..4ebe79b3 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -10,7 +10,7 @@ use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; use texturecraft_engine::core::{BakedMap, Channel}; use texturecraft_engine::geom::glam::{Vec2, Vec3}; use texturecraft_engine::{Tool, ViewMode}; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; use crate::gpu::ViewCallback; @@ -217,6 +217,14 @@ fn shade(app: &TextureCraftApp) -> Shade { } } +/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { + let set = crate::shelf::material_drop_set(app, ui, response)?; + let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); + + Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) +} + /// Show what the GPU side reported (each message once while its toast is up). fn gpu_report_toasts(app: &mut TextureCraftApp, reports: crate::gpu::GpuReports) { let names: Vec = reports.memory.iter().filter_map(|ts| app.session.doc.project.texture_sets.get(*ts).map(|t| t.name.clone())).collect(); @@ -565,11 +573,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: shade(app), + shade: Shade { highlight: drop_highlight(app, ui, &resp), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection, an alpha on the brush. + // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d); // Brush cursor. diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs new file mode 100644 index 00000000..5b35cc06 --- /dev/null +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -0,0 +1,72 @@ +//! A shelf material dropped on the 3D view goes to the texture set under the pointer + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; + +/// Distance between the view points searched for a set or the background +const SEARCH_STEP: f32 = 8.0; + +/// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + assert_eq!(harness.state().session.ts(), 0); + harness +} + +/// The first point of the 3D view showing texture set `set`, or the background when `None` +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| app.session.texture_set_at(Vec2::new(x, y), app.session.viewport) == set) + .map(|(x, y)| rect.min + egui::vec2(x, y)) + .unwrap() +} + +/// Drop a built-in shelf material at `position`, as a drag from the shelf ends there +fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + harness.hover_at(position); + harness.run_steps(2); + + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// Top-level layer count of each texture set +fn stack_sizes(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets.iter().map(|set| set.stack.len()).collect() +} + +#[test] +fn a_material_dropped_on_another_set_goes_to_that_set_and_selects_it() { + let mut harness = sample_app(); + let before = stack_sizes(&harness); + + let base = point_over(&harness, Some(1)); + drop_material(&mut harness, base); + + assert_eq!(harness.state().session.ts(), 1, "the set under the pointer is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1], "only the set under the pointer gets the material"); +} + +#[test] +fn a_material_dropped_on_the_background_changes_nothing() { + let mut harness = sample_app(); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + + let background = point_over(&harness, None); + drop_material(&mut harness, background); + + assert_eq!(harness.state().session.ts(), 0); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); +} From 747068dbdfa5fd78110a6019881be93439c423c4 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Thu, 5 Nov 2026 21:30:34 -0500 Subject: [PATCH 047/275] Fix bake settings and UV tile controls --- crates/automation/src/headless.rs | 2 +- crates/automation/src/render.rs | 2 +- crates/bake/src/lib.rs | 36 ++- crates/bake/src/test/tile_selection.rs | 54 ++++ crates/bake/src/tests.rs | 5 +- crates/compose/src/baked_maps.rs | 53 +++ crates/compose/src/display.rs | 4 +- crates/compose/src/eval.rs | 17 +- crates/compose/src/lib.rs | 1 + crates/compose/src/store.rs | 37 +-- crates/compose/tests/cache_and_instances.rs | 13 +- crates/core/src/block_scales.rs | 43 +++ crates/core/src/lib.rs | 1 + crates/core/src/project.rs | 31 +- crates/engine/src/bake/bake_task.rs | 15 +- crates/engine/src/bake/layout.rs | 46 +++ .../mesh_map_command.rs} | 50 ++- crates/engine/src/bake/mod.rs | 20 ++ crates/engine/src/bake/model_patch.rs | 40 +++ .../paint_command.rs} | 8 +- crates/engine/src/bake/preserve_tiles.rs | 54 ++++ crates/engine/src/bake/tile_command.rs | 42 +++ crates/engine/src/commands.rs | 3 +- crates/engine/src/inspect.rs | 46 +-- crates/engine/src/lib.rs | 8 +- crates/engine/src/meshmap_cmds.rs | 2 +- crates/engine/src/preview.rs | 1 + crates/engine/src/session.rs | 2 + crates/engine/src/uv_tile_cmds.rs | 145 +++++---- crates/engine/tests/bake_resolution.rs | 130 ++++++++ crates/engine/tests/bake_settings.rs | 112 +++++++ crates/engine/tests/bake_tiles.rs | 172 ++++++++++ crates/engine/tests/udim.rs | 28 +- crates/formats/README.md | 5 + crates/formats/src/export/mod.rs | 4 +- crates/formats/src/project_file/mod.rs | 2 + crates/formats/src/project_file/tests.rs | 20 ++ crates/render/src/mesh_maps.rs | 31 +- crates/ui-egui/src/bake_mode.rs | 112 ------- .../ui-egui/src/bake_mode/common_settings.rs | 15 +- crates/ui-egui/src/bake_mode/map_settings.rs | 27 +- crates/ui-egui/src/bake_mode/mod.rs | 216 +++++++++++++ crates/ui-egui/src/gpu.rs | 10 +- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/tests/bake_mode.rs | 302 +++++++++++++++++- crates/ui-egui/tests/ui_snapshots.rs | 45 +++ docs/control-protocol.md | 33 ++ 56 files changed, 1757 insertions(+), 317 deletions(-) create mode 100644 crates/bake/src/test/tile_selection.rs create mode 100644 crates/compose/src/baked_maps.rs create mode 100644 crates/core/src/block_scales.rs create mode 100644 crates/engine/src/bake/layout.rs rename crates/engine/src/{bake_cmds.rs => bake/mesh_map_command.rs} (90%) create mode 100644 crates/engine/src/bake/model_patch.rs rename crates/engine/src/{bake_paint_cmds.rs => bake/paint_command.rs} (97%) create mode 100644 crates/engine/src/bake/preserve_tiles.rs create mode 100644 crates/engine/src/bake/tile_command.rs create mode 100644 crates/engine/tests/bake_resolution.rs create mode 100644 crates/engine/tests/bake_settings.rs create mode 100644 crates/engine/tests/bake_tiles.rs delete mode 100644 crates/ui-egui/src/bake_mode.rs create mode 100644 crates/ui-egui/src/bake_mode/mod.rs diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 87d58648..0af8274d 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -72,7 +72,7 @@ fn join(dir: &str, name: &str) -> String { impl Headless { pub fn new(session: Session, fs: Filesystem) -> Headless { // Bakes run here (CLI, MCP) cast their rays on the GPU when there is one. - texturecraft_engine::bake_cmds::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); Headless { session, fs, gpu: None } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 4621d6a0..c61fce50 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -72,7 +72,7 @@ impl Gpu { // The aux texture behind the mesh-map and mask views (rebuilt every render). let res = texturecraft_render::aux_size(cache.size); let aux = match s.view { - ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)), + ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &comp.block_scales)), ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res), _ => None, }; diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 0b315cdb..67c349a4 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -143,14 +143,20 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer) + bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) } /// Retry on the CPU if the supplied tracer fails pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result { - match bake_in_strips(request, progress, STRIP_TEXELS, tracer) { + bake_tiles(request, progress, &[], Some(tracer)) +} + +/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing +pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { + let tracer = tracer.unwrap_or(&CpuTracer); + match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { Err(BakeError::Tracer(error)) => { - let mut output = bake(request, progress)?; + let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); Ok(output) } @@ -160,8 +166,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) type OutRow<'a> = Vec<&'a mut [f32]>; -fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result { +fn bake_in_strips( + request: &BakeRequest, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { validate(request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + let settings = request.settings; let (tile_width, tile_height) = settings.common.output_size(); let tile_size = (tile_width as usize, tile_height as usize); @@ -196,7 +212,17 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis); strip_mesh.uvs = request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect(); - let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + let mut gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32); + for &(column, row) in excluded_tiles { + let start_x = column as usize * tile_size.0 * samples_per_axis; + let start_y = row as usize * tile_size.1 * samples_per_axis; + let end_y = (start_y + tile_size.1 * samples_per_axis).min(sample_start_y + strip_sample_height); + for sample_y in start_y.max(sample_start_y)..end_y { + let first = (sample_y - sample_start_y) * sample_width + start_x; + gbuffer.tri.get_mut(first..first + tile_size.0 * samples_per_axis).ok_or_else(strip_error)?.fill(NO_TRI); + } + } + let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?; coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| { for (x, covered_pixel) in row.iter_mut().enumerate() { diff --git a/crates/bake/src/test/tile_selection.rs b/crates/bake/src/test/tile_selection.rs new file mode 100644 index 00000000..18f13968 --- /dev/null +++ b/crates/bake/src/test/tile_selection.rs @@ -0,0 +1,54 @@ +use super::{Broken, settings}; +use crate::tracing::CpuTracer; +use crate::{BakeRequest, Progress, bake, bake_in_strips, bake_tiles}; +use texturecraft_core::{BakeAntialiasing, BakedMap, TileGrid}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::{Bvh, primitives}; + +#[test] +fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() { + let mut mesh = primitives::udim_plane(); + let grid = TileGrid::of(&[1001, 1002]).unwrap(); + mesh.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array()))); + let bvh = Bvh::new(&mesh); + let mut settings = settings(32, &[BakedMap::Position, BakedMap::AmbientOcclusion]); + settings.maps.ao.parameters.rays.rays = 4; + settings.common.antialiasing = BakeAntialiasing::Subsampling2x2; + settings.common.dilation = 4; + settings.common.apply_diffusion = true; + let request = BakeRequest { + mesh: &mesh, + bvh: &bvh, + material: 0, + low_base_color: &[], + settings: &settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (2, 1), + }; + let full = bake(&request, &Progress::new()).unwrap(); + for excluded in [[(0, 0)], [(1, 0)]] { + let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap(); + let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap(); + let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap(); + assert_eq!(strips.maps, partial.maps); + assert_eq!(fallback.maps, partial.maps); + assert!(fallback.tracer.contains("Broken unavailable")); + + for map in [BakedMap::Position, BakedMap::AmbientOcclusion] { + let components = map.components(); + for (index, pixel) in partial.maps[&map].chunks_exact(components).enumerate() { + if index % 64 / 32 == excluded[0].0 as usize { + assert_eq!(pixel, &map.neutral()[..components]); + } else { + assert_eq!(pixel, &full.maps[&map][index * components..(index + 1) * components]); + } + } + } + } + + assert!(bake_tiles(&request, &Progress::new(), &[(2, 0)], None).is_err()); + assert!(bake_tiles(&request, &Progress::new(), &[(0, u32::MAX)], None).is_err()); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 00b46b7b..bb75353e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -17,6 +17,9 @@ use super::*; #[path = "test/setting.rs"] mod setting; +#[path = "test/tile_selection.rs"] +mod tile_selection; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { @@ -307,7 +310,7 @@ fn strips_match_a_single_pass() { tiles: (1, 1), }; let whole = bake(&req, &Progress::new()).unwrap(); - let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap(); + let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap(); for (map, a) in &whole.maps { let b = &strips.maps[map]; let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count(); diff --git a/crates/compose/src/baked_maps.rs b/crates/compose/src/baked_maps.rs new file mode 100644 index 00000000..1ce05bf7 --- /dev/null +++ b/crates/compose/src/baked_maps.rs @@ -0,0 +1,53 @@ +use std::collections::BTreeMap; + +use texturecraft_core::{BakedMap, BlockScales}; + +/// Dense mesh maps with `components()` floats per texel in row-major order +/// Each UV tile fills its block independently of the working resolution +/// The width is `resolution`; height follows the output size and UV tile grid +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BakedMaps { + /// Width in texels + pub resolution: u32, + pub maps: BTreeMap>>, +} + +impl BakedMaps { + /// Sample a working atlas texel without resampling the stored bake + pub fn sample_working(&self, map: BakedMap, x: u32, y: u32, size: (u32, u32), scales: &BlockScales) -> Option<[f32; 3]> { + let uv = [(x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32]; + self.sample_uv(map, scales.bake_uv(uv, size)?) + } + + /// Nearest sample in the uniform bake atlas + pub fn sample_uv(&self, map: BakedMap, uv: [f32; 2]) -> Option<[f32; 3]> { + if uv.iter().any(|value| !value.is_finite()) { + return None; + } + + let size = (self.resolution, self.height(map)); + self.sample(map, (uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32, size) + } + + /// Height in texels of map `m`, from its length + pub fn height(&self, m: BakedMap) -> u32 { + self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) + } + + /// Sample the corresponding texel of an image with the supplied output size + pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { + let data = self.maps.get(&map)?; + let width = u64::from(self.resolution.max(1)); + let height = u64::from(self.height(map).max(1)); + let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); + let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); + let component_count = map.components(); + let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; + let texel = data.get(offset..offset.checked_add(component_count)?)?; + Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) + } + + pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { + self.sample(m, x, y, size).map(|v| v[0]) + } +} diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index f78e9470..ba4b675e 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0); + let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let px = &mut out[i * 4..i * 4 + 4]; px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; @@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let px = &mut out[i * 4..i * 4 + 4]; // The baked normal is the base the painted normal details sit on (as in export). let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height)); + let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); match (n, base) { (Some(t), None) => { for (k, d) in px.iter_mut().take(3).enumerate() { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ec75cd97..c5eb4978 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -93,6 +93,7 @@ pub struct Inputs<'a> { pub gbuf: &'a UvGBuffer, pub pixels: &'a PixelStore, pub baked: &'a BakedMaps, + pub block_scales: BlockScales, pub preview: Option<&'a StrokePreview>, /// Imported image resources (fill sources). pub images: &'a ImageStore, @@ -1043,7 +1044,11 @@ impl<'a, 'b> Texel<'a, 'b> { } fn baked(&self, m: BakedMap) -> Option { - self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height)) + self.baked_color(m).map(|value| value[0]) + } + + fn baked_color(&self, map: BakedMap) -> Option<[f32; 3]> { + self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } /// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its @@ -1179,7 +1184,7 @@ impl<'a, 'b> Texel<'a, 'b> { v += (val - v) * o; } EffectKind::ColorSelection { colors, tolerance } => { - let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height)); + let id = self.baked_color(BakedMap::Id); let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); let val = if hit { 1.0 } else { 0.0 }; v += (blend1(e.blend, v, val) - v) * o; @@ -1981,7 +1986,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u false } }; - let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); // A field covers the bounding box of the tiles it is built for, which for a scattered sample @@ -2058,7 +2063,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option< if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, ..*inp }; + let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; let fields = neighbourhood_fields(&solo_inp, &channels, tiles); let out: Vec> = tiles .par_iter() @@ -2135,6 +2140,7 @@ mod tests { gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview, images: &images, bounds: f.mesh.bounds(), @@ -2252,6 +2258,7 @@ mod tests { gbuf: &fixture.gbuf, pixels: &fixture.pixels, baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: fixture.mesh.bounds(), @@ -2606,6 +2613,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), @@ -2667,6 +2675,7 @@ soft {soft:?}" gbuf: &f.gbuf, pixels: &f.pixels, baked: &f.baked, + block_scales: f.project.texture_sets[0].block_scales(), preview: None, images: &images, bounds: f.mesh.bounds(), diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ee940e06..01365a27 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod baked_maps; pub mod below; pub mod display; pub mod eval; diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index cf640e0a..1370c0c0 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -1,9 +1,9 @@ //! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh //! maps. Everything is copy-on-write, so cloning the store for undo is cheap. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; -use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId}; +use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TileImage, from_u16, from_u16_signed}; /// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per @@ -56,38 +56,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 { if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) } } -/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The -/// width is `resolution`; height follows the output size and UV tile grid -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BakedMaps { - /// Width in texels. - pub resolution: u32, - pub maps: BTreeMap>>, -} - -impl BakedMaps { - /// Height in texels of map `m` (from its length). - pub fn height(&self, m: BakedMap) -> u32 { - self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32) - } - - /// Sample the corresponding texel of an image with the supplied output size - pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> { - let data = self.maps.get(&map)?; - let width = u64::from(self.resolution.max(1)); - let height = u64::from(self.height(map).max(1)); - let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1); - let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1); - let component_count = map.components(); - let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?; - let texel = data.get(offset..offset.checked_add(component_count)?)?; - Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] }) - } - - pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option { - self.sample(m, x, y, size).map(|v| v[0]) - } -} +pub use crate::baked_maps::BakedMaps; /// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`). #[derive(Clone, Debug, PartialEq)] diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 020a9de0..d7df0258 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -90,7 +90,18 @@ fn heavy_stack(f: &mut Fixture) -> LayerId { } fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> { - Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() } + Inputs { + project: &f.project, + ts, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked, + block_scales: f.project.texture_sets[ts].block_scales(), + preview: None, + images, + bounds: f.mesh.bounds(), + } } fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite { diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs new file mode 100644 index 00000000..65b2403e --- /dev/null +++ b/crates/core/src/block_scales.rs @@ -0,0 +1,43 @@ +/// Per-block UV tile scale for working-to-bake coordinates, filter radii, and height slopes +/// Empty when every tile fills its block; see [`crate::TextureSet::tile_scale`] +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BlockScales { + pub(crate) block: u32, + pub(crate) cols: u32, + pub(crate) scales: Vec, +} + +impl BlockScales { + /// Working atlas UV → uniform bake atlas UV, excluding unused portions of tile blocks + pub fn bake_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> { + if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + if self.scales.is_empty() { + return Some(uv); + } + + let block = self.block.max(1) as f32; + let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block]; + let origin = position.map(f32::floor); + let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32); + let local = [(position[0] - origin[0]) / scale, (position[1] - origin[1]) / scale]; + if local.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) { + return None; + } + + Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32]) + } + + /// The scale at atlas texel (x, y) + pub fn at(&self, x: u32, y: u32) -> f32 { + let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); + if bx >= self.cols { + return 1.0; + } + + let index = (by as usize).checked_mul(self.cols as usize).and_then(|index| index.checked_add(bx as usize)); + index.and_then(|index| self.scales.get(index)).copied().unwrap_or(1.0) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index ddaa6045..72adf044 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -9,6 +9,7 @@ pub mod bake; pub mod blend; +mod block_scales; pub mod channel; pub mod layer; pub mod project; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 26d4f6e6..36b5f856 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; -pub const FORMAT_VERSION: u32 = 1; +pub const FORMAT_VERSION: u32 = 2; /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -63,6 +63,9 @@ pub struct TextureSet { /// [`TileGrid`], [`TextureSet::block_resolution`] texels square. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub uv_tiles: Vec, + /// UV tiles excluded from baking; missing entries stay included + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub bake_excluded_tiles: BTreeSet, /// Per-tile resolutions overriding `resolution` (UDIM → texels per side). A tile smaller /// than the atlas block fills the block's top-left corner (see [`TextureSet::to_atlas`]). #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -132,26 +135,7 @@ impl TileGrid { } } -/// The fraction of its atlas block the UV tile of each block fills ([`TextureSet::tile_scale`]): -/// such a tile has fewer texels per UV unit, so filter radii and height slopes shrink with it. -/// Empty (every scale 1) unless a tile is smaller than its block. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct BlockScales { - block: u32, - cols: u32, - scales: Vec, -} - -impl BlockScales { - /// The scale at atlas texel (x, y). - pub fn at(&self, x: u32, y: u32) -> f32 { - let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); - if bx >= self.cols { - return 1.0; - } - self.scales.get(by as usize * self.cols as usize + bx as usize).copied().unwrap_or(1.0) - } -} +pub use crate::block_scales::BlockScales; fn one() -> f32 { 1.0 @@ -176,6 +160,7 @@ impl TextureSet { baked: BTreeSet::new(), visible: true, uv_tiles: Vec::new(), + bake_excluded_tiles: BTreeSet::new(), tile_resolutions: BTreeMap::new(), } } @@ -185,6 +170,10 @@ impl TextureSet { TileGrid::of(&self.uv_tiles) } + pub fn has_enabled_bake_tiles(&self) -> bool { + self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile)) + } + /// Height strength for slopes measured over the whole texture width (the viewport shader, /// the path tracer): a UV tile atlas is one tile per column wide. pub fn atlas_height_strength(&self) -> f32 { diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 831a7abc..8c942176 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,7 +1,8 @@ use super::MergedHigh; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_compose::BakedMaps; use texturecraft_core::BakeSettings; use texturecraft_geom::{Bvh, Mesh}; @@ -20,6 +21,9 @@ pub struct BakeTask { pub cage_paint: Option>, /// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles. pub tiles: (u32, u32), + /// Snapshot of tile selection and pixels to retain while the worker runs + pub excluded_tiles: Vec<(u32, u32)>, + pub previous_maps: BakedMaps, /// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`). pub tracer: Option>, } @@ -40,10 +44,9 @@ impl BakeTask { cage_paint: self.cage_paint.as_deref(), tiles: self.tiles, }; - match &self.tracer { - Some(tracer) => bake_on(&request, progress, tracer.as_ref()), - None => bake(&request, progress), - } - .map_err(|e| EngineError::Other(format!("bake failed: {e}"))) + let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref()) + .map_err(|error| EngineError::Other(format!("bake failed: {error}")))?; + super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; + Ok(output) } } diff --git a/crates/engine/src/bake/layout.rs b/crates/engine/src/bake/layout.rs new file mode 100644 index 00000000..70e4b539 --- /dev/null +++ b/crates/engine/src/bake/layout.rs @@ -0,0 +1,46 @@ +use std::sync::Arc; + +use rayon::prelude::*; +use texturecraft_bake::BakePaintMap; +use texturecraft_core::TextureSet; +use texturecraft_geom::glam::Vec2; + +use crate::{EngineError, Result}; + +/// Correction paint stays in working coordinates; the worker reads a uniform bake atlas +pub(super) fn paint_for_bake(painted: &Arc, set: &TextureSet) -> Result> { + let Some(grid) = set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) else { + return Ok(painted.clone()); + }; + + painted.validate().map_err(|error| EngineError::Other(error.to_string()))?; + let (width, height) = (painted.width, painted.height); + let mut values = vec![0.0; painted.values.len()]; + values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| { + for (x, value) in row.iter_mut().enumerate() { + let uv = grid.from_atlas([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]); + *value = painted.sample(Vec2::from_array(set.to_atlas(&grid, uv, uv))); + } + }); + Ok(Arc::new(BakePaintMap { width, height, values })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn correction_paint_follows_the_same_surface_in_bake_coordinates() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let mut paint = BakePaintMap::constant(0.0).resized(128, 64).unwrap(); + paint.paint(&[Vec2::new(0.625, 0.25)], 0.05, 1.0, 1.0, 1.0).unwrap(); + let paint = Arc::new(paint); + let baked = paint_for_bake(&paint, &set).unwrap(); + assert!(paint.sample(Vec2::new(0.625, 0.25)) > 0.99); + assert!(baked.sample(Vec2::new(0.75, 0.5)) > 0.99); + assert_eq!(baked.sample(Vec2::new(0.25, 0.5)), 0.0); + assert_eq!(paint.sample(Vec2::new(0.75, 0.5)), 0.0); + } +} diff --git a/crates/engine/src/bake_cmds.rs b/crates/engine/src/bake/mesh_map_command.rs similarity index 90% rename from crates/engine/src/bake_cmds.rs rename to crates/engine/src/bake/mesh_map_command.rs index d56a2bc0..e5982f18 100644 --- a/crates/engine/src/bake_cmds.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -2,6 +2,8 @@ //! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU //! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise. +use super::model_patch; + use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; @@ -17,7 +19,7 @@ use texturecraft_core::{ use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!( "bake.run", @@ -33,7 +35,7 @@ pub fn specs() -> Vec { "Bake settings", [], None, - "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", + "{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, patch?: nested BakeSettings fields to update after model (omitted fields stay unchanged, null clears optional fields), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}", always, settings ), @@ -90,6 +92,10 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { impl Session { pub fn bake_task(&self, ts: usize) -> Result { let set = self.doc.project.texture_set(ts)?; + if !set.has_enabled_bake_tiles() { + return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); + } + let needs_low_color = set.bake.maps.opacity.is_enabled || (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) { @@ -112,14 +118,25 @@ impl Session { } else { None }; - let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned()); - let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned()); - let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); + let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); + let skew = painted(BakePaintTarget::Skew)?; + let cage_paint = painted(BakePaintTarget::Cage)?; + let grid = set.tile_grid(); + let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, ts, - mesh: self.mesh.clone(), + mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -128,6 +145,8 @@ impl Session { skew, cage_paint, tiles, + excluded_tiles, + previous_maps, tracer, }) } @@ -364,7 +383,7 @@ pub fn settings_params(settings: &BakeSettings) -> Value { /// Apply only the bake parameters supplied by the caller fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> { - // Keep the current command limits until the reference controls are integrated + // Preserve the legacy flat-parameter limits for existing callers const MAX_DILATION_PIXELS: u32 = 256; const MAX_SUFFIX_CHARS: usize = 64; @@ -378,6 +397,14 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> } } + if let Some(patch) = params.get("patch") { + let mut model = json!(settings); + model_patch::apply_patch(&mut model, patch, command)?; + let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + validate_model_settings(&updated, command)?; + *settings = updated; + } + if let Some(resolution) = u64p(params, "resolution") { settings.common.resolution = u32::try_from(resolution) .ok() @@ -604,8 +631,15 @@ fn settings(session: &mut Session, params: &Value) -> Result { } fn bake_run(session: &mut Session, params: &Value) -> Result { - let next = updated_settings(session, params, "bake.run")?; + let next: Vec<_> = updated_settings(session, params, "bake.run")? + .into_iter() + .filter(|(index, _)| session.doc.project.texture_sets.get(*index).is_some_and(|texture_set| texture_set.has_enabled_bake_tiles())) + .collect(); let sets: Vec = next.iter().map(|(index, _)| *index).collect(); + if sets.is_empty() { + return Ok(json!({"baked": [], "tracer": []})); + } + let cpu = boolp(params, "cpu") == Some(true); let tracers = session.edit("Bake mesh maps", |session| { let mut tracers = Vec::with_capacity(next.len()); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 075943b3..213e1ff6 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,11 +1,31 @@ +//! Baking tasks, commands, settings helpers, and the mesh-map baking API + mod bake_mesh; mod bake_meshes; mod bake_task; +mod layout; mod merged_high; +mod mesh_map_command; +mod model_patch; +mod paint_command; +mod preserve_tiles; +mod tile_command; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; pub use merged_high::MergedHigh; +pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; +pub use model_patch::settings_patch; +pub use texturecraft_bake::*; + +use crate::CommandSpec; type MaterialColors = std::sync::Arc>>>; + +pub(crate) fn specs() -> Vec { + let mut commands = mesh_map_command::specs(); + commands.extend(paint_command::specs()); + commands.extend(tile_command::specs()); + commands +} diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs new file mode 100644 index 00000000..871d7dc8 --- /dev/null +++ b/crates/engine/src/bake/model_patch.rs @@ -0,0 +1,40 @@ +use serde_json::{Value, json}; +use texturecraft_core::BakeSettings; + +use crate::Result; +use crate::commands::bad; + +/// Only the changed fields, using the persisted model's names and enum values +pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value { + changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({})) +} + +fn changed_fields(before: &Value, after: &Value) -> Option { + if before == after { + return None; + } + + if let (Some(before), Some(after)) = (before.as_object(), after.as_object()) { + let fields = after + .iter() + .filter_map(|(name, value)| changed_fields(before.get(name).unwrap_or(&Value::Null), value).map(|change| (name.clone(), change))) + .collect(); + Some(Value::Object(fields)) + } else { + Some(after.clone()) + } +} + +/// Merge known fields only; null is a value, so optional settings can be cleared +pub(super) fn apply_patch(model: &mut Value, patch: &Value, command: &str) -> Result<()> { + let fields = patch.as_object().ok_or_else(|| bad(command, "bake settings patch must be an object"))?; + for (name, value) in fields { + let target = model.get_mut(name).ok_or_else(|| bad(command, format!("unknown bake setting `{name}`")))?; + if target.is_object() { + apply_patch(target, value, command)?; + } else { + *target = value.clone(); + } + } + Ok(()) +} diff --git a/crates/engine/src/bake_paint_cmds.rs b/crates/engine/src/bake/paint_command.rs similarity index 97% rename from crates/engine/src/bake_paint_cmds.rs rename to crates/engine/src/bake/paint_command.rs index 80cf4852..1bbe2580 100644 --- a/crates/engine/src/bake_paint_cmds.rs +++ b/crates/engine/src/bake/paint_command.rs @@ -6,7 +6,7 @@ use texturecraft_bake::BakePaintMap; use texturecraft_core::BakePaintTarget; use texturecraft_geom::glam::Vec2; -pub fn specs() -> Vec { +pub(super) fn specs() -> Vec { vec![ cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set( session, @@ -65,7 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re session.doc.bake_paint.insert((texture_set, target), Arc::new(map)); Ok(()) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -76,7 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Ok(()) })?; } - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result { @@ -123,7 +123,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> } Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string())) })?; - Ok(crate::bake_cmds::meshes_json(session)) + Ok(super::meshes_json(session)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs new file mode 100644 index 00000000..27c74ae8 --- /dev/null +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -0,0 +1,54 @@ +use texturecraft_bake::BakeOutput; +use texturecraft_compose::BakedMaps; + +use crate::{EngineError, Result}; + +/// Retain excluded tiles from the worker's snapshot, resampling when output size changes +pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], grid: (u32, u32)) -> Result<()> { + if excluded_tiles.is_empty() { + return Ok(()); + } + + let size = (output.resolution, output.height); + let tile_width = size.0 / grid.0.max(1); + let tile_height = size.1 / grid.1.max(1); + for (map, pixels) in &mut output.maps { + let components = map.components(); + for &(column, row) in excluded_tiles { + for y in row * tile_height..(row + 1) * tile_height { + let first = (y as usize * size.0 as usize + column as usize * tile_width as usize) * components; + let last = first + tile_width as usize * components; + let row_pixels = pixels.get_mut(first..last).ok_or_else(|| EngineError::Other("excluded UV tile lies outside the baked pixels".into()))?; + for (offset, pixel) in row_pixels.chunks_exact_mut(components).enumerate() { + let value = previous.sample(*map, column * tile_width + offset as u32, y, size).unwrap_or_else(|| map.neutral()); + for (component, value) in pixel.iter_mut().zip(value) { + *component = value; + } + } + } + } + } + + // Keep unchecked map outputs too when a partial bake changes the atlas dimensions + for map in previous.maps.keys() { + if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) { + continue; + } + + let components = map.components(); + let count = (size.0 as usize) + .checked_mul(size.1 as usize) + .and_then(|count| count.checked_mul(components)) + .ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?; + let mut pixels = Vec::new(); + pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?; + for y in 0..size.1 { + for x in 0..size.0 { + let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral()); + pixels.extend(value.into_iter().take(components)); + } + } + output.maps.insert(*map, pixels); + } + Ok(()) +} diff --git a/crates/engine/src/bake/tile_command.rs b/crates/engine/src/bake/tile_command.rs new file mode 100644 index 00000000..766a4b84 --- /dev/null +++ b/crates/engine/src/bake/tile_command.rs @@ -0,0 +1,42 @@ +use serde_json::{Value, json}; + +use crate::commands::{CommandSpec, always, bad, boolp, u64p}; +use crate::set_cmds::ts_param; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![cmd!( + "bake.tile.set", + "Include UV tile in bake", + [], + None, + "{ts?, tile: UDIM number, enabled: bool} → {ts, tile, enabled}; excluded tiles keep existing baked pixels", + always, + set_enabled + )] +} + +fn set_enabled(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.tile.set"; + let texture_set = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` must be a UDIM number"))?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` must be true or false"))?; + let settings = session.doc.project.texture_set(texture_set)?; + if !settings.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set {} has no UV tile {tile}", settings.name))); + } + + let was_enabled = !settings.bake_excluded_tiles.contains(&tile); + if enabled != was_enabled { + session.edit("Include UV tile in bake", |session| { + let settings = session.doc.project.texture_set_mut(texture_set)?; + if enabled { + settings.bake_excluded_tiles.remove(&tile); + } else { + settings.bake_excluded_tiles.insert(tile); + } + Ok(()) + })?; + } + Ok(json!({"ts": texture_set, "tile": tile, "enabled": enabled})) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 94bb350c..9f0d126b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -68,8 +68,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); - v.extend(crate::bake_cmds::specs()); - v.extend(crate::bake_paint_cmds::specs()); + v.extend(crate::bake::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); v.extend(crate::preset_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..347b7390 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -129,26 +129,34 @@ pub fn texture_sets(s: &Session) -> Value { json!((0..s.set_count()).map(|i| texture_set(s, i)).collect::>()) } -/// One texture set; UV-tiled sets list their tiles and where each sits in the texel atlas. -pub fn texture_set(s: &Session, i: usize) -> Value { - let Some(t) = s.doc.project.texture_sets.get(i) else { return Value::Null }; - let grid = t.tile_grid(); - let tiles: Vec = - t.uv_tiles.iter().filter_map(|u| grid?.block(*u).map(|(x, y)| json!({ "udim": u, "block": [x, y], "resolution": t.tile_resolution(*u) }))).collect(); +/// One texture set, including UV tile layout and bake selection +pub fn texture_set(session: &Session, index: usize) -> Value { + let Some(texture_set) = session.doc.project.texture_sets.get(index) else { return Value::Null }; + + let grid = texture_set.tile_grid(); + let tiles: Vec = texture_set + .uv_tiles + .iter() + .filter_map(|tile| { + grid?.block(*tile).map(|(x, y)| { + json!({"udim": tile, "block": [x, y], "resolution": texture_set.tile_resolution(*tile), "bakeEnabled": !texture_set.bake_excluded_tiles.contains(tile)}) + }) + }) + .collect(); json!({ - "index": i, - "name": t.name, - "resolution": t.resolution, - "size": t.size(), - "blockResolution": t.block_resolution(), - "uvTiles": t.uv_tiles, + "index": index, + "name": texture_set.name, + "resolution": texture_set.resolution, + "size": texture_set.size(), + "blockResolution": texture_set.block_resolution(), + "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::>(), - "layers": s.doc.project.walk(i).len(), - "parts": crate::set_cmds::parts(s, i), - "baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)), - "visible": t.visible, - "active": i == s.ts(), + "channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "layers": session.doc.project.walk(index).len(), + "parts": crate::set_cmds::parts(session, index), + "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), + "visible": texture_set.visible, + "active": index == session.ts(), }) } @@ -161,7 +169,7 @@ pub fn session(s: &Session) -> Value { "path": s.path, "modified": s.modified, "textureSets": texture_sets(s), - "bakeMeshes": crate::bake_cmds::meshes_json(s), + "bakeMeshes": crate::bake::meshes_json(s), "activeTextureSet": ts, "selectedLayer": s.selected_layer().map(|l| l.0), "target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) }, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ca7cdeea..00fd151e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,10 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -pub mod bake_cmds; -#[path = "bake/mod.rs"] -mod bake_data; -mod bake_paint_cmds; +pub mod bake; pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; @@ -50,14 +47,13 @@ pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; -pub use texturecraft_bake as bake; pub use texturecraft_compose as compose; pub use texturecraft_core as core; pub use texturecraft_formats as formats; diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 2220df34..0fbe1f5b 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -59,7 +59,7 @@ fn set(s: &mut Session, p: &Value) -> Result { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in. Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { - let uv = set.from_atlas(grid, [u, v]); + let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 1dc33631..f6f1ef9c 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -165,6 +165,7 @@ pub fn filter(id: &str, size: usize) -> Option>> { gbuf: &gbuf, pixels: &pixels, baked: &baked, + block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(), preview: None, images: &images, bounds: mesh.bounds(), diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index aeaa5550..36263560 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -728,6 +728,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview, images: &self.images, bounds: self.mesh.bounds(), @@ -816,6 +817,7 @@ impl Session { gbuf: &cache.gbuf, pixels: &self.doc.pixels, baked: self.doc.baked.get(&ts).unwrap_or(&empty), + block_scales: cache.composite.block_scales.clone(), preview: None, images: &self.images, bounds: self.mesh.bounds(), diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index d4659943..cd8c3a76 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -39,61 +39,69 @@ pub fn specs() -> Vec { ] } -fn tile_resolution(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.tile.resolution"; - let ts = ts_param(s, p, CMD)?; - let tile = u64p(p, "tile").and_then(|t| u32::try_from(t).ok()).ok_or_else(|| bad(CMD, "`tile` (a UDIM number) is required"))?; - let r = u64p(p, "resolution").ok_or_else(|| bad(CMD, "`resolution` is required"))?; - let r = check_resolution(u32::try_from(r).unwrap_or(0))?; - let set = s.doc.project.texture_set(ts)?; - if !set.uv_tiles.contains(&tile) { - return Err(bad(CMD, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", set.name, set.uv_tiles))); +fn tile_resolution(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.tile.resolution"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` (a UDIM number) is required"))?; + let resolution = u64p(params, "resolution").ok_or_else(|| bad(COMMAND, "`resolution` is required"))?; + let resolution = check_resolution(u32::try_from(resolution).unwrap_or(0))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; + if !texture_set.uv_tiles.contains(&tile) { + return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles))); } - if set.tile_resolution(tile) == r { - return Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": set.size() })); + + let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile); + if texture_set.tile_resolution(tile) == resolution && !removes_override { + return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() })); } - s.cancel_stroke(); - let size = s.edit("UV tile resolution", |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - if r == set.resolution { - set.tile_resolutions.remove(&tile); + + session.cancel_stroke(); + let size = session.edit("UV tile resolution", |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + if resolution == texture_set.resolution { + texture_set.tile_resolutions.remove(&tile); } else { - set.tile_resolutions.insert(tile, r); + texture_set.tile_resolutions.insert(tile, resolution); + } + check_size(texture_set)?; + let size = texture_set.size(); + if previous.tile_resolution(tile) != resolution { + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)?; } - check_size(set)?; - let size = set.size(); - relayout(&mut s.doc, ts, &old, &mut s.log)?; Ok(size) })?; - Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": size })) + Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": size })) } -fn uv_tiles(s: &mut Session, p: &Value) -> Result { - const CMD: &str = "textureSet.uvTiles"; - let ts = ts_param(s, p, CMD)?; - let enabled = boolp(p, "enabled").ok_or_else(|| bad(CMD, "`enabled` (true or false) is required"))?; - let set = s.doc.project.texture_set(ts)?; +fn uv_tiles(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "textureSet.uvTiles"; + let texture_set_index = ts_param(session, params, COMMAND)?; + let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` (true or false) is required"))?; + let texture_set = session.doc.project.texture_set(texture_set_index)?; let tiles = if enabled { - detect_uv_tiles(&s.source, set.material, Some(true), &mut Vec::new()).map_err(|e| bad(CMD, format!("texture set \"{}\": {e}", set.name)))? + detect_uv_tiles(&session.source, texture_set.material, Some(true), &mut Vec::new()) + .map_err(|error| bad(COMMAND, format!("texture set \"{}\": {error}", texture_set.name)))? } else { Vec::new() }; - if tiles == set.uv_tiles { - return Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": [] })); + if tiles == texture_set.uv_tiles { + return Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": [] })); } - // Leaving UV tile mode keeps tile 1001 (UV 0..1), the area a classic set paints. - let dropped: Vec = set.uv_tiles.iter().copied().filter(|t| !enabled && *t != 1001).collect(); - s.cancel_stroke(); - s.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |s| { - let set = s.doc.project.texture_set_mut(ts)?; - let old = set.clone(); - set.tile_resolutions.retain(|u, _| tiles.contains(u)); - set.uv_tiles = tiles.clone(); - check_size(set)?; - relayout(&mut s.doc, ts, &old, &mut s.log) + + // Leaving UV tile mode keeps tile 1001, the area a classic set paints + let dropped: Vec = texture_set.uv_tiles.iter().copied().filter(|tile| !enabled && *tile != 1001).collect(); + session.cancel_stroke(); + session.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |session| { + let texture_set = session.doc.project.texture_set_mut(texture_set_index)?; + let previous = texture_set.clone(); + texture_set.tile_resolutions.retain(|tile, _| tiles.contains(tile)); + texture_set.bake_excluded_tiles.retain(|tile| tiles.contains(tile)); + texture_set.uv_tiles = tiles.clone(); + check_size(texture_set)?; + relayout(&mut session.doc, texture_set_index, &previous, &mut session.log) })?; - Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": dropped })) + Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": dropped })) } /// Mesh UV → normalized atlas position of UV tile layout `set` (None where the layout holds @@ -119,23 +127,30 @@ fn from_layout(set: &TextureSet, a: [f32; 2]) -> Option<[f32; 2]> { (set.uv_tiles.contains(&udim) && local.0 <= scale && local.1 <= scale).then(|| set.from_atlas(&g, a)) } -/// Resample texture set `ts`'s painted images and baked maps from layout `old` into the set's -/// current layout (inside [`Session::edit`] after changing the set). Notes go to `log`. +/// Move painted images into the working layout and baked maps only when the tile grid changes pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mut Vec) -> Result<()> { let new = doc.project.texture_set(ts)?.clone(); - let map = |a: [f32; 2]| from_layout(&new, a).and_then(|m| to_layout(old, m)); - let ((ow, oh), (nw, nh)) = (old.size(), new.size()); - let texel = |x: f32, y: f32| map([x / nw as f32, y / nh as f32]).map(|o| (o[0] * ow as f32, o[1] * oh as f32)); - let all = TileImage::new(nw, nh, 1); + let map = |uv: [f32; 2]| from_layout(&new, uv).and_then(|mesh_uv| to_layout(old, mesh_uv)); + let (old_size, new_size) = (old.size(), new.size()); + let texel = |x: f32, y: f32| map([x / new_size.0 as f32, y / new_size.1 as f32]).map(|uv| (uv[0] * old_size.0 as f32, uv[1] * old_size.1 as f32)); + let all = TileImage::new(new_size.0, new_size.1, 1); let tiles: Vec<(u32, u32)> = (0..all.tiles_y()).flat_map(|ty| (0..all.tiles_x()).map(move |tx| (tx, ty))).collect(); - // Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the - // map is affine (or None) over each destination tile. - crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true)); + + // Atlas blocks align with the 64-texel storage tiles, making each mapping affine + crate::layer_ops::map_set_images(doc, ts, |image, empty| remap_image(image, new_size, empty, &texel, &tiles, true)); remap_bake_paint(doc, ts, old, &new, &map)?; - if let Some(baked) = doc.baked.get(&ts) { - match remap_baked(baked, old, &new, &map) { - Some(b) => { - doc.baked.insert(ts, b); + + if old.uv_tiles != new.uv_tiles + && let Some(baked) = doc.baked.get(&ts) + { + let mut old_bake = old.clone(); + let mut new_bake = new.clone(); + old_bake.tile_resolutions.clear(); + new_bake.tile_resolutions.clear(); + let bake_map = |uv| from_layout(&new_bake, uv).and_then(|mesh_uv| to_layout(&old_bake, mesh_uv)); + match remap_baked(baked, &old_bake, &new_bake, &bake_map) { + Some(baked) => { + doc.baked.insert(ts, baked); } None => { doc.baked.remove(&ts); @@ -326,6 +341,28 @@ mod tests { assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1001, "resolution": 100})).is_err()); } + #[test] + fn removing_a_tile_override_at_the_sets_current_resolution_restores_inheritance() { + let mut session = udim_session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + + assert!(session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reopened.doc.project.texture_sets[0].tile_resolutions.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + execute(&mut session, "textureSet.resolution", &json!({"resolution": 256})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].tile_resolution(1002), 256); + assert_eq!(session.doc.project.texture_sets[0].bake, before.texture_sets[0].bake); + } + #[test] fn export_writes_each_tile_at_its_own_size() { let mut s = udim_session(); diff --git a/crates/engine/tests/bake_resolution.rs b/crates/engine/tests/bake_resolution.rs new file mode 100644 index 00000000..620de675 --- /dev/null +++ b/crates/engine/tests/bake_resolution.rs @@ -0,0 +1,130 @@ +use std::sync::Arc; + +use serde_json::json; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake detail", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 128, "maps": ["position"], "dilation": 0, "patch": {"common": {"apply_diffusion": false}}})) + .unwrap(); + session +} + +#[test] +fn working_tile_resolution_preserves_bake_samples_and_pixels() { + let mut session = session(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let task = session.bake_task(0).unwrap(); + let output = task.run(&Progress::new()).unwrap(); + assert_eq!((output.resolution, output.height), (256, 128)); + + let gbuffer = UvGBuffer::new(&task.mesh, task.material, output.resolution, output.height); + let mut samples = [0usize; 2]; + for (index, triangle) in gbuffer.tri.iter().enumerate() { + if *triangle != NO_TRI { + samples[(index % 256) / 128] += 1; + } + } + assert_eq!(samples, [128 * 128; 2], "each tile receives the full Bake Output Size"); + assert_eq!(output.maps, original.maps); +} + +#[test] +fn changing_working_resolution_never_resamples_stored_bakes() { + let mut session = session(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + let original = session.doc.baked[&0].clone(); + for resolution in [128, 512, 256] { + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": resolution})).unwrap(); + let current = &session.doc.baked[&0]; + assert!(Arc::ptr_eq(¤t.maps[&BakedMap::Position], &original.maps[&BakedMap::Position]), "working resize must retain the bake buffer"); + assert_eq!(current, &original); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked[&0], original); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + session.redo().unwrap(); + assert_eq!(session.doc.baked[&0], original); + + for resolution in [512, 128] { + execute(&mut session, "textureSet.resolution", &json!({"resolution": resolution})).unwrap(); + assert!(Arc::ptr_eq(&session.doc.baked[&0].maps[&BakedMap::Position], &original.maps[&BakedMap::Position])); + } +} + +#[test] +fn rectangular_bakes_and_excluded_vertical_tiles_ignore_working_resolution() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical bake", mesh, "builtin:udim_plane", None, 256).unwrap(); + execute( + &mut session, + "bake.settings", + &json!({"resolution": 64, "maps": ["position"], "dilation": 0, "patch": {"common": {"resolution_height": "R128", "apply_diffusion": false}}}), + ) + .unwrap(); + let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!((original.resolution, original.height), (64, 256)); + let pixels = original.maps.clone(); + session.apply_bake(0, original).unwrap(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1011, "resolution": 128})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap(); + assert_eq!(output.maps, pixels, "rebaked and excluded tiles both keep their full rectangular detail"); +} + +#[test] +fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { + use texturecraft_engine::compose::{DisplayKind, tile_bytes}; + use texturecraft_engine::formats::export::{Dest, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef}; + + let mut session = session(); + execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + let image = image::GrayImage::from_fn(128, 128, |x, y| image::Luma([(x + y) as u8])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + for tile in [1001, 1002] { + session.import_resource_bytes(&format!("ao.{tile}.png"), bytes.clone()).unwrap(); + } + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": "ao.1001.png"})).unwrap(); + while session.update() {} + + let baked = &session.doc.baked[&0]; + let map = BakedMap::AmbientOcclusion; + assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001); + let composite = &session.caches[0].composite; + let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1); + assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile"); + + let options = ExportOptions::new(ExportPreset { + name: "Bake detail".into(), + maps: vec![MapSpec { + file: "ao.$udim".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })], + }], + }); + let files = session.export_files(&[0], &options).unwrap(); + let file = files.iter().find(|file| file.name == "ao.1002.png").unwrap(); + let exported = image::load_from_memory(&file.bytes).unwrap().to_luma8(); + assert_eq!(exported.dimensions(), (128, 128)); + assert_eq!(exported.get_pixel(120, 120)[0], 240); + assert_eq!(exported.get_pixel(10, 10)[0], 20); + + let layer = session.doc.project.texture_sets[0].stack[0]; + execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap(); + let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap(); + assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout"); +} diff --git a/crates/engine/tests/bake_settings.rs b/crates/engine/tests/bake_settings.rs new file mode 100644 index 00000000..b22c53d9 --- /dev/null +++ b/crates/engine/tests/bake_settings.rs @@ -0,0 +1,112 @@ +use serde_json::json; +use texturecraft_engine::core::{BakeResolution, BakeSettings}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Bake settings", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let second = &mut session.doc.project.texture_sets[1].bake; + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.min_distance = 0.25; + second.maps.ao.parameters.rays.rays = 16; + second.maps.height.parameters.scaling_divisor = 2.0; + session +} + +#[test] +fn nested_settings_patch_preserves_other_fields_and_is_one_undo_step() { + let mut session = session(); + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"rays": 128}}}}}); + + let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap(); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.rays.rays = 128; + } + assert_eq!(session.doc.project, expected); + assert_eq!(result.as_array().unwrap().len(), 2); + assert_eq!(result[1]["model"], json!(expected.texture_sets[1].bake)); + assert_eq!(session.history_labels().len(), history_steps + 1); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.texture_sets, expected.texture_sets); + + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn settings_patch_validates_every_target_before_changing_any() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + // This maximum is valid for the active set but below the second set's minimum + let patch = json!({"maps": {"ao": {"parameters": {"rays": {"max_distance": 0.1}}}}}); + let error = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap_err(); + assert!(error.to_string().contains("minimum occluder distance"), "{error}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); +} + +#[test] +fn settings_patch_rejects_unknown_fields_and_invalid_shapes() { + let mut session = session(); + let before = session.doc.project.clone(); + let history = session.history_labels(); + + for patch in [ + json!(null), + json!([]), + json!({"unknown": 1}), + json!({"common": null}), + json!({"common": {"resolution": "invalid"}}), + json!({"common": {"antialiasing": true}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rays": 257}}}}}), + json!({"maps": {"ao": {"parameters": {"rays": {"rayz": 128}}}}}), + ] { + assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).is_err(), "{patch}"); + assert_eq!(session.doc.project, before); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn settings_patch_can_clear_optional_height_and_keeps_target_selection() { + let mut session = session(); + let first = session.doc.project.texture_sets[0].bake.clone(); + let mut second = session.doc.project.texture_sets[1].bake.clone(); + let patch = json!({"common": {"resolution_height": null}}); + + execute(&mut session, "bake.settings", &json!({"ts": [1], "patch": patch})).unwrap(); + + second.common.resolution_height = None; + assert_eq!(session.doc.project.texture_sets[0].bake, first); + assert_eq!(session.doc.project.texture_sets[1].bake, second); + + let history_steps = session.history_labels().len(); + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {}})).unwrap(); + execute(&mut session, "bake.settings", &json!({"ts": 1, "patch": patch})).unwrap(); + assert_eq!(session.history_labels().len(), history_steps); +} + +#[test] +fn settings_patch_can_reset_one_section_without_replacing_other_settings() { + let mut session = session(); + let mut expected = session.doc.project.clone(); + let defaults = BakeSettings::default().maps.ao.parameters; + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters = defaults; + } + + execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {"maps": {"ao": {"parameters": defaults}}}})).unwrap(); + + assert_eq!(session.doc.project, expected); +} diff --git a/crates/engine/tests/bake_tiles.rs b/crates/engine/tests/bake_tiles.rs new file mode 100644 index 00000000..3f000321 --- /dev/null +++ b/crates/engine/tests/bake_tiles.rs @@ -0,0 +1,172 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::compose::BakedMaps; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut session = Session::new_project("Tile baking", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2})).unwrap(); + session +} + +#[test] +fn tile_selection_is_inspectable_saved_and_undoable() { + let mut session = session(); + let before = session.doc.project.clone(); + let result = execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(result, json!({"ts": 0, "tile": 1002, "enabled": false})); + let selected = session.doc.project.clone(); + let inspected = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); + assert_eq!(inspected["tiles"][0]["bakeEnabled"], true); + assert_eq!(inspected["tiles"][1]["bakeEnabled"], false); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, selected); + + let history = session.history_labels(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + assert_eq!(session.history_labels(), history); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, selected); + + for params in [json!({}), json!({"tile": 1003, "enabled": false}), json!({"tile": u64::MAX, "enabled": false}), json!({"tile": 1001, "enabled": 1})] { + assert!(execute(&mut session, "bake.tile.set", ¶ms).is_err()); + assert_eq!(session.doc.project, selected); + assert_eq!(session.history_labels(), history); + } +} + +#[test] +fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { + let mut session = session(); + session.doc.baked.insert(0, BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + + // Editing the checkboxes while a bake runs affects the next bake + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + let before = session.doc.baked.clone(); + let output = task.run(&Progress::new()).unwrap(); + session.apply_bake(0, output).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + for row in pixels.chunks_exact(64) { + assert!(row[..32].iter().all(|value| *value > 0.99)); + assert!(row[32..].iter().all(|value| *value == 0.25)); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked, before); +} + +#[test] +fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { + let mut session = session(); + session.doc.baked.insert( + 0, + BakedMaps { + resolution: 64, + maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3]))].into(), + }, + ); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([0])); + + let baked = &session.doc.baked[&0]; + assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64)); + for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) { + assert!(row[..64].iter().all(|value| *value > 0.99)); + assert!(row[64..].iter().all(|value| *value == 0.25)); + } + assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3); + assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4)); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.baked, session.doc.baked); +} + +#[test] +fn tile_selection_preserves_the_correct_udim_row() { + let mut mesh = primitives::udim_plane(); + let second_plane = mesh.uvs.len() / 2; + for uv in mesh.uvs.iter_mut().skip(second_plane) { + uv.x -= 1.0; + uv.y -= 1.0; + } + let mut session = Session::new_project("Vertical UV tiles", mesh, "builtin:udim_plane", None, 128).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1011]); + session.doc.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 64]))].into() }); + execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2, "cpu": true})).unwrap(); + + let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; + assert!(pixels[..32 * 32].iter().all(|value| *value == 0.25)); + assert!(pixels[32 * 32..].iter().all(|value| *value > 0.99)); +} + +#[test] +fn excluded_tiles_without_previous_pixels_use_neutral_values() { + let mut session = session(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); + execute(&mut session, "bake.run", &json!({"maps": ["normal", "ambientOcclusion"], "cpu": true})).unwrap(); + let baked = &session.doc.baked[&0]; + for map in [BakedMap::Normal, BakedMap::AmbientOcclusion] { + for row in baked.maps[&map].chunks_exact(64 * map.components()) { + for pixel in row[..32 * map.components()].chunks_exact(map.components()) { + assert_eq!(pixel, &map.neutral()[..map.components()]); + } + } + } +} + +#[test] +fn no_selected_tiles_is_a_noop_and_old_projects_include_every_tile() { + let mut session = session(); + let serialized = serde_json::to_value(&session.doc.project).unwrap(); + assert!(serialized["texture_sets"][0].get("bake_excluded_tiles").is_none()); + let legacy: texturecraft_engine::core::Project = serde_json::from_value(serialized).unwrap(); + assert!(legacy.texture_sets[0].has_enabled_bake_tiles()); + + for tile in [1001, 1002] { + execute(&mut session, "bake.tile.set", &json!({"tile": tile, "enabled": false})).unwrap(); + } + let before = session.doc.project.clone(); + let history = session.history_labels(); + let result = execute(&mut session, "bake.run", &json!({"ts": "selected", "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([])); + assert_eq!(session.doc.project, before); + assert!(session.doc.baked.is_empty()); + assert_eq!(session.history_labels(), history); + assert!(session.bake_task(0).is_err()); + + execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].bake_excluded_tiles.is_empty()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +#[ignore] +fn partial_bake_timing() { + let mut session = session(); + execute(&mut session, "bake.run", &json!({"resolution": 256, "rays": 64, "cpu": true})).unwrap(); + for enabled in [true, false] { + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": enabled})).unwrap(); + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + let mut times = Vec::new(); + for _ in 0..5 { + let started = std::time::Instant::now(); + task.run(&Progress::new()).unwrap(); + times.push(started.elapsed()); + } + times.sort(); + eprintln!("{} of 2 UV tiles, 256 square, AO 64 rays, CPU: median {:?}, runs {:?}", if enabled { 2 } else { 1 }, times[2], times); + } +} diff --git a/crates/engine/tests/udim.rs b/crates/engine/tests/udim.rs index bcfab00b..aff12622 100644 --- a/crates/engine/tests/udim.rs +++ b/crates/engine/tests/udim.rs @@ -48,20 +48,24 @@ fn paint_red_at(s: &mut Session, p: Vec3) { #[test] fn uv_tiles_are_detected_and_inspected() { - let mut s = session(); - let set = execute(&mut s, "textureSet.inspect", &Value::Null).unwrap(); + let mut session = session(); + let set = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap(); assert_eq!(set["uvTiles"], json!([1001, 1002])); assert_eq!(set["size"], json!([2 * RES, RES])); - assert_eq!(set["tiles"], json!([{ "udim": 1001, "block": [0, 0], "resolution": RES }, { "udim": 1002, "block": [1, 0], "resolution": RES }])); - assert_eq!(s.caches[0].size, (2 * RES, RES)); - // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh. - execute(&mut s, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty()); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); - assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); - execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); - assert_eq!(s.doc.project.texture_sets[0].uv_tiles, vec![1001]); - assert_eq!(s.caches[0].size, (RES, RES)); + assert_eq!( + set["tiles"], + json!([{ "udim": 1001, "block": [0, 0], "resolution": RES, "bakeEnabled": true }, { "udim": 1002, "block": [1, 0], "resolution": RES, "bakeEnabled": true }]) + ); + assert_eq!(session.caches[0].size, (2 * RES, RES)); + + // Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh + execute(&mut session, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty()); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap(); + assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic"); + execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap(); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, vec![1001]); + assert_eq!(session.caches[0].size, (RES, RES)); } #[test] diff --git a/crates/formats/README.md b/crates/formats/README.md index 7b28004e..a52e80a5 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -145,6 +145,11 @@ pub fn load_project(path: &Path) -> Result; // native allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless). Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE. +Project format version 2 stores baked maps in uniform UV tile blocks, independent of working +tile-resolution overrides. Older projects load their stored bake pixels as-is, without converting +the old layout; their appearance may change until rebaked. Painted layers and cage/skew correction +maps retain their working atlas layout. + Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f8fc1b97..24fc9833 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -596,7 +596,9 @@ impl Sampler<'_> { fn baked(&self, m: BakedMap, at: At) -> [f32; 3] { match at { - At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, (self.res, self.comp.height)).unwrap_or(m.neutral()), + At::Texel(x, y) if self.set.baked.contains(&m) => { + self.baked.sample_working(m, x, y, (self.res, self.comp.height), &self.scales).unwrap_or(m.neutral()) + } _ => m.neutral(), } } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 045dd0da..115ed5e0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -455,6 +455,8 @@ fn load(reader: R) -> Result { // Ignore other entries from newer minor revisions } + pf.project.format_version = FORMAT_VERSION; + if recovered { pf.warnings.push( "Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(), diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 0a3c5067..7f756554 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -82,6 +82,26 @@ fn round_trip_is_identical_and_deterministic() { assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap()); } +#[test] +fn legacy_bakes_load_as_is_without_layout_conversion() { + let mut sample = sample(); + sample.pf.project.format_version = 1; + sample.pf.pixels.layers.clear(); + let set = &mut sample.pf.project.texture_sets[0]; + set.resolution = 256; + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels: Vec = (0..16).flat_map(|y| (0..32).map(move |x| (y * 32 + x) as f32)).collect(); + sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }); + + let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap(); + assert_eq!(loaded.project.format_version, FORMAT_VERSION); + assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout"); + assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout"); + let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap(); + assert_same(&loaded, &reopened); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn save_and_load_through_files() { diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index bf811478..4bfb13dc 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -1,27 +1,46 @@ //! Debug textures for the mesh-map view. use texturecraft_compose::BakedMaps; -use texturecraft_core::BakedMap; -use texturecraft_texel::linear_to_srgb; +use texturecraft_core::{BakedMap, BlockScales}; /// RGBA8 of baked map `m` resampled to `size × size` stretched over the map (mid gray where not /// baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are display /// (sRGB) encoded. -pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec { +pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_size: (u32, u32), scales: &BlockScales) -> Vec { let size = size.max(1); let mut out = vec![128u8; (size * size * 4) as usize]; let Some(b) = baked.filter(|b| b.maps.contains_key(&m)) else { return out }; + for y in 0..size { for x in 0..size { - let v = b.sample(m, x, y, (size, size)).unwrap_or([0.5; 3]); + let uv = [(x as f32 + 0.5) / size as f32, (y as f32 + 0.5) / size as f32]; + let v = scales.bake_uv(uv, working_size).and_then(|uv| b.sample_uv(m, uv)).unwrap_or([0.5; 3]); let i = ((y * size + x) * 4) as usize; for k in 0..3 { - // Data maps are shown as stored, i.e. treated as display values. + // Data maps are shown as stored out[i + k] = (v[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } out[i + 3] = 255; } } - let _ = linear_to_srgb; out } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use texturecraft_core::TextureSet; + + #[test] + fn mesh_map_preview_places_bake_detail_in_the_working_tile() { + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let pixels = (0..128).flat_map(|y| (0..256).map(move |x| ((x % 128) + y) as f32 / 255.0)).collect(); + let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }; + let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, 512, set.size(), &set.block_scales()); + assert_eq!(preview[(240 * 512 + 376) * 4], 240); + assert_eq!(preview[(400 * 512 + 500) * 4], 128, "unused working block area stays neutral"); + } +} diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs deleted file mode 100644 index a5ee88f4..00000000 --- a/crates/ui-egui/src/bake_mode.rs +++ /dev/null @@ -1,112 +0,0 @@ -//! Bake Mode presentation; persisted settings live in core and edits use engine commands - -mod bake_paint_brush; -mod breadcrumb; -mod common_settings; -pub use bake_paint_brush::BakePaintBrush; -mod controls; -mod map_settings; -mod mesh_map_bakers; - -use egui::{Ui, vec2}; -use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; - -use crate::TextureCraftApp; -use crate::i18n::{tr, trf}; -use crate::state::Mode; -use crate::widgets::primary_button; - -pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { - for set_index in 0..app.session.set_count() { - let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; - - let name = texture_set.name.clone(); - let (width, height) = texture_set.bake.common.output_size(); - let mut is_enabled = texture_set.bake.common.is_enabled; - ui.push_id(set_index, |ui| { - ui.horizontal(|ui| { - if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { - app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); - } - if ui.selectable_label(set_index == app.session.ts(), format!("{name} ({width} × {height})")).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - } - }); - }); - } - }); -} - -/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows -pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "mesh_map_bakers", mesh_map_bakers::show); -} - -/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters -pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; - - let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); - breadcrumb::show(app, ui, selected); - ui.separator(); - edit_settings(app, ui, "mesh_map_settings", |_, ui, settings| ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner); -} - -/// The Common Settings panel: output, high poly, cage and skew settings -pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_common_settings", common_settings::show); -} - -/// The map whose settings show: the chosen one, else the first enabled map, else Normal -fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { - selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) -} - -/// Draw `contents` over a copy of the active set's bake settings and run `bake.settings` on change -fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) { - let set_index = app.session.ts(); - let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; - - let mut settings = before.clone(); - egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)); - if settings != before { - app.run("bake.settings", json!({ "ts": set_index, "model": settings })); - } -} - -pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { - egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( - ctx, - |ui| { - ui.horizontal(|ui| { - if let Some(progress) = app.bake_progress() { - ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); - if ui.button(tr("Cancel")).clicked() { - app.cancel_bake(); - } - } else { - let texture_sets: Vec = app - .session - .doc - .project - .texture_sets - .iter() - .enumerate() - .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) - .map(|(index, _)| index) - .collect(); - let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); - if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { - app.start_bake(texture_sets); - } - } - - if ui.button(tr("Return to Painting Mode")).clicked() { - app.ui.mode = Mode::Painting; - } - }); - }, - ); -} diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index fe4819a0..02d712a0 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -4,13 +4,14 @@ use crate::i18n::tr; use crate::widgets::icon_button; use egui::Ui; use egui_phosphor::regular as icon; -use serde_json::json; +use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; /// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage) -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { + let mut reset = Map::new(); ui.push_id("common", |ui| { // Restore Defaults keeps whether the texture set is included in the bake let is_enabled = settings.common.is_enabled; @@ -31,6 +32,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); }) { settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; + let mut defaults = json!(settings.common); + if let Some(fields) = defaults.as_object_mut() { + fields.remove("is_enabled"); + } + reset.insert("common".into(), defaults); } }); @@ -53,6 +59,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); } }); @@ -78,6 +85,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe } }) { settings.cage = Default::default(); + reset.insert("cage".into(), json!(settings.cage)); } }); @@ -100,10 +108,13 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); }) { settings.skew = Default::default(); + reset.insert("skew".into(), json!(settings.skew)); } }); } } + + (!reset.is_empty()).then_some(Value::Object(reset)) } fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 0b5ac9e0..5168d341 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,6 +1,8 @@ use super::controls::{choice, hint, integer, number}; use crate::i18n::tr; use egui::Ui; +use serde::Serialize; +use serde_json::{Value, json}; use texturecraft_engine::core::{ AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization, HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings, @@ -8,28 +10,33 @@ use texturecraft_engine::core::{ }; /// Draw `map`'s parameters with Restore Defaults; maps without parameters say so -pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) { +pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option { match map { - BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => hint(ui, tr("No Parameters")), - BakedMap::Id => parameters(ui, &mut settings.id.parameters, id), - BakedMap::AmbientOcclusion => parameters(ui, &mut settings.ao.parameters, ambient_occlusion), - BakedMap::Curvature => parameters(ui, &mut settings.curvature.parameters, curvature), - BakedMap::Position => parameters(ui, &mut settings.position.parameters, position), - BakedMap::Thickness => parameters(ui, &mut settings.thickness.parameters, thickness), - BakedMap::Height => parameters(ui, &mut settings.height.parameters, height), - BakedMap::BentNormal => parameters(ui, &mut settings.bent_normal.parameters, bent_normal), + BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { + hint(ui, tr("No Parameters")); + None + } + BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id), + BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion), + BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature), + BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position), + BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness), + BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height), + BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal), } } /// A map's controls, then a right-aligned Restore Defaults that resets only its parameters -fn parameters(ui: &mut Ui, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) { +fn parameters(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option { controls(ui, parameters); ui.add_space(6.0); let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; if restore.clicked() { *parameters = T::default(); + return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } + None } fn id(ui: &mut Ui, settings: &mut IdSettings) { diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs new file mode 100644 index 00000000..3a308a4a --- /dev/null +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -0,0 +1,216 @@ +//! Bake Mode presentation; persisted settings live in core and edits use engine commands + +mod bake_paint_brush; +mod breadcrumb; +mod common_settings; +pub use bake_paint_brush::BakePaintBrush; +mod controls; +mod map_settings; +mod mesh_map_bakers; + +use egui::{Ui, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakedMap}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::widgets::{icon_button, primary_button}; + +pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { + egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| { + for set_index in 0..app.session.set_count() { + let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; + + let name = texture_set.name.clone(); + let resolution = texture_set.resolution; + let mut is_enabled = texture_set.bake.common.is_enabled; + let visible = texture_set.visible; + let tiles: Vec<_> = texture_set + .uv_tiles + .iter() + .map(|tile| (*tile, texture_set.tile_resolutions.get(tile).copied(), !texture_set.bake_excluded_tiles.contains(tile))) + .collect(); + + ui.push_id(set_index, |ui| { + ui.horizontal(|ui| { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() { + app.run("textureSet.visible", json!({ "ts": set_index })); + } + if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled })); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None) + && selected != resolution + { + app.start_resize(set_index, selected); + } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + } + }); + }); + }); + + if !tiles.is_empty() { + egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| { + for (tile, override_resolution, enabled) in &tiles { + let mut enabled = *enabled; + ui.push_id(tile, |ui| { + ui.horizontal(|ui| { + if ui.checkbox(&mut enabled, tile.to_string()).on_hover_text(tr("Include in Bake")).changed() { + app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled})); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default(); + let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]); + if let Some(selected) = resolution_menu( + ui, + &label, + text, + override_resolution.unwrap_or(resolution), + override_resolution.map(|_| resolution), + ) { + app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": tile, "resolution": selected})); + } + }); + }) + }); + } + }); + } + }); + } + }); +} + +fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option) -> Option { + let effective_size = format!("{resolution} × {resolution}"); + let measured = if text.is_empty() { &effective_size } else { &text }; + let font = egui::TextStyle::Button.resolve(ui.style()); + let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x; + let width = text_width + ui.spacing().button_padding.x * 2.0; + let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false)); + let popup_id = response.id.with("resolution_menu"); + let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked(); + let shown = if text.is_empty() && (response.hovered() || open) { effective_size } else { text }; + ui.painter().text(response.rect.center(), egui::Align2::CENTER_CENTER, &shown, font, ui.style().interact(&response).text_color()); + + let mut selected = None; + egui::Popup::menu(&response).id(popup_id).show(|ui| { + if let Some(inherited) = inherited_resolution { + if ui.button(tr("Remove resolution override")).clicked() { + selected = Some(inherited); + ui.close(); + } + ui.separator(); + } + for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] { + if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() { + selected = Some(candidate); + } + } + }); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), label); + info.current_text_value = Some(shown.clone()); + info + }); + response.on_hover_text(label); + selected +} + +/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows +pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let texture_set = json!(app.session.ts()); + edit_settings(app, ui, "mesh_map_bakers", texture_set, |app, ui, settings| { + mesh_map_bakers::show(app, ui, settings); + None + }); +} + +/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters +pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; + + let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); + breadcrumb::show(app, ui, selected); + ui.separator(); + edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| { + ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner + }); +} + +/// The Common Settings panel: output, high poly, cage and skew settings +pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { + edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show); +} + +/// The map whose settings show: the chosen one, else the first enabled map, else Normal +fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { + selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) +} + +/// Send changed fields and explicitly reset sections through the same undoable command +fn edit_settings( + app: &mut TextureCraftApp, + ui: &mut Ui, + scroll_id: &str, + texture_sets: Value, + contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, +) { + let set_index = app.session.ts(); + let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return }; + + let mut settings = before.clone(); + let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; + if settings == before && reset.is_none() { + return; + } + + let mut patch = settings_patch(&before, &settings); + if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) { + fields.extend(reset); + } + app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); +} + +pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { + egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( + ctx, + |ui| { + ui.horizontal(|ui| { + if let Some(progress) = app.bake_progress() { + ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); + if ui.button(tr("Cancel")).clicked() { + app.cancel_bake(); + } + } else { + let texture_sets: Vec = app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles()) + .map(|(index, _)| index) + .collect(); + let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]); + if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() { + app.start_bake(texture_sets); + } + } + + if ui.button(tr("Return to Painting Mode")).clicked() { + app.ui.mode = Mode::Painting; + } + }); + }, + ); +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..c6695b34 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -216,8 +216,14 @@ impl GpuLink { if self.aux.get(&ts) == Some(&key) { continue; } - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res))); + let Some(cache) = s.caches.get(ts) else { continue }; + + let res = texturecraft_render::aux_size(cache.size); + out.aux.push(( + ts, + res, + texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + )); self.aux.insert(ts, key); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 294e8964..ebdc5ebc 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1055,4 +1055,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Remove resolution override", "إزالة تجاوز الدقة"), + ("Texture set resolution", "دقة مجموعة الخامات"), + ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 3155e6ce..c2b97532 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1104,4 +1104,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Remove resolution override", "Auflösungsüberschreibung entfernen"), + ("Texture set resolution", "Auflösung des Textursets"), + ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 7ba164a9..5d29bf57 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1089,4 +1089,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Remove resolution override", "Quitar resolución personalizada"), + ("Texture set resolution", "Resolución del conjunto de texturas"), + ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 034d78b5..35f55392 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1113,4 +1113,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Remove resolution override", "Supprimer la résolution personnalisée"), + ("Texture set resolution", "Résolution de l'ensemble de textures"), + ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07ce31ea..b0df32cb 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1098,4 +1098,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Remove resolution override", "Rimuovi risoluzione personalizzata"), + ("Texture set resolution", "Risoluzione del set di texture"), + ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ac768443..eeb64614 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1083,4 +1083,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Remove resolution override", "解像度の上書きを解除"), + ("Texture set resolution", "テクスチャセットの解像度"), + ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 8fa260be..d8b13cfe 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1068,4 +1068,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Remove resolution override", "해상도 재정의 제거"), + ("Texture set resolution", "텍스처 세트 해상도"), + ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 203a94de..444a903f 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1086,4 +1086,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Remove resolution override", "Remover resolução personalizada"), + ("Texture set resolution", "Resolução do conjunto de texturas"), + ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d651ba67..8bad2a36 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1014,4 +1014,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Remove resolution override", "移除分辨率覆盖"), + ("Texture set resolution", "纹理集分辨率"), + ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index df2d1c7a..acaf6385 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -128,7 +128,7 @@ impl TextureCraftApp { theme::install(&cc.egui_ctx); // Bakes cast their rays on a GPU device of their own (created on the first bake). #[cfg(not(target_arch = "wasm32"))] - texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); + texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); // The first run speaks the OS (or browser) language. let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 7802f9d5..88a7c1f2 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -1,7 +1,7 @@ use egui::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; -use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization}; +use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::Mode; @@ -45,6 +45,306 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let label_row = harness.get_by_label(label).rect().center().y; + harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap() +} + +#[test] +fn mesh_map_edits_update_all_sets_without_copying_unedited_fields() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + assert_eq!(session.set_count(), 2); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + second.maps.height.parameters.scaling_divisor = 2.0; + let before = session.doc.project.clone(); + let history_steps = session.history_labels().len(); + + click_checkbox(&mut harness, "Ground Plane"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.maps.ao.parameters.ground_plane.enabled = true; + } + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + assert_eq!(session.history_labels().len(), history_steps + 1); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); + session.redo().unwrap(); + assert_eq!(session.doc.project, expected); +} + +#[test] +fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.maps.select([BakedMap::Height]); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + click_checkbox(&mut harness, "Apply Diffusion"); + + let mut expected = before.clone(); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.apply_diffusion = false; + } + assert_eq!(harness.state().session.doc.project, expected); + + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "256"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.common.resolution = BakeResolution::R256; + } + assert_eq!(harness.state().session.doc.project, expected); + + click_checkbox(&mut harness, "Use Low Poly Mesh as High Poly Mesh"); + for texture_set in &mut expected.texture_sets { + texture_set.bake.high_poly.use_low_as_high = true; + } + assert_eq!(harness.state().session.doc.project, expected); +} + +#[test] +fn secondary_rays_edit_from_another_set_updates_all_sets() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[1].bake = BakeSettings::default(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + texturecraft_engine::execute(session, "textureSet.select", &serde_json::json!({"ts": 1})).unwrap(); + harness.run_steps(3); + select_map(&mut harness, "Ambient Occlusion"); + let history_steps = harness.state().session.history_labels().len(); + + number_field(&harness, "Secondary Rays").focus(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.run_steps(1); + number_field(&harness, "Secondary Rays").type_text("128"); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + let session = &harness.state().session; + assert_eq!(session.ts(), 1); + for texture_set in &session.doc.project.texture_sets { + assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 128); + } + assert_eq!(session.history_labels().len(), history_steps + 1); +} + +#[test] +fn map_selection_stays_per_set() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let second = harness.state().session.doc.project.texture_sets[1].bake.clone(); + + click_checkbox(&mut harness, "Ambient Occlusion"); + assert!(enabled_maps(&harness).is_empty()); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); + + click_checkbox(&mut harness, "Check All"); + assert_eq!(enabled_maps(&harness), BakedMap::ALL); + assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second); +} + +#[test] +fn bake_texture_set_visibility_is_independent_of_bake_selection() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before: Vec<_> = harness.state().session.doc.project.texture_sets.iter().map(|texture_set| texture_set.bake.clone()).collect(); + let active_set = harness.state().session.ts(); + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + + let session = &harness.state().session; + assert!(session.doc.project.texture_sets[0].visible); + assert!(!session.doc.project.texture_sets[1].visible); + assert_eq!(session.ts(), active_set); + for (texture_set, settings) in session.doc.project.texture_sets.iter().zip(&before) { + assert_eq!(&texture_set.bake, settings); + } + + harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click(); + harness.run_steps(3); + assert!(harness.state().session.doc.project.texture_sets[1].visible); +} + +#[test] +fn texture_set_resolution_controls_are_independent_from_bake_output() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let before = harness.state().session.doc.project.clone(); + let active_set = harness.state().session.ts(); + harness.get_all_by_value("256 × 256").nth(1).unwrap().click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + wait_for_resolution(&mut harness, 1, 128); + + let session = &harness.state().session; + assert_eq!(session.ts(), active_set); + assert_eq!(session.doc.project.texture_sets[0], before.texture_sets[0]); + assert_eq!(session.doc.project.texture_sets[1].bake, before.texture_sets[1].bake); + harness.state_mut().session.undo().unwrap(); + assert_eq!(harness.state().session.doc.project, before); +} + +fn wait_for_resolution(harness: &mut Harness<'_, TextureCraftApp>, texture_set: usize, resolution: u32) { + for _ in 0..100 { + harness.run_steps(1); + if harness.state().session.doc.project.texture_sets[texture_set].resolution == resolution { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("texture set resize did not finish"); +} + +#[test] +fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() { + let session = texturecraft_engine::Session::new_project( + "Tile resolution controls", + texturecraft_engine::geom::primitives::udim_plane(), + "builtin:udim_plane", + None, + 256, + ) + .unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + let before = harness.state().session.doc.project.clone(); + + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(resolution_position); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(3); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.get_by_label("UV tile 1002 resolution").click(); + harness.run_steps(3); + click(&mut harness, "128 × 128"); + harness.get_by_value("128 × 128*"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1001), 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake, before.texture_sets[0].bake); + + harness.get_by_value("128 × 128*").click(); + harness.run_steps(3); + click(&mut harness, "Remove resolution override"); + assert_eq!(harness.state().session.doc.project, before); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 1); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + harness.get_by_value("128 × 128*"); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("2048").next().unwrap().click(); + harness.run_steps(3); + click(&mut harness, "64"); + let texture_set = &harness.state().session.doc.project.texture_sets[0]; + assert_eq!(texture_set.resolution, 256); + assert_eq!(texture_set.tile_resolution(1002), 128); + assert_eq!(texture_set.bake.common.resolution, BakeResolution::R64); +} + +#[test] +fn bake_texture_sets_list_uv_tiles_and_their_resolutions() { + let mut session = + texturecraft_engine::Session::new_project("UV tile list", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let before = session.doc.project.clone(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + + harness.get_by_label("1001"); + harness.get_by_value("256 × 256"); + harness.get_by_label("1002"); + harness.get_by_value("128 × 128*"); + click_checkbox(&mut harness, "1002"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled()); + click_checkbox(&mut harness, "1001"); + assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled()); + harness.state_mut().session.undo().unwrap(); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + click(&mut harness, "UV tiles (UDIM) (2)"); + assert!(harness.query_by_label("1001").is_none()); + assert!(harness.query_by_label("1002").is_none()); + assert_eq!(harness.state().session.doc.project, before); +} + +#[test] +fn restoring_map_defaults_updates_other_sets_even_when_active_values_are_default() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.maps.ao.is_enabled = false; + second.maps.ao.parameters.rays.rays = 16; + second.maps.ao.parameters.ground_plane.offset = 3.0; + let before = session.doc.project.clone(); + + click(&mut harness, "Restore Defaults"); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.maps.ao.parameters = BakeSettings::default().maps.ao.parameters; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + +#[test] +fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { + let mut harness = harness(Some(BakedMap::AmbientOcclusion)); + let session = &mut harness.state_mut().session; + session.doc.project.texture_sets[0].bake.common = Default::default(); + let second = &mut session.doc.project.texture_sets[1].bake; + *second = BakeSettings::default(); + second.common.is_enabled = false; + second.common.resolution = BakeResolution::R128; + second.common.resolution_height = Some(BakeResolution::R256); + second.common.apply_diffusion = false; + second.maps.select([BakedMap::Height]); + second.high_poly.low_suffix = "_custom_low".into(); + let before = session.doc.project.clone(); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click(); + harness.run_steps(3); + + let mut expected = before.clone(); + expected.texture_sets[1].bake.common = Default::default(); + expected.texture_sets[1].bake.common.is_enabled = false; + let session = &mut harness.state_mut().session; + assert_eq!(session.doc.project, expected); + session.undo().unwrap(); + assert_eq!(session.doc.project, before); +} + #[test] fn output_axes_unlock_independently_and_relock_to_width() { let mut harness = harness(None); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 31c4c35a..536d30d9 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -161,6 +161,51 @@ fn window_snapshots() { harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); } +#[test] +#[ignore] +fn bake_uv_tiles_snapshot() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = + texturecraft_engine::Session::new_project("UV tile baking", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256) + .unwrap(); + texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + save(&mut harness, &output_dir, "bake-uv-tiles"); + + harness.get_by_value("128 × 128*").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-menu"); + harness.get_by_label("Remove resolution override").click(); + save(&mut harness, &output_dir, "bake-tile-resolution-inherited"); + assert!(harness.query_by_value("128 × 128*").is_none()); + assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty()); + let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center(); + harness.hover_at(inherited_resolution); + save(&mut harness, &output_dir, "bake-tile-resolution-hover"); + assert_eq!(harness.get_all_by_value("256 × 256").count(), 2); + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.state_mut().session.undo().unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(egui::Role::CheckBox, "1002").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-partial"); + assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002)); + + harness.get_by_label("Show or hide the texture set").click(); + save(&mut harness, &output_dir, "bake-uv-tiles-hidden"); + assert!(!harness.state().session.doc.project.texture_sets[0].visible); + assert!(harness.state().session.doc.project.texture_sets[0].bake.common.is_enabled); +} + #[test] #[ignore] fn smart_mask_shelf_snapshot() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 74322c74..78707aa1 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -24,6 +24,39 @@ as the history reaches); `edit.history` lists the steps done and the undone ones Any command takes `merge: true` to fold its edit into the previous undo step when that step has the same label: a drag that applies a value on every frame stays one step. +Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each +set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the +changed fields; Restore Defaults resets the whole parameter section across all sets. + +`bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes +only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum +values returned in the command's `model` result; omitted fields retain each set's values, and +`null` clears optional fields such as `common.resolution_height`. All targeted sets are validated +before the edit is applied as one undo step. `model` still replaces the complete settings; +when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts` +still targets the active set for scripts that need individual control. + +The bake texture-set list shows visibility eyes and expandable UV tile rows. Visibility affects +the viewport independently of bake inclusion. Its resolution menus edit the texture-set size +(`textureSet.resolution`) and individual tile overrides (`textureSet.tile.resolution`), independently +of Common Settings' bake Output Size. Overridden tiles display a resolution marked with an asterisk; +inherited tile resolutions appear only on hover or while their menu is open. Remove resolution +override hides the number and restores inheritance from the set, including when their current +sizes happen to match. + +Baked maps use a uniform UV tile atlas: every selected tile receives the full bake Output Size, +including rectangular output sizes. Changing a texture-set or tile working resolution preserves +the stored bake pixels. Materials, mesh-map previews, and exports sample those pixels through +the working tile layout. Older project files load their baked pixels as-is without layout +conversion; rebaking restores correct mapping and detail. + +`bake.tile.set {ts?, tile: 1002, enabled: false}` +excludes one UV tile; `textureSet.inspect` / `session.inspect` expose each tile's `bakeEnabled`. +Tile choices are saved and undoable. Unchecked tiles retain their previous baked pixels, resampled +if output size changes, or neutral values when no previous map exists. A running bake uses the +tile selection captured when its worker started. Sets with no checked tiles are skipped; their +geometry still contributes to occlusion when baking other tiles. + ## Control channel (desktop app) ```sh From 03a9870db20d77cf0f000567d629a3610969434c Mon Sep 17 00:00:00 2001 From: chasse20 Date: Fri, 6 Nov 2026 01:12:55 -0500 Subject: [PATCH 048/275] Fix shelf hover previews and clean up comments --- crates/engine/src/mask_preview.rs | 40 ++++++------ crates/engine/src/mask_preview_camera.rs | 19 +++--- crates/ui-egui/src/mask_preview_image.rs | 14 ++--- crates/ui-egui/src/mask_shape.rs | 10 +-- crates/ui-egui/src/preview_image.rs | 35 +++++------ crates/ui-egui/src/preview_request.rs | 10 +-- crates/ui-egui/src/preview_worker.rs | 35 +++++------ crates/ui-egui/src/shelf.rs | 43 +++++++------ crates/ui-egui/src/shelf_preview.rs | 29 ++++----- crates/ui-egui/src/thumbs.rs | 69 ++++++++++----------- crates/ui-egui/src/worker_preview.rs | 9 ++- crates/ui-egui/tests/shelf_hover_preview.rs | 62 +++++++++++++----- 12 files changed, 188 insertions(+), 187 deletions(-) diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs index 6e3f3525..a44757fc 100644 --- a/crates/engine/src/mask_preview.rs +++ b/crates/engine/src/mask_preview.rs @@ -1,6 +1,5 @@ -//! Smart mask shelf previews: the real smart masks on a baked preview shape. The shape -//! ([`primitives::preview_orb`]) is baked once; each preset is then applied with -//! `mask.smart.apply`, read back from the compositor and seen from a fixed camera. +//! Smart mask previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply` and the compositor, matching document masks use serde_json::json; use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; @@ -11,34 +10,33 @@ use crate::mask_preview_camera::MaskPreviewCamera; pub use crate::mask_preview_pixel::MaskPreviewPixel; use crate::{EngineError, Result, Session}; -/// Texture and bake size of the preview shape in texels (at 256 the edge lines break up). +/// Bake resolution in texels; 256 loses the thin edge lines const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline). +/// Camera rays per preview pixel along each axis (anti-aliased outline) const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews. +/// Bound camera samples and output allocations for shelf previews pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel (the default is 64; fewer look the same at thumbnail size). +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default const OCCLUSION_RAYS: u32 = 12; -/// Mesh curvature rays per texel (the default is 32; fewer look the same at thumbnail size). +/// Curvature rays per texel; thumbnail detail needs fewer than the default const CURVATURE_RAYS: u32 = 12; -/// Mesh curvature sampling radius relative to the bounding box: wide enough that edges read as -/// lines at thumbnail size, narrow enough that the round body does not count as an edge. +/// Radius relative to the bounding box; isolates panel edges from the round body const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read. +/// The mesh maps the smart mask generators read const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Camera views kept at most (one per preview size: the shelf thumbnail and the hover preview). +/// Keep camera views for the thumbnail and hover preview sizes const CAMERAS_KEPT: usize = 2; -/// The baked preview shape and, per preview size, what its camera sees. +/// The baked preview shape and, per preview size, what its camera sees pub struct MaskPreview { session: Session, layer: LayerId, - /// Camera views of the most recently used preview sizes, oldest first (traced on first use). + /// Cached camera views, least recently used first cameras: Vec, } impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it). + /// Bake the preview shape once (previews of any size reuse it) pub fn new() -> Result { let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; let set = session.doc.project.texture_set_mut(0)?; @@ -58,15 +56,15 @@ impl MaskPreview { Ok(MaskPreview { session, layer, cameras: Vec::new() }) } - /// Smart mask `id` per preview pixel, row-major `size²`, None where the shape is not seen - /// Returns None for an unknown id or a size outside 1..=[`MAX_PREVIEW_SIZE_PX`]. + /// Row-major `size²` pixels, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] pub fn render(&mut self, id: &str, size: usize) -> Option>> { if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { return None; } crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Nothing is undone here; the snapshots would pile up over the presets + // Previews need no undo history; retaining snapshots grows memory across presets self.session.undo.clear(); let camera = camera_for(&mut self.cameras, &self.session, size)?; @@ -94,8 +92,7 @@ impl MaskPreview { } } -/// The camera view for `size²` previews of `session`'s shape, traced on first use (moved to the end -/// of `cameras`); past [`CAMERAS_KEPT`] the least recently used size goes. +/// Cache one camera per preview size, evicting the least recently used view fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { let rays_per_side = size * SUPERSAMPLE; let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { @@ -114,7 +111,7 @@ fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, si mod tests { use super::*; - /// Mean absolute difference of the masks of two previews over the pixels both see. + /// Mean absolute difference of the masks of two previews over the pixels both see fn difference(a: &[Option], b: &[Option]) -> f32 { let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 @@ -154,7 +151,6 @@ mod tests { assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); assert!(preview.render("nope", size).is_none()); - // The same bake renders other sizes, showing the same mask let big = preview.render("edges_sharp", size * 3).unwrap(); let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; assert_eq!(big.len(), size * size * 9); diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/mask_preview_camera.rs index 9787accb..ea3d6d1f 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/mask_preview_camera.rs @@ -1,5 +1,4 @@ -//! The fixed camera of the smart mask previews (see [`crate::mask_preview::MaskPreview`]) at one -//! image size. +//! Cached camera rays for one smart mask preview size use std::collections::HashMap; @@ -8,27 +7,25 @@ use texturecraft_geom::surface_at; use crate::Session; -/// Camera: looking down by this angle, turned to show the front, left and top panels. +/// Camera angles expose the front, left and top panels const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// What one camera ray sees: the index of its texel in [`MaskPreviewCamera::texels`] and the -/// view-space normal there (None where the ray misses). +/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees. +/// What each ray of a square orthographic view of the preview shape sees pub(crate) struct MaskPreviewCamera { - /// Rays along each side of the view. + /// Rays along each side of the view pub rays_per_side: usize, - /// The texels (x, y) the camera sees, each once. + /// The texels (x, y) the camera sees, each once pub texels: Vec<(u32, u32)>, - /// Per ray, row-major `rays_per_side²`. + /// Per ray, row-major `rays_per_side²` pub samples: Vec, } impl MaskPreviewCamera { - /// Trace `rays_per_side²` rays at the shape of `session`, whose textures are `texture_px` - /// square. + /// Trace a square orthographic view onto a `texture_px²` texture pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { let (lo, hi) = session.mesh.bounds(); let center = (lo + hi) * 0.5; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 49fe70f7..4418d099 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -1,28 +1,24 @@ -//! Shading of the smart mask previews: the mask as white over a near-black surface. +//! Smart masks appear white against a near-black surface use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::mask_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; -/// View-space directions of the key light (upper left) and a weaker fill (right), and how much -/// each lights the surface. +/// View-space lighting uses an upper-left key and a weaker right fill const KEY: [f32; 3] = [-0.72, 0.62, 0.3]; const FILL: [f32; 3] = [0.7, -0.1, 0.7]; const AMBIENT: f32 = 0.1; const KEY_STRENGTH: f32 = 0.8; const FILL_STRENGTH: f32 = 0.35; -/// Where the mask is empty: a near-black albedo with a faint sheen of the key light, so the -/// shape reads without looking glossy. +/// A faint sheen reveals the unmasked shape without a glossy finish const UNMASKED_ALBEDO: f32 = 0.006; const SHEEN: f32 = 0.1; const SHEEN_EXPONENT: f32 = 40.0; -/// Where the mask is full: white, darkened at most this much where unlit. +/// Where the mask is full: white, darkened at most this much where unlit const WHITE_SHADING: f32 = 0.2; -/// A smart mask preview (sRGB, transparent outside the shape) from preview pixels (row-major -/// `size²`): the mask as white over a near-black surface lit softly from the upper left. No -/// environment reflections. +/// Shade row-major `size²` mask pixels in sRGB with a transparent background pub fn mask_preview_image(size: usize, pixels: &[Option]) -> ColorImage { let key = Vec3::from(KEY).normalize(); let fill = Vec3::from(FILL).normalize(); diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs index e34c5a7e..c99a9b1c 100644 --- a/crates/ui-egui/src/mask_shape.rs +++ b/crates/ui-egui/src/mask_shape.rs @@ -1,20 +1,20 @@ -//! The smart mask preview shape, baked on first use. +//! The smart mask preview shape, baked on first use use texturecraft_engine::mask_preview::MaskPreview; -/// Whether the smart mask preview shape is baked. +/// Whether the smart mask preview shape is baked #[derive(Default)] pub enum MaskShape { #[default] NotBaked, - /// Boxed: the baked session is large and the enum sits in the worker for its whole life. + /// Box the large session to keep the unbaked worker small Baked(Box), - /// The bake failed; smart mask previews stay empty. + /// The bake failed; smart mask previews stay empty Failed, } impl MaskShape { - /// The baked shape, baking it on the first call (about two seconds; None when it fails). + /// Bake on first use; retain failure to avoid retrying every frame pub fn get(&mut self) -> Option<&mut MaskPreview> { if matches!(self, MaskShape::NotBaked) { *self = match MaskPreview::new() { diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 3f2321dc..f689c85d 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -1,5 +1,4 @@ -//! The CPU renderers of the shelf previews at any size: shaded material spheres, procedural -//! swatches, alpha swatches, brush strokes and letterboxed images (no image assets). +//! CPU renderers for shelf spheres, swatches, strokes and imported images use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; @@ -9,27 +8,25 @@ use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; use texturecraft_engine::texel::linear_to_srgb; -/// Pattern scale of the procedural swatches (repeats across the swatch). +/// Pattern scale of the procedural swatches (repeats across the swatch) const PROCEDURAL_SCALE: f32 = 3.0; -/// Samples per pixel along each axis of the alpha swatches. +/// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; -/// Linear color of a surface with view-space normal `n` and these material values, lit by a key -/// light and a studio environment, seen along +Z. +/// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { let l = [0.45f32, 0.7, 0.55]; let len = (l[0] * l[0] + l[1] * l[1] + l[2] * l[2]).sqrt(); let l = l.map(|v| v / len); let ndl = (n[0] * l[0] + n[1] * l[1] + n[2] * l[2]).max(0.0); let ndv = n[2].max(0.0); - // View along +Z: half vector between light and view. + // The view direction is +Z let h = [l[0], l[1], l[2] + 1.0]; let hl = (h[0] * h[0] + h[1] * h[1] + h[2] * h[2]).sqrt(); let ndh = ((n[0] * h[0] + n[1] * h[1] + n[2] * h[2]) / hl).max(0.0); let shin = 2.0 / (rough * rough * rough * rough).max(1e-3) - 2.0; let spec_amt = ndh.powf(shin.clamp(1.0, 4096.0)) * (shin + 2.0) / 8.0; - // A studio environment seen in the mirror direction: dark floor, bright sky, a horizon that - // blurs (and the whole environment averages out) as roughness grows. + // Roughness blurs the reflected horizon toward the environment average let ry = 2.0 * ndv * n[1]; let w = 0.06 + rough * 0.9; let t = ((ry + w) / (2.0 * w)).clamp(0.0, 1.0); @@ -47,14 +44,13 @@ pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { out } -/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1. +/// ACES filmic tone mapping of linear `x` (exposure folded in) to 0..=1 pub fn aces(x: f32) -> f32 { let v = x * 0.6; ((v * (2.51 * v + 0.03)) / (v * (2.43 * v + 0.59) + 0.14)).clamp(0.0, 1.0) } -/// A shaded sphere image (sRGB, transparent outside) from per-pixel preview samples (row-major -/// `size²`, see [`preview::sphere_normals`]); height bumps the normals. +/// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); let r = (size as f32 * 0.5 - 1.0).max(0.5); @@ -64,9 +60,10 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { }; for (i, n) in preview::sphere_normals(size).enumerate() { let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let (x, y) = (i % size, i / size); let c = s.height; - // Central differences (image y points down). + // Image Y points down; the shading normal uses Y up let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); let k = r * 0.5 * 1.5; @@ -79,7 +76,7 @@ pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { img } -/// Grayscale `size²` swatch of procedural `kind`. +/// Grayscale `size²` swatch of procedural `kind` pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { use texturecraft_engine::compose::pattern::{Coords, procedural}; use texturecraft_engine::core::{Procedural, Projection}; @@ -95,14 +92,13 @@ pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { img } -/// White-on-black `size²` swatch of library alpha `alpha`. +/// White-on-black `size²` swatch of library alpha `alpha` pub fn alpha_image(alpha: &LibraryAlpha, size: usize) -> ColorImage { let pixels = alpha.render(size, ALPHA_SUPERSAMPLE).into_iter().map(|v| Color32::from_gray((v * 255.0 + 0.5) as u8)).collect(); ColorImage::new([size, size], pixels) } -/// Image resource `img` letterboxed into a `size²` square to keep its proportions, over black -/// where it is transparent. +/// Letterbox into a `size²` square, compositing transparency over black pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { let aspect = img.width as f32 / img.height.max(1) as f32; let (scale_u, scale_v) = if aspect >= 1.0 { (1.0, aspect) } else { (1.0 / aspect.max(1e-6), 1.0) }; @@ -124,15 +120,14 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { preview } -/// `b`'s stamps (shape, spacing, flow, angle, path following, jitters) along an S curve across -/// an `n`-pixel square, white on black. +/// Preview the brush along an S curve in an `n`-pixel square pub fn stroke_preview(b: &BrushSettings, n: usize) -> ColorImage { let library = b.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); let radius = n as f32 * 0.11; let shape = Shape { alpha: b.alpha, image: None, library, level: 0 }.at_radius(radius); let curve = |t: f32| (n as f32 * (0.15 + 0.7 * t), n as f32 * (0.5 - 0.22 * (t * std::f32::consts::TAU).sin())); let mut cover = vec![0f32; n * n]; - // Deterministic jitter per stamp. + // Stable jitter keeps the preview reproducible let rnd = |i: u32, k: u32| (i.wrapping_mul(0x9E37_79B9) ^ k.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32; let step = (b.spacing * 2.0 * radius).max(0.5); let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 56e2e3b3..71c7870b 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -1,4 +1,4 @@ -//! A request to the shelf preview worker (see [`crate::preview_worker::PreviewWorker`]). +//! Shelf preview work submitted to [`crate::preview_worker::PreviewWorker`] use egui::ColorImage; @@ -6,20 +6,20 @@ use crate::mask_preview_image::mask_preview_image; use crate::mask_shape::MaskShape; use crate::shelf_preview::ShelfPreview; -/// Render `preview` at `size_px²`; the answer comes back under `key`. +/// Render `preview` at `size_px²`; the answer comes back under `key` pub struct PreviewRequest { pub key: String, pub preview: ShelfPreview, pub size_px: usize, - /// A hover preview: the worker renders the newest of these before anything else. + /// A hover preview: the worker renders the newest of these before anything else // The web renders each request at once, so nothing is reordered there #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub hover: bool, } impl PreviewRequest { - /// The requested image (None for an unknown asset, or a smart mask when the shape fails to - /// bake); smart masks bake `shape` on first use. + /// Render the asset, baking the mask shape on first use + /// Unknown assets and failed bakes return None pub fn render(&self, shape: &mut MaskShape) -> Option { match &self.preview { ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index cf51812e..a3d2cc8f 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -1,35 +1,33 @@ -//! Renders shelf previews off the UI thread, on threads of its own (one core is left for the UI): -//! big hover previews and the smart mask thumbnails, which share one baked preview shape. On the web there are no threads: each request renders -//! inline on the UI thread (the window pauses for it). +//! Native preview rendering uses a separate thread pool +//! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] use crate::mask_shape::MaskShape; use crate::preview_request::PreviewRequest; -/// A rendered preview: the request's key and its image (None when it could not be rendered). +/// Request key and rendered image; None on failure pub type PreviewResult = (String, Option); -/// The preview worker, started by the first request. +/// The preview worker, started by the first request #[derive(Default)] pub enum PreviewWorker { #[default] NotStarted, - /// The worker thread: requests go in, results come out (it ends when the requests sender is - /// dropped). + /// Native worker; dropping the request sender ends it after pending work #[cfg(not(target_arch = "wasm32"))] Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, - /// The web: requests render as they are made. + /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] Inline { shape: MaskShape, results: Vec }, - /// The worker could not start or stopped; requests are refused. + /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] Stopped, } impl PreviewWorker { - /// Queue `request`, starting the worker first if needed; false when the worker is stopped. - /// The worker repaints `ctx` when a result is ready. + /// Submit work, starting the worker on first use; false if it has stopped + /// Native results request a repaint pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool { if matches!(self, PreviewWorker::NotStarted) { *self = PreviewWorker::start(ctx); @@ -53,7 +51,7 @@ impl PreviewWorker { } } - /// The results ready since the last call. + /// The results ready since the last call pub fn poll(&mut self) -> Vec { match self { #[cfg(not(target_arch = "wasm32"))] @@ -80,12 +78,12 @@ impl PreviewWorker { } } - /// Whether the worker stopped: it refuses requests and answers none of the queued ones. + /// Whether the worker stopped: it refuses requests and answers none of the queued ones pub fn is_stopped(&self) -> bool { matches!(self, PreviewWorker::Stopped) } - /// Start the worker thread (Stopped when it cannot start). + /// Start the worker thread (Stopped when it cannot start) #[cfg(not(target_arch = "wasm32"))] fn start(ctx: &egui::Context) -> PreviewWorker { use std::collections::VecDeque; @@ -97,7 +95,7 @@ impl PreviewWorker { let (result_tx, results) = channel(); let ctx = ctx.clone(); let spawned = std::thread::Builder::new().name("texturecraft-shelf-previews".into()).spawn(move || { - // Its own threads: on the global pool a big render would hold up the UI thread's work + // A separate pool keeps previews from queuing ahead of the UI's work let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-preview-{i}")).build(); if let Err(e) = &pool { @@ -106,7 +104,6 @@ impl PreviewWorker { let mut shape = MaskShape::default(); let mut queue = VecDeque::new(); loop { - // Wait for work, then take in everything sent meanwhile if queue.is_empty() { let Ok(request) = request_rx.recv() else { break }; @@ -115,6 +112,7 @@ impl PreviewWorker { queue.extend(request_rx.try_iter()); let Some(request) = next_request(&mut queue) else { continue }; + let image = match &pool { Ok(pool) => pool.install(|| request.render(&mut shape)), Err(_) => request.render(&mut shape), @@ -135,15 +133,14 @@ impl PreviewWorker { } } - /// Render inline (no threads on the web). + /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } } } -/// The request to render next: the newest hover preview (the one under the pointer), else the -/// oldest request. +/// Prioritize the newest hover preview over older requests #[cfg(not(target_arch = "wasm32"))] fn next_request(queue: &mut std::collections::VecDeque) -> Option { match queue.iter().rposition(|request| request.hover) { diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 2617a56d..46ced908 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -26,25 +26,24 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::{dnd_release, icon_button}; -/// A shelf tile's size in points. +/// A shelf tile's size in points const TILE_WIDTH: f32 = 72.0; const TILE_HEIGHT: f32 = 86.0; -/// Corner radius of a tile's hover and selection highlights, in points. +/// Corner radius of a tile's hover and selection highlights, in points const TILE_ROUNDING: f32 = 3.0; -/// The thumbnail's size in a tile and its center below the tile's top, in points. +/// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width. +/// A placeholder disc's radius relative to the thumbnail's width const PLACEHOLDER_RADIUS: f32 = 0.45; -/// A tile label's font size, its gap below the thumbnail and its total side margin, in points. +/// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; const LABEL_MARGIN: f32 = 4.0; -/// The hover preview's size and its gap above the label, in points. +/// The hover preview's size and its gap above the label, in points const BIG_PREVIEW_SIZE: f32 = 256.0; const BIG_PREVIEW_LABEL_GAP: f32 = 4.0; -/// How long the pointer rests on a tile before its big preview renders, in seconds (well inside -/// the popup's delay). +/// Dwell in seconds before rendering, shorter than the popup delay const BIG_PREVIEW_DWELL: f32 = 0.1; #[derive(Clone, Copy, PartialEq, Eq)] @@ -564,6 +563,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: tiles(ui, |ui| { for name in names { let Some(img) = app.session.images.get(&name).cloned() else { continue }; + let tex = app.thumbs.image(ctx, &name, &img); let asset = Asset::Texture(name.clone()); let preview = || ShelfPreview::Image(name.clone(), img); @@ -585,8 +585,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: }); } -/// A shelf tile: thumbnail (a placeholder disc while it renders) and a wrapped label; tiles with -/// a `drag` asset can be dragged. Hovering shows a big `preview` (made only then) over the label. +/// Asset tile with optional dragging and a larger hover preview fn tile( ui: &mut Ui, thumbs: &mut Thumbs, @@ -618,25 +617,26 @@ fn tile( resp.on_hover_ui(|ui| hover_preview(ui, tex, big.as_ref(), label)) } -/// A hovered tile's big preview: requested once the pointer has rested [`BIG_PREVIEW_DWELL`], so -/// it renders during the popup's delay but not for tiles the pointer sweeps across (None until the -/// worker renders it). +/// Start rendering during the popup delay once the pointer rests fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPreview) -> Option { let ctx = ui.ctx(); - let size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; let preview = preview(); - // Keep smart mask hover previews within the camera's allocation limit at high display scales. - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { size_px }; - let still_for = ui.input(|i| i.pointer.time_since_last_movement()); - if still_for >= BIG_PREVIEW_DWELL { + let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; + + // High display scales must respect the mask camera's allocation limit + let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + + // Scrolling moves tiles beneath a stationary pointer + let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); + if idle_seconds >= BIG_PREVIEW_DWELL { return thumbs.big(ctx, preview, size_px); } - ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - still_for); + ctx.request_repaint_after_secs(BIG_PREVIEW_DWELL - idle_seconds); thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders. +/// `tex` drawn into `rect`, or a placeholder disc while it renders fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { match tex { Some(t) => { @@ -648,8 +648,7 @@ fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: e } } -/// A tile's hover popup: the `big` preview (the tile's `small` thumbnail scaled up until it -/// renders) over the label. +/// Use the thumbnail as a placeholder until the hover preview arrives fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&egui::TextureHandle>, label: &str) { let tk = Tokens::get(ui.ctx()); ui.set_max_width(BIG_PREVIEW_SIZE); diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index f8cc7e3b..a23ffb32 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -1,4 +1,4 @@ -//! What a shelf preview shows, and how to render it at any size. +//! Shelf assets and their preview renderers use std::sync::Arc; @@ -12,27 +12,26 @@ use texturecraft_engine::preview; use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_image, stroke_preview}; -/// The asset a shelf tile previews. +/// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere. + /// A built-in material or smart material on a sphere Material(&'static str), - /// A smart mask on the baked preview shape (only the preview worker can render it: see - /// [`crate::preview_request::PreviewRequest::render`]). + /// Smart mask rendering requires the worker's baked shape SmartMask(&'static str), - /// A library filter on a sample material on a sphere. + /// A library filter on a sample material on a sphere Filter(&'static str), - /// A procedural pattern as a grayscale swatch. + /// A procedural pattern as a grayscale swatch Procedural(ProceduralKind), - /// A library brush alpha, white on black. + /// A library brush alpha, white on black Alpha(&'static LibraryAlpha), - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve Brush(&'static BrushPreset), - /// An image resource by name. + /// An image resource by name Image(String, Arc), } impl ShelfPreview { - /// The cache key of the preview (one per asset). + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), @@ -45,9 +44,8 @@ impl ShelfPreview { } } - /// The preview as a `size²` image (None for an unknown material or filter id). Smart masks are - /// None here: they need the baked preview shape, which only the preview worker holds, so the - /// UI thread never bakes. + /// Render a `size²` image; unknown assets return None + /// Smart masks return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), @@ -70,7 +68,7 @@ mod tests { use super::*; - /// The hover preview's size at 100 % scale. + /// The hover preview's size at 100 % scale const BIG_PX: usize = 256; #[test] @@ -91,7 +89,6 @@ mod tests { assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); } - // The shaded spheres come from finite material values let finite = |samples: Vec>| { samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) }; diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 982caa17..9ed4f73b 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,7 +1,6 @@ -//! Thumbnails: shelf previews (see [`crate::preview_image`]) cached as egui textures, plus small -//! shaded spheres and alpha previews drawn as shapes. New shelf thumbnails are rendered lazily, a -//! few per frame, so opening the shelf never stalls a frame; the smart mask thumbnails and the big -//! hover previews render on a worker. +//! Shelf and brush preview caches +//! Small synchronous renders are limited per frame +//! Smart masks and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -17,39 +16,39 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames). +/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) const PER_FRAME: usize = 2; -/// Shelf sphere and smart mask thumbnail size in pixels. +/// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; -/// Shelf procedural swatch size in pixels. +/// Shelf procedural swatch size in pixels const PROCEDURAL_PX: usize = 56; -/// Shelf alpha and brush stroke swatch size in pixels. +/// Shelf alpha and brush stroke swatch size in pixels const SWATCH_PX: usize = 64; -/// Image resource preview size in pixels. +/// Image resource preview size in pixels const IMAGE_PX: usize = 64; -/// Big hover previews kept at most (the least recently shown go first). +/// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; -/// The shelf's and the brush panel's preview textures. +/// The shelf's and the brush panel's preview textures #[derive(Default)] pub struct Thumbs { - /// Shelf thumbnails by [`ShelfPreview::key`]. + /// Shelf thumbnails by [`ShelfPreview::key`] shelf: HashMap, images: HashMap, - /// (frame, thumbnails rendered in it). + /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews. + /// Renders the smart mask thumbnails and the big previews worker: PreviewWorker, - /// Worker-rendered previews by [`worker_key`]. + /// Worker-rendered previews by [`worker_key`] rendered: HashMap, - /// The keys of the big previews in `rendered`, least recently shown first. + /// The keys of the big previews in `rendered`, least recently shown first big_shown: VecDeque, - /// The frame that last took in the worker's results. + /// The frame that last took in the worker's results received_in_pass: u64, } impl Thumbs { - /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px). + /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { let key = format!("stencil:{name}"); if let Some(t) = self.images.get(&key) { @@ -70,7 +69,7 @@ impl Thumbs { t } - /// Cached preview of an image resource (64 px, letterboxed). + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle { if let Some(t) = self.images.get(name) { return t.clone(); @@ -80,8 +79,7 @@ impl Thumbs { t } - /// A cached shelf thumbnail of `preview` at `size_px²`, rendering it if this frame's budget - /// allows (None until then; a repaint is requested so it follows shortly). + /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); if let Some(t) = self.shelf.get(&key) { @@ -105,8 +103,8 @@ impl Thumbs { Some(t) } - /// A worker-rendered `size_px²` image of `preview`, requested on the first call (None until it - /// arrives, and for good when it cannot be rendered); `hover` previews jump the worker's queue. + /// Request once per asset and size; return None while pending or after failure + /// Hover requests take priority in the native worker fn worker_rendered(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize, hover: bool) -> Option { self.receive(ctx); @@ -118,7 +116,7 @@ impl Thumbs { self.ready(&key) } - /// The worker-rendered preview under `key` if it arrived. + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { Some(WorkerPreview::Ready(t)) => Some(t.clone()), @@ -126,8 +124,7 @@ impl Thumbs { } } - /// Take in the worker's finished previews, once per frame (dropping the ones no longer - /// wanted). + /// Poll once per pass and discard results evicted from the cache fn receive(&mut self, ctx: &egui::Context) { let pass = ctx.cumulative_pass_nr(); if self.received_in_pass == pass { @@ -152,8 +149,7 @@ impl Thumbs { } } - /// The big hover preview of `preview`, `size_px²` (None until the worker renders it; the - /// least recently shown are dropped past [`BIG_PREVIEWS_KEPT`]). + /// Request a hover preview and evict the least recently shown beyond the cache limit pub fn big(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = worker_key(&preview, size_px); self.big_shown.retain(|k| *k != key); @@ -167,45 +163,44 @@ impl Thumbs { self.worker_rendered(ctx, preview, size_px, true) } - /// The big preview of `preview` if the worker already rendered it (requests nothing). + /// The big preview of `preview` if the worker already rendered it (requests nothing) pub fn rendered_big(&mut self, ctx: &egui::Context, preview: &ShelfPreview, size_px: usize) -> Option { self.receive(ctx); self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id`. + /// Sphere thumbnail of built-in material `id` pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) } - /// Thumbnail of smart mask `id` on the baked preview shape (None while the worker renders - /// it). + /// Smart mask thumbnail; None until the worker returns it pub fn smart_mask(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.worker_rendered(ctx, ShelfPreview::SmartMask(id), SPHERE_PX, false) } - /// Sphere thumbnail of library filter `id` applied to a sample material. + /// Sphere thumbnail of library filter `id` applied to a sample material pub fn filter(&mut self, ctx: &egui::Context, id: &'static str) -> Option { self.shelf(ctx, ShelfPreview::Filter(id), SPHERE_PX) } - /// Grayscale swatch of procedural `kind`. + /// Grayscale swatch of procedural `kind` pub fn procedural(&mut self, ctx: &egui::Context, kind: ProceduralKind) -> Option { self.shelf(ctx, ShelfPreview::Procedural(kind), PROCEDURAL_PX) } - /// White-on-black swatch of library alpha `alpha`. + /// White-on-black swatch of library alpha `alpha` pub fn alpha(&mut self, ctx: &egui::Context, alpha: &'static alphas::LibraryAlpha) -> Option { self.shelf(ctx, ShelfPreview::Alpha(alpha), SWATCH_PX) } - /// A brush preset's stroke along an S curve. + /// A brush preset's stroke along an S curve pub fn brush_preset(&mut self, ctx: &egui::Context, preset: &'static BrushPreset) -> Option { self.shelf(ctx, ShelfPreview::Brush(preset), SWATCH_PX) } } -/// The key of a worker-rendered preview: one per asset and size. +/// The key of a worker-rendered preview: one per asset and size fn worker_key(preview: &ShelfPreview, size_px: usize) -> String { format!("{}@{size_px}", preview.key()) } diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 0252d69f..53767276 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -1,13 +1,12 @@ -//! A preview rendered by the [`crate::preview_worker::PreviewWorker`], as the thumbnail cache -//! tracks it. +//! Cached state of a worker-rendered preview use egui::TextureHandle; -/// Where a worker-rendered preview is. +/// A pending, ready or failed preview pub enum WorkerPreview { - /// Requested; the worker has not answered yet. + /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder). + /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 1bb9a4d7..460ed7c8 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -1,5 +1,4 @@ -//! Hovering a shelf tile shows a big preview of the asset over its name, rendered once the pointer -//! rests on the tile. +//! Shelf hover previews render after a dwell and appear above the asset name use std::time::{Duration, Instant}; @@ -9,20 +8,19 @@ use texturecraft_engine::materials::{MATERIALS, SmartMaterial}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf_preview::ShelfPreview; -/// The shelf's Materials tab. +/// The shelf's Materials tab const MATERIALS_TAB: usize = 0; -/// The hover preview's size in points (pixels at this scale). +/// Popup image size in logical points, independent of display scale const BIG_PREVIEW_SIZE: f32 = 256.0; -/// Simulated seconds per frame, fine enough to stop between the rest and the popup's delay. +/// Small time steps distinguish preview scheduling from popup visibility const STEP_SECONDS: f32 = 0.001; -/// The popup's delay (egui's tooltip delay) and the rest after which the big preview renders. +/// Simulated delays in seconds for the popup and preview request const POPUP_DELAY: f32 = 0.5; const REST: f32 = 0.1; -/// Real time the worker gets to render. +/// Real time the worker gets to render const WORKER_TIMEOUT: Duration = Duration::from_secs(60); -/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show -/// nowhere else. +/// Open the Materials tab and find two labels unique to shelf tiles fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() @@ -38,8 +36,7 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (h, unique) } -/// The pixel size of the largest texture (not the font atlas) the last frame drew at least -/// `min_width` points wide. +/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); @@ -51,7 +48,7 @@ fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Op .max() } -/// Whether `material`'s big preview has arrived from the worker (asks for nothing). +/// Check the cache without submitting a preview request fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &SmartMaterial) -> bool { let ctx = h.ctx.clone(); h.state_mut().thumbs.rendered_big(&ctx, &ShelfPreview::Material(material.id), BIG_PREVIEW_SIZE as usize).is_some() @@ -65,7 +62,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover"); h.get_by_label(material.label).hover(); - // The popup's delay, then the worker let big_px = BIG_PREVIEW_SIZE as usize; let start = Instant::now(); while largest_drawn_texture(&h, BIG_PREVIEW_SIZE) != Some([big_px, big_px]) && start.elapsed() < WORKER_TIMEOUT { @@ -74,7 +70,6 @@ fn hovering_a_shelf_tile_shows_its_big_preview() { } assert_eq!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE), Some([big_px, big_px]), "the popup draws the big preview"); - // The popup's name sits under the big image, below the tile let popup_name = h.get_all_by_label(material.label).map(|n| n.rect()).find(|r| r.min.y > tile.max.y).expect("the popup shows the name"); assert!(popup_name.min.y - tile.max.y >= BIG_PREVIEW_SIZE, "{popup_name:?} under {tile:?}"); } @@ -85,7 +80,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { let (first, second) = (materials[0], materials[1]); let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center()); - // A sweep: the pointer moves every frame across both tiles, then leaves the shelf + // Moving every frame must never satisfy the dwell delay let sweep_frames = 40; for frame in 0..=sweep_frames { h.hover_at(from.lerp(to, frame as f32 / sweep_frames as f32)); @@ -97,7 +92,7 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { h.run_steps(1); assert!(!big_preview_ready(&mut h, first) && !big_preview_ready(&mut h, second), "a sweep renders nothing"); - // A rest: the preview renders before the popup opens + // A stationary pointer should start rendering before the popup opens h.hover_at(from); h.run_steps((REST * 1.2 / STEP_SECONDS) as usize); let start = Instant::now(); @@ -113,6 +108,41 @@ fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() { assert_eq!(h.query_all_by_label(first.label).count(), 1, "the popup is not open yet"); } +#[test] +fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { + let (mut harness, materials) = materials_shelf(STEP_SECONDS, 1.0); + let material = materials[0]; + harness.get_by_label(material.label).hover(); + + // Scroll toward the top boundary to keep the same tile beneath the pointer + for _ in 0..(REST * 2.0 / STEP_SECONDS) as usize { + harness.input_mut().events.push(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, 10.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(1); + } + assert!(harness.ctx.input(|input| input.pointer.time_since_last_movement()) >= REST, "the pointer stayed still beyond the dwell delay"); + assert_eq!(harness.query_all_by_label(material.label).count(), 1, "scrolling suppresses the popup"); + + harness.hover_at(egui::pos2(900.0, 500.0)); + harness.run_steps(1); + std::thread::sleep(Duration::from_secs(1)); + harness.run_steps(1); + assert!(!big_preview_ready(&mut harness, material), "scrolling must not submit a hover preview"); + + harness.get_by_label(material.label).hover(); + let started = Instant::now(); + while !big_preview_ready(&mut harness, material) && started.elapsed() < WORKER_TIMEOUT { + harness.run_steps(1); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(big_preview_ready(&mut harness, material), "the preview renders after scrolling and pointer movement stop"); +} + #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; From f6b201010950c85301e6a8e7294e4d2bd0fc7595 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 06:46:26 +0000 Subject: [PATCH 049/275] Run every neighbourhood filter of a mask or content stack Only the last neighbourhood filter of a stack ran; any below it was skipped silently, so Blur then Warp gave the same result as Warp alone. field() now runs each one in turn, continuing from the previous field, over a region widened by what the filters above it read. Stacks with a single neighbourhood filter are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/eval.rs | 314 ++++++++++++++++++++++++------------- 1 file changed, 207 insertions(+), 107 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index ec75cd97..8b2d6be3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -265,36 +265,35 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// Index (among visible effects) of the last neighbourhood filter of an effect stack, its -/// radius in texels (`res` texels per UV tile across) and what it does. +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { - let texels = |v: f32| (v * res as f32 / 2048.0).max(0.5); - effects - .iter() - .filter(|e| e.visible) - .enumerate() - .filter_map(|(i, e)| match &e.kind { - EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((i, texels(*radius), Op::Blur(None))), - EffectKind::Filter(Filter::Sharpen { amount }) => Some((i, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), - EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((i, texels(*radius), Op::Line(direction(*angle)))), - EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) - } - EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { - Some((i, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) - } - EffectKind::Filter(Filter::HighPass { radius }) => Some((i, texels(*radius), Op::HighPass)), - EffectKind::Filter(Filter::EdgeDetect { width }) => Some((i, texels(*width), Op::Edge)), - // Three box passes ramp an edge over about twice their radius. - EffectKind::Filter(Filter::Bevel { width }) => Some((i, texels(*width * 0.5), Op::Bevel)), - EffectKind::Filter(Filter::Glow { radius, amount }) => Some((i, texels(*radius), Op::Glow(*amount))), - EffectKind::Filter(Filter::Mosaic { size }) => Some((i, texels(*size), Op::Mosaic)), - EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { - Some((i, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) - } - _ => None, - }) - .last() + neighbourhood_filters(effects, res).last() +} + +/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does. +fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator + '_ { + let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5); + effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind { + EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))), + EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))), + EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))), + EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None })) + } + EffectKind::Filter(Filter::DirectionalWarp { intensity, angle, scale, seed }) if *intensity > 0.0 => { + Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: Some(direction(*angle)) })) + } + EffectKind::Filter(Filter::HighPass { radius }) => Some((index, texels(*radius), Op::HighPass)), + EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), + // Three box passes ramp an edge over about twice their radius + EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)), + EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), + EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)), + EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => { + Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed })) + } + _ => None, + }) } /// Unit texel-space vector of `angle` degrees. Texel rows run down: positive angles turn @@ -528,153 +527,205 @@ enum Job<'a> { Content(Channel), } -/// One neighbourhood-filtered field of `layer` over `tiles` plus the filter's reach, built on -/// the fields already computed below it. +/// A layer's mask or content channel after every neighbourhood filter of its stack, over `tiles`. fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: Job, tiles: &[(u32, u32)]) -> Option { - let (gw, gh) = (inp.gbuf.width, inp.gbuf.height); let effects = match job { - Job::Mask(m) => &m.effects, + Job::Mask(mask) => &mask.effects, Job::Content(_) => &inp.project.content_layer(id)?.content_effects, }; - let (k, radius, op) = neighbourhood(effects, inp.tile_res())?; - let opacity = effects.iter().filter(|e| e.visible).nth(k).map(|e| e.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); - // Clamped: a hostile radius must not overflow the halo and window arithmetic. - let r = radius.round().clamp(1.0, gw.max(gh) as f32) as u32; - // Three box passes reach 3r texels, the other filters r (and a texel for bilinear samples). - let blurs = matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)); - let reach = if blurs { 3 * r } else { r + 1 }; - let halo = reach.div_ceil(TILE); - let (tx0, ty0) = tiles.iter().fold((u32::MAX, u32::MAX), |(a, b), t| (a.min(t.0), b.min(t.1))); - let (tx1, ty1) = tiles.iter().fold((0, 0), |(a, b), t| (a.max(t.0), b.max(t.1))); - let (rx0, ry0) = (tx0.saturating_sub(halo) * TILE, ty0.saturating_sub(halo) * TILE); - let (rx1, ry1) = (((tx1 + 1 + halo) * TILE).min(gw), ((ty1 + 1 + halo) * TILE).min(gh)); - let (w, h) = (rx1.saturating_sub(rx0), ry1.saturating_sub(ry0)); - if w == 0 || h == 0 { - return None; + let filters: Vec<(usize, f32, Op)> = neighbourhood_filters(effects, inp.tile_res()).collect(); + let longest_side = inp.gbuf.width.max(inp.gbuf.height); + + // Each filter's region also holds what every filter above it reads around the tiles + let mut margins: Vec = filters.iter().map(|&(_, radius, op)| filter_extent(radius, op, longest_side).1.div_ceil(TILE)).collect(); + for index in (0..margins.len().saturating_sub(1)).rev() { + margins[index] += margins[index + 1]; } + + let mut previous: Option<(usize, Field)> = None; + for (&filter, &margin) in filters.iter().zip(&margins) { + let region = region_around(inp, tiles, margin)?; + let start = previous.as_ref().map(|(index, field)| (*index, field)); + let filtered = filter_region(inp, channels, below, id, job, effects, filter, region, start)?; + previous = Some((filter.0, filtered)); + } + previous.map(|(_, field)| field) +} + +/// The tile-aligned texel region `(x0, y0, w, h)` around `tiles` plus `margin` tiles, clipped to the set. +fn region_around(inp: &Inputs, tiles: &[(u32, u32)], margin: u32) -> Option<(u32, u32, u32, u32)> { + let (first_x, first_y) = tiles.iter().fold((u32::MAX, u32::MAX), |(min_x, min_y), tile| (min_x.min(tile.0), min_y.min(tile.1))); + let (last_x, last_y) = tiles.iter().fold((0, 0), |(max_x, max_y), tile| (max_x.max(tile.0), max_y.max(tile.1))); + let (x0, y0) = (first_x.saturating_sub(margin) * TILE, first_y.saturating_sub(margin) * TILE); + let (x1, y1) = (((last_x + 1 + margin) * TILE).min(inp.gbuf.width), ((last_y + 1 + margin) * TILE).min(inp.gbuf.height)); + let (w, h) = (x1.saturating_sub(x0), y1.saturating_sub(y0)); + (w > 0 && h > 0).then_some((x0, y0, w, h)) +} + +/// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads. +fn filter_extent(radius: f32, op: Op, longest_side: u32) -> (u32, u32) { + // Clamped so a hostile radius can't overflow the region arithmetic + let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; + + // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel + let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; + (radius_texels, reach) +} + +/// Whether neighbourhood filter `op` is computed from box blurs (the others gather samples). +fn is_box_blur(op: Op) -> bool { + matches!(op, Op::Blur(_) | Op::HighPass | Op::Bevel | Op::Glow(_)) +} + +/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given. +#[allow(clippy::too_many_arguments)] +fn filter_region( + inp: &Inputs, + channels: &[Channel], + below: &Fields, + id: LayerId, + job: Job, + effects: &[Effect], + (index, radius, op): (usize, f32, Op), + (rx0, ry0, w, h): (u32, u32, u32, u32), + start: Option<(usize, &Field)>, +) -> Option { + let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); + let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height)); let comps = match job { Job::Mask(_) => 1, Job::Content(_) => 4, }; - // Evaluate the stack before the filter, tile by tile (content premultiplied by coverage). + + // Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage) + let (rx1, ry1) = (rx0 + w, ry0 + h); let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect(); let parts: Vec> = region_tiles .par_iter() .map(|&(tx, ty)| { let full = anchor_plan(inp, id, channels, tx, ty, Some(below)); - let preview_tile = inp.preview.and_then(|p| p.alpha.tile(tx, ty)); + let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty)); let mut mask = None; let mut nodes = Vec::new(); match job { - Job::Mask(m) => { - let Some(mut mp) = mask_plan(inp, id, m, tx, ty, None) else { return Vec::new() }; - mp.effects.truncate(k); - mask = Some(mp); + Job::Mask(layer_mask) => { + let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() }; + + mask_stack.effects.truncate(index); + mask_stack.start = start; + mask = Some(mask_stack); } - Job::Content(ch) => { - nodes = plan(inp, &[id], &[ch], tx, ty, 0, Some(below)); - if let Some(c) = nodes.first_mut().and_then(|n| n.chans.first_mut()) { - c.effects.truncate(k); - c.start = None; + Job::Content(channel) => { + nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below)); + if let Some(chan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) { + chan.effects.truncate(index); + chan.start = start; } } } tile_texels(inp.gbuf, tx, ty) - .map(|(x, y, o)| { - let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); + .map(|(x, y, offset)| { + let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset)); if !full.is_empty() { - tex.anchors_below(&full, id); + texel.anchors_below(&full, id); } - let v = match (&mask, nodes.first()) { - (Some(mp), _) => [tex.mask(mp), 0.0, 0.0, 0.0], - (None, Some(n)) => match n.chans.first().and_then(|c| tex.content(&n.content, c)) { - Some((v, cov)) => [v[0] * cov, v[1] * cov, v[2] * cov, cov], + let value = match (&mask, nodes.first()) { + (Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0], + (None, Some(node)) => match node.chans.first().and_then(|chan| texel.content(&node.content, chan)) { + Some((color, cov)) => [color[0] * cov, color[1] * cov, color[2] * cov, cov], None => [0.0; 4], }, (None, None) => [0.0; 4], }; - (x, y, v) + (x, y, value) }) .collect() }) .collect(); - // Scatter into the region, a row of tiles at a time (the region is tile aligned). - let n = (w * h) as usize; - let mut orig = vec![0.0f32; n * comps]; - let mut cover = vec![0.0f32; n]; + + // Scatter into the region, a row of tiles at a time (the region is tile aligned) + let texel_count = (w * h) as usize; + let mut orig = vec![0.0f32; texel_count * comps]; + let mut cover = vec![0.0f32; texel_count]; let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize; let band = (TILE * w) as usize; orig.par_chunks_mut(band * comps).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((orig, cover), row)| { - for &(x, y, v) in row.iter().flatten() { - let i = (((y - ry0) % TILE) * w + (x - rx0)) as usize; - if let (Some(c), Some(px)) = (cover.get_mut(i), orig.get_mut(i * comps..(i + 1) * comps)) { - *c = 1.0; - px.copy_from_slice(&v[..comps]); + for &(x, y, value) in row.iter().flatten() { + let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize; + if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), orig.get_mut(texel * comps..(texel + 1) * comps)) { + *covered = 1.0; + pixel.copy_from_slice(&value[..comps]); } } }); - // High pass centers on the channel's mid value (0 for signed channels like height). + + // High pass centers on the channel's mid value (0 for signed channels like height) let mid = match job { - Job::Content(ch) if ch.kind() == ChannelKind::Signed => 0.0, + Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; - // The filter at the radius of a tile filling `scale` of its atlas block (a smaller tile has - // fewer texels per UV unit, so its filters reach fewer texels). + + // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let filtered = |scale: f32| -> Vec { let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); - let r = neighbourhood(effects, res).map_or(r, |(_, radius, _)| radius.round().clamp(1.0, r as f32) as u32); - if !blurs { - return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, res, opacity); + let scaled_radius = neighbourhood_filters(effects, res) + .find(|filter| filter.0 == index) + .map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); + if !is_box_blur(op) { + return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), scaled_radius as f32, res, opacity); } - // Weighted so uncovered texels don't bleed in. - let (wu, hu, ru) = (w as usize, h as usize, r as usize); + + // Weighted so uncovered texels don't bleed in + let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize); let mut weights = cover.clone(); - blur(&mut weights, wu, hu, ru); + blur(&mut weights, width, height, blur_radius); let mut data = orig.clone(); - for p in 0..comps { - let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect(); - blur(&mut vals, wu, hu, ru); - data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept). - let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *wt > 1e-6 - && let Some(slot) = px.get_mut(p) + for component in 0..comps { + let mut sums: Vec = orig.par_chunks(comps).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect(); + blur(&mut sums, width, height, blur_radius); + data.par_chunks_mut(comps).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| { + // Content is premultiplied, so the mid value is too (coverage itself is kept) + let cov = if comps == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *weight > 1e-6 + && let Some(slot) = pixel.get_mut(component) { - let (o, blurred) = (*slot, v / wt); - let filtered = match op { - Op::Blur(Some(amount)) => o + amount * (o - blurred), - Op::HighPass if p < 3 => o - blurred + mid * cov, - // Away from 0 by at most the value itself: 0 at the edge, full inside. - Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)), - Op::Glow(amount) if p < 3 => o + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => o, + let (original, blurred) = (*slot, sum / weight); + let result = match op { + Op::Blur(Some(amount)) => original + amount * (original - blurred), + Op::HighPass if component < 3 => original - blurred + mid * cov, + // Away from 0 by at most the value itself: 0 at the edge, full inside + Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)), + Op::Glow(amount) if component < 3 => original + amount * blurred, + Op::HighPass | Op::Bevel | Op::Glow(_) => original, _ => blurred, }; - *slot = o + (filtered - o) * opacity; + *slot = original + (result - original) * opacity; } }); } data }; - // Each block keeps the result at its tile's scale (blocks are TILE aligned). + + // Each block keeps the result at its tile's scale (blocks are TILE aligned) let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); let mut levels: Vec = (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); levels.sort_by(f32::total_cmp); levels.dedup(); - let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(f, r)| (*f, r)); + let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest)); let mut data = filtered(first); for &scale in rest { let other = filtered(scale); let row = w as usize * comps; data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { - for (x, (d, s)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { + for (x, (target, source)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { - d.copy_from_slice(s); + target.copy_from_slice(source); } } }); } + unpremultiply(&mut data, comps); Some(Field { x0: rx0, y0: ry0, w, h, comps, data }) } @@ -2348,6 +2399,55 @@ mod tests { } } + #[test] + fn a_mask_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); + fixture.project.texture_sets[0].resolution = 128; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); + let mut masked = |filters: &[Filter]| { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker.clone(), projection: Projection::default() })); + for filter in filters { + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(filter.clone()))); + } + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap() + }; + + let warped = masked(std::slice::from_ref(&warp)); + let blurred_then_warped = masked(&[Filter::Blur { radius: 64.0 }, warp]); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + assert!(blurred_then_warped.iter().any(|value| *value > 0.05 && *value < 0.95), "the blur softens the checker before the warp moves it"); + } + + #[test] + fn a_content_stack_runs_every_neighbourhood_filter_in_order() { + let mut fixture = fixture(); + let layer = fill_layer(&mut fixture.project, [0.0; 3], 1.0); + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(layer).unwrap().kind else { panic!("expected a fill layer") }; + + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; + let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); + let row = |fixture: &Fixture| -> Vec { + let composite = run(fixture, None); + (0..64).map(|x| composite.value(Channel::BaseColor, x, 20)[0]).collect() + }; + let warped = row(&fixture); + + content_fx(&mut fixture, layer, EffectKind::Filter(Filter::Blur { radius: 64.0 })); + let effects = &mut fixture.project.layer_mut(layer).unwrap().content_effects; + let warp_index = effects.iter().position(|effect| effect.id == warp_effect).unwrap(); + let warp_on_top = effects.remove(warp_index); + effects.push(warp_on_top); + let blurred_then_warped = row(&fixture); + assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); From 297fad6fe789761728bc36688ac27c5af671a551 Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Fri, 6 Nov 2026 01:50:36 -0500 Subject: [PATCH 050/275] Helpful PR review guidelines doc for reviewers --- docs/helpful-pr-review-guidelines.md | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 docs/helpful-pr-review-guidelines.md diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md new file mode 100644 index 00000000..eebcb242 --- /dev/null +++ b/docs/helpful-pr-review-guidelines.md @@ -0,0 +1,68 @@ +# My PR review standards + +Review and improve the PR using these preferences. Follow the repository's instructions and keep changes focused on the problem being solved. + +## Correctness + +- Verify the claimed fix against the actual code and its callers +- Look for missed edge cases, incomplete fixes, and regressions +- Reproduce suspicious behavior locally when practical +- Make regression tests fail before the fix and pass afterward +- Confirm tests exercise the intended path, especially fallbacks and error handling + +## Optimization and simplicity + +- Prefer the smallest complete solution that is efficient and easy to understand +- Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- Consider caching, batching, and parallelism when measurements justify their complexity and memory cost +- Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads +- Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations +- Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity + +## Clarity, naming, and spacing + +- Clean up the methods being changed, including their tests +- Use descriptive names that explain purpose; include units where useful +- Avoid cryptic abbreviations, misleading names, and unexplained production constants +- Keep control flow direct and share repeated logic when it makes the code simpler +- Separate logical steps with sensible blank lines so code is easy to scan +- Put a blank line after a multiline `let ... else` guard before the next statement; never place the next `let` directly after its closing `};` +- Keep related statements together and follow the repository's formatter + +## Source organization + +- Keep each class, enum, or struct in its own source file, with its implementation beside it +- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust +- Use singular folder names, such as `map`, `setting`, or `tracing` +- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file + +## Comments + +- Use short, single-line comments or concise adjacent comments +- Avoid block comments and prose wrapped across multiple comment lines +- Explain intent or a non-obvious constraint rather than narrating the code +- No trailing punctuation on ordinary code comments +- Avoid overexplaining and remove stale or redundant comments +- Apply these standards to both production code and tests + +## Validation and reporting + +- Run relevant tests and required repository checks with the project's expected toolchain +- For comments or spacing alone, verify formatting and that executable code is unchanged +- Report concrete findings with locations, reproduction details, and practical impact +- Separate confirmed problems from hypotheses and optional improvements +- Give measured optimization results with workload and environment details +- State remaining limitations and distinguish existing failures from new ones + +## Review and commit workflow + +- Preserve unrelated work and leave changes unstaged for my manual review unless I ask otherwise +- Stage only when requested +- Wait for my explicit commit command before committing +- Do not push or post reviews or comments without explicit instructions +- When requested, provide a simple ready-to-post Markdown summary outside the repository and exclude it from the commit + +## Scope of method fixes + +- Whenever a method needs a fix, apply all of my review standards across the entire method, including existing code outside the immediate fix +- Ensure the whole method has sensible spacing between logical steps and concise, useful comments that follow the standards above From 19f75c3a00b9eb7635d4763f6ac4ccd657f66b03 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 07:00:56 +0000 Subject: [PATCH 051/275] Smart material previews on the preview orb Smart material shelf tiles and hover previews render the real material, applied with materials::apply to the baked preview orb and composited by the compositor, lit in a dark studio of soft boxes. MaskPreview becomes OrbPreview (masks and materials share one bake and one worker). Tiles show a loading icon until their preview arrives; the web takes one worker request per frame. preview::material keeps plain materials only. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/lib.rs | 5 +- crates/engine/src/mask_preview.rs | 161 ---------- crates/engine/src/mask_preview_pixel.rs | 2 +- crates/engine/src/material_preview_pixel.rs | 16 + .../{mask_preview_camera.rs => orb_camera.rs} | 30 +- crates/engine/src/orb_preview.rs | 297 ++++++++++++++++++ crates/engine/src/preview.rs | 115 +++---- crates/geom/src/primitives.rs | 2 +- crates/ui-egui/src/lib.rs | 4 +- crates/ui-egui/src/mask_preview_image.rs | 2 +- crates/ui-egui/src/mask_shape.rs | 33 -- crates/ui-egui/src/material_preview_image.rs | 100 ++++++ crates/ui-egui/src/orb_shape.rs | 33 ++ crates/ui-egui/src/preview_image.rs | 73 +++-- crates/ui-egui/src/preview_request.rs | 10 +- crates/ui-egui/src/preview_worker.rs | 19 +- crates/ui-egui/src/shelf.rs | 49 +-- crates/ui-egui/src/shelf_preview.rs | 35 ++- crates/ui-egui/src/soft_box.rs | 48 +++ crates/ui-egui/src/thumbs.rs | 50 ++- crates/ui-egui/src/worker_preview.rs | 2 +- crates/ui-egui/tests/shelf_hover_preview.rs | 2 +- 22 files changed, 727 insertions(+), 361 deletions(-) delete mode 100644 crates/engine/src/mask_preview.rs create mode 100644 crates/engine/src/material_preview_pixel.rs rename crates/engine/src/{mask_preview_camera.rs => orb_camera.rs} (69%) create mode 100644 crates/engine/src/orb_preview.rs delete mode 100644 crates/ui-egui/src/mask_shape.rs create mode 100644 crates/ui-egui/src/material_preview_image.rs create mode 100644 crates/ui-egui/src/orb_shape.rs create mode 100644 crates/ui-egui/src/soft_box.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..cedf6cdb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,13 +22,14 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; -pub mod mask_preview; -mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; +mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod orb_camera; +pub mod orb_preview; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs deleted file mode 100644 index a44757fc..00000000 --- a/crates/engine/src/mask_preview.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Smart mask previews share one baked [`primitives::preview_orb`] -//! Presets use `mask.smart.apply` and the compositor, matching document masks - -use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::primitives; - -use crate::mask_preview_camera::MaskPreviewCamera; -pub use crate::mask_preview_pixel::MaskPreviewPixel; -use crate::{EngineError, Result, Session}; - -/// Bake resolution in texels; 256 loses the thin edge lines -const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline) -const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews -pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel; thumbnail detail needs fewer than the default -const OCCLUSION_RAYS: u32 = 12; -/// Curvature rays per texel; thumbnail detail needs fewer than the default -const CURVATURE_RAYS: u32 = 12; -/// Radius relative to the bounding box; isolates panel edges from the round body -const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read -const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Keep camera views for the thumbnail and hover preview sizes -const CAMERAS_KEPT: usize = 2; - -/// The baked preview shape and, per preview size, what its camera sees -pub struct MaskPreview { - session: Session, - layer: LayerId, - /// Cached camera views, least recently used first - cameras: Vec, -} - -impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it) - pub fn new() -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); - } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; - session.bake_now(0, false)?; - - Ok(MaskPreview { session, layer, cameras: Vec::new() }) - } - - /// Row-major `size²` pixels, with None outside the shape - /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] - pub fn render(&mut self, id: &str, size: usize) -> Option>> { - if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { - return None; - } - - crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Previews need no undo history; retaining snapshots grows memory across presets - self.session.undo.clear(); - - let camera = camera_for(&mut self.cameras, &self.session, size)?; - let values = self.session.mask_at(self.layer, &camera.texels)?; - - let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..size * size) - .map(|i| { - let (x, y) = (i % size, i / size); - let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); - for sy in 0..SUPERSAMPLE { - for sx in 0..SUPERSAMPLE { - let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; - let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; - - mask += values.get(texel).copied().unwrap_or(0.0); - normal += n; - hits += 1.0; - } - } - (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) - }) - .collect(); - Some(pixels) - } -} - -/// Cache one camera per preview size, evicting the least recently used view -fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { - let rays_per_side = size * SUPERSAMPLE; - let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { - Some(i) => cameras.remove(i), - None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), - }; - if cameras.len() >= CAMERAS_KEPT { - cameras.remove(0); - } - - cameras.push(camera); - cameras.last() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Mean absolute difference of the masks of two previews over the pixels both see - fn difference(a: &[Option], b: &[Option]) -> f32 { - let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); - pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 - } - - #[test] - fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { - let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - let layer = session.doc.project.texture_set(0).unwrap().stack[0]; - let mut preview = MaskPreview { session, layer, cameras: Vec::new() }; - for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { - assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); - assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); - assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); - } - } - - #[test] - fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { - let size = 24; - let mut preview = MaskPreview::new().unwrap(); - for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); - assert_eq!(px.len(), size * size, "{}", sm.id); - assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); - let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); - assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); - for p in seen { - assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); - assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); - } - } - - let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); - let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); - assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); - assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope", size).is_none()); - - let big = preview.render("edges_sharp", size * 3).unwrap(); - let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; - assert_eq!(big.len(), size * size * 9); - assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); - preview.render("edges_sharp", size * 2).unwrap(); - assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); - } -} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs index bcde5629..14ad5842 100644 --- a/crates/engine/src/mask_preview_pixel.rs +++ b/crates/engine/src/mask_preview_pixel.rs @@ -1,4 +1,4 @@ -//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). +//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`]) use texturecraft_geom::glam::Vec3; diff --git a/crates/engine/src/material_preview_pixel.rs b/crates/engine/src/material_preview_pixel.rs new file mode 100644 index 00000000..7b83422e --- /dev/null +++ b/crates/engine/src/material_preview_pixel.rs @@ -0,0 +1,16 @@ +//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`]) + +use texturecraft_geom::glam::Vec3; + +use crate::preview::Sample; + +/// The material values seen at a preview pixel, with what a display needs to light the shape +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialPreviewPixel { + /// Linear material values, averaged over the pixel + pub sample: Sample, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer) + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline) + pub coverage: f32, +} diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/orb_camera.rs similarity index 69% rename from crates/engine/src/mask_preview_camera.rs rename to crates/engine/src/orb_camera.rs index ea3d6d1f..d0015361 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/orb_camera.rs @@ -1,4 +1,4 @@ -//! Cached camera rays for one smart mask preview size +//! Cached camera rays for one preview orb size use std::collections::HashMap; @@ -11,11 +11,11 @@ use crate::Session; const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss +/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees -pub(crate) struct MaskPreviewCamera { +/// What each ray of a square orthographic view of the orb sees +pub(crate) struct OrbCamera { /// Rays along each side of the view pub rays_per_side: usize, /// The texels (x, y) the camera sees, each once @@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera { pub samples: Vec, } -impl MaskPreviewCamera { +impl OrbCamera { /// Trace a square orthographic view onto a `texture_px²` texture - pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera { + let (min, max) = session.mesh.bounds(); + let center = (min + max) * 0.5; + let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max); let pitch = CAMERA_PITCH_DEG.to_radians(); let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); @@ -40,9 +40,9 @@ impl MaskPreviewCamera { let mut texels = Vec::new(); let mut index_of = HashMap::new(); let samples = (0..rays_per_side * rays_per_side) - .map(|i| { + .map(|ray| { let side = rays_per_side as f32; - let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0); // Start well outside the shape so every ray enters it from the front let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; let hit = session.bvh.closest(origin, forward, radius * 8.0)?; @@ -52,10 +52,12 @@ impl MaskPreviewCamera { texels.push(texel); texels.len() - 1 }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + + let normal = surface.nrm; + Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward)))) }) .collect(); - MaskPreviewCamera { rays_per_side, texels, samples } + + OrbCamera { rays_per_side, texels, samples } } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs new file mode 100644 index 00000000..f29a247d --- /dev/null +++ b/crates/engine/src/orb_preview.rs @@ -0,0 +1,297 @@ +//! Smart mask and smart material previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use texturecraft_texel::TILE; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +pub use crate::material_preview_pixel::MaterialPreviewPixel; +use crate::orb_camera::OrbCamera; +use crate::preview::Sample; +use crate::session::Document; +use crate::{EngineError, Result, Session, materials}; + +/// Bake resolution in texels; 256 loses the thin edge lines +const TEXTURE_PX: u32 = 512; +/// Camera rays per preview pixel along each axis (anti-aliased outline) +const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for shelf previews +pub const MAX_PREVIEW_SIZE_PX: usize = 512; +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default +const OCCLUSION_RAYS: u32 = 12; +/// Curvature rays per texel; thumbnail detail needs fewer than the default +const CURVATURE_RAYS: u32 = 12; +/// Radius relative to the bounding box; isolates panel edges from the round body +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read; smart materials build on the same presets +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Keep camera views for the thumbnail and hover preview sizes +const CAMERAS_KEPT: usize = 2; +/// The channels a material preview shows, in [`Sample`] order +const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; +/// The orb's only texture set +const SET: usize = 0; + +/// The baked orb and, per preview size, what its camera sees +pub struct OrbPreview { + session: Session, + /// The layer smart masks are applied to + layer: LayerId, + /// The baked document and selection, restored before each material + bare: (Document, BTreeMap), + /// Cached camera views, least recently used first + cameras: Vec, +} + +impl OrbPreview { + /// Bake the orb once (previews of any size reuse it) + pub fn new() -> Result { + let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(SET)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(SET, false)?; + + let bare = (session.doc.clone(), session.selected.clone()); + Ok(OrbPreview { session, layer, bare, cameras: Vec::new() }) + } + + /// Row-major `size²` pixels of smart mask `id`, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn mask(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Previews need no undo history; retaining snapshots grows memory across presets + self.session.undo.clear(); + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + mask_sum += values.get(texel).copied().unwrap_or(0.0); + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } + + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn material(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each material goes on the bare shape, not over the previous one + (self.session.doc, self.session.selected) = self.bare.clone(); + let applied = materials::apply(&mut self.session, id); + // Previews need no undo history; retaining snapshots grows memory across materials + self.session.undo.clear(); + applied.ok()?; + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = material_at(&self.session, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 }; + let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + let Some(value) = values.get(texel) else { continue }; + + sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]); + sum.metallic += value.metallic; + sum.roughness += value.roughness; + sum.height += value.height; + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| { + let mean = Sample { + base: sum.base.map(|component| component / hits), + metallic: sum.metallic / hits, + roughness: sum.roughness / hits, + height: sum.height / hits, + }; + MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels } + }) + }) + .collect(); + Some(pixels) + } +} + +/// Preview sizes the camera may allocate +fn valid_size(size: usize) -> bool { + (1..=MAX_PREVIEW_SIZE_PX).contains(&size) +} + +/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal) +fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator + '_ { + let (x, y) = (pixel % size, pixel / size); + (0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| { + let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE); + let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x; + camera.samples.get(ray).copied().flatten() + }) +} + +/// The material values at `texels`, compositing only the tiles that hold them +fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> { + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + + session.with_inputs(SET, |inputs| { + let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); + texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); + + let samples = texels + .iter() + .map(|&(x, y)| { + let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y)); + Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] } + }) + .collect(); + Some(samples) + }) +} + +/// Cache one camera per preview size, evicting the least recently used view +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a OrbCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) { + Some(index) => cameras.remove(index), + None => OrbCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } + + cameras.push(camera); + cameras.last() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + /// Mean mask value over the pixels a preview sees + fn mean_mask(pixels: &[Option]) -> f32 { + pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 + } + + #[test] + fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); + for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { + assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); + assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); + assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); + } + } + + #[test] + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for smart_mask in crate::smart_masks::SMART_MASKS { + let id = smart_mask.id; + let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame"); + for pixel in seen { + assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite(), "{id}: {pixel:?}"); + } + } + + let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap()); + let shows = |pixels: &[Option]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.mask("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.mask("edges_sharp", size * 3).unwrap(); + assert_eq!(big.len(), size * size * 9); + assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges)); + + preview.mask("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); + } + + #[test] + fn smart_materials_render_on_the_orb_and_show_their_wear() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for material in materials::MATERIALS.iter().filter(|material| material.smart) { + let id = material.id; + let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + for pixel in pixels.iter().flatten() { + let sample = pixel.sample; + let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]); + assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); + } + } + assert!(preview.material("nope", size).is_none()); + + // Paint chipped at the edges shows the steel under it: the smart material is not its base + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); + let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); + assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); + + let base_colors = |pixels: &[Option]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::>(); + assert_ne!(base_colors(&worn), base_colors(&steel)); + + // Each material starts from the bare orb: rendering another one in between changes nothing + preview.material("iron_rusted", size).unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 5b72cea4..ce45b9ff 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,14 +1,8 @@ -//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or -//! baked maps (generators that need mesh maps are approximated with world-space noise), and -//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked -//! preview ([`crate::mask_preview`]). +//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) use rayon::prelude::*; -use texturecraft_compose::pattern::{Coords, procedural, world_noise}; -use texturecraft_core::{ - Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, - Projection, Source, TextureSet, blend1, -}; +use texturecraft_compose::pattern::{Coords, procedural}; +use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { } } -/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities). -fn generator(g: &Generator, c: &Coords) -> f32 { - let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y); - let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2; - let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1; - let s = match g.kind { - GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5, - GeneratorKind::EdgeWear => wear, - GeneratorKind::Curvature => 0.5 + wear * 0.5, - GeneratorKind::AmbientOcclusion => 1.0 - cavity, - _ => cavity, - }; - // Same thresholding as the compositor. - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } -} - -fn mask(m: &Mask, c: &Coords) -> f32 { - if !m.enabled { - return 1.0; - } - let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 }; - for e in m.effects.iter().filter(|e| e.visible) { - let val = match &e.kind { - EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]), - EffectKind::Generator(g) => Some(generator(g, c)), - EffectKind::Levels(l) => Some(l.apply(v)), - EffectKind::Filter(Filter::Invert) => Some(1.0 - v), - _ => None, - }; - if let Some(val) = val { - let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) }; - v += (blended - v) * e.opacity.clamp(0.0, 1.0); - } - } - v.clamp(0.0, 1.0) -} - const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; -/// Preview of built-in material `id` (None for an unknown id). +/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps) pub fn material(id: &str, size: usize) -> Option>> { + let plain = crate::materials::find(id).filter(|found| !found.smart)?; let mut project = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?; // Pixels evaluate independently and big previews take long on one core let normals: Vec<_> = sphere_normals(size).collect(); @@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option>> { .map(|normal| { let at = coords(normal?); let mut values = CHANNELS.map(Channel::default_value); - for layer in layers.iter().filter(|l| l.visible) { + for layer in layers.iter().filter(|layer| layer.visible) { + // Plain materials are unmasked fills let LayerKind::Fill(fill) = &layer.kind else { continue }; - let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); for (value, channel) in values.iter_mut().zip(CHANNELS) { - let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at)); if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { - let weight = coverage * blend.opacity.clamp(0.0, 1.0); - *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); + let weight = blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight); } } } - let [base, metal, rough, height] = values; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + let [base, metallic, roughness, height] = values; + Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }) }) .collect(); + Some(samples) } @@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option>> { mod tests { use super::*; + /// Whether every value of `sample` is finite + fn finite(sample: &Sample) -> bool { + sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite) + } + #[test] fn previews_cover_the_sphere_with_finite_values() { - for m in crate::materials::MATERIALS { - let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id)); - let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id)); - assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); - assert!(px[0].is_none(), "corners are outside the sphere"); + let size = 16; + for built_in in crate::materials::MATERIALS { + let id = built_in.id; + if built_in.smart { + assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb"); + continue; + } + + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap(); + assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks"); + + let pixels = material(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); + assert!(pixels[0].is_none(), "corners are outside the sphere"); } - assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); - for f in crate::filter_lib::FILTERS { - let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); - let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); - assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id); + assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + + let size = 24; + for library_filter in crate::filter_lib::FILTERS { + let id = library_filter.id; + let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); } - let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap()); + let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } } diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 29bad947..69fab43b 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8; /// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. const ORB_PANEL_VALLEY: f32 = 0.88; -/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base /// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly /// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys /// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..f383c197 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,8 +17,9 @@ pub mod gpu; pub mod i18n; pub mod keymap; mod mask_preview_image; -mod mask_shape; +mod material_preview_image; pub mod menus; +mod orb_shape; pub mod parity; mod preview_image; mod preview_request; @@ -27,6 +28,7 @@ pub mod profile; pub mod render_mode; pub mod shelf; pub mod shelf_preview; +mod soft_box; pub mod state; pub mod theme; pub mod thumbs; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 4418d099..de7368df 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -2,7 +2,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::orb_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; /// View-space lighting uses an upper-left key and a weaker right fill diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs deleted file mode 100644 index c99a9b1c..00000000 --- a/crates/ui-egui/src/mask_shape.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The smart mask preview shape, baked on first use - -use texturecraft_engine::mask_preview::MaskPreview; - -/// Whether the smart mask preview shape is baked -#[derive(Default)] -pub enum MaskShape { - #[default] - NotBaked, - /// Box the large session to keep the unbaked worker small - Baked(Box), - /// The bake failed; smart mask previews stay empty - Failed, -} - -impl MaskShape { - /// Bake on first use; retain failure to avoid retrying every frame - pub fn get(&mut self) -> Option<&mut MaskPreview> { - if matches!(self, MaskShape::NotBaked) { - *self = match MaskPreview::new() { - Ok(preview) => MaskShape::Baked(Box::new(preview)), - Err(e) => { - log::warn!("smart mask previews: {e}"); - MaskShape::Failed - } - }; - } - match self { - MaskShape::Baked(preview) => Some(preview), - MaskShape::NotBaked | MaskShape::Failed => None, - } - } -} diff --git a/crates/ui-egui/src/material_preview_image.rs b/crates/ui-egui/src/material_preview_image.rs new file mode 100644 index 00000000..bc232b75 --- /dev/null +++ b/crates/ui-egui/src/material_preview_image.rs @@ -0,0 +1,100 @@ +//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaterialPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius}; +use crate::soft_box::{SoftBox, smoothstep}; + +/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind +const SOFT_BOXES: [SoftBox; 3] = [ + SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 }, + SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 }, + SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 }, +]; +/// The studio's backdrop brightness straight down and straight up (linear) +const FLOOR: f32 = 0.03; +const CEILING: f32 = 0.16; +/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges) +const MIN_ROUGHNESS: f32 = 0.02; +/// Reflectance of dielectrics at normal incidence +const DIELECTRIC_F0: f32 = 0.04; +/// Exposure before tone mapping +const EXPOSURE: f32 = 1.4; + +/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals +pub fn material_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let radius = preview_radius(size); + let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() { + let Some(pixel) = pixel else { continue }; + + let sample = pixel.sample; + let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius); + let roughness = sample.roughness.max(MIN_ROUGHNESS); + let normal_dot_view = normal.z.max(0.0); + // Mirror the direction towards the viewer (+Z) about the normal + let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero(); + let specular_light = reflected_light(reflected, roughness); + let diffuse_light = diffuse_light(normal); + // Schlick's Fresnel term, damped on rough surfaces below + let fresnel = (1.0 - normal_dot_view).powi(5); + + let color = [0, 1, 2].map(|component| { + let base = sample.base[component]; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic; + let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel; + let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light; + (linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8 + }); + let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha); + } + image +} + +/// How far unit direction component `y` points up: 0 straight down, 1 straight up +fn upward(y: f32) -> f32 { + y * 0.5 + 0.5 +} + +/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1) +fn backdrop(upward: f32) -> f32 { + FLOOR + (CEILING - FLOOR) * upward +} + +/// The studio seen along unit direction `view` by a surface of `roughness` +fn reflected_light(view: Vec3, roughness: f32) -> f32 { + // A soft horizon: reflections sweep from floor to ceiling smoothly + backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::() +} + +/// The light reaching a diffuse surface with unit normal `normal` +fn diffuse_light(normal: Vec3) -> f32 { + backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::preview::Sample; + + use super::*; + + #[test] + fn the_studio_lights_the_shape_from_the_upper_right() { + let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 }; + let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 }); + // Halfway between the viewer and the key light, a mirror reflects the key + let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z; + let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None]; + + let image = material_preview_image(2, &pixels); + let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]); + assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}"); + assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside"); + } +} diff --git a/crates/ui-egui/src/orb_shape.rs b/crates/ui-egui/src/orb_shape.rs new file mode 100644 index 00000000..3d220a5c --- /dev/null +++ b/crates/ui-egui/src/orb_shape.rs @@ -0,0 +1,33 @@ +//! The preview orb of the smart mask and smart material previews, baked on first use + +use texturecraft_engine::orb_preview::OrbPreview; + +/// Whether the preview orb is baked +#[derive(Default)] +pub enum OrbShape { + #[default] + NotBaked, + /// Box the large session to keep the unbaked worker small + Baked(Box), + /// The bake failed; previews on the orb stay empty + Failed, +} + +impl OrbShape { + /// Bake on first use; retain failure to avoid retrying every frame + pub fn get(&mut self) -> Option<&mut OrbPreview> { + if matches!(self, OrbShape::NotBaked) { + *self = match OrbPreview::new() { + Ok(preview) => OrbShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("preview orb: {e}"); + OrbShape::Failed + } + }; + } + match self { + OrbShape::Baked(preview) => Some(preview), + OrbShape::NotBaked | OrbShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index f689c85d..9b753b74 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -3,6 +3,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; @@ -12,6 +13,14 @@ use texturecraft_engine::texel::linear_to_srgb; const PROCEDURAL_SCALE: f32 = 3.0; /// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; +/// Normal tilt per height step, relative to the shape's radius in pixels +const BUMP_PER_RADIUS: f32 = 0.75; +/// Exposure of the shaded previews before tone mapping +const EXPOSURE: f32 = 1.4; +/// Gap between a preview's shape and the image edge in pixels +const SHAPE_MARGIN_PX: f32 = 1.0; +/// Guards the normal division against a zero vector +const MIN_NORMAL_LENGTH: f32 = 1e-6; /// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -52,28 +61,52 @@ pub fn aces(x: f32) -> f32 { /// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let radius = preview_radius(size); + let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height); - let (x, y) = (i % size, i / size); - let c = s.height; - // Image Y points down; the shading normal uses Y up - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + for (index, normal) in preview::sphere_normals(size).enumerate() { + let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue }; + + // Anti-aliased outline: opaque from one pixel inside the rim + let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0); + image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage); } - img + image +} + +/// Radius in pixels of the shape filling a `size²` preview +pub(crate) fn preview_radius(size: usize) -> f32 { + (size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5) +} + +/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center` +pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option) -> [f32; 2] { + let (x, y) = (pixel % size, pixel / size); + let at = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + height(y.checked_mul(size)?.checked_add(x)?) + }; + + // Image Y points down; the shading normal uses Y up + let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center); + let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center); + [right, up] +} + +/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels +pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 { + let bump = radius * BUMP_PER_RADIUS; + let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z]; + let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH); + Vec3::from(bumped.map(|component| component / length)) +} + +/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque +fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 { + let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness); + let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8) } /// Grayscale `size²` swatch of procedural `kind` diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c7870b..7797a7e3 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -3,7 +3,8 @@ use egui::ColorImage; use crate::mask_preview_image::mask_preview_image; -use crate::mask_shape::MaskShape; +use crate::material_preview_image::material_preview_image; +use crate::orb_shape::OrbShape; use crate::shelf_preview::ShelfPreview; /// Render `preview` at `size_px²`; the answer comes back under `key` @@ -18,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the mask shape on first use + /// Render the asset, baking the orb on first use for smart masks and smart materials /// Unknown assets and failed bakes return None - pub fn render(&self, shape: &mut MaskShape) -> Option { + pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { - ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index a3d2cc8f..1fe89353 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -2,7 +2,7 @@ //! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] -use crate::mask_shape::MaskShape; +use crate::orb_shape::OrbShape; use crate::preview_request::PreviewRequest; /// Request key and rendered image; None on failure @@ -18,7 +18,7 @@ pub enum PreviewWorker { Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] - Inline { shape: MaskShape, results: Vec }, + Inline { shape: OrbShape, results: Vec }, /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -89,7 +89,7 @@ impl PreviewWorker { use std::collections::VecDeque; use std::sync::mpsc::channel; - use crate::mask_shape::MaskShape; + use crate::orb_shape::OrbShape; let (requests, request_rx) = channel::(); let (result_tx, results) = channel(); @@ -101,7 +101,7 @@ impl PreviewWorker { if let Err(e) = &pool { log::warn!("shelf previews share the global thread pool: {e}"); } - let mut shape = MaskShape::default(); + let mut shape = OrbShape::default(); let mut queue = VecDeque::new(); loop { if queue.is_empty() { @@ -136,7 +136,7 @@ impl PreviewWorker { /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { - PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() } } } @@ -170,23 +170,26 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), + ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; + let requests_sent = requests.len(); for (key, preview) in requests { assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); } let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask"] { + for key in ["material", "mask", "smart material"] { let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); assert_eq!(image.size, [size_px, size_px], "{key}"); } - for key in ["unknown material", "unknown mask"] { + for key in ["unknown material", "unknown mask", "unknown smart material"] { assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); } assert!(!worker.is_stopped()); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..5d876249 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,8 +12,8 @@ use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::materials::MATERIALS; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -34,8 +34,9 @@ const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width -const PLACEHOLDER_RADIUS: f32 = 0.45; +/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color +const LOADING_ICON_SCALE: f32 = 0.9; +const LOADING_ICON_OPACITY: f32 = 0.5; /// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; @@ -300,20 +301,22 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// Built-in materials (or smart materials), grouped by category. +/// Built-in materials or smart materials, grouped by category fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect(); + let shown: Vec<_> = + MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); if shown.is_empty() { return; } + title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); + for category in categories(&shown, |material| material.category) { + header(ui, category); tiles(ui, |ui| { - for m in shown.iter().filter(|m| m.category == cat) { - let tex = app.thumbs.material(ctx, m.id); - let asset = Asset::Material(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { + for material in shown.iter().filter(|material| material.category == category) { + let texture = app.thumbs.material(ctx, material.id); + let asset = Asset::Material(material.id); + if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -623,8 +626,9 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let preview = preview(); let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; - // High display scales must respect the mask camera's allocation limit - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + // High display scales must respect the orb camera's allocation limit + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); @@ -636,14 +640,21 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders -fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { - match tex { - Some(t) => { - painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); +/// `texture` drawn into `rect`, or a dim loading icon while it renders +fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); + let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROWS_CLOCKWISE, + font, + tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY), + ); } } } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a23ffb32..b512f250 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; @@ -14,9 +15,11 @@ use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_ /// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere + /// A built-in plain material on a sphere Material(&'static str), - /// Smart mask rendering requires the worker's baked shape + /// Smart material rendering requires the worker's baked orb + SmartMaterial(&'static str), + /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), /// A library filter on a sample material on a sphere Filter(&'static str), @@ -31,10 +34,19 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Smart materials preview on the orb, plain materials on a sphere + pub fn material(id: &'static str) -> ShelfPreview { + match materials::find(id) { + Some(found) if found.smart => ShelfPreview::SmartMaterial(id), + Some(_) | None => ShelfPreview::Material(id), + } + } + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), @@ -45,11 +57,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks return None here because their bake belongs to the worker + /// Smart masks and smart materials return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), @@ -86,14 +98,23 @@ mod tests { let key = preview.key(); let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); - assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows"); } let finite = |samples: Vec>| { - samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) }; assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); - assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); + assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); + } + + #[test] + fn smart_materials_and_only_they_preview_on_the_orb() { + for material in MATERIALS { + let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_)); + assert_eq!(on_the_orb, material.smart, "{}", material.id); + } } } diff --git a/crates/ui-egui/src/soft_box.rs b/crates/ui-egui/src/soft_box.rs new file mode 100644 index 00000000..9c2c8391 --- /dev/null +++ b/crates/ui-egui/src/soft_box.rs @@ -0,0 +1,48 @@ +//! A soft box of the smart material preview studio (see [`crate::material_preview_image`]) + +use texturecraft_engine::geom::glam::Vec3; + +/// How much roughness widens a soft box's reflection, in radians per unit of roughness +const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1; +/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians +const EDGE_SOFTNESS: f32 = 0.25; +const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02; +/// The share of a soft box's light that reaches a diffuse surface facing it +const DIFFUSE_SHARE: f32 = 0.9; + +/// A round area light far away, seen as a disc in reflections +pub struct SoftBox { + /// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized + pub direction: [f32; 3], + /// Angular radius of the disc in radians + pub radius_rad: f32, + /// Brightness of the disc (linear) + pub intensity: f32, +} + +impl SoftBox { + /// The unit direction towards the light + pub fn unit_direction(&self) -> Vec3 { + Vec3::from(self.direction).normalize_or_zero() + } + + /// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out) + pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 { + let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS); + let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos(); + let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD; + let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad); + self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside + } + + /// The light reaching a diffuse surface with unit normal `normal` + pub fn diffuse(&self, normal: Vec3) -> f32 { + self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0) + } +} + +/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends +pub fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9ed4f73b..d0067411 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,6 @@ //! Shelf and brush preview caches //! Small synchronous renders are limited per frame -//! Smart masks and hover previews use [`PreviewWorker`] +//! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -16,7 +16,7 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) +/// UI-thread renders per frame at most; a web worker request uses the whole budget const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; @@ -37,7 +37,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews + /// Renders the orb thumbnails and the big previews worker: PreviewWorker, /// Worker-rendered previews by [`worker_key`] rendered: HashMap, @@ -82,25 +82,34 @@ impl Thumbs { /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); } + if !self.spend_budget(ctx, 1) { + return None; + } + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint + fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool { let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); } - if self.budget.1 >= PER_FRAME { + if self.budget.1 + renders > PER_FRAME { ctx.request_repaint(); - return None; + return false; } - self.budget.1 += 1; - // An unknown asset shows as an empty thumbnail - let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); - let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + self.budget.1 += renders; + true } /// Request once per asset and size; return None while pending or after failure @@ -109,13 +118,19 @@ impl Thumbs { self.receive(ctx); let key = worker_key(&preview, size_px); - if !self.rendered.contains_key(&key) { + if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); } + self.ready(&key) } + /// Native workers take every request; the web renders inline, so it takes one per frame + fn may_request(&mut self, ctx: &egui::Context) -> bool { + !cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME) + } + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { @@ -169,9 +184,12 @@ impl Thumbs { self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id` + /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { - self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + match ShelfPreview::material(id) { + preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false), + preview => self.shelf(ctx, preview, SPHERE_PX), + } } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 53767276..27c3525b 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -7,6 +7,6 @@ pub enum WorkerPreview { /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) + /// The asset is unknown or the worker could not render it (the tile keeps its loading icon) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 460ed7c8..2ad76a68 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -145,7 +145,7 @@ fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { - use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; + use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::smart_masks::SMART_MASKS; let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0); From 14f2332a695704b05e7c876c13b62c787ee8e7f9 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:50:02 +0100 Subject: [PATCH 052/275] Copy the shared house rules into AGENTS.md. The blocks come from craft-contrib at dde09ea31e2e457f5b4653a6e76f7cdf55944bdf. CLAUDE.md imports AGENTS.md. The house-rules workflow checks the copy. --- .github/workflows/house-rules.yml | 28 ++++++++++++++ AGENTS.md | 64 +++++++++++++++++++++++++++---- CLAUDE.md | 6 +-- 3 files changed, 86 insertions(+), 12 deletions(-) create mode 100644 .github/workflows/house-rules.yml diff --git a/.github/workflows/house-rules.yml b/.github/workflows/house-rules.yml new file mode 100644 index 00000000..de64ad3e --- /dev/null +++ b/.github/workflows/house-rules.yml @@ -0,0 +1,28 @@ +name: House rules + +on: + push: + branches: [main] + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + pull_request: + paths: + - AGENTS.md + - CLAUDE.md + - .github/workflows/house-rules.yml + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: house-rules-${{ github.ref }} + cancel-in-progress: true + +jobs: + house-rules: + uses: storytold/craft-common-actions/.github/workflows/house-rules.yml@main + with: + rust: true diff --git a/AGENTS.md b/AGENTS.md index 5882a81c..c9b40de3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,3 +1,56 @@ + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + # AGENTS.md: guide for AI agents and contributors TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the @@ -10,10 +63,7 @@ PdfCraft, EffectCraft, DesignCraft) in user-facing text: UI, window titles, Abou release names, docs prose. Machine names stay lowercase: crates (`texturecraft-*`), binaries, file names, ids (`ai.storyteller.texturecraft`), the native project extension `.tcraft`. -Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next -to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its -standards, and contribute reusable learnings back there. Shared code goes only in craft-libs -(`standards/shared-libraries.md`); otherwise copy, don't depend. +Shared code goes only in craft-libs; otherwise copy, don't depend. The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer stack semantics and export conventions) with better performance, every feature drivable by agents, @@ -98,7 +148,7 @@ as a clean-room implementation, in code, docs and commits. People trust TextureCraft with hours of painting. A malformed mesh or project, a bad command or MCP param, an odd keystroke or a full disk must produce an error the user or agent can act on, never a -panic. The shared standard is `../craftrules/standards/never-crash.md`. +panic. - Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or `unimplemented!`. Every production crate root carries @@ -176,6 +226,6 @@ after every arc of work that builds and passes. - `ROADMAP.md`: milestones, parity estimate and remaining effort. - `docs/parity.md`: generated Painter menu coverage. -- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing. -- `plan/` (local, gitignored): execution plan and notes. +- `docs/releasing.md`: release builds and signing. +- `plan/` is an optional gitignored notebook (execution notes). Do not ask for it and do not stop when it is absent. - `log/` (local, gitignored): the dev log. diff --git a/CLAUDE.md b/CLAUDE.md index 3e690427..43c994c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,5 +1 @@ -# TextureCraft: instructions for Claude - -Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository -(workspace map, golden rules including the asset and attribution rules, the definition of done). -Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps. +@AGENTS.md From 5da1f689fc2fc301f10175bc346b69a4f81bf712 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:41:09 +0100 Subject: [PATCH 053/275] docs: route release version bumps through pull requests --- docs/releasing.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/docs/releasing.md b/docs/releasing.md index c387a5f3..2658af20 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,20 +1,19 @@ # Releasing TextureCraft -The recipe is craftrules' [release playbook](release-playbook.md); this page covers what is +The recipe is the [release playbook](release-playbook.md); this page covers what is specific to TextureCraft. The pipeline is [`.github/workflows/release.yml`](../.github/workflows/release.yml). ## Release manager checklist The steps below are the release manager's; agents never create the `release` branch, tags or -GitHub Releases. The shared runbook with copy-paste `gh` commands is craftrules -`release/cut-a-release.md`. +GitHub Releases. Follow the checklist below and the linked release playbook. ### 1. One-time repository setup (org admin) Status on 2026-10-23: `storytold/texturecraft` has the `release` environment (deployable from `release` only) and the `release` ruleset (steps 1 and 2 below). Still to do before the first run: the secrets (step 3) and the runner group (step 4); the `release` branch is created by the first -release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 for this repo: +release push. An org admin completes the following setup for this repo: 1. Create the **`release` environment**, with deployment branches limited to `release`. 2. Add the **ruleset on `refs/heads/release`** (restrict creations, updates and deletions, block @@ -38,15 +37,21 @@ release push. An org admin runs craftrules `release/signing-setup.md` steps 1-2 ### 2. Set the version -On `main`: +Start from an up-to-date `main` and create a version-bump branch: ```sh +git switch main +git pull --ff-only +git switch -c bump-version-0.2.0 cargo xtask version # prints the current version cargo xtask version set 0.2.0 # or 0.2.0-rc.1 for a pre-release ``` `set` rewrites `[workspace.package] version` in the root `Cargo.toml` (the single source of truth) -and refreshes `Cargo.lock`. Commit, push, and wait for CI on `main` to pass. +and refreshes `Cargo.lock`. Commit the version bump on that branch, push the branch, and open +a pull request into `main`. Wait for the applicable checks to pass and for review, then merge +the pull request. Do not push changes directly to `main`. Wait for CI on the merged `main` +commit to pass before cutting the release below. ### 3. Cut the release @@ -160,7 +165,7 @@ unsigned artifact and a `::warning::`, never a failed build. ## Icons `assets/app-icon/texturecraft.svg` is the engraved zebra (the owner's original drawing, vectorised -to three colours, craftrules `standards/icon-design.md`); `texturecraft-small.svg` is a lighter +to three colours); `texturecraft-small.svg` is a lighter trace for the hicolor scalable icon. `packaging/icons.sh` renders everything else with resvg and `cargo xtask ico|icns`: the hicolor PNGs (16-512 px) and scalable SVG, `texturecraft-1024.png`, `texturecraft.ico` and `texturecraft.icns`. The outputs are committed; rerun it after changing the From 0f0047ae7b4f3427b7278a7cb28fac560aa0601b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:27:43 +0000 Subject: [PATCH 054/275] Panel layouts survive a restart The UI state was saved as RON through eframe's storage, and a dock read through a JSON value lost RON's enum variant names, so every saved layout loaded as the default. The UI state is now saved as JSON in a store of its own: ui.json beside eframe's settings on the desktop, a storage key on the web. A saved state this build cannot fully read is kept beside it before the next save, and the state earlier builds saved still loads. --- apps/texturecraft/src/main.rs | 60 +++-- crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/state.rs | 24 +- crates/ui-egui/src/ui_state_store.rs | 314 ++++++++++++++++++++++++++ crates/ui-egui/tests/split_divider.rs | 14 +- 5 files changed, 373 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/ui_state_store.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..694e8826 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,6 +11,7 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). @@ -115,13 +116,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off +fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); + let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -170,20 +174,24 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); let session = initial_session(&args); - // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + if let Some(file) = &ui_file { + let _ = ui_state_store::FILE.set(file.clone()); + } + let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -195,7 +203,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -296,19 +304,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; - // Written as eframe writes it: a pretty RON map of RON strings. + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); - std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + ui.prefs.system_title_bar = !on; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + std::fs::write(&json_path, "not json").unwrap(); + std::fs::write(&ron_path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..2a586519 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -32,6 +32,7 @@ pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; pub mod viewport; pub mod web_files; pub mod widgets; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { /// A smooth move to a saved camera in progress. camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -132,12 +135,13 @@ pub struct TextureCraftApp { impl TextureCraftApp { pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui @@ -147,6 +151,7 @@ impl TextureCraftApp { camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -179,14 +184,14 @@ impl TextureCraftApp { export_templates::load_library(&mut app, cc.storage); #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } app } @@ -477,7 +482,7 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); export_templates::save_library(self, storage); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..2aaab049 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -429,35 +429,13 @@ mod tests { } } - /// The app's own settings store: eframe keeps `UiState` as RON text under a key - #[derive(Default)] - struct MemoryStorage(std::collections::HashMap); - - impl eframe::Storage for MemoryStorage { - fn get_string(&self, key: &str) -> Option { - self.0.get(key).cloned() - } - - fn set_string(&mut self, key: &str, value: String) { - self.0.insert(key.to_string(), value); - } - - fn remove_string(&mut self, key: &str) { - self.0.remove(key); - } - - fn flush(&mut self) {} - } - #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { let mut ui = UiState { mode, ..UiState::default() }; ui.sync_mode_dock(); - let mut storage = MemoryStorage::default(); - eframe::set_value(&mut storage, "ui", &ui); - let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + let mut restarted = crate::ui_state_store::tests::restart(&ui); restarted.sync_mode_dock(); let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..467dad78 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,314 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// eframe storage key under which earlier builds kept the UI state, as RON +const RON_STORAGE_KEY: &str = "ui"; + +/// eframe storage key of a saved state this build could not fully read, where there is no file +const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; + +/// Largest UI state file read; a saved state is a few kilobytes +const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; + +/// Copies of unreadable saved states kept beside the file before saving stops +const MAX_UNREADABLE_COPIES: u32 = 10; + +/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + unreadable: Option>, + /// The unreadable state could not be kept, so the saved one is left as it is + frozen: bool, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, unreadable: None, frozen: false } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) if too_large(file) => { + self.frozen = true; + return None; + } + Some(file) => std::fs::read(file).ok(), + None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), + }; + let Some(bytes) = saved else { + return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); + }; + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some(bytes); + } + ui + } + + /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds + pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { + if let Some(bytes) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, storage); + } + if self.frozen { + return; + } + + let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => { + storage.set_string(STORAGE_KEY, json); + true + } + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + } + } + + /// Keep a saved state this build could not fully read, beside the file or under its own storage key + fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + match &self.file { + Some(file) => keep_file_copy(file, bytes), + None => { + storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + true + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + if too_large(file) { + return None; + } + + serde_json::from_slice(&std::fs::read(file).ok()?).ok() +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// Whether `file` is too large to be a saved UI state, so it is neither read nor saved over +fn too_large(file: &Path) -> bool { + std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` +fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { + use std::io::Write as _; + + let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; + match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// eframe's storage held in memory + #[derive(Default)] + pub(crate) struct MemoryStorage(pub(crate) std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.0)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.0.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + store.save(&loaded.unwrap_or_default(), &mut storage); + let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); + assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + let folder = test_folder("frozen"); + let file = folder.join("ui.json"); + for n in 1..=MAX_UNREADABLE_COPIES { + let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; + std::fs::write(folder.join(name), "").unwrap(); + } + std::fs::write(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); + let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); + storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } +} diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs index d5af8c8f..e0a487fc 100644 --- a/crates/ui-egui/tests/split_divider.rs +++ b/crates/ui-egui/tests/split_divider.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` const MIN_VIEW_WIDTH: f32 = 16.0; @@ -144,16 +145,15 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { let mut storage = MemoryStorage::default(); let mut ui_state = UiState::default(); ui_state.split_ratio = 0.3; - eframe::set_value(&mut storage, "ui", &ui_state); - let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); assert_eq!(restored.split_ratio, 0.3); // A state saved before the divider existed has no ratio - let saved = storage.0.get("ui").cloned().unwrap(); - let without_ratio = saved.replace("split_ratio:0.3,", ""); - assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); - storage.0.insert("ui".to_owned(), without_ratio); - let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); assert_eq!(restored.split_ratio, 0.5); } From b1f377b8eb76705aeea098f048b7e0a78730e15f Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:46:46 +0000 Subject: [PATCH 055/275] Bake curvature from the mesh by default The normal-map method cannot see the low poly's own edges: a box baked from itself gets flat curvature, and a box baked from a beveled high poly gets a dark line along its convex edges. New projects now start on the mesh method; projects that store a method keep it. --- crates/bake/src/tests.rs | 19 ++++++++++++++ crates/core/src/bake/curvature_method.rs | 2 +- crates/core/src/bake/curvature_settings.rs | 8 +----- crates/core/tests/bake_settings.rs | 4 ++- crates/ui-egui/tests/bake_mode.rs | 29 ++++++++++++++-------- 5 files changed, 43 insertions(+), 19 deletions(-) diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index bb75353e..aaa855f6 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -565,6 +565,25 @@ fn a_high_poly_box_has_bright_edges_and_flat_faces() { } } +#[test] +fn default_curvature_brightens_box_edges_and_never_darkens_them() { + let mut bake_settings = settings(256, &[BakedMap::Curvature]); + bake_settings.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..bake_settings.cage }; + bake_settings.maps.curvature.parameters.method = CurvatureMethod::default(); + + // A box has no concave texel, whether it is baked from itself or from a beveled high poly + let low = primitives::cube(2.0); + let high = primitives::rounded_box(Vec3::ONE, 0.15); + let bakes = [("itself", run(&low, &bake_settings).unwrap()), ("a beveled high poly", transfer(&low, &high, None, &bake_settings).unwrap())]; + for (source, bake_output) in bakes { + let curvature = covered_values(&low, &bake_output, BakedMap::Curvature); + let darkest = curvature.iter().map(|(_, value)| *value).fold(1.0, f32::min); + let brightest = curvature.iter().map(|(_, value)| *value).fold(0.0, f32::max); + assert!(darkest > 0.45, "baked from {source}, darkest {darkest}"); + assert!(brightest > 0.6, "baked from {source}, brightest {brightest}"); + } +} + #[test] fn a_narrow_high_poly_bevel_stays_bright() { let s = { diff --git a/crates/core/src/bake/curvature_method.rs b/crates/core/src/bake/curvature_method.rs index 2085c85b..32ac645b 100644 --- a/crates/core/src/bake/curvature_method.rs +++ b/crates/core/src/bake/curvature_method.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum CurvatureMethod { - #[default] NormalMap, + #[default] Mesh, } diff --git a/crates/core/src/bake/curvature_settings.rs b/crates/core/src/bake/curvature_settings.rs index d67138b8..66b4e732 100644 --- a/crates/core/src/bake/curvature_settings.rs +++ b/crates/core/src/bake/curvature_settings.rs @@ -1,16 +1,10 @@ use super::{CurvatureMethod, MeshCurvatureSettings, NormalMapCurvatureSettings}; use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct CurvatureSettings { pub method: CurvatureMethod, pub normal_map: NormalMapCurvatureSettings, pub mesh: MeshCurvatureSettings, } - -impl Default for CurvatureSettings { - fn default() -> Self { - Self { method: CurvatureMethod::NormalMap, normal_map: NormalMapCurvatureSettings::default(), mesh: MeshCurvatureSettings::default() } - } -} diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 708560f0..800efd98 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -20,7 +20,7 @@ fn reference_defaults_cover_common_and_per_map_settings() { "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { - "method": "NormalMap", + "method": "Mesh", "normal_map": {"details": 0.5, "enable_seams": true, "seams_intensity": 1.0}, "mesh": {"rays": 32, "sampling_radius": 0.001, "relative_to_bounding_box": true, "self_intersection": "Always", "auto_tonemapping": true, "value_min": -1.0, "value_max": 1.0} }, @@ -54,7 +54,9 @@ fn reference_defaults_cover_common_and_per_map_settings() { } } } + assert_shape(&serde_json::to_value(decoded).unwrap(), &expected); + assert_eq!(BakedMap::ALL.len(), 10); for name in ["color_map", "Color map", "WorldDirection", "world_space_direction"] { assert_eq!(BakedMap::parse(name), None); diff --git a/crates/ui-egui/tests/bake_mode.rs b/crates/ui-egui/tests/bake_mode.rs index 88a7c1f2..1b330244 100644 --- a/crates/ui-egui/tests/bake_mode.rs +++ b/crates/ui-egui/tests/bake_mode.rs @@ -434,39 +434,48 @@ fn check_all_enables_every_map_then_disables_them_all() { #[test] fn the_breadcrumb_switches_the_shown_map() { let mut harness = harness(Some(BakedMap::Curvature)); - harness.get_by_label("Details"); + harness.get_by_label("Sampling Radius"); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); + let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; map_dropdown.click(); harness.run_steps(3); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); + // The menu draws its items after the list rows harness.get_all_by_role_and_label(Role::Button, "Position").last().unwrap().click(); harness.run_steps(3); harness.get_by_label("Normalization Scale"); - assert!(harness.query_by_label("Details").is_none()); + assert!(harness.query_by_label("Sampling Radius").is_none()); assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } #[test] fn curvature_controls_follow_the_method_and_notes_visibility_rules() { let mut harness = harness(Some(BakedMap::Curvature)); - harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); - click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); - click(&mut harness, "Method"); - click(&mut harness, "Generate from Mesh"); - assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.method, CurvatureMethod::Mesh); + let curvature = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters; + + assert_eq!(curvature(&harness).method, CurvatureMethod::Mesh); assert!(harness.query_by_label("Details").is_none()); harness.get_by_label("Sampling Radius"); assert!(harness.query_by_label("Value Bounds Min").is_none()); assert!(harness.query_by_label("Value Bounds Max").is_none()); + click(&mut harness, "Auto Tonemapping"); harness.get_by_label("Value Bounds Min"); harness.get_by_label("Value Bounds Max"); - assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters.mesh.auto_tonemapping); + assert!(!curvature(&harness).mesh.auto_tonemapping); + + click(&mut harness, "Method"); + click(&mut harness, "Generate from Normal Map"); + assert_eq!(curvature(&harness).method, CurvatureMethod::NormalMap); + assert!(harness.query_by_label("Sampling Radius").is_none()); + harness.get_by_label("Details"); + + harness.get_by_label("Seams Intensity"); + click(&mut harness, "Enable Seams"); + assert!(harness.query_by_label("Seams Intensity").is_none()); } #[test] From b0c07454af61416c860246053d3b05e373369932 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:05:59 +0000 Subject: [PATCH 056/275] Collapsible UV transformations section for fill projections Fill Properties keep the projection kind, its axis and the tri-planar hardness visible, and move scale, rotation and offsets into a collapsible "UV transformations" section, open by default, so the material channels sit higher. Each fill keeps its own open or closed state. The tri-planar "Blend sharpness" slider is now labelled "Hardness"; its range and effect are unchanged. --- crates/ui-egui/src/dock.rs | 108 +++++++++--------- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- .../ui-egui/tests/fill_projection_section.rs | 68 +++++++++++ 11 files changed, 132 insertions(+), 62 deletions(-) create mode 100644 crates/ui-egui/tests/fill_projection_section.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4d5a1d06..702104c0 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Source, + Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -1572,46 +1572,41 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } -/// Projection and per-channel sources of a fill: a fill layer's (`base` = {"layer"}, `on` = -/// its enabled channels) or a content fill effect's (`base` = {"effect"}, `on` = the channels -/// it has a source for). `reader` is the layer owning the fill (for anchor sources). +/// Projection and channel sources of a fill layer (`base` = {"layer"}) or fill effect (`base` = {"effect"}) filling `on`, owned by `reader` fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { - use texturecraft_engine::core::Projection; let salt = base.to_string(); - if let Projection::Decal(d) = &fill.projection { - decal_editor(app, ui, d, reader); + if let Projection::Decal(decal) = &fill.projection { + decal_editor(app, ui, decal, reader); } else { projection_editor(app, ui, fill, base); } + ui.add_space(6.0); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let enabled = on.contains(c); - if chip(ui, tr(c.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("layer.fill.set", with(base, json!({"channel": c.id(), "enabled": solo || !enabled, "solo": solo}))); + for channel in &channels { + let enabled = on.contains(channel); + if chip(ui, tr(channel.short()), enabled).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "enabled": solo || !enabled, "solo": solo}))); } } }); + ui.add_space(4.0); let anchors = anchors_below(app, reader); - for c in chans { - if !on.contains(&c) { - continue; + for channel in channels { + if on.contains(&channel) { + fill_channel(app, ui, fill, base, channel, &anchors, &salt); } - fill_channel(app, ui, fill, base, c, &anchors, &salt); } } -/// The projection of a fill (other than a decal): kind, scale, and what the kind adds (UV -/// rotation and offset, tri-planar sharpness, an axis, a world offset). Each edit sends only the -/// field it changed; the command keeps the others. +/// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { - use texturecraft_engine::core::Projection; - let proj_label = fill.projection.label(); - combo(ui, tr("Projection"), tr(proj_label), |ui| { + let projection_label = fill.projection.label(); + combo(ui, tr("Projection"), tr(projection_label), |ui| { for (id, label) in [ ("uv", n_("UV projection")), ("triplanar", n_("Tri-planar projection")), @@ -1619,55 +1614,62 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: ("spherical", n_("Spherical projection")), ("cylindrical", n_("Cylindrical projection")), ] { - if ui.selectable_label(proj_label == label, tr(label)).clicked() { + if ui.selectable_label(projection_label == label, tr(label)).clicked() { app.run("layer.fill.projection", with(base, json!({"projection": id}))); } } }); - let mut scale = match &fill.projection { + + let mut edit = |extra: Value| { + app.run("layer.fill.projection", with(base, extra)); + }; + if let Projection::Planar { axis, .. } | Projection::Cylindrical { axis, .. } = &fill.projection + && let Some(picked_axis) = axis_combo(ui, *axis) + { + edit(json!({"axis": picked_axis})); + } + if let Projection::Triplanar { sharpness, .. } = &fill.projection { + let mut sharpness = *sharpness; + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, 1.0..=64.0, 1) { + edit(json!({"sharpness": sharpness, "merge": merge})); + } + } + + // One id per fill so each keeps its own open or closed state + section(ui, &format!("sec_fill_transform{base}"), tr("UV transformations"), true, |ui| { + projection_transform(ui, &fill.projection, &mut edit); + }); +} + +/// Scale plus what the projection kind adds: UV rotation and offset, or a world offset +fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl FnMut(Value)) { + let mut scale = match projection { Projection::Uv { scale, .. } => scale[0], Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } | Projection::Spherical { scale } | Projection::Cylindrical { scale, .. } => { *scale } Projection::Decal(_) => return, }; - let mut edit = |extra: Value| app.run("layer.fill.projection", with(base, extra)); if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { edit(json!({"scale": scale, "merge": merge})); } - match &fill.projection { + + match projection { Projection::Uv { rotation, offset, .. } => { - let mut r = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut r, 0.0..=360.0, 0) { - edit(json!({"rotation": r, "merge": merge})); + let mut rotation_degrees = *rotation; + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, 0.0..=360.0, 0) { + edit(json!({"rotation": rotation_degrees, "merge": merge})); } - if let Some((o, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": o, "merge": merge})); + if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { + edit(json!({"offset": offset, "merge": merge})); } } - Projection::Triplanar { sharpness, offset, .. } => { - let mut s = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Blend sharpness"), &mut s, 1.0..=64.0, 1) { - edit(json!({"sharpness": s, "merge": merge})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); + Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { + if let Some((offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { + edit(json!({"offset": offset, "merge": merge})); } } - Projection::Planar { axis, offset, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - if let Some((o, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": o, "merge": merge})); - } - } - Projection::Cylindrical { axis, .. } => { - if let Some(a) = axis_combo(ui, *axis) { - edit(json!({"axis": a})); - } - } - Projection::Spherical { .. } | Projection::Decal(_) => {} + Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0f2e023f..21c87eb2 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "النواظم المنحنية"), ("Bevel", "شطف الحواف"), ("Black", "أسود"), - ("Blend sharpness", "حدة المزج"), ("Blending", "الدمج"), ("Blending mode of the displayed channel", "نمط الدمج للقناة المعروضة"), ("Blur", "تمويه"), @@ -796,6 +795,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ مع الخامات"), ("UV checker", "رقعة فحص UV"), ("UV island fill", "تعبئة جزيرة UV"), + ("UV transformations", "تحويلات UV"), ("UV projection", "إسقاط UV"), ("UV tiles", "بلاطات UV"), ("UV tiles (UDIM)", "بلاطات UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 77cf296b..ea536d5e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Gebogene Normalen"), ("Bevel", "Abschrägung"), ("Black", "Schwarz"), - ("Blend sharpness", "Übergangsschärfe"), ("Blending", "Überblendung"), ("Blending mode of the displayed channel", "Füllmethode des angezeigten Kanals"), ("Blur", "Weichzeichnen"), @@ -835,6 +834,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ mit Texturen"), ("UV checker", "UV-Schachbrett"), ("UV island fill", "UV-Insel-Füllung"), + ("UV transformations", "UV-Transformationen"), ("UV projection", "UV-Projektion"), ("UV tiles", "UV-Kacheln"), ("UV tiles (UDIM)", "UV-Kacheln (UDIM)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4153783e..de7c76e2 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales curvadas"), ("Bevel", "Bisel"), ("Black", "Negro"), - ("Blend sharpness", "Nitidez de la mezcla"), ("Blending", "Fusión"), ("Blending mode of the displayed channel", "Modo de fusión del canal mostrado"), ("Blur", "Desenfoque"), @@ -823,6 +822,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texturas"), ("UV checker", "Damero UV"), ("UV island fill", "Relleno de islas UV"), + ("UV transformations", "Transformaciones UV"), ("UV projection", "Proyección UV"), ("UV tiles", "Mosaicos UV"), ("UV tiles (UDIM)", "Mosaicos UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0c07e5a4..fc4b8b11 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -111,7 +111,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normales déviées"), ("Bevel", "Biseau"), ("Black", "Noir"), - ("Blend sharpness", "Netteté du fondu"), ("Blending", "Fusion"), ("Blending mode of the displayed channel", "Mode de fusion du canal affiché"), ("Blur", "Flou"), @@ -841,6 +840,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ avec textures"), ("UV checker", "Damier UV"), ("UV island fill", "Remplissage d'îlots UV"), + ("UV transformations", "Transformations UV"), ("UV projection", "Projection UV"), ("UV tiles", "Tuiles UV"), ("UV tiles (UDIM)", "Tuiles UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index b4bd33b3..67648219 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -108,7 +108,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Bent normal"), ("Bevel", "Smusso"), ("Black", "Nero"), - ("Blend sharpness", "Nitidezza della fusione"), ("Blending", "Fusione"), ("Blending mode of the displayed channel", "Metodo di fusione del canale visualizzato"), ("Blur", "Sfocatura"), @@ -832,6 +831,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ con texture"), ("UV checker", "Scacchiera UV"), ("UV island fill", "Riempimento isola UV"), + ("UV transformations", "Trasformazioni UV"), ("UV projection", "Proiezione UV"), ("UV tiles", "Tile UV"), ("UV tiles (UDIM)", "Tile UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f764e268..dfbe8a65 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -111,7 +111,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "ベントノーマル"), ("Bevel", "ベベル"), ("Black", "黒"), - ("Blend sharpness", "ブレンドのシャープさ"), ("Blending", "ブレンド"), ("Blending mode of the displayed channel", "表示中のチャンネルのブレンドモード"), ("Blur", "ぼかし"), @@ -814,6 +813,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ (テクスチャ付き)"), ("UV checker", "UVチェッカー"), ("UV island fill", "UVアイランド塗りつぶし"), + ("UV transformations", "UV変換"), ("UV projection", "UV投影"), ("UV tiles", "UVタイル"), ("UV tiles (UDIM)", "UVタイル (UDIM)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a1c8d363..f81cfe6d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -105,7 +105,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "벤트 노멀"), ("Bevel", "베벨"), ("Black", "검은색"), - ("Blend sharpness", "블렌드 선명도"), ("Blending", "블렌딩"), ("Blending mode of the displayed channel", "표시된 채널의 블렌딩 모드"), ("Blur", "블러"), @@ -805,6 +804,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "텍스처 포함 USDZ"), ("UV checker", "UV 체커"), ("UV island fill", "UV 아일랜드 채우기"), + ("UV transformations", "UV 변환"), ("UV projection", "UV 투영"), ("UV tiles", "UV 타일"), ("UV tiles (UDIM)", "UV 타일 (UDIM)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 880b62ff..7bd3d231 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -108,7 +108,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "Normais curvadas"), ("Bevel", "Chanfro"), ("Black", "Preto"), - ("Blend sharpness", "Nitidez da mistura"), ("Blending", "Mesclagem"), ("Blending mode of the displayed channel", "Modo de mesclagem do canal exibido"), ("Blur", "Desfoque"), @@ -820,6 +819,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "USDZ com texturas"), ("UV checker", "Xadrez UV"), ("UV island fill", "Preenchimento de ilhas UV"), + ("UV transformations", "Transformações UV"), ("UV projection", "Projeção UV"), ("UV tiles", "Tiles UV"), ("UV tiles (UDIM)", "Tiles UV (UDIM)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f894f1ad..7d393f75 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -96,7 +96,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Bent Normals", "弯曲法线"), ("Bevel", "斜角"), ("Black", "黑色"), - ("Blend sharpness", "混合锐度"), ("Blending", "混合"), ("Blending mode of the displayed channel", "所显示通道的混合模式"), ("Blur", "模糊"), @@ -766,6 +765,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("USDZ with textures", "带纹理的 USDZ"), ("UV checker", "UV 棋盘格"), ("UV island fill", "UV 岛填充"), + ("UV transformations", "UV 变换"), ("UV projection", "UV 投影"), ("UV tiles", "UV 图块"), ("UV tiles (UDIM)", "UV 图块(UDIM)"), diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs new file mode 100644 index 00000000..c46b4c7e --- /dev/null +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -0,0 +1,68 @@ +//! A fill's projection settings fold into a "UV transformations" section under the Projection combo + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id +fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let layer = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, layer) +} + +fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_label("UV transformations").click(); + harness.run_steps(3); +} + +#[test] +fn the_uv_transformations_start_open_and_fold_away() { + let (mut harness, _) = app_with_fill("uv"); + assert!(harness.query_by_label("Rotation").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Projection").is_some()); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_some()); +} + +#[test] +fn hardness_and_axis_stay_outside_the_section() { + let (mut harness, _) = app_with_fill("triplanar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Hardness").is_some()); + + let (mut harness, _) = app_with_fill("planar"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Offset X").is_none()); + assert!(harness.query_by_label("Axis").is_some()); +} + +#[test] +fn each_fill_keeps_its_own_open_state() { + let (mut harness, first) = app_with_fill("uv"); + toggle_section(&mut harness); + + let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); + let second = added["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); + harness.run_steps(3); + assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); +} From a626af86bb7f9e3009968b3c77be0444c6d883e0 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:10:23 +0000 Subject: [PATCH 057/275] Keep every saved state that cannot be read, and save only states that read back --- crates/ui-egui/src/ui_state_store.rs | 146 +++++++++++++++++++++------ 1 file changed, 114 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 467dad78..4535817d 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -8,16 +8,16 @@ use crate::UiState; /// eframe storage key of the UI state as JSON, where there is no file const STORAGE_KEY: &str = "ui.json"; +/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there +const STORAGE_STEM: &str = "ui"; + /// eframe storage key under which earlier builds kept the UI state, as RON const RON_STORAGE_KEY: &str = "ui"; -/// eframe storage key of a saved state this build could not fully read, where there is no file -const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json"; - /// Largest UI state file read; a saved state is a few kilobytes const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024; -/// Copies of unreadable saved states kept beside the file before saving stops +/// Copies of unreadable saved states kept before saving stops const MAX_UNREADABLE_COPIES: u32 = 10; /// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage @@ -27,8 +27,9 @@ pub static FILE: OnceLock = OnceLock::new(); #[derive(Default)] pub struct UiStateStore { file: Option, - unreadable: Option>, - /// The unreadable state could not be kept, so the saved one is left as it is + /// A saved state this build could not fully read and its file extension, kept by the next save + unreadable: Option<(Vec, &'static str)>, + /// A saved state could not be read or kept, so it is left as it is frozen: bool, } @@ -45,30 +46,51 @@ impl UiStateStore { self.frozen = true; return None; } - Some(file) => std::fs::read(file).ok(), + Some(file) => match std::fs::read(file) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => { + self.frozen = true; + return None; + } + }, None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes), }; - let Some(bytes) = saved else { - return storage.and_then(|storage| eframe::get_value::(storage, RON_STORAGE_KEY)); - }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; let ui = serde_json::from_slice::(&bytes).ok(); if !ui.as_ref().is_some_and(fully_read) { - self.unreadable = Some(bytes); + self.unreadable = Some((bytes, "json")); + } + ui + } + + /// The RON state an earlier build saved; its docks never read back, so only text that does not parse is kept + fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(storage, RON_STORAGE_KEY); + if ui.is_none() { + self.unreadable = Some((text.into_bytes(), "ron")); } ui } /// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) { - if let Some(bytes) = self.unreadable.take() { - self.frozen = !self.keep_unreadable(&bytes, storage); + if let Some((bytes, extension)) = self.unreadable.take() { + self.frozen = !self.keep_unreadable(&bytes, extension, storage); } if self.frozen { return; } let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + // JSON writes a non-finite number as null, which would not read back + if serde_json::from_str::(&json).is_err() { + log::warn!("the UI state was not saved: it would not read back"); + return; + } + let saved = match &self.file { Some(file) => write_file(file, json.as_bytes()), None => { @@ -81,12 +103,15 @@ impl UiStateStore { } } - /// Keep a saved state this build could not fully read, beside the file or under its own storage key - fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool { + /// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage + fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool { match &self.file { - Some(file) => keep_file_copy(file, bytes), + Some(file) => keep_file_copy(file, bytes, extension), None => { - storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none()); + let Some(key) = free else { return false }; + + storage.set_string(&key, String::from_utf8_lossy(bytes).into_owned()); true } } @@ -112,6 +137,11 @@ fn too_large(file: &Path) -> bool { std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) } +/// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` +fn unreadable_name(stem: &str, n: u32, extension: &str) -> String { + if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") } +} + #[cfg(not(target_arch = "wasm32"))] fn write_file(file: &Path, bytes: &[u8]) -> bool { if let Some(folder) = file.parent() { @@ -126,14 +156,14 @@ fn write_file(_file: &Path, _bytes: &[u8]) -> bool { false } -/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` -fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool { +/// Copy `bytes` beside `file` under the first free copy name +fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool { use std::io::Write as _; let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default(); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") }; - match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) { + let copy_file = file.with_file_name(unreadable_name(&stem, n, extension)); + match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) { Ok(mut copy) => return copy.write_all(bytes).is_ok(), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} Err(_) => return false, @@ -257,7 +287,7 @@ pub(crate) mod tests { } store.save(&loaded.unwrap_or_default(), &mut storage); - let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) }; + let copy = unreadable_name("ui", n as u32 + 1, "json"); assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text); assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept"); } @@ -269,8 +299,7 @@ pub(crate) mod tests { let folder = test_folder("frozen"); let file = folder.join("ui.json"); for n in 1..=MAX_UNREADABLE_COPIES { - let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") }; - std::fs::write(folder.join(name), "").unwrap(); + std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap(); } std::fs::write(&file, "not json").unwrap(); @@ -298,17 +327,70 @@ pub(crate) mod tests { } #[test] - fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() { let mut storage = MemoryStorage::default(); UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage); - let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1); - storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone()); + let saved = storage.0[STORAGE_KEY].clone(); + for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] { + let unreadable = saved.replacen("\"Assets\"", panel, 1); + storage.0.insert(STORAGE_KEY.to_owned(), unreadable.clone()); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).unwrap(); + assert_eq!(loaded.dock, Dock::default()); + store.save(&loaded, &mut storage); + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, n, "json")], unreadable); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays"); + } + + #[test] + fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() { + let folder = test_folder("ron"); + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + storage.0.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned()); + + let mut store = UiStateStore::new(file.clone()); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + let copy = match &file { + Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(), + None => storage.0[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(), + }; + assert_eq!(copy, "(not ron", "{file:?}"); + assert!(!storage.0.contains_key(RON_STORAGE_KEY), "{file:?}"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() { + let folder = test_folder("read-error"); + let file = folder.join("ui.json"); + // A folder in the file's place fails to read with an error other than not found + std::fs::create_dir_all(&file).unwrap(); + let mut storage = MemoryStorage::default(); + eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default()); + + let mut store = UiStateStore::new(Some(file.clone())); + assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place"); + store.save(&UiState::default(), &mut storage); + assert!(file.is_dir()); + assert!(storage.0.contains_key(RON_STORAGE_KEY)); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_state_that_would_not_read_back_is_not_saved() { + let mut storage = MemoryStorage::default(); let mut store = UiStateStore::default(); - let loaded = store.load(Some(&storage)).unwrap(); - assert_eq!(loaded.dock, Dock::default()); - store.save(&loaded, &mut storage); - assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus); - assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage); + let saved = storage.0[STORAGE_KEY].clone(); + + store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage); + assert_eq!(storage.0[STORAGE_KEY], saved); } } From 56bbf26acf681d1be4d900a8c757f85c0dbb3b40 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 03:15:50 +0000 Subject: [PATCH 058/275] Bake: curvature from the normal map follows the surface, one band per edge Curvature from the normal map took a 4-texel (at 2K) difference of the tangent-space normal. The wide difference split each sharp normal change into two thin peaks with rings around small details, and the tangent map bends against a smooth-shaded low poly's own shading, so flat faces baked as concave. It now measures how fast the baked world normal turns along the surface direction of each texel step (from each low-poly triangle's UV mapping), with differences that never read uncovered texels or cross a UV tile, a 1-2-1 average across each derivative so lines are equally wide in every direction, and a soft roll-off instead of clipping. Details keeps its meaning; the default response is about 25% softer. Fixes #316 --- crates/bake/src/lib.rs | 16 ++- crates/bake/src/map.rs | 2 + crates/bake/src/map/normal_curvature.rs | 142 ++++++++++++++----- crates/bake/src/map/texel_grid.rs | 32 +++++ crates/bake/src/test/normal_map_curvature.rs | 84 +++++++++++ crates/bake/src/tests.rs | 18 +-- 6 files changed, 241 insertions(+), 53 deletions(-) create mode 100644 crates/bake/src/map/texel_grid.rs create mode 100644 crates/bake/src/test/normal_map_curvature.rs diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 67c349a4..a8b087bc 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -189,12 +189,13 @@ fn bake_in_strips( let mut scene = tracer.scene(&meshes)?; progress.done.store(0, Relaxed); - // Normal-map curvature needs a normal bake even when normal output is disabled + // Normal-map curvature needs a world normal bake even when that output is disabled let from_normal = settings.maps.curvature.parameters.method == CurvatureMethod::NormalMap && settings.maps.is_enabled(BakedMap::Curvature); let mut maps: Vec = settings.maps.enabled().collect(); - if from_normal && !maps.contains(&BakedMap::Normal) { - maps.push(BakedMap::Normal); + if from_normal && !maps.contains(&BakedMap::WorldNormal) { + maps.push(BakedMap::WorldNormal); } + let mut buffers = maps.iter().map(|map| alloc(width * height * map.components(), 0.0f32)).collect::, _>>()?; let mut covered = alloc(width * height, false)?; let mut padding_map = None; @@ -281,15 +282,18 @@ fn bake_in_strips( let mut output: BTreeMap> = maps.into_iter().zip(buffers).collect(); if from_normal { - let normal = if settings.maps.is_enabled(BakedMap::Normal) { output.get(&BakedMap::Normal).cloned() } else { output.remove(&BakedMap::Normal) }; - if let (Some(normal), Some(curvature_pixels)) = (normal, output.get_mut(&BakedMap::Curvature)) { + let world_normal = + if settings.maps.is_enabled(BakedMap::WorldNormal) { output.get(&BakedMap::WorldNormal).cloned() } else { output.remove(&BakedMap::WorldNormal) }; + if let (Some(world_normal), Some(curvature_pixels)) = (world_normal, output.get_mut(&BakedMap::Curvature)) { let parameters = settings.maps.curvature.parameters.normal_map; - map::curvature_from_normal(&normal, &covered, width, tile_size, parameters, curvature_pixels); + let grid = map::TexelGrid { covered: &covered, size: (width, height), tile_size }; + map::curvature_from_normal(&world_normal, request.mesh, request.material, &grid, parameters, curvature_pixels); if parameters.enable_seams { map::fix_seams(request.mesh, request.material, &covered, (width, height), parameters.seams_intensity, curvature_pixels); } } } + let (bounds_min, bounds_max) = request.mesh.bounds(); map::normalize(&mut output, &covered, width, tile_size, settings, (bounds_max - bounds_min).max_element().max(1e-6)); if let Some(padding_map) = padding_map { diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 9638a140..384d9d02 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -12,11 +12,13 @@ pub(crate) use seam::fix_seams; mod position_projection; mod sampling; mod source; +mod texel_grid; mod traced; mod transfer; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; diff --git a/crates/bake/src/map/normal_curvature.rs b/crates/bake/src/map/normal_curvature.rs index 2cc6bfc5..c96163c7 100644 --- a/crates/bake/src/map/normal_curvature.rs +++ b/crates/bake/src/map/normal_curvature.rs @@ -1,42 +1,120 @@ -/// Divergence of the tangent-space normal map; positive curvature is convex +use rayon::prelude::*; +use texturecraft_core::NormalMapCurvatureSettings; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; + +use super::TexelGrid; + +/// Output slope per unit of normal turn per texel at a 2048-texel tile and Details 0.5, set by eye on a hard-surface bake +const SLOPE_AT_2K: f32 = 3.0; + +/// How fast the baked world normal turns along the low poly's surface; positive curvature is convex pub(crate) fn curvature_from_normal( - normal: &[f32], - covered: &[bool], - width: usize, - tile_size: (usize, usize), - settings: texturecraft_core::NormalMapCurvatureSettings, + world_normal: &[f32], + mesh: &Mesh, + material: usize, + grid: &TexelGrid, + settings: NormalMapCurvatureSettings, output: &mut [f32], ) { - use rayon::prelude::*; - let radius_texels = (tile_size.0.min(tile_size.1) / 512).max(1); - let strength = 2.0f32.powf((settings.details - 0.5) * 4.0); - let normal_component = |x: usize, y: usize, component: usize, fallback: f32| match covered.get(y * width + x) { - Some(true) => normal.get((y * width + x) * 3 + component).copied().unwrap_or(fallback), - _ => fallback, + let TexelGrid { covered, size, tile_size } = *grid; + let triangle_of_texel = triangle_of_each_texel(mesh, material, grid); + let surface_directions = surface_direction_of_each_triangle(mesh, size); + let normal_at = |index: usize| { + let encoded = world_normal.get(index * 3..index * 3 + 3).and_then(|components| <[f32; 3]>::try_from(components).ok()).unwrap_or([0.5, 0.5, 1.0]); + Vec3::from_array(encoded) * 2.0 - 1.0 }; - output.par_chunks_mut(width).enumerate().for_each(|(y, row)| { + + // Turn of the normal per texel, measured along the surface direction each texel axis points to + let turn_along = |axis: usize| -> Vec { + (0..covered.len()) + .into_par_iter() + .map(|index| { + let Some(direction) = + triangle_of_texel.get(index).and_then(|triangle| surface_directions.get(*triangle as usize)).and_then(|pair| pair.get(axis).copied()) + else { + return 0.0; + }; + + let step = if axis == 0 { (1, 0) } else { (0, 1) }; + let forward = grid.neighbour(index, step.0, step.1); + let backward = grid.neighbour(index, -step.0, -step.1); + let change = match (forward, backward) { + (Some(ahead), Some(behind)) => (normal_at(ahead) - normal_at(behind)) * 0.5, + (Some(ahead), None) => normal_at(ahead) - normal_at(index), + (None, Some(behind)) => normal_at(index) - normal_at(behind), + (None, None) => Vec3::ZERO, + }; + change.dot(direction) + }) + .collect() + }; + let (turn_along_x, turn_along_y) = (turn_along(0), turn_along(1)); + + let slope = SLOPE_AT_2K * tile_size.0.min(tile_size.1) as f32 / 2048.0 * 2.0f32.powf((settings.details - 0.5) * 4.0); + output.par_chunks_mut(size.0).enumerate().for_each(|(y, row)| { for (x, value) in row.iter_mut().enumerate() { - if covered.get(y * width + x) != Some(&true) { + let index = y * size.0 + x; + if covered.get(index) != Some(&true) { continue; } - let (center_x, center_y) = (normal_component(x, y, 0, 0.5), normal_component(x, y, 1, 0.5)); - let (left, right) = ( - if x % tile_size.0 >= radius_texels { normal_component(x - radius_texels, y, 0, center_x) } else { center_x }, - if x % tile_size.0 + radius_texels < tile_size.0 && x + radius_texels < width { - normal_component(x + radius_texels, y, 0, center_x) - } else { - center_x - }, - ); - let (up, down) = ( - if y % tile_size.1 >= radius_texels { normal_component(x, y - radius_texels, 1, center_y) } else { center_y }, - if y % tile_size.1 + radius_texels < tile_size.1 && y + radius_texels < covered.len() / width.max(1) { - normal_component(x, y + radius_texels, 1, center_y) - } else { - center_y - }, - ); - *value = (0.5 + ((right - left) + (up - down)) * strength).clamp(0.0, 1.0); + + // A 1-2-1 average across each derivative keeps lines equally wide in every direction + let curvature = grid.average_along(&turn_along_x, index, (0, 1)) + grid.average_along(&turn_along_y, index, (1, 0)); + + // Rises at `slope` near flat and rolls off softly, so strong edges never clip into flat white + *value = 0.5 + 0.5 * (2.0 * slope * curvature).tanh(); } }); } + +/// Unit surface directions of a texel step in x and in y on each triangle of the low poly +fn surface_direction_of_each_triangle(mesh: &Mesh, size: (usize, usize)) -> Vec<[Vec3; 2]> { + let texel_scale = Vec2::new(size.0 as f32, size.1 as f32); + (0..mesh.indices.len() / 3) + .map(|triangle| { + let corner = |slot: usize| -> Option<(Vec3, Vec2)> { + let vertex = *mesh.tri(triangle)?.get(slot)?; + Some((*mesh.positions.get(vertex)?, *mesh.uvs.get(vertex)? * texel_scale)) + }; + let (Some((first_position, first_texel)), Some((second_position, second_texel)), Some((third_position, third_texel))) = + (corner(0), corner(1), corner(2)) + else { + return [Vec3::ZERO; 2]; + }; + + let (position_edge_1, position_edge_2) = (second_position - first_position, third_position - first_position); + let (texel_edge_1, texel_edge_2) = (second_texel - first_texel, third_texel - first_texel); + let determinant = texel_edge_1.perp_dot(texel_edge_2); + // A triangle with no UV area has no texel directions + if determinant.abs() < 1e-12 { + return [Vec3::ZERO; 2]; + } + + let along_x = (position_edge_1 * texel_edge_2.y - position_edge_2 * texel_edge_1.y) / determinant; + let along_y = (position_edge_2 * texel_edge_1.x - position_edge_1 * texel_edge_2.x) / determinant; + [along_x.normalize_or_zero(), along_y.normalize_or_zero()] + }) + .collect() +} + +/// Low-poly triangle under each covered texel; edge texels covered only by antialiasing borrow a neighbour's +fn triangle_of_each_texel(mesh: &Mesh, material: usize, grid: &TexelGrid) -> Vec { + let centres = UvGBuffer::new(mesh, material, grid.size.0 as u32, grid.size.1 as u32).tri; + (0..centres.len()) + .into_par_iter() + .map(|index| { + let own = centres.get(index).copied().unwrap_or(NO_TRI); + if own != NO_TRI || grid.covered.get(index) != Some(&true) { + return own; + } + + [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] + .into_iter() + .filter_map(|(step_x, step_y)| grid.neighbour(index, step_x, step_y)) + .map(|neighbour| centres.get(neighbour).copied().unwrap_or(NO_TRI)) + .find(|triangle| *triangle != NO_TRI) + .unwrap_or(NO_TRI) + }) + .collect() +} diff --git a/crates/bake/src/map/texel_grid.rs b/crates/bake/src/map/texel_grid.rs new file mode 100644 index 00000000..49e2b588 --- /dev/null +++ b/crates/bake/src/map/texel_grid.rs @@ -0,0 +1,32 @@ +/// Covered texels of a baked map, with UV tiles that neighbours never cross +#[derive(Clone, Copy)] +pub(crate) struct TexelGrid<'a> { + pub covered: &'a [bool], + pub size: (usize, usize), + pub tile_size: (usize, usize), +} + +impl TexelGrid<'_> { + /// The covered texel one step away in the same tile, if any + pub fn neighbour(&self, index: usize, step_x: isize, step_y: isize) -> Option { + let (width, height) = self.size; + let (x, y) = (index % width.max(1), index / width.max(1)); + let (next_x, next_y) = (x.checked_add_signed(step_x)?, y.checked_add_signed(step_y)?); + if next_x >= width || next_y >= height { + return None; + } + + let same_tile = next_x / self.tile_size.0.max(1) == x / self.tile_size.0.max(1) && next_y / self.tile_size.1.max(1) == y / self.tile_size.1.max(1); + let next = next_y * width + next_x; + (same_tile && self.covered.get(next) == Some(&true)).then_some(next) + } + + /// A 1-2-1 weighted average of `values` along `step`, over covered texels only + pub fn average_along(&self, values: &[f32], index: usize, step: (isize, isize)) -> f32 { + let centre = values.get(index).copied().unwrap_or(0.0); + let sides = [self.neighbour(index, step.0, step.1), self.neighbour(index, -step.0, -step.1)]; + let (sum, weight) = + sides.into_iter().flatten().fold((2.0 * centre, 2.0), |(sum, weight), side| (sum + values.get(side).copied().unwrap_or(0.0), weight + 1.0)); + sum / weight + } +} diff --git a/crates/bake/src/test/normal_map_curvature.rs b/crates/bake/src/test/normal_map_curvature.rs new file mode 100644 index 00000000..99ea078e --- /dev/null +++ b/crates/bake/src/test/normal_map_curvature.rs @@ -0,0 +1,84 @@ +use super::{bumped, covered_values, quad, quad_texel, settings, smooth_shaded_box, transfer}; +use texturecraft_core::{BakeSettings, BakedMap, CageSettings, CommonBakeSettings, CurvatureMethod, CurvatureSettings}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; + +fn normal_map_settings(resolution: u32) -> BakeSettings { + let mut base = settings(resolution, &[BakedMap::Curvature]); + base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; + base.common = CommonBakeSettings { dilation: 4, ..base.common }; + base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; + base.maps.curvature.parameters.normal_map.enable_seams = false; + base +} + +fn coordinates_beyond(position: Vec3, threshold: f32) -> usize { + position.abs().to_array().iter().filter(|coordinate| **coordinate > threshold).count() +} + +fn lowest_and_highest(values: impl IntoIterator) -> (f32, f32) { + values.into_iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lowest, highest), value| (lowest.min(value), highest.max(value))) +} + +#[test] +fn curvature_from_the_normal_map_sees_the_bump() { + let out = transfer(&quad(), &bumped(0.1, 0.12), None, &normal_map_settings(64)).unwrap(); + assert!(!out.maps.contains_key(&BakedMap::WorldNormal), "the helper world normal map is not returned"); + + let curvature = &out.maps[&BakedMap::Curvature]; + assert!(curvature[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", curvature[quad_texel(64, 0.0, 0.0)]); + assert!((curvature[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", curvature[quad_texel(64, 0.9, 0.9)]); +} + +#[test] +fn flat_faces_of_a_smooth_shaded_low_poly_stay_mid_grey() { + let low = smooth_shaded_box(); + let curvature = covered_values(&low, &transfer(&low, &primitives::cube(2.0), None, &normal_map_settings(256)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.7) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.02), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} + +#[test] +fn a_rounded_edge_is_one_convex_band() { + let bevel = 0.1; + let low = smooth_shaded_box(); + let curvature = + covered_values(&low, &transfer(&low, &primitives::rounded_box(Vec3::ONE, bevel), None, &normal_map_settings(512)).unwrap(), BakedMap::Curvature); + let across_one_edge = |from: f32, to: f32| { + curvature + .iter() + .filter(move |(position, _)| (position.x - 1.0).abs() < 1e-3 && position.z.abs() < 0.3 && (from..to).contains(&position.y)) + .map(|(_, value)| *value) + }; + + let inside_the_bevel = across_one_edge(1.0 - bevel * 0.8, 0.99).fold(1.0f32, f32::min); + let next_to_the_bevel = lowest_and_highest(across_one_edge(0.5, 1.0 - bevel * 1.5)); + assert!(inside_the_bevel > 0.55, "the band dips inside the bevel: {inside_the_bevel}"); + assert!(next_to_the_bevel.0 > 0.48 && next_to_the_bevel.1 < 0.52, "next to the bevel {next_to_the_bevel:?}"); +} + +#[test] +fn a_small_bump_has_no_ring_beyond_its_skirt() { + let (resolution, sigma) = (512, 0.08); + let out = transfer(&quad(), &bumped(0.08, sigma), None, &normal_map_settings(resolution)).unwrap(); + let curvature = &out.maps[&BakedMap::Curvature]; + let ring: Vec = (0..64) + .map(|step| step as f32 / 64.0 * std::f32::consts::TAU) + .flat_map(|angle| [3.0f32, 4.0].map(|radius| curvature[quad_texel(resolution, radius * sigma * angle.cos(), radius * sigma * angle.sin())])) + .collect(); + + assert!(curvature[quad_texel(resolution, 0.0, 0.0)] > 0.6, "convex top {}", curvature[quad_texel(resolution, 0.0, 0.0)]); + assert!(ring.iter().all(|value| (value - 0.5).abs() < 0.02), "ring {:?}", lowest_and_highest(ring.iter().copied())); +} + +#[test] +fn island_borders_of_flat_faces_do_not_streak() { + let cube = primitives::cube(2.0); + let curvature = covered_values(&cube, &transfer(&cube, &cube, None, &normal_map_settings(128)).unwrap(), BakedMap::Curvature); + let faces: Vec = curvature.iter().filter(|(position, _)| coordinates_beyond(*position, 0.97) == 1).map(|(_, value)| *value).collect(); + + assert!(!faces.is_empty()); + assert!(faces.iter().all(|value| (value - 0.5).abs() < 0.01), "face range {:?}", lowest_and_highest(faces.iter().copied())); +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index bb75353e..4cd074cc 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -17,6 +17,9 @@ use super::*; #[path = "test/setting.rs"] mod setting; +#[path = "test/normal_map_curvature.rs"] +mod normal_map_curvature; + #[path = "test/tile_selection.rs"] mod tile_selection; @@ -638,21 +641,6 @@ fn bump_tilts_the_baked_normal() { assert!(height[quad_texel(64, 0.0, 0.0)] > height[quad_texel(64, 0.6, 0.6)] + 0.2, "the bump top is higher"); } -#[test] -fn curvature_from_the_normal_map_sees_the_bump() { - let s = { - let mut base = settings(64, &[BakedMap::Curvature]); - base.cage = CageSettings { max_frontal: 0.06, max_rear: 0.02, ..base.cage }; - base.maps.curvature.parameters = CurvatureSettings { method: CurvatureMethod::NormalMap, ..base.maps.curvature.parameters }; - base - }; - let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap(); - assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned"); - let c = &out.maps[&BakedMap::Curvature]; - assert!(c[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", c[quad_texel(64, 0.0, 0.0)]); - assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]); -} - #[test] fn bent_normals_point_away_from_occluders() { let mut m = quad(); From 3a6a160d335ddec437cdcdb3d395eb9e47fdc0dd Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 02:55:59 +0000 Subject: [PATCH 059/275] Right-click in a view opens the Properties panel's contents at the cursor A plain right click in the 3D or 2D view (no drag, no Ctrl/Alt/Shift) opens what the Properties panel shows in a popup at the cursor; a click outside, Escape or leaving Painting closes it, and the closing click doesn't paint. Every right-drag gesture is unchanged. Closes #149 --- crates/ui-egui/src/dock.rs | 29 +- crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/src/menus.rs | 13 +- crates/ui-egui/src/properties_popup.rs | 79 +++++ crates/ui-egui/src/toolbar.rs | 9 +- crates/ui-egui/src/viewport.rs | 425 +++++++++++++---------- crates/ui-egui/tests/properties_popup.rs | 167 +++++++++ 7 files changed, 531 insertions(+), 195 deletions(-) create mode 100644 crates/ui-egui/src/properties_popup.rs create mode 100644 crates/ui-egui/tests/properties_popup.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 4d5a1d06..87e9d84b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -924,23 +924,28 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let sel = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); - let target = app.session.target; - egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| match (&sel, target) { - (Some(l), StackTarget::Effect(e)) => effect_properties(app, ui, l, e), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => fill_properties(app, ui, l), - (Some(l), StackTarget::Content) if l.is_group() => { - ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tk.text_dim)); + egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); +} + +/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool +pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); + + match (&selected, app.session.target) { + (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), + (Some(layer), StackTarget::Content) if layer.is_group() => { + ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); } - (Some(l), StackTarget::Content) if l.instance_source().is_some() => instance_properties(app, ui, l), - (Some(l), StackTarget::Mask) => { - height_mask_section(app, ui, l); + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => instance_properties(app, ui, layer), + (Some(layer), StackTarget::Mask) => { + height_mask_section(app, ui, layer); ui.separator(); tool_properties(app, ui); } _ => tool_properties(app, ui), - }); + } } /// An instance draws its source: point there for edits. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..5b5045e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -24,6 +24,7 @@ mod preview_image; mod preview_request; mod preview_worker; pub mod profile; +pub mod properties_popup; pub mod render_mode; pub mod shelf; pub mod shelf_preview; @@ -111,6 +112,8 @@ pub struct TextureCraftApp { pub last_paint_point: Option, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, + /// The Properties popup a right click in a view opens. + pub properties_popup: Option, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -164,6 +167,7 @@ impl TextureCraftApp { render: render_mode::RenderView::default(), last_paint_point: None, placing_decal: None, + properties_popup: None, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7890d436..b74aa300 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -9,6 +9,7 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::state::{Mode, ViewLayout}; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; /// One menu entry. `label == "-"` is a separator; `sub` names a submenu group. #[derive(Clone, Copy, Debug)] @@ -305,7 +306,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { - if crate::keymap::capturing(ctx) || (ctx.memory(|m| m.focused().is_some()) && ctx.egui_wants_keyboard_input()) { + if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } @@ -327,14 +328,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } } + // [ and ] shrink and grow the brush by this factor per press + const BRACKET_SIZE_STEP: f32 = 1.15; let size_down = input.consume_key(Modifiers::NONE, Key::OpenBracket); let size_up = input.consume_key(Modifiers::NONE, Key::CloseBracket); if app.ui.mode == Mode::Painting && (size_down || size_up) { - let scale = if size_up { 1.15 } else { 1.0 / 1.15 }; - app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(0.0005, 0.25); + let scale = if size_up { BRACKET_SIZE_STEP } else { 1.0 / BRACKET_SIZE_STEP }; + app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.properties_popup = None; + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs new file mode 100644 index 00000000..5c174cdd --- /dev/null +++ b/crates/ui-egui/src/properties_popup.rs @@ -0,0 +1,79 @@ +//! The Properties panel's contents in a popup at the cursor: a right click in the 3D or 2D view opens it + +use egui::{PointerButton, Pos2, Rect, Ui}; + +use crate::TextureCraftApp; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The popup's width, about the docked Properties panel's +const PROPERTIES_POPUP_WIDTH: f32 = 300.0; + +/// Share of the view's height the popup fills before its contents scroll +const PROPERTIES_POPUP_MAX_HEIGHT_SHARE: f32 = 0.7; + +/// Gap the popup keeps from the view's edges, so its border stays visible beside a split line +const PROPERTIES_POPUP_VIEW_MARGIN: f32 = 4.0; + +/// The Properties popup over a view +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum PropertiesPopup { + /// Shown with its top-left corner at `at`, kept inside the view `bounds` + Open { at: Pos2, bounds: Rect }, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + Closing, +} + +/// The popup's area, whose rect egui remembers between frames +pub fn area_id() -> egui::Id { + egui::Id::unique("properties_popup") +} + +/// Opens the popup on a plain right click in a view; right drags and modified clicks keep their gestures +pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, view: Rect, gesture_key_held: bool) { + let free = app.ui.mode == Mode::Painting + && app.properties_popup.is_none() + && !app.session.stroke_active() + && app.placing_decal.is_none() + && !gesture_key_held + && !crate::viewport::focus_picking(ui.ctx()) + && ui.input(|input| input.modifiers.is_none()); + if !free || !response.clicked_by(PointerButton::Secondary) { + return; + } + + if let Some(at) = response.interact_pointer_pos() { + app.properties_popup = Some(PropertiesPopup::Open { at, bounds: view }); + } +} + +/// Draws the open popup and closes it on a press outside it or when the app leaves Painting +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()))); + match app.properties_popup { + _ if app.ui.mode != Mode::Painting => app.properties_popup = None, + Some(PropertiesPopup::Closing) if !any_down => app.properties_popup = None, + Some(PropertiesPopup::Open { .. }) => { + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))); + // A press in one of the popup's own dropdowns lands outside its area + if outside && !egui::Popup::is_any_open(ctx) { + app.properties_popup = Some(PropertiesPopup::Closing); + } + } + _ => {} + } + + let Some(PropertiesPopup::Open { at, bounds }) = app.properties_popup else { return }; + let tokens = Tokens::get(ctx); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds.shrink(PROPERTIES_POPUP_VIEW_MARGIN)).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).show(ui, |ui| { + ui.set_width(PROPERTIES_POPUP_WIDTH); + // The area's remembered size would otherwise cap the scroll height + ui.set_max_height(bounds.height() * PROPERTIES_POPUP_MAX_HEIGHT_SHARE); + // A floating bar would cover the sliders' right-aligned values + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); + egui::ScrollArea::vertical().id_salt("properties_popup_scroll").show(ui, |ui| crate::dock::properties_contents(app, ui)); + }); + }); +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 897d305f..eee357f7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -202,11 +202,14 @@ fn scrolling_tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: }); } +/// Largest brush radius as a fraction of the mesh diagonal; size sliders show it as 100 +pub(crate) const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Smallest brush radius as a fraction of the mesh diagonal +pub(crate) const MIN_BRUSH_SIZE: f32 = 0.0005; + /// The selected tool's icon and its settings fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) { - // Brush radius limits as a fraction of the mesh diagonal; the slider shows the maximum as 100 - const MAX_BRUSH_SIZE: f32 = 0.25; - const MIN_BRUSH_SIZE: f32 = 0.0005; const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4ebe79b3..f20210d4 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -4,10 +4,10 @@ use std::sync::Mutex; use egui::emath::GuiRounding as _; -use egui::{Color32, PointerButton, Pos2, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; +use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; use texturecraft_engine::{Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; @@ -17,6 +17,7 @@ use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; use crate::theme::Tokens; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -51,13 +52,13 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } let tokens = Tokens::get(ui.ctx()); - let aux = match app.session.view { + let aux_view = match app.session.view { _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ => None, }; - let mut sync = PendingSync(Some(aux)); + let mut sync = PendingSync(Some(aux_view)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); @@ -86,6 +87,8 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } } + crate::properties_popup::show(app, ui.ctx()); + if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); } else if app.render.is_active() { @@ -159,6 +162,9 @@ const UV_VIEW_MIN_ZOOM: f32 = 0.1; /// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) const UV_VIEW_MAX_ZOOM: f32 = 40.0; +/// UV zoom change per point of mouse wheel, as a fraction of the zoom +const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -407,119 +413,157 @@ fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { } } +/// Camera turn per point of a drag (radians) +const ORBIT_RADIANS_PER_POINT: f32 = 0.008; + +/// Camera zoom per point of an Alt+right drag +const DRAG_ZOOM_PER_POINT: f32 = 0.01; + +/// Camera zoom per point of mouse wheel +const WHEEL_ZOOM_PER_POINT: f32 = 0.0025; + +/// Environment light turn per point of a Shift+right drag (degrees) +const LIGHT_DEGREES_PER_POINT: f32 = 0.5; + +/// Brush size change per point of Shift+wheel, as a fraction of the size +const WHEEL_BRUSH_SIZE_PER_POINT: f32 = 0.002; + +/// Stencil turn per point of an S+left drag (degrees) +const STENCIL_DEGREES_PER_POINT: f32 = 0.4; + +/// Stencil scale change per point of an S+right drag, as a fraction of the scale +const STENCIL_SCALE_PER_POINT: f32 = 0.005; + +/// Smallest stencil scale an S+right drag reaches +const MIN_STENCIL_SCALE: f32 = 0.05; + +/// Largest stencil scale an S+right drag reaches +const MAX_STENCIL_SCALE: f32 = 10.0; + +/// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points) +const MIN_CAMERA_VIEWPORT: f32 = 16.0; + fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let resp = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); - app.session.viewport = Vec2::new(size.x.max(16.0), size.y.max(16.0)); - let (alt, shift) = ui.input(|i| (i.modifiers.alt, i.modifiers.shift)); - let local = |p: egui::Pos2| Vec2::new(p.x - rect.left(), p.y - rect.top()); - let adjusting = brush_drag(app, ui, &resp); - let navigating = !adjusting && (alt || ui.input(|i| i.pointer.middle_down() || i.pointer.secondary_down())); + app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); + let adjusting = brush_drag(app, ui, &response); + let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation (S + drag manipulates the projection stencil instead, below). - let delta = ui.input(|i| i.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|i| i.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); + // Navigation; S + drag moves the projection stencil instead, below + let delta = ui.input(|input| input.pointer.delta()); + let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); let stencil_drag = s_held && app.session.tool.stencil.is_some(); if stencil_drag || adjusting { - // The stencil moves, turns and scales instead of the camera (handled below), or the - // brush changes. - } else if resp.dragged_by(PointerButton::Middle) { + // The stencil or the brush changes instead of the camera + } else if response.dragged_by(PointerButton::Middle) { app.session.camera.pan(delta.x / size.y, delta.y / size.y); - } else if alt && resp.dragged_by(PointerButton::Primary) { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); - } else if resp.dragged_by(PointerButton::Secondary) { + } else if alt && response.dragged_by(PointerButton::Primary) { + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + } else if response.dragged_by(PointerButton::Secondary) { if alt { - app.session.camera.zoom(-delta.y * 0.01); + app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); } else if shift { - // Shift + right drag turns the environment light. - let d = &mut app.session.doc.project.display; - d.env_rotation = (d.env_rotation + delta.x * 0.5).rem_euclid(360.0); + let display = &mut app.session.doc.project.display; + display.env_rotation = (display.env_rotation + delta.x * LIGHT_DEGREES_PER_POINT).rem_euclid(360.0); } else { - app.session.camera.orbit(delta.x * 0.008, delta.y * 0.008); + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); } } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { if shift && app.ui.mode == crate::state::Mode::Painting { let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * 0.002)).clamp(0.0005, 0.25); + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } else { - app.session.camera.zoom(scroll * 0.0025); + app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } } } - // Touch screens: two fingers orbit and pinch zooms, three fingers pan. A second finger - // cancels the stroke the first one started, so navigating leaves no paint behind. - let touch = ui.input(|i| i.multi_touch()).filter(|_| resp.contains_pointer() || resp.dragged()); - if let Some(t) = touch { + // Touch: two fingers orbit and pinch zooms, three pan; a second finger cancels the first one's stroke + let touch = ui.input(|input| input.multi_touch()).filter(|_| response.contains_pointer() || response.dragged()); + if let Some(gesture) = touch { if app.session.stroke_active() { app.session.cancel_stroke(); } - let d = t.translation_delta; - if t.num_touches >= 3 { - app.session.camera.pan(d.x / size.y, d.y / size.y); + + let moved = gesture.translation_delta; + if gesture.num_touches >= 3 { + app.session.camera.pan(moved.x / size.y, moved.y / size.y); } else { - app.session.camera.orbit(d.x * 0.008, d.y * 0.008); + app.session.camera.orbit(moved.x * ORBIT_RADIANS_PER_POINT, moved.y * ORBIT_RADIANS_PER_POINT); } - if t.zoom_delta.is_finite() && t.zoom_delta > 0.0 { - app.session.camera.zoom(t.zoom_delta.ln()); + if gesture.zoom_delta.is_finite() && gesture.zoom_delta > 0.0 { + app.session.camera.zoom(gesture.zoom_delta.ln()); } } - // Stencil: S + left drag rotates, S + right drag scales, S + middle drag moves. - if s_held && let Some(st) = app.session.tool.stencil.as_mut() { - if resp.dragged_by(PointerButton::Primary) { - st.rotation = (st.rotation + delta.x * 0.4).rem_euclid(360.0); - } else if resp.dragged_by(PointerButton::Secondary) { - st.scale = (st.scale * (1.0 + delta.x * 0.005)).clamp(0.05, 10.0); - } else if resp.dragged_by(PointerButton::Middle) { - st.center[0] += delta.x / size.x * 2.0; - st.center[1] -= delta.y / size.y * 2.0; + // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it + if s_held && let Some(stencil) = app.session.tool.stencil.as_mut() { + if response.dragged_by(PointerButton::Primary) { + stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); + } else if response.dragged_by(PointerButton::Secondary) { + stencil.scale = (stencil.scale * (1.0 + delta.x * STENCIL_SCALE_PER_POINT)).clamp(MIN_STENCIL_SCALE, MAX_STENCIL_SCALE); + } else if response.dragged_by(PointerButton::Middle) { + stencil.center[0] += delta.x / size.x * 2.0; + stencil.center[1] -= delta.y / size.y * 2.0; } } - // Clone source: V + click. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held && !alt - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("tool.cloneSource", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } - // Depth of field focus pick: a click focuses there instead of painting. + + // Depth of field focus pick: a click focuses there instead of painting let focus_pick = focus_picking(ui.ctx()); if focus_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("viewport.focusAt", json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("viewport.focusAt", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); set_focus_picking(ui.ctx(), false); } } - // Decal placement: a click moves the decal being placed there. + + // Decal placement: a click moves the decal being placed there let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt - && resp.clicked_by(PointerButton::Primary) - && let Some(p) = resp.interact_pointer_pos() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() { - let (q, vp) = (local(p), app.session.viewport); - app.run("layer.decal.set", json!({"layer": layer.0, "x": q.x, "y": q.y, "viewport": [vp.x, vp.y]})); + let (at, viewport) = (local(pointer), app.session.viewport); + app.run("layer.decal.set", json!({"layer": layer.0, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); app.placing_decal = None; } } - // The selected decal's frame and handles: drag to move, scale or turn it. - let decal_drag = !alt && !s_held && !v_held && !focus_pick && placing.is_none() && touch.is_none() && decal_input(app, ui, &resp, rect); - // Painting. + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + let popup = app.properties_popup.is_some(); + + // The selected decal's frame and handles: drag to move, scale or turn it + let decal_drag = !alt && !s_held && !v_held && !focus_pick && !popup && placing.is_none() && touch.is_none() && decal_input(app, ui, &response, rect); + + // Painting let painting = app.ui.mode == crate::state::Mode::Painting + && !popup && !alt && !adjusting && !s_held @@ -529,42 +573,42 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && touch.is_none() && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; - let vp = app.session.viewport; - let show = |app: &TextureCraftApp, p: Vec3| project(app, rect, p); + let viewport = app.session.viewport; + let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); if painting && path_tool { - path_input(app, ui, &resp, false, |app, p| app.session.pick(local(p), vp).map(|h| h.pos), show); + path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); } else if painting { let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - // Shift+click paints a straight line from where the last stroke ended. + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + // Shift+click paints a straight line from where the last stroke ended let line_from = if shift { app.last_paint_point } else { None }; - if let Some(p) = resp.interact_pointer_pos() { - match app.session.begin_stroke(line_from.unwrap_or(local(p)), app.session.viewport, pressure) { + if let Some(pointer) = response.interact_pointer_pos() { + match app.session.begin_stroke(line_from.unwrap_or(local(pointer)), app.session.viewport, pressure) { Ok(_) => { if line_from.is_some() { - app.session.continue_stroke(local(p), pressure); + app.session.continue_stroke(local(pointer), pressure); } - app.last_paint_point = Some(local(p)); + app.last_paint_point = Some(local(pointer)); } - Err(e) => app.toast(e.to_string(), true), + Err(error) => app.toast(error.to_string(), true), } } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.clicked_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - } else if resp.dragged_by(PointerButton::Primary) + } else if response.dragged_by(PointerButton::Primary) && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() + && let Some(pointer) = response.interact_pointer_pos() { - app.session.continue_stroke(local(p), pressure); - app.last_paint_point = Some(local(p)); + app.session.continue_stroke(local(pointer), pressure); + app.last_paint_point = Some(local(pointer)); } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.drag_stopped_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } } @@ -573,43 +617,45 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &resp), ..shade(app) }, - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View3d); - // Brush cursor. + // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); + + // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began if app.ui.mode == crate::state::Mode::Painting && !navigating - && resp.hovered() + && response.hovered() && brush_tool(app.session.tool.tool) - // While a Ctrl+drag changes the brush, its cursor stays where the drag began. - && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { resp.hover_pos() } - && let Some(hit) = app.session.pick(local(hp), app.session.viewport) + && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } + && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor(app, ui, rect, hit.pos, hit.nrm); if app.session.tool.tool == Tool::Clone - && let Some(src) = app.session.clone_source_point(Some(hit.uv)) + && let Some(source) = app.session.clone_source_point(Some(hit.uv)) { - clone_marker(app, ui, rect, src); + clone_marker(app, ui, rect, source); } - // Shift: preview the straight line Shift+click paints from the last stroke. + + // Shift: preview the straight line Shift+click paints from the last stroke if shift && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hp); + rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); } } + if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, false, show); + path_overlay(app, ui, rect, &response, false, show); } stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); - brush_readout(app, ui, &resp, adjusting); + brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( rect.left_top() + vec2(12.0, 40.0), @@ -1021,15 +1067,23 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjustin p.galley(r.min + vec2(6.0, 3.0), g, tk.text_strong); } -/// Brush change for a Ctrl+drag by `d` points: `right` sets the size (x) and hardness (y), else -/// the flow (x) and angle (y); dragging up raises hardness and angle. -fn adjust_brush(b: &mut texturecraft_engine::paint::BrushSettings, right: bool, d: egui::Vec2) { +/// Size fraction, hardness and flow change per point of a Ctrl+drag +const CTRL_DRAG_RATE_PER_POINT: f32 = 0.005; + +/// Brush angle change per point of a Ctrl+left drag (degrees) +const CTRL_DRAG_DEGREES_PER_POINT: f32 = 0.5; + +/// Highest hardness a Ctrl+right drag sets +const CTRL_DRAG_MAX_HARDNESS: f32 = 0.999; + +/// Brush change for a Ctrl+drag by `drag` points: a right drag sets the size (x) and hardness (y), a left drag the flow (x) and angle (y); up raises hardness and angle +fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bool, drag: egui::Vec2) { if right { - b.size = (b.size * (1.0 + d.x * 0.005)).clamp(0.0005, 0.25); - b.hardness = (b.hardness - d.y * 0.005).clamp(0.0, 0.999); + brush.size = (brush.size * (1.0 + drag.x * CTRL_DRAG_RATE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + brush.hardness = (brush.hardness - drag.y * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, CTRL_DRAG_MAX_HARDNESS); } else { - b.flow = (b.flow + d.x * 0.005).clamp(0.0, 1.0); - b.angle = (b.angle - d.y * 0.5 + 180.0).rem_euclid(360.0) - 180.0; + brush.flow = (brush.flow + drag.x * CTRL_DRAG_RATE_PER_POINT).clamp(0.0, 1.0); + brush.angle = (brush.angle - drag.y * CTRL_DRAG_DEGREES_PER_POINT + 180.0).rem_euclid(360.0) - 180.0; } } @@ -1095,136 +1149,155 @@ fn pen_pressure(ui: &Ui) -> f32 { } fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); - let resp = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|i| i.modifiers.alt); - let adjusting = brush_drag(app, ui, &resp); - let delta = ui.input(|i| i.pointer.delta()); - if resp.dragged_by(PointerButton::Middle) || (alt && resp.dragged_by(PointerButton::Primary)) { + let alt = ui.input(|input| input.modifiers.alt); + let adjusting = brush_drag(app, ui, &response); + + // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor + let delta = ui.input(|input| input.pointer.delta()); + if response.dragged_by(PointerButton::Middle) || (alt && response.dragged_by(PointerButton::Primary)) { app.ui.uv_pan[0] += delta.x / size.x * 2.0; app.ui.uv_pan[1] -= delta.y / size.y * 2.0; } - if resp.hovered() { - let scroll = ui.input(|i| i.smooth_scroll_delta.y); + if response.hovered() { + let scroll = ui.input(|input| input.smooth_scroll_delta.y); if scroll != 0.0 { - let old = app.ui.uv_zoom; - let new = (old * (1.0 + scroll * 0.002)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); - // Zoom about the cursor. - if let Some(hp) = resp.hover_pos() { - let c = [(hp.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hp.y - rect.top()) / size.y * 2.0]; - for k in 0..2 { - app.ui.uv_pan[k] = c[k] - (c[k] - app.ui.uv_pan[k]) * new / old; + let old_zoom = app.ui.uv_zoom; + let new_zoom = (old_zoom * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); + if let Some(hover_pos) = response.hover_pos() { + let cursor = [(hover_pos.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hover_pos.y - rect.top()) / size.y * 2.0]; + for axis in 0..2 { + app.ui.uv_pan[axis] = cursor[axis] - (cursor[axis] - app.ui.uv_pan[axis]) * new_zoom / old_zoom; } } - app.ui.uv_zoom = new; + app.ui.uv_zoom = new_zoom; } } + + // Conversions between the view's points and the texture set's UV space let ts = app.session.ts(); let set = app.session.doc.project.texture_sets.get(ts); - let [sx, sy] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |t| t.size())); + let [scale_x, scale_y] = texturecraft_render::uv_view_scale(size.x / size.y.max(1.0), app.ui.uv_zoom, set.map_or((1, 1), |texture_set| texture_set.size())); let pan = app.ui.uv_pan; - let to_uv = |p: egui::Pos2| { - let xc = (p.x - rect.left()) / size.x * 2.0 - 1.0; - let yc = 1.0 - (p.y - rect.top()) / size.y * 2.0; - Vec2::new(((xc - pan[0]) / sx + 1.0) * 0.5, (1.0 - (yc - pan[1]) / sy) * 0.5) + let to_uv = |pointer: egui::Pos2| { + let clip_x = (pointer.x - rect.left()) / size.x * 2.0 - 1.0; + let clip_y = 1.0 - (pointer.y - rect.top()) / size.y * 2.0; + Vec2::new(((clip_x - pan[0]) / scale_x + 1.0) * 0.5, (1.0 - (clip_y - pan[1]) / scale_y) * 0.5) }; - let to = |u: f32, v: f32| { - let x = (u * 2.0 - 1.0) * sx + pan[0]; - let y = (1.0 - v * 2.0) * sy + pan[1]; - pos2(rect.left() + (x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - y * 0.5) * size.y) + let to_screen = |u: f32, v: f32| { + let clip_x = (u * 2.0 - 1.0) * scale_x + pan[0]; + let clip_y = (1.0 - v * 2.0) * scale_y + pan[1]; + pos2(rect.left() + (clip_x * 0.5 + 0.5) * size.x, rect.top() + (0.5 - clip_y * 0.5) * size.y) }; - let show = |_: &TextureCraftApp, p: Vec3| Some(to(p.x, p.y)); + let show = |_: &TextureCraftApp, point: Vec3| Some(to_screen(point.x, point.y)); let path_tool = app.session.tool.tool == Tool::Path; - // Clone source (V + click) and painting in UV space. + + // Clone source: V + click let v_held = clone_source_key(app, ui); if v_held - && (resp.clicked_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) - && let Some(p) = resp.interact_pointer_pos() + && (response.clicked_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary)) + && let Some(pointer) = response.interact_pointer_pos() { - let uv = to_uv(p); + let uv = to_uv(pointer); app.run("tool.cloneSource", json!({"uv": [uv.x, uv.y]})); } + let bake_paint_on = app.ui.mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on && !alt; if bake_paint_on { - bake_paint_input(app, ui, &resp, &to_uv); + bake_paint_input(app, ui, &response, &to_uv); } - let painting = app.ui.mode == crate::state::Mode::Painting && !alt && !adjusting && !v_held; + + crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); + + // Painting in UV space + let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; if painting && path_tool { - path_input(app, ui, &resp, true, |_, p| Some(to_uv(p).extend(0.0)), show); + path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { let pressure = pen_pressure(ui); - if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { - if let Some(p) = resp.interact_pointer_pos() - && let Err(e) = app.session.begin_stroke_uv(to_uv(p), pressure) + if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { + if let Some(pointer) = response.interact_pointer_pos() + && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - if resp.clicked_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.clicked_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } - } else if resp.dragged_by(PointerButton::Primary) + } else if response.dragged_by(PointerButton::Primary) && app.session.stroke_active() - && let Some(p) = resp.interact_pointer_pos() + && let Some(pointer) = response.interact_pointer_pos() { - app.session.continue_stroke_uv(to_uv(p), pressure); + app.session.continue_stroke_uv(to_uv(pointer), pressure); } - if resp.drag_stopped_by(PointerButton::Primary) - && let Err(e) = app.session.end_stroke() + if response.drag_stopped_by(PointerButton::Primary) + && let Err(error) = app.session.end_stroke() { - app.toast(e.to_string(), true); + app.toast(error.to_string(), true); } } - if resp.double_clicked() && !(painting && path_tool) { + if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; app.ui.uv_pan = [0.0, 0.0]; } + let frame = Frame { view_id: VIEW_2D, size: frame_size_in_pixels(ui, rect), kind: ViewKind::Uv { ts, zoom: app.ui.uv_zoom, pan: app.ui.uv_pan }, camera: app.session.camera, shade: shade(app), - visible: app.session.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); - crate::shelf::drop_target(app, ui, &resp, crate::shelf::DropZone::View2d); - // The UV tile outlines (numbered for UDIM sets) and the path being edited. + crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); + + // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |r: Rect| painter.rect_stroke(r, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); - match set.and_then(|t| Some((t, t.tile_grid()?))) { - Some((t, g)) => { - for (udim, (bx, by)) in t.uv_tiles.iter().filter_map(|u| Some((*u, g.block(*u)?))) { - // A tile smaller than its block fills the block's top-left corner. - let (u0, v0, k) = (bx as f32 / g.cols as f32, by as f32 / g.rows as f32, t.tile_scale(udim)); - let r = Rect::from_two_pos(to(u0, v0), to(u0 + k / g.cols as f32, v0 + k / g.rows as f32)); - outline(r); - painter.text(r.left_top() + vec2(6.0, 4.0), egui::Align2::LEFT_TOP, udim.to_string(), egui::FontId::proportional(11.0), tk.viewport_text); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { + Some((texture_set, grid)) => { + for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { + // A tile smaller than its block fills the block's top-left corner + let (u0, v0) = (block_x as f32 / grid.cols as f32, block_y as f32 / grid.rows as f32); + let tile_scale = texture_set.tile_scale(udim); + let tile = Rect::from_two_pos(to_screen(u0, v0), to_screen(u0 + tile_scale / grid.cols as f32, v0 + tile_scale / grid.rows as f32)); + outline(tile); + painter.text( + tile.left_top() + vec2(6.0, 4.0), + egui::Align2::LEFT_TOP, + udim.to_string(), + egui::FontId::proportional(11.0), + tokens.viewport_text, + ); } } None => { - outline(Rect::from_two_pos(to(0.0, 0.0), to(1.0, 1.0))); + outline(Rect::from_two_pos(to_screen(0.0, 0.0), to_screen(1.0, 1.0))); } } if app.ui.mode == crate::state::Mode::Painting && path_tool { - path_overlay(app, ui, rect, &resp, true, show); + path_overlay(app, ui, rect, &response, true, show); } + if app.ui.mode == crate::state::Mode::Baking { - bake_paint_overlay(app, ui, &painter, to(0.0, 1.0), to(1.0, 0.0)); - if bake_paint_on && let Some(hover) = resp.hover_pos() { - let r = (to(app.ui.bake_paint_brush.radius, 0.0).x - to(0.0, 0.0).x).abs().max(2.0); - painter.circle_stroke(hover, r, Stroke::new(1.0, Color32::from_white_alpha(200))); + bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); + if bake_paint_on && let Some(hover) = response.hover_pos() { + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } - brush_readout(app, ui, &resp, adjusting); + + brush_readout(app, ui, &response, adjusting); view_header(app, ui, rect, "v2d"); axis_gizmo(ui, rect, app, true); - let name = app.session.doc.project.texture_sets.get(ts).map(|t| t.name.clone()).unwrap_or_default(); - ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tk.viewport_text); - let _ = (RichText::new(""), Channel::BaseColor); + let name = app.session.doc.project.texture_sets.get(ts).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); + ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). diff --git a/crates/ui-egui/tests/properties_popup.rs b/crates/ui-egui/tests/properties_popup.rs new file mode 100644 index 00000000..8d3b413f --- /dev/null +++ b/crates/ui-egui/tests/properties_popup.rs @@ -0,0 +1,167 @@ +//! A plain right click in a view opens the Properties panel's contents at the cursor; right drags keep their gestures + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerKind; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +fn view_center(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + harness.state().viewport_rect.center() +} + +fn is_open(harness: &Harness<'_, TextureCraftApp>) -> bool { + matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { .. })) +} + +/// Press and release `button` at `at` without moving +fn click(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, at: Pos2) { + harness.hover_at(at); + harness.event(Event::PointerButton { pos: at, button, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Drag with `button` from `from` by `by` in a few moves while `modifiers` are held +fn drag(harness: &mut Harness<'_, TextureCraftApp>, button: PointerButton, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); +} + +#[test] +fn a_right_click_opens_the_popup_at_the_cursor_in_both_views() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(matches!(harness.state().properties_popup, Some(PropertiesPopup::Open { at, .. }) if at == center)); + + harness.key_press(Key::Escape); + harness.run_steps(2); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(2); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness), "the 2D view opens it too"); +} + +#[test] +fn right_drags_keep_their_gestures_and_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + let yaw = harness.state().session.camera.yaw; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::NONE); + assert_ne!(harness.state().session.camera.yaw, yaw, "a right drag orbits"); + assert!(!is_open(&harness), "an orbit doesn't open it"); + + let size = harness.state().session.tool.brush.size; + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), Modifiers::COMMAND); + assert!(harness.state().session.tool.brush.size > size, "Ctrl+right drag sets the brush"); + assert!(!is_open(&harness)); + + for modifiers in [Modifiers::ALT, Modifiers::SHIFT] { + drag(&mut harness, PointerButton::Secondary, center, vec2(80.0, -40.0), modifiers); + assert!(!is_open(&harness), "{modifiers:?}"); + } +} + +#[test] +fn a_click_outside_closes_it_without_painting() { + let mut harness = harness(); + let center = view_center(&harness); + let outside = harness.state().viewport_rect.left_center() + vec2(20.0, 0.0); + let history = harness.state().session.history_labels().len(); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + + click(&mut harness, PointerButton::Primary, outside); + assert_eq!(harness.state().properties_popup, None); + assert_eq!(harness.state().session.history_labels().len(), history, "the closing click doesn't paint"); + + click(&mut harness, PointerButton::Secondary, center); + click(&mut harness, PointerButton::Secondary, outside); + assert_eq!(harness.state().properties_popup, None, "a right click outside closes it and doesn't reopen it"); +} + +#[test] +fn escape_closes_it() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + harness.key_press(Key::Escape); + harness.run_steps(2); + assert_eq!(harness.state().properties_popup, None); +} + +#[test] +fn dragging_its_size_slider_changes_the_brush() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + + // The Size section's header sits above its slider of the same name + let slider_label = harness + .query_all_by_label("Size") + .map(|node| node.rect()) + .filter(|rect| popup.contains_rect(*rect)) + .max_by(|first, second| first.top().total_cmp(&second.top())) + .unwrap(); + let track_y = slider_label.bottom() + 10.0; + let size = harness.state().session.tool.brush.size; + harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); + harness.run_steps(3); + assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); + assert!(is_open(&harness), "editing it keeps it open"); +} + +#[test] +fn it_shows_what_the_properties_panel_shows() { + let mut harness = harness(); + let fill = harness.state().session.doc.project.layers.values().find(|layer| matches!(layer.kind, LayerKind::Fill(_))).map(|layer| layer.id.0).unwrap(); + let selected = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": fill})); + assert!(selected.is_ok(), "{selected:?}"); + harness.run_steps(3); + + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); + assert!(in_popup("Projection"), "a selected fill shows its fill settings"); + assert!(!in_popup("Minimum size (%)"), "not the brush's"); +} + +#[test] +fn bake_and_render_modes_never_open_it() { + let mut harness = harness(); + let center = view_center(&harness); + for mode in [Mode::Baking, Mode::Rendering] { + harness.state_mut().ui.mode = mode; + harness.run_steps(3); + click(&mut harness, PointerButton::Secondary, center); + assert_eq!(harness.state().properties_popup, None, "{mode:?}"); + } +} From 3b302b88dc9d44235bbccb4cdd6721212a0760ba Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 05:03:21 +0000 Subject: [PATCH 060/275] Polygon fill: box selection, polygon mode, hit-test, visible polygons only and the 2D view A drag in the 3D or 2D view draws a rectangle and fills what it selects live; releasing it records one undo step. A click still fills one target, now also in the 2D view. Fill modes gain Polygon (the source quad or n-gon, from the importer's diagonals), and Mesh fills connected geometry. The hit-test picks polygons the rectangle touches or whose center it holds; visible polygons only uses a nearest-triangle buffer next to the eye-depth raster, leaving hidden texture sets out. Polygon fill's properties show its own settings and, by selection, the material, the mask gray, or why it can't fill. Wireframes show while the tool is active without changing the saved toggles. Commands: tool.fillMode takes polygon, tool.fillSelection sets hitTest and visibleOnly, and tool.click takes a screen box, a UV point or a UV box. --- crates/engine/src/fill_hit_test.rs | 80 ++++ crates/engine/src/lib.rs | 5 + crates/engine/src/painting.rs | 130 ++----- crates/engine/src/polygon_fill.rs | 470 ++++++++++++++++++++++++ crates/engine/src/polygon_fill_drag.rs | 28 ++ crates/engine/src/session.rs | 19 +- crates/engine/src/tool_cmds.rs | 71 +++- crates/engine/src/triangle_partition.rs | 77 ++++ crates/engine/tests/session.rs | 23 ++ crates/paint/src/visibility.rs | 135 ++++--- crates/ui-egui/src/dock.rs | 183 +++++++-- crates/ui-egui/src/i18n/ar.rs | 20 + crates/ui-egui/src/i18n/de.rs | 23 ++ crates/ui-egui/src/i18n/es.rs | 26 ++ crates/ui-egui/src/i18n/fr.rs | 26 ++ crates/ui-egui/src/i18n/it.rs | 26 ++ crates/ui-egui/src/i18n/ja.rs | 26 ++ crates/ui-egui/src/i18n/ko.rs | 23 ++ crates/ui-egui/src/i18n/pt_br.rs | 26 ++ crates/ui-egui/src/i18n/zh_hans.rs | 17 + crates/ui-egui/src/toolbar.rs | 31 +- crates/ui-egui/src/viewport.rs | 74 +++- crates/ui-egui/tests/polygon_fill.rs | 85 +++++ 23 files changed, 1414 insertions(+), 210 deletions(-) create mode 100644 crates/engine/src/fill_hit_test.rs create mode 100644 crates/engine/src/polygon_fill.rs create mode 100644 crates/engine/src/polygon_fill_drag.rs create mode 100644 crates/engine/src/triangle_partition.rs create mode 100644 crates/ui-egui/tests/polygon_fill.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs new file mode 100644 index 00000000..8a2b9359 --- /dev/null +++ b/crates/engine/src/fill_hit_test.rs @@ -0,0 +1,80 @@ +//! Which polygons a polygon fill box selects. + +use serde::{Deserialize, Serialize}; +use texturecraft_geom::glam::Vec2; + +/// How a polygon fill box decides whether it selects a polygon +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillHitTest { + /// Any part of the polygon inside the box or crossing it + #[default] + Intersection, + /// The polygon's center point inside the box + ContainedCenter, +} + +impl FillHitTest { + /// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners) + pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool { + match self { + FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)), + FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()), + } + } +} + +/// Area-weighted center of the triangles (their corners' mean when they have no area) +fn center(triangles: &[[Vec2; 3]]) -> Option { + let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; + let total: f32 = triangles.iter().map(area).sum(); + let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); + let centroids: Vec2 = triangles.iter().map(centroid).sum(); + + match triangles.len() { + 0 => None, + count if total <= f32::EPSILON => Some(centroids / count as f32), + _ => Some(weighted / total), + } +} + +/// Separating axis test of a triangle against an axis-aligned box +fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool { + let triangle_low = corners[0].min(corners[1]).min(corners[2]); + let triangle_high = corners[0].max(corners[1]).max(corners[2]); + if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() { + return false; + } + + let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)]; + (0..3).all(|edge| { + let axis = (corners[(edge + 1) % 3] - corners[edge]).perp(); + let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point)))); + let (triangle_min, triangle_max) = span(&corners); + let (box_min, box_max) = span(&box_corners); + triangle_max >= box_min && box_max >= triangle_min + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; + + #[test] + fn intersection_needs_any_overlap_and_contained_center_the_center() { + let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); + } + + #[test] + fn a_polygon_center_weighs_its_triangles_by_area() { + let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]]; + assert_eq!(center(&square), Some(Vec2::ONE)); + assert_eq!(center(&[]), None); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..824ccf48 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_hit_test; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -31,6 +32,8 @@ pub mod materialx_cmds; pub mod meshmap_cmds; pub mod painting; pub mod path_tool; +mod polygon_fill; +mod polygon_fill_drag; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] mod preserve; @@ -45,11 +48,13 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod triangle_partition; pub mod uv_tile_cmds; pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; +pub use fill_hit_test::FillHitTest; pub use path_tool::PathState; pub use project_cmds::sample_session; pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..86761f79 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -7,11 +7,11 @@ use texturecraft_compose::PaintTarget; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ - CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, - fill_triangles, pick, rasterize, + CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, + rasterize, }; -use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; use crate::{EngineError, Result}; impl Session { @@ -301,12 +301,15 @@ impl Session { Ok(self.continue_stroke(screen, pressure)) } - /// Start a stroke in the 2D view at texture coordinate `uv`. + /// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there). pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { self.cancel_stroke(); - if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) { - return Err(EngineError::Other("use this tool in the 3D view".into())); + match self.tool.tool { + Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()), + Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())), + _ => {} } + self.start_stroke(self.viewport, true, Some(uv))?; self.continue_stroke_uv(uv, pressure); Ok(()) @@ -482,21 +485,6 @@ impl Session { Ok(tiles) } - /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. - pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { - let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - let ts = self.ts(); - let material = self.doc.project.texture_set(ts)?.material; - if hit.material != material { - return Err(EngineError::Other("that surface belongs to another texture set".into())); - } - let tris = self.fill_set(hit.tri, material); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - fill_triangles(&mut canvas, &gbuf, &tris); - self.commit_fill("Polygon fill", ts, &canvas)?; - Ok(tris.len()) - } - /// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the /// quick mask unless the fill edits it. pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc, StrokeCanvas)> { @@ -510,61 +498,30 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { - let size = (canvas.alpha.width(), canvas.alpha.height()); - let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; if self.quick_mask.editing { - self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); - return Ok(()); + return self.paint_fill(ts, canvas); } - self.edit(label, |s| { - let target = s.paint_target()?; - let values = s.stroke_values(target); - match target { - PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()), - PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()), - } - Ok(()) - }) + + self.edit(label, |session| session.paint_fill(ts, canvas)) } - /// Triangles filled by the current fill mode starting from `tri`. - fn fill_set(&self, tri: u32, material: usize) -> BTreeSet { - let m = &self.mesh; - match self.tool.fill_mode { - FillMode::Triangle => [tri].into_iter().collect(), - FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(), - FillMode::UvIsland => { - // Triangles sharing an edge in UV space form a UV island: imported meshes often - // split vertices along hard edges (or per face) where the UVs run on, so shared - // vertex indices alone break an island into its polygons. - let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]); - let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) { - Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(), - _ => Vec::new(), - }; - let mut by_edge: BTreeMap<_, Vec> = BTreeMap::new(); - for t in m.triangles_of(material) { - for e in edges(t) { - by_edge.entry(e).or_default().push(t as u32); - } - } - let mut seen = BTreeSet::new(); - let mut stack = vec![tri]; - while let Some(t) = stack.pop() { - if !seen.insert(t) { - continue; - } - for e in edges(t as usize) { - for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) { - if !seen.contains(n) { - stack.push(*n); - } - } - } - } - seen - } + /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) + pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> { + let size = (canvas.alpha.width(), canvas.alpha.height()); + let opacity = self.tool.brush.opacity; + let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.quick_mask.editing { + self.commit_quick_mask(ts, size, source); + return Ok(()); } + + let target = self.paint_target()?; + let values = self.stroke_values(target); + match target { + PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()), + PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()), + } + Ok(()) } /// Color picker: copy the material under the cursor into the tool's paint values. @@ -627,34 +584,3 @@ fn with_commit_source( let carried = st.canvas.pickup.as_ref().map(|p| &p.values); f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) } - -#[cfg(test)] -mod tests { - use texturecraft_geom::glam::{Vec2, Vec3}; - use texturecraft_geom::mesh::Mesh; - use texturecraft_geom::primitives; - - use crate::session::{FillMode, Session}; - - #[test] - fn uv_island_fill_follows_uvs_across_split_vertices() { - // Two copies of a plane, each triangle with its own three vertices (as hard edges or - // per-face imports leave a mesh), the second copy apart in UV space. - let plane = primitives::plane(2.0, 4); - let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); - for shift in [0.0, 0.5] { - for i in plane.indices.iter().map(|i| *i as usize) { - positions.push(plane.positions[i] + Vec3::Y * shift); - uvs.push(plane.uvs[i] * 0.5 + shift); - } - } - let indices = (0..positions.len() as u32).collect(); - let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); - let n = plane.triangle_count(); - assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared"); - let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap(); - s.tool.fill_mode = FillMode::UvIsland; - assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island"); - assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island"); - } -} diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs new file mode 100644 index 00000000..2d577835 --- /dev/null +++ b/crates/engine/src/polygon_fill.rs @@ -0,0 +1,470 @@ +//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view. + +use std::borrow::Cow; +use std::collections::{BTreeSet, HashSet}; + +use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::{Mesh, NO_TRI}; +use texturecraft_paint::{EyeDepth, fill_triangles}; + +use crate::polygon_fill_drag::PolygonFillDrag; +use crate::session::{FillMode, Session}; +use crate::triangle_partition::TrianglePartition; +use crate::{EngineError, Result}; + +/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner +const CORNER_GRID_STEPS: f32 = 1e5; + +/// Clip-space w below which a vertex counts as behind the camera +const MIN_CLIP_W: f32 = 1e-5; + +impl Session { + /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` + pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + if hit.material != self.fill_material()? { + return Err(EngineError::Other("that surface belongs to another texture set".into())); + } + + self.fill_group_of(hit.tri) + } + + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { + let material = self.fill_material()?; + let mesh = &self.mesh; + let triangle = mesh + .triangles_of(material) + .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + + self.fill_group_of(triangle as u32) + } + + /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) + pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + self.drag_polygon_fill_box(corner, opposite, viewport)?; + Ok(self.end_polygon_fill_box()) + } + + /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) + pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + self.drag_polygon_fill_box_uv(corner, opposite)?; + Ok(self.end_polygon_fill_box()) + } + + /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` + pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + let viewport = viewport.max(Vec2::ONE); + self.start_polygon_fill_drag(Some(viewport))?; + + let view_proj = self.camera.view_proj(viewport.x / viewport.y); + let mesh = self.mesh.clone(); + let to_screen = |vertex: usize| { + let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); + let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; + Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) + }; + let screen_corners = |triangle: usize| { + let [first, second, third] = mesh.tri(triangle)?; + Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) + }; + let selected = self.box_selection(&screen_corners, low, high); + self.show_box_fill(selected) + } + + /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) + pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + let (low, high) = box_bounds(corner, opposite)?; + self.start_polygon_fill_drag(None)?; + + let mesh = self.mesh.clone(); + let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); + self.show_box_fill(selected) + } + + /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count + pub fn end_polygon_fill_box(&mut self) -> usize { + let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; + + // Quick mask edits keep no history, as with its strokes + let filled = drag.filled.len(); + if filled > 0 && drag.quick_mask_before.is_none() { + self.push_history("Polygon fill", drag.before); + } + filled + } + + /// The mesh material of the texture set being painted + fn fill_material(&self) -> Result { + Ok(self.doc.project.texture_set(self.ts())?.material) + } + + /// The triangles the current fill mode fills together, for `material` + fn fill_partition(&self, material: usize) -> TrianglePartition { + match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges), + FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges), + FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges), + } + } + + /// Fill the fill-mode group holding `triangle` (one undo step) + fn fill_group_of(&mut self, triangle: u32) -> Result { + let ts = self.ts(); + let groups = self.fill_partition(self.fill_material()?); + let triangles: BTreeSet = groups.group(triangle).unwrap_or_default().iter().copied().collect(); + + let (gbuf, mut canvas) = self.fill_canvas(ts)?; + fill_triangles(&mut canvas, &gbuf, &triangles); + self.commit_fill("Polygon fill", ts, &canvas)?; + Ok(triangles.len()) + } + + /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + if self.polygon_fill_drag.is_some() { + return Ok(()); + } + + let material = self.fill_material()?; + let polygons = match self.tool.fill_mode { + FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), + _ => TrianglePartition::new(&self.mesh, material, polygon_edges), + }; + let depth = viewport + .filter(|_| self.tool.fill_visible_only) + .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); + self.polygon_fill_drag = Some(PolygonFillDrag { + before: self.doc.clone(), + quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), + filled: BTreeSet::new(), + depth, + polygons, + fill_groups: self.fill_partition(material), + failed: false, + }); + Ok(()) + } + + /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden + fn shown_mesh(&self) -> Cow<'_, Mesh> { + let sets = &self.doc.project.texture_sets; + if sets.iter().all(|set| set.visible) { + return Cow::Borrowed(&self.mesh); + } + + let mut mesh = (*self.mesh).clone(); + for set in sets.iter().filter(|set| !set.visible) { + for triangle in self.mesh.triangles_of(set.material) { + if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) { + let first = corners[0]; + corners.fill(first); + } + } + } + Cow::Owned(mesh) + } + + /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space + fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; + + let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let hit_test = self.tool.fill_hit_test; + let mut groups = BTreeSet::new(); + for polygon in &drag.polygons.groups { + let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); + let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); + if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); + } + } + + groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect() + } + + /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed + fn show_box_fill(&mut self, selected: BTreeSet) -> Result { + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + if drag.failed || drag.filled == selected { + return Ok(drag.filled.len()); + } + + drag.filled = selected.clone(); + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + } + + let ts = self.ts(); + let painted = if selected.is_empty() { + Ok(()) + } else { + self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| { + fill_triangles(&mut canvas, &gbuf, &selected); + self.paint_fill(ts, &canvas) + }) + }; + self.invalidate_changed(&previous); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + + // A failed fill is reported once; the rest of the drag fills nothing + if painted.is_err() + && let Some(mut drag) = self.polygon_fill_drag.take() + { + self.restore_before_box(&drag); + drag.failed = true; + drag.filled.clear(); + self.polygon_fill_drag = Some(drag); + } + painted.map(|_| selected.len()) + } + + /// Put back the document and quick mask from before the box `drag` + fn restore_before_box(&mut self, drag: &PolygonFillDrag) { + let previous = std::mem::replace(&mut self.doc, drag.before.clone()); + if let Some(masks) = &drag.quick_mask_before { + self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); + } + self.invalidate_changed(&previous); + } +} + +/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { + let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); + let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); + let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + + rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) + .copied() + .filter(|triangle| *triangle != NO_TRI) + .collect() +} + +/// The two corners spanning a box, lowest first +fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + Ok((corner.min(opposite), corner.max(opposite))) +} + +/// Texture coordinates of `triangle`'s corners +fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { + let [first, second, third] = mesh.tri(triangle)?; + Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) +} + +/// Whether `point` lies in the triangle with `corners` (either winding) +fn contains(corners: [Vec2; 3], point: Vec2) -> bool { + let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); + let sides = [side(0), side(1), side(2)]; + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) +} + +/// The polygon diagonals of `triangle`: edges the importer added to split a polygon +fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { + let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); + let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() }; + + (0..3) + .filter(|edge| hidden >> edge & 1 == 1) + .map(|edge| { + let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]); + (from.min(to), from.max(to)) + }) + .collect() +} + +/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart +fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> { + let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected +fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> { + let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64)); + let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() }; + let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() }; + + [(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec() +} + +#[cfg(test)] +mod tests { + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + use texturecraft_geom::primitives; + + use crate::fill_hit_test::FillHitTest; + use crate::session::{FillMode, Session, Tool}; + + /// The roughness the test fills paint, to tell filled texels apart + const FILL_ROUGHNESS: f32 = 0.9; + + /// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`] + fn fill_session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.tool.tool = Tool::PolygonFill; + session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]); + session.update(); + session + } + + /// Whether the texel at texture coordinate `uv` shows the fill's roughness + fn filled_at(session: &Session, uv: Vec2) -> bool { + let (width, height) = session.caches[0].size; + let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32); + (roughness[0] - FILL_ROUGHNESS).abs() < 0.01 + } + + /// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh) + fn split_planes() -> (Mesh, usize) { + let plane = primitives::plane(2.0, 4); + let (mut positions, mut uvs) = (Vec::::new(), Vec::::new()); + for shift in [0.0, 0.5] { + for vertex in plane.indices.iter().map(|index| *index as usize) { + positions.push(plane.positions[vertex] + Vec3::Y * shift); + uvs.push(plane.uvs[vertex] * 0.5 + shift); + } + } + let indices = (0..positions.len() as u32).collect(); + let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap(); + assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared"); + (mesh, plane.triangle_count()) + } + + #[test] + fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() { + let (mesh, per_plane) = split_planes(); + let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap(); + + for fill_mode in [FillMode::UvIsland, FillMode::Mesh] { + session.tool.fill_mode = fill_mode; + let groups = session.fill_partition(0); + assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane"); + assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane"); + } + } + + #[test] + fn polygon_mode_groups_the_two_triangles_of_each_quad() { + let mut session = fill_session(primitives::plane(2.0, 2)); + + session.tool.fill_mode = FillMode::Triangle; + assert_eq!(session.fill_partition(0).group(0), Some(&[0][..])); + + session.tool.fill_mode = FillMode::Polygon; + let mut quad = session.fill_partition(0).group(0).unwrap().to_vec(); + quad.sort_unstable(); + assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad"); + } + + #[test] + fn a_uv_box_over_half_a_plane_fills_that_half() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap(); + session.update(); + + assert_eq!(filled, 16, "the left two columns of quads"); + assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9))); + assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1))); + } + + #[test] + fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() { + let mut session = fill_session(primitives::plane(2.0, 2)); + session.tool.fill_mode = FillMode::Polygon; + let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2)); + + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside"); + assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step"); + + session.tool.fill_hit_test = FillHitTest::Intersection; + assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts"); + } + + #[test] + fn visible_only_skips_the_back_of_a_cube() { + let mut session = fill_session(primitives::cube(1.0)); + session.camera.yaw = 0.6; + session.camera.pitch = 0.4; + let (low, high) = (Vec2::ZERO, session.viewport); + let every_triangle = session.mesh.triangle_count(); + + session.tool.fill_visible_only = true; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees"); + + session.tool.fill_visible_only = false; + assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle); + } + + #[test] + fn visible_only_sees_through_a_hidden_texture_set() { + let mut session = fill_session(primitives::material_ball()); + let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap(); + session.active_set = base; + let (low, high) = (Vec2::ZERO, session.viewport); + + let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap(); + session.doc.project.texture_sets[0].visible = false; + let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap(); + + assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}"); + } + + #[test] + fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills"); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging"); + assert_eq!(session.history_labels().len(), history, "no undo step yet"); + + assert_eq!(session.end_polygon_fill_box(), 16); + assert_eq!(session.history_labels().len(), history + 1); + session.undo().unwrap(); + session.update(); + assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); + } + + #[test] + fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { + let mut session = fill_session(primitives::udim_plane()); + assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + let every_triangle = session.mesh.triangle_count(); + assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); + } + + #[test] + fn a_2d_click_fills_the_triangle_under_it() { + let mut session = fill_session(primitives::plane(2.0, 1)); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + + assert!(filled_at(&session, Vec2::new(0.2, 0.7))); + assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays"); + assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs"); + } +} diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs new file mode 100644 index 00000000..4a7bc104 --- /dev/null +++ b/crates/engine/src/polygon_fill_drag.rs @@ -0,0 +1,28 @@ +//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move. + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_geom::glam::Vec2; +use texturecraft_paint::EyeDepth; +use texturecraft_texel::TileImage; + +use crate::session::Document; +use crate::triangle_partition::TrianglePartition; + +/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends +pub(crate) struct PolygonFillDrag { + /// The document before the drag, refilled each time the selection changes + pub before: Document, + /// The quick mask's coverage before the drag, when the drag paints the quick mask + pub quick_mask_before: Option>, + /// The triangles filled so far + pub filled: BTreeSet, + /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) + pub depth: Option<(EyeDepth, Vec2)>, + /// The polygons the box tests + pub polygons: TrianglePartition, + /// What the fill mode fills together + pub fill_groups: TrianglePartition, + /// The fill failed (reported once): the rest of the drag fills nothing + pub failed: bool, +} diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..c5b55649 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -165,6 +165,8 @@ impl ViewMode { pub enum FillMode { #[default] Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, UvIsland, Mesh, } @@ -210,6 +212,12 @@ pub struct ToolState { /// Gray painted into masks. pub mask_value: f32, pub fill_mode: FillMode, + /// How a polygon fill box decides which polygons it selects + #[serde(default)] + pub fill_hit_test: crate::fill_hit_test::FillHitTest, + /// Polygon fill boxes in the 3D view select only the polygons the camera sees + #[serde(default = "default_fill_visible_only")] + pub fill_visible_only: bool, /// Stencil used by the Projection tool. #[serde(default)] pub stencil: Option, @@ -231,6 +239,10 @@ fn default_smudge_strength() -> f32 { 0.5 } +fn default_fill_visible_only() -> bool { + true +} + /// What the Clone tool copies (the clone source modes). #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum CloneFrom { @@ -260,6 +272,8 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), mask_value: 1.0, fill_mode: FillMode::Triangle, + fill_hit_test: Default::default(), + fill_visible_only: default_fill_visible_only(), stencil: None, smudge_strength: default_smudge_strength(), clone_source: None, @@ -356,6 +370,8 @@ pub struct Session { /// The last stroke's camera visibility buffer: reused while the camera, view size and mesh /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, + /// The polygon fill box being dragged + pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). pub export_presets: crate::preset_cmds::UserPresets, /// The user's project templates (kept when another project opens). @@ -405,6 +421,7 @@ impl Session { revision: 1, log: Vec::new(), depth_cache: None, + polygon_fill_drag: None, export_presets: Default::default(), templates: Default::default(), }) @@ -530,7 +547,7 @@ impl Session { /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { + pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..ba7f0f9b 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; +use crate::fill_hit_test::FillHitTest; use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; use crate::{Result, Session, cmd}; @@ -69,7 +70,16 @@ pub fn specs() -> Vec { always, clone_source ), - cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode), + cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode), + cmd!( + "tool.fillSelection", + "Polygon fill selection", + [], + None, + "{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}", + always, + fill_selection + ), cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke), cmd!( "tool.strokeUv", @@ -80,7 +90,15 @@ pub fn specs() -> Vec { always, stroke_uv ), - cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click), + cmd!( + "tool.click", + "Tool click", + [], + None, + "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}", + always, + click + ), cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))), ] } @@ -322,6 +340,7 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { fn fill_mode(s: &mut Session, p: &Value) -> Result { s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, + "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), @@ -329,6 +348,20 @@ fn fill_mode(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +fn fill_selection(s: &mut Session, p: &Value) -> Result { + match strp(p, "hitTest") { + None => {} + Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), + } + if let Some(visible_only) = boolp(p, "visibleOnly") { + s.tool.fill_visible_only = visible_only; + } + + Ok(Value::Null) +} + pub(crate) fn viewport_of(s: &Session, p: &Value) -> Vec2 { match p.get("viewport").and_then(Value::as_array) { Some(a) if a.len() == 2 => { @@ -370,21 +403,43 @@ fn stroke(s: &mut Session, p: &Value) -> Result { } fn click(s: &mut Session, p: &Value) -> Result { + if s.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(s, p)? + { + s.update(); + return Ok(json!({ "triangles": triangles })); + } + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; - let vp = viewport_of(s, p); + + let point = Vec2::new(x, y); + let viewport = viewport_of(s, p); let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }), + Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let v = s.color_pick(Vec2::new(x, y), vp)?; - json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>()) + let picked = s.color_pick(point, viewport)?; + json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?, - _ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, + _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), }; s.update(); Ok(out) } +/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point +fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { + let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); + let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, + (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, + _ => return Ok(None), + }; + + Ok(Some(filled)) +} + fn stroke_uv(s: &mut Session, p: &Value) -> Result { let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?; let tiles = s.stroke_uv_points(&points)?; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs new file mode 100644 index 00000000..1364fe69 --- /dev/null +++ b/crates/engine/src/triangle_partition.rs @@ -0,0 +1,77 @@ +//! Triangles of one material grouped into the pieces polygon fill selects and fills. + +use std::collections::{BTreeMap, HashMap}; + +use texturecraft_geom::Mesh; + +/// A material's triangles split into groups joined across shared edges +pub struct TrianglePartition { + /// The triangles of each group + pub groups: Vec>, + /// The index of each triangle's group + group_of: HashMap, +} + +impl TrianglePartition { + /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); + let mut by_edge: BTreeMap> = BTreeMap::new(); + for &triangle in &triangles { + for edge in edges(mesh, triangle as usize) { + by_edge.entry(edge).or_default().push(triangle); + } + } + + let mut groups = Vec::new(); + let mut group_of = HashMap::with_capacity(triangles.len()); + for &start in &triangles { + if group_of.contains_key(&start) { + continue; + } + let mut members = Vec::new(); + let mut stack = vec![start]; + group_of.insert(start, groups.len()); + while let Some(triangle) = stack.pop() { + members.push(triangle); + for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + if !group_of.contains_key(neighbour) { + group_of.insert(*neighbour, groups.len()); + stack.push(*neighbour); + } + } + } + groups.push(members); + } + TrianglePartition { groups, group_of } + } + + /// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material) + pub fn index_of(&self, triangle: u32) -> Option { + self.group_of.get(&triangle).copied() + } + + /// The group holding `triangle` (None for a triangle of another material) + pub fn group(&self, triangle: u32) -> Option<&[u32]> { + self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice) + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::primitives; + + use super::*; + + #[test] + fn triangles_sharing_a_key_join_one_group() { + let mesh = primitives::plane(2.0, 2); + let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]); + + assert_eq!(singles.groups.len(), mesh.triangle_count()); + assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2); + assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2)); + assert_eq!(pairs.group(99), None); + } +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..7973d52e 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -105,6 +105,29 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn polygon_fill_boxes_survive_hostile_params() { + let hostile = [ + json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}), + json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}), + json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}), + json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}), + json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}), + ]; + for visible_only in [true, false] { + for hit_test in ["intersection", "containedCenter"] { + let mut session = session(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap(); + for params in &hostile { + let _ = execute(&mut session, "tool.click", params); + let _ = execute(&mut session, "tool.fillSelection", params); + session.update(); + } + } + } +} + /// Every command must return Ok or Err — never panic — for hostile params. #[test] fn panic_hunt() { diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index 01ce84f8..e914d297 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -3,10 +3,25 @@ use rayon::prelude::*; use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; -use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; +/// Largest buffer side in pixels. +const MAX_SIZE: u32 = 4096; + +/// Clip-space w below which a vertex counts as behind the camera. +const MIN_CLIP_W: f32 = 1e-5; + +/// Screen area (pixels squared) below which a triangle is skipped as degenerate. +const MIN_SCREEN_AREA: f32 = 1e-9; + +/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours. +const EDGE_TOLERANCE: f32 = 1e-4; + +/// [`EyeDepth::bias`] as a fraction of the scene radius. +const BIAS_PER_RADIUS: f32 = 0.004; + /// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty). #[derive(Clone, Debug)] pub struct EyeDepth { @@ -15,73 +30,99 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { - let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096)); - let aspect = w as f32 / h as f32; - let vp = camera.view_proj(aspect); + let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); + let view_proj = camera.view_proj(width as f32 / height as f32); let eye = camera.eye(); - // Project every vertex once. - let clip: Vec = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect(); - let screen: Vec> = - clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect(); - let dist_v: Vec = mesh.positions.iter().map(|p| p.distance(eye)).collect(); - let bands = (h as usize).div_ceil(BAND); - let mut bins: Vec> = vec![Vec::new(); bands]; - for t in 0..mesh.triangle_count() { - let Some([a, b, c]) = mesh.tri(t) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0); - let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32); - if y1 <= y0 || !y0.is_finite() || !y1.is_finite() { + + // Project every vertex once + let screen: Vec> = mesh + .positions + .iter() + .map(|position| { + let clip: Vec4 = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) + }) + .collect(); + let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); + + // Bin each triangle into the bands of rows it covers + let mut bands: Vec> = vec![Vec::new(); (height as usize).div_ceil(BAND)]; + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; + + let top = first.1.min(second.1).min(third.1).floor().max(0.0); + let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } - let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND); - for bin in bins.iter_mut().take(b1 + 1).skip(b0) { - bin.push(t as u32); + let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND); + for band in bands.iter_mut().take(last_band + 1).skip(first_band) { + band.push(triangle as u32); } } - let mut dist = vec![f32::MAX; (w * h) as usize]; - dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| { - let row0 = bi * BAND; - let nrows = rows.len() / w as usize; - for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) { - let Some([a, b, c]) = mesh.tri(t as usize) else { continue }; - let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue }; - let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]); - let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0); - if area.abs() < 1e-9 { + + let mut dist = vec![f32::MAX; (width * height) as usize]; + let mut triangle = vec![NO_TRI; (width * height) as usize]; + let band_len = BAND * width as usize; + dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let first_row = band * BAND; + let row_count = band_dist.len() / width as usize; + for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { + let Some(corners) = mesh.tri(candidate as usize) else { continue }; + let [first, second, third] = corners; + let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third)) + else { + continue; + }; + let corner_distance = corners.map(|vertex| vertex_distance[vertex]); + let area = + (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + if area.abs() < MIN_SCREEN_AREA { continue; } - let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize; - let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize; - let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize; - let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize; - for y in y0.max(row0)..y1 { - for x in x0..x1.min(w as usize) { - let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); - let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area; - let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area; - let w2 = 1.0 - w0 - w1; - if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 { + + let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; + let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; + let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; + let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + for row in top.max(first_row)..bottom { + for column in left..right.min(width as usize) { + let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); + let first_weight = + ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; + let second_weight = + ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + let third_weight = 1.0 - first_weight - second_weight; + if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; } - let d = w0 * da + w1 * db + w2 * dc; - if let Some(slot) = rows.get_mut((y - row0) * w as usize + x) - && d < *slot + + let distance = first_weight * corner_distance[0] + second_weight * corner_distance[1] + third_weight * corner_distance[2]; + let at = (row - first_row) * width as usize + column; + if let Some(slot) = band_dist.get_mut(at) + && distance < *slot { - *slot = d; + *slot = distance; + if let Some(nearest) = band_triangles.get_mut(at) { + *nearest = candidate; + } } } } } }); - EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 } + + EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS } } /// Whether world point `p` is visible (not hidden behind other geometry, inside the view). diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 87e9d84b..c42ee799 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -912,12 +912,14 @@ fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits. pub(crate) fn properties_title(app: &TextureCraftApp) -> String { - let p = &app.session.doc.project; - let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) { - (Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(), - (Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), - (Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(), - (Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(), + let project = &app.session.doc.project; + let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) { + // Polygon fill keeps its own properties whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(), + (Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(), + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(), + (Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(), _ => tr(app.session.tool.tool.label()).to_string(), }; format!("{} - {what}", tr("Properties")) @@ -927,12 +929,14 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } -/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool +/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); match (&selected, app.session.target) { + // Polygon fill shows its own settings and says what it fills into, whatever is selected + _ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui), (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => { @@ -1144,6 +1148,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Width of the label column in polygon fill's properties +const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; + +/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill) +fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::FillHitTest; + + let button_size = ui.spacing().interact_size.y; + ui.label(caption(&tr("Polygon fill").to_uppercase())); + property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| { + icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size); + }); + property_row( + ui, + tr("Fill mode"), + tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"), + |ui| crate::toolbar::fill_mode_buttons(app, ui), + ); + property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| { + for (hit_test, icon, tooltip) in [ + (FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")), + (FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() { + app.session.tool.fill_hit_test = hit_test; + } + } + }); + ui.horizontal(|ui| { + ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)"))); + }); + section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| { + let mut opacity = app.session.tool.brush.opacity * 100.0; + if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() { + app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0); + } + }); + ui.separator(); + + match polygon_fill_paints_mask(app) { + Ok(false) => { + ui.label(caption(&tr("Material").to_uppercase())); + material_controls(app, ui); + } + Ok(true) => { + ui.label(caption(&tr("Grayscale").to_uppercase())); + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; + } + } + Err(note) => { + ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim)); + } + } +} + +/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge +fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let label_width = ui.label(label).rect.width(); + ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0)); + controls(ui); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info)); + }); +} + +/// A dim info icon explaining a setting on hover +fn info_icon(ui: &mut Ui, text: &str) { + ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text); +} + +/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill +fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { + if app.session.quick_mask.editing { + return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string()); + } + + let project = &app.session.doc.project; + let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else { + return Err(tr("Select a paint layer or a layer's mask to fill").to_string()); + }; + + match app.session.target { + StackTarget::Mask => Ok(true), + StackTarget::Effect(_) => Ok(!targets_content(app)), + StackTarget::Content => { + let content = project.content_layer(layer.id).unwrap_or(layer); + if matches!(content.kind, LayerKind::Paint) { + Ok(false) + } else { + Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)])) + } + } + } +} + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let b = &mut app.session.tool.brush; ui.label(caption(tr("Brush"))); @@ -1365,59 +1467,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; +/// The tool's material under a "Material" heading fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Material"))); - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + material_controls(app, ui); +} + +/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) +fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::core::ChannelKind; + + let tokens = Tokens::get(ui.ctx()); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { - for c in &chans { - let on = app.session.tool.enabled.contains(c); - if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { - let solo = ui.input(|i| i.modifiers.alt); - app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo})); + for channel in &channels { + let on = app.session.tool.enabled.contains(channel); + if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() { + let solo = ui.input(|input| input.modifiers.alt); + app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo})); } } }); ui.add_space(4.0); - let mask_mode = !targets_content(app); - if mask_mode { - let mut v = app.session.tool.mask_value; - if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() { - app.session.tool.mask_value = v; + + if !targets_content(app) { + let mut gray = app.session.tool.mask_value; + if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() { + app.session.tool.mask_value = gray; } return; } - for c in chans { - if !app.session.tool.enabled.contains(&c) { + + for channel in channels { + if !app.session.tool.enabled.contains(&channel) { continue; } - let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value()); - match c.kind() { - texturecraft_engine::core::ChannelKind::Color => { + let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()); + match channel.kind() { + ChannelKind::Color => { ui.horizontal(|ui| { - ui.label(tr(c.label())); - if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.session.tool.values.insert(c, v); + ui.label(tr(channel.label())); + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + app.session.tool.values.insert(channel, value); } }); } - texturecraft_engine::core::ChannelKind::NormalMap => { - ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim)); + ChannelKind::NormalMap => { + ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim)); } - texturecraft_engine::core::ChannelKind::Signed => { - if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Signed => { + if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } - texturecraft_engine::core::ChannelKind::Scalar => { - if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() { - app.session.tool.values.insert(c, [v[0]; 3]); + ChannelKind::Scalar => { + if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() { + app.session.tool.values.insert(channel, [value[0]; 3]); } } } } if app.session.tool.tool == Tool::Eraser { - ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim)); + ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim)); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 0f2e023f..4c50e9ac 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه", + ), + ("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."), + ("Fill mode", "وضع التعبئة"), + ("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"), + ("Hit-test", "اختبار الإصابة"), + ("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"), + ("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"), + ("Rectangle fill", "تعبئة مستطيلة"), + ("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"), + ("Selection mode", "وضع التحديد"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV", + ), + ("Visible polygons only", "المضلعات المرئية فقط"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 77cf296b..63ec501e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,27 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.", + ), + ("Fill mode", "Füllmodus"), + ("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"), + ("Hit-test", "Treffertest"), + ("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"), + ("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"), + ("Rectangle fill", "Rechteckfüllung"), + ("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"), + ("Selection mode", "Auswahlmodus"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln", + ), + ("Visible polygons only", "Nur sichtbare Polygone"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 4153783e..99fd2177 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.", + ), + ("Fill mode", "Modo de relleno"), + ("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"), + ("Hit-test", "Prueba de selección"), + ("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"), + ("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"), + ("Rectangle fill", "Relleno rectangular"), + ("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"), + ("Selection mode", "Modo de selección"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV", + ), + ("Visible polygons only", "Solo polígonos visibles"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 0c07e5a4..4ef684a1 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.", + ), + ("Fill mode", "Mode de remplissage"), + ("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"), + ("Hit-test", "Test de sélection"), + ("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"), + ("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"), + ("Rectangle fill", "Remplissage rectangulaire"), + ("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"), + ("Selection mode", "Mode de sélection"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV", + ), + ("Visible polygons only", "Polygones visibles uniquement"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index b4bd33b3..44171f06 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.", + ), + ("Fill mode", "Modalità di riempimento"), + ("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"), + ("Hit-test", "Test di selezione"), + ("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"), + ("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"), + ("Rectangle fill", "Riempimento rettangolare"), + ("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"), + ("Selection mode", "Modalità di selezione"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV", + ), + ("Visible polygons only", "Solo poligoni visibili"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f764e268..9b4b7fe9 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします", + ), + ("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。", + ), + ("Fill mode", "塗りつぶしモード"), + ("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"), + ("Hit-test", "ヒットテスト"), + ("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"), + ("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"), + ("Rectangle fill", "矩形塗りつぶし"), + ("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"), + ("Selection mode", "選択モード"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします", + ), + ("Visible polygons only", "表示されているポリゴンのみ"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a1c8d363..e11e5ccb 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,27 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다", + ), + ("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.", + ), + ("Fill mode", "채우기 모드"), + ("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"), + ("Hit-test", "히트 테스트"), + ("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"), + ("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"), + ("Rectangle fill", "사각형 채우기"), + ("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"), + ("Selection mode", "선택 모드"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다", + ), + ("Visible polygons only", "보이는 폴리곤만"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 880b62ff..307a93e6 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,30 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ( + "A click fills what is under it; a dragged rectangle fills what it selects as it grows", + "Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce", + ), + ("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"), + ( + "Editing the quick mask: fills paint where painting is allowed. Press U to finish.", + "Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.", + ), + ("Fill mode", "Modo de preenchimento"), + ("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"), + ("Hit-test", "Teste de seleção"), + ("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"), + ("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"), + ("Rectangle fill", "Preenchimento retangular"), + ("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"), + ("Selection mode", "Modo de seleção"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV", + ), + ("Visible polygons only", "Apenas polígonos visíveis"), + ( + "\"{layer}\" can't be filled: select a paint layer or a layer's mask", + "\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f894f1ad..d3d35296 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,21 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"), + ("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"), + ("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"), + ("Fill mode", "填充模式"), + ("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"), + ("Hit-test", "命中测试"), + ("How a rectangle selects polygons", "矩形选择多边形的方式"), + ("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"), + ("Rectangle fill", "矩形填充"), + ("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"), + ("Selection mode", "选择模式"), + ( + "Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands", + "三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛", + ), + ("Visible polygons only", "仅可见多边形"), + ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ]; diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..889d2de7 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -281,19 +281,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) path_controls(app, ui); } } - Tool::PolygonFill => { - use texturecraft_engine::FillMode; - - for (fill_mode, icon, tooltip) in [ - (FillMode::Triangle, ic::POLYGON, tr("Triangle fill")), - (FillMode::UvIsland, ic::SHAPES, tr("UV island fill")), - (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), - ] { - if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { - app.session.tool.fill_mode = fill_mode; - } - } - } + Tool::PolygonFill => fill_mode_buttons(app, ui), Tool::ColorPicker => { ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); } @@ -317,6 +305,23 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { } } +/// Polygon fill's fill modes (top bar and properties) +pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + use texturecraft_engine::FillMode; + + let button_size = ui.spacing().interact_size.y; + for (fill_mode, icon, tooltip) in [ + (FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")), + (FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")), + (FillMode::Mesh, ic::CUBE, tr("Mesh fill")), + (FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")), + ] { + if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() { + app.session.tool.fill_mode = fill_mode; + } + } +} + /// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..91f816e9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -9,7 +9,7 @@ use serde_json::json; use texturecraft_engine::camera_cmds::DEFAULT_CAMERA; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::glam::{Vec2, Vec3}; -use texturecraft_engine::{Tool, ViewMode}; +use texturecraft_engine::{Session, Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; @@ -213,12 +213,14 @@ fn shade(app: &TextureCraftApp) -> Shade { }; let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + // Polygon fill shows the polygons it fills without changing the saved wireframe toggles + let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe, - wireframe_3d: app.ui.wireframe_3d, + wireframe: app.ui.uv_wireframe || polygon_fill, + wireframe_3d: app.ui.wireframe_3d || polygon_fill, ..Shade::from_project(&app.session.doc.project) } } @@ -575,8 +577,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill(local(point), viewport), + |session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -621,6 +632,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1003,6 +1015,52 @@ fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); } +/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image +fn polygon_fill_input( + app: &mut TextureCraftApp, + ui: &Ui, + response: &egui::Response, + fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result, + drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result, +) -> Option { + let origin_id = response.id.with("polygon_fill_box"); + let dragging = response.dragged_by(PointerButton::Primary); + let released = response.drag_stopped_by(PointerButton::Primary); + let held = ui.input(|input| input.pointer.primary_down()); + if !held && !released { + // A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step + if ui.data_mut(|data| data.remove_temp::(origin_id)).is_some() { + app.session.end_polygon_fill_box(); + } + } else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) { + ui.data_mut(|data| data.insert_temp(origin_id, press)); + } + + let origin = ui.data(|data| data.get_temp::(origin_id)); + let pointer = ui.input(|input| input.pointer.latest_pos()); + let (filled, dragged_box) = match (origin, pointer) { + _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), + (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), + _ => (None, None), + }; + if let Some(Err(error)) = filled { + app.toast(error.to_string(), true); + } + dragged_box +} + +/// How strongly the polygon fill box tints what it covers (0..1) +const FILL_BOX_TINT: f32 = 0.15; + +/// The polygon fill box being dragged, over view `rect` +fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { + let Some(fill_box) = fill_box else { return }; + + let accent = Tokens::get(ui.ctx()).viewport_accent; + ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside); +} + /// V held with the Clone tool in painting mode: clicks set the clone source. fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { app.ui.mode == crate::state::Mode::Painting @@ -1213,8 +1271,17 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Painting in UV space let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + } else if painting && app.session.tool.tool == Tool::PolygonFill { + fill_box = polygon_fill_input( + app, + ui, + &response, + |session, point| session.polygon_fill_uv(to_uv(point)), + |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), + ); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -1254,6 +1321,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); + polygon_fill_box_overlay(ui, rect, fill_box); crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); // The UV tile outlines (numbered for UDIM sets) and the path being edited diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs new file mode 100644 index 00000000..dc007035 --- /dev/null +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -0,0 +1,85 @@ +//! Polygon fill in the views: a click fills one target and a box drag fills what the box selects, each as one undo step + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample project in the default split layout at 1600 x 960 with the polygon fill tool +fn polygon_fill_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + harness +} + +/// Drag the primary button from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Press and release the primary button at `at` +fn click(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Allocated tiles in the selected layer's base color +fn painted_tiles(harness: &Harness<'_, TextureCraftApp>) -> usize { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + session.doc.pixels.layer(layer, Channel::BaseColor).map_or(0, |image| image.allocated_count()) +} + +/// The undo steps recorded so far +fn history(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.history_labels() +} + +#[test] +fn a_box_drag_in_the_3d_view_is_one_fill_over_more_than_a_click() { + let mut clicked = polygon_fill_app(); + let center = clicked.state().viewport_rect.center(); + let before = history(&clicked).len(); + click(&mut clicked, center); + assert_eq!(history(&clicked).len(), before + 1, "a click fills one triangle"); + + let mut boxed = polygon_fill_app(); + drag(&mut boxed, center - vec2(120.0, 120.0), center + vec2(120.0, 120.0)); + assert_eq!(history(&boxed).len(), before + 1); + assert_eq!(history(&boxed).last().map(String::as_str), Some("Polygon fill")); + assert!( + painted_tiles(&boxed) > painted_tiles(&clicked), + "the box fills every triangle in it: {} tiles vs {}", + painted_tiles(&boxed), + painted_tiles(&clicked) + ); +} + +#[test] +fn a_box_drag_in_the_2d_view_is_one_fill() { + let mut harness = polygon_fill_app(); + let view_3d = harness.state().viewport_rect; + let center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let before = history(&harness).len(); + + drag(&mut harness, center - vec2(80.0, 20.0), center + vec2(80.0, 20.0)); + assert_eq!(history(&harness).len(), before + 1); + assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); +} From 538220069de65d4f75dd905c72664a5707f779ef Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:00:18 +0000 Subject: [PATCH 061/275] Name the fill slider ranges and the test's sizes and frame counts The tri-planar hardness range is the one layer.fill.projection clamps to; scale and rotation get named slider ranges as well. --- crates/ui-egui/src/dock.rs | 15 ++++++++--- .../ui-egui/tests/fill_projection_section.rs | 25 ++++++++++++++----- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 702104c0..22474fd6 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1603,6 +1603,15 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value } } +/// Slider range of a fill's scale or tiling +const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; + +/// Slider range of a UV fill's rotation, a full turn +const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; + +/// Tri-planar hardness: the exponent on the normal that weights the three projections, clamped to the same range by `layer.fill.projection` +const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; + /// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { let projection_label = fill.projection.label(); @@ -1630,7 +1639,7 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: } if let Projection::Triplanar { sharpness, .. } = &fill.projection { let mut sharpness = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, 1.0..=64.0, 1) { + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, TRIPLANAR_HARDNESS_RANGE, 1) { edit(json!({"sharpness": sharpness, "merge": merge})); } } @@ -1650,14 +1659,14 @@ fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl Fn } Projection::Decal(_) => return, }; - if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, 0.01..=20.0, 2) { + if let Some(merge) = slider_edit(ui, tr("Scale / tiling"), &mut scale, FILL_SCALE_RANGE, 2) { edit(json!({"scale": scale, "merge": merge})); } match projection { Projection::Uv { rotation, offset, .. } => { let mut rotation_degrees = *rotation; - if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, 0.0..=360.0, 0) { + if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { edit(json!({"rotation": rotation_degrees, "merge": merge})); } if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs index c46b4c7e..3d6e2c20 100644 --- a/crates/ui-egui/tests/fill_projection_section.rs +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -5,23 +5,36 @@ use egui_kittest::kittest::Queryable; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; +/// Tall enough that Properties shows the whole fill without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1400.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click or selection change to reach the panel +const SETTLE_FRAMES: usize = 3; + /// The app with a new fill layer (projected as `projection`) selected in Properties, and its layer id fn app_with_fill(projection: &str) -> (Harness<'static, TextureCraftApp>, u64) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let added = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); let layer = added["layer"].as_u64().unwrap(); texturecraft_engine::execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": projection})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); // The labels below are English; a first run would speak the system's language harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); + harness.run_steps(STARTUP_FRAMES); (harness, layer) } fn toggle_section(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label("UV transformations").click(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); } #[test] @@ -59,10 +72,10 @@ fn each_fill_keeps_its_own_open_state() { let added = texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({})).unwrap(); let second = added["layer"].as_u64().unwrap(); texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": second})).unwrap(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_some(), "a new fill starts open"); texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": first})).unwrap(); - harness.run_steps(3); + harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); } From 042627589557d4b18e367bca453dc1c01df0876b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:13:04 +0000 Subject: [PATCH 062/275] Tidy the fill editors and test the fill effect and cylindrical paths Name the fill's two gaps, give the edited offsets and hardness their own names, reuse the fill's id salt for the section, shorten the doc comments, and cover a fill effect's own open state and the cylindrical Axis. --- crates/ui-egui/src/dock.rs | 41 +++++++++++-------- .../ui-egui/tests/fill_projection_section.rs | 21 ++++++++++ 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 22474fd6..db87585e 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1572,16 +1572,22 @@ fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> Str trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) } -/// Projection and channel sources of a fill layer (`base` = {"layer"}) or fill effect (`base` = {"effect"}) filling `on`, owned by `reader` +/// Space above a fill's Material caption, setting it apart from the projection +const FILL_MATERIAL_GAP: f32 = 6.0; + +/// Space between a fill's channel chips and its channel sources +const FILL_CHANNELS_GAP: f32 = 4.0; + +/// Projection and sources of a fill layer or fill effect (`base`) for its channels `on`; `reader` owns it fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { let salt = base.to_string(); if let Projection::Decal(decal) = &fill.projection { decal_editor(app, ui, decal, reader); } else { - projection_editor(app, ui, fill, base); + projection_editor(app, ui, fill, base, &salt); } - ui.add_space(6.0); + ui.add_space(FILL_MATERIAL_GAP); ui.label(caption(tr("Material"))); let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { @@ -1594,7 +1600,7 @@ fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value } }); - ui.add_space(4.0); + ui.add_space(FILL_CHANNELS_GAP); let anchors = anchors_below(app, reader); for channel in channels { if on.contains(&channel) { @@ -1609,11 +1615,11 @@ const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; /// Slider range of a UV fill's rotation, a full turn const FILL_ROTATION_DEGREES_RANGE: std::ops::RangeInclusive = 0.0..=360.0; -/// Tri-planar hardness: the exponent on the normal that weights the three projections, clamped to the same range by `layer.fill.projection` +/// Tri-planar hardness, the exponent weighting the three projections; `layer.fill.projection` clamps to the same range const TRIPLANAR_HARDNESS_RANGE: std::ops::RangeInclusive = 1.0..=64.0; -/// A fill's projection kind, axis and tri-planar hardness, then its collapsible UV transformations; each edit sends only its field -fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value) { +/// A fill's projection kind, axis and hardness, then its collapsible UV transformations +fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, salt: &str) { let projection_label = fill.projection.label(); combo(ui, tr("Projection"), tr(projection_label), |ui| { for (id, label) in [ @@ -1629,8 +1635,9 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: } }); - let mut edit = |extra: Value| { - app.run("layer.fill.projection", with(base, extra)); + // Each edit sends only the fields it changed; the command keeps the others + let mut edit = |fields: Value| { + app.run("layer.fill.projection", with(base, fields)); }; if let Projection::Planar { axis, .. } | Projection::Cylindrical { axis, .. } = &fill.projection && let Some(picked_axis) = axis_combo(ui, *axis) @@ -1638,14 +1645,14 @@ fn projection_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: edit(json!({"axis": picked_axis})); } if let Projection::Triplanar { sharpness, .. } = &fill.projection { - let mut sharpness = *sharpness; - if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut sharpness, TRIPLANAR_HARDNESS_RANGE, 1) { - edit(json!({"sharpness": sharpness, "merge": merge})); + let mut hardness = *sharpness; + if let Some(merge) = slider_edit(ui, tr("Hardness"), &mut hardness, TRIPLANAR_HARDNESS_RANGE, 1) { + edit(json!({"sharpness": hardness, "merge": merge})); } } // One id per fill so each keeps its own open or closed state - section(ui, &format!("sec_fill_transform{base}"), tr("UV transformations"), true, |ui| { + section(ui, &format!("sec_fill_transform{salt}"), tr("UV transformations"), true, |ui| { projection_transform(ui, &fill.projection, &mut edit); }); } @@ -1669,13 +1676,13 @@ fn projection_transform(ui: &mut Ui, projection: &Projection, edit: &mut impl Fn if let Some(merge) = slider_edit(ui, tr("Rotation"), &mut rotation_degrees, FILL_ROTATION_DEGREES_RANGE, 0) { edit(json!({"rotation": rotation_degrees, "merge": merge})); } - if let Some((offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { - edit(json!({"offset": offset, "merge": merge})); + if let Some((edited_offset, merge)) = offset_sliders(ui, ["U", "V"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } Projection::Triplanar { offset, .. } | Projection::Planar { offset, .. } => { - if let Some((offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { - edit(json!({"offset": offset, "merge": merge})); + if let Some((edited_offset, merge)) = offset_sliders(ui, ["X", "Y", "Z"], *offset) { + edit(json!({"offset": edited_offset, "merge": merge})); } } Projection::Spherical { .. } | Projection::Cylindrical { .. } | Projection::Decal(_) => {} diff --git a/crates/ui-egui/tests/fill_projection_section.rs b/crates/ui-egui/tests/fill_projection_section.rs index 3d6e2c20..983f1bc5 100644 --- a/crates/ui-egui/tests/fill_projection_section.rs +++ b/crates/ui-egui/tests/fill_projection_section.rs @@ -62,6 +62,11 @@ fn hardness_and_axis_stay_outside_the_section() { toggle_section(&mut harness); assert!(harness.query_by_label("Offset X").is_none()); assert!(harness.query_by_label("Axis").is_some()); + + let (mut harness, _) = app_with_fill("cylindrical"); + toggle_section(&mut harness); + assert!(harness.query_by_label("Scale / tiling").is_none()); + assert!(harness.query_by_label("Axis").is_some()); } #[test] @@ -79,3 +84,19 @@ fn each_fill_keeps_its_own_open_state() { harness.run_steps(SETTLE_FRAMES); assert!(harness.query_by_label("Rotation").is_none(), "the first fill stays closed"); } + +#[test] +fn a_fill_effect_keeps_a_state_apart_from_its_layer() { + let (mut harness, layer) = app_with_fill("uv"); + toggle_section(&mut harness); + + let session = &mut harness.state_mut().session; + let added = texturecraft_engine::execute(session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap(); + let effect = added["effect"].as_u64().unwrap(); + texturecraft_engine::execute(session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label("Rotation").is_some(), "the effect's section starts open"); + + toggle_section(&mut harness); + assert!(harness.query_by_label("Rotation").is_none()); +} From 49bd4a1273fdf58bb8e4954addeaa0bf7c7c8b6a Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 07:52:40 +0000 Subject: [PATCH 063/275] Polygon fill: review fixes - A box drag always finishes: on release (even after a failed move), before any edit, undo, redo or tool change, and when a scripted box fails or starts while another drag is open. A camera move mid-drag (wheel zoom) keeps the drag and selects again from the new camera. - A drag projects the mesh once, skips repaints whose box hasn't moved, and builds each grouping once; triangle edges are computed once. - 2D clicks read the triangle from the set's UV G-buffer at the clicked texel, so collapsed UV faces can't take the click. - Brush strokes no longer record the nearest-triangle buffer; only polygon fill asks for it (EyeDepth::render_with_triangles). Screen projection is shared through paint::screen_point. - A box touching the view's edge or zero-size on whole pixels selects exactly the pixels it covers. - Click fills never merge into a box drag's undo step; FillMode moves to its own file; partial box parameters get their own error. --- crates/engine/src/fill_hit_test.rs | 33 ++- crates/engine/src/fill_mode.rs | 17 ++ crates/engine/src/lib.rs | 4 +- crates/engine/src/painting.rs | 3 +- crates/engine/src/polygon_fill.rs | 367 ++++++++++++++++-------- crates/engine/src/polygon_fill_drag.rs | 23 +- crates/engine/src/session.rs | 56 ++-- crates/engine/src/tool_cmds.rs | 72 ++--- crates/engine/src/triangle_partition.rs | 20 +- crates/paint/src/lib.rs | 2 +- crates/paint/src/visibility.rs | 72 +++-- crates/ui-egui/src/viewport.rs | 13 +- crates/ui-egui/tests/polygon_fill.rs | 3 +- 13 files changed, 439 insertions(+), 246 deletions(-) create mode 100644 crates/engine/src/fill_mode.rs diff --git a/crates/engine/src/fill_hit_test.rs b/crates/engine/src/fill_hit_test.rs index 8a2b9359..b30b2452 100644 --- a/crates/engine/src/fill_hit_test.rs +++ b/crates/engine/src/fill_hit_test.rs @@ -25,17 +25,17 @@ impl FillHitTest { /// Area-weighted center of the triangles (their corners' mean when they have no area) fn center(triangles: &[[Vec2; 3]]) -> Option { - let area = |corners: &[Vec2; 3]| (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); - let centroid = |corners: &[Vec2; 3]| (corners[0] + corners[1] + corners[2]) / 3.0; - let total: f32 = triangles.iter().map(area).sum(); - let weighted: Vec2 = triangles.iter().map(|corners| centroid(corners) * area(corners)).sum(); - let centroids: Vec2 = triangles.iter().map(centroid).sum(); - - match triangles.len() { - 0 => None, - count if total <= f32::EPSILON => Some(centroids / count as f32), - _ => Some(weighted / total), + if triangles.is_empty() { + return None; } + + // One pass: total area, area-weighted centroids and plain centroids + let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| { + let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs(); + let centroid = (corners[0] + corners[1] + corners[2]) / 3.0; + (total_area + area, weighted + centroid * area, centroids + centroid) + }); + Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 }) } /// Separating axis test of a triangle against an axis-aligned box @@ -63,11 +63,14 @@ mod tests { const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)]; #[test] - fn intersection_needs_any_overlap_and_contained_center_the_center() { - let (low, high) = (Vec2::new(2.0, 2.0), Vec2::new(6.0, 6.0)); - assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(1.0, 1.0), high), "a box cutting the triangle"); - assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::new(3.0, 3.0), Vec2::new(5.0, 5.0)), "inside the bounds, past the long edge"); - assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], low, high), "the center (4/3, 4/3) lies outside"); + fn intersection_selects_any_overlap() { + assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle"); + assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge"); + } + + #[test] + fn contained_center_selects_only_by_the_center() { + assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside"); assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0))); } diff --git a/crates/engine/src/fill_mode.rs b/crates/engine/src/fill_mode.rs new file mode 100644 index 00000000..f314562e --- /dev/null +++ b/crates/engine/src/fill_mode.rs @@ -0,0 +1,17 @@ +//! What one polygon fill target grows to. + +use serde::{Deserialize, Serialize}; + +/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum FillMode { + /// The triangle itself + #[default] + Triangle, + /// The source polygon (quad or n-gon) the importer split into triangles + Polygon, + /// The UV island: triangles sharing edges in UV space + UvIsland, + /// The connected geometry: triangles sharing edges by position + Mesh, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 824ccf48..6c6c9964 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; pub mod fill_hit_test; +pub mod fill_mode; pub mod filter_lib; pub mod inspect; pub mod instance_cmds; @@ -55,9 +56,10 @@ pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; +pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; -pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; +pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; pub use set_cmds::{ResizeOutput, ResizeTask}; pub use texturecraft_compose as compose; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 86761f79..afc67a28 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -502,7 +502,8 @@ impl Session { return self.paint_fill(ts, canvas); } - self.edit(label, |session| session.paint_fill(ts, canvas)) + // Each fill is its own step, never merged into a box drag's step of the same label + self.edit_merging(label, false, |session| session.paint_fill(ts, canvas)) } /// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step) diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 2d577835..a235e483 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -3,21 +3,19 @@ use std::borrow::Cow; use std::collections::{BTreeSet, HashSet}; -use texturecraft_geom::glam::{Vec2, Vec4Swizzles}; +use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Mesh, NO_TRI}; -use texturecraft_paint::{EyeDepth, fill_triangles}; +use texturecraft_paint::{EyeDepth, fill_triangles, screen_point}; +use crate::fill_mode::FillMode; use crate::polygon_fill_drag::PolygonFillDrag; -use crate::session::{FillMode, Session}; +use crate::session::Session; use crate::triangle_partition::TrianglePartition; use crate::{EngineError, Result}; /// Corners closer than one step of this grid (per unit of position or UV) count as the same corner const CORNER_GRID_STEPS: f32 = 1e5; -/// Clip-space w below which a vertex counts as behind the camera -const MIN_CLIP_W: f32 = 1e-5; - impl Session { /// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen` pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { @@ -29,73 +27,131 @@ impl Session { self.fill_group_of(hit.tri) } - /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view) + /// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result { - let material = self.fill_material()?; - let mesh = &self.mesh; - let triangle = mesh - .triangles_of(material) - .find(|triangle| uv_corners(mesh, *triangle).is_some_and(|corners| contains(corners, uv))) + let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let size = Vec2::new(gbuf.width as f32, gbuf.height as f32); + let texel = (uv * size).floor(); + let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all()) + .then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied()) + .flatten() + .filter(|triangle| *triangle != NO_TRI) .ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; - self.fill_group_of(triangle as u32) + self.fill_group_of(triangle) } /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { - self.drag_polygon_fill_box(corner, opposite, viewport)?; - Ok(self.end_polygon_fill_box()) + // A scripted box stands alone: it finishes any drag under way, and ends even when it fails + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box(corner, opposite, viewport); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { - self.drag_polygon_fill_box_uv(corner, opposite)?; - Ok(self.end_polygon_fill_box()) + self.end_polygon_fill_box(); + let shown = self.drag_polygon_fill_box_uv(corner, opposite); + let filled = self.end_polygon_fill_box(); + shown.map(|_| filled) } /// Show the fill of a box being dragged between viewport pixels `corner` and `opposite` pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - let viewport = viewport.max(Vec2::ONE); - self.start_polygon_fill_drag(Some(viewport))?; - - let view_proj = self.camera.view_proj(viewport.x / viewport.y); - let mesh = self.mesh.clone(); - let to_screen = |vertex: usize| { - let clip = view_proj * mesh.positions.get(vertex)?.extend(1.0); - let ndc = (clip.w > MIN_CLIP_W).then(|| clip.xy() / clip.w)?; - Some(Vec2::new(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * viewport) - }; - let screen_corners = |triangle: usize| { - let [first, second, third] = mesh.tri(triangle)?; - Some([to_screen(first)?, to_screen(second)?, to_screen(third)?]) - }; - let selected = self.box_selection(&screen_corners, low, high); - self.show_box_fill(selected) + // Whole pixels, as the visibility buffer is rendered at + self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE))) } /// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view) pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { - let (low, high) = box_bounds(corner, opposite)?; - self.start_polygon_fill_drag(None)?; - - let mesh = self.mesh.clone(); - let selected = self.box_selection(&|triangle| uv_corners(&mesh, triangle), low, high); - self.show_box_fill(selected) + self.drag_polygon_fill(corner, opposite, None) } /// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count pub fn end_polygon_fill_box(&mut self) -> usize { let Some(drag) = self.polygon_fill_drag.take() else { return 0 }; - // Quick mask edits keep no history, as with its strokes let filled = drag.filled.len(); + // Quick mask edits keep no history, as with its strokes if filled > 0 && drag.quick_mask_before.is_none() { self.push_history("Polygon fill", drag.before); } filled } + /// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None + fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option) -> Result { + if !corner.is_finite() || !opposite.is_finite() { + return Err(EngineError::Other("the box corners must be finite".into())); + } + + let (low, high) = (corner.min(opposite), corner.max(opposite)); + self.start_polygon_fill_drag(viewport)?; + let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; + + if drag.failed || drag.last_box == Some((low, high)) { + return Ok(drag.filled.len()); + } + + drag.last_box = Some((low, high)); + let selected = self.box_selection(low, high); + self.show_box_fill(selected) + } + + /// Begin a box drag unless one is under way in the same view, texture set and quick mask state; a drag from another one ends first + fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { + let ts = self.ts(); + let quick_mask = self.quick_mask.editing; + // A different view size, set or quick mask state starts a new drag; the old one keeps its fill as one step + if let Some(drag) = &self.polygon_fill_drag { + if drag.ts == ts && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask { + // A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera + if drag.camera != self.camera { + let (points, depth) = self.box_space(viewport); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + (drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None); + } + } + return Ok(()); + } + self.end_polygon_fill_box(); + } + + let material = self.fill_material()?; + let (points, depth) = self.box_space(viewport); + let polygons = match self.tool.fill_mode { + FillMode::Triangle | FillMode::Polygon => None, + FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)), + }; + self.polygon_fill_drag = Some(PolygonFillDrag { + ts, + viewport, + camera: self.camera, + before: self.doc.clone(), + quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()), + points, + depth, + fill_groups: self.fill_partition(material), + polygons, + filled: BTreeSet::new(), + last_box: None, + failed: false, + }); + Ok(()) + } + + /// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees + fn box_space(&self, viewport: Option) -> (Vec>, Option) { + let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) }; + + let view_proj = self.camera.view_proj(size.x / size.y); + let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); + let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32)); + (points, depth) + } + /// The mesh material of the texture set being painted fn fill_material(&self) -> Result { Ok(self.doc.project.texture_set(self.ts())?.material) @@ -123,32 +179,6 @@ impl Session { Ok(triangles.len()) } - /// Begin a box drag unless one is under way; `viewport` is the 3D view's size (None in the 2D view) - fn start_polygon_fill_drag(&mut self, viewport: Option) -> Result<()> { - if self.polygon_fill_drag.is_some() { - return Ok(()); - } - - let material = self.fill_material()?; - let polygons = match self.tool.fill_mode { - FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::::new()), - _ => TrianglePartition::new(&self.mesh, material, polygon_edges), - }; - let depth = viewport - .filter(|_| self.tool.fill_visible_only) - .map(|size| (EyeDepth::render(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32), size)); - self.polygon_fill_drag = Some(PolygonFillDrag { - before: self.doc.clone(), - quick_mask_before: self.quick_mask.editing.then(|| self.quick_mask.masks.clone()), - filled: BTreeSet::new(), - depth, - polygons, - fill_groups: self.fill_partition(material), - failed: false, - }); - Ok(()) - } - /// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden fn shown_mesh(&self) -> Cow<'_, Mesh> { let sets = &self.doc.project.texture_sets; @@ -168,17 +198,28 @@ impl Session { Cow::Owned(mesh) } - /// Triangles the dragged box from `low` to `high` fills, given each triangle's `corners` in the box's space - fn box_selection(&self, corners: &dyn Fn(usize) -> Option<[Vec2; 3]>, low: Vec2, high: Vec2) -> BTreeSet { + /// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode + fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet { let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() }; - let visible = drag.depth.as_ref().map(|(depth, viewport)| visible_triangles(depth, *viewport, low, high)); + let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high)); + let point = |vertex: usize| drag.points.get(vertex).copied().flatten(); + let corners = |triangle: u32| { + let [first, second, third] = self.mesh.tri(triangle as usize)?; + Some([point(first)?, point(second)?, point(third)?]) + }; let hit_test = self.tool.fill_hit_test; + let mut polygon_corners = Vec::new(); let mut groups = BTreeSet::new(); - for polygon in &drag.polygons.groups { + for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups { let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle))); - let triangles: Option> = polygon.iter().map(|triangle| corners(*triangle as usize)).collect(); - if seen && triangles.is_some_and(|triangles| hit_test.selects(&triangles, low, high)) { + if !seen { + continue; + } + + polygon_corners.clear(); + polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle))); + if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) { groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle))); } } @@ -189,17 +230,17 @@ impl Session { /// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed fn show_box_fill(&mut self, selected: BTreeSet) -> Result { let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) }; - if drag.failed || drag.filled == selected { - return Ok(drag.filled.len()); + if drag.filled == selected { + return Ok(selected.len()); } - drag.filled = selected.clone(); + let ts = drag.ts; let previous = std::mem::replace(&mut self.doc, drag.before.clone()); if let Some(masks) = &drag.quick_mask_before { self.quick_mask.masks = masks.clone(); + self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); } - let ts = self.ts(); let painted = if selected.is_empty() { Ok(()) } else { @@ -209,37 +250,23 @@ impl Session { }) }; self.invalidate_changed(&previous); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - // A failed fill is reported once; the rest of the drag fills nothing - if painted.is_err() - && let Some(mut drag) = self.polygon_fill_drag.take() - { - self.restore_before_box(&drag); - drag.failed = true; - drag.filled.clear(); - self.polygon_fill_drag = Some(drag); + // A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing + let selected_count = selected.len(); + if let Some(drag) = self.polygon_fill_drag.as_mut() { + drag.failed = painted.is_err(); + drag.filled = if drag.failed { BTreeSet::new() } else { selected }; } - painted.map(|_| selected.len()) - } - - /// Put back the document and quick mask from before the box `drag` - fn restore_before_box(&mut self, drag: &PolygonFillDrag) { - let previous = std::mem::replace(&mut self.doc, drag.before.clone()); - if let Some(masks) = &drag.quick_mask_before { - self.quick_mask.masks = masks.clone(); - self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); - } - self.invalidate_changed(&previous); + painted.map(|_| selected_count) } } -/// Triangles `depth` (rendered for `viewport`) shows in the viewport pixels from `low` to `high` +/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet { - let pixels_per_point = Vec2::new(depth.width as f32, depth.height as f32) / viewport; - let (first, last) = ((low * pixels_per_point).floor(), (high * pixels_per_point).ceil()); - let columns = first.x.max(0.0) as usize..(last.x as usize).min(depth.width as usize); - let rows = first.y.max(0.0) as usize..(last.y as usize).min(depth.height as usize); + let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport; + let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel); + let columns = pixel_span(low.x, high.x, depth.width); + let rows = pixel_span(low.y, high.y, depth.height); rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start))) .copied() @@ -247,13 +274,11 @@ fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> .collect() } -/// The two corners spanning a box, lowest first -fn box_bounds(corner: Vec2, opposite: Vec2) -> Result<(Vec2, Vec2)> { - if !corner.is_finite() || !opposite.is_finite() { - return Err(EngineError::Other("the box corners must be finite".into())); - } - - Ok((corner.min(opposite), corner.max(opposite))) +/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside) +fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range { + let first = low.floor().clamp(0.0, count as f32) as usize; + let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize; + first..end.max(first) } /// Texture coordinates of `triangle`'s corners @@ -262,13 +287,6 @@ fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> { Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?]) } -/// Whether `point` lies in the triangle with `corners` (either winding) -fn contains(corners: [Vec2; 3], point: Vec2) -> bool { - let side = |edge: usize| (corners[(edge + 1) % 3] - corners[edge]).perp_dot(point - corners[edge]); - let sides = [side(0), side(1), side(2)]; - sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) -} - /// The polygon diagonals of `triangle`: edges the importer added to split a polygon fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> { let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0); @@ -308,7 +326,8 @@ mod tests { use texturecraft_geom::primitives; use crate::fill_hit_test::FillHitTest; - use crate::session::{FillMode, Session, Tool}; + use crate::fill_mode::FillMode; + use crate::session::{Session, Tool}; /// The roughness the test fills paint, to tell filled texels apart const FILL_ROUGHNESS: f32 = 0.9; @@ -446,6 +465,44 @@ mod tests { assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag"); } + #[test] + fn a_failed_box_fill_leaves_no_drag_behind() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let layer = session.selected.remove(&0).unwrap(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on"); + + session.selected.insert(0, layer); + assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again"); + } + + #[test] + fn undo_and_tool_changes_finish_a_box_drag_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished"); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step"); + } + + #[test] + fn an_unmoved_box_keeps_its_fill() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let narrow_box = Vec2::new(0.3, 1.0); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches"); + + // Contained center would select one column, so a second selection would show 8 + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again"); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again"); + } + #[test] fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() { let mut session = fill_session(primitives::udim_plane()); @@ -456,6 +513,82 @@ mod tests { assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002"); } + #[test] + fn a_2d_click_skips_a_triangle_with_collapsed_uvs() { + // A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them + let plane = primitives::plane(2.0, 1); + let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z]; + let mut uvs = vec![Vec2::ZERO; 3]; + positions.extend(&plane.positions); + uvs.extend(&plane.uvs); + let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect(); + let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()); + + assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1); + session.update(); + assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one"); + } + + #[test] + fn a_failing_drag_reports_once_and_records_nothing() { + let mut session = fill_session(primitives::plane(2.0, 4)); + let history = session.history_labels().len(); + session.selected.clear(); + + assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err()); + assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing"); + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(session.history_labels().len(), history); + } + + #[test] + fn an_edit_during_a_drag_records_the_fill_first() { + let mut session = fill_session(primitives::plane(2.0, 4)); + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(); + + let layers = session.doc.project.layers.len(); + crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + assert!(session.polygon_fill_drag.is_none()); + let labels = session.history_labels(); + assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}"); + + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(); + assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer"); + } + + #[test] + fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() { + let mut session = fill_session(primitives::cube(1.0)); + let center = (session.viewport * 0.5).floor(); + + assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0); + } + + #[test] + fn a_camera_move_mid_drag_keeps_one_drag() { + let mut session = fill_session(primitives::cube(1.0)); + let viewport = session.viewport; + let history = session.history_labels().len(); + + let (corner, opposite) = (viewport * 0.4, viewport * 0.6); + + let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.camera.zoom(0.5); + let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap(); + session.end_polygon_fill_box(); + + assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera"); + assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it"); + } + + #[test] + fn pixel_spans_include_both_edges_and_nothing_outside() { + assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel"); + assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel"); + assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel"); + assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100); + } + #[test] fn a_2d_click_fills_the_triangle_under_it() { let mut session = fill_session(primitives::plane(2.0, 1)); diff --git a/crates/engine/src/polygon_fill_drag.rs b/crates/engine/src/polygon_fill_drag.rs index 4a7bc104..f4457e55 100644 --- a/crates/engine/src/polygon_fill_drag.rs +++ b/crates/engine/src/polygon_fill_drag.rs @@ -2,6 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::Vec2; use texturecraft_paint::EyeDepth; use texturecraft_texel::TileImage; @@ -11,18 +12,28 @@ use crate::triangle_partition::TrianglePartition; /// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends pub(crate) struct PolygonFillDrag { + /// The texture set it fills + pub ts: usize, + /// The 3D view's size in pixels, or None for a drag in the 2D view + pub viewport: Option, + /// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with + pub camera: OrbitCamera, /// The document before the drag, refilled each time the selection changes pub before: Document, /// The quick mask's coverage before the drag, when the drag paints the quick mask pub quick_mask_before: Option>, - /// The triangles filled so far - pub filled: BTreeSet, - /// What the camera sees and the viewport size it was rendered for (3D view, visible polygons only) - pub depth: Option<(EyeDepth, Vec2)>, - /// The polygons the box tests - pub polygons: TrianglePartition, + /// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view + pub points: Vec>, + /// What the camera sees (3D view, visible polygons only) + pub depth: Option, /// What the fill mode fills together pub fill_groups: TrianglePartition, + /// The polygons the box tests, when they differ from the fill groups + pub polygons: Option, + /// The triangles filled so far + pub filled: BTreeSet, + /// The box last shown, lowest corner first: an unmoved box isn't selected again + pub last_box: Option<(Vec2, Vec2)>, /// The fill failed (reported once): the rest of the drag fills nothing pub failed: bool, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index c5b55649..c6b7c469 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; use texturecraft_texel::DilationMap; +use crate::fill_mode::FillMode; use crate::{EngineError, Result}; /// Padding (texels) applied to composites for display. @@ -160,17 +161,6 @@ impl ViewMode { } } -/// Polygon fill granularity. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum FillMode { - #[default] - Triangle, - /// The source polygon (quad or n-gon) the importer split into triangles - Polygon, - UvIsland, - Mesh, -} - /// A screen-pinned image for the Projection tool (a stencil). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { @@ -506,22 +496,24 @@ impl Session { self.edit_merging(label, self.merge_edits, f) } - /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the - /// same label (a drag in the viewport is one step however many updates it makes). - pub fn edit_merging(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result) -> Result { + /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes). + pub fn edit_merging(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result) -> Result { + // A box fill under way becomes its own step first, so this edit isn't written over or folded into it + self.end_polygon_fill_box(); + let before = self.doc.clone(); - let result = f(self).and_then(|v| match self.doc.project.instance_cycle() { + let result = change(self).and_then(|value| match self.doc.project.instance_cycle() { Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), - None => Ok(v), + None => Ok(value), }); match result { - Ok(v) => { + Ok(value) => { self.record(label, before, merge); - Ok(v) + Ok(value) } - Err(e) => { + Err(error) => { self.doc = before; - Err(e) + Err(error) } } } @@ -642,25 +634,29 @@ impl Session { } pub fn undo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.redo.push((label.clone(), now)); + + let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.redo.push((label.clone(), current)); self.sync_images(); Ok(label) } pub fn redo(&mut self) -> Result { + // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + self.end_polygon_fill_box(); self.stop_path_edit(); - let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; - let now = std::mem::replace(&mut self.doc, doc); - self.after_history(&now); - self.undo.push((label.clone(), now)); + + let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; + let current = std::mem::replace(&mut self.doc, restored); + self.after_history(¤t); + self.undo.push((label.clone(), current)); self.sync_images(); Ok(label) } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index ba7f0f9b..a3f92bba 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -8,7 +8,8 @@ use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; use crate::fill_hit_test::FillHitTest; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::fill_mode::FillMode; +use crate::session::{CloneFrom, CloneSource, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -103,11 +104,13 @@ pub fn specs() -> Vec { ] } -pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result { - s.cancel_stroke(); - s.tool.tool = t; - s.revision = s.revision.wrapping_add(1); - Ok(json!({ "tool": t.id() })) +pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result { + session.cancel_stroke(); + // A box fill under way keeps what it filled as one undo step + session.end_polygon_fill_box(); + session.tool.tool = tool; + session.revision = session.revision.wrapping_add(1); + Ok(json!({ "tool": tool.id() })) } fn select(s: &mut Session, p: &Value) -> Result { @@ -337,26 +340,27 @@ fn clone_source(s: &mut Session, p: &Value) -> Result { Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null)) } -fn fill_mode(s: &mut Session, p: &Value) -> Result { - s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") { +fn fill_mode(session: &mut Session, params: &Value) -> Result { + session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") { "triangle" => FillMode::Triangle, "polygon" => FillMode::Polygon, "uvIsland" | "island" => FillMode::UvIsland, "mesh" => FillMode::Mesh, other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))), }; + Ok(Value::Null) } -fn fill_selection(s: &mut Session, p: &Value) -> Result { - match strp(p, "hitTest") { +fn fill_selection(session: &mut Session, params: &Value) -> Result { + match strp(params, "hitTest") { None => {} - Some("intersection") => s.tool.fill_hit_test = FillHitTest::Intersection, - Some("containedCenter") => s.tool.fill_hit_test = FillHitTest::ContainedCenter, + Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection, + Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter, Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))), } - if let Some(visible_only) = boolp(p, "visibleOnly") { - s.tool.fill_visible_only = visible_only; + if let Some(visible_only) = boolp(params, "visibleOnly") { + session.tool.fill_visible_only = visible_only; } Ok(Value::Null) @@ -402,38 +406,42 @@ fn stroke(s: &mut Session, p: &Value) -> Result { Ok(json!({ "stamps": stamps })) } -fn click(s: &mut Session, p: &Value) -> Result { - if s.tool.tool == Tool::PolygonFill - && let Some(triangles) = polygon_fill_click(s, p)? +fn click(session: &mut Session, params: &Value) -> Result { + if session.tool.tool == Tool::PolygonFill + && let Some(triangles) = polygon_fill_click(session, params)? { - s.update(); + session.update(); return Ok(json!({ "triangles": triangles })); } - let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) }; let point = Vec2::new(x, y); - let viewport = viewport_of(s, p); - let out = match s.tool.tool { - Tool::PolygonFill => json!({ "triangles": s.polygon_fill(point, viewport)? }), + let viewport = viewport_of(session, params); + let out = match session.tool.tool { + Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }), Tool::ColorPicker => { - let picked = s.color_pick(point, viewport)?; + let picked = session.color_pick(point, viewport)?; json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>()) } - Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, point, viewport)?, - _ => json!({ "stamps": s.stroke_points(&[point], viewport)? }), + Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?, + _ => json!({ "stamps": session.stroke_points(&[point], viewport)? }), }; - s.update(); + session.update(); Ok(out) } /// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point -fn polygon_fill_click(s: &mut Session, p: &Value) -> Result> { - let screen_box = (f32p(p, "x0"), f32p(p, "y0"), f32p(p, "x1"), f32p(p, "y1")); - let filled = match (pair(p, "uv0"), pair(p, "uv1"), pair(p, "uv"), screen_box) { - (Some(corner), Some(opposite), ..) => s.polygon_fill_box_uv(corner.into(), opposite.into())?, - (_, _, Some(uv), _) => s.polygon_fill_uv(uv.into())?, - (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => s.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(s, p))?, +fn polygon_fill_click(session: &mut Session, params: &Value) -> Result> { + let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1")); + let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some()); + let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) { + (Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?, + _ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")), + (_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?, + _ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")), + (.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?, + _ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")), _ => return Ok(None), }; diff --git a/crates/engine/src/triangle_partition.rs b/crates/engine/src/triangle_partition.rs index 1364fe69..bd137e35 100644 --- a/crates/engine/src/triangle_partition.rs +++ b/crates/engine/src/triangle_partition.rs @@ -1,6 +1,7 @@ //! Triangles of one material grouped into the pieces polygon fill selects and fills. -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; +use std::hash::Hash; use texturecraft_geom::Mesh; @@ -14,12 +15,15 @@ pub struct TrianglePartition { impl TrianglePartition { /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both - pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + // Each triangle's edges once, in mesh order so the groups come out the same every time let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); - let mut by_edge: BTreeMap> = BTreeMap::new(); - for &triangle in &triangles { - for edge in edges(mesh, triangle as usize) { - by_edge.entry(edge).or_default().push(triangle); + let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); + let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); + let mut by_edge: HashMap> = HashMap::new(); + for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { + for edge in triangle_edges { + by_edge.entry(edge.clone()).or_default().push(*triangle); } } @@ -29,12 +33,14 @@ impl TrianglePartition { if group_of.contains_key(&start) { continue; } + let mut members = Vec::new(); let mut stack = vec![start]; group_of.insert(start, groups.len()); while let Some(triangle) = stack.pop() { members.push(triangle); - for neighbour in edges(mesh, triangle as usize).iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { + let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.get(edge).into_iter().flatten()) { if !group_of.contains_key(neighbour) { group_of.insert(*neighbour, groups.len()); stack.push(*neighbour); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..307ccd7f 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -29,4 +29,4 @@ pub use path::{Lasso, spline}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; -pub use visibility::EyeDepth; +pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index e914d297..c2921979 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -2,7 +2,7 @@ //! rendered once at the start of a stroke. use rayon::prelude::*; -use texturecraft_geom::glam::{Mat4, Vec3, Vec4}; +use texturecraft_geom::glam::{Mat4, Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; @@ -11,7 +11,7 @@ const BAND: usize = 16; const MAX_SIZE: u32 = 4096; /// Clip-space w below which a vertex counts as behind the camera. -const MIN_CLIP_W: f32 = 1e-5; +pub const MIN_CLIP_W: f32 = 1e-5; /// Screen area (pixels squared) below which a triangle is skipped as degenerate. const MIN_SCREEN_AREA: f32 = 1e-9; @@ -30,28 +30,38 @@ pub struct EyeDepth { pub view_proj: Mat4, pub eye: Vec3, pub dist: Vec, - /// The nearest triangle per screen pixel ([`NO_TRI`] where empty). + /// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`]. pub triangle: Vec, /// Tolerance in world units (≈ 0.4% of the scene radius). pub bias: f32, } +/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera. +pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option { + let clip = view_proj * position.extend(1.0); + (clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size) +} + impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]). + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`]. pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, false) + } + + /// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`]. + pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { + Self::rasterize(mesh, camera, width, height, true) + } + + /// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set. + fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth { let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); - let view_proj = camera.view_proj(width as f32 / height as f32); + let size = Vec2::new(width as f32, height as f32); + let view_proj = camera.view_proj(size.x / size.y); let eye = camera.eye(); // Project every vertex once - let screen: Vec> = mesh - .positions - .iter() - .map(|position| { - let clip: Vec4 = view_proj * position.extend(1.0); - (clip.w > MIN_CLIP_W).then(|| ((clip.x / clip.w * 0.5 + 0.5) * width as f32, (0.5 - clip.y / clip.w * 0.5) * height as f32)) - }) - .collect(); + let screen: Vec> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); let vertex_distance: Vec = mesh.positions.iter().map(|position| position.distance(eye)).collect(); // Bin each triangle into the bands of rows it covers @@ -60,8 +70,8 @@ impl EyeDepth { let Some([first, second, third]) = mesh.tri(triangle) else { continue }; let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue }; - let top = first.1.min(second.1).min(third.1).floor().max(0.0); - let bottom = first.1.max(second.1).max(third.1).ceil().min(height as f32); + let top = first.y.min(second.y).min(third.y).floor().max(0.0); + let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y); if bottom <= top || !top.is_finite() || !bottom.is_finite() { continue; } @@ -72,9 +82,11 @@ impl EyeDepth { } let mut dist = vec![f32::MAX; (width * height) as usize]; - let mut triangle = vec![NO_TRI; (width * height) as usize]; + let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() }; let band_len = BAND * width as usize; - dist.par_chunks_mut(band_len).zip(triangle.par_chunks_mut(band_len)).enumerate().for_each(|(band, (band_dist, band_triangles))| { + let mut triangle_bands: Vec> = triangle.chunks_mut(band_len).map(Some).collect(); + triangle_bands.resize_with(dist.len().div_ceil(band_len), || None); + dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| { let first_row = band * BAND; let row_count = band_dist.len() / width as usize; for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) { @@ -84,24 +96,22 @@ impl EyeDepth { else { continue; }; - let corner_distance = corners.map(|vertex| vertex_distance[vertex]); - let area = - (second_point.0 - first_point.0) * (third_point.1 - first_point.1) - (second_point.1 - first_point.1) * (third_point.0 - first_point.0); + + let corner_distance = corners.map(|vertex| vertex_distance.get(vertex).copied().unwrap_or(f32::MAX)); + let area = (*second_point - *first_point).perp_dot(*third_point - *first_point); if area.abs() < MIN_SCREEN_AREA { continue; } - let left = first_point.0.min(second_point.0).min(third_point.0).floor().max(0.0) as usize; - let right = (first_point.0.max(second_point.0).max(third_point.0).ceil().min(width as f32)) as usize; - let top = (first_point.1.min(second_point.1).min(third_point.1).floor().max(first_row as f32)) as usize; - let bottom = (first_point.1.max(second_point.1).max(third_point.1).ceil().min((first_row + row_count) as f32)) as usize; + let low = first_point.min(*second_point).min(*third_point).floor(); + let high = first_point.max(*second_point).max(*third_point).ceil(); + let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize)); + let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize); for row in top.max(first_row)..bottom { - for column in left..right.min(width as usize) { - let (sample_x, sample_y) = (column as f32 + 0.5, row as f32 + 0.5); - let first_weight = - ((second_point.0 - sample_x) * (third_point.1 - sample_y) - (second_point.1 - sample_y) * (third_point.0 - sample_x)) / area; - let second_weight = - ((third_point.0 - sample_x) * (first_point.1 - sample_y) - (third_point.1 - sample_y) * (first_point.0 - sample_x)) / area; + for column in left..right { + let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5); + let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area; + let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area; let third_weight = 1.0 - first_weight - second_weight; if first_weight < -EDGE_TOLERANCE || second_weight < -EDGE_TOLERANCE || third_weight < -EDGE_TOLERANCE { continue; @@ -113,7 +123,7 @@ impl EyeDepth { && distance < *slot { *slot = distance; - if let Some(nearest) = band_triangles.get_mut(at) { + if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) { *nearest = candidate; } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 91f816e9..491aed10 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -214,13 +214,13 @@ fn shade(app: &TextureCraftApp) -> Shade { let set_index = app.session.ts(); let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles - let polygon_fill = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; + let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, view_mode, channel, - wireframe: app.ui.uv_wireframe || polygon_fill, - wireframe_3d: app.ui.wireframe_3d || polygon_fill, + wireframe: app.ui.uv_wireframe || polygon_fill_tool, + wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool, ..Shade::from_project(&app.session.doc.project) } } @@ -1040,7 +1040,12 @@ fn polygon_fill_input( let pointer = ui.input(|input| input.pointer.latest_pos()); let (filled, dragged_box) = match (origin, pointer) { _ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None), - (Some(origin), Some(pointer)) if released => (Some(drag_box(&mut app.session, origin, pointer).map(|_| app.session.end_polygon_fill_box())), None), + (Some(origin), Some(pointer)) if released => { + // The drag ends on release even when its last move failed + let shown = drag_box(&mut app.session, origin, pointer); + let filled = app.session.end_polygon_fill_box(); + (Some(shown.map(|_| filled)), None) + } (Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))), _ => (None, None), }; diff --git a/crates/ui-egui/tests/polygon_fill.rs b/crates/ui-egui/tests/polygon_fill.rs index dc007035..313ad184 100644 --- a/crates/ui-egui/tests/polygon_fill.rs +++ b/crates/ui-egui/tests/polygon_fill.rs @@ -27,8 +27,9 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { harness.run_steps(1); } + // Only the release frame runs, so the release itself must finish the drag harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - harness.run_steps(3); + harness.run_steps(1); } /// Press and release the primary button at `at` From 695a3eed910226ef6e815df4a47c8de5e6de2667 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:27 +0000 Subject: [PATCH 064/275] Shift+click paints straight lines in the 2D view The 2D view keeps the end of the last finished stroke in texture coordinates, with its texture set, so a line drawn after zooming or panning joins the same texels, and previews the line while Shift is held, as the 3D view does. A cancelled stroke (Escape) leaves the line start where it was. Session::continue_stroke_uv stamps a long segment in batches of 4096 up to 1 << 17 stamps instead of stopping at 4096, keeps its carry within one step, and seeds stamps from the stroke's running count (UvStrokeState) so noise alphas don't repeat every pointer sample. The line preview is clipped to the view, keeping its dash phase. Refs #306 --- crates/engine/src/lib.rs | 1 + crates/engine/src/painting.rs | 83 +++++++----- crates/engine/src/session.rs | 4 +- crates/engine/src/uv_stroke_state.rs | 14 ++ crates/engine/tests/uv_strokes.rs | 77 +++++++++++ crates/ui-egui/src/lib.rs | 25 +++- crates/ui-egui/src/viewport.rs | 171 ++++++++++++++++++----- crates/ui-egui/tests/shift_lines_2d.rs | 180 +++++++++++++++++++++++++ 8 files changed, 482 insertions(+), 73 deletions(-) create mode 100644 crates/engine/src/uv_stroke_state.rs create mode 100644 crates/engine/tests/uv_strokes.rs create mode 100644 crates/ui-egui/tests/shift_lines_2d.rs diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..a6c444e0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,6 +45,7 @@ pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; pub mod tool_cmds; +mod uv_stroke_state; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..c9c19085 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -12,8 +12,18 @@ use texturecraft_paint::{ }; use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool}; +use crate::uv_stroke_state::UvStrokeState; use crate::{EngineError, Result}; +/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. +const MIN_UV_STAMP_STEP: f32 = 1e-5; + +/// 2D view stamps rasterized together, bounding the memory of one batch. +const UV_STAMP_BATCH: usize = 4096; + +/// Most stamps one 2D view sample adds: a line across the texture at the finest brush (about 71k) fits, a hostile coordinate stays bounded. +const MAX_UV_STAMPS_PER_SAMPLE: usize = 1 << 17; + impl Session { /// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change). fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc { @@ -234,7 +244,7 @@ impl Session { stroke, canvas, depth, - uv: uv_mode.then_some((None, 0.0)), + uv: uv_mode.then(UvStrokeState::default), camera: self.camera, viewport, values, @@ -314,40 +324,45 @@ impl Session { /// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square. pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) { - let Some(st) = self.stroke.as_mut() else { return }; - let Some((last, carry)) = st.uv.as_mut() else { return }; - let Some(cache) = self.caches.get_mut(st.ts) else { return }; - let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; - let step = (b.spacing * 2.0 * radius).max(1e-5); - let mut points = Vec::new(); - match *last { - None => points.push(uv), - Some(prev) => { - let seg = uv - prev; - let len = seg.length(); - let mut t = step - *carry; - while t <= len && points.len() < 4096 { - points.push(prev + seg * (t / len.max(1e-9))); - t += step; - } - *carry = len - (t - step); - } - } - // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down). - let angle = match *last { - Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0, - _ => b.angle, + let Some(active) = self.stroke.as_mut() else { return }; + let Some(progress) = active.uv.as_mut() else { return }; + let Some(cache) = self.caches.get_mut(active.ts) else { return }; + let settings = &active.stroke.settings; + let pressure = pressure.clamp(0.0, 1.0); + let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 }; + let radius = settings.size * 2.0 * size_scale; + let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP); + + // Follow path: turn the stamp with the stroke direction (y up on screen, v grows down) + let angle = match progress.last { + Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0, + _ => settings.angle, }; - *last = Some(uv); - let n0 = st.stroke.stamps.len() as u32; - let stamps: Vec = points - .iter() - .enumerate() - .map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 }) - .collect(); - texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps); + + // The first sample is one stamp; a later one stamps every `step` along the segment from the previous + let (start, segment, mut distance) = match progress.last.replace(uv) { + None => (uv, Vec2::ZERO, 0.0), + Some(previous) => (previous, uv - previous, step - progress.carry), + }; + let length = segment.length(); + let shape = Self::shape(&self.images, settings); + let mut stamped = 0; + while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { + let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped); + let mut batch = Vec::new(); + while distance <= length && batch.len() < batch_size { + let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); + let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + distance += step; + } + stamped += batch.len(); + texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); + } + + // At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards + progress.carry = (length - (distance - step)).min(step); + progress.stamps = progress.stamps.wrapping_add(stamped as u32); self.stroke_painted(); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..137affdc 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -291,8 +291,8 @@ pub(crate) struct ActiveStroke { pub canvas: StrokeCanvas, /// Camera visibility for 3D strokes (None for strokes in the 2D view). pub depth: Option>, - /// 2D view strokes: last UV point and the distance carried to the next stamp. - pub uv: Option<(Option, f32)>, + /// 2D view strokes: where the stroke is between samples. + pub uv: Option, pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, diff --git a/crates/engine/src/uv_stroke_state.rs b/crates/engine/src/uv_stroke_state.rs new file mode 100644 index 00000000..5ce5ae2f --- /dev/null +++ b/crates/engine/src/uv_stroke_state.rs @@ -0,0 +1,14 @@ +//! Where a stroke in the 2D view is between pointer samples. + +use texturecraft_geom::glam::Vec2; + +/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far. +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct UvStrokeState { + /// The last sample's texture coordinates (None before the first sample). + pub last: Option, + /// Distance from the last stamp to the last sample, at most one stamp step. + pub carry: f32, + /// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample. + pub stamps: u32, +} diff --git a/crates/engine/tests/uv_strokes.rs b/crates/engine/tests/uv_strokes.rs new file mode 100644 index 00000000..b17fb0bf --- /dev/null +++ b/crates/engine/tests/uv_strokes.rs @@ -0,0 +1,77 @@ +//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// Texture size: 1e-4 UV is 0.0256 texels +const RESOLUTION: u32 = 256; + +/// A sphere project painting red with `brush` settings (the UI's 0–100 scales) +fn red_brush_session(brush: serde_json::Value) -> Session { + let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &brush).unwrap(); + session +} + +/// The composite base color at texel (`x`, `y`) +fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] { + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +/// Whether the composite base color at (`u`, `v`) is the painted red +fn red_at(session: &Session, u: f32, v: f32) -> bool { + let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +#[test] +fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() { + // 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap(); + + for u in [0.1, 0.5, 0.9] { + assert!(red_at(&session, u, 0.5), "painted at u = {u}"); + } +} + +#[test] +fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() { + // 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off the texture, near u = -6.9 + let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap(); + + assert!(red_at(&session, 0.55, 0.5), "the last segment is painted"); + assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start"); +} + +#[test] +fn each_sample_of_a_stroke_stamps_new_noise() { + // A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5 + let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"})); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap(); + + let patch = |centre_x: u32| -> Vec<[f32; 3]> { + (centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect() + }; + let first_stamp = patch(64); + assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted"); + assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise"); +} + +#[test] +fn a_hostile_segment_stays_bounded() { + // The finest brush the settings allow: 2e-5 UV between stamps + let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0})); + + let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]})); + + assert!(result.is_ok(), "{result:?}"); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..15d22ac5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -110,6 +110,8 @@ pub struct TextureCraftApp { pub profiler: profile::Profiler, /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. pub last_paint_point: Option, + /// Where the last finished 2D view stroke ended: its texture set and texture coordinates (so zoom and pan keep it), for Shift+click straight lines. + pub last_paint_uv: Option<(usize, texturecraft_engine::geom::glam::Vec2)>, /// The decal layer the next click in the 3D view places. pub placing_decal: Option, /// The Properties popup a right click in a view opens. @@ -133,19 +135,23 @@ pub struct TextureCraftApp { } impl TextureCraftApp { + /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + + // The first run speaks the OS (or browser) language + let ui = cc.storage.and_then(|storage| eframe::get_value::(storage, "ui")).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + let mut app = TextureCraftApp { camera_glide: None, session, @@ -166,6 +172,7 @@ impl TextureCraftApp { brushes: None, render: render_mode::RenderView::default(), last_paint_point: None, + last_paint_uv: None, placing_decal: None, properties_popup: None, render_state: cc.wgpu_render_state.clone(), @@ -181,17 +188,21 @@ impl TextureCraftApp { app.ui.windows.new_project = false; i18n::set_language(&app.ui.prefs.language); export_templates::load_library(&mut app, cc.storage); + #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } + let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } + app } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..cb1c9bc1 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -165,6 +165,18 @@ const UV_VIEW_MAX_ZOOM: f32 = 40.0; /// UV zoom change per point of mouse wheel, as a fraction of the zoom const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; +/// Dash length of the straight-line preview, in points +const RUBBER_BAND_DASH: f32 = 6.0; + +/// Gap between the straight-line preview's dashes, in points +const RUBBER_BAND_GAP: f32 = 4.0; + +/// Opacity of the UV tile outlines in the 2D view +const UV_TILE_OUTLINE_ALPHA: u8 = 40; + +/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible +const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; + /// The 2D view's width when the split divider is at `divider_x` fn uv_view_width(full: Rect, divider_x: f32) -> f32 { (full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0) @@ -996,11 +1008,43 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons } } -/// Dashed preview of a straight segment. +/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); + let Some(visible) = visible_dashes(rect, from, to) else { return }; + let painter = ui.painter_at(rect); + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + } +} + +/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place. +fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> { + let direction = to - from; + let length = direction.length(); + if length == 0.0 { + return rect.contains(from).then_some([from, to]); + } + + // Clip the segment's parameter range against each axis's slab + let (mut enter, mut exit) = (0.0_f32, 1.0_f32); + for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] { + if delta == 0.0 { + if origin < low || origin > high { + return None; + } + continue; + } + let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta); + enter = enter.max(at_low.min(at_high)); + exit = exit.min(at_low.max(at_high)); + } + if enter > exit { + return None; + } + + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let start = (enter * length / period).floor() * period / length; + Some([from + direction * start, from + direction * exit]) } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -1148,11 +1192,12 @@ fn pen_pressure(ui: &Ui) -> f32 { } } +/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture. fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let tokens = Tokens::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let alt = ui.input(|input| input.modifiers.alt); + let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); let adjusting = brush_drag(app, ui, &response); // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor @@ -1216,29 +1261,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { - let pressure = pen_pressure(ui); - if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { - if let Some(pointer) = response.interact_pointer_pos() - && let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure) - { - app.toast(error.to_string(), true); - } - if response.clicked_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } - } else if response.dragged_by(PointerButton::Primary) - && app.session.stroke_active() - && let Some(pointer) = response.interact_pointer_pos() - { - app.session.continue_stroke_uv(to_uv(pointer), pressure); - } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + paint_2d_input(app, ui, &response, shift, &to_uv); } if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; @@ -1259,7 +1282,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); let set = app.session.doc.project.texture_sets.get(ts); - let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside); + let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside); match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) { Some((texture_set, grid)) => { for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) { @@ -1285,10 +1308,22 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &response, true, show); } + // Shift: preview the straight line Shift+click paints from the last stroke + if painting + && shift + && !path_tool + && brush_tool(app.session.tool.tool) + && let Some((last_set, from)) = app.last_paint_uv + && last_set == ts + && let Some(hover) = response.hover_pos() + { + rubber_band(ui, rect, to_screen(from.x, from.y), hover); + } + if app.ui.mode == crate::state::Mode::Baking { bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0)); if bake_paint_on && let Some(hover) = response.hover_pos() { - let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0); + let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS); painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200))); } } @@ -1300,6 +1335,51 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text); } +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. +fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { + let pressure = pen_pressure(ui); + let set = app.session.ts(); + // Where the stroke under way is; it becomes the line start only when the stroke finishes + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); + + if resp.drag_started_by(PointerButton::Primary) || resp.clicked_by(PointerButton::Primary) { + // A line starts only from a point on the same texture set + let line_start = match app.last_paint_uv { + Some((last_set, last_uv)) if shift && last_set == set => Some(last_uv), + _ => None, + }; + if let Some(pointer) = resp.interact_pointer_pos() { + let uv = to_uv(pointer); + match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { + Ok(()) => { + if line_start.is_some() { + app.session.continue_stroke_uv(uv, pressure); + } + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + Err(error) => app.toast(error.to_string(), true), + } + } + } else if resp.dragged_by(PointerButton::Primary) + && app.session.stroke_active() + && let Some(pointer) = resp.interact_pointer_pos() + { + let uv = to_uv(pointer); + app.session.continue_stroke_uv(uv, pressure); + ui.data_mut(|data| data.insert_temp(stroke_end, (set, uv))); + } + + // Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here + if resp.clicked_by(PointerButton::Primary) || resp.drag_stopped_by(PointerButton::Primary) { + let finishing = app.session.stroke_active(); + match app.session.end_stroke() { + Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)), + Ok(()) => {} + Err(error) => app.toast(error.to_string(), true), + } + } +} + /// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke). fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8)); @@ -1351,3 +1431,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t }; painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); } + +#[cfg(test)] +mod tests { + use super::*; + + const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); + const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + + #[test] + fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() { + let far_start = pos2(-10_003.0, 50.0); + + let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap(); + + assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}"); + let periods = (start.x - far_start.x) / DASH_PERIOD; + assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}"); + assert_eq!(end, pos2(50.0, 50.0)); + } + + #[test] + fn a_segment_inside_the_view_is_kept_whole() { + assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)])); + } + + #[test] + fn a_segment_outside_the_view_draws_nothing() { + assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None); + assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None); + } +} diff --git a/crates/ui-egui/tests/shift_lines_2d.rs b/crates/ui-egui/tests/shift_lines_2d.rs new file mode 100644 index 00000000..5b87f409 --- /dev/null +++ b/crates/ui-egui/tests/shift_lines_2d.rs @@ -0,0 +1,180 @@ +//! Shift+click in the 2D view paints a straight line from where the last stroke ended, as in the 3D view + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// The first click, on the sample's texture in the 2D view +const FIRST_CLICK: Pos2 = pos2(700.0, 420.0); + +/// The Shift+click, on the texture of both of the sample's texture sets +const SECOND_CLICK: Pos2 = pos2(900.0, 520.0); + +/// Start of a drag cancelled with Escape, well away from the line between the two clicks +const CANCELLED_DRAG_FROM: Pos2 = pos2(760.0, 700.0); + +/// End of the cancelled drag +const CANCELLED_DRAG_TO: Pos2 = pos2(820.0, 700.0); + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// How far beside the line the unpainted check looks, in brush radii +const BESIDE_LINE_IN_RADII: f32 = 3.0; + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// Press at `from`, drag to `to`, press Escape and release: the stroke is cancelled +fn cancelled_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!harness.state().session.stroke_active(), "Escape cancelled the stroke"); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// Alpha added between two snapshots +fn added(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// Whether `paint` holds visible alpha at `texel` +fn painted_at(paint: &[f32], width: u32, texel: Vec2) -> bool { + let index = texel.y.round() as usize * width as usize + texel.x.round() as usize; + paint[index] > PAINTED_ALPHA +} + +/// The brush radius in texels: a 2D view stamp's radius is twice the brush size in UV units +fn brush_radius_in_texels(harness: &Harness<'_, TextureCraftApp>, width: u32) -> f32 { + harness.state().session.tool.brush.size * 2.0 * width as f32 +} + +/// Click, run `between` (zoom or pan), Shift+click; assert one straight stroke joins both dabs +fn assert_shift_click_draws_a_line(between: impl FnOnce(&mut Harness<'_, TextureCraftApp>)) { + let mut harness = uv_view_app(); + let (blank, width) = alpha(&harness); + click(&mut harness, FIRST_CLICK, false); + let (first_dab, _) = alpha(&harness); + let start = centre(&added(&blank, &first_dab), width); + + between(&mut harness); + harness.run_steps(2); + let steps_before = harness.state().session.history_labels().len(); + click(&mut harness, SECOND_CLICK, true); + assert_eq!(harness.state().session.history_labels().len(), steps_before + 1, "the line is one undo step"); + let (with_line, _) = alpha(&harness); + let line = added(&first_dab, &with_line); + + // A plain click at the same point finds where the line should end + harness.state_mut().session.undo().unwrap(); + click(&mut harness, SECOND_CLICK, false); + let (with_dab, _) = alpha(&harness); + let end = centre(&added(&first_dab, &with_dab), width); + + let middle = (start + end) * 0.5; + let across = (end - start).perp().normalize() * brush_radius_in_texels(&harness, width) * BESIDE_LINE_IN_RADII; + assert!(painted_at(&line, width, middle), "the line passes halfway between {start} and {end}"); + assert!(!painted_at(&line, width, middle + across), "nothing is painted beside the line"); +} + +#[test] +fn shift_click_paints_a_straight_line_from_the_last_stroke() { + assert_shift_click_draws_a_line(|_| {}); +} + +#[test] +fn the_line_joins_the_same_texture_points_after_zoom_and_pan() { + assert_shift_click_draws_a_line(|harness| { + let ui_state = &mut harness.state_mut().ui; + ui_state.uv_zoom *= 1.5; + ui_state.uv_pan = [0.2, -0.1]; + }); +} + +/// Shift+click at the second point; assert it painted the same dot a plain click there paints +fn assert_shift_click_paints_only_a_dot(harness: &mut Harness<'_, TextureCraftApp>) { + let (before, _) = alpha(harness); + click(harness, SECOND_CLICK, true); + let (after_shift_click, _) = alpha(harness); + let shift_click_alpha: f32 = added(&before, &after_shift_click).iter().sum(); + + harness.state_mut().session.undo().unwrap(); + click(harness, SECOND_CLICK, false); + let (after_click, _) = alpha(harness); + let click_alpha: f32 = added(&before, &after_click).iter().sum(); + + assert!(click_alpha > 1.0, "the plain click painted: {click_alpha}"); + assert!((shift_click_alpha - click_alpha).abs() < click_alpha * 0.01, "Shift+click paints only a dot: {shift_click_alpha} vs {click_alpha}"); +} + +#[test] +fn shift_click_without_a_previous_stroke_paints_a_dot() { + assert_shift_click_paints_only_a_dot(&mut uv_view_app()); +} + +#[test] +fn a_line_does_not_start_from_a_point_on_another_texture_set() { + let mut harness = uv_view_app(); + click(&mut harness, FIRST_CLICK, false); + + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + + assert_shift_click_paints_only_a_dot(&mut harness); +} + +#[test] +fn a_stroke_cancelled_with_escape_leaves_the_line_start_where_it_was() { + assert_shift_click_draws_a_line(|harness| cancelled_drag(harness, CANCELLED_DRAG_FROM, CANCELLED_DRAG_TO)); +} From cfe837b86cb83b60c4224aa04f1fb8cf1d22b4cf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:22:20 +0000 Subject: [PATCH 065/275] Import baked maps when creating a project New project > Advanced settings gets the project's normal map format and Import baked maps: Add lists image files, and Create imports them with the new textureSet.meshMap.import command, which sets each file as the mesh map of the texture set and slot its name names (Body_ambient_occlusion.png, Body_normal.1001.png) in one undo step and reports the files it left out. --- crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 2 + crates/engine/src/meshmap_cmds.rs | 43 ++--- crates/engine/src/meshmap_file_name.rs | 153 +++++++++++++++++ crates/engine/src/meshmap_import_cmds.rs | 79 +++++++++ crates/engine/src/resource_cmds.rs | 35 ++-- crates/engine/tests/meshmap_import.rs | 136 +++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 6 + crates/ui-egui/src/i18n/de.rs | 6 + crates/ui-egui/src/i18n/es.rs | 6 + crates/ui-egui/src/i18n/fr.rs | 6 + crates/ui-egui/src/i18n/it.rs | 6 + crates/ui-egui/src/i18n/ja.rs | 6 + crates/ui-egui/src/i18n/ko.rs | 6 + crates/ui-egui/src/i18n/pt_br.rs | 6 + crates/ui-egui/src/i18n/zh_hans.rs | 6 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/new_project_advanced.rs | 155 ++++++++++++++++++ crates/ui-egui/src/state.rs | 10 +- crates/ui-egui/src/windows.rs | 7 +- .../ui-egui/tests/new_project_baked_maps.rs | 80 +++++++++ docs/control-protocol.md | 2 +- 22 files changed, 725 insertions(+), 33 deletions(-) create mode 100644 crates/engine/src/meshmap_file_name.rs create mode 100644 crates/engine/src/meshmap_import_cmds.rs create mode 100644 crates/engine/tests/meshmap_import.rs create mode 100644 crates/ui-egui/src/new_project_advanced.rs create mode 100644 crates/ui-egui/tests/new_project_baked_maps.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..922c380b 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -65,6 +65,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); + v.extend(crate::meshmap_import_cmds::specs()); v.extend(crate::uv_tile_cmds::specs()); v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..da0ab3ae 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -29,6 +29,8 @@ pub mod material_lib; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod meshmap_file_name; +pub mod meshmap_import_cmds; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 0fbe1f5b..932ba137 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,11 +38,17 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let img = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + Ok(json!({ "map": map.id(), "resolution": resolution })) +} + +/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width +pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { + let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; - // Every mesh map of a set shares one size: the other maps', or what a bake would make (a - // block of the bake resolution per tile of the atlas). + let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; + + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), @@ -52,37 +58,34 @@ fn set(s: &mut Session, p: &Value) -> Result { } }; if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(CMD, format!("mesh map size {res} × {height} is too large or empty"))); + return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); } + let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; let data = match &tiles { None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), - // An atlas texel reads the image of the tile its mesh UV falls in. + // An atlas texel reads the image of the tile its mesh UV falls in Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { let uv = grid.from_atlas([u, v]); udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; - s.edit("Use image as mesh map", |s| { - let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; - entry.maps.insert(map, Arc::new(data)); - s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(()) - })?; - Ok(json!({ "map": map.id(), "resolution": res })) + + let entry = s.doc.baked.entry(ts).or_default(); + entry.resolution = res; + entry.maps.insert(map, Arc::new(data)); + s.doc.project.texture_set_mut(ts)?.baked.insert(map); + Ok(res) } -/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for -/// each tile's. -fn tile_images(images: &ImageStore, name: &str, tiles: &[u32]) -> Result>> { - const CMD: &str = "textureSet.meshMap.set"; - let at = udim_in(name).ok_or_else(|| bad(CMD, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; +/// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's +fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { + let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; tiles .iter() .map(|&t| { let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(CMD, format!("no image `{tile_name}` for UV tile {t}"))) + images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) }) .collect() } diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs new file mode 100644 index 00000000..cfc4f125 --- /dev/null +++ b/crates/engine/src/meshmap_file_name.rs @@ -0,0 +1,153 @@ +//! Which texture set and mesh map a baked map file is for, by file name (`Body_ao.1001.png` = Body's ambient occlusion) + +use std::path::Path; + +use texturecraft_core::{BakedMap, UDIM_RANGE}; + +/// Mesh maps named by two words anywhere in the file name; they win over the one-word names +const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ + ("world", &["normal", "normals"], BakedMap::WorldNormal), + ("bent", &["normal", "normals"], BakedMap::BentNormal), + ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), +]; + +const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ + ("worldnormal", BakedMap::WorldNormal), + ("worldnormals", BakedMap::WorldNormal), + ("bentnormal", BakedMap::BentNormal), + ("bentnormals", BakedMap::BentNormal), + ("ambientocclusion", BakedMap::AmbientOcclusion), + ("normal", BakedMap::Normal), + ("normals", BakedMap::Normal), + ("nrm", BakedMap::Normal), + ("occlusion", BakedMap::AmbientOcclusion), + ("ao", BakedMap::AmbientOcclusion), + ("curvature", BakedMap::Curvature), + ("curv", BakedMap::Curvature), + ("id", BakedMap::Id), + ("position", BakedMap::Position), + ("pos", BakedMap::Position), + ("thickness", BakedMap::Thickness), + ("height", BakedMap::Height), + ("displacement", BakedMap::Height), + ("opacity", BakedMap::Opacity), + ("alpha", BakedMap::Opacity), +]; + +fn is_separator(c: char) -> bool { + matches!(c, '_' | '-' | '.' | ' ') +} + +/// The file name without its folder and extension +fn stem(path: &str) -> &str { + Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +} + +/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) +fn words(path: &str) -> Vec { + stem(path) + .split(is_separator) + .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) + .map(str::to_lowercase) + .collect() +} + +/// The mesh map a file holds, from the words of its name; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str) -> Option { + let words = words(path); + let has = |word: &str| words.iter().any(|w| w == word); + TWO_WORD_NAMES + .iter() + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .map(|(_, _, map)| *map) + .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) +} + +/// The set a file is for: the longest set name its name starts with before a separator (any name with one set) +pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Option { + if set_names.len() == 1 { + return Some(0); + } + + let stem = stem(path).to_lowercase(); + set_names + .iter() + .enumerate() + .filter(|(_, name)| !name.is_empty()) + .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) + .max_by_key(|(_, name)| name.chars().count()) + .map(|(ts, _)| ts) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_word_names_its_map() { + let cases = [ + ("Body_normal.png", BakedMap::Normal), + ("Body_normals.png", BakedMap::Normal), + ("Body_nrm.png", BakedMap::Normal), + ("Body_world_normal.png", BakedMap::WorldNormal), + ("Body_normals_world.png", BakedMap::WorldNormal), + ("Body_WorldNormal.png", BakedMap::WorldNormal), + ("Body_bent_normals.png", BakedMap::BentNormal), + ("Body-ambient-occlusion.png", BakedMap::AmbientOcclusion), + ("Body_AmbientOcclusion.png", BakedMap::AmbientOcclusion), + ("Body_occlusion.png", BakedMap::AmbientOcclusion), + ("Body AO.png", BakedMap::AmbientOcclusion), + ("Body_curvature.png", BakedMap::Curvature), + ("Body_curv.png", BakedMap::Curvature), + ("Body_ID.png", BakedMap::Id), + ("Body_position.png", BakedMap::Position), + ("Body_pos.png", BakedMap::Position), + ("Body_thickness.png", BakedMap::Thickness), + ("Body_height.png", BakedMap::Height), + ("Body_displacement.png", BakedMap::Height), + ("Body_opacity.png", BakedMap::Opacity), + ("Body_alpha.png", BakedMap::Opacity), + ]; + for (file, map) in cases { + assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + } + } + + #[test] + fn tile_numbers_and_folders_are_ignored() { + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); + } + + #[test] + fn unknown_words_match_no_map() { + assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png"), None); + assert_eq!(baked_map_from_file_name("ambient.png"), None); + assert_eq!(baked_map_from_file_name(""), None); + } + + #[test] + fn the_longest_set_name_wins() { + let sets = ["Body", "Body_Upper", "Head"]; + assert_eq!(texture_set_from_file_name("Body_Upper_ao.png", &sets), Some(1)); + assert_eq!(texture_set_from_file_name("body_ao.png", &sets), Some(0)); + assert_eq!(texture_set_from_file_name("HEAD-normal.png", &sets), Some(2)); + } + + #[test] + fn a_set_name_must_end_at_a_separator() { + let sets = ["Body", "Head"]; + assert_eq!(texture_set_from_file_name("Bodywork_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Arm_ao.png", &sets), None); + assert_eq!(texture_set_from_file_name("Body.png", &sets), None); + } + + #[test] + fn one_set_takes_every_file() { + assert_eq!(texture_set_from_file_name("ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("Head_ao.png", &["Body"]), Some(0)); + assert_eq!(texture_set_from_file_name("ao.png", &[]), None); + } +} diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs new file mode 100644 index 00000000..9770cf63 --- /dev/null +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -0,0 +1,79 @@ +//! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::BakedMap; + +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::meshmap_cmds::use_image; +use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; +use crate::resource_cmds::read_image_file; +use crate::{Result, Session, cmd}; + +const CMD: &str = "textureSet.meshMap.import"; + +/// Most files one import takes +const MAX_FILES: usize = 1024; + +pub fn specs() -> Vec { + vec![cmd!( + "textureSet.meshMap.import", + "Import baked maps", + [], + None, + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + always, + import + )] +} + +fn import(s: &mut Session, p: &Value) -> Result { + let files = p.get("files").and_then(Value::as_array).ok_or_else(|| bad(CMD, "`files` (a list of {path, map?}) is required"))?; + if files.len() > MAX_FILES { + return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); + } + + let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); + let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); + let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let mut unmatched = Vec::new(); + for file in files { + let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; + let map = match strp(file, "map") { + Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), + None => baked_map_from_file_name(path), + }; + match (texture_set_from_file_name(path, &set_names), map) { + (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + _ => unmatched.push(path), + } + } + + let result = s.edit("Import baked maps", |s| { + let mut assigned = Vec::new(); + for ((ts, map), paths) in &slots { + // A UV-tiled set reads every tile's file; any other set takes the first file for a slot + let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; + let (taken, extra) = paths.split_at(files_used); + let mut image_name = None; + for path in taken { + let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; + image_name.get_or_insert(name); + } + if let Some(name) = image_name { + use_image(s, CMD, *ts, *map, &name)?; + } + + assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); + unmatched.extend(extra); + } + Ok(assigned) + }); + // A failed edit leaves the document as it was; forget the images it decoded + if result.is_err() { + s.sync_images(); + } + + Ok(json!({ "assigned": result?, "unmatched": unmatched })) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 87f6d50f..74682be8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,9 +38,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) + } + + /// [`Session::import_resource_bytes`] without its own undo step, for imports inside a larger edit + pub(crate) fn add_image_resource(&mut self, file_name: &str, bytes: Vec) -> Result { if bytes.len() > MAX_BYTES { return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); } + let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image"); let base = texturecraft_formats::sanitize_resource_name(leaf); @@ -50,11 +56,8 @@ impl Session { name = format!("{n}_{base}"); n += 1; } - let key = name.clone(); - self.edit("Import resource", |s| { - s.doc.resources.insert(key, Arc::new(bytes)); - Ok(()) - })?; + + self.doc.resources.insert(name.clone(), Arc::new(bytes)); self.images.insert(name.clone(), decoded(image)); Ok(name) } @@ -98,15 +101,27 @@ fn list(s: &Session) -> Value { #[cfg(not(target_arch = "wasm32"))] fn import(s: &mut Session, p: &Value) -> Result { let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?; - let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; - if meta.len() > MAX_BYTES as u64 { - return Err(bad("resource.import", format!("{path} is too large"))); - } - let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?; + let bytes = read_image_file("resource.import", path)?; let name = s.import_resource_bytes(path, bytes)?; Ok(json!({ "name": name })) } +/// The bytes of the image file at `path`, refused above [`MAX_BYTES`] +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn read_image_file(cmd: &str, path: &str) -> Result> { + let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?; + if meta.len() > MAX_BYTES as u64 { + return Err(bad(cmd, format!("{path} is too large"))); + } + + std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +pub(crate) fn read_image_file(cmd: &str, _: &str) -> Result> { + Err(bad(cmd, "file paths are not available in the browser")) +} + #[cfg(target_arch = "wasm32")] fn import(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into())) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs new file mode 100644 index 00000000..62a983d6 --- /dev/null +++ b/crates/engine/tests/meshmap_import.rs @@ -0,0 +1,136 @@ +//! Importing baked map files at once: each lands in the texture set and mesh map its name names + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use texturecraft_engine::core::BakedMap; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// The material ball: texture sets "Ball" and "Base" +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +/// A folder of 4×4 gray PNGs named `files`, each with its own gray level +fn bake_folder(test: &str, files: &[&str]) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (index, file) in files.iter().enumerate() { + let gray = 20 + 20 * index as u8; + image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); + } + dir +} + +fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { + let files: Vec = files + .iter() + .map(|(file, map)| { + let path = dir.join(file).display().to_string(); + match map { + Some(map) => json!({"path": path, "map": map}), + None => json!({"path": path}), + } + }) + .collect(); + execute(s, "textureSet.meshMap.import", &json!({ "files": files })).unwrap() +} + +fn file_names(list: &Value) -> Vec { + list.as_array() + .unwrap() + .iter() + .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) + .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .collect() +} + +fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { + s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) +} + +#[test] +fn files_go_to_the_set_and_map_their_names_name() { + let files = ["Ball_normal.png", "Ball_world_normal.png", "base-AO.png", "Base_curvature.png", "Ball_diffuse.png", "Head_ao.png", "Base_id.png"]; + let dir = bake_folder("sets", &files); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &files.map(|f| (f, None))); + + let assigned = &result["assigned"]; + assert_eq!(file_names(assigned).len(), 5, "{result}"); + for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { + assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); + assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + } + assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); + assert_eq!(s.undo_label(), Some("Import baked maps")); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_given_map_overrides_the_name() { + let dir = bake_folder("override", &["Ball_bake3.png", "Base_normal.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_bake3.png", Some("thickness")), ("Base_normal.png", Some("height"))]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + assert!(has_map(&s, 0, BakedMap::Thickness)); + assert!(has_map(&s, 1, BakedMap::Height)); + assert!(!has_map(&s, 1, BakedMap::Normal)); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_second_file_for_one_slot_is_left_out() { + let dir = bake_folder("twice", &["Ball_ao.png", "Ball_occlusion.png"]); + let mut s = session(); + + let result = import(&mut s, &dir, &[("Ball_ao.png", None), ("Ball_occlusion.png", None)]); + + assert_eq!(file_names(&result["assigned"]), ["Ball_ao.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Ball_occlusion.png"]); + assert_eq!(s.doc.resources.len(), 1, "the left-out file is not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_failed_file_imports_nothing() { + let dir = bake_folder("failed", &["Ball_ao.png"]); + std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + let files = json!({"files": [{"path": dir.join("Ball_ao.png").display().to_string()}, {"path": dir.join("Base_ao.png").display().to_string()}]}); + + let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); + + assert!(error.contains("Base_ao.png"), "{error}"); + assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.resources.is_empty() && s.images.is_empty()); + assert_eq!(s.undo_label().map(str::to_string), label_before); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile() { + let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + + let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); + + assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); + let baked = &s.doc.baked[&0]; + let ao = &baked.maps[&BakedMap::AmbientOcclusion]; + let width = baked.resolution as usize; + let middle_row = ao.len() / width / 2 * width; + assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..e1746a31 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Advanced settings", "إعدادات متقدمة"), + ("Import baked maps", "استيراد خرائط مخبوزة"), + ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), + ("Add...", "إضافة..."), + ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..1b86b2e7 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Advanced settings", "Erweiterte Einstellungen"), + ("Import baked maps", "Gebackene Maps importieren"), + ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), + ("Add...", "Hinzufügen..."), + ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..a0445eed 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Advanced settings", "Ajustes avanzados"), + ("Import baked maps", "Importar mapas horneados"), + ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), + ("Add...", "Añadir..."), + ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..235bf5a9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Advanced settings", "Paramètres avancés"), + ("Import baked maps", "Importer des cartes précalculées"), + ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), + ("Add...", "Ajouter..."), + ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..12a180ed 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Advanced settings", "Impostazioni avanzate"), + ("Import baked maps", "Importa mappe bake"), + ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), + ("Add...", "Aggiungi..."), + ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..8b930774 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Advanced settings", "詳細設定"), + ("Import baked maps", "ベイク済みマップを読み込む"), + ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), + ("Add...", "追加..."), + ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..30d5eef5 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Advanced settings", "고급 설정"), + ("Import baked maps", "베이크된 맵 가져오기"), + ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), + ("Add...", "추가..."), + ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..330c09a3 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Advanced settings", "Configurações avançadas"), + ("Import baked maps", "Importar mapas com bake"), + ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), + ("Add...", "Adicionar..."), + ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..f0731a7c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Advanced settings", "高级设置"), + ("Import baked maps", "导入已烘焙贴图"), + ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), + ("Add...", "添加..."), + ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..23f67ca9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod keymap; mod mask_preview_image; mod mask_shape; pub mod menus; +pub mod new_project_advanced; pub mod parity; mod preview_image; mod preview_request; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs new file mode 100644 index 00000000..50dd64c6 --- /dev/null +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -0,0 +1,155 @@ +//! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation + +use egui::{RichText, Sense, Ui, vec2}; +use serde_json::{Value, json}; +use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::template_cmds::builtin_templates; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::NewProject; +use crate::theme::{Tokens, caption}; +use crate::widgets::{section, section_chevron}; +use crate::windows::file_dialogs_available; + +/// Labels of every New project form row, so Basic and Advanced share one label column +const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolution", "UV tiles (UDIM)", "Name", "Normal map format"]; + +/// Each normal map format with its command id and label +const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; + +/// Width of the dialog's dropdowns +const COMBO_WIDTH: f32 = 200.0; + +/// Width of the Add... and Clear buttons +const FILE_BUTTON_WIDTH: f32 = 96.0; + +/// Tallest the list of added files grows before it scrolls +const FILE_LIST_HEIGHT: f32 = 160.0; + +/// Width of the widest form label, for the label column of every form grid in the dialog +pub(crate) fn form_label_width(ui: &Ui) -> f32 { + let font = egui::TextStyle::Body.resolve(ui.style()); + FORM_LABELS.iter().map(|label| ui.painter().layout_no_wrap(tr(label).to_string(), font.clone(), egui::Color32::WHITE).size().x).fold(0.0, f32::max) +} + +/// The collapsible Advanced settings section (closed until opened) +pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { + let id = ui.make_persistent_id("np_advanced"); + let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false); + let header = ui + .horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); + ui.add(egui::Label::new(caption(tr("Advanced settings"))).selectable(false)); + }) + .response + .interact(Sense::click()); + if header.clicked() { + state.toggle(ui); + } + + state.show_body_unindented(ui, |ui| { + egui::Grid::new("np_advanced_grid").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(form_label_width(ui)).show(ui, |ui| { + ui.label(tr("Normal map format")); + normal_format_combo(app, ui); + ui.end_row(); + }); + if file_dialogs_available() { + ui.add_space(4.0); + section(ui, "np_baked_maps", tr("Import baked maps"), false, |ui| baked_maps(&mut app.ui.new_project, ui)); + } + }); +} + +fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { + let new_project = &mut app.ui.new_project; + let user_templates = app.session.templates.list.iter().cloned(); + let template_format = + builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let current = new_project.normal_format.unwrap_or(template_format); + let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); + egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + for (format, _, label) in NORMAL_FORMATS { + if ui.selectable_label(format == current, label).clicked() { + new_project.normal_format = Some(format); + } + } + }); +} + +fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); + ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(hint_width); + ui.add(egui::Label::new(RichText::new(tr("Name each file after its texture set, like Body_normal.png")).color(tokens.text_dim)).wrap()); + }); + if ui.add(egui::Button::new(tr("Add...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + add_baked_map_files(new_project, pick_baked_map_files()); + } + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + new_project.baked_maps.clear(); + } + }); + if new_project.baked_maps.is_empty() { + return; + } + + ui.add_space(4.0); + egui::ScrollArea::vertical().max_height(FILE_LIST_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); +} + +/// List picked baked map files (files already listed are skipped) +pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { + for path in paths { + if !new_project.baked_maps.contains(&path) { + new_project.baked_maps.push(path); + } + } +} + +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { + let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); + if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { + app.run("textureSet.settings", json!({ "normalFormat": id })); + } + if new_project.baked_maps.is_empty() { + return; + } + + let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { + return; + }; + + let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); + let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + if !not_imported.is_empty() { + text.push('\n'); + text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); + } + app.toast(text, !not_imported.is_empty()); +} + +fn file_name(path: &str) -> String { + std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |name| name.to_string_lossy().into_owned()) +} + +#[cfg(not(target_arch = "wasm32"))] +fn pick_baked_map_files() -> Vec { + let files = rfd::FileDialog::new().add_filter(tr("Images"), crate::web_files::IMAGE_EXTS).pick_files(); + files.unwrap_or_default().into_iter().map(|path| path.display().to_string()).collect() +} + +#[cfg(target_arch = "wasm32")] +fn pick_baked_map_files() -> Vec { + Vec::new() +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..f22d1d69 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -151,6 +151,12 @@ pub struct NewProject { /// Name typed to save the current project's settings as a template. #[serde(skip)] pub template_name: String, + /// Normal map format of the project and its imported normal maps; None keeps the template's + #[serde(default)] + pub normal_format: Option, + /// Baked map files to import at creation, matched to sets and mesh maps by name (desktop only) + #[serde(skip)] + pub baked_maps: Vec, } fn default_template() -> String { @@ -167,6 +173,8 @@ impl Default for NewProject { uv_tiles: None, template: default_template(), template_name: String::new(), + normal_format: None, + baked_maps: Vec::new(), } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..8ac07749 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -392,7 +392,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { ui.label(caption(tr("Basic settings"))); - egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { + egui::Grid::new("np").num_columns(2).spacing(vec2(12.0, 8.0)).min_col_width(crate::new_project_advanced::form_label_width(ui)).show(ui, |ui| { ui.label(tr("3D mesh")); ui.horizontal(|ui| { let label = app.ui.new_project.file.clone().unwrap_or_else(|| { @@ -429,6 +429,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if ui.selectable_label(t.name == np.template, &t.name).clicked() { np.template = t.name.clone(); np.resolution = t.resolution; + np.normal_format = None; } } }); @@ -469,6 +470,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + crate::new_project_advanced::advanced_settings(app, ui); + ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { if ui.add(primary_button(ui, tr("Create"))).clicked() { @@ -490,6 +493,8 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if r.is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; + app.ui.new_project.baked_maps.clear(); + crate::new_project_advanced::apply_after_create(app, &np); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs new file mode 100644 index 00000000..a2c95e98 --- /dev/null +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -0,0 +1,80 @@ +//! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakedMap, NormalFormat}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.windows.new_project = true; + h.state_mut().ui.new_project.resolution = 256; + h.run_steps(3); + h.get_by_label("Advanced settings").click(); + h.run_steps(3); + h.get_by_label("Import baked maps").click(); + h.run_steps(3); + h +} + +/// 4×4 PNGs named `files` in a fresh folder, as their full paths +fn bake_files(test: &str, files: &[&str]) -> Vec { + let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + files + .iter() + .map(|file| { + let path: PathBuf = dir.join(file); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + path.display().to_string() + }) + .collect() +} + +#[test] +fn added_files_are_listed_once_and_clear_empties_the_list() { + let mut h = harness(); + let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + + add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.run_steps(3); + + assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); + for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { + h.get_by_label(file); + } + + h.get_by_label("Clear").click(); + h.run_steps(3); + assert!(h.state().ui.new_project.baked_maps.is_empty()); + assert!(h.query_by_label("Ball_normal.png").is_none()); +} + +#[test] +fn create_imports_the_listed_maps_in_the_chosen_normal_format() { + let mut h = harness(); + let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + add_baked_map_files(&mut h.state_mut().ui.new_project, paths); + h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); + h.run_steps(3); + + h.get_by_label("Create").click(); + h.run_steps(3); + + let state = h.state(); + assert!(!state.ui.windows.new_project, "the dialog closes"); + let project = &state.session.doc.project; + assert_eq!(project.normal_format, NormalFormat::DirectX); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); + let toast = &state.toasts.last().unwrap().text; + assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); + assert_eq!(state.session.undo_label(), Some("Import baked maps")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78707aa1..734036ca 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot) | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From ffe8587e541792eb356226b6cc476e1c3bc4a56e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 08:25:04 +0000 Subject: [PATCH 066/275] Take &Path in the import test helper --- crates/engine/tests/meshmap_import.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index 62a983d6..da3cb780 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -1,6 +1,6 @@ //! Importing baked map files at once: each lands in the texture set and mesh map its name names -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde_json::{Value, json}; use texturecraft_engine::core::BakedMap; @@ -23,7 +23,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { dir } -fn import(s: &mut Session, dir: &PathBuf, files: &[(&str, Option<&str>)]) -> Value { +fn import(s: &mut Session, dir: &Path, files: &[(&str, Option<&str>)]) -> Value { let files: Vec = files .iter() .map(|(file, map)| { From 6eed52435db0ff1dfc05ff16e38ae51a8ae647f6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 09:14:35 +0000 Subject: [PATCH 067/275] Match UV tiles per file, skip empty imports, review cleanups - Each tiled file is keyed by its own tile number and its image passed to use_images, so tiles named differently or renamed on import still match - Files of a tiled set without one of its tiles, and maps missing a tile, go to unmatched instead of failing the import - Nothing to import leaves no undo step - The map is read from the file name after the set name - Toast counts maps; a failed import keeps the file list - Cap the bytes one import reads; whole-method cleanup of set, use_images, tile_images and new_project --- crates/engine/src/meshmap_cmds.rs | 79 +++++++++++------- crates/engine/src/meshmap_file_name.rs | 72 ++++++++-------- crates/engine/src/meshmap_import_cmds.rs | 83 +++++++++++++------ crates/engine/src/resource_cmds.rs | 2 +- crates/engine/tests/meshmap_import.rs | 68 +++++++++++---- crates/ui-egui/src/i18n/ar.rs | 2 +- crates/ui-egui/src/i18n/de.rs | 2 +- crates/ui-egui/src/i18n/es.rs | 2 +- crates/ui-egui/src/i18n/fr.rs | 2 +- crates/ui-egui/src/i18n/it.rs | 2 +- crates/ui-egui/src/i18n/ja.rs | 2 +- crates/ui-egui/src/i18n/ko.rs | 2 +- crates/ui-egui/src/i18n/pt_br.rs | 2 +- crates/ui-egui/src/i18n/zh_hans.rs | 2 +- crates/ui-egui/src/new_project_advanced.rs | 20 +++-- crates/ui-egui/src/windows.rs | 56 +++++++------ .../ui-egui/tests/new_project_baked_maps.rs | 10 ++- 17 files changed, 258 insertions(+), 150 deletions(-) diff --git a/crates/engine/src/meshmap_cmds.rs b/crates/engine/src/meshmap_cmds.rs index 932ba137..ac9003b7 100644 --- a/crates/engine/src/meshmap_cmds.rs +++ b/crates/engine/src/meshmap_cmds.rs @@ -38,58 +38,81 @@ fn set(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, CMD)?; let map = map_param(p, CMD)?; let name = strp(p, "image").ok_or_else(|| bad(CMD, "`image` (an image resource name) is required"))?; - let resolution = s.edit("Use image as mesh map", |s| use_image(s, CMD, ts, map, name))?; + let image = s.images.get(name).cloned().ok_or_else(|| bad(CMD, format!("no image resource `{name}`")))?; + let texture_set = s.doc.project.texture_set(ts)?; + let images = match texture_set.tile_grid() { + Some(_) => tile_images(&s.images, CMD, name, &texture_set.uv_tiles)?, + None => BTreeMap::from([(FIRST_TILE, image)]), + }; + + let resolution = s.edit("Use image as mesh map", |s| use_images(s, CMD, ts, map, &images))?; Ok(json!({ "map": map.id(), "resolution": resolution })) } -/// Use image resource `name` as mesh map `map` of set `ts` inside the caller's edit; returns the map width -pub(crate) fn use_image(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, name: &str) -> Result { - let img = s.images.get(name).cloned().ok_or_else(|| bad(cmd, format!("no image resource `{name}`")))?; - let set = s.doc.project.texture_set(ts)?.clone(); - let tiles = set.tile_grid().map(|grid| tile_images(&s.images, cmd, name, &set.uv_tiles).map(|imgs| (grid, imgs))).transpose()?; +/// The tile number a set without UV tiles keys its one image by +pub(crate) const FIRST_TILE: u32 = *UDIM_RANGE.start(); - // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) - let (cols, rows) = tiles.as_ref().map_or((1, 1), |(g, _)| (g.cols, g.rows)); - let (res, height) = match s.doc.baked.get(&ts).filter(|b| !b.maps.is_empty()) { - Some(b) => (b.resolution, b.maps.keys().next().map_or(b.resolution, |m| b.height(*m))), - None => { - let (width, height) = set.bake.common.output_size(); - (width.saturating_mul(cols), height.saturating_mul(rows)) - } - }; - if res == 0 || height == 0 || u64::from(res) * u64::from(height) > texturecraft_bake::MAX_TEXELS || (tiles.is_none() && res > MAX_RESOLUTION) { - return Err(bad(cmd, format!("mesh map size {res} × {height} is too large or empty"))); +/// Use `images` (by UV tile; one at [`FIRST_TILE`] without UV tiles) as mesh map `map` of set `ts` in the caller's edit; returns its width +pub(crate) fn use_images(s: &mut Session, cmd: &str, ts: usize, map: BakedMap, images: &BTreeMap>) -> Result { + let texture_set = s.doc.project.texture_set(ts)?; + let grid = texture_set.tile_grid(); + if let Some(tile) = texture_set.uv_tiles.iter().find(|tile| grid.is_some() && !images.contains_key(tile)) { + return Err(bad(cmd, format!("no image for UV tile {tile}"))); } - let directx = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; - let data = match &tiles { - None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)), + // Every mesh map of a set shares one size: the other maps', or a bake's (a bake-size block per atlas tile) + let (columns, rows) = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); + let (width, height) = match s.doc.baked.get(&ts).filter(|baked| !baked.maps.is_empty()) { + Some(baked) => (baked.resolution, baked.maps.keys().next().map_or(baked.resolution, |other| baked.height(*other))), + None => { + let (width, height) = texture_set.bake.common.output_size(); + (width.saturating_mul(columns), height.saturating_mul(rows)) + } + }; + let empty = width == 0 || height == 0; + let too_many_texels = u64::from(width) * u64::from(height) > texturecraft_bake::MAX_TEXELS; + let too_wide = grid.is_none() && width > MAX_RESOLUTION; + if empty || too_many_texels || too_wide { + return Err(bad(cmd, format!("mesh map size {width} × {height} is too large or empty"))); + } + + let flip_green = map == BakedMap::Normal && s.doc.project.normal_format == NormalFormat::DirectX; + let data = match (grid, images.values().next()) { + (_, None) => return Err(bad(cmd, "no image to use")), + (None, Some(image)) => resample(map.components(), (width, height), flip_green, |u, v| image.sample(u, v)), // An atlas texel reads the image of the tile its mesh UV falls in - Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| { + (Some(grid), Some(_)) => resample(map.components(), (width, height), flip_green, |u, v| { let uv = grid.from_atlas([u, v]); - udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) + udim_at(uv).and_then(|tile| images.get(&tile)).map_or([0.0; 4], |image| image.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor())) }), }; let entry = s.doc.baked.entry(ts).or_default(); - entry.resolution = res; + entry.resolution = width; entry.maps.insert(map, Arc::new(data)); s.doc.project.texture_set_mut(ts)?.baked.insert(map); - Ok(res) + Ok(width) } /// The image of every UV tile of a set: `name` with its tile number (`ao.1001.png`) swapped for each tile's fn tile_images(images: &ImageStore, cmd: &str, name: &str, tiles: &[u32]) -> Result>> { - let at = udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let tile_at = + udim_in(name).ok_or_else(|| bad(cmd, format!("`{name}` names no UV tile: a UV-tiled set takes one image per tile, named like ao.1001.png")))?; + let (before_tile, after_tile) = (name.get(..tile_at).unwrap_or_default(), name.get(tile_at + 4..).unwrap_or_default()); tiles .iter() - .map(|&t| { - let tile_name = format!("{}{t}{}", name.get(..at).unwrap_or_default(), name.get(at + 4..).unwrap_or_default()); - images.get(&tile_name).cloned().map(|img| (t, img)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {t}"))) + .map(|&tile| { + let tile_name = format!("{before_tile}{tile}{after_tile}"); + images.get(&tile_name).cloned().map(|image| (tile, image)).ok_or_else(|| bad(cmd, format!("no image `{tile_name}` for UV tile {tile}"))) }) .collect() } +/// The UV tile number in a file name (`Body_ao.1002.png` → 1002) +pub(crate) fn tile_number(file_name: &str) -> Option { + udim_in(file_name).and_then(|at| file_name.get(at..at + 4)).and_then(|digits| digits.parse().ok()) +} + /// Where the last UDIM tile number (four digits alone, in [`UDIM_RANGE`]) in `name` starts. fn udim_in(name: &str) -> Option { let b = name.as_bytes(); diff --git a/crates/engine/src/meshmap_file_name.rs b/crates/engine/src/meshmap_file_name.rs index cfc4f125..fde32d5e 100644 --- a/crates/engine/src/meshmap_file_name.rs +++ b/crates/engine/src/meshmap_file_name.rs @@ -5,13 +5,14 @@ use std::path::Path; use texturecraft_core::{BakedMap, UDIM_RANGE}; /// Mesh maps named by two words anywhere in the file name; they win over the one-word names -const TWO_WORD_NAMES: [(&str, &[&str], BakedMap); 3] = [ +const TWO_WORD_NAMES: &[(&str, &[&str], BakedMap)] = &[ ("world", &["normal", "normals"], BakedMap::WorldNormal), ("bent", &["normal", "normals"], BakedMap::BentNormal), ("ambient", &["occlusion"], BakedMap::AmbientOcclusion), ]; -const ONE_WORD_NAMES: [(&str, BakedMap); 20] = [ +/// Mesh maps named by one word, including the two-word names written as one +const ONE_WORD_NAMES: &[(&str, BakedMap)] = &[ ("worldnormal", BakedMap::WorldNormal), ("worldnormals", BakedMap::WorldNormal), ("bentnormal", BakedMap::BentNormal), @@ -38,29 +39,33 @@ fn is_separator(c: char) -> bool { matches!(c, '_' | '-' | '.' | ' ') } -/// The file name without its folder and extension -fn stem(path: &str) -> &str { - Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or_default() +/// The lowercase file name without its folder and extension +fn lowercase_stem(path: &str) -> String { + Path::new(path).file_stem().and_then(|stem| stem.to_str()).unwrap_or_default().to_lowercase() } -/// The lowercase words of a file name, without UV tile numbers (`Body_AO.1001` → body, ao) -fn words(path: &str) -> Vec { - stem(path) - .split(is_separator) - .filter(|w| !w.is_empty() && !w.parse::().is_ok_and(|n| w.len() == 4 && UDIM_RANGE.contains(&n))) - .map(str::to_lowercase) - .collect() +/// What follows `set_name` at the start of a lowercase stem, when a separator follows it +fn after_set_name<'a>(stem: &'a str, set_name: &str) -> Option<&'a str> { + if set_name.is_empty() { + return None; + } + + stem.strip_prefix(&set_name.to_lowercase()).filter(|rest| rest.starts_with(is_separator)) } -/// The mesh map a file holds, from the words of its name; the last recognised word wins -pub(crate) fn baked_map_from_file_name(path: &str) -> Option { - let words = words(path); - let has = |word: &str| words.iter().any(|w| w == word); +/// The mesh map a file holds, from the words of its name after `set_name`; the last recognised word wins +pub(crate) fn baked_map_from_file_name(path: &str, set_name: &str) -> Option { + let stem = lowercase_stem(path); + let rest = after_set_name(&stem, set_name).unwrap_or(&stem); + let is_tile_number = |word: &str| word.len() == 4 && word.parse::().is_ok_and(|number| UDIM_RANGE.contains(&number)); + let words: Vec<&str> = rest.split(is_separator).filter(|word| !word.is_empty() && !is_tile_number(word)).collect(); + + let has = |name: &str| words.contains(&name); TWO_WORD_NAMES .iter() - .find(|(first, seconds, _)| has(first) && seconds.iter().any(|s| has(s))) + .find(|(first, seconds, _)| has(first) && seconds.iter().any(|second| has(second))) .map(|(_, _, map)| *map) - .or_else(|| words.iter().rev().find_map(|w| ONE_WORD_NAMES.iter().find(|(name, _)| name == w).map(|(_, map)| *map))) + .or_else(|| words.iter().rev().find_map(|word| ONE_WORD_NAMES.iter().find(|(name, _)| name == word).map(|(_, map)| *map))) } /// The set a file is for: the longest set name its name starts with before a separator (any name with one set) @@ -69,14 +74,8 @@ pub(crate) fn texture_set_from_file_name(path: &str, set_names: &[&str]) -> Opti return Some(0); } - let stem = stem(path).to_lowercase(); - set_names - .iter() - .enumerate() - .filter(|(_, name)| !name.is_empty()) - .filter(|(_, name)| stem.strip_prefix(&name.to_lowercase()).and_then(|rest| rest.chars().next()).is_some_and(is_separator)) - .max_by_key(|(_, name)| name.chars().count()) - .map(|(ts, _)| ts) + let stem = lowercase_stem(path); + set_names.iter().enumerate().filter(|(_, name)| after_set_name(&stem, name).is_some()).max_by_key(|(_, name)| name.chars().count()).map(|(ts, _)| ts) } #[cfg(test)] @@ -109,23 +108,30 @@ mod tests { ("Body_alpha.png", BakedMap::Opacity), ]; for (file, map) in cases { - assert_eq!(baked_map_from_file_name(file), Some(map), "{file}"); + assert_eq!(baked_map_from_file_name(file, "Body"), Some(map), "{file}"); } } #[test] fn tile_numbers_and_folders_are_ignored() { - assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png"), Some(BakedMap::AmbientOcclusion)); - assert_eq!(baked_map_from_file_name("Body_normal_1002.tga"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("/bakes/Body_ao.1001.png", "Body"), Some(BakedMap::AmbientOcclusion)); + assert_eq!(baked_map_from_file_name("Body_normal_1002.tga", "Body"), Some(BakedMap::Normal)); assert_eq!(texture_set_from_file_name("/bakes/Body_ao.1001.png", &["Head", "Body"]), Some(1)); } #[test] fn unknown_words_match_no_map() { - assert_eq!(baked_map_from_file_name("Body_diffuse.png"), None); - assert_eq!(baked_map_from_file_name("Body_1001.png"), None); - assert_eq!(baked_map_from_file_name("ambient.png"), None); - assert_eq!(baked_map_from_file_name(""), None); + assert_eq!(baked_map_from_file_name("Body_diffuse.png", "Body"), None); + assert_eq!(baked_map_from_file_name("Body_1001.png", "Body"), None); + assert_eq!(baked_map_from_file_name("ambient.png", "Body"), None); + assert_eq!(baked_map_from_file_name("", "Body"), None); + } + + #[test] + fn the_set_name_is_not_read_as_a_map() { + assert_eq!(baked_map_from_file_name("World_normal.png", "World"), Some(BakedMap::Normal)); + assert_eq!(baked_map_from_file_name("ID_diffuse.png", "ID"), None); + assert_eq!(baked_map_from_file_name("Body_ao.png", ""), Some(BakedMap::AmbientOcclusion)); } #[test] diff --git a/crates/engine/src/meshmap_import_cmds.rs b/crates/engine/src/meshmap_import_cmds.rs index 9770cf63..f8ea8244 100644 --- a/crates/engine/src/meshmap_import_cmds.rs +++ b/crates/engine/src/meshmap_import_cmds.rs @@ -1,20 +1,24 @@ //! Import mesh maps baked in another app: many files at once, each to the set and slot its file name names use std::collections::BTreeMap; +use std::path::Path; use serde_json::{Value, json}; use texturecraft_core::BakedMap; use crate::commands::{CommandSpec, always, bad, strp}; -use crate::meshmap_cmds::use_image; +use crate::meshmap_cmds::{FIRST_TILE, tile_number, use_images}; use crate::meshmap_file_name::{baked_map_from_file_name, texture_set_from_file_name}; use crate::resource_cmds::read_image_file; use crate::{Result, Session, cmd}; const CMD: &str = "textureSet.meshMap.import"; -/// Most files one import takes -const MAX_FILES: usize = 1024; +/// Most files one import takes: every mesh map of dozens of sets, each split over a few UV tiles +const MAX_FILES: usize = 512; + +/// Most bytes one import reads, since every file stays decoded in memory until the import ends +const MAX_TOTAL_BYTES: u64 = 2 << 30; pub fn specs() -> Vec { vec![cmd!( @@ -22,7 +26,7 @@ pub fn specs() -> Vec { "Import baked maps", [], None, - "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set: a UV-tiled set takes one file per tile (`Body_ao.1001.png`, `Body_ao.1002.png`). Files matching no set or map, and any file after the first for one slot, are left out and listed in `unmatched`. One undo step; desktop only", + "{files: [{path, map?: mesh map id}]} → {assigned: [{path, ts, map}], unmatched: [path]} — each image file becomes the mesh map its name names (`Body_ao.png`, `Body_world_normal.png`; or `map`) of the texture set its name starts with (any name when there is one set), read as by textureSet.meshMap.set. A UV-tiled set takes one file per tile, named with the tile number (`Body_ao.1001.png`, `Body_ao.1002.png`). Left out and listed in `unmatched`: files matching no set or map, a second file for one slot or tile, files of a UV-tiled set without one of its tile numbers, and every file of a map missing a tile. One undo step (none when nothing matches); desktop only", always, import )] @@ -34,39 +38,52 @@ fn import(s: &mut Session, p: &Value) -> Result { return Err(bad(CMD, format!("at most {MAX_FILES} files at once"))); } - let set_names: Vec = s.doc.project.texture_sets.iter().map(|set| set.name.clone()).collect(); - let set_names: Vec<&str> = set_names.iter().map(String::as_str).collect(); - let mut slots: BTreeMap<(usize, BakedMap), Vec<&str>> = BTreeMap::new(); + let set_names: Vec<&str> = s.doc.project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + let mut slots: BTreeMap<(usize, BakedMap), BTreeMap> = BTreeMap::new(); let mut unmatched = Vec::new(); for file in files { let path = strp(file, "path").ok_or_else(|| bad(CMD, "every file needs a `path`"))?; - let map = match strp(file, "map") { - Some(id) => Some(BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))?), - None => baked_map_from_file_name(path), - }; - match (texture_set_from_file_name(path, &set_names), map) { - (Some(ts), Some(map)) => slots.entry((ts, map)).or_default().push(path), + let given_map = strp(file, "map").map(|id| BakedMap::parse(id).ok_or_else(|| bad(CMD, format!("unknown mesh map `{id}`")))).transpose()?; + match slot_of(s, &set_names, path, given_map) { + Some((slot, tile)) if !slots.get(&slot).is_some_and(|tiles| tiles.contains_key(&tile)) => { + slots.entry(slot).or_default().insert(tile, path); + } _ => unmatched.push(path), } } + // A UV-tiled map needs a file for every tile of its set + slots.retain(|(ts, _), tiles| { + let complete = + s.doc.project.texture_sets.get(*ts).is_some_and(|set| set.tile_grid().is_none() || set.uv_tiles.iter().all(|tile| tiles.contains_key(tile))); + if !complete { + unmatched.extend(tiles.values()); + } + complete + }); + if slots.is_empty() { + return Ok(json!({ "assigned": [], "unmatched": unmatched })); + } + let result = s.edit("Import baked maps", |s| { let mut assigned = Vec::new(); - for ((ts, map), paths) in &slots { - // A UV-tiled set reads every tile's file; any other set takes the first file for a slot - let files_used = if s.doc.project.texture_set(*ts)?.tile_grid().is_some() { paths.len() } else { 1 }; - let (taken, extra) = paths.split_at(files_used); - let mut image_name = None; - for path in taken { - let name = s.add_image_resource(path, read_image_file(CMD, path)?)?; - image_name.get_or_insert(name); - } - if let Some(name) = image_name { - use_image(s, CMD, *ts, *map, &name)?; - } + let mut total_bytes = 0; + for ((ts, map), tiles) in &slots { + let mut images = BTreeMap::new(); + for (tile, path) in tiles { + let bytes = read_image_file(CMD, path)?; + total_bytes += bytes.len() as u64; + if total_bytes > MAX_TOTAL_BYTES { + return Err(bad(CMD, format!("the files are larger than {} GB together", MAX_TOTAL_BYTES >> 30))); + } - assigned.extend(taken.iter().map(|path| json!({"path": path, "ts": ts, "map": map.id()}))); - unmatched.extend(extra); + let name = s.add_image_resource(path, bytes)?; + if let Some(image) = s.images.get(&name) { + images.insert(*tile, image.clone()); + } + assigned.push(json!({"path": path, "ts": ts, "map": map.id()})); + } + use_images(s, CMD, *ts, *map, &images)?; } Ok(assigned) }); @@ -77,3 +94,15 @@ fn import(s: &mut Session, p: &Value) -> Result { Ok(json!({ "assigned": result?, "unmatched": unmatched })) } + +/// The texture set and mesh map a file is for, and its UV tile ([`FIRST_TILE`] on a set without UV tiles) +fn slot_of(s: &Session, set_names: &[&str], path: &str, given_map: Option) -> Option<((usize, BakedMap), u32)> { + let ts = texture_set_from_file_name(path, set_names)?; + let map = given_map.or_else(|| baked_map_from_file_name(path, set_names.get(ts).copied().unwrap_or_default()))?; + let texture_set = s.doc.project.texture_sets.get(ts)?; + let tile = match texture_set.tile_grid() { + Some(_) => tile_number(Path::new(path).file_name()?.to_str()?).filter(|tile| texture_set.uv_tiles.contains(tile))?, + None => FIRST_TILE, + }; + Some(((ts, map), tile)) +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 74682be8..3dc415a4 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -36,7 +36,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { } impl Session { - /// Add an image resource from bytes (one undo step); returns its unique, sanitized name. + /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { self.edit("Import resource", |s| s.add_image_resource(file_name, bytes)) } diff --git a/crates/engine/tests/meshmap_import.rs b/crates/engine/tests/meshmap_import.rs index da3cb780..d9ed53f1 100644 --- a/crates/engine/tests/meshmap_import.rs +++ b/crates/engine/tests/meshmap_import.rs @@ -17,7 +17,7 @@ fn bake_folder(test: &str, files: &[&str]) -> PathBuf { let dir = std::env::temp_dir().join(format!("texturecraft-meshmap-import-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); for (index, file) in files.iter().enumerate() { - let gray = 20 + 20 * index as u8; + let gray = u8::try_from(20 + 20 * index).unwrap_or(u8::MAX); image::RgbaImage::from_pixel(4, 4, image::Rgba([gray, gray, gray, 255])).save(dir.join(file)).unwrap(); } dir @@ -41,13 +41,13 @@ fn file_names(list: &Value) -> Vec { list.as_array() .unwrap() .iter() - .map(|v| v.as_str().map_or_else(|| v["path"].as_str().unwrap(), |p| p)) - .map(|p| p.rsplit(['/', '\\']).next().unwrap().to_string()) + .map(|entry| entry.as_str().unwrap_or_else(|| entry["path"].as_str().unwrap())) + .map(|path| path.rsplit(['/', '\\']).next().unwrap().to_string()) .collect() } fn has_map(s: &Session, ts: usize, map: BakedMap) -> bool { - s.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) + s.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)) && s.doc.project.texture_sets[ts].baked.contains(&map) } #[test] @@ -57,21 +57,21 @@ fn files_go_to_the_set_and_map_their_names_name() { let mut s = session(); let label_before = s.undo_label().map(str::to_string); - let result = import(&mut s, &dir, &files.map(|f| (f, None))); + let result = import(&mut s, &dir, &files.map(|file| (file, None))); let assigned = &result["assigned"]; assert_eq!(file_names(assigned).len(), 5, "{result}"); for (ts, map) in [(0, BakedMap::Normal), (0, BakedMap::WorldNormal), (1, BakedMap::AmbientOcclusion), (1, BakedMap::Curvature), (1, BakedMap::Id)] { assert!(has_map(&s, ts, map), "set {ts} lacks {}", map.id()); - assert!(assigned.as_array().unwrap().iter().any(|a| a["ts"] == ts && a["map"] == map.id()), "{result}"); + assert!(assigned.as_array().unwrap().iter().any(|entry| entry["ts"] == ts && entry["map"] == map.id()), "{result}"); } assert_eq!(file_names(&result["unmatched"]), ["Ball_diffuse.png", "Head_ao.png"]); assert_eq!(s.undo_label(), Some("Import baked maps")); execute(&mut s, "edit.undo", &Value::Null).unwrap(); assert_eq!(s.undo_label().map(str::to_string), label_before, "one undo step"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty()), "undo removes every imported map"); - assert!(s.doc.resources.is_empty(), "undo removes the imported images"); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty()), "undo removes every imported map"); + assert!(s.doc.resources.is_empty(), "undo removes the imported image resources"); std::fs::remove_dir_all(dir).ok(); } @@ -103,8 +103,8 @@ fn a_second_file_for_one_slot_is_left_out() { } #[test] -fn a_failed_file_imports_nothing() { - let dir = bake_folder("failed", &["Ball_ao.png"]); +fn an_undecodable_file_imports_nothing() { + let dir = bake_folder("undecodable", &["Ball_ao.png"]); std::fs::write(dir.join("Base_ao.png"), b"not an image").unwrap(); let mut s = session(); let label_before = s.undo_label().map(str::to_string); @@ -113,18 +113,24 @@ fn a_failed_file_imports_nothing() { let error = execute(&mut s, "textureSet.meshMap.import", &files).unwrap_err().to_string(); assert!(error.contains("Base_ao.png"), "{error}"); - assert!(s.doc.baked.values().all(|b| b.maps.is_empty())); + assert!(s.doc.baked.values().all(|baked| baked.maps.is_empty())); assert!(s.doc.resources.is_empty() && s.images.is_empty()); assert_eq!(s.undo_label().map(str::to_string), label_before); std::fs::remove_dir_all(dir).ok(); } -#[test] -fn a_uv_tiled_set_takes_one_file_per_tile() { - let dir = bake_folder("tiles", &["Plane_ao.1001.png", "Plane_ao.1002.png"]); - let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); +/// The UV tile plane: one texture set "Plane" on tiles 1001 and 1002 +fn tiled_session() -> Session { + Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap() +} - let result = import(&mut s, &dir, &[("Plane_ao.1001.png", None), ("Plane_ao.1002.png", None)]); +#[test] +fn a_uv_tiled_set_takes_one_file_per_tile_however_each_is_written() { + let files = ["Plane_ao.1001.png", "plane-AO-1002.png"]; + let dir = bake_folder("tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); assert_eq!(file_names(&result["assigned"]).len(), 2, "{result}"); let baked = &s.doc.baked[&0]; @@ -134,3 +140,33 @@ fn a_uv_tiled_set_takes_one_file_per_tile() { assert!(ao[middle_row + width / 4] < ao[middle_row + 3 * width / 4], "each tile reads its own file"); std::fs::remove_dir_all(dir).ok(); } + +#[test] +fn tiled_files_without_their_tiles_are_left_out_alone() { + let files = ["Plane_ao.1001.png", "Plane_ao.1002.png", "Plane_normal.png", "Plane_curvature.1001.png", "Plane_id.1005.png"]; + let dir = bake_folder("partial-tiles", &files); + let mut s = tiled_session(); + + let result = import(&mut s, &dir, &files.map(|file| (file, None))); + + assert_eq!(file_names(&result["assigned"]), ["Plane_ao.1001.png", "Plane_ao.1002.png"]); + assert_eq!(file_names(&result["unmatched"]), ["Plane_normal.png", "Plane_id.1005.png", "Plane_curvature.1001.png"]); + assert!(has_map(&s, 0, BakedMap::AmbientOcclusion)); + assert_eq!(s.doc.resources.len(), 2, "left-out files are not imported"); + std::fs::remove_dir_all(dir).ok(); +} + +#[test] +fn nothing_matched_makes_no_undo_step() { + let dir = bake_folder("none", &["Head_ao.png", "Ball_diffuse.png"]); + let mut s = session(); + let label_before = s.undo_label().map(str::to_string); + + let result = import(&mut s, &dir, &[("Head_ao.png", None), ("Ball_diffuse.png", None)]); + + assert_eq!(file_names(&result["assigned"]), Vec::::new()); + assert_eq!(file_names(&result["unmatched"]).len(), 2); + assert_eq!(s.undo_label().map(str::to_string), label_before); + assert!(!s.modified); + std::fs::remove_dir_all(dir).ok(); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e1746a31..6ed381eb 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1039,6 +1039,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "استيراد خرائط مخبوزة"), ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), ("Add...", "إضافة..."), - ("Imported {count} baked maps", "تم استيراد {count} من الخرائط المخبوزة"), + ("Baked maps imported: {count}", "الخرائط المخبوزة المستوردة: {count}"), ("Not imported: {files}", "لم يتم استيرادها: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 1b86b2e7..4d59f67f 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1082,6 +1082,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Gebackene Maps importieren"), ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), ("Add...", "Hinzufügen..."), - ("Imported {count} baked maps", "{count} gebackene Maps importiert"), + ("Baked maps imported: {count}", "Gebackene Maps importiert: {count}"), ("Not imported: {files}", "Nicht importiert: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index a0445eed..f8b84617 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1067,6 +1067,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas horneados"), ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), ("Add...", "Añadir..."), - ("Imported {count} baked maps", "{count} mapas horneados importados"), + ("Baked maps imported: {count}", "Mapas horneados importados: {count}"), ("Not imported: {files}", "Sin importar: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 235bf5a9..b282f90b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1091,6 +1091,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importer des cartes précalculées"), ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), ("Add...", "Ajouter..."), - ("Imported {count} baked maps", "{count} cartes précalculées importées"), + ("Baked maps imported: {count}", "Cartes précalculées importées : {count}"), ("Not imported: {files}", "Non importés : {files}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 12a180ed..5d937383 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1076,6 +1076,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importa mappe bake"), ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), ("Add...", "Aggiungi..."), - ("Imported {count} baked maps", "{count} mappe bake importate"), + ("Baked maps imported: {count}", "Mappe bake importate: {count}"), ("Not imported: {files}", "Non importati: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 8b930774..634660bd 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1061,6 +1061,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "ベイク済みマップを読み込む"), ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), ("Add...", "追加..."), - ("Imported {count} baked maps", "ベイク済みマップを {count} 個読み込みました"), + ("Baked maps imported: {count}", "読み込んだベイク済みマップ: {count}"), ("Not imported: {files}", "読み込まれなかったファイル: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 30d5eef5..cafc4b90 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1049,6 +1049,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "베이크된 맵 가져오기"), ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), ("Add...", "추가..."), - ("Imported {count} baked maps", "베이크된 맵 {count}개를 가져왔습니다"), + ("Baked maps imported: {count}", "가져온 베이크된 맵: {count}"), ("Not imported: {files}", "가져오지 않음: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 330c09a3..f7779924 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1064,6 +1064,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "Importar mapas com bake"), ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), ("Add...", "Adicionar..."), - ("Imported {count} baked maps", "{count} mapas com bake importados"), + ("Baked maps imported: {count}", "Mapas com bake importados: {count}"), ("Not imported: {files}", "Não importados: {files}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index f0731a7c..83044fc3 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1007,6 +1007,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Import baked maps", "导入已烘焙贴图"), ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), ("Add...", "添加..."), - ("Imported {count} baked maps", "已导入 {count} 张烘焙贴图"), + ("Baked maps imported: {count}", "已导入的烘焙贴图:{count}"), ("Not imported: {files}", "未导入:{files}"), ]; diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 50dd64c6..ae1993d1 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -1,5 +1,7 @@ //! New project ▸ Advanced settings: the normal map format, and baked map files imported at creation +use std::collections::BTreeSet; + use egui::{RichText, Sense, Ui, vec2}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; @@ -19,7 +21,7 @@ const FORM_LABELS: [&str; 6] = ["3D mesh", "Project template", "Document resolut const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, "openGl", "OpenGL"), (NormalFormat::DirectX, "directX", "DirectX")]; /// Width of the dialog's dropdowns -const COMBO_WIDTH: f32 = 200.0; +pub(crate) const COMBO_WIDTH: f32 = 200.0; /// Width of the Add... and Clear buttons const FILE_BUTTON_WIDTH: f32 = 96.0; @@ -64,8 +66,12 @@ pub(crate) fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let new_project = &mut app.ui.new_project; let user_templates = app.session.templates.list.iter().cloned(); - let template_format = - builtin_templates().into_iter().chain(user_templates).find(|t| t.name == new_project.template).map(|t| t.normal_format).unwrap_or_default(); + let template_format = builtin_templates() + .into_iter() + .chain(user_templates) + .find(|template| template.name == new_project.template) + .map(|template| template.normal_format) + .unwrap_or_default(); let current = new_project.normal_format.unwrap_or(template_format); let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); egui::ComboBox::from_id_salt("np_normal_format").width(COMBO_WIDTH).selected_text(current_label).show_ui(ui, |ui| { @@ -114,7 +120,7 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { } } -/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome +/// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { @@ -129,14 +135,16 @@ pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewPro return; }; - let assigned = result["assigned"].as_array().map_or(0, Vec::len); + let assigned = result["assigned"].as_array().into_iter().flatten(); + let maps: BTreeSet<(u64, &str)> = assigned.filter_map(|entry| Some((entry["ts"].as_u64()?, entry["map"].as_str()?))).collect(); let not_imported: Vec = result["unmatched"].as_array().into_iter().flatten().filter_map(Value::as_str).map(file_name).collect(); - let mut text = trf("Imported {count} baked maps", &[("count", &assigned)]); + let mut text = trf("Baked maps imported: {count}", &[("count", &maps.len())]); if !not_imported.is_empty() { text.push('\n'); text.push_str(&trf("Not imported: {files}", &[("files", ¬_imported.join(", "))])); } app.toast(text, !not_imported.is_empty()); + app.ui.new_project.baked_maps.clear(); } fn file_name(path: &str) -> String { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8ac07749..4bd8197f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -11,6 +11,7 @@ use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; +use crate::new_project_advanced::COMBO_WIDTH; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; @@ -388,6 +389,7 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { return; } + let mut open = true; let mut create = false; dialog("new_project", tr("New project"), &mut open).show(ctx, |ui| { @@ -399,13 +401,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { BUILTINS .iter() .find(|(id, _)| *id == app.ui.new_project.mesh) - .map(|(_, l)| trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .map(|(_, builtin_label)| trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))])) .unwrap_or_default() }); - egui::ComboBox::from_id_salt("np_mesh").width(200.0).selected_text(label).show_ui(ui, |ui| { - for (id, l) in BUILTINS { + egui::ComboBox::from_id_salt("np_mesh").width(COMBO_WIDTH).selected_text(label).show_ui(ui, |ui| { + for (id, builtin_label) in BUILTINS { if ui - .selectable_label(app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), trf("Built-in: {mesh}", &[("mesh", &tr(l))])) + .selectable_label( + app.ui.new_project.mesh == id && app.ui.new_project.file.is_none(), + trf("Built-in: {mesh}", &[("mesh", &tr(builtin_label))]), + ) .clicked() { app.ui.new_project.mesh = id.to_string(); @@ -415,21 +420,21 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); if file_dialogs_available() && ui.button(tr("Select...")).clicked() - && let Some(p) = pick_mesh_file() + && let Some(path) = pick_mesh_file() { - app.ui.new_project.file = Some(p); + app.ui.new_project.file = Some(path); } }); ui.end_row(); ui.label(tr("Project template")); - let np = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(200.0).selected_text(np.template.clone()).show_ui(ui, |ui| { - let user = app.session.templates.list.iter(); - for t in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user) { - if ui.selectable_label(t.name == np.template, &t.name).clicked() { - np.template = t.name.clone(); - np.resolution = t.resolution; - np.normal_format = None; + let new_project = &mut app.ui.new_project; + egui::ComboBox::from_id_salt("np_template").width(COMBO_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + let user_templates = app.session.templates.list.iter(); + for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { + if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { + new_project.template = template.name.clone(); + new_project.resolution = template.resolution; + new_project.normal_format = None; } } }); @@ -448,20 +453,20 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); ui.label(tr("Document resolution")); egui::ComboBox::from_id_salt("np_res").selected_text(format!("{0} x {0}", app.ui.new_project.resolution)).show_ui(ui, |ui| { - for r in [512u32, 1024, 2048, 4096] { - ui.selectable_value(&mut app.ui.new_project.resolution, r, format!("{r} x {r}")); + for size in [512u32, 1024, 2048, 4096] { + ui.selectable_value(&mut app.ui.new_project.resolution, size, format!("{size} x {size}")); } }); ui.end_row(); ui.label(tr("UV tiles (UDIM)")); - let tiles_label = |m: Option| match m { + let tiles_label = |tiles: Option| match tiles { None => tr("Automatic (from the mesh UVs)"), Some(true) => tr("On"), Some(false) => tr("Off"), }; egui::ComboBox::from_id_salt("np_tiles").selected_text(tiles_label(app.ui.new_project.uv_tiles)).show_ui(ui, |ui| { - for m in [None, Some(true), Some(false)] { - ui.selectable_value(&mut app.ui.new_project.uv_tiles, m, tiles_label(m)); + for tiles in [None, Some(true), Some(false)] { + ui.selectable_value(&mut app.ui.new_project.uv_tiles, tiles, tiles_label(tiles)); } }); ui.end_row(); @@ -484,17 +489,16 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); if create { - let np = app.ui.new_project.clone(); - let (cmd, mesh) = match &np.file { + let new_project = app.ui.new_project.clone(); + let (command, mesh) = match &new_project.file { Some(path) => ("file.new", path.clone()), - None => ("project.new", np.mesh.clone()), + None => ("project.new", new_project.mesh.clone()), }; - let r = app.run(cmd, json!({"mesh": mesh, "resolution": np.resolution, "name": np.name, "uvTiles": np.uv_tiles, "template": np.template})).map(|_| ()); - if r.is_some() { + let params = json!({"mesh": mesh, "resolution": new_project.resolution, "name": new_project.name, "uvTiles": new_project.uv_tiles, "template": new_project.template}); + if app.run(command, params).is_some() { app.ui.windows.new_project = false; app.ui.mode = Mode::Painting; - app.ui.new_project.baked_maps.clear(); - crate::new_project_advanced::apply_after_create(app, &np); + crate::new_project_advanced::apply_after_create(app, &new_project); } } if !open { diff --git a/crates/ui-egui/tests/new_project_baked_maps.rs b/crates/ui-egui/tests/new_project_baked_maps.rs index a2c95e98..5b1d7615 100644 --- a/crates/ui-egui/tests/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/new_project_baked_maps.rs @@ -21,7 +21,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { h } -/// 4×4 PNGs named `files` in a fresh folder, as their full paths +/// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read fn bake_files(test: &str, files: &[&str]) -> Vec { let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -29,7 +29,7 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { .iter() .map(|file| { let path: PathBuf = dir.join(file); - image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 255, 255])).save(&path).unwrap(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 51, 255, 255])).save(&path).unwrap(); path.display().to_string() }) .collect() @@ -70,11 +70,13 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { assert!(!state.ui.windows.new_project, "the dialog closes"); let project = &state.session.doc.project; assert_eq!(project.normal_format, NormalFormat::DirectX); - let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|b| b.maps.contains_key(&map)); + let baked = |ts: usize, map: BakedMap| state.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); assert!(baked(0, BakedMap::Normal) && baked(1, BakedMap::AmbientOcclusion)); + let normal_green = state.session.doc.baked[&0].maps[&BakedMap::Normal][1]; + assert!(normal_green > 0.75, "the normal map is read as DirectX (green flipped): {normal_green}"); assert_eq!(state.session.doc.resources.len(), 2, "the file naming no map is not imported"); let toast = &state.toasts.last().unwrap().text; - assert!(toast.contains("Imported 2 baked maps") && toast.contains("Ball_notes.png"), "{toast}"); + assert!(toast.contains("Baked maps imported: 2") && toast.contains("Ball_notes.png"), "{toast}"); assert!(state.ui.new_project.baked_maps.is_empty(), "the next new project starts with no files"); assert_eq!(state.session.undo_label(), Some("Import baked maps")); } From 4543c858122565b13529299e8715b31fc7c990db Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 10:32:33 +0000 Subject: [PATCH 068/275] Reset icon on each brush section header Each brush section header gets a reset icon at its right end that puts only that section's settings back to their defaults; dimmed and inert while already at them. Docked Properties uses the solid scroll bar so the icon sits flush right. --- crates/ui-egui/src/dock.rs | 191 ++++++++++++-------- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/widgets.rs | 56 +++++- crates/ui-egui/tests/brush_section_reset.rs | 123 +++++++++++++ 12 files changed, 300 insertions(+), 79 deletions(-) create mode 100644 crates/ui-egui/tests/brush_section_reset.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..2799dbca 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -9,7 +9,7 @@ use texturecraft_engine::core::{ Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; @@ -17,7 +17,8 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, section_with_reset, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -924,6 +925,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { + // A floating scroll bar would cover the right-aligned slider values and section reset icons + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } @@ -1144,104 +1147,150 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Font size of the dim hint line under the Brush caption +const HINT_TEXT_SIZE: f32 = 10.5; + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let b = &mut app.session.tool.brush; + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); ui.label(caption(tr("Brush"))); let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); - section(ui, "sec_size", tr("Size"), true, |ui| { - let mut size = b.size / 0.25 * 100.0; - if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); + ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); + + // Each section's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); + if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - let mut ms = b.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut ms, 0.0..=100.0, 0).changed() { - b.min_size = ms / 100.0; + + let mut min_size_percent = brush.min_size * 100.0; + if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { + brush.min_size = min_size_percent / 100.0; } - ui.checkbox(&mut b.screen_space, tr("Size in screen space")); - }); - section(ui, "sec_flow", tr("Flow and opacity"), true, |ui| { - let mut f = b.flow * 100.0; - if slider(ui, tr("Flow"), &mut f, 0.0..=100.0, 0).changed() { - b.flow = f / 100.0; + + ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); + }) { + (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); + } + + let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness); + if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { + let mut flow_percent = brush.flow * 100.0; + if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { + brush.flow = flow_percent / 100.0; } - let mut o = b.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut o, 0.0..=100.0, 0).changed() { - b.opacity = o / 100.0; + + let mut opacity_percent = brush.opacity * 100.0; + if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { + brush.opacity = opacity_percent / 100.0; } - let mut s = b.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut s, 1.0..=1000.0, 0).changed() { - b.spacing = s / 100.0; + + let mut spacing_percent = brush.spacing * 100.0; + if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { + brush.spacing = spacing_percent / 100.0; } - let mut h = b.hardness * 100.0; - if slider(ui, tr("Hardness"), &mut h, 0.0..=99.9, 0).changed() { - b.hardness = h / 100.0; + + let mut hardness_percent = brush.hardness * 100.0; + if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() { + brush.hardness = hardness_percent / 100.0; } - }); - section(ui, "sec_angle", tr("Angle"), false, |ui| { - slider(ui, tr("Angle"), &mut b.angle, -180.0..=180.0, 0); - ui.checkbox(&mut b.follow_path, tr("Follow path")); - }); - section(ui, "sec_jitter", tr("Jitters"), false, |ui| { - for (label, v) in [(tr("Size jitter"), &mut b.jitter_size), (tr("Angle jitter"), &mut b.jitter_angle), (tr("Flow jitter"), &mut b.jitter_flow)] { - let mut x = *v * 100.0; - if slider(ui, label, &mut x, 0.0..=100.0, 0).changed() { - *v = x / 100.0; + }) { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults); + } + + let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { + slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); + ui.checkbox(&mut brush.follow_path, tr("Follow path")); + }) { + (brush.angle, brush.follow_path) = angle_fields(&defaults); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); + if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { + let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; + for (label, jitter) in jitters { + let mut jitter_percent = *jitter * 100.0; + if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { + *jitter = jitter_percent / 100.0; } } - let mut pj = b.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut pj, 0.0..=400.0, 0).changed() { - b.jitter_position = pj / 100.0; + + let mut position_jitter_percent = brush.jitter_position * 100.0; + if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { + brush.jitter_position = position_jitter_percent / 100.0; } - }); - section(ui, "sec_align", tr("Alignment and culling"), false, |ui| { + }) { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); + } + + let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); + if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { use texturecraft_engine::paint::Alignment; let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(a, _)| *a == b.alignment).map_or("", |(_, l)| l); + let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); combo(ui, tr("Alignment"), shown, |ui| { - for (a, l) in alignments { - ui.selectable_value(&mut b.alignment, a, l); + for (alignment, label) in alignments { + ui.selectable_value(&mut brush.alignment, alignment, label); } }); - ui.checkbox(&mut b.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut b.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut b.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut b.depth, 0.05..=4.0, 2); - }); - section(ui, "sec_particles", tr("Particles"), false, |ui| { - let pt = &mut b.particles; - ui.checkbox(&mut pt.enabled, tr("Particle brush (slides down the surface)")); - let mut count = pt.count as f32; + + ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); + slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); + slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); + slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); + }) { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); + } + + if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { + let particles = &mut brush.particles; + ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); + + let mut count = particles.count as f32; if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - pt.count = count as u32; + particles.count = count as u32; } - let mut life = pt.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut life, 1.0..=128.0, 0).changed() { - pt.lifetime = life as u32; + + let mut lifetime_steps = particles.lifetime as f32; + if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { + particles.lifetime = lifetime_steps as u32; } - slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2); - }); - section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0); + + slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); + }) { + brush.particles = defaults.particles; + } + + let lazy_fields = |settings: &BrushSettings| (settings.lazy, settings.symmetry); + if section_with_reset(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, lazy_fields(brush) == lazy_fields(&defaults), |ui| { + slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); ui.horizontal(|ui| { - ui.checkbox(&mut b.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut b.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut b.symmetry.z, tr("Mirror Z")); + ui.checkbox(&mut brush.symmetry.x, tr("Mirror X")); + ui.checkbox(&mut brush.symmetry.y, tr("Mirror Y")); + ui.checkbox(&mut brush.symmetry.z, tr("Mirror Z")); }); - let mut copies = f32::from(b.symmetry.radial); + + let mut copies = f32::from(brush.symmetry.radial); if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - b.symmetry.radial = copies as u8; + brush.symmetry.radial = copies as u8; } - ui.add_enabled_ui(b.symmetry.radial > 1, |ui| { + + ui.add_enabled_ui(brush.symmetry.radial > 1, |ui| { ui.horizontal(|ui| { ui.label(tr("Radial axis")); - for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut b.symmetry.axis, k as u8, name); + for (axis_index, name) in ["X", "Y", "Z"].into_iter().enumerate() { + ui.selectable_value(&mut brush.symmetry.axis, axis_index as u8, name); } }); }); - }); - *b = b.sanitized(); + }) { + (brush.lazy, brush.symmetry) = lazy_fields(&defaults); + } + + *brush = brush.sanitized(); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..ab5b6dec 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -646,6 +646,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), + ("Reset to defaults", "إعادة الضبط إلى الإعدادات الافتراضية"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..224275cf 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -685,6 +685,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Bibliotheksordner neu einlesen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), + ("Reset to defaults", "Auf Standardwerte zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..8df454f8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -673,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), + ("Reset to defaults", "Restablecer valores predeterminados"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..77df362b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -688,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), + ("Reset to defaults", "Rétablir les valeurs par défaut"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a22f6bd3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -682,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), + ("Reset to defaults", "Ripristina i valori predefiniti"), ("Reset to {shortcut}", "Ripristina {shortcut}"), ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d4c52347 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -664,6 +664,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), + ("Reset to defaults", "デフォルトに戻す"), ("Reset to {shortcut}", "{shortcut} にリセット"), ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..a96df9c3 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -655,6 +655,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), + ("Reset to defaults", "기본값으로 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..496f3c7c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -670,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), + ("Reset to defaults", "Redefinir para o padrão"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..bf2c959c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -616,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "重新扫描库文件夹"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), + ("Reset to defaults", "恢复默认值"), ("Reset to {shortcut}", "重置为 {shortcut}"), ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..80b7fa90 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::i18n::tr; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -261,23 +262,62 @@ pub(crate) fn section_chevron(ui: &Ui, is_open: bool) -> RichText { /// A collapsible section header with a chevron pub fn section(ui: &mut Ui, id: &str, title: &str, default_open: bool, body: impl FnOnce(&mut Ui)) { + collapsible_section(ui, id, title, default_open, None, body); +} + +/// A [`section`] whose header ends in a reset icon, inert while `at_default`; true when clicked +pub fn section_with_reset(ui: &mut Ui, id: &str, title: &str, default_open: bool, at_default: bool, body: impl FnOnce(&mut Ui)) -> bool { + collapsible_section(ui, id, title, default_open, Some(at_default), body) +} + +/// Glyph size of a section header's reset icon +const SECTION_RESET_ICON_SIZE: f32 = 14.0; + +/// How much of `text_dim` the reset icon keeps while its section is at its defaults +const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// The header row and body of [`section`]; `reset_at_default` adds the reset icon +fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); - let response = ui - .horizontal(|ui| { - ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); - ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); - }) - .response - .interact(Sense::click()); - if response.clicked() { + + let mut reset_rect = None; + let header = ui.horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); + ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); + if reset_at_default.is_some() { + let icon_size = vec2(SECTION_RESET_ICON_SIZE, SECTION_RESET_ICON_SIZE); + reset_rect = Some(ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.allocate_exact_size(icon_size, Sense::hover()).0).inner); + } + }); + if header.response.interact(Sense::click()).clicked() { collapsing_state.toggle(ui); } + // Registered after the header so the icon, not the header, takes its clicks + let mut reset_clicked = false; + if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { + let response = ui.interact(rect, id.with("reset"), Sense::click()).on_hover_text(tr("Reset to defaults")); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, tr("Reset to defaults"))); + + let color = if at_default { + tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) + } else if response.hovered() { + tokens.text_strong + } else { + tokens.text_dim + }; + let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + reset_clicked = response.clicked() && !at_default; + } + collapsing_state.show_body_unindented(ui, |ui| { ui.indent(id.with("in"), body); }); + + reset_clicked } /// A channel chip ("color", "metal", "rough"…): toggled = the accent-tinted well. diff --git a/crates/ui-egui/tests/brush_section_reset.rs b/crates/ui-egui/tests/brush_section_reset.rs new file mode 100644 index 00000000..198b618c --- /dev/null +++ b/crates/ui-egui/tests/brush_section_reset.rs @@ -0,0 +1,123 @@ +//! Each brush section header has a reset icon that puts only that section's settings back to their defaults + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::paint::{Alignment, BrushSettings, Particles, Symmetry}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click to reach the brush settings and the panel +const SETTLE_FRAMES: usize = 3; + +/// Puts one section's fields of the first brush back to the second's values +type SectionReset = fn(&mut BrushSettings, &BrushSettings); + +/// A brush that differs from the defaults in every field a section shows, within the valid ranges +fn changed_brush() -> BrushSettings { + BrushSettings { + size: 0.1, + min_size: 0.5, + screen_space: true, + flow: 0.5, + opacity: 0.6, + spacing: 0.5, + hardness: 0.9, + angle: 45.0, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.4, + jitter_flow: 0.3, + jitter_position: 1.0, + alignment: Alignment::Camera, + backface_culling: false, + angle_fade: (30.0, 60.0), + depth: 2.0, + particles: Particles { enabled: true, count: 8, lifetime: 12, gravity: 0.5 }, + lazy: 50.0, + symmetry: Symmetry { x: true, y: false, z: true, radial: 4, axis: 2 }, + ..BrushSettings::default() + } +} + +/// The app showing the brush in Properties, set to `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The reset icon on the header row titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + // "Size" and "Angle" also label sliders, so match the title on the icon's row + let on_title_row = |icon: egui::Rect| harness.query_all_by_label(title).any(|label| label.rect().y_range().intersects(icon.y_range())); + harness.query_all_by_label("Reset to defaults").find(|icon| on_title_row(icon.rect())).unwrap_or_else(|| panic!("no reset icon on the {title} header")) +} + +/// Scrolls the header titled `title` into view and clicks its reset icon +fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + reset_icon(harness, title).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn each_reset_puts_back_only_its_own_section() { + let defaults = BrushSettings::default(); + let sections: [(&str, SectionReset); 7] = [ + ("Size", |brush, defaults| (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space)), + ("Flow and opacity", |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse and symmetry", |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), + ]; + + for (title, reset_section) in sections { + let mut harness = app_with_brush(changed_brush()); + click_reset(&mut harness, title); + + let mut expected = changed_brush(); + reset_section(&mut expected, &defaults); + assert_eq!(harness.state().session.tool.brush, expected, "resetting {title}"); + } +} + +#[test] +fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { + let mut harness = app_with_brush(changed_brush()); + + click_reset(&mut harness, "Size"); + assert!(harness.query_by_label("Minimum size (%)").is_some(), "Size starts open and stays open"); + + click_reset(&mut harness, "Jitters"); + assert!(harness.query_by_label("Size jitter").is_none(), "Jitters starts closed and stays closed"); +} + +#[test] +fn at_the_defaults_the_reset_icon_does_nothing() { + let mut harness = app_with_brush(BrushSettings::default()); + + click_reset(&mut harness, "Size"); + assert_eq!(harness.state().session.tool.brush, BrushSettings::default()); + assert!(harness.query_by_label("Minimum size (%)").is_some(), "the click doesn't reach the header"); +} From 3836730030e719f4db76aca7c884e106f6ce9bcf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 11:43:05 +0000 Subject: [PATCH 069/275] X inverts the mask paint value while painting a mask New command tool.swapMaskValue (mask value becomes 1 - value), default shortcut X, enabled only while the selected layer's mask or one of its mask effects is the paint target. Ctrl+X stays cut. Closes #332. --- crates/engine/src/tool_cmds.rs | 34 +++++++++++++- crates/engine/tests/tools.rs | 35 +++++++++++++- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/tests/mask_value_swap.rs | 61 +++++++++++++++++++++++++ 12 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/tests/mask_value_swap.rs diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..e4d61f67 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,7 +7,7 @@ use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::session::{CloneFrom, CloneSource, FillMode, StackTarget, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -51,6 +51,15 @@ pub fn specs() -> Vec { always, material ), + cmd!( + "tool.swapMaskValue", + "Invert mask value", + ["Tools"], + Some("X"), + "{} — mask value becomes 1 − value: switch the brush between adding to and removing from the mask", + paints_mask, + swap_mask_value + ), cmd!( "tool.stencil", "Projection stencil", @@ -252,6 +261,29 @@ fn material(s: &mut Session, p: &Value) -> Result { })) } +/// Whether strokes paint the selected layer's mask: the mask itself or one of its effects +fn paints_mask(s: &Session) -> std::result::Result<(), String> { + s.selected_layer().ok_or("no layer selected")?; + + let project = &s.doc.project; + let targets_mask = match s.target { + StackTarget::Content => false, + StackTarget::Mask => true, + StackTarget::Effect(effect_id) => project + .effect(effect_id) + .and_then(|(owner, _)| project.layers.get(&owner)) + .is_some_and(|owner_layer| !owner_layer.content_effects.iter().any(|effect| effect.id == effect_id)), + }; + + if targets_mask { Ok(()) } else { Err("select a mask to paint on".into()) } +} + +fn swap_mask_value(s: &mut Session, _: &Value) -> Result { + s.tool.mask_value = 1.0 - s.tool.mask_value; + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "maskValue": s.tool.mask_value })) +} + fn stencil(s: &mut Session, p: &Value) -> Result { if boolp(p, "clear") == Some(true) { s.tool.stencil = None; diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/tools.rs index dcd65100..a8130797 100644 --- a/crates/engine/tests/tools.rs +++ b/crates/engine/tests/tools.rs @@ -2,10 +2,10 @@ //! agents paint. use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{Channel, LayerId}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, StackTarget, execute}; const RES: f32 = 256.0; @@ -180,3 +180,34 @@ fn quick_mask_limits_painting() { dab(&mut s, 150.0, 200.0); assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } + +#[test] +fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { + let mut s = session(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let swap = |s: &mut Session| execute(s, "tool.swapMaskValue", &Value::Null); + let effect_target = |v: Value| StackTarget::Effect(LayerId(v["effect"].as_u64().unwrap())); + + assert!(swap(&mut s).is_err(), "painting the layer content: nothing to invert"); + + let content_effect = effect_target(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap()); + s.target = content_effect; + assert!(swap(&mut s).is_err(), "a content effect is not a mask"); + + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + s.target = StackTarget::Mask; + s.tool.mask_value = 0.2; + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.8); + + s.tool.mask_value = 1.0; + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.0); + + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 1.0, "pressing it again goes back"); + + s.target = effect_target(execute(&mut s, "effect.add.paint", &json!({"target": "mask"})).unwrap()); + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.0, "a mask effect paints the mask too"); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..948b1a66 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -416,6 +416,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "عكس"), ("Invert mask", "عكس القناع"), ("Invert mask background", "عكس خلفية القناع"), + ("Invert mask value", "عكس قيمة القناع"), ("Invert quick mask", "عكس القناع السريع"), ("Jitters", "اضطرابات (Jitters)"), ("Join the ArtCraft community on Discord", "انضم إلى مجتمع ArtCraft على Discord"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..4341e1b5 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -443,6 +443,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertieren"), ("Invert mask", "Maske invertieren"), ("Invert mask background", "Maskenhintergrund invertieren"), + ("Invert mask value", "Maskenwert invertieren"), ("Invert quick mask", "Schnellmaske invertieren"), ("Jitters", "Streuung"), ("Join the ArtCraft community on Discord", "Der ArtCraft-Community auf Discord beitreten"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..50e64695 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -434,6 +434,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertir"), ("Invert mask", "Invertir máscara"), ("Invert mask background", "Invertir fondo de la máscara"), + ("Invert mask value", "Invertir valor de máscara"), ("Invert quick mask", "Invertir máscara rápida"), ("Jitters", "Variaciones"), ("Join the ArtCraft community on Discord", "Únete a la comunidad de ArtCraft en Discord"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..85f061ae 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -446,6 +446,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverser"), ("Invert mask", "Inverser le masque"), ("Invert mask background", "Inverser le fond du masque"), + ("Invert mask value", "Inverser la valeur du masque"), ("Invert quick mask", "Inverser le masque rapide"), ("Jitters", "Variations"), ("Join the ArtCraft community on Discord", "Rejoindre la communauté ArtCraft sur Discord"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..4a0e374b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -437,6 +437,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverti"), ("Invert mask", "Inverti maschera"), ("Invert mask background", "Inverti sfondo maschera"), + ("Invert mask value", "Inverti valore maschera"), ("Invert quick mask", "Inverti maschera rapida"), ("Jitters", "Variazioni"), ("Join the ArtCraft community on Discord", "Unisciti alla community di ArtCraft su Discord"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d7036576 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -428,6 +428,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反転"), ("Invert mask", "マスクを反転"), ("Invert mask background", "マスクの背景を反転"), + ("Invert mask value", "マスク値を反転"), ("Invert quick mask", "クイックマスクを反転"), ("Jitters", "ジッター"), ("Join the ArtCraft community on Discord", "DiscordでArtCraftコミュニティに参加"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..68fc23d2 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -422,6 +422,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "반전"), ("Invert mask", "마스크 반전"), ("Invert mask background", "마스크 배경 반전"), + ("Invert mask value", "마스크 값 반전"), ("Invert quick mask", "퀵 마스크 반전"), ("Jitters", "지터"), ("Join the ArtCraft community on Discord", "Discord에서 ArtCraft 커뮤니티에 참여하세요"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..f1ff8397 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -431,6 +431,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverter"), ("Invert mask", "Inverter máscara"), ("Invert mask background", "Inverter fundo da máscara"), + ("Invert mask value", "Inverter valor da máscara"), ("Invert quick mask", "Inverter máscara rápida"), ("Jitters", "Variações"), ("Join the ArtCraft community on Discord", "Participe da comunidade ArtCraft no Discord"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..cd813723 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -389,6 +389,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反相"), ("Invert mask", "反相遮罩"), ("Invert mask background", "反相遮罩背景"), + ("Invert mask value", "反相遮罩值"), ("Invert quick mask", "反相快速遮罩"), ("Jitters", "抖动"), ("Join the ArtCraft community on Discord", "加入 Discord 上的 ArtCraft 社区"), diff --git a/crates/ui-egui/tests/mask_value_swap.rs b/crates/ui-egui/tests/mask_value_swap.rs new file mode 100644 index 00000000..37f79daf --- /dev/null +++ b/crates/ui-egui/tests/mask_value_swap.rs @@ -0,0 +1,61 @@ +//! X inverts the mask value while a mask is the paint target; Ctrl+X still cuts the layer + +use egui_kittest::Harness; +use texturecraft_engine::StackTarget; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with a white mask on its selected layer, painting that mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); + session.target = StackTarget::Mask; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn mask_value(h: &Harness<'_, TextureCraftApp>) -> f32 { + h.state().session.tool.mask_value +} + +#[test] +fn x_inverts_the_mask_value_and_back() { + let mut h = harness(); + h.state_mut().session.tool.mask_value = 0.25; + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.75); + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} + +#[test] +fn x_does_nothing_while_painting_layer_content() { + let mut h = harness(); + h.state_mut().session.target = StackTarget::Content; + h.state_mut().session.tool.mask_value = 0.25; + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} + +#[test] +fn ctrl_x_still_cuts_the_layer_while_a_mask_is_the_target() { + let mut h = harness(); + let layer = h.state().session.selected_layer().unwrap(); + h.event(egui::Event::Cut); + h.run_steps(3); + assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Ctrl+X removes the layer"); +} + +#[test] +fn ctrl_x_is_not_x() { + let mut h = harness(); + // With cut unbound, nothing else may answer Ctrl+X + h.state_mut().ui.keymap.insert("layer.cut".into(), String::new()); + h.state_mut().session.tool.mask_value = 0.25; + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} From ed45aa080705602a8088b63ed2719a68d3a9cb26 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 12:33:01 +0000 Subject: [PATCH 070/275] Levels: edit the input range, gamma and output range on the histogram Drag the input low, gamma and input high handles above the histogram and the output low/high handles under a black-to-white strip; double-click a handle to type its value. Reset, Auto and Invert replace the five sliders. Every drag is one undo step through effect.set. --- crates/ui-egui/src/dock.rs | 49 +--- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/levels_editor.rs | 313 ++++++++++++++++++++++++ crates/ui-egui/src/levels_handle.rs | 91 +++++++ crates/ui-egui/src/levels_properties.rs | 130 ++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/widgets.rs | 25 -- crates/ui-egui/tests/effect_sliders.rs | 6 +- crates/ui-egui/tests/levels_editor.rs | 247 +++++++++++++++++++ 17 files changed, 816 insertions(+), 75 deletions(-) create mode 100644 crates/ui-egui/src/levels_editor.rs create mode 100644 crates/ui-egui/src/levels_handle.rs create mode 100644 crates/ui-egui/src/levels_properties.rs create mode 100644 crates/ui-egui/tests/levels_editor.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..bf24149b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -17,7 +17,7 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -1918,20 +1918,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } } - EffectKind::Levels(l) => { - ui.label(caption(tr("Levels"))); - levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); - let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; - let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; - let mut edit = None; - for (i, label) in labels.iter().enumerate() { - let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge})); - } - } + EffectKind::Levels(l) => crate::levels_properties::levels_properties(app, ui, layer, eid, l), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2026,38 +2013,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } -/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel -/// picked here), with the input range marked. Recomputed after a document change once no -/// pointer button is held, so dragging a slider keeps the last one. -fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) { - let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor); - if layer.content_effects.iter().any(|e| e.id == eid) { - let pick = egui::Id::unique(("levels_channel", eid.0)); - let chans: Vec = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect(); - channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel); - combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == channel, tr(c.label())).clicked() { - ui.data_mut(|d| d.insert_temp(pick, c)); - } - } - }); - } - let key = egui::Id::unique(("levels_histogram", eid.0, channel)); - let rev = app.session.revision; - let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc>)>(key)) { - Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h), - _ => app.session.effect_histogram(eid, channel, 64).map(|h| { - let h = std::sync::Arc::new(h); - ui.data_mut(|d| d.insert_temp(key, (rev, h.clone()))); - h - }), - }; - if let Some(counts) = counts { - histogram(ui, &counts, range); - } -} - /// The parameters of filter effect `id`. fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..26bd6066 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), + ("Auto", "تلقائي"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), ("Autosave every", "حفظ تلقائي كل"), ( @@ -308,6 +309,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), ("Fingerprints", "بصمات أصابع"), + ("Fit the input range to the histogram", "ملاءمة نطاق الإدخال مع المدرج التكراري"), ("Flatten layer", "تسطيح الطبقة"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -644,6 +646,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), + ("Reset", "إعادة تعيين"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..8906dea3 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), ("Autosave every", "Automatisch speichern alle"), ( @@ -332,6 +333,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), ("Fingerprints", "Fingerabdrücke"), + ("Fit the input range to the histogram", "Eingabebereich an das Histogramm anpassen"), ("Flatten layer", "Ebene reduzieren"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -683,6 +685,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), + ("Reset", "Zurücksetzen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..319d99ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), ("Autosave every", "Autoguardar cada"), ( @@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), ("Fingerprints", "Huellas dactilares"), + ("Fit the input range to the histogram", "Ajustar el rango de entrada al histograma"), ("Flatten layer", "Acoplar capa"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -671,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), + ("Reset", "Restablecer"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..ab69ad41 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), ("Autosave every", "Sauvegarde automatique toutes les"), ( @@ -335,6 +336,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), ("Fingerprints", "Empreintes digitales"), + ("Fit the input range to the histogram", "Ajuster la plage d'entrée à l'histogramme"), ("Flatten layer", "Aplatir le calque"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -686,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), + ("Reset", "Réinitialiser"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..19a53171 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), ("Autosave every", "Salvataggio automatico ogni"), ( @@ -329,6 +330,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), ("Fingerprints", "Impronte digitali"), + ("Fit the input range to the histogram", "Adatta l'intervallo di input all'istogramma"), ("Flatten layer", "Appiattisci livello"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -680,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), + ("Reset", "Reimposta"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), ("Reset to {shortcut}", "Ripristina {shortcut}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..ed70cda4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), + ("Auto", "自動"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), ("Autosave every", "自動保存の間隔"), ( @@ -320,6 +321,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), ("Fingerprints", "指紋"), + ("Fit the input range to the histogram", "入力範囲をヒストグラムに合わせる"), ("Flatten layer", "レイヤーを統合"), ("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"), ("Flow", "フロー"), @@ -662,6 +664,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), + ("Reset", "リセット"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), ("Reset to {shortcut}", "{shortcut} にリセット"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..4e9cbdfe 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), + ("Auto", "자동"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), ("Autosave every", "자동 저장 간격"), ( @@ -317,6 +318,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "필터"), ("Fine noise", "미세 노이즈"), ("Fingerprints", "지문"), + ("Fit the input range to the histogram", "입력 범위를 히스토그램에 맞추기"), ("Flatten layer", "레이어 병합"), ("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"), ("Flow", "흐름"), @@ -653,6 +655,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), + ("Reset", "초기화"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..68676186 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), ("Autosave every", "Salvar automaticamente a cada"), ( @@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), ("Fingerprints", "Impressões digitais"), + ("Fit the input range to the histogram", "Ajustar o intervalo de entrada ao histograma"), ("Flatten layer", "Achatar camada"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -668,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), + ("Reset", "Redefinir"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..5f12ab99 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -71,6 +71,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), + ("Auto", "自动"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), ("Autosave every", "自动保存间隔"), ( @@ -290,6 +291,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "滤镜"), ("Fine noise", "细噪波"), ("Fingerprints", "指纹"), + ("Fit the input range to the histogram", "使输入范围适合直方图"), ("Flatten layer", "合并图层"), ("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"), ("Flow", "流量"), @@ -614,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), + ("Reset", "重置"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), ("Reset to {shortcut}", "重置为 {shortcut}"), diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs new file mode 100644 index 00000000..55e2d53d --- /dev/null +++ b/crates/ui-egui/src/levels_editor.rs @@ -0,0 +1,313 @@ +//! The levels editor: draggable handles over a histogram and an output gradient, double-click to type a value + +use egui::{Color32, CornerRadius, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use texturecraft_engine::core::Levels; + +use crate::levels_handle::LevelsHandle; +use crate::theme::Tokens; + +const HISTOGRAM_HEIGHT: f32 = 56.0; +const HANDLE_HEIGHT: f32 = 11.0; +const HANDLE_HALF_WIDTH: f32 = 5.0; + +/// Height of a handle's straight sides; the rest is its tip pointing at the track +const HANDLE_SIDE_HEIGHT: f32 = 6.0; + +/// Extra width on each side of a handle that still grabs it +const HANDLE_GRAB_MARGIN: f32 = 2.0; + +const GRADIENT_HEIGHT: f32 = 8.0; +const GAP_BELOW_HISTOGRAM: f32 = 3.0; +const VALUE_ROW_HEIGHT: f32 = 16.0; +const VALUE_FONT_SIZE: f32 = 10.5; + +/// Width of the box a value is typed into +const TYPED_VALUE_WIDTH: f32 = 52.0; + +/// Padding of the histogram well around its bars +const WELL_PADDING: f32 = 3.0; + +/// Gray of the gamma handle, between the black input-low and white input-high handles +const GAMMA_HANDLE_GRAY: u8 = 128; + +/// Grid lines across the histogram, at these fractions of its width +const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Decimals of a value typed in or printed beside a handle (printed without trailing zeros) +const VALUE_DECIMALS: usize = 3; + +/// Space kept around a printed value; a value closer to one already printed is left out +const VALUE_SPACING: f32 = 2.0; + +/// Text margin inside the box a value is typed into +const TYPED_VALUE_MARGIN: egui::Vec2 = vec2(2.0, 1.0); + +/// Opacity of the shade over the histogram outside the input range +const OUTSIDE_RANGE_SHADE: f32 = 0.7; + +/// Opacity of the line at gamma, fainter than the input range's accent lines +const GAMMA_LINE_OPACITY: f32 = 0.6; + +/// Edits `levels` over histogram `counts`; `Some(merge)` per change, `merge` true for a drag's later frames +pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, counts: Option<&[u32]>, levels: &mut Levels) -> Option { + let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT + GAP_BELOW_HISTOGRAM + GRADIENT_HEIGHT; + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + let histogram_top = rect.top() + VALUE_ROW_HEIGHT + HANDLE_HEIGHT; + let gradient_top = output_handles_top(rect) - GRADIENT_HEIGHT; + let track = track(rect); + let id = ui.make_persistent_id(("levels_editor", id_salt)); + + // Gamma goes last so it stays grabbable between input handles that close in on it + let handles = [LevelsHandle::InputLow, LevelsHandle::InputHigh, LevelsHandle::Gamma, LevelsHandle::OutputLow, LevelsHandle::OutputHigh]; + let mut edit = None; + let mut responses = Vec::with_capacity(handles.len()); + for handle in handles { + let x = track_x(&track, handle.position(levels)); + let top = handle_top(rect, handle); + let grab_half_width = HANDLE_HALF_WIDTH + HANDLE_GRAB_MARGIN; + let hit = Rect::from_x_y_ranges(x - grab_half_width..=x + grab_half_width, top..=top + HANDLE_HEIGHT); + let response = ui.interact(hit, id.with(handle), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand); + if response.drag_started() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + + if response.dragged() + && let Some(pointer) = response.interact_pointer_pos() + { + let mut next = *levels; + handle.set_position(&mut next, track_position(&track, pointer.x)); + if next != *levels { + *levels = next; + edit = Some(continues_drag(ui, response.id)); + } + } + + let value = handle.value(levels); + response.widget_info(|| WidgetInfo::slider(true, f64::from(value), handle.label())); + responses.push((handle, response)); + } + + let typing_id = id.with("typing"); + let double_clicked = responses.iter().find(|(_, response)| response.double_clicked()).map(|(handle, _)| *handle); + if let Some(handle) = double_clicked { + start_typing(ui, typing_id, handle, levels); + } + + let typing = ui.data(|data| data.get_temp::<(LevelsHandle, String)>(typing_id)); + + let well = Rect::from_x_y_ranges(rect.x_range().shrink(HANDLE_HALF_WIDTH), histogram_top..=histogram_top + HISTOGRAM_HEIGHT); + paint_histogram(ui, well, counts.unwrap_or_default(), levels); + paint_output_gradient(ui, Rect::from_x_y_ranges(track, gradient_top..=gradient_top + GRADIENT_HEIGHT)); + paint_handles_and_values(ui, rect, &responses, levels, typing.as_ref().map(|(handle, _)| *handle)); + let typed = typing.and_then(|(handle, text)| typed_value(ui, rect, typing_id, (handle, text), double_clicked.is_some(), levels)); + edit.or(typed) +} + +fn handle_top(rect: Rect, handle: LevelsHandle) -> f32 { + if LevelsHandle::INPUT.contains(&handle) { rect.top() + VALUE_ROW_HEIGHT } else { output_handles_top(rect) } +} + +fn output_handles_top(rect: Rect) -> f32 { + rect.bottom() - VALUE_ROW_HEIGHT - HANDLE_HEIGHT +} + +/// The x range the handles move along in the editor's `rect`, lined up with the histogram bars +fn track(rect: Rect) -> egui::Rangef { + rect.x_range().shrink(HANDLE_HALF_WIDTH + WELL_PADDING) +} + +fn track_x(track: &egui::Rangef, position: f32) -> f32 { + track.min + track.span() * position.clamp(0.0, 1.0) +} + +fn track_position(track: &egui::Rangef, x: f32) -> f32 { + ((x - track.min) / track.span().max(1.0)).clamp(0.0, 1.0) +} + +/// True once the drag of `id` has already changed a value, so its later changes share that undo step +fn continues_drag(ui: &Ui, id: Id) -> bool { + ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(id), true)) +} + +/// `value` with [`VALUE_DECIMALS`] decimals, trailing zeros dropped ("1", "0.25", "0.634") +fn shown_value(value: f32) -> String { + let fixed = format!("{value:.VALUE_DECIMALS$}"); + fixed.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// Where `handle`'s value of `size` goes: over an input handle, under an output one, inside `rect` +fn value_rect(rect: Rect, handle: LevelsHandle, levels: &Levels, size: egui::Vec2) -> Rect { + let x = track_x(&track(rect), handle.position(levels)); + let top = handle_top(rect, handle); + let placed = if LevelsHandle::INPUT.contains(&handle) { + egui::Align2::CENTER_BOTTOM.anchor_size(pos2(x, top), size) + } else { + egui::Align2::CENTER_TOP.anchor_size(pos2(x, top + HANDLE_HEIGHT), size) + }; + let shift = (rect.left() - placed.left()).max(0.0) + (rect.right() - placed.right()).min(0.0); + placed.translate(vec2(shift, 0.0)) +} + +/// The histogram in its well: quarter lines, the outside of the input range dimmed, lines at the handles +fn paint_histogram(ui: &Ui, well: Rect, counts: &[u32], levels: &Levels) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(well); + painter.rect(well, CornerRadius::same(tokens.radius), tokens.field, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + + let inner = well.shrink(WELL_PADDING); + let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, inner.top()), pos2(x, inner.bottom())], Stroke::new(1.0, color)); + for fraction in GRID_FRACTIONS { + vertical_line(track_x(&inner.x_range(), fraction), tokens.field_border); + } + + let fullest = counts.iter().copied().max().unwrap_or(0).max(1) as f32; + let bar_width = inner.width() / counts.len().max(1) as f32; + for (index, count) in counts.iter().enumerate() { + let bar_height = inner.height() * *count as f32 / fullest; + let x = inner.left() + index as f32 * bar_width; + painter.rect_filled(Rect::from_min_max(pos2(x, inner.bottom() - bar_height), pos2(x + bar_width, inner.bottom())), 0.0, tokens.text_dim); + } + + let x_at = |handle: LevelsHandle| track_x(&inner.x_range(), handle.position(levels)); + let (low, high) = (x_at(LevelsHandle::InputLow), x_at(LevelsHandle::InputHigh)); + let shade = tokens.field.gamma_multiply(OUTSIDE_RANGE_SHADE); + painter.rect_filled(Rect::from_x_y_ranges(inner.left()..=low, inner.y_range()), 0.0, shade); + painter.rect_filled(Rect::from_x_y_ranges(high..=inner.right(), inner.y_range()), 0.0, shade); + vertical_line(low, tokens.accent); + vertical_line(high, tokens.accent); + vertical_line(x_at(LevelsHandle::Gamma), tokens.text_dim.gamma_multiply(GAMMA_LINE_OPACITY)); +} + +/// A black-to-white strip: the output values the output handles pick from +fn paint_output_gradient(ui: &Ui, strip: Rect) { + let mut mesh = egui::Mesh::default(); + for (corner, color) in + [(strip.left_top(), Color32::BLACK), (strip.right_top(), Color32::WHITE), (strip.right_bottom(), Color32::WHITE), (strip.left_bottom(), Color32::BLACK)] + { + mesh.colored_vertex(corner, color); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + + let painter = ui.painter(); + painter.add(mesh); + painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); +} + +/// Each handle filled with its gray and its value beside it, the active one first and overlapping values left out +fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels, typing: Option) { + let track = track(rect); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let font = egui::FontId::proportional(VALUE_FONT_SIZE); + let is_active = |response: &Response| response.dragged() || response.hovered(); + let mut printed: Vec = Vec::new(); + let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_priority.sort_by_key(|(_, response)| !is_active(response)); + + for &(handle, ref response) in by_priority { + let x = track_x(&track, handle.position(levels)); + let fill = match handle { + LevelsHandle::InputLow => Color32::BLACK, + LevelsHandle::Gamma => Color32::from_gray(GAMMA_HANDLE_GRAY), + LevelsHandle::InputHigh => Color32::WHITE, + LevelsHandle::OutputLow | LevelsHandle::OutputHigh => Color32::from_gray((handle.value(levels).clamp(0.0, 1.0) * 255.0).round() as u8), + }; + let outline = if response.dragged() { + tokens.accent + } else if response.hovered() { + tokens.text_strong + } else { + tokens.text + }; + let points_down = LevelsHandle::INPUT.contains(&handle); + painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.0, outline))); + if typing == Some(handle) { + continue; + } + + let color = if is_active(response) { tokens.text_strong } else { tokens.text_dim }; + let galley = painter.layout_no_wrap(shown_value(handle.value(levels)), font.clone(), color); + let text_rect = value_rect(rect, handle, levels, galley.size()); + if printed.iter().any(|other| other.expand(VALUE_SPACING).intersects(text_rect)) { + continue; + } + + painter.galley(text_rect.min, galley, color); + printed.push(text_rect); + } +} + +/// A pentagon pointer centred on `x`: flat side away from the track, tip touching it +fn handle_outline(x: f32, top: f32, points_down: bool) -> Vec { + let bottom = top + HANDLE_HEIGHT; + let (flat, side_end, tip) = if points_down { (top, top + HANDLE_SIDE_HEIGHT, bottom) } else { (bottom, bottom - HANDLE_SIDE_HEIGHT, top) }; + vec![ + pos2(x - HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, side_end), + pos2(x, tip), + pos2(x - HANDLE_HALF_WIDTH, side_end), + ] +} + +/// Opens the box that types `handle`'s value, holding its current value +fn start_typing(ui: &Ui, typing_id: Id, handle: LevelsHandle, levels: &Levels) { + let text = format!("{:.VALUE_DECIMALS$}", handle.value(levels)); + ui.data_mut(|data| data.insert_temp(typing_id, (handle, text))); +} + +/// The floating box a value is typed into: Enter or a click elsewhere applies it as one undo step, Escape drops it +fn typed_value(ui: &Ui, rect: Rect, typing_id: Id, (handle, mut text): (LevelsHandle, String), opened: bool, levels: &mut Levels) -> Option { + let field_id = typing_id.with("field"); + let field = value_rect(rect, handle, levels, vec2(TYPED_VALUE_WIDTH, VALUE_ROW_HEIGHT)); + // Floating over the editor, so opening it never moves the rest of the panel + let response = egui::Area::new(typing_id.with("area")) + .order(egui::Order::Foreground) + .fixed_pos(field.min) + .show(ui.ctx(), |ui| { + let text_edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(egui::FontId::proportional(VALUE_FONT_SIZE)) + .align(egui::Align2::CENTER_CENTER) + .margin(TYPED_VALUE_MARGIN); + ui.add_sized(field.size(), text_edit) + }) + .inner; + + // The app can consume Escape before the box sees it, so read the raw event + let escape = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + + if opened { + // Typing replaces the value; selected only now, as the unfocused box collapses a selection + let mut state = egui::text_edit::TextEditState::load(ui.ctx(), field_id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(ui.ctx(), field_id); + response.request_focus(); + return None; + } + + if response.has_focus() && !escape { + ui.data_mut(|data| data.insert_temp(typing_id, (handle, text))); + return None; + } + + ui.data_mut(|data| data.remove::<(LevelsHandle, String)>(typing_id)); + ui.memory_mut(|memory| memory.surrender_focus(field_id)); + // A box left open while the editor was hidden is dropped, not applied later + if !response.lost_focus() { + return None; + } + + let typed = text.trim().parse::().ok().filter(|value| value.is_finite()); + let (false, Some(typed)) = (escape, typed) else { return None }; + + let mut next = *levels; + handle.set_value(&mut next, typed); + if next == *levels { + return None; + } + + *levels = next; + Some(false) +} diff --git a/crates/ui-egui/src/levels_handle.rs b/crates/ui-egui/src/levels_handle.rs new file mode 100644 index 00000000..0ac160f6 --- /dev/null +++ b/crates/ui-egui/src/levels_handle.rs @@ -0,0 +1,91 @@ +//! The five handles of the levels editor and how each one reads and moves a [`Levels`] + +use texturecraft_engine::core::Levels; + +use crate::i18n::tr; + +/// Narrowest gap the handles and typed values leave between the low and high handle of a pair +const MIN_HANDLE_GAP: f32 = 0.01; + +/// Gamma range of the handle and typed values: the engine's own, so the handle nearly reaches either input handle +const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + +/// One draggable value of a levels effect +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LevelsHandle { + InputLow, + Gamma, + InputHigh, + OutputLow, + OutputHigh, +} + +impl LevelsHandle { + /// The handles above the histogram, left to right at the default levels + pub const INPUT: [LevelsHandle; 3] = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh]; + + pub fn label(self) -> &'static str { + match self { + LevelsHandle::InputLow => tr("Input low"), + LevelsHandle::Gamma => tr("Gamma"), + LevelsHandle::InputHigh => tr("Input high"), + LevelsHandle::OutputLow => tr("Output low"), + LevelsHandle::OutputHigh => tr("Output high"), + } + } + + pub fn value(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::InputLow => levels.in_low, + LevelsHandle::Gamma => levels.gamma, + LevelsHandle::InputHigh => levels.in_high, + LevelsHandle::OutputLow => levels.out_low, + LevelsHandle::OutputHigh => levels.out_high, + } + } + + /// Where the handle sits along its track (0 left, 1 right); gamma 1 is halfway between the input handles + pub fn position(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::Gamma => levels.in_low + input_span(levels) * 0.5f32.powf(levels.gamma), + _ => self.value(levels), + } + .clamp(0.0, 1.0) + } + + /// Moves the handle to `position` along its track (see [`Self::position`]) + pub fn set_position(self, levels: &mut Levels, position: f32) { + let value = match self { + LevelsHandle::Gamma => { + let span = input_span(levels).max(f32::EPSILON); + let fraction = ((position - levels.in_low) / span).clamp(f32::EPSILON, 1.0 - f32::EPSILON); + fraction.ln() / 0.5f32.ln() + } + _ => position, + }; + self.set_value(levels, value); + } + + /// Sets the handle's value without crossing a neighbour: input low < gamma < input high, outputs keep their sides + pub fn set_value(self, levels: &mut Levels, value: f32) { + if !value.is_finite() { + return; + } + + // The gap keeps each output handle on its side; min/max, not clamp, as a project's bounds can cross + let inverted = levels.out_low > levels.out_high; + match self { + LevelsHandle::InputLow => levels.in_low = value.min(levels.in_high - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::Gamma => levels.gamma = value.clamp(*GAMMA_RANGE.start(), *GAMMA_RANGE.end()), + LevelsHandle::InputHigh => levels.in_high = value.max(levels.in_low + MIN_HANDLE_GAP).min(1.0), + LevelsHandle::OutputLow if inverted => levels.out_low = value.max(levels.out_high + MIN_HANDLE_GAP).min(1.0), + LevelsHandle::OutputLow => levels.out_low = value.min(levels.out_high - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::OutputHigh if inverted => levels.out_high = value.min(levels.out_low - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::OutputHigh => levels.out_high = value.max(levels.out_low + MIN_HANDLE_GAP).min(1.0), + } + } +} + +fn input_span(levels: &Levels) -> f32 { + (levels.in_high - levels.in_low).max(0.0) +} diff --git a/crates/ui-egui/src/levels_properties.rs b/crates/ui-egui/src/levels_properties.rs new file mode 100644 index 00000000..fee6af57 --- /dev/null +++ b/crates/ui-egui/src/levels_properties.rs @@ -0,0 +1,130 @@ +//! Properties of a levels effect: the levels editor, then the channel picker (content), Reset, Auto and Invert + +use std::sync::Arc; + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::core::{Channel, ChannelKind, Layer, LayerId, Levels}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::levels_editor::levels_editor; +use crate::theme::caption; + +/// Buckets of the histogram, over 0..1 +const HISTOGRAM_BUCKETS: usize = 64; + +/// Share of the counted texels a bucket needs to hold for Auto to keep it in the input range +const AUTO_MIN_SHARE: f64 = 0.001; + +/// The properties of levels effect `effect_id` of `layer`; every edit goes through `effect.set` +pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, levels: &Levels) { + ui.label(caption(tr("Levels"))); + let is_content = layer.content_effects.iter().any(|effect| effect.id == effect_id); + let channels: Vec = + if is_content { layer.channels.keys().copied().filter(|channel| channel.kind() != ChannelKind::NormalMap).collect() } else { Vec::new() }; + let picked = egui::Id::unique(("levels_channel", effect_id.0)); + let channel = ui + .data(|data| data.get_temp(picked)) + .filter(|channel| channels.contains(channel)) + .or(channels.first().copied()) + .or(layer.channels.keys().next().copied()) + .unwrap_or(Channel::BaseColor); + let counts = histogram_counts(app, ui, effect_id, channel); + + let mut edited = *levels; + let mut edit = levels_editor(ui, effect_id, counts.as_ref().map(|counts| counts.as_slice()), &mut edited); + ui.horizontal(|ui| { + if !channels.is_empty() { + egui::ComboBox::from_id_salt(picked) + .selected_text(tr(channel.label())) + .show_ui(ui, |ui| { + for option in channels { + if ui.selectable_label(option == channel, tr(option.label())).clicked() { + ui.data_mut(|data| data.insert_temp(picked, option)); + } + } + }) + .response + .on_hover_text(tr("Channel")); + } + + // Right to left: the last button comes first + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Invert")).clicked() { + std::mem::swap(&mut edited.out_low, &mut edited.out_high); + edit = Some(false); + } + + let auto_range = counts.as_ref().and_then(|counts| auto_input_range(counts)); + let auto = ui.add_enabled(auto_range.is_some(), egui::Button::new(tr("Auto"))).on_hover_text(tr("Fit the input range to the histogram")); + if auto.clicked() + && let Some((low, high)) = auto_range + { + (edited.in_low, edited.in_high) = (low, high); + edit = Some(false); + } + + if ui.add_enabled(edited != Levels::default(), egui::Button::new(tr("Reset"))).clicked() { + edited = Levels::default(); + edit = Some(false); + } + }); + }); + + // Auto or Invert with nothing to change would add an empty undo step + if let Some(merge) = edit + && edited != *levels + { + let Levels { in_low, in_high, gamma, out_low, out_high } = edited; + app.run( + "effect.set", + json!({"effect": effect_id.0, "inLow": in_low, "inHigh": in_high, "gamma": gamma, "outLow": out_low, "outHigh": out_high, "merge": merge}), + ); + } +} + +/// The histogram levels effect `effect_id` remaps, recomputed after a change once no pointer button is held +fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option>> { + let key = egui::Id::unique(("levels_histogram", effect_id.0, channel)); + let revision = app.session.revision; + match ui.data(|data| data.get_temp::<(u64, Arc>)>(key)) { + Some((cached, counts)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(counts), + _ => app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS).map(|counts| { + let counts = Arc::new(counts); + ui.data_mut(|data| data.insert_temp(key, (revision, counts.clone()))); + counts + }), + } +} + +/// The input range Auto picks: the first to the last bucket holding more than [`AUTO_MIN_SHARE`] of the texels +fn auto_input_range(counts: &[u32]) -> Option<(f32, f32)> { + let total: u64 = counts.iter().map(|&count| u64::from(count)).sum(); + let holds_enough = |count: &u32| f64::from(*count) > total as f64 * AUTO_MIN_SHARE; + let first = counts.iter().position(holds_enough)?; + let last = counts.iter().rposition(holds_enough)?; + let buckets = counts.len() as f32; + Some((first as f32 / buckets, (last + 1) as f32 / buckets)) +} + +#[cfg(test)] +mod tests { + use super::{HISTOGRAM_BUCKETS, auto_input_range}; + + #[test] + fn auto_skips_buckets_under_the_share() { + let mut counts = vec![0u32; HISTOGRAM_BUCKETS]; + counts[3] = 1; + counts[10] = 5_000; + counts[40] = 5_000; + counts[60] = 1; + assert_eq!(auto_input_range(&counts), Some((10.0 / HISTOGRAM_BUCKETS as f32, 41.0 / HISTOGRAM_BUCKETS as f32))); + } + + #[test] + fn auto_has_nothing_to_fit_in_an_empty_histogram() { + assert_eq!(auto_input_range(&[0; HISTOGRAM_BUCKETS]), None); + assert_eq!(auto_input_range(&[]), None); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..7367894e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,9 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod levels_editor; +mod levels_handle; +mod levels_properties; mod mask_preview_image; mod mask_shape; pub mod menus; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..64a6f4e2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -142,31 +142,6 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive, y: f32, t: p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring)); } -/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well -/// the width of the panel, the part of 0..1 outside `range` dimmed. -pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover()); - let p = ui.painter_at(rect); - p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let inner = rect.shrink(3.0); - let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32; - let w = inner.width() / counts.len().max(1) as f32; - for (i, c) in counts.iter().enumerate() { - let h = inner.height() * *c as f32 / max; - let x = inner.left() + i as f32 * w; - p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim); - } - let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0); - let shade = tk.field.gamma_multiply(0.7); - p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade); - p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade); - for t in [range.0, range.1] { - p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent)); - } - resp -} - /// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel. pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color: Color32, max_width: f32) -> std::sync::Arc { let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color); diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/effect_sliders.rs index c5374fb0..a26ac303 100644 --- a/crates/ui-egui/tests/effect_sliders.rs +++ b/crates/ui-egui/tests/effect_sliders.rs @@ -78,10 +78,10 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } -/// The combo box in the row of the "Channel" label. +/// The combo box in the row of the levels editor's Reset button. fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Channel").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() + let row = h.get_by_label("Reset").rect().center().y; + h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. diff --git a/crates/ui-egui/tests/levels_editor.rs b/crates/ui-egui/tests/levels_editor.rs new file mode 100644 index 00000000..c09246c4 --- /dev/null +++ b/crates/ui-egui/tests/levels_editor.rs @@ -0,0 +1,247 @@ +//! The levels editor in Properties: handles, typed values and Reset, Auto and Invert edit the effect + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels}; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Histogram buckets and Auto's share, as in levels_properties.rs +const HISTOGRAM_BUCKETS: usize = 64; +const AUTO_MIN_SHARE: f64 = 0.001; + +/// A clouds mask under a levels effect added by `command` with `params`, selected, and its id +fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for (id, params) in [ + ("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})), + ("mask.add.black", Value::Null), + ("effect.add.fill", json!({"target": "mask", "procedural": "clouds"})), + (command, params), + ] { + execute(&mut session, id, ¶ms).unwrap(); + } + let effect = levels_effect(&session); + open(session, effect) +} + +fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraftApp>, LayerId) { + let (layer, _) = session.doc.project.effect(effect).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The newest levels effect in the project +fn levels_effect(session: &Session) -> LayerId { + let layers = session.doc.project.layers.values(); + let effects = layers.flat_map(|layer| layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()))); + effects.filter(|effect| matches!(effect.kind, EffectKind::Levels(_))).map(|effect| effect.id).max_by_key(|id| id.0).unwrap() +} + +fn levels(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Levels { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Levels(levels) => *levels, + other => panic!("a levels effect, found {other:?}"), + } +} + +fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn handle(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::Slider, label).rect().center() +} + +/// The button labelled `label` (an effect in the stack can share its name) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::Button, label) +} + +/// Presses at `from`, moves in a few steps to `to` (one frame each, like a hand) and releases +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { + harness.drag_at(from); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.drop_at(to); + harness.run_steps(3); +} + +fn set_levels(harness: &mut Harness<'_, TextureCraftApp>, effect: LayerId, mut params: Value) { + params["effect"] = json!(effect.0); + execute(&mut harness.state_mut().session, "effect.set", ¶ms).unwrap(); + harness.run_steps(3); +} + +#[test] +fn dragging_each_handle_edits_its_value_in_one_undo_step() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + for (label, offset_x) in [("Input low", 80.0), ("Input high", -80.0), ("Gamma", 30.0), ("Output low", 60.0), ("Output high", -60.0)] { + let before = levels(&harness, effect); + let steps = undo_steps(&harness); + let at = handle(&harness, label); + drag(&mut harness, at, at + egui::vec2(offset_x, 0.0)); + let after = levels(&harness, effect); + let changed: Vec<&str> = [ + ("Input low", before.in_low != after.in_low), + ("Input high", before.in_high != after.in_high), + ("Gamma", before.gamma != after.gamma), + ("Output low", before.out_low != after.out_low), + ("Output high", before.out_high != after.out_high), + ] + .into_iter() + .filter_map(|(name, changed)| changed.then_some(name)) + .collect(); + assert_eq!(changed, [label], "dragging {label} changes only it: {before:?} -> {after:?}"); + assert_eq!(undo_steps(&harness), steps + 1, "dragging {label} is one undo step"); + } + + let dragged = levels(&harness, effect); + assert!(dragged.in_low > 0.0 && dragged.in_high < 1.0 && dragged.out_low > 0.0 && dragged.out_high < 1.0, "{dragged:?}"); + assert!(dragged.gamma < 1.0, "gamma right of the middle darkens: {}", dragged.gamma); +} + +#[test] +fn handles_stop_at_their_neighbours() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.6, "outLow": 0.3, "outHigh": 0.7})); + let far_right = egui::vec2(1000.0, 0.0); + for label in ["Input low", "Gamma", "Output low"] { + let at = handle(&harness, label); + drag(&mut harness, at, at + far_right); + } + let edited = levels(&harness, effect); + assert!((edited.in_low - 0.59).abs() < 1e-4, "input low stops below input high: {edited:?}"); + assert_eq!(edited.gamma, 0.01, "gamma stops at its lowest value"); + let gap = handle(&harness, "Input high").x - handle(&harness, "Gamma").x; + assert!((0.0..1.0).contains(&gap), "the gamma handle reaches input high over this narrow range: {gap} pt apart"); + assert!((edited.out_low - 0.69).abs() < 1e-4, "output low stops below output high: {edited:?}"); +} + +#[test] +fn output_handles_keep_their_side_once_inverted() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "outLow": 0.2, "outHigh": 0.8})); + button(&harness, "Invert").click(); + harness.run_steps(3); + let inverted = levels(&harness, effect); + assert_eq!((inverted.out_low, inverted.out_high), (0.8, 0.2)); + + let at = handle(&harness, "Output high"); + drag(&mut harness, at, at + egui::vec2(1000.0, 0.0)); + let edited = levels(&harness, effect); + assert!((edited.out_high - 0.79).abs() < 1e-4, "output high stops below output low: {edited:?}"); +} + +#[test] +fn reset_and_invert_are_one_undo_step_each() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert!(button(&harness, "Reset").accesskit_node().is_disabled(), "nothing to reset at the defaults"); + set_levels(&mut harness, effect, json!({"inLow": 0.1, "inHigh": 0.9, "gamma": 2.0, "outLow": 0.2, "outHigh": 0.7})); + + let steps = undo_steps(&harness); + button(&harness, "Invert").click(); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 }); + assert_eq!(undo_steps(&harness), steps + 1); + + button(&harness, "Reset").click(); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps + 2); +} + +#[test] +fn auto_fits_the_input_range_to_the_histogram() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5})); + let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap(); + let total: u32 = counts.iter().sum(); + let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; + let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; + let high = (counts.iter().rposition(holds).unwrap() + 1) as f32 / HISTOGRAM_BUCKETS as f32; + assert!(low > 0.0 || high < 1.0, "the clouds don't fill the whole range: {low}..{high}"); + + button(&harness, "Auto").click(); + harness.run_steps(3); + let edited = levels(&harness, effect); + assert_eq!((edited.in_low, edited.in_high), (low, high)); + assert_eq!(edited.gamma, 1.5, "Auto leaves gamma"); + + let steps = undo_steps(&harness); + button(&harness, "Auto").click(); + harness.run_steps(3); + assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step"); +} + +/// Double-clicks `label`'s handle, then types `text` into the box that opens with the value selected +fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + let at = handle(harness, label); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false, true, false] { + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + harness.run_steps(2); + for character in text.chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } +} + +#[test] +fn a_value_typed_after_double_clicking_a_handle_applies() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + type_value(&mut harness, "Gamma", "2.5"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(levels(&harness, effect).gamma, 2.5); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn the_typing_box_moves_nothing_in_the_panel() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect()); + let before = buttons(&harness); + type_value(&mut harness, "Output low", ""); + assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the box is open"); + assert_eq!(buttons(&harness), before); +} + +#[test] +fn escape_drops_a_typed_value() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + type_value(&mut harness, "Output low", "0.4"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps); + assert!(harness.query_by_value("0.4").is_none(), "the box closed"); +} + +#[test] +fn a_typed_value_keeps_input_low_below_input_high() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inHigh": 0.5})); + type_value(&mut harness, "Input low", "0.9"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert!((levels(&harness, effect).in_low - 0.49).abs() < 1e-4, "{:?}", levels(&harness, effect)); +} + +#[test] +fn the_levels_filter_shows_the_same_editor() { + let (harness, _) = levels_harness("effect.add.filter", json!({"target": "mask", "filter": "levels"})); + for label in ["Input low", "Gamma", "Input high", "Output low", "Output high"] { + harness.get_by_role_and_label(Role::Slider, label); + } + for button in ["Reset", "Auto", "Invert"] { + harness.get_by_role_and_label(Role::Button, button); + } +} From bac53688c139d5779291c77d7ab7034613d729b2 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 12:13:03 +0000 Subject: [PATCH 071/275] Bake mode: draw the high poly, the cage and where the bake's rays miss The 3D view in bake mode gets a Baking Visualization panel (high poly, cage, UV seams, low poly, selected texture set only). The cage is built from the bake's own ray starts (a RayFrame now shared by the bake and the view), so it grows and shrinks with the distance sliders exactly as the rays do, and high-poly vertices the transfer rays cannot reach are drawn red. Refs #330 --- crates/bake/src/cage.rs | 15 + crates/bake/src/cage/cage_shell.rs | 65 +++ crates/bake/src/cage/high_poly_reach.rs | 103 +++++ crates/bake/src/cage/ray_frame.rs | 63 +++ crates/bake/src/cage/ray_start.rs | 20 + crates/bake/src/cage/vertex_reach.rs | 28 ++ crates/bake/src/lib.rs | 4 + crates/bake/src/map.rs | 3 + crates/bake/src/map/bake_context.rs | 86 +--- crates/bake/src/map/sampling.rs | 47 +- crates/bake/src/map/source.rs | 13 + crates/bake/src/map/transfer_keys.rs | 8 + crates/bake/src/mesh_extent.rs | 35 ++ crates/bake/src/test/cage_shell.rs | 103 +++++ crates/bake/src/test/high_poly_reach.rs | 198 ++++++++ crates/bake/src/tests.rs | 6 + crates/engine/src/bake/bake_cage_inputs.rs | 45 ++ crates/engine/src/bake/bake_meshes.rs | 5 + crates/engine/src/bake/mesh_map_command.rs | 90 +++- crates/engine/src/bake/mod.rs | 2 + crates/geom/src/mesh.rs | 54 +++ crates/render/src/bake_visualization.rs | 12 + crates/render/src/cage_gpu.rs | 9 + crates/render/src/high_poly_gpu.rs | 11 + crates/render/src/lib.rs | 5 + crates/render/src/renderer.rs | 423 ++++++++++++++---- crates/render/src/shaders/bake_view.wgsl | 88 ++++ crates/render/src/uv_seam_gpu.rs | 8 + crates/render/tests/headless.rs | 75 +++- .../src/bake_mode/bake_visualization_panel.rs | 61 +++ .../bake_mode/bake_visualization_toggles.rs | 34 ++ crates/ui-egui/src/bake_mode/mod.rs | 4 + crates/ui-egui/src/bake_scene.rs | 11 + .../ui-egui/src/bake_scene/bake_scene_link.rs | 213 +++++++++ crates/ui-egui/src/bake_scene/cage_link.rs | 16 + .../ui-egui/src/bake_scene/cage_shell_key.rs | 47 ++ crates/ui-egui/src/bake_scene/cage_upload.rs | 10 + crates/ui-egui/src/bake_scene/reach_link.rs | 100 +++++ .../ui-egui/src/bake_scene/shared_handle.rs | 32 ++ crates/ui-egui/src/gpu.rs | 206 ++++++--- crates/ui-egui/src/i18n/ar.rs | 5 + crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 5 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/viewport.rs | 56 ++- 52 files changed, 2179 insertions(+), 285 deletions(-) create mode 100644 crates/bake/src/cage.rs create mode 100644 crates/bake/src/cage/cage_shell.rs create mode 100644 crates/bake/src/cage/high_poly_reach.rs create mode 100644 crates/bake/src/cage/ray_frame.rs create mode 100644 crates/bake/src/cage/ray_start.rs create mode 100644 crates/bake/src/cage/vertex_reach.rs create mode 100644 crates/bake/src/map/transfer_keys.rs create mode 100644 crates/bake/src/mesh_extent.rs create mode 100644 crates/bake/src/test/cage_shell.rs create mode 100644 crates/bake/src/test/high_poly_reach.rs create mode 100644 crates/engine/src/bake/bake_cage_inputs.rs create mode 100644 crates/render/src/bake_visualization.rs create mode 100644 crates/render/src/cage_gpu.rs create mode 100644 crates/render/src/high_poly_gpu.rs create mode 100644 crates/render/src/shaders/bake_view.wgsl create mode 100644 crates/render/src/uv_seam_gpu.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_panel.rs create mode 100644 crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs create mode 100644 crates/ui-egui/src/bake_scene.rs create mode 100644 crates/ui-egui/src/bake_scene/bake_scene_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_link.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_shell_key.rs create mode 100644 crates/ui-egui/src/bake_scene/cage_upload.rs create mode 100644 crates/ui-egui/src/bake_scene/reach_link.rs create mode 100644 crates/ui-egui/src/bake_scene/shared_handle.rs diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs new file mode 100644 index 00000000..d2c7d7f3 --- /dev/null +++ b/crates/bake/src/cage.rs @@ -0,0 +1,15 @@ +//! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws + +mod cage_shell; +mod high_poly_reach; +mod ray_frame; +mod ray_start; +mod vertex_reach; + +#[cfg(test)] +pub(crate) use cage_shell::CORNERS; +pub use cage_shell::CageShell; +pub use high_poly_reach::HighPolyReach; +pub(crate) use ray_frame::RayFrame; +pub use ray_start::RayStart; +pub use vertex_reach::VertexReach; diff --git a/crates/bake/src/cage/cage_shell.rs b/crates/bake/src/cage/cage_shell.rs new file mode 100644 index 00000000..e1664219 --- /dev/null +++ b/crates/bake/src/cage/cage_shell.rs @@ -0,0 +1,65 @@ +use super::{RayFrame, RayStart}; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use std::collections::{HashMap, HashSet}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::surface_at; + +/// Barycentric coordinates of a triangle's three corners +pub(crate) const CORNERS: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]; + +/// The cage of one texture set as the bake sees it: where its transfer rays start at each corner of the set's triangles +#[derive(Clone, Debug, Default)] +pub struct CageShell { + /// Low-poly position of each triangle corner, three per triangle + pub positions: Vec, + pub starts: Vec, + /// Corner pairs along the low poly's polygon edges, for the wireframe + pub edges: Vec<[u32; 2]>, + /// World units per unit of the max frontal distance setting + pub cage_units: f32, +} + +impl CageShell { + /// The cage of `request`'s texture set, from the same ray starts the bake uses + pub fn new(request: &BakeRequest) -> Result { + let ray_frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let (frame, mesh) = (&ray_frame, request.mesh); + let triangles: Vec = mesh.triangles_of(request.material).collect(); + let (positions, starts): (Vec, Vec) = triangles + .par_iter() + .flat_map_iter(|&triangle| { + CORNERS.into_iter().map(move |barycentric| match surface_at(mesh, triangle as u32, barycentric[0], barycentric[1]) { + Some(surface) => (surface.pos, frame.start(&surface, barycentric)), + None => (Vec3::ZERO, RayStart::Distance { up: Vec3::ZERO, scale: 0.0 }), + }) + }) + .unzip(); + + let wire_edges: HashSet<(u32, u32)> = mesh.wire_edges().into_iter().nth(request.material).unwrap_or_default().into_iter().collect(); + let mut edge_corners = HashMap::new(); + for (triangle_index, &triangle) in triangles.iter().enumerate() { + let Some(vertices) = mesh.tri(triangle) else { continue }; + + for corner in 0..3 { + let next = (corner + 1) % 3; + let (from, to) = (vertices[corner] as u32, vertices[next] as u32); + let key = (from.min(to), from.max(to)); + if wire_edges.contains(&key) { + let first_corner = (triangle_index * 3) as u32; + edge_corners.entry(key).or_insert([first_corner + corner as u32, first_corner + next as u32]); + } + } + } + let mut edges: Vec<[u32; 2]> = edge_corners.into_values().collect(); + edges.sort_unstable(); + + Ok(CageShell { positions, starts, edges, cage_units: ray_frame.cage_units }) + } + + /// Each corner's cage position at `max_frontal`, the setting before relative-to-bounding-box scaling + pub fn corners(&self, max_frontal: f32) -> Vec { + let frontal = max_frontal * self.cage_units; + self.positions.par_iter().zip(&self.starts).map(|(position, start)| start.origin(*position, frontal)).collect() + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs new file mode 100644 index 00000000..f957ce49 --- /dev/null +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -0,0 +1,103 @@ +use super::{RayFrame, VertexReach}; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeError, BakeRequest, MeshExtent}; +use rayon::prelude::*; +use texturecraft_core::MeshMatchMode; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, surface_at}; + +/// Where each high-poly vertex sits relative to the transfer rays of one texture set, to show which parts its bake misses +#[derive(Clone, Debug, Default)] +pub struct HighPolyReach { + /// Per high-poly vertex; `None` where another texture set's low poly is nearer or the request has no high poly + pub vertices: Vec>, + /// World units per unit of the cage distance settings + pub cage_units: f32, + pub ignore_backface: bool, +} + +impl HighPolyReach { + /// The reach of `request`'s transfer rays at the high-poly vertices whose nearest low-poly point is on this set, from the same ray starts the bake uses there + pub fn new(request: &BakeRequest) -> Result { + let Some(high) = request.high else { return Ok(HighPolyReach::default()) }; + + let frame = RayFrame::new(request, MeshExtent::of(request.mesh)?)?; + let mut in_set = vec![false; request.mesh.triangle_count()]; + for triangle in request.mesh.triangles_of(request.material) { + if let Some(flag) = in_set.get_mut(triangle) { + *flag = true; + } + } + + let winding_normals = winding_normals(high.mesh); + let (low_keys, high_vertex_keys) = match request.settings.high_poly.match_mode { + MeshMatchMode::Always => (Vec::new(), Vec::new()), + MeshMatchMode::ByMeshName => { + let (low_keys, high_keys) = transfer_keys(request); + (low_keys, vertex_keys(high.mesh, &high_keys)) + } + }; + let key = |keys: &[u32], index: usize| keys.get(index).copied().unwrap_or(ANY); + let frame = &frame; + let vertices = high + .mesh + .positions + .par_iter() + .zip(&winding_normals) + .enumerate() + .map(|(vertex, (&high_position, &high_facing))| { + let nearest = request.bvh.nearest(high_position, f32::INFINITY, &|_| true)?; + if !in_set.get(nearest.tri as usize).copied().unwrap_or(false) { + return None; + } + + let surface = surface_at(request.mesh, nearest.tri, nearest.u, nearest.v)?; + let ray_key = key(&low_keys, nearest.tri as usize); + Some(VertexReach { + low_position: surface.pos, + start: frame.start(&surface, [nearest.u, nearest.v]), + high_position, + high_facing, + name_matches: ray_key == ANY || key(&high_vertex_keys, vertex) == ray_key, + }) + }) + .collect(); + + Ok(HighPolyReach { vertices, cage_units: frame.cage_units, ignore_backface: request.settings.high_poly.ignore_backface }) + } + + /// Whether the transfer rays miss high-poly vertex `vertex` at the `max_frontal` and `max_rear` settings; `None` when the vertex isn't this set's + pub fn missed(&self, vertex: usize, max_frontal: f32, max_rear: f32) -> Option { + let reach = self.vertices.get(vertex).copied().flatten()?; + Some(reach.missed(max_frontal * self.cage_units, max_rear * self.cage_units, self.ignore_backface)) + } +} + +/// Each vertex's mesh-name key, from the first triangle that uses it +fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { + let mut keys = vec![ANY; mesh.positions.len()]; + for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) { + for &corner in corners { + if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { + *key = triangle_key; + } + } + } + keys +} + +/// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front +fn winding_normals(mesh: &Mesh) -> Vec { + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact(3) { + let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); + let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); + for &corner in corners { + if let Some(normal) = normals.get_mut(corner as usize) { + *normal += winding_normal; + } + } + } + normals +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs new file mode 100644 index 00000000..e8692cf2 --- /dev/null +++ b/crates/bake/src/cage/ray_frame.rs @@ -0,0 +1,63 @@ +use super::RayStart; +use crate::MeshExtent; +use crate::map::{interpolate, welded}; +use crate::skew::PreparedSkew; +use crate::{BakeError, BakePaintMap, BakeRequest}; +use texturecraft_core::CageType; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, Surface}; + +/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +pub(crate) struct RayFrame<'a> { + mesh: &'a Mesh, + ray_normals: Vec, + cage: Option<&'a Mesh>, + skew: Option>, + cage_paint: Option<&'a BakePaintMap>, + /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead + ray_epsilon: f32, + /// World units per unit of the cage distance settings + pub(crate) cage_units: f32, +} + +impl<'a> RayFrame<'a> { + pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { + let settings = request.settings; + let ray_normals = match settings.cage.average_normals && request.high.is_some() { + true => { + let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); + welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + } + false => Vec::new(), + }; + + Ok(RayFrame { + mesh: request.mesh, + ray_normals, + cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, + cage_paint: request.cage_paint, + ray_epsilon: extent.ray_epsilon(), + cage_units: if settings.cage.relative_to_bounding_box { extent.scale } else { 1.0 }, + }) + } + + /// Where the transfer ray of the low-poly point `surface` at `barycentric` starts + pub(crate) fn start(&self, surface: &Surface, barycentric: [f32; 2]) -> RayStart { + let cage_offset = self + .cage + .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) + .map(|cage_position| surface.pos - cage_position) + .filter(|offset| offset.length() > self.ray_epsilon); + if let Some(offset) = cage_offset { + return RayStart::CageMesh(offset); + } + + let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let up = match &self.skew { + Some(skew) => skew.correct(self.mesh, surface, averaged_normal), + None => averaged_normal, + }; + RayStart::Distance { up, scale: self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)) } + } +} diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs new file mode 100644 index 00000000..c0c3923a --- /dev/null +++ b/crates/bake/src/cage/ray_start.rs @@ -0,0 +1,20 @@ +use texturecraft_geom::glam::Vec3; + +/// Where the bake's transfer ray for one low-poly point starts +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum RayStart { + /// On the cage mesh: the offset from the cage to the low-poly point + CageMesh(Vec3), + /// Out along `up` by the frontal distance times `scale` (the painted cage amount) + Distance { up: Vec3, scale: f32 }, +} + +impl RayStart { + /// The ray origin for the low-poly point `position` at `frontal` world units of max frontal distance + pub fn origin(&self, position: Vec3, frontal: f32) -> Vec3 { + match *self { + RayStart::CageMesh(offset) => position - offset, + RayStart::Distance { up, scale } => position + up * frontal * scale, + } + } +} diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs new file mode 100644 index 00000000..34adea92 --- /dev/null +++ b/crates/bake/src/cage/vertex_reach.rs @@ -0,0 +1,28 @@ +use super::RayStart; +use texturecraft_geom::glam::Vec3; + +/// One high-poly vertex seen from the transfer ray through its nearest low-poly point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VertexReach { + pub low_position: Vec3, + pub start: RayStart, + pub high_position: Vec3, + /// The side the high poly's triangles face at the vertex, by their winding (not normalized) + pub high_facing: Vec3, + /// Whether the bake lets this low-poly point's ray hit the vertex's part (always, unless matching by mesh name) + pub name_matches: bool, +} + +impl VertexReach { + /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray + pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { + let origin = self.start.origin(self.low_position, frontal); + let (direction, front) = match self.start { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), + RayStart::Distance { up, scale } => (-up, frontal * scale), + }; + let along_ray = (self.high_position - origin).dot(direction); + + !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) + } +} diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index a8b087bc..eb8a61de 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -6,13 +6,17 @@ mod bake_error; mod bake_output; mod bake_request; +mod cage; mod high_poly; +mod mesh_extent; mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; pub use bake_request::BakeRequest; +pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; +pub(crate) use mesh_extent::MeshExtent; pub use progress::Progress; mod map; diff --git a/crates/bake/src/map.rs b/crates/bake/src/map.rs index 384d9d02..c9c30fd6 100644 --- a/crates/bake/src/map.rs +++ b/crates/bake/src/map.rs @@ -15,10 +15,13 @@ mod source; mod texel_grid; mod traced; mod transfer; +mod transfer_keys; pub(crate) use bake_context::BakeContext; pub(crate) use normal_curvature::curvature_from_normal; pub(crate) use sample::Sample; +pub(crate) use sampling::{interpolate, welded}; pub(crate) use texel_grid::TexelGrid; pub(crate) use traced::Traced; pub(crate) use transfer::Transfer; +pub(crate) use transfer_keys::transfer_keys; diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index 21fed094..f3e35df6 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,28 +1,22 @@ use super::curvature::Curvature; -use super::sampling::{interpolate, pack, splitmix64, tangent_normal, welded}; +use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::skew::PreparedSkew; +use crate::cage::{RayFrame, RayStart}; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; -use crate::{BakeError, BakeRequest}; +use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; -use std::collections::HashMap; use texturecraft_core::{ - AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CageType, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, + AmbientOcclusionAttenuation, BackfaceMode, BakeSettings, BakedMap, CurvatureMethod, MeshMatchMode, RayDistribution, RaySettings, SelfOcclusion, }; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::{Hit, Mesh, Surface, surface_at}; +use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - cage: Option<&'a Mesh>, - skew: Option>, - cage_paint: Option<&'a crate::BakePaintMap>, - ray_normals: Vec, + ray_frame: RayFrame<'a>, settings: &'a BakeSettings, - eps: f32, frontal: f32, rear: f32, position: PositionProjection, @@ -36,36 +30,10 @@ pub(crate) struct BakeContext<'a> { impl<'a> BakeContext<'a> { pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { let settings = request.settings; - let (bounds_min, bounds_max) = request.mesh.bounds(); - let mesh_diagonal = (bounds_max - bounds_min).length().max(1e-6); - if !mesh_diagonal.is_finite() { - return Err(BakeError::Invalid("mesh bounds are too large".into())); - } - - let mesh_scale = (bounds_max - bounds_min).max_element().max(1e-6); - let mut name_keys = HashMap::new(); - let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.high_poly.low_suffix, &settings.high_poly, &mut name_keys); - let high = request.high.map(|high_mesh| { - Source::new( - high_mesh.mesh, - high_mesh.bvh, - high_mesh.base_color, - high_mesh.file_ids, - &settings.high_poly.high_suffix, - &settings.high_poly, - &mut name_keys, - ) - }); - let ray_normals = match settings.cage.average_normals && high.is_some() { - true => { - let (welded_indices, _, normals) = welded(request.mesh, mesh_diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() - } - false => Vec::new(), - }; - - let skew = request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, mesh_scale, settings.skew)).transpose()?; - let ray_epsilon = 1e-6 * mesh_diagonal; + let extent = MeshExtent::of(request.mesh)?; + let (low, high) = Source::of_request(request); + let ray_frame = RayFrame::new(request, extent)?; + let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); let units = if ray_settings.relative_to_bounding_box { mesh_scale } else { 1.0 }; @@ -91,27 +59,26 @@ impl<'a> BakeContext<'a> { pass.ignore_backface = parameters.ignore_backface; pass.same_key = parameters.self_occlusion == SelfOcclusion::SameMeshName; pass.attenuation = parameters.attenuation; - pass.ground_height = parameters.ground_plane.enabled.then_some(bounds_min.y - parameters.ground_plane.offset); + pass.ground_height = parameters.ground_plane.enabled.then_some(extent.bounds_min.y - parameters.ground_plane.offset); } + let mut bent = pass(BakedMap::BentNormal, &settings.maps.bent_normal.parameters.rays, RayKind::Occlusion); if let Some(pass) = &mut bent { pass.ignore_backface = settings.maps.bent_normal.parameters.ignore_backface; pass.same_key = settings.maps.bent_normal.parameters.self_occlusion == SelfOcclusion::SameMeshName; } + let mut thickness = pass(BakedMap::Thickness, &settings.maps.thickness.parameters.rays, RayKind::Thickness); if let Some(pass) = &mut thickness { pass.same_key = settings.maps.thickness.parameters.self_occlusion == SelfOcclusion::SameMeshName; } - let cage_units = if settings.cage.relative_to_bounding_box { mesh_scale } else { 1.0 }; + + let cage_units = ray_frame.cage_units; Ok(BakeContext { low, high, - cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, - skew, - cage_paint: request.cage_paint, - ray_normals, + ray_frame, settings, - eps: ray_epsilon, frontal: settings.cage.max_frontal * cage_units, rear: settings.cage.max_rear * cage_units, position: PositionProjection::new(request.mesh, request.material, settings.maps.position.parameters), @@ -140,22 +107,11 @@ impl<'a> BakeContext<'a> { } pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { - let averaged_normal = interpolate(self.low.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); - let cage = self - .cage - .and_then(|cage_mesh| interpolate(cage_mesh, &cage_mesh.positions, surface.tri, barycentric)) - .map(|cage_position| surface.pos - cage_position) - .filter(|offset| offset.length() > self.eps); - let cage_scale = self.cage_paint.map_or(1.0, |map| map.sample(surface.uv)); - let (origin, direction, front) = match cage { - Some(offset) => (surface.pos - offset, offset.normalize(), offset.length()), - None => { - let up = match &self.skew { - Some(skew) => skew.correct(self.low.mesh, surface, averaged_normal), - None => averaged_normal, - }; - (surface.pos + up * self.frontal * cage_scale, -up, self.frontal * cage_scale) - } + let start = self.ray_frame.start(surface, barycentric); + let origin = start.origin(surface.pos, self.frontal); + let (direction, front) = match start { + RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), + RayStart::Distance { up, scale } => (-up, self.frontal * scale), }; let key = match self.settings.high_poly.match_mode { MeshMatchMode::Always => ANY, diff --git a/crates/bake/src/map/sampling.rs b/crates/bake/src/map/sampling.rs index d19e4afa..5f2d2677 100644 --- a/crates/bake/src/map/sampling.rs +++ b/crates/bake/src/map/sampling.rs @@ -3,34 +3,43 @@ use std::ops::{Add, Mul}; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -pub(super) fn interpolate + Add>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option { - let [a, b, c] = mesh.tri(tri as usize)?; - Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2) +/// `values` (one per vertex) at `barycentric` in triangle `triangle` +pub(crate) fn interpolate + Add>(mesh: &Mesh, values: &[T], triangle: u32, barycentric: [f32; 2]) -> Option { + let [first, second, third] = mesh.tri(triangle as usize)?; + let [second_weight, third_weight] = barycentric; + + Some(*values.get(first)? * (1.0 - second_weight - third_weight) + *values.get(second)? * second_weight + *values.get(third)? * third_weight) } -pub(super) fn welded(mesh: &Mesh, diag: f32) -> (Vec, Vec, Vec) { - let q = diag * 1e-5; - let mut ids: HashMap<[i64; 3], u32> = HashMap::new(); - let (mut pos, mut nrm) = (Vec::new(), Vec::::new()); - let weld: Vec = mesh +/// Vertices closer than this fraction of the mesh diagonal count as one when welding +const WELD_TOLERANCE_PER_DIAGONAL: f32 = 1e-5; + +/// Vertices that share a position merged: each vertex's welded index, the welded positions and their averaged normals +pub(crate) fn welded(mesh: &Mesh, diagonal: f32) -> (Vec, Vec, Vec) { + let tolerance = diagonal * WELD_TOLERANCE_PER_DIAGONAL; + let mut welded_index_of_cell: HashMap<[i64; 3], u32> = HashMap::new(); + let (mut positions, mut normal_sums) = (Vec::new(), Vec::::new()); + + let welded_indices: Vec = mesh .positions .iter() .zip(&mesh.normals) - .map(|(p, n)| { - let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64); - let id = *ids.entry(key).or_insert_with(|| { - pos.push(*p); - nrm.push(Vec3::ZERO); - (pos.len() - 1) as u32 + .map(|(position, normal)| { + let cell = [position.x, position.y, position.z].map(|coordinate| (coordinate / tolerance).round() as i64); + let welded_index = *welded_index_of_cell.entry(cell).or_insert_with(|| { + positions.push(*position); + normal_sums.push(Vec3::ZERO); + (positions.len() - 1) as u32 }); - if let Some(acc) = nrm.get_mut(id as usize) { - *acc += *n; + if let Some(normal_sum) = normal_sums.get_mut(welded_index as usize) { + *normal_sum += *normal; } - id + welded_index }) .collect(); - let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect(); - (weld, pos, nrm) + + let normals = normal_sums.into_iter().map(|normal_sum| normal_sum.try_normalize().unwrap_or(Vec3::ZERO)).collect(); + (welded_indices, positions, normals) } pub(super) fn splitmix64(x: u64) -> u64 { diff --git a/crates/bake/src/map/source.rs b/crates/bake/src/map/source.rs index 0e1f9164..ad057b11 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -1,4 +1,5 @@ use super::sampling::{generated_hue, interpolate, splitmix64}; +use crate::BakeRequest; use crate::tracing::{ANY, TraceMesh}; use std::collections::HashMap; use std::sync::Arc; @@ -21,6 +22,18 @@ pub(super) struct Source<'a> { } impl<'a> Source<'a> { + /// `request`'s low and high poly, their mesh names keyed from one shared table so the bake can match a low-poly part to its high-poly part + pub(super) fn of_request(request: &BakeRequest<'a>) -> (Source<'a>, Option>) { + let settings = &request.settings.high_poly; + let mut name_keys = HashMap::new(); + let low = Source::new(request.mesh, request.bvh, request.low_base_color, &[], &settings.low_suffix, settings, &mut name_keys); + let high = request.high.map(|high_mesh| { + Source::new(high_mesh.mesh, high_mesh.bvh, high_mesh.base_color, high_mesh.file_ids, &settings.high_suffix, settings, &mut name_keys) + }); + + (low, high) + } + pub(super) fn new( mesh: &'a Mesh, bvh: &'a Bvh, diff --git a/crates/bake/src/map/transfer_keys.rs b/crates/bake/src/map/transfer_keys.rs new file mode 100644 index 00000000..69e9b12a --- /dev/null +++ b/crates/bake/src/map/transfer_keys.rs @@ -0,0 +1,8 @@ +use super::source::Source; +use crate::BakeRequest; + +/// The bake's mesh-name key of each low-poly and each high-poly triangle: with By Mesh Name a transfer ray from a low-poly triangle only hits high-poly triangles with its key +pub(crate) fn transfer_keys(request: &BakeRequest) -> (Vec, Vec) { + let (low, high) = Source::of_request(request); + (low.key, high.map(|high| high.key).unwrap_or_default()) +} diff --git a/crates/bake/src/mesh_extent.rs b/crates/bake/src/mesh_extent.rs new file mode 100644 index 00000000..3c6fa48d --- /dev/null +++ b/crates/bake/src/mesh_extent.rs @@ -0,0 +1,35 @@ +use crate::BakeError; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// Smallest size a mesh is treated as having, so a flat or empty mesh still gives finite distances +const MIN_MESH_SIZE: f32 = 1e-6; + +/// How far a ray starts past the surface it leaves, as a fraction of the mesh diagonal +const RAY_EPSILON_PER_DIAGONAL: f32 = 1e-6; + +/// The low-poly mesh's size, which scales the bake's relative distances +#[derive(Clone, Copy, Debug)] +pub(crate) struct MeshExtent { + pub(crate) bounds_min: Vec3, + pub(crate) diagonal: f32, + /// The bounding box's largest side + pub(crate) scale: f32, +} + +impl MeshExtent { + pub(crate) fn of(mesh: &Mesh) -> Result { + let (bounds_min, bounds_max) = mesh.bounds(); + let diagonal = (bounds_max - bounds_min).length().max(MIN_MESH_SIZE); + if !diagonal.is_finite() { + return Err(BakeError::Invalid("mesh bounds are too large".into())); + } + + Ok(MeshExtent { bounds_min, diagonal, scale: (bounds_max - bounds_min).max_element().max(MIN_MESH_SIZE) }) + } + + /// How far a ray starts past the surface it leaves, in world units + pub(crate) fn ray_epsilon(&self) -> f32 { + RAY_EPSILON_PER_DIAGONAL * self.diagonal + } +} diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs new file mode 100644 index 00000000..2d114b06 --- /dev/null +++ b/crates/bake/src/test/cage_shell.rs @@ -0,0 +1,103 @@ +use super::settings; +use crate::cage::CORNERS; +use crate::map::BakeContext; +use crate::{BakePaintMap, BakeRequest, CageShell, HighPoly}; +use texturecraft_core::{BakedMap, CageType}; +use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// A painted map whose values vary over the UV square +fn painted_map() -> BakePaintMap { + let mut map = BakePaintMap::constant(0.25).resized(32, 32).unwrap(); + map.paint(&[Vec2::new(0.2, 0.3), Vec2::new(0.7, 0.6)], 0.3, 1.0, 0.5, 1.0).unwrap(); + map +} + +/// Every corner of `request`'s cage equals the origin of the bake's transfer ray at that corner, bit for bit +fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { + let shell = CageShell::new(request).unwrap(); + let corners = shell.corners(request.settings.cage.max_frontal); + let context = BakeContext::new(request).unwrap(); + let triangles: Vec = request.mesh.triangles_of(request.material).collect(); + assert_eq!(corners.len(), triangles.len() * 3); + + for (corner_index, corner) in corners.iter().enumerate() { + let barycentric = CORNERS[corner_index % 3]; + let surface = surface_at(request.mesh, triangles[corner_index / 3] as u32, barycentric[0], barycentric[1]).unwrap(); + let (ray, _) = context.transfer_ray(&surface, barycentric); + assert_eq!(*corner, ray.origin, "corner {corner_index}"); + } +} + +#[test] +fn the_cage_corners_are_the_bake_ray_origins() { + let low = primitives::cube(1.0); + let high_mesh = primitives::sphere(0.8, 16, 8); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let (skew, cage_paint) = (painted_map(), painted_map()); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.max_frontal = 0.03; + bake_settings.skew.edge_protection = true; + let request = |settings| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings, + high: Some(high), + cage: None, + skew: Some(&skew), + cage_paint: Some(&cage_paint), + tiles: (1, 1), + }; + + assert_cage_matches_the_ray_origins(&request(&bake_settings)); + let face_normals = { + let mut face_normals = bake_settings.clone(); + face_normals.cage.average_normals = false; + face_normals.cage.relative_to_bounding_box = false; + face_normals + }; + assert_cage_matches_the_ray_origins(&request(&face_normals)); +} + +#[test] +fn the_cage_follows_the_frontal_distance_and_a_cage_mesh() { + let low = primitives::cube(1.0); + let low_bvh = Bvh::new(&low); + let high = HighPoly { file_ids: &[], mesh: &low, bvh: &low_bvh, base_color: &[] }; + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let distance_from_the_cube = |max_frontal: f32| shell.corners(max_frontal).iter().map(|corner| corner.abs().max_element() - 0.5).fold(0.0, f32::max); + + assert!(distance_from_the_cube(0.0).abs() < 1e-6, "at frontal 0 the cage is the low poly"); + // Averaged normals point diagonally at the corners, so a corner moves out by at least half the distance along each axis + assert!(distance_from_the_cube(0.2) > 0.1 && distance_from_the_cube(0.2) <= 0.2 + 1e-6, "the cage grows with the frontal distance"); + assert_eq!(shell.edges.len(), low.wire_edges()[0].len(), "one wireframe line per polygon edge"); + + let cage_mesh = Mesh { positions: low.positions.iter().map(|position| *position * 1.5).collect(), ..low.clone() }; + let custom_settings = { + let mut custom_settings = bake_settings.clone(); + custom_settings.cage.kind = CageType::CustomFile; + custom_settings + }; + let custom = BakeRequest { settings: &custom_settings, cage: Some(&cage_mesh), ..request }; + assert_cage_matches_the_ray_origins(&custom); + let corners = CageShell::new(&custom).unwrap().corners(0.0); + assert!(corners.iter().all(|corner| (corner.abs().max_element() - 0.75).abs() < 1e-6), "the cage mesh is drawn as it is"); + assert!(corners.iter().all(|corner| corner.is_finite() && *corner != Vec3::ZERO)); +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs new file mode 100644 index 00000000..bb8753f8 --- /dev/null +++ b/crates/bake/src/test/high_poly_reach.rs @@ -0,0 +1,198 @@ +use super::settings; +use crate::map::{BakeContext, transfer_keys}; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly, HighPolyReach, RayStart}; +use texturecraft_core::{BakedMap, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives, surface_at}; + +/// Ray distances closer than this to the end of the ray's range are left out: rounding decides them +const BOUNDARY: f32 = 1e-4; + +/// How close the ray's hit must be to the vertex to count as reaching it +const HIT_TOLERANCE: f32 = 1e-4; + +/// A bumpy plane over the flat low poly, with the triangles right of `FLIPPED_FROM_X` wound the other way +fn bumpy_high_poly() -> (Mesh, Vec) { + const FLIPPED_FROM_X: f32 = 0.2; + + let mut mesh = primitives::plane(1.0, 40); + for position in &mut mesh.positions { + position.y = 0.04 * (position.x * 9.0).sin() * (position.z * 7.0).cos() + 0.005; + } + + let mut flipped = vec![false; mesh.positions.len()]; + let mut unflipped = vec![false; mesh.positions.len()]; + for corners in mesh.indices.chunks_exact_mut(3) { + let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; + if center_x > FLIPPED_FROM_X { + corners.swap(1, 2); + } + for &corner in corners.iter() { + if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } + } + } + // Vertices on the border face both ways: neither answer is right for them + let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); + (mesh, mixed) +} + +#[test] +fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { + let low = primitives::plane(1.0, 8); + let (high_mesh, mixed) = bumpy_high_poly(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let high = HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }; + let back_facing = |triangle: u32, direction: Vec3| { + let [a, b, c] = high_mesh.tri(triangle as usize).unwrap().map(|corner| high_mesh.positions[corner]); + (b - a).cross(c - a).dot(direction) > 0.0 + }; + let mut checked = [0usize; 2]; + + for ignore_backface in [false, true] { + for (max_frontal, max_rear) in [(0.0, 0.01), (0.02, 0.0), (0.02, 0.01), (0.05, 0.05)] { + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.high_poly.ignore_backface = ignore_backface; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (max_frontal, max_rear); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(high), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); + let RayStart::Distance { scale, .. } = vertex_reach.start else { panic!("a distance-based cage") }; + let height = vertex_reach.high_position.y - vertex_reach.low_position.y; + let near_the_range_end = [max_frontal * scale, -max_rear].iter().any(|end| (height - end).abs() < BOUNDARY); + if near_the_range_end || mixed[vertex] { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let hit = high_bvh + .closest_filtered(ray.origin, ray.direction, ray.max_distance, &|triangle| !(ignore_backface && back_facing(triangle, ray.direction))); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!( + missed, !reaches_the_vertex, + "vertex {vertex}, ignore backface {ignore_backface}, frontal {max_frontal}, rear {max_rear}: height {height}" + ); + checked[usize::from(missed)] += 1; + } + } + } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); +} + +#[test] +fn a_vertex_belongs_to_the_texture_set_whose_low_poly_is_nearest() { + let mut low = primitives::plane(1.0, 4); + let mut right = primitives::plane(1.0, 4); + for position in &mut right.positions { + position.x += 2.0; + } + low.append(&right); + assert_eq!(low.materials.len(), 2, "each plane is its own texture set"); + let mut high_mesh = primitives::plane(3.0, 30); + for position in &mut high_mesh.positions { + position.x += 1.0; + position.y = 0.3; + } + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = |material| BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let (left, right) = (HighPolyReach::new(&request(0)).unwrap(), HighPolyReach::new(&request(1)).unwrap()); + + for (vertex, position) in high_mesh.positions.iter().enumerate() { + let owners = (left.vertices[vertex].is_some(), right.vertices[vertex].is_some()); + assert!(owners != (true, true), "vertex {vertex} belongs to one set at most"); + if position.x < 0.9 { + assert_eq!(owners, (true, false), "vertex {vertex} at {position} is over the left set"); + } else if position.x > 1.1 { + assert_eq!(owners, (false, true), "vertex {vertex} at {position} is over the right set"); + } + } +} + +#[test] +fn matching_by_mesh_name_misses_the_parts_with_another_name() { + const HEIGHT_INSIDE_THE_CAGE: f32 = 0.01; + + let mut low = primitives::plane(1.0, 8); + low.submeshes[0].name = "part_low".into(); + let mut high_mesh = primitives::plane(0.5, 10); + let mut other_part = primitives::plane(0.5, 10); + for (mesh, center_x) in [(&mut high_mesh, -0.25), (&mut other_part, 0.25)] { + for position in &mut mesh.positions { + position.x += center_x; + position.y = HEIGHT_INSIDE_THE_CAGE; + } + } + high_mesh.append(&other_part); + high_mesh.submeshes[0].name = "part_high".into(); + high_mesh.submeshes[1].name = "other_high".into(); + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high_mesh)); + let mut bake_settings = settings(16, &[BakedMap::Normal]); + bake_settings.cage.relative_to_bounding_box = false; + bake_settings.cage.max_frontal = 0.02; + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high_mesh, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + let context = BakeContext::new(&request).unwrap(); + let (_, high_keys) = transfer_keys(&request); + + for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { + let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles + if vertex_reach.high_position.x.abs() < BOUNDARY { + continue; + } + + let nearest = low_bvh.nearest(vertex_reach.high_position, f32::INFINITY, &|_| true).unwrap(); + let surface = surface_at(&low, nearest.tri, nearest.u, nearest.v).unwrap(); + let (ray, _) = context.transfer_ray(&surface, [nearest.u, nearest.v]); + let same_name = |triangle: u32| ray.key == ANY || high_keys.get(triangle as usize) == Some(&ray.key); + let hit = high_bvh.closest_filtered(ray.origin, ray.direction, ray.max_distance, &same_name); + let reaches_the_vertex = hit.is_some_and(|hit| (ray.origin + ray.direction * hit.t - vertex_reach.high_position).length() < HIT_TOLERANCE); + assert_eq!(missed, !reaches_the_vertex, "vertex {vertex} at {}", vertex_reach.high_position); + assert_eq!( + missed, + vertex >= high_mesh.positions.len() - other_part.positions.len(), + "only the part named like the low poly is reached: vertex {vertex}" + ); + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 26c8665c..c834da7a 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -14,6 +14,12 @@ use texturecraft_geom::primitives; use super::*; +#[path = "test/cage_shell.rs"] +mod cage_shell; + +#[path = "test/high_poly_reach.rs"] +mod high_poly_reach; + #[path = "test/setting.rs"] mod setting; diff --git a/crates/engine/src/bake/bake_cage_inputs.rs b/crates/engine/src/bake/bake_cage_inputs.rs new file mode 100644 index 00000000..ab559beb --- /dev/null +++ b/crates/engine/src/bake/bake_cage_inputs.rs @@ -0,0 +1,45 @@ +use super::MergedHigh; +use std::sync::Arc; +use texturecraft_bake::{BakeError, BakePaintMap, BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::BakeSettings; +use texturecraft_geom::{Bvh, Mesh}; + +/// What a texture set's bake reads to place its transfer rays, owned so a worker thread can use it +#[derive(Clone, Debug)] +pub struct BakeCageInputs { + pub(super) mesh: Arc, + pub(super) bvh: Arc, + pub(super) material: usize, + pub(super) settings: BakeSettings, + pub(super) high: MergedHigh, + pub(super) cage: Option>, + pub(super) skew: Option>, + pub(super) cage_paint: Option>, +} + +impl BakeCageInputs { + /// The cage the 3D view draws: the bake's ray origins at each triangle corner + pub fn cage_shell(&self) -> Result { + CageShell::new(&self.request()) + } + + /// Where each high-poly vertex sits relative to the bake's transfer rays + pub fn high_poly_reach(&self) -> Result { + HighPolyReach::new(&self.request()) + } + + fn request(&self) -> BakeRequest<'_> { + BakeRequest { + low_base_color: &[], + mesh: &self.mesh, + bvh: &self.bvh, + material: self.material, + settings: &self.settings, + high: Some(HighPoly { file_ids: &self.high.file_ids, mesh: &self.high.mesh, bvh: &self.high.bvh, base_color: &self.high.base_color }), + cage: self.cage.as_deref(), + skew: self.skew.as_deref(), + cage_paint: self.cage_paint.as_deref(), + tiles: (1, 1), + } + } +} diff --git a/crates/engine/src/bake/bake_meshes.rs b/crates/engine/src/bake/bake_meshes.rs index 260002db..da0e4a97 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -14,6 +14,11 @@ pub struct BakeMeshes { } impl BakeMeshes { + /// Every high poly appended into one mesh, as bakes see it + pub fn merged_high(&self) -> Option<&MergedHigh> { + self.merged.as_ref() + } + pub(crate) fn rebuild(&mut self) { self.merged = (!self.high.is_empty()).then(|| { let (mut mesh, mut base_color, mut file_ids) = (Mesh::default(), Vec::new(), Vec::new()); diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index e5982f18..b65d6ac8 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -8,6 +8,7 @@ use std::collections::BTreeMap; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; +use super::{BakeCageInputs, MergedHigh}; use crate::{BakeMesh, BakeTask}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; @@ -15,6 +16,7 @@ use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, }; +use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; @@ -90,8 +92,8 @@ fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } impl Session { - pub fn bake_task(&self, ts: usize) -> Result { - let set = self.doc.project.texture_set(ts)?; + pub fn bake_task(&self, texture_set: usize) -> Result { + let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } @@ -112,31 +114,22 @@ impl Session { } else { Arc::new(Vec::new()) }; - let high = if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }; - let cage = if high.is_some() && set.bake.cage.kind == texturecraft_core::CageType::CustomFile { - Some(self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?.mesh.clone()) - } else { - None - }; - let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose(); - let skew = painted(BakePaintTarget::Skew)?; - let cage_paint = painted(BakePaintTarget::Cage)?; + + let high = self.bake_high(texture_set)?; + let cage = self.bake_cage(texture_set, high.is_some())?; + let skew = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Skew)?; + let cage_paint = self.bake_paint(texture_set, high.is_some(), BakePaintTarget::Cage)?; + let grid = set.tile_grid(); let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows)); let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect(); - let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() }; + let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&texture_set).cloned().unwrap_or_default() }; + let tracer = GPU_TRACER.get().cloned(); Ok(BakeTask { low_base_color, - ts, - mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) { - Some(grid) => { - let mut mesh = (*self.source).clone(); - mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); - Arc::new(mesh) - } - None => self.mesh.clone(), - }, + ts: texture_set, + mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), @@ -151,6 +144,61 @@ impl Session { }) } + /// What texture set `texture_set`'s bake reads to place its transfer rays; `None` when the set bakes without a high poly or misses its cage file + pub fn bake_cage_inputs(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + let Some(high) = self.bake_high(texture_set)? else { return Ok(None) }; + let Ok(cage) = self.bake_cage(texture_set, true) else { return Ok(None) }; + + Ok(Some(BakeCageInputs { + mesh: self.bake_mesh(texture_set)?, + bvh: self.bvh.clone(), + material: set.material, + settings: set.bake.clone(), + high, + cage, + skew: self.bake_paint(texture_set, true, BakePaintTarget::Skew)?, + cage_paint: self.bake_paint(texture_set, true, BakePaintTarget::Cage)?, + })) + } + + /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly + fn bake_high(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + } + + /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage + fn bake_cage(&self, texture_set: usize, has_high: bool) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + if !has_high || set.bake.cage.kind != texturecraft_core::CageType::CustomFile { + return Ok(None); + } + + let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + Ok(Some(cage.mesh.clone())) + } + + /// Texture set `texture_set`'s painted skew or cage map, used only when it bakes from a high poly + fn bake_paint(&self, texture_set: usize, has_high: bool, target: BakePaintTarget) -> Result>> { + let set = self.doc.project.texture_set(texture_set)?; + let paint = self.doc.bake_paint.get(&(texture_set, target)).filter(|_| has_high); + paint.map(|map| super::layout::paint_for_bake(map, set)).transpose() + } + + /// The low poly texture set `texture_set` bakes: UV tiles of mixed resolutions move into its atlas + fn bake_mesh(&self, texture_set: usize) -> Result> { + let set = self.doc.project.texture_set(texture_set)?; + Ok(match set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) { + Some(grid) => { + let mut mesh = (*self.source).clone(); + mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array()))); + Arc::new(mesh) + } + None => self.mesh.clone(), + }) + } + /// Store a finished bake as one undo step pub fn apply_bake(&mut self, texture_set: usize, output: BakeOutput) -> Result<()> { let tracer = output.tracer.clone(); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 213e1ff6..16ff68a7 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -1,5 +1,6 @@ //! Baking tasks, commands, settings helpers, and the mesh-map baking API +mod bake_cage_inputs; mod bake_mesh; mod bake_meshes; mod bake_task; @@ -11,6 +12,7 @@ mod paint_command; mod preserve_tiles; mod tile_command; +pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..a145ccb2 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -4,6 +4,9 @@ use glam::{Vec2, Vec3, Vec4}; use crate::{GeomError, Result}; +/// An edge by the bits of its two end positions, the lower one first +type EdgePositions = ([u32; 3], [u32; 3]); + /// A contiguous index range drawn with one material. #[derive(Clone, Debug, PartialEq)] pub struct SubMesh { @@ -107,6 +110,37 @@ impl Mesh { .collect() } + /// Edges where the UV layout splits: two triangles meet there in 3D but not in UV space, per material in `0..materials.len().max(1)` + pub fn uv_seam_edges(&self) -> Vec> { + let bits = |position: Vec3| position.to_array().map(f32::to_bits); + (0..self.materials.len().max(1)) + .map(|material| { + // Each 3D edge (by position) with the vertex pairs of the triangles that use it, the lower position first + let mut sides: std::collections::HashMap> = std::collections::HashMap::new(); + for triangle in self.triangles_of(material) { + let Some(corners) = self.indices.get(triangle * 3..triangle * 3 + 3) else { continue }; + + for (from, to) in [(corners[0], corners[1]), (corners[1], corners[2]), (corners[2], corners[0])] { + let (Some(from_position), Some(to_position)) = (self.positions.get(from as usize), self.positions.get(to as usize)) else { continue }; + let (from_bits, to_bits) = (bits(*from_position), bits(*to_position)); + let side = if from_bits <= to_bits { ((from_bits, to_bits), (from, to)) } else { ((to_bits, from_bits), (to, from)) }; + sides.entry(side.0).or_default().push(side.1); + } + } + + let uv = |index: u32| self.uvs.get(index as usize).copied(); + let mut seams: Vec<(u32, u32)> = sides + .into_values() + .filter(|pairs| pairs.iter().any(|&(from, to)| (uv(from), uv(to)) != (uv(pairs[0].0), uv(pairs[0].1)))) + .flat_map(|pairs| pairs.into_iter().map(|(from, to)| (from.min(to), from.max(to)))) + .collect(); + seams.sort_unstable(); + seams.dedup(); + seams + }) + .collect() + } + /// Material of triangle `t`. pub fn material_of(&self, t: usize) -> Option { let idx = (t * 3) as u32; @@ -433,6 +467,26 @@ mod tests { assert_eq!(crate::primitives::plane(1.0, 2).wire_edges()[0].len(), 12, "a 2×2 grid of quads has 12 edges"); } + #[test] + fn uv_seams_are_where_the_uv_layout_splits() { + let mesh = quad(); + assert_eq!(mesh.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()], "one UV island has no seam"); + + // Vertex 4 copies vertex 0's position with another UV: the diagonal (0, 2) / (4, 2) is cut + let mut seam = mesh.clone(); + seam.positions.push(seam.positions[0]); + seam.normals.push(seam.normals[0]); + seam.tangents.push(seam.tangents[0]); + seam.uvs.push(Vec2::new(0.9, 0.9)); + seam.indices[3] = 4; + assert_eq!(seam.uv_seam_edges(), vec![vec![(0, 2), (2, 4)]]); + + // The same split with the same UV is a hard edge, not a seam + let mut hard = seam.clone(); + hard.uvs[4] = hard.uvs[0]; + assert_eq!(hard.uv_seam_edges(), vec![Vec::<(u32, u32)>::new()]); + } + #[test] fn validate_catches_bad_indices() { let mut m = quad(); diff --git a/crates/render/src/bake_visualization.rs b/crates/render/src/bake_visualization.rs new file mode 100644 index 00000000..8dbc4927 --- /dev/null +++ b/crates/render/src/bake_visualization.rs @@ -0,0 +1,12 @@ +//! What bake mode's 3D view draws while a bake is set up: the high poly, the cage, the UV seams and the low poly + +/// Which parts of the bake setup the 3D view draws +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BakeVisualization { + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, + /// Draw the cage, seams and low poly of only this texture set + pub only_set: Option, +} diff --git a/crates/render/src/cage_gpu.rs b/crates/render/src/cage_gpu.rs new file mode 100644 index 00000000..3ed4f13f --- /dev/null +++ b/crates/render/src/cage_gpu.rs @@ -0,0 +1,9 @@ +/// One texture set's cage on the GPU: three corners per triangle and the wireframe's corner pairs +pub(crate) struct CageGpu { + /// Identifies the corners' order and the edges: a new distance with the same topology only rewrites `corners` + pub(crate) topology: u64, + pub(crate) corners: wgpu::Buffer, + pub(crate) corner_count: u32, + pub(crate) edges: wgpu::Buffer, + pub(crate) edge_index_count: u32, +} diff --git a/crates/render/src/high_poly_gpu.rs b/crates/render/src/high_poly_gpu.rs new file mode 100644 index 00000000..97da6861 --- /dev/null +++ b/crates/render/src/high_poly_gpu.rs @@ -0,0 +1,11 @@ +/// The high poly bake mode draws over the low poly +pub(crate) struct HighPolyGpu { + /// Which mesh the buffers hold + pub(crate) id: u64, + pub(crate) vertices: wgpu::Buffer, + pub(crate) vertex_count: usize, + pub(crate) indices: wgpu::Buffer, + pub(crate) index_count: u32, + /// One value per vertex: 1 where the bake's rays miss it (drawn red), 0 where they reach it + pub(crate) missed: wgpu::Buffer, +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c5ca2221..bb0967c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -13,12 +13,15 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod bake_visualization; +mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; pub mod gpu_trace; #[cfg(not(target_arch = "wasm32"))] pub mod headless; +mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; pub mod readback; @@ -26,7 +29,9 @@ pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; +mod uv_seam_gpu; +pub use bake_visualization::BakeVisualization; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4ce9dac3..a2da0223 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -30,10 +30,14 @@ use texturecraft_geom::glam::{Mat4, Vec3}; use texturecraft_geom::{Mesh, OrbitCamera}; use texturecraft_texel::TILE; +use crate::bake_visualization::BakeVisualization; +use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; +use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; +use crate::uv_seam_gpu::UvSeamGpu; pub const MSAA: u32 = 4; pub const COLOR_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; @@ -173,6 +177,8 @@ pub struct Shade { /// Move the surface by the height channel (3D view): a dense copy of the mesh, displaced in /// the vertex shader at the height-to-normal strength. pub displacement: bool, + /// Bake mode's high poly, cage and UV seams over the 3D view + pub bake: Option, } /// The viewport's subsurface scattering approximation: the diffuse lighting wraps around the @@ -259,6 +265,7 @@ impl Default for Shade { sss_blur: None, refraction: false, displacement: false, + bake: None, } } } @@ -530,6 +537,11 @@ pub struct Renderer { wire3d_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, + /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams + bake_high_pipeline: wgpu::RenderPipeline, + cage_pipeline: wgpu::RenderPipeline, + cage_wire_pipeline: wgpu::RenderPipeline, + uv_seam_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, blit_pipeline: wgpu::RenderPipeline, post_pipeline: wgpu::RenderPipeline, @@ -563,6 +575,10 @@ pub struct Renderer { /// accumulation. content_rev: u64, mesh: Option, + bake_high: Option, + /// Each texture set's cage, by set index + cages: Vec>, + uv_seams: Option, sets: Vec, /// Viewport texture resolution: display textures at 1/2^shift of each set's size (at least /// as reduced as the device's texture limit needs). @@ -808,20 +824,31 @@ fn halton(mut i: u32, base: u32) -> f32 { const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); +/// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves +const SHADOW_SLOPE_BIAS: f32 = 1.5; + +/// Anisotropic filtering of the texture sets' sampler +const MAX_ANISOTROPY: u16 = 8; + +/// Size of the environment texture before the first environment loads +const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; + impl Renderer { /// `target_format`: the format of the pass [`Renderer::blit`] draws into. pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, target_format: wgpu::TextureFormat) -> Renderer { let shader = |label: &str, source: &str| { device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(source.into()) }) }; - let module = shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"))); + let module = + shader("tc_mesh", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/mesh.wgsl"), "\n", include_str!("shaders/bake_view.wgsl"))); let util_module = shader("tc_util", include_str!("shaders/util.wgsl")); let post_module = shader("tc_post", concat!(include_str!("shaders/util.wgsl"), include_str!("shaders/post.wgsl"), include_str!("shaders/fx.wgsl"))); let shadow_module = shader("tc_shadow", concat!(include_str!("shaders/displace.wgsl"), include_str!("shaders/shadow.wgsl"))); - let bgl = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { + + let bind_group_layout = |label: &str, entries: &[wgpu::BindGroupLayoutEntry]| { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries }) }; - let globals_bgl = bgl( + let globals_bind_group_layout = bind_group_layout( "tc_globals", &[ uniform_entry(0), @@ -838,44 +865,47 @@ impl Renderer { fragment_entry(4, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison)), ], ); - // The display textures, the aux texture, the sampler. + // The display textures, the aux texture, the sampler let textures = DisplayKind::ALL.len() as u32 + 1; - // Displacement reads the height (and the sampler) in the vertex shader. - let height = DisplayKind::ALL.iter().position(|k| *k == DisplayKind::Height).unwrap_or(0) as u32; + // Displacement reads the height (and the sampler) in the vertex shader + let height = DisplayKind::ALL.iter().position(|kind| *kind == DisplayKind::Height).unwrap_or(0) as u32; let set_entries: Vec<_> = (0..textures) .map(tex_entry) .chain(std::iter::once(sampler_entry(textures))) - .map(|mut e| { - if e.binding == height || e.binding == textures { - e.visibility |= wgpu::ShaderStages::VERTEX; + .map(|mut entry| { + if entry.binding == height || entry.binding == textures { + entry.visibility |= wgpu::ShaderStages::VERTEX; } - e + entry }) .collect(); - let set_bgl = bgl("tc_set", &set_entries); - let refr_bgl = bgl("tc_refr", &[tex_entry(0)]); - let blit_bgl = bgl("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); - let mip_bgl = bgl("tc_mip", &[tex_entry(0), sampler_entry(1)]); - let fx_bgl = bgl("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); - let shadow_bgl = bgl("tc_shadow", &[uniform_entry(0)]); - let pl = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { + let set_bind_group_layout = bind_group_layout("tc_set", &set_entries); + let refraction_bind_group_layout = bind_group_layout("tc_refr", &[tex_entry(0)]); + let blit_bind_group_layout = bind_group_layout("tc_blit", &[tex_entry(0), sampler_entry(1), uniform_entry(2)]); + let mip_bind_group_layout = bind_group_layout("tc_mip", &[tex_entry(0), sampler_entry(1)]); + let effect_bind_group_layout = + bind_group_layout("tc_fx", &[tex_entry(0), sampler_entry(1), uniform_entry(3), tex_entry(4), tex_entry(5), tex_entry(6)]); + let shadow_bind_group_layout = bind_group_layout("tc_shadow", &[uniform_entry(0)]); + + let pipeline_layout = |label: &str, groups: &[Option<&wgpu::BindGroupLayout>]| { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: groups, immediate_size: 0 }) }; - let layout = pl("tc_uv", &[Some(&globals_bgl), Some(&set_bgl)]); - let mesh_layout = pl("tc_mesh", &[Some(&globals_bgl), Some(&set_bgl), Some(&refr_bgl)]); - let bg_layout = pl("tc_bg", &[Some(&globals_bgl)]); - let blit_layout = pl("tc_blit", &[Some(&blit_bgl)]); - let fx_layout = pl("tc_fx", &[Some(&fx_bgl)]); - let shadow_layout = pl("tc_shadow", &[Some(&shadow_bgl), Some(&set_bgl)]); - let vb = [Some(wgpu::VertexBufferLayout { + let layout = pipeline_layout("tc_uv", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout)]); + let mesh_layout = pipeline_layout("tc_mesh", &[Some(&globals_bind_group_layout), Some(&set_bind_group_layout), Some(&refraction_bind_group_layout)]); + let background_layout = pipeline_layout("tc_bg", &[Some(&globals_bind_group_layout)]); + let blit_layout = pipeline_layout("tc_blit", &[Some(&blit_bind_group_layout)]); + let effect_layout = pipeline_layout("tc_fx", &[Some(&effect_bind_group_layout)]); + let shadow_layout = pipeline_layout("tc_shadow", &[Some(&shadow_bind_group_layout), Some(&set_bind_group_layout)]); + + let vertex_layout = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, attributes: &wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3, 2 => Float32x4, 3 => Float32x2], })]; - // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode - // (e.g. RGBM) if WebGL2 without float color buffers turns out to matter. + + // shortcut: the RGBA8 fallback clips highlights above 1 and bands in the darks; encode (e.g. RGBM) if WebGL2 without float color buffers turns out to matter let hdr_format = if hdr_renderable(device) { HDR_FORMAT } else { COLOR_FORMAT }; - let hdr = |fs, blend| Some((fs, hdr_format, blend)); + let hdr_target = |fragment_entry_point, blend| Some((fragment_entry_point, hdr_format, blend)); let always = || Some(depth_state(false, wgpu::CompareFunction::Always)); let mesh_pipeline = pipeline( device, @@ -883,8 +913,8 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_mesh", None), + &vertex_layout, + hdr_target("fs_mesh", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); @@ -894,31 +924,103 @@ impl Renderer { &mesh_layout, &module, "vs_mesh", - &vb, - hdr("fs_opaque", None), + &vertex_layout, + hdr_target("fs_opaque", None), MSAA, Some(depth_state(true, wgpu::CompareFunction::Less)), ); - let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vb, hdr("fs_uv", None), MSAA, always()); + let uv_pipeline = pipeline(device, "tc_uv", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_uv", None), MSAA, always()); let blend = Some(wgpu::BlendState::ALPHA_BLENDING); - let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); + let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vertex_layout, hdr_target("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); - let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); - let highlight_pipeline = - pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); - let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); + let wire3d_pipeline = + pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let highlight_pipeline = pipeline( + device, + "tc_highlight", + &layout, + &module, + "vs_wire_highlight", + &vertex_layout, + hdr_target("fs_wire_highlight", blend), + MSAA, + wire3d_depth.clone(), + ); + + let [mesh_vertex_layout] = vertex_layout.clone(); + let high_layout = [ + mesh_vertex_layout, + Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![4 => Float32], + }), + ]; + let bake_high_pipeline = pipeline( + device, + "tc_bake_high", + &background_layout, + &module, + "vs_bake_high", + &high_layout, + hdr_target("fs_bake_high", None), + MSAA, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let corner_layout = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::<[f32; 3]>() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &wgpu::vertex_attr_array![0 => Float32x3], + })]; + let cage_pipeline = pipeline( + device, + "tc_cage", + &background_layout, + &module, + "vs_bake_cage", + &corner_layout, + hdr_target("fs_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let cage_wire_pipeline = pipeline( + device, + "tc_cage_wire", + &background_layout, + &module, + "vs_bake_cage_wire", + &corner_layout, + hdr_target("fs_wire_bake_cage", blend), + MSAA, + wire3d_depth.clone(), + ); + let uv_seam_pipeline = + pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); + let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); - let post_pipeline = pipeline(device, "tc_post", &fx_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); - let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))] - .map(|(fs, blend)| pipeline(device, "tc_bloom", &fx_layout, &post_module, "vs_full", &[], hdr(fs, blend), 1, None)); - let gbuf_pipeline = - pipeline(device, "tc_gbuf", &mesh_layout, &module, "vs_mesh", &vb, hdr("fs_gbuf", None), 1, Some(depth_state(true, wgpu::CompareFunction::Less))); - let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fs| pipeline(device, "tc_sss", &fx_layout, &post_module, "vs_full", &[], hdr(fs, None), 1, None)); - let dof_pipeline = pipeline(device, "tc_dof", &fx_layout, &post_module, "vs_full", &[], hdr("fs_dof", None), 1, None); + let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); + let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { + pipeline(device, "tc_bloom", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, blend), 1, None) + }); + let gbuffer_pipeline = pipeline( + device, + "tc_gbuf", + &mesh_layout, + &module, + "vs_mesh", + &vertex_layout, + hdr_target("fs_gbuf", None), + 1, + Some(depth_state(true, wgpu::CompareFunction::Less)), + ); + let sss_pipelines = ["fs_sss_h", "fs_sss_v"].map(|fragment_entry_point| { + pipeline(device, "tc_sss", &effect_layout, &post_module, "vs_full", &[], hdr_target(fragment_entry_point, None), 1, None) + }); + let dof_pipeline = pipeline(device, "tc_dof", &effect_layout, &post_module, "vs_full", &[], hdr_target("fs_dof", None), 1, None); let dof_target = Some(wgpu::ColorTargetState { format: hdr_format, blend: None, write_mask: wgpu::ColorWrites::ALL }); let dof_gather_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("tc_dof_gather"), - layout: Some(&fx_layout), + layout: Some(&effect_layout), vertex: wgpu::VertexState { module: &post_module, entry_point: Some("vs_full"), buffers: &[], compilation_options: Default::default() }, primitive: wgpu::PrimitiveState::default(), depth_stencil: None, @@ -932,20 +1034,23 @@ impl Renderer { multiview_mask: None, cache: None, }); + let shadow_depth = wgpu::DepthStencilState { - bias: wgpu::DepthBiasState { constant: 0, slope_scale: 1.5, clamp: 0.0 }, + bias: wgpu::DepthBiasState { constant: 0, slope_scale: SHADOW_SLOPE_BIAS, clamp: 0.0 }, ..depth_state(true, wgpu::CompareFunction::Less) }; - let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vb, None, 1, Some(shadow_depth)); - // accum = hdr * k + accum * (1 - k) with k = 1 / (sample + 1): a running average. + let shadow_pipeline = pipeline(device, "tc_shadow", &shadow_layout, &shadow_module, "vs_shadow", &vertex_layout, None, 1, Some(shadow_depth)); + + // accum = hdr_target * k + accum * (1 - k) with k = 1 / (sample + 1): a running average let average = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Constant, dst_factor: wgpu::BlendFactor::OneMinusConstant, operation: wgpu::BlendOperation::Add, }; - let accum_layout = pl("tc_accum", &[Some(&mip_bgl)]); + let accum_layout = pipeline_layout("tc_accum", &[Some(&mip_bind_group_layout)]); let accum_blend = Some(wgpu::BlendState { color: average, alpha: average }); - let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr("fs_copy", accum_blend), 1, None); + let accum_pipeline = pipeline(device, "tc_accum", &accum_layout, &util_module, "vs_full", &[], hdr_target("fs_copy", accum_blend), 1, None); + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { label: Some("tc_tex"), address_mode_u: wgpu::AddressMode::ClampToEdge, @@ -953,7 +1058,7 @@ impl Renderer { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::MipmapFilterMode::Linear, - anisotropy_clamp: 8, + anisotropy_clamp: MAX_ANISOTROPY, ..Default::default() }); let env_sampler = device.create_sampler(&wgpu::SamplerDescriptor { @@ -972,7 +1077,8 @@ impl Renderer { compare: Some(wgpu::CompareFunction::LessEqual), ..Default::default() }); - let shadow_buf = device.create_buffer(&wgpu::BufferDescriptor { + + let shadow_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("tc_shadow"), size: std::mem::size_of::<[[f32; 4]; 5]>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, @@ -986,39 +1092,45 @@ impl Renderer { vp: Mat4::IDENTITY, bg: device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_shadow"), - layout: &shadow_bgl, - entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buf.as_entire_binding() }], + layout: &shadow_bind_group_layout, + entries: &[wgpu::BindGroupEntry { binding: 0, resource: shadow_buffer.as_entire_binding() }], }), - buf: shadow_buf, + buf: shadow_buffer, }; + let black = Tex::new(device, "tc_black", 1, 1, COLOR_FORMAT, 1).view; - let refr_black = device.create_bind_group(&wgpu::BindGroupDescriptor { + let refraction_black = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_refr_black"), - layout: &refr_bgl, + layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", 512, 256, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); - let mut r = Renderer { + let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + + let mut renderer = Renderer { target_format, hdr_format, - globals_bgl, - set_bgl, - blit_bgl, - mip_bgl, - fx_bgl, - refr_bgl, - refr_black, + globals_bgl: globals_bind_group_layout, + set_bgl: set_bind_group_layout, + blit_bgl: blit_bind_group_layout, + mip_bgl: mip_bind_group_layout, + fx_bgl: effect_bind_group_layout, + refr_bgl: refraction_bind_group_layout, + refr_black: refraction_black, mesh_pipeline, opaque_pipeline, uv_pipeline, wire_pipeline, wire3d_pipeline, highlight_pipeline, + bake_high_pipeline, + cage_pipeline, + cage_wire_pipeline, + uv_seam_pipeline, bg_pipeline, blit_pipeline, post_pipeline, bloom_pipelines, - gbuf_pipeline, + gbuf_pipeline: gbuffer_pipeline, sss_pipelines, dof_gather_pipeline, dof_pipeline, @@ -1038,13 +1150,16 @@ impl Renderer { sh: [[0.0; 4]; 9], content_rev: 0, mesh: None, + bake_high: None, + cages: Vec::new(), + uv_seams: None, sets: Vec::new(), display_shift: 0, material_sets: Vec::new(), views: HashMap::new(), }; - r.set_environment(device, queue, "Studio Soft", None); - r + renderer.set_environment(device, queue, "Studio Soft", None); + renderer } pub fn environment_name(&self) -> &str { @@ -1124,6 +1239,79 @@ impl Renderer { self.content_rev += 1; } + /// Upload the high poly bake mode draws when `id` changed; `None` removes it + pub fn set_bake_high(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh: Option<&Mesh>, id: u64) { + if self.bake_high.as_ref().map(|high| high.id) == mesh.map(|_| id) { + return; + } + + self.bake_high = mesh.map(|mesh| HighPolyGpu { + id, + vertices: upload_buffer(device, queue, "tc_bake_high_vb", bytemuck::cast_slice(&subdivide::vertices(mesh)), wgpu::BufferUsages::VERTEX), + vertex_count: mesh.positions.len(), + indices: upload_buffer(device, queue, "tc_bake_high_ib", bytemuck::cast_slice(&mesh.indices), wgpu::BufferUsages::INDEX), + index_count: mesh.indices.len() as u32, + missed: upload_buffer(device, queue, "tc_bake_high_missed", bytemuck::cast_slice(&vec![0f32; mesh.positions.len()]), wgpu::BufferUsages::VERTEX), + }); + self.content_rev += 1; + } + + /// Which vertices of high poly `id` the bake's rays miss (1) or reach (0); ignored for another mesh or vertex count + pub fn set_bake_high_missed(&mut self, queue: &wgpu::Queue, id: u64, missed: &[f32]) { + let Some(high) = self.bake_high.as_ref().filter(|high| high.id == id && high.vertex_count == missed.len()) else { return }; + + queue.write_buffer(&high.missed, 0, bytemuck::cast_slice(missed)); + self.content_rev += 1; + } + + /// Texture set `texture_set`'s cage: `corners` three per triangle and `edges` as corner pairs; `None` removes it. The same `topology` as before only rewrites the corners + pub fn set_bake_cage(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, cage: Option<(&[Vec3], &[[u32; 2]])>, topology: u64) { + if self.cages.len() <= texture_set { + self.cages.resize_with(texture_set + 1, || None); + } + let Some(slot) = self.cages.get_mut(texture_set) else { return }; + + match (cage, slot.as_mut()) { + (None, _) => *slot = None, + (Some((corners, _)), Some(gpu)) if gpu.topology == topology && gpu.corner_count as usize == corners.len() => { + queue.write_buffer(&gpu.corners, 0, bytemuck::cast_slice(corners)); + } + (Some((corners, edges)), _) => { + *slot = Some(CageGpu { + topology, + corners: upload_buffer(device, queue, "tc_cage_vb", bytemuck::cast_slice(corners), wgpu::BufferUsages::VERTEX), + corner_count: corners.len() as u32, + edges: upload_buffer(device, queue, "tc_cage_ib", bytemuck::cast_slice(edges), wgpu::BufferUsages::INDEX), + edge_index_count: (edges.len() * 2) as u32, + }); + } + } + self.content_rev += 1; + } + + /// Forget the cages of texture sets from `count` on (sets that were removed) + pub fn truncate_bake_cages(&mut self, count: usize) { + if self.cages.len() > count { + self.cages.truncate(count); + self.content_rev += 1; + } + } + + /// The low poly's UV seams as vertex pairs per material ([`Mesh::uv_seam_edges`]) for mesh `mesh_id` + pub fn set_uv_seams(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, mesh_id: u64, seams: &[Vec<(u32, u32)>]) { + let mut line_indices: Vec = Vec::new(); + let mut line_draws = Vec::new(); + for (material, edges) in seams.iter().enumerate() { + let start = line_indices.len() as u32; + line_indices.extend(edges.iter().flat_map(|&(from, to)| [from, to])); + line_draws.push((start, line_indices.len() as u32 - start, material)); + } + + let lines = upload_buffer(device, queue, "tc_uv_seams", bytemuck::cast_slice(&line_indices), wgpu::BufferUsages::INDEX); + self.uv_seams = Some(UvSeamGpu { mesh_id, lines, line_draws }); + self.content_rev += 1; + } + /// Build the mesh's dense copy for displacement (once per mesh). fn ensure_dense(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) { let Some(m) = self.mesh.as_mut() else { return }; @@ -1889,30 +2077,30 @@ impl Renderer { self.draw_scene(encoder, v, resolve, globals_bg, frame, pipe, wire, highlight, refr); } - /// One scene pass: background, then the mesh with `pipe`, the wireframe with `wire` and one set's highlighted edges with `highlight` + /// One scene pass: background, then the mesh with `mesh_pipeline`, the wireframe with `wire` and one set's highlighted edges with `highlight` #[allow(clippy::too_many_arguments)] fn draw_scene( &self, encoder: &mut wgpu::CommandEncoder, - v: &ViewTargets, + targets: &ViewTargets, resolve: &wgpu::TextureView, - globals_bg: &wgpu::BindGroup, + globals_bind_group: &wgpu::BindGroup, frame: &Frame, - pipe: &wgpu::RenderPipeline, + mesh_pipeline: &wgpu::RenderPipeline, wire: Option<&wgpu::RenderPipeline>, highlight: Option<(&wgpu::RenderPipeline, usize)>, - refr: &wgpu::BindGroup, + refraction_source: &wgpu::BindGroup, ) { let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("tc_view"), color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: &v.msaa, + view: &targets.msaa, resolve_target: Some(resolve), depth_slice: None, ops: wgpu::Operations { load: CLEAR, store: wgpu::StoreOp::Discard }, })], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { - view: &v.depth, + view: &targets.depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: wgpu::StoreOp::Discard }), stencil_ops: None, }), @@ -1920,33 +2108,86 @@ impl Renderer { occlusion_query_set: None, multiview_mask: None, }); - pass.set_bind_group(0, globals_bg, &[]); + pass.set_bind_group(0, globals_bind_group, &[]); pass.set_pipeline(&self.bg_pipeline); pass.draw(0..3, 0..1); - let Some(m) = &self.mesh else { return }; - let uv_ts = match frame.kind { + let Some(mesh) = &self.mesh else { return }; + + let uv_set = match frame.kind { ViewKind::Scene => None, ViewKind::Uv { ts, .. } => Some(ts), }; - pass.set_bind_group(2, refr, &[]); - let geo = self.geometry(m, frame); - // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) + pass.set_bind_group(2, refraction_source, &[]); + let geometry = self.geometry(mesh, frame); let (highlight, highlight_set) = highlight.unzip(); + let bake = frame.shade.bake.filter(|_| uv_set.is_none()); + let low_poly_shown = bake.is_none_or(|bake| bake.low_poly); + let low_poly_set = bake.and_then(|bake| bake.only_set).or(uv_set); + // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (Some(pipe), &geo.vb, &geo.ib, &geo.draws, uv_ts, 1), - (wire, &m.geo.vb, &m.lines, &m.line_draws, uv_ts, 1), - (highlight, &m.geo.vb, &m.lines, &m.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (Some(mesh_pipeline).filter(|_| low_poly_shown), &geometry.vb, &geometry.ib, &geometry.draws, low_poly_set, 1), + (wire, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), ]; - for (pipe, vb, ib, ranges, only, instances) in passes { - let Some(pipe) = pipe else { continue }; - pass.set_pipeline(pipe); - pass.set_vertex_buffer(0, vb.slice(..)); - pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only) { + for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + let Some(pipeline) = pipeline else { continue }; + + pass.set_pipeline(pipeline); + pass.set_vertex_buffer(0, vertices.slice(..)); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(ranges, &frame.visible, only_set) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..instances); } } + + if let Some(bake) = bake { + self.draw_bake(&mut pass, mesh, frame, bake); + } + } + + /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` + fn draw_bake(&self, pass: &mut wgpu::RenderPass<'_>, low_poly: &MeshGpu, frame: &Frame, bake: BakeVisualization) { + if bake.high_poly + && let Some(high) = &self.bake_high + { + pass.set_pipeline(&self.bake_high_pipeline); + pass.set_vertex_buffer(0, high.vertices.slice(..)); + pass.set_vertex_buffer(1, high.missed.slice(..)); + pass.set_index_buffer(high.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..high.index_count, 0, 0..1); + } + + if bake.uv_seams + && let Some(seams) = self.uv_seams.as_ref().filter(|seams| seams.mesh_id == low_poly.id) + { + pass.set_pipeline(&self.uv_seam_pipeline); + pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); + pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); + for (range, set) in self.drawable(&seams.line_draws, &frame.visible, bake.only_set) { + pass.set_bind_group(1, &set.bind_group, &[]); + pass.draw_indexed(range, 0, 0..1); + } + } + + if !bake.cage { + return; + } + + let shown = |texture_set: usize| bake.only_set.is_none_or(|only| only == texture_set) && frame.visible.get(texture_set).copied().unwrap_or(true); + let cages = || self.cages.iter().enumerate().filter(move |(texture_set, _)| shown(*texture_set)).filter_map(|(_, cage)| cage.as_ref()); + // The translucent faces first, then the wireframe over them + pass.set_pipeline(&self.cage_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.draw(0..cage.corner_count, 0..1); + } + pass.set_pipeline(&self.cage_wire_pipeline); + for cage in cages() { + pass.set_vertex_buffer(0, cage.corners.slice(..)); + pass.set_index_buffer(cage.edges.slice(..), wgpu::IndexFormat::Uint32); + pass.draw_indexed(0..cage.edge_index_count, 0, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). diff --git a/crates/render/src/shaders/bake_view.wgsl b/crates/render/src/shaders/bake_view.wgsl new file mode 100644 index 00000000..1985f980 --- /dev/null +++ b/crates/render/src/shaders/bake_view.wgsl @@ -0,0 +1,88 @@ +// Bake mode's 3D view: the high poly, the cage around the low poly and the UV seams + +struct BakeViewOut { + @builtin(position) clip: vec4, + @location(0) world_position: vec3, + @location(1) normal: vec3, + // 1 where the bake's rays miss the high poly, 0 where they reach it + @location(2) missed: f32, +}; + +const HIGH_POLY_COLOR: vec3 = vec3(0.10, 0.36, 0.56); +const MISSED_COLOR: vec3 = vec3(0.80, 0.01, 0.01); +const CAGE_COLOR: vec3 = vec3(0.55, 0.42, 0.26); +const CAGE_OPACITY: f32 = 0.16; +const CAGE_WIRE_COLOR: vec4 = vec4(0.75, 0.62, 0.42, 0.7); +const UV_SEAM_COLOR: vec4 = vec4(0.20, 0.85, 0.30, 1.0); + +// Brightness of surfaces seen edge-on; facing the camera adds the rest +const HEADLIGHT_AMBIENT: f32 = 0.3; + +// Fractions of the way to the camera each vertex moves, so near-coincident surfaces and lines draw in a fixed order +const HIGH_POLY_PULL_TOWARD_EYE: f32 = 0.001; +const CAGE_WIRE_PULL_TOWARD_EYE: f32 = 0.002; + +// Lit from the camera: surfaces facing it are brightest +fn headlight(color: vec3, normal: vec3, world_position: vec3) -> vec3 { + let facing = abs(dot(normal, normalize(g.eye.xyz - world_position))); + return color * (HEADLIGHT_AMBIENT + (1.0 - HEADLIGHT_AMBIENT) * facing); +} + +fn pulled_toward_eye(world_position: vec3, fraction: f32) -> vec4 { + return g.view_proj * vec4(world_position + (g.eye.xyz - world_position) * fraction, 1.0); +} + +// Pulled slightly toward the camera: where the high poly nearly touches the low poly it shows instead of flickering with it +@vertex +fn vs_bake_high(@location(0) position: vec3, @location(1) normal: vec3, @location(4) missed: f32) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, HIGH_POLY_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = normal; + out.missed = missed; + return out; +} + +@fragment +fn fs_bake_high(surface: BakeViewOut) -> @location(0) vec4 { + let color = mix(HIGH_POLY_COLOR, MISSED_COLOR, surface.missed); + return vec4(headlight(color, normalize(surface.normal), surface.world_position), 1.0); +} + +@vertex +fn vs_bake_cage(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = g.view_proj * vec4(position, 1.0); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +// The cage's own faces: their normal comes from the screen-space change of the position +@fragment +fn fs_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + let face_normal = normalize(cross(dpdx(surface.world_position), dpdy(surface.world_position))); + return vec4(headlight(CAGE_COLOR, face_normal, surface.world_position), CAGE_OPACITY); +} + +// Pulled toward the camera like the 3D wireframe, so the lines win against the cage's faces +@vertex +fn vs_bake_cage_wire(@location(0) position: vec3) -> BakeViewOut { + var out: BakeViewOut; + out.clip = pulled_toward_eye(position, CAGE_WIRE_PULL_TOWARD_EYE); + out.world_position = position; + out.normal = vec3(0.0, 1.0, 0.0); + out.missed = 0.0; + return out; +} + +@fragment +fn fs_wire_bake_cage(surface: BakeViewOut) -> @location(0) vec4 { + return CAGE_WIRE_COLOR; +} + +@fragment +fn fs_wire_uv_seam(surface: VOut) -> @location(0) vec4 { + return UV_SEAM_COLOR; +} diff --git a/crates/render/src/uv_seam_gpu.rs b/crates/render/src/uv_seam_gpu.rs new file mode 100644 index 00000000..0ac80dc9 --- /dev/null +++ b/crates/render/src/uv_seam_gpu.rs @@ -0,0 +1,8 @@ +/// The low poly's UV seams as a line list over its vertex buffer +pub(crate) struct UvSeamGpu { + /// The low-poly mesh the lines belong to + pub(crate) mesh_id: u64, + pub(crate) lines: wgpu::Buffer, + /// (first index, count, material) per material + pub(crate) line_draws: Vec<(u32, u32, usize)>, +} diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..d148a268 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,8 +1,9 @@ use texturecraft_compose::{DisplayKind, ImageRes}; +use texturecraft_geom::glam::Vec3; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; -use texturecraft_render::{Frame, Shade, ViewKind}; +use texturecraft_render::{BakeVisualization, Frame, Shade, ViewKind}; /// The UI's key light (`viewport::shade`). const LIGHT: [f32; 4] = [0.5, 0.8, 0.4, 2.5]; @@ -42,6 +43,9 @@ impl Img { } } +/// The id `setup` uploads the material ball under +const MESH_ID: u64 = 1; + /// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). fn setup() -> Option<(Headless, Frame)> { let Ok(mut h) = Headless::new() else { @@ -49,7 +53,7 @@ fn setup() -> Option<(Headless, Frame)> { return None; }; let mesh = primitives::material_ball(); - h.renderer.set_mesh(&h.device, &h.queue, &mesh, 1); + h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); @@ -220,6 +224,73 @@ fn wireframe_3d_overlays_the_mesh() { assert_eq!(a.at(5, 5), b.at(5, 5), "the background stays clean"); } +#[test] +fn bake_visualization_draws_the_high_poly_and_the_cage() { + // A high poly inside the material ball, a cage around it, and how far a color must lead the others to count as that color + const HIGH_POLY_RADIUS_PER_SIZE: f32 = 0.3; + const CAGE_SCALE: f32 = 2.5; + const HIGH_POLY_ID: u64 = 7; + const CAGE_TOPOLOGY: u64 = 1; + const CAGE_EDGES: [[u32; 2]; 2] = [[0, 1], [1, 2]]; + const COLOR_LEAD: i32 = 30; + + let Some((mut h, frame)) = setup() else { return }; + let ball = primitives::material_ball(); + let (low_min, low_max) = ball.bounds(); + let ball_center = (low_min + low_max) * 0.5; + let mut high = primitives::sphere((low_max - low_min).max_element() * HIGH_POLY_RADIUS_PER_SIZE, 32, 16); + for position in &mut high.positions { + *position += ball_center; + } + h.renderer.set_bake_high(&h.device, &h.queue, Some(&high), HIGH_POLY_ID); + let corners: Vec = high.indices.iter().map(|index| (high.positions[*index as usize] - ball_center) * CAGE_SCALE + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&corners, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bake = BakeVisualization { high_poly: false, cage: false, uv_seams: false, low_poly: true, only_set: None }; + let center = (frame.size[0] / 2, frame.size[1] / 2); + + let only = |h: &mut Headless, parts: BakeVisualization, name: &str| render(h, &shaded(&frame, |s| s.bake = Some(parts)), name); + let low_only = only(&mut h, bake, "bake_low_only"); + let hidden = only(&mut h, BakeVisualization { low_poly: false, ..bake }, "bake_low_hidden"); + let high_poly = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_poly"); + let caged = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage"); + assert_same(&low_only, &render(&mut h, &frame, "bake_off"), "every part off draws only the low poly"); + let background = render(&mut h, &Frame { visible: vec![false, false], ..frame.clone() }, "bake_background"); + assert_same(&hidden, &background, "without the low poly only the background is left"); + let [red, green, blue] = high_poly.at(center.0, center.1).map(i32::from); + assert!(blue > red + COLOR_LEAD && blue > green, "the high poly inside the low poly draws blue: {:?}", [red, green, blue]); + let ([low_red, low_green, low_blue], [caged_red, caged_green, caged_blue]) = (low_only.at(center.0, center.1), caged.at(center.0, center.1)); + assert!( + caged_blue < low_blue && caged_red >= caged_blue && caged_green >= caged_blue, + "the cage tints the ball tan: {:?} → {:?}", + [low_red, low_green, low_blue], + [caged_red, caged_green, caged_blue] + ); + + // Vertices the bake's rays miss turn red + h.renderer.set_bake_high_missed(&h.queue, HIGH_POLY_ID, &vec![1.0; high.positions.len()]); + let missed = only(&mut h, BakeVisualization { low_poly: false, high_poly: true, ..bake }, "bake_high_missed"); + let [red, green, blue] = missed.at(center.0, center.1).map(i32::from); + assert!(red > blue + COLOR_LEAD && red > green + COLOR_LEAD, "missed vertices draw red: {:?}", [red, green, blue]); + + // Show for selected texture set only: the other set's low poly and the cage of set 0 drop out + let first_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(0), ..bake }, "bake_only_first_set"); + let second_set = only(&mut h, BakeVisualization { cage: true, only_set: Some(1), ..bake }, "bake_only_second_set"); + assert_ne!(first_set.px, caged.px, "the second set's low poly is left out"); + assert_ne!(second_set.px, caged.px, "the first set's low poly and cage are left out"); + assert_ne!(first_set.px, second_set.px); + + // UV seams draw over the low poly + h.renderer.set_uv_seams(&h.device, &h.queue, MESH_ID, &ball.uv_seam_edges()); + let seams = only(&mut h, BakeVisualization { uv_seams: true, ..bake }, "bake_uv_seams"); + assert_ne!(seams.px, low_only.px, "the seams show"); + + // A new distance with the same topology only moves the corners + let grown: Vec = corners.iter().map(|corner| (*corner - ball_center) * 2.0 + ball_center).collect(); + h.renderer.set_bake_cage(&h.device, &h.queue, 0, Some((&grown, &CAGE_EDGES)), CAGE_TOPOLOGY); + let bigger = only(&mut h, BakeVisualization { cage: true, ..bake }, "bake_cage_grown"); + assert_ne!(caged.px, bigger.px, "the cage grew"); +} + #[test] fn ortho_background_matches_perspective() { let Some((mut h, frame)) = setup() else { return }; diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs new file mode 100644 index 00000000..42da4393 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -0,0 +1,61 @@ +use egui::collapsing_header::CollapsingState; +use egui::{Rect, Ui, vec2}; +use egui_phosphor::regular as icon; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::{icon_button_without_tooltip, section_chevron}; + +/// The panel's width and its gap from the 3D view's top-left corner +const PANEL_WIDTH: f32 = 280.0; +const PANEL_MARGIN: f32 = 12.0; + +/// Size of the panel's eye buttons +const EYE_BUTTON_SIZE: f32 = 22.0; + +/// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` +pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let toggles = &mut app.ui.bake_visualization; + egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( + ui.ctx(), + |ui| { + ui.set_width(PANEL_WIDTH); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("bake_visualization_open"), true); + let header = eye_row(ui, &mut toggles.on, tr("Baking Visualization"), Some(collapsing_state.is_open())); + if header.clicked() { + collapsing_state.toggle(ui); + } + + collapsing_state.show_body_unindented(ui, |ui| { + ui.add_enabled_ui(toggles.on, |ui| { + ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); + eye_row(ui, &mut toggles.high_poly, tr("High Definition Mesh (HP)"), None); + eye_row(ui, &mut toggles.cage, tr("Cage"), None); + eye_row(ui, &mut toggles.uv_seams, tr("UV Seams"), None); + eye_row(ui, &mut toggles.low_poly, tr("Project Mesh (LP)"), None); + }); + }); + }, + ); +} + +/// A row with `label`, a chevron when `open` is given, and an eye button on the right that switches `shown`; returns the label's response +fn eye_row(ui: &mut Ui, shown: &mut bool, label: &str, open: Option) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + ui.horizontal(|ui| { + ui.set_min_height(EYE_BUTTON_SIZE); + let text = match open { + Some(is_open) => egui::RichText::new(format!("{} {label}", section_chevron(ui, is_open).text())), + None => egui::RichText::new(label), + }; + let response = ui.add(egui::Label::new(text.color(tokens.text_strong)).selectable(false).sense(egui::Sense::click())); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if icon_button_without_tooltip(ui, if *shown { icon::EYE } else { icon::EYE_SLASH }, label, false, EYE_BUTTON_SIZE).clicked() { + *shown = !*shown; + } + }); + response + }) + .inner +} diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs new file mode 100644 index 00000000..0603c523 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; +use texturecraft_render::BakeVisualization; + +/// The Baking Visualization panel's switches in bake mode's 3D view +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeVisualizationToggles { + /// The panel's eye: the whole visualization on or off + pub on: bool, + pub selected_set_only: bool, + pub high_poly: bool, + pub cage: bool, + pub uv_seams: bool, + pub low_poly: bool, +} + +impl Default for BakeVisualizationToggles { + fn default() -> Self { + Self { on: true, selected_set_only: false, high_poly: true, cage: true, uv_seams: false, low_poly: true } + } +} + +impl BakeVisualizationToggles { + /// What the renderer draws with these switches while texture set `selected_set` is selected + pub fn visualization(&self, selected_set: usize) -> Option { + self.on.then_some(BakeVisualization { + high_poly: self.high_poly, + cage: self.cage, + uv_seams: self.uv_seams, + low_poly: self.low_poly, + only_set: self.selected_set_only.then_some(selected_set), + }) + } +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3a308a4a..70dd4225 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -1,9 +1,13 @@ //! Bake Mode presentation; persisted settings live in core and edits use engine commands mod bake_paint_brush; +mod bake_visualization_panel; +mod bake_visualization_toggles; mod breadcrumb; mod common_settings; pub use bake_paint_brush::BakePaintBrush; +pub(crate) use bake_visualization_panel::bake_visualization_panel; +pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; mod mesh_map_bakers; diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs new file mode 100644 index 00000000..1a30780e --- /dev/null +++ b/crates/ui-egui/src/bake_scene.rs @@ -0,0 +1,11 @@ +//! Keeps the GPU's copy of bake mode's visualization (high poly, cages, UV seams) in step with the session + +mod bake_scene_link; +mod cage_link; +mod cage_shell_key; +mod cage_upload; +mod reach_link; +mod shared_handle; + +pub use bake_scene_link::BakeSceneLink; +pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs new file mode 100644 index 00000000..7f4459c6 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -0,0 +1,213 @@ +use std::sync::Arc; + +use texturecraft_engine::Session; +use texturecraft_engine::geom::Mesh; +use texturecraft_render::BakeVisualization; + +use super::CageUpload; +use super::cage_link::CageLink; +use super::cage_shell_key::CageShellKey; +use super::reach_link::ReachLink; +use super::shared_handle::SharedHandle; +use crate::gpu::SceneSync; + +/// What the GPU has of bake mode's visualization: the high poly, each set's cage and the UV seams +#[derive(Default)] +pub struct BakeSceneLink { + /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) + high: SharedHandle, + high_id: u64, + /// Whether the GPU has the high poly (a lost frame sends it again under the same id) + high_sent: bool, + cages: Vec>, + /// How many texture sets' cages the GPU was last told to keep + sent_cage_count: Option, + /// The low-poly mesh whose seams are uploaded + seams_mesh_id: Option, + next_topology: u64, + reach: ReachLink, +} + +impl BakeSceneLink { + /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay + pub fn resend(&mut self) { + self.high_sent = false; + self.sent_cage_count = None; + self.seams_mesh_id = None; + for link in self.cages.iter_mut().flatten() { + link.max_frontal = f32::NAN; + } + self.reach.resend(); + } + + /// Whether something is still being worked out off the UI thread + pub fn busy(&self) -> bool { + self.reach.busy() + } + + /// Add to `out` what the GPU needs to draw `visualization` this frame + pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + let Some(visualization) = visualization else { return }; + + if visualization.high_poly { + let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let handle = SharedHandle::of(high.as_ref()); + if handle != self.high { + self.high = handle; + self.high_id += 1; + self.high_sent = false; + } + if !self.high_sent { + out.bake_high = Some((high, self.high_id)); + self.high_sent = true; + } + self.reach.sync(session, self.high_id, visualization.only_set, out); + } + + if visualization.uv_seams && self.seams_mesh_id != Some(session.mesh_id) { + self.seams_mesh_id = Some(session.mesh_id); + out.uv_seams = Some((session.mesh_id, session.mesh.uv_seam_edges())); + } + + if visualization.cage { + self.sync_cages(session, out); + } + } + + /// Rebuild the cages whose inputs changed and move the corners of those whose distance changed + fn sync_cages(&mut self, session: &Session, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + if self.sent_cage_count != Some(set_count) { + out.bake_cage_count = Some(set_count); + self.sent_cage_count = Some(set_count); + } + self.cages.truncate(set_count); + self.cages.resize_with(set_count, || None); + + for (texture_set, link) in self.cages.iter_mut().enumerate() { + let (Some(key), Some(set)) = (CageShellKey::of(session, texture_set), session.doc.project.texture_sets.get(texture_set)) else { continue }; + + let max_frontal = set.bake.cage.max_frontal; + match link { + Some(link) if link.key == key => { + if link.max_frontal == max_frontal { + continue; + } + link.max_frontal = max_frontal; + } + _ => { + self.next_topology += 1; + let shell = session.bake_cage_inputs(texture_set).ok().flatten().and_then(|inputs| inputs.cage_shell().ok()).map(Arc::new); + *link = Some(CageLink { key, shell, topology: self.next_topology, max_frontal }); + } + } + + let Some(link) = link.as_ref() else { continue }; + + let upload = link.shell.as_ref().map(|shell| CageUpload { corners: shell.corners(max_frontal), shell: shell.clone() }); + out.bake_cages.push((texture_set, upload, link.topology)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + + /// The sample project with a high poly a little outside its low poly + fn session() -> Session { + const HIGH_POLY_OFFSET: f32 = 0.02; + + let mut session = texturecraft_engine::sample_session(128, 128).unwrap(); + let low = session.mesh.clone(); + let mut obj = String::new(); + for (position, normal) in low.positions.iter().zip(&low.normals) { + let raised = *position + *normal * HIGH_POLY_OFFSET; + obj += &format!("v {} {} {}\n", raised.x, raised.y, raised.z); + } + for corners in low.indices.chunks(3) { + obj += &format!("f {} {} {}\n", corners[0] + 1, corners[1] + 1, corners[2] + 1); + } + session.add_high_poly_bytes("high.obj", obj.into_bytes()).unwrap(); + session + } + + fn sync(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> SceneSync { + let mut out = SceneSync::default(); + link.sync(session, Some(visualization), &mut out); + out + } + + /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red + fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { + for _ in 0..2000 { + if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { + return missed.iter().sum::() / missed.len().max(1) as f32; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the reach never arrived"); + } + + fn set_distances(session: &mut Session, max_frontal: f32) { + texturecraft_engine::execute(session, "bake.settings", &json!({"ts": "all", "maxFrontal": max_frontal})).unwrap(); + } + + #[test] + fn a_new_distance_moves_the_corners_and_new_settings_rebuild_the_cage() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + let first = sync(&mut link, &session, EVERYTHING); + assert!(first.bake_high.is_some() && first.uv_seams.is_some() && first.bake_cage_count == Some(session.doc.project.texture_sets.len())); + let (_, Some(cage), topology) = first.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + + let unchanged = sync(&mut link, &session, EVERYTHING); + assert!(unchanged.bake_high.is_none() && unchanged.bake_cages.is_empty() && unchanged.uv_seams.is_none(), "nothing changed, nothing is sent"); + + set_distances(&mut session, 0.03); + let moved = sync(&mut link, &session, EVERYTHING); + let (_, Some(moved_cage), moved_topology) = moved.bake_cages.first().unwrap() else { panic!("set 0 has a cage") }; + assert_eq!(moved_topology, topology, "a distance only moves the corners"); + assert_ne!(moved_cage.corners, cage.corners); + + texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); + let rebuilt = sync(&mut link, &session, EVERYTHING); + assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + + link.resend(); + let resent = sync(&mut link, &session, EVERYTHING); + assert!(resent.bake_high.is_some() && resent.uv_seams.is_some() && resent.bake_cage_count.is_some(), "a lost frame sends everything again"); + assert_eq!(resent.bake_cages.len(), rebuilt.bake_cages.len()); + assert_eq!(resent.bake_cages.first().unwrap().2, rebuilt.bake_cages.first().unwrap().2, "the cages are not rebuilt for a lost frame"); + assert_eq!(resent.bake_high.unwrap().1, first.bake_high.unwrap().1, "the high poly goes again under the same id"); + assert!(!link.busy(), "a lost frame doesn't work out the reach again"); + } + + #[test] + fn the_red_follows_the_distances_and_the_selected_set() { + let (mut session, mut link) = (session(), BakeSceneLink::default()); + set_distances(&mut session, 0.0); + let at_zero = red_share(&mut link, &session, EVERYTHING); + assert!(at_zero > 0.5, "at frontal 0 the high poly outside the low poly is red: {at_zero}"); + + set_distances(&mut session, 0.05); + let covered = red_share(&mut link, &session, EVERYTHING); + assert!(covered < at_zero / 10.0, "a cage past the high poly reaches it: {covered}"); + + set_distances(&mut session, 0.0); + let by_name = |session: &mut Session, low_suffix: &str| { + for set in &mut session.doc.project.texture_sets { + set.bake.high_poly.match_mode = texturecraft_engine::core::MeshMatchMode::ByMeshName; + set.bake.high_poly.low_suffix = low_suffix.into(); + } + }; + by_name(&mut session, "_no_such_suffix"); + let by_name_red = red_share(&mut link, &session, EVERYTHING); + assert!(by_name_red > 0.5, "matching by name and other suffixes works out the reach again: {by_name_red}"); + + let no_set = BakeVisualization { only_set: Some(session.doc.project.texture_sets.len()), ..EVERYTHING }; + assert_eq!(red_share(&mut link, &session, no_set), 0.0, "sets left out by the filter color nothing"); + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_link.rs b/crates/ui-egui/src/bake_scene/cage_link.rs new file mode 100644 index 00000000..855d9619 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_link.rs @@ -0,0 +1,16 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; + +use super::cage_shell_key::CageShellKey; + +/// A texture set's cage as the GPU has it +pub(super) struct CageLink { + pub(super) key: CageShellKey, + /// `None`: the set bakes without a high poly or its cage can't be built + pub(super) shell: Option>, + /// The renderer's name for the shell's corner order and edges + pub(super) topology: u64, + /// The max frontal distance the GPU's corners are at + pub(super) max_frontal: f32, +} diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs new file mode 100644 index 00000000..44e17eca --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeMap; + +use texturecraft_engine::Session; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::geom::Mesh; + +use super::shared_handle::SharedHandle; + +/// Everything a texture set's cage shell is built from except the distances, which only move its corners +#[derive(Clone, Debug, PartialEq)] +pub(super) struct CageShellKey { + mesh_id: u64, + high: SharedHandle, + cage_file: SharedHandle, + material: usize, + uv_tiles: Vec, + tile_resolutions: BTreeMap, + cage_kind: CageType, + relative_to_bounding_box: bool, + average_normals: bool, + use_low_as_high: bool, + skew: SkewSettings, + /// The painted skew and cage maps + paint: [SharedHandle; 2], +} + +impl CageShellKey { + pub(super) fn of(session: &Session, texture_set: usize) -> Option { + let set = session.doc.project.texture_sets.get(texture_set)?; + let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); + Some(CageShellKey { + mesh_id: session.mesh_id, + high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + material: set.material, + uv_tiles: set.uv_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + cage_kind: set.bake.cage.kind, + relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, + average_normals: set.bake.cage.average_normals, + use_low_as_high: set.bake.high_poly.use_low_as_high, + skew: set.bake.skew, + paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], + }) + } +} diff --git a/crates/ui-egui/src/bake_scene/cage_upload.rs b/crates/ui-egui/src/bake_scene/cage_upload.rs new file mode 100644 index 00000000..81951645 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/cage_upload.rs @@ -0,0 +1,10 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::CageShell; +use texturecraft_engine::geom::glam::Vec3; + +/// A texture set's cage for the GPU: its corners at the current distance and the shell they come from +pub struct CageUpload { + pub corners: Vec, + pub shell: Arc, +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs new file mode 100644 index 00000000..45527522 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -0,0 +1,100 @@ +use std::sync::mpsc::{Receiver, TryRecvError}; + +use rayon::prelude::*; +use texturecraft_engine::Session; +use texturecraft_engine::bake::HighPolyReach; +use texturecraft_engine::core::HighPolySettings; + +use super::cage_shell_key::CageShellKey; +use crate::gpu::SceneSync; + +/// Each set's (max frontal, max rear) and the selected-set filter +type ShownDistances = (Vec<(f32, f32)>, Option); + +/// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show +#[derive(Default)] +pub(super) struct ReachLink { + /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for + keys: Vec>, + high_id: u64, + job: Option>>>, + reach: Vec>, + /// Each set's (max frontal, max rear) and the selected-set filter the GPU's colors are for + shown: Option, +} + +impl ReachLink { + /// Whether a reach is being worked out (the view must keep drawing to pick it up) + pub(super) fn busy(&self) -> bool { + self.job.is_some() + } + + /// Send the colors again (the GPU lost what it was sent); the reach itself stays + pub(super) fn resend(&mut self) { + self.shown = None; + } + + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed + pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { + let set_count = session.doc.project.texture_sets.len(); + let keys: Vec> = session + .doc + .project + .texture_sets + .iter() + .enumerate() + .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) + .collect(); + if keys != self.keys || high_id != self.high_id { + let inputs: Vec<_> = (0..set_count).map(|texture_set| session.bake_cage_inputs(texture_set).ok().flatten()).collect(); + self.job = Some(crate::spawn_worker("texturecraft-bake-reach", move || { + inputs.iter().map(|inputs| inputs.as_ref().and_then(|inputs| inputs.high_poly_reach().ok())).collect() + })); + (self.keys, self.high_id) = (keys, high_id); + } + + if let Some(job) = &self.job { + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + + // Colors wait for the reach being worked out: the old ones stay until it arrives + if self.job.is_some() { + return; + } + + let distances: Vec<(f32, f32)> = session.doc.project.texture_sets.iter().map(|set| (set.bake.cage.max_frontal, set.bake.cage.max_rear)).collect(); + let shown = (distances, only_set); + if self.shown.as_ref() == Some(&shown) { + return; + } + + let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + + // Each vertex is its nearest set's: other sets, and a set left out by the selected-set filter, never color it + let sets: Vec<(&HighPolyReach, f32, f32)> = self + .reach + .iter() + .zip(&shown.0) + .enumerate() + .filter(|(texture_set, _)| only_set.is_none_or(|only| only == *texture_set)) + .filter_map(|(_, (reach, &(max_frontal, max_rear)))| Some((reach.as_ref()?, max_frontal, max_rear))) + .collect(); + let missed: Vec = (0..vertex_count) + .into_par_iter() + .map(|vertex| { + let missed = sets.iter().find_map(|(reach, max_frontal, max_rear)| reach.missed(vertex, *max_frontal, *max_rear)); + f32::from(u8::from(missed.unwrap_or(false))) + }) + .collect(); + out.bake_high_missed = Some((self.high_id, missed)); + self.shown = Some(shown); + } +} diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs new file mode 100644 index 00000000..15ceb1d8 --- /dev/null +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Weak}; + +/// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it +#[derive(Debug)] +pub(super) struct SharedHandle(Option>); + +impl SharedHandle { + pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + SharedHandle(value.map(Arc::downgrade)) + } +} + +impl Clone for SharedHandle { + fn clone(&self) -> Self { + SharedHandle(self.0.clone()) + } +} + +impl Default for SharedHandle { + fn default() -> Self { + SharedHandle(None) + } +} + +impl PartialEq for SharedHandle { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (Some(this), Some(other)) => Weak::ptr_eq(this, other), + (this, other) => this.is_none() && other.is_none(), + } + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index c6695b34..6bce1312 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -11,7 +11,9 @@ use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, tile_bytes}; use texturecraft_engine::core::BakedMap; use texturecraft_engine::geom::Mesh; -use texturecraft_render::{Frame, Renderer, wgpu}; +use texturecraft_render::{BakeVisualization, Frame, Renderer, wgpu}; + +use crate::bake_scene::{BakeSceneLink, CageUpload}; /// Content shown through the aux texture. #[derive(Clone, Copy, Debug, PartialEq)] @@ -25,6 +27,9 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); +/// The low poly's UV seam edges (vertex pairs) per material +pub type UvSeamEdges = Vec>; + /// What the renderer must catch up with before drawing. #[derive(Default)] pub struct SceneSync { @@ -36,6 +41,16 @@ pub struct SceneSync { pub env: Option<(String, Option>)>, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, pub aux: Vec<(usize, u32, Vec)>, + /// Bake mode's high poly (`None` removes it) and the id it is sent under + pub bake_high: Option<(Option>, u64)>, + /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) + pub bake_high_missed: Option<(u64, Vec)>, + /// Changed cages: texture set, the cage or `None` to remove it, its topology + pub bake_cages: Vec<(usize, Option, u64)>, + /// Texture sets left after some were removed: their cages go too + pub bake_cage_count: Option, + /// The low poly's UV seams per material, for mesh id + pub uv_seams: Option<(u64, UvSeamEdges)>, } /// Lives in egui's callback resources. @@ -78,6 +93,7 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + bake_scene: BakeSceneLink, } /// Compositing time per frame: a full recomposite of a large texture set spreads over frames. @@ -124,6 +140,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + bake_scene: BakeSceneLink::default(), } } @@ -133,132 +150,158 @@ impl GpuLink { std::mem::take(&mut *self.reports.lock().unwrap_or_else(PoisonError::into_inner)) } - /// Collect everything the GPU needs this frame (runs the compositor first). + /// Whether bake mode's visualization is still being worked out off the UI thread + pub fn bake_busy(&self) -> bool { + self.bake_scene.busy() + } + /// Compositing progress (0..1) while tiles wait to be composited. pub fn composite_progress(&self, s: &Session) -> Option { let pending = s.pending_tiles(); (pending > 0 && self.composite_total > 0).then(|| 1.0 - pending as f32 / self.composite_total as f32) } - /// `spent_ms`: time this frame already took before the sync. - pub fn sync(&mut self, s: &mut Session, aux_map: Option, shift: u32, spent_ms: f64) -> SceneSync { - let start = crate::now_ms(); + /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + let start_ms = crate::now_ms(); let mut queued = 0usize; - let left = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start) - queued as f64 * UPLOAD_MS_PER_TILE; - let pending = s.pending_tiles(); + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - s.update_for(COMPOSITE_BUDGET_MS.min(left(0)).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { self.mesh_id = 0; self.sets.clear(); self.env = Default::default(); + self.bake_scene.resend(); self.reset.store(true, Ordering::Release); } - if self.mesh_id != s.mesh_id { - out.mesh = Some((s.mesh.clone(), s.mesh_id)); - self.mesh_id = s.mesh_id; + + if self.mesh_id != session.mesh_id { + out.mesh = Some((session.mesh.clone(), session.mesh_id)); + self.mesh_id = session.mesh_id; self.aux.clear(); } - let sets: Vec = s.doc.project.texture_sets.iter().map(|t| (t.size(), t.material)).collect(); + + let sets: Vec = session.doc.project.texture_sets.iter().map(|texture_set| (texture_set.size(), texture_set.material)).collect(); if sets != self.sets || shift != self.shift || out.mesh.is_some() { - out.sets = Some((sets.clone(), s.mesh.materials.len().max(1), shift)); + out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); self.sets = sets; self.shift = shift; } - let d = &s.doc.project.display; - let image = d.environment_resource().and_then(|n| s.images.get(n)); - let ptr = image.map_or(0, |i| Arc::as_ptr(i) as usize); - if self.env.0 != d.environment || self.env.1 != ptr { - self.env = (d.environment.clone(), ptr); - out.env = Some((d.environment.clone(), image.cloned())); + + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)); + let image_identity = image.map_or(0, |image| Arc::as_ptr(image) as usize); + if self.env.0 != display.environment || self.env.1 != image_identity { + self.env = (display.environment.clone(), image_identity); + out.env = Some((display.environment.clone(), image.cloned())); } + if self.reset.swap(false, Ordering::AcqRel) { - for c in &mut s.caches { - c.upload.extend(texturecraft_engine::compose::all_tiles(c.size.0, c.size.1)); + for cache in &mut session.caches { + cache.upload.extend(texturecraft_engine::compose::all_tiles(cache.size.0, cache.size.1)); } self.aux.clear(); } - for ts in 0..s.caches.len() { - let tiles = s.take_uploads(ts); + + for texture_set in 0..session.caches.len() { + let tiles = session.take_uploads(texture_set); if tiles.is_empty() { continue; } + let mut done = 0; - if let Some(cache) = s.caches.get(ts) { + if let Some(cache) = session.caches.get(texture_set) { let empty = Default::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&empty); - let comp = &cache.composite; - // In chunks while the frame has time (at least one chunk); the rest waits. + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let composite = &cache.composite; + // In chunks while the frame has time (at least one chunk); the rest waits for chunk in tiles.chunks(UPLOAD_CHUNK) { let bytes: Vec<_> = chunk .par_iter() - .flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty))) - .map(|(k, tx, ty)| (ts, k, tx, ty, tile_bytes(comp, baked, k, tx, ty))) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); done += chunk.len(); - if left(queued) < MIN_SLICE_MS { + if time_left_ms(queued) < MIN_SLICE_MS { break; } } } - if let (Some(rest), Some(cache)) = (tiles.get(done..), s.caches.get_mut(ts)) { + if let (Some(rest), Some(cache)) = (tiles.get(done..), session.caches.get_mut(texture_set)) { cache.upload.extend(rest.iter().copied()); } } + match aux_map { - Some(AuxView::MeshMap(m)) => { - for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); - if self.aux.get(&ts) == Some(&key) { + Some(AuxView::MeshMap(map)) => { + for texture_set in 0..session.caches.len() { + let revision = session.doc.baked.get(&texture_set).and_then(|baked| baked.maps.get(&map)).map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}"), revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let Some(cache) = s.caches.get(ts) else { continue }; + let Some(cache) = session.caches.get(texture_set) else { continue }; - let res = texturecraft_render::aux_size(cache.size); + let resolution = texturecraft_render::aux_size(cache.size); out.aux.push(( - ts, - res, - texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales), + texture_set, + resolution, + texturecraft_render::mesh_maps::mesh_map_rgba( + session.doc.baked.get(&texture_set), + map, + resolution, + cache.size, + &cache.composite.block_scales, + ), )); - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } Some(AuxView::Mask(id)) => { - if let Some((ts, _, _)) = s.doc.project.locate(id) { - let key = (format!("mask{}", id.0), s.revision); - if self.aux.get(&ts) != Some(&key) && !s.stroke_active() { - let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - if let Some(rgba) = s.mask_view_rgba(id, res) { - out.aux.push((ts, res, rgba)); + if let Some((texture_set, _, _)) = session.doc.project.locate(id) { + let key = (format!("mask{}", id.0), session.revision); + if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { + let resolution = + session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); + if let Some(rgba) = session.mask_view_rgba(id, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } } Some(AuxView::QuickMask) => { - for ts in 0..s.caches.len() { - let Some(cache) = s.caches.get(ts) else { continue }; - let key = (format!("quickmask{}", s.quick_mask.revision), cache.revision); - if self.aux.get(&ts) == Some(&key) { + for texture_set in 0..session.caches.len() { + let Some(cache) = session.caches.get(texture_set) else { continue }; + + let key = (format!("quickmask{}", session.quick_mask.revision), cache.revision); + if self.aux.get(&texture_set) == Some(&key) { continue; } - let res = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = s.quick_mask_rgba(ts, res) { - out.aux.push((ts, res, rgba)); + let resolution = texturecraft_render::aux_size(cache.size); + if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { + out.aux.push((texture_set, resolution, rgba)); } - self.aux.insert(ts, key); + self.aux.insert(texture_set, key); } } None => {} } + + self.bake_scene.sync(session, bake, &mut out); out } } +/// Mask view resolution for a texture set without a composite cache +const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024; + /// Paint callback for one view. pub struct ViewCallback { pub frame: Frame, @@ -295,39 +338,58 @@ impl CallbackTrait for ViewCallback { if let Some((mesh, id)) = &sync.mesh { gpu.renderer.set_mesh(device, queue, mesh, *id); } - if let Some((sets, mats, shift)) = &sync.sets { + if let Some((sets, material_count, shift)) = &sync.sets { gpu.renderer.set_display_shift(*shift); - let reset = gpu.renderer.set_texture_sets(device, queue, sets, *mats); + let reset = gpu.renderer.set_texture_sets(device, queue, sets, *material_count); if !reset.is_empty() { gpu.reset.store(true, Ordering::Release); } } - for (ts, k, tx, ty, bytes) in &sync.tiles { - gpu.renderer.upload_tile(device, queue, *ts, *k, *tx, *ty, bytes); + for (texture_set, kind, tile_x, tile_y, bytes) in &sync.tiles { + gpu.renderer.upload_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes); } - for (ts, size, bytes) in &sync.aux { - gpu.renderer.upload_aux(device, queue, *ts, *size, bytes); + for (texture_set, size, bytes) in &sync.aux { + gpu.renderer.upload_aux(device, queue, *texture_set, *size, bytes); + } + if let Some((high, id)) = &sync.bake_high { + gpu.renderer.set_bake_high(device, queue, high.as_deref(), *id); + } + if let Some((id, missed)) = &sync.bake_high_missed { + gpu.renderer.set_bake_high_missed(queue, *id, missed); + } + if let Some(count) = sync.bake_cage_count { + gpu.renderer.truncate_bake_cages(count); + } + for (texture_set, cage, topology) in &sync.bake_cages { + let cage = cage.as_ref().map(|upload| (upload.corners.as_slice(), upload.shell.edges.as_slice())); + gpu.renderer.set_bake_cage(device, queue, *texture_set, cage, *topology); + } + if let Some((mesh_id, seams)) = &sync.uv_seams { + gpu.renderer.set_uv_seams(device, queue, *mesh_id, seams); } } - // Also installs (or rejects) full-size textures WebGPU answered for since last frame. + + // Also installs (or rejects) full-size textures WebGPU answered for since last frame gpu.renderer.prepare(device, queue, encoder, &self.frame); let failed = gpu.renderer.take_memory_failures(); if !failed.is_empty() { - let mut r = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); - for ts in failed { - if !r.memory.contains(&ts) { - r.memory.push(ts); + let mut reports = gpu.reports.lock().unwrap_or_else(PoisonError::into_inner); + for texture_set in failed { + if !reports.memory.contains(&texture_set) { + reports.memory.push(texture_set); } } - // This frame's report drain already ran: the next frame shows the toast. + // This frame's report drain already ran: the next frame shows the toast gpu.ctx.request_repaint(); } if gpu.renderer.awaiting_gpu() { gpu.ctx.request_repaint(); } - let ppp = screen.pixels_per_point; - let r = self.rect; - gpu.renderer.set_blit_rect(queue, self.frame.view_id, [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp], screen.size_in_pixels); + + let pixels_per_point = screen.pixels_per_point; + let rect = self.rect; + let blit_rect = [rect.min.x * pixels_per_point, rect.min.y * pixels_per_point, rect.width() * pixels_per_point, rect.height() * pixels_per_point]; + gpu.renderer.set_blit_rect(queue, self.frame.view_id, blit_rect, screen.size_in_pixels); Vec::new() } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..5487c415 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Baking Visualization", "تصور الخبز"), + ("Show for Selected Texture Set Only", "العرض لمجموعة الخامات المحددة فقط"), + ("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"), + ("UV Seams", "فواصل UV"), + ("Project Mesh (LP)", "مجسم الإسقاط (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..ac1c709d 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Baking Visualization", "Bake-Visualisierung"), + ("Show for Selected Texture Set Only", "Nur für das ausgewählte Texturset anzeigen"), + ("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"), + ("UV Seams", "UV-Nähte"), + ("Project Mesh (LP)", "Projektions-Mesh (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..07b0be27 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Baking Visualization", "Visualización del horneado"), + ("Show for Selected Texture Set Only", "Mostrar solo para el conjunto de texturas seleccionado"), + ("High Definition Mesh (HP)", "Malla de alta resolución (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malla de proyección (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..0f5288c9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Baking Visualization", "Visualisation du baking"), + ("Show for Selected Texture Set Only", "Afficher uniquement pour l'ensemble de textures sélectionné"), + ("High Definition Mesh (HP)", "Maillage haute définition (HP)"), + ("UV Seams", "Coutures UV"), + ("Project Mesh (LP)", "Maillage de projection (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..e3956a8c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Baking Visualization", "Visualizzazione del baking"), + ("Show for Selected Texture Set Only", "Mostra solo per il set di texture selezionato"), + ("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"), + ("UV Seams", "Cuciture UV"), + ("Project Mesh (LP)", "Mesh di proiezione (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..089e77e4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Baking Visualization", "ベイクの可視化"), + ("Show for Selected Texture Set Only", "選択したテクスチャセットのみ表示"), + ("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"), + ("UV Seams", "UVシーム"), + ("Project Mesh (LP)", "投影メッシュ (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..726e1c35 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Baking Visualization", "베이크 시각화"), + ("Show for Selected Texture Set Only", "선택한 텍스처 세트만 표시"), + ("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"), + ("UV Seams", "UV 심"), + ("Project Mesh (LP)", "투영 메시 (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..607c0c49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Baking Visualization", "Visualização do bake"), + ("Show for Selected Texture Set Only", "Mostrar apenas para o conjunto de texturas selecionado"), + ("High Definition Mesh (HP)", "Malha de alta resolução (HP)"), + ("UV Seams", "Costuras UV"), + ("Project Mesh (LP)", "Malha de projeção (LP)"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..5b47bd31 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,9 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Baking Visualization", "烘焙可视化"), + ("Show for Selected Texture Set Only", "仅显示所选纹理集"), + ("High Definition Mesh (HP)", "高模网格 (HP)"), + ("UV Seams", "UV 接缝"), + ("Project Mesh (LP)", "投射网格 (LP)"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..bd7591fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,6 +8,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod bake_scene; pub mod control; pub mod dock; pub mod docking; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..94958f61 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -296,6 +296,9 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) + #[serde(default)] + pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, } impl UiState { @@ -365,6 +368,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..82bd0258 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -296,30 +296,43 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { } fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, frame: Frame, sync: &mut PendingSync) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); + let bake = bake_visualization(app); let scene = match (sync.0.take(), app.gpu.as_mut()) { - (Some(aux), Some(g)) => { - let t0 = crate::now_ms(); - let scene = g.sync(&mut app.session, aux, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); - let reports = g.take_reports(); - app.profiler.sync_ms += (crate::now_ms() - t0) as f32; + (Some(aux), Some(gpu_link)) => { + let sync_start_ms = crate::now_ms(); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + let reports = gpu_link.take_reports(); + app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); - // Display tiles left for later frames (the frame budget ran out). - if app.session.caches.iter().any(|c| !c.upload.is_empty()) { + + // Display tiles left for later frames (the frame budget ran out), or the bake visualization still being worked out + if app.session.caches.iter().any(|cache| !cache.upload.is_empty()) || app.gpu.as_ref().is_some_and(crate::gpu::GpuLink::bake_busy) { ui.ctx().request_repaint(); } Some(scene) } _ => None, }; + let Some(gpu) = &app.gpu else { - ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, tr("No GPU renderer available"), egui::FontId::proportional(14.0), tk.viewport_text); + ui.painter().text( + rect.center(), + egui::Align2::CENTER_CENTER, + tr("No GPU renderer available"), + egui::FontId::proportional(NO_GPU_TEXT_SIZE), + tokens.viewport_text, + ); return; }; - let cb = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; - ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, cb)); + + let callback = ViewCallback { frame, sync: Mutex::new(scene), rect, lost: gpu.lost.clone() }; + ui.painter().add(eframe::egui_wgpu::Callback::new_paint_callback(rect, callback)); } +/// Text size of the notice a view shows without a GPU renderer +const NO_GPU_TEXT_SIZE: f32 = 14.0; + /// Width of the camera and view pickers centred at the top of a view const VIEW_HEADER_WIDTH: f32 = 300.0; @@ -617,7 +630,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + shade: Shade { highlight: drop_highlight(app, ui, &response), bake: bake_visualization(app), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), }; add_callback(app, ui, rect, frame, sync); @@ -658,17 +671,30 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin brush_readout(app, ui, &response, adjusting); if app.session.quick_mask.editing { ui.painter_at(rect).text( - rect.left_top() + vec2(12.0, 40.0), + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, egui::Align2::LEFT_TOP, tr("Editing quick mask: paint where painting is allowed (U to finish)"), - egui::FontId::proportional(12.0), - Color32::from_rgb(0xe8, 0x6a, 0x6a), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, ); } + if app.ui.mode == crate::state::Mode::Baking { + crate::bake_mode::bake_visualization_panel(app, ui, rect); + } view_header(app, ui, rect, "v3d"); axis_gizmo(ui, rect, app, false); } +/// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red +const QUICK_MASK_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 40.0); +const QUICK_MASK_NOTICE_TEXT_SIZE: f32 = 12.0; +const QUICK_MASK_NOTICE_COLOR: Color32 = Color32::from_rgb(0xe8, 0x6a, 0x6a); + +/// What bake mode's 3D view draws besides the low poly (nothing in the other modes) +fn bake_visualization(app: &TextureCraftApp) -> Option { + (app.ui.mode == crate::state::Mode::Baking).then(|| app.ui.bake_visualization.visualization(app.session.ts())).flatten() +} + /// What a drag on the selected decal's frame does. #[derive(Clone, Copy, Debug, PartialEq)] enum DecalGrab { From 9c570137f7b5557559c3d64c612ac068e2a98b47 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 15:37:56 +0100 Subject: [PATCH 072/275] Keep the pointer over the 2D view header and size the brush outline by pen pressure The brush cursor in the 2D view hid the system pointer and drew the outline over the view header pickers. Its radius also ignored pen pressure, while painting shrinks the stamp towards min_size. Both now follow the painted footprint (BrushSettings::uv_stamp_radius, shared with continue_stroke_uv), with regression tests for header hover and partial pressure. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 3 +- crates/paint/src/brush.rs | 16 +++++++ crates/ui-egui/src/viewport.rs | 20 +++++---- crates/ui-egui/tests/brush_cursor_2d.rs | 59 ++++++++++++++++++++++++- 4 files changed, 87 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6f2a74ff..388758b9 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -318,8 +318,7 @@ impl Session { let Some((last, carry)) = st.uv.as_mut() else { return }; let Some(cache) = self.caches.get_mut(st.ts) else { return }; let b = &st.stroke.settings; - let p = pressure.clamp(0.0, 1.0); - let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 }; + let radius = b.uv_stamp_radius(pressure); let step = (b.spacing * 2.0 * radius).max(1e-5); let mut points = Vec::new(); match *last { diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 61313d57..45c9ed30 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -291,6 +291,13 @@ impl Default for BrushSettings { } impl BrushSettings { + /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the + /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { + let p = pressure.clamp(0.0, 1.0); + self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + } + /// Clamp every value into its valid range (input from UI, CLI or agents). pub fn sanitized(&self) -> BrushSettings { let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d }; @@ -323,6 +330,15 @@ impl BrushSettings { #[cfg(test)] mod tests { + #[test] + fn uv_stamp_radius_follows_pen_pressure() { + let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; + assert!((b.uv_stamp_radius(1.0) - 0.2).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.5) - 0.15).abs() < 1e-6); + assert!((b.uv_stamp_radius(0.0) - 0.1).abs() < 1e-6); + assert!((b.uv_stamp_radius(7.0) - 0.2).abs() < 1e-6, "pressure clamps to 1"); + } + use super::*; #[test] diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 24ed251c..213dc8f0 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -332,14 +332,16 @@ const VIEW_HEADER_TOP_GAP: f32 = 8.0; /// Width of each of the two pickers const VIEW_PICKER_WIDTH: f32 = 130.0; +/// Where `view_header` draws its pickers in a view of `rect`; `None` when the view is too narrow. +fn view_header_rect(rect: Rect) -> Option { + (rect.width() >= VIEW_HEADER_WIDTH).then(|| { + Rect::from_min_size(rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP), vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)) + }) +} + /// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { - if rect.width() < VIEW_HEADER_WIDTH { - return; - } - - let header_min = rect.min + vec2((rect.width() - VIEW_HEADER_WIDTH) * 0.5, VIEW_HEADER_TOP_GAP); - let header = Rect::from_min_size(header_min, vec2(VIEW_HEADER_WIDTH, VIEW_HEADER_HEIGHT)); + let Some(header) = view_header_rect(rect) else { return }; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); let current = texturecraft_engine::camera_cmds::current(&app.session); @@ -1300,9 +1302,11 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !response.dragged_by(PointerButton::Middle) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } + // The view header's pickers keep the normal pointer. + && !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(hp)) { - // A UV brush stamp has a radius of twice the brush size, as in `continue_stroke_uv`. - let r = (to_screen(app.session.tool.brush.size * 2.0, 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); + // The stamp's radius as `continue_stroke_uv` paints it, including a light pen's smaller footprint. + let r = (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); } diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 58cb4a8e..d205c541 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -1,6 +1,6 @@ //! The 2D view hides the system pointer and draws the brush outline under it while painting. -use egui::CursorIcon; +use egui::{CursorIcon, Event, Pos2, Shape, TouchDeviceId, TouchId, TouchPhase}; use egui_kittest::Harness; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; @@ -39,3 +39,60 @@ fn outside_painting_the_2d_view_keeps_the_normal_pointer() { h.run_steps(3); assert_ne!(cursor(&h), CursorIcon::None); } + +/// Radii of the white brush-outline rings (stroke 1.2) around `c` in the last frame. +fn rings_at(h: &Harness<'_, TextureCraftApp>, c: Pos2) -> Vec { + fn walk(shape: &Shape, c: Pos2, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, c, out)), + Shape::Circle(circle) if (circle.stroke.width - 1.2).abs() < 1e-3 && circle.center.distance(c) < 0.5 => out.push(circle.radius), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, c, &mut out)); + out +} + +#[test] +fn the_view_header_keeps_the_normal_pointer_and_gets_no_brush_outline() { + let mut h = harness(); + // The view's top edge is where the brush outline first replaces the pointer; the header is + // centred 8 points below it and 22 high. + let view_top = (0..200).map(|y| y as f32).find(|&y| { + h.hover_at(egui::pos2(300.0, y)); + h.run_steps(2); + cursor(&h) == CursorIcon::None + }); + let top = view_top.expect("the view has a top edge"); + let header = egui::pos2(800.0, top + 8.0 + 11.0); + h.hover_at(header); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "over the pickers the pointer stays"); + assert!(rings_at(&h, header).is_empty(), "no brush outline over the pickers"); + let below = egui::pos2(800.0, top + 120.0); + h.hover_at(below); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "below the header the brush outline is back"); + assert!(!rings_at(&h, below).is_empty()); +} + +#[test] +fn a_light_pen_shows_the_smaller_footprint_it_paints() { + let mut h = harness(); + h.state_mut().session.tool.brush.size = 0.05; + h.state_mut().session.tool.brush.min_size = 0.5; + let c = egui::pos2(800.0, 600.0); + h.hover_at(c); + h.run_steps(3); + let full = rings_at(&h, c); + assert_eq!(full.len(), 1, "one outline at full pressure"); + // A pen sample at half pressure: stamp radius is min + (1 - min) * p = 0.75 of full. + let events = &mut h.input_mut().events; + events.push(Event::Touch { device_id: TouchDeviceId(1), id: TouchId(1), phase: TouchPhase::Move, pos: c, force: Some(0.5) }); + events.push(Event::PointerMoved(c)); + h.step(); + let light = rings_at(&h, c); + assert_eq!(light.len(), 1); + assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); +} From 8eeb8e5e7e78d331b18f2ca2d8df6b35b8b36b41 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:54:00 +0100 Subject: [PATCH 073/275] Name the exact byte counts in the too-large-to-save error Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 2 +- crates/formats/src/project_file/tests.rs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 92f6ca8a..3319c4f0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -147,7 +147,7 @@ fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { if size > limit { let gib = |b: u64| b as f64 / (1u64 << 30) as f64; return Err(FormatError::TooLarge(format!( - "the project holds {:.2} GiB of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB, so nothing was saved and an existing file is unchanged. \ + "the project holds {:.2} GiB ({size} bytes) of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB ({limit} bytes), so nothing was saved and an existing file is unchanged. \ Remove paint layers or baked maps to make it smaller", gib(size), gib(limit) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index b16d2f02..074566bf 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -358,6 +358,9 @@ fn a_project_too_big_to_reopen_is_not_saved() { let err = check_loadable(&s.pf, size - 1).unwrap_err(); assert!(matches!(err, FormatError::TooLarge(_))); assert!(err.to_string().contains("nothing was saved"), "{err}"); + // Exact byte counts: a size just over the limit does not read as the limit. + let msg = err.to_string(); + assert!(msg.contains(&format!("({size} bytes)")) && msg.contains(&format!("({} bytes)", size - 1)), "{msg}"); } #[cfg(not(target_arch = "wasm32"))] From 8d902bea6fe28a607be989064373aba6ff0de146 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:54:02 +0100 Subject: [PATCH 074/275] Hide the system pointer only while it is over the 2D view Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 213dc8f0..2443e182 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1300,6 +1300,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && brush_tool(app.session.tool.tool) && !response.dragged_by(PointerButton::Middle) + // During a drag egui keeps reporting a hover position after the pointer left the view: + // the system pointer is hidden only while the pointer is really over it. + && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } // The view header's pickers keep the normal pointer. From 3f13752155c4f45f305b66483185410956c6347b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 00:54:31 +0100 Subject: [PATCH 075/275] Test that the generator offset survives save and reopen and undoes Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/tests/session.rs | 36 ++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index af1dbc6a..e73b7a47 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -80,6 +80,42 @@ fn generator_offset_is_settable_and_clamped() { assert_eq!(offset(&s), 1.0, "clamped to 1"); } +fn generator_offset_of(s: &Session) -> f32 { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() +} + +#[test] +fn generator_offset_survives_save_and_reopen_and_undo_restores_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": -0.6})).unwrap(); + assert_eq!(generator_offset_of(&s), -0.6); + + let path = std::env::temp_dir().join(format!("tc-generator-offset-{}.tcraft", std::process::id())); + let path = path.to_str().unwrap(); + execute(&mut s, "file.saveCopy", &json!({"path": path})).unwrap(); + let reopened = texturecraft_engine::file_cmds::open_path(path); + let _ = std::fs::remove_file(path); + assert_eq!(generator_offset_of(&reopened.unwrap()), -0.6, "the offset is saved and read back"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(generator_offset_of(&s), 0.25, "undo restores the previous offset"); +} + #[test] fn layer_rename_and_undo() { let mut s = session(); From d0967df09eacb8fe6737e5b538c0de3f5a9bcebe Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 00:54:33 +0100 Subject: [PATCH 076/275] Test that the system pointer returns when a drag leaves the 2D view Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/tests/brush_cursor_2d.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index d205c541..3b7cca9c 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -96,3 +96,23 @@ fn a_light_pen_shows_the_smaller_footprint_it_paints() { assert_eq!(light.len(), 1); assert!((light[0] / full[0] - 0.75).abs() < 1e-3, "half pressure shows 0.75 of the radius: {} vs {}", light[0], full[0]); } + +#[test] +fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + h.hover_at(c); + h.run_steps(3); + assert_eq!(cursor(&h), CursorIcon::None, "inside the view the brush outline replaces the pointer"); + // Press inside the view, then carry the pointer out of the view (top-left corner) with the button held. + h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() }); + h.run_steps(2); + assert_eq!(cursor(&h), CursorIcon::None, "still inside while dragging"); + let outside = egui::pos2(2.0, 2.0); + h.hover_at(outside); + h.run_steps(3); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible even during a drag"); + assert!(rings_at(&h, outside).is_empty(), "no brush outline outside the view"); + h.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); +} From ca19e714a0cf76fd809f9abc47ef8cdc8d3d86e6 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:51:56 +0000 Subject: [PATCH 077/275] Filter picker: swap a filter's type from its Properties slot effect.set takes filter: to swap a filter effect's type in place, keeping its place, blending, opacity and visibility (one undo step). A reusable resource_picker shows grouped, searchable shelf tiles at a slot; the filter slot uses it, and Add filter adds a neutral filter. --- crates/engine/src/filter_lib.rs | 7 ++ crates/engine/src/mask_cmds.rs | 96 +++++++++++----- crates/engine/tests/filter_swap.rs | 94 +++++++++++++++ crates/ui-egui/src/dock.rs | 126 ++++++++++----------- crates/ui-egui/src/filter_slot.rs | 83 ++++++++++++++ crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/i18n/de.rs | 2 + crates/ui-egui/src/i18n/es.rs | 2 + crates/ui-egui/src/i18n/fr.rs | 2 + crates/ui-egui/src/i18n/it.rs | 2 + crates/ui-egui/src/i18n/ja.rs | 2 + crates/ui-egui/src/i18n/ko.rs | 2 + crates/ui-egui/src/i18n/pt_br.rs | 2 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/menus.rs | 8 +- crates/ui-egui/src/resource_picker.rs | 126 +++++++++++++++++++++ crates/ui-egui/src/resource_picker_item.rs | 9 ++ crates/ui-egui/src/shelf.rs | 10 +- crates/ui-egui/tests/filter_picker.rs | 81 +++++++++++++ 20 files changed, 562 insertions(+), 99 deletions(-) create mode 100644 crates/engine/tests/filter_swap.rs create mode 100644 crates/ui-egui/src/filter_slot.rs create mode 100644 crates/ui-egui/src/resource_picker.rs create mode 100644 crates/ui-egui/src/resource_picker_item.rs create mode 100644 crates/ui-egui/tests/filter_picker.rs diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index f3168c9d..0f0fd952 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -19,6 +19,13 @@ pub struct FilterDef { pub mask: bool, } +impl FilterDef { + /// Whether it builds a filter effect (levels and material finishes are effect types of their own) + pub fn is_filter_effect(&self) -> bool { + matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_))) + } +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..bd545fbc 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -413,55 +413,76 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } +/// Edits effect `effect`: visibility, blending, name, its kind's parameters, or a filter's type fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { + const CMD: &str = "effect.set"; + let effect = effect_id(s, p, CMD)?; + let blend = blend_param(CMD, p, "blend")?; + + // `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one + let anchor = match s.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; + let channel_param = channel_param(CMD, p, "anchorChannel")?; match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + Some(anchor) => Some(anchor_source(s, CMD, owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; + + let swapped = match strp(p, "filter") { + Some(filter) => Some(swapped_filter(s, effect, filter, p)?), + None => None, + }; + let swaps_filter = swapped.is_some(); + s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + let edited = s.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let Some((kind, label)) = swapped { + if let EffectKind::Filter(old) = &edited.kind + && edited.name == old.label() + { + edited.name = label.to_string(); + } + edited.kind = kind; } - if let Some(b) = blend { - e.blend = b; + + if let Some(visible) = boolp(p, "visible") { + edited.visible = visible; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(blend) = blend { + edited.blend = blend; } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(opacity) = f32p(p, "opacity") { + edited.opacity = opacity.clamp(0.0, 1.0); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + if let Some(name) = name_param(p) { + edited.name = name.to_string(); + } + + match &mut edited.kind { + EffectKind::Generator(generator) => generator_from(p, generator), + EffectKind::Levels(levels) => levels_from(p, levels), + // The swapped filter was built with the parameters already + EffectKind::Filter(_) if swaps_filter => {} + EffectKind::Filter(filter) => crate::filter_lib::apply(p, filter, CMD)?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(p, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(p, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} @@ -471,6 +492,27 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Filter `id` built with `p` and its label, to replace filter effect `effect` +fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { + const CMD: &str = "effect.set"; + let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if !matches!(current.kind, EffectKind::Filter(_)) { + return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase()))); + } + + let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?; + if !def.is_filter_effect() { + return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label))); + } + + let mask = s.doc.project.layer(owner)?.mask.as_ref(); + let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect)); + if on_mask && !def.mask { + return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label))); + } + Ok((crate::filter_lib::build(def.id, p)?, def.label)) +} + /// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there. fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec, usize)> { project.layers.values_mut().find_map(|l| { diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs new file mode 100644 index 00000000..87341c60 --- /dev/null +++ b/crates/engine/tests/filter_swap.rs @@ -0,0 +1,94 @@ +//! Swapping a filter effect's type in place through `effect.set {filter}` + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// A sphere project with its default layer selected +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap() +} + +/// Runs effect-adding `command` and returns the new effect, which it selects +fn add(s: &mut Session, command: &str, params: Value) -> LayerId { + execute(s, command, ¶ms).unwrap(); + let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) }; + + added +} + +/// A copy of effect `id` +fn effect(s: &Session, id: LayerId) -> Effect { + s.doc.project.effect(id).unwrap().1.clone() +} + +/// Ids of the selected layer's content effects, bottom first +fn content_order(s: &Session) -> Vec { + let layer = s.selected_layer().unwrap(); + s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect() +} + +#[test] +fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind); + assert_eq!(blur.name, "Blur", "a default name follows the new filter"); + assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false)); + assert_eq!(content_order(&s), vec![below, swapped, above]); +} + +#[test] +fn swapping_a_filter_keeps_a_name_the_user_chose() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap(); + + assert_eq!(effect(&s, id).name, "Flip"); +} + +#[test] +fn one_undo_restores_the_old_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + let restored = effect(&s, id); + assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind); + assert_eq!(restored.name, "Threshold"); +} + +#[test] +fn a_mask_refuses_a_content_only_filter() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + + let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err(); + + assert!(err.to_string().contains("not on masks"), "{err}"); + assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn only_filter_effects_swap_and_only_to_filters() { + let mut s = session(); + let levels = add(&mut s, "effect.add.levels", json!({"target": "content"})); + let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); + assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); + assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..13604e91 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,7 +8,7 @@ use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; -use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; +use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; @@ -19,6 +19,13 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +const NEW_FILTER: &str = "hsl"; +const FILTER_SWATCH_WIDTH: f32 = 36.0; +const FILTER_HINT_SIZE: f32 = 10.5; +/// The most colors `effect.set {colors}` takes for a gradient map +const MAX_GRADIENT_STOPS: usize = 16; + const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), Color32::from_rgb(0xd0, 0x80, 0x30), @@ -208,48 +215,34 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go -/// to the content when it is the selected target; generators and compare always go to the -/// mask, anchor points to the content. +/// "Add effect" items for `layer`: content when it is the selected target, else the mask fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let t = if content { "content" } else { "mask" }; + let target = if content { "content" } else { "mask" }; ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); + + // Generators and compare masks always go to the mask, anchor points to the content let items = [ (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": t})), - (tr("Add fill"), "effect.add.fill", json!({"target": t})), - (tr("Add levels"), "effect.add.levels", json!({"target": t})), + (tr("Add paint"), "effect.add.paint", json!({"target": target})), + (tr("Add fill"), "effect.add.fill", json!({"target": target})), + (tr("Add levels"), "effect.add.levels", json!({"target": target})), (tr("Add compare mask"), "effect.add.compare", json!({})), + (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), (tr("Add anchor point"), "effect.add.anchor", json!({})), ]; - let run = |app: &mut TextureCraftApp, id: &str, p: &Value| { + for (label, command, params) in items { + let enabled = command != "effect.add.anchor" || !layer.is_group(); + if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + continue; + } + if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(id, with(p, json!({"layer": layer.id.0}))); - }; - for (label, id, p) in items { - let enabled = id != "effect.add.anchor" || !layer.is_group(); - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - run(app, id, &p); - ui.close(); - } + app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + ui.close(); } - // The filter library (material finishes only fill content). - ui.menu_button(tr("Add filter"), |ui| { - let mut group = ""; - for f in FILTERS.iter().filter(|f| content || f.mask) { - if f.group != group { - ui.label(caption(tr(f.group))); - group = f.group; - } - if ui.button(tr(f.label)).clicked() { - run(app, "effect.add.filter", &json!({"target": t, "filter": f.id})); - ui.close(); - } - } - }); } fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { @@ -2058,82 +2051,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye } } -/// The parameters of filter effect `id`. -fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { +/// The filter slot and the parameters of filter effect `id` +fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) { let tk = Tokens::get(ui.ctx()); - let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| { - let mut p = json!({ "effect": id, "merge": merge }); - p[key] = v; - app.run("effect.set", p); + let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| { + let mut params = json!({ "effect": id, "merge": merge }); + params[key] = value; + app.run("effect.set", params); }; - ui.label(caption(tr(f.label()))); - if let Filter::Hsl { hue, .. } = f { - let mut h = hue * 360.0; - if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) { - set(app, "hue", json!(h / 360.0), merge); + crate::filter_slot::show(app, ui, id, filter); + + if let Filter::Hsl { hue, .. } = filter { + let mut degrees = hue * 360.0; + if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) { + set(app, "hue", json!(degrees / 360.0), merge); } } - for (key, label, mut v, lo, hi) in scalar_params(f) { + + for (key, label, mut value, min, max) in scalar_params(filter) { let decimals = if matches!(key, "seed" | "levels") { 0 - } else if hi - lo > 10.0 { + } else if max - min > 10.0 { 1 } else { 2 }; - if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) { - set(app, key, json!(v), merge); + if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) { + set(app, key, json!(value), merge); } } - match f { + + match filter { Filter::ColorBalance { shadows, midtones, highlights } => { for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)] { ui.label(RichText::new(label).strong()); - let mut v = *rgb; + let mut balance = *rgb; let mut edit = None; - for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { - edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2)); + for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) { + edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2)); } if let Some(merge) = edit { - set(app, key, json!(v), merge); + set(app, key, json!(balance), merge); } } } Filter::ReplaceColor { from, to, .. } => { for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] { - let mut v = *rgb; + let mut color = *rgb; ui.horizontal(|ui| { - if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) { - set(app, key, json!(v), false); + if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) { + set(app, key, json!(color), false); } ui.label(label); }); } - ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::GradientMap { colors } => { - let mut c = colors.clone(); + let mut stops = colors.clone(); let mut changed = false; ui.horizontal_wrapped(|ui| { - for (i, col) in c.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0); + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); } }); ui.horizontal(|ui| { - if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - c.push(c.last().copied().unwrap_or([1.0; 3])); + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); changed = true; } - if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - c.pop(); + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); changed = true; } }); if changed { - set(app, "colors", json!(c), false); + set(app, "colors", json!(stops), false); } - ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } Filter::Warp { .. } | Filter::DirectionalBlur { .. } @@ -2144,7 +2140,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter | Filter::Bevel { .. } | Filter::Mosaic { .. } | Filter::Glow { .. } => { - ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim)); + ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); } _ => {} } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs new file mode 100644 index 00000000..7a143612 --- /dev/null +++ b/crates/ui-egui/src/filter_slot.rs @@ -0,0 +1,83 @@ +//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it + +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{Filter, LayerId}; +use texturecraft_engine::filter_lib::{FILTERS, find}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +const SLOT_HEIGHT: f32 = 52.0; +const SLOT_ROUNDING: f32 = 3.0; +const THUMBNAIL_SIZE: f32 = 40.0; +const THUMBNAIL_INSET: f32 = 6.0; +const CAPTION_FONT_SIZE: f32 = 11.0; +const NAME_FONT_SIZE: f32 = 13.0; +/// Gap between the caption's and the name's centers +const LINE_GAP: f32 = 15.0; +const CARET_INSET: f32 = 14.0; +const CARET_FONT_SIZE: f32 = 14.0; + +/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { + let ctx = ui.ctx().clone(); + let on_mask = is_on_mask(app, effect); + let current = find(filter.label()).map(|def| def.id); + let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id)); + let name = tr(filter.label()); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); + paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); + + let popup = ui.make_persistent_id(("filter_picker", effect)); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + + let items = |thumbs: &mut Thumbs| { + FILTERS + .iter() + .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) + .collect() + }; + let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter); + if let Some(id) = picked.filter(|id| Some(*id) != current) { + app.run("effect.set", json!({"effect": effect, "filter": id})); + } +} + +/// Whether filter effect `effect` sits in a mask rather than the layer content +fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { + let project = &app.session.doc.project; + let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner)); + owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) +} + +/// The slot's box: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + + if let Some(texture) = thumbnail { + let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + + let center = rect.center(); + painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); + painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + + let caret_color = if hovered { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..c61f4ce3 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -304,6 +304,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "تعبئة"), ("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"), ("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"), + ("Filter", "مرشح"), ("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"), ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), @@ -677,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "خدوش"), ("Screen", "شاشة (Screen)"), ("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"), + ("Search", "بحث"), ("Search all assets", "البحث في جميع الأصول"), ("Search commands or keys", "البحث في الأوامر أو المفاتيح"), ("Seed", "البذرة العشوائية (Seed)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..18a2c94b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -328,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Füllung"), ("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"), ("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"), + ("Filter", "Filter"), ("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"), ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), @@ -716,6 +717,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Kratzer"), ("Screen", "Negativ multiplizieren"), ("Screenshot of the viewport", "Screenshot des Ansichtsfensters"), + ("Search", "Suchen"), ("Search all assets", "Alle Assets durchsuchen"), ("Search commands or keys", "Befehle oder Tasten suchen"), ("Seed", "Startwert"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..e0c7842b 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Relleno"), ("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"), ("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"), ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), @@ -704,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arañazos"), ("Screen", "Trama"), ("Screenshot of the viewport", "Captura de la ventana gráfica"), + ("Search", "Buscar"), ("Search all assets", "Buscar en todos los recursos"), ("Search commands or keys", "Buscar comandos o teclas"), ("Seed", "Semilla"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..20209ab5 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -331,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Remplissage"), ("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"), ("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"), + ("Filter", "Filtre"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"), ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), @@ -722,6 +723,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Rayures"), ("Screen", "Superposition"), ("Screenshot of the viewport", "Capture de la fenêtre d'affichage"), + ("Search", "Rechercher"), ("Search all assets", "Rechercher dans toutes les ressources"), ("Search commands or keys", "Rechercher des commandes ou des touches"), ("Seed", "Graine"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..8388adcc 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -325,6 +325,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Riempimento"), ("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"), ("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"), ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), @@ -713,6 +714,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Graffi"), ("Screen", "Scolora"), ("Screenshot of the viewport", "Screenshot della viewport"), + ("Search", "Cerca"), ("Search all assets", "Cerca in tutte le risorse"), ("Search commands or keys", "Cerca comandi o tasti"), ("Seed", "Seme"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b20c9d55 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -316,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "塗りつぶし"), ("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"), ("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"), + ("Filter", "フィルター"), ("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"), ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), @@ -695,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "引っかき傷"), ("Screen", "スクリーン"), ("Screenshot of the viewport", "ビューポートのスクリーンショット"), + ("Search", "検索"), ("Search all assets", "すべてのアセットを検索"), ("Search commands or keys", "コマンドまたはキーを検索"), ("Seed", "シード"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..9837b49f 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -313,6 +313,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "채우기"), ("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"), ("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"), + ("Filter", "필터"), ("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"), ("Filters", "필터"), ("Fine noise", "미세 노이즈"), @@ -686,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "스크래치"), ("Screen", "스크린"), ("Screenshot of the viewport", "뷰포트 스크린샷"), + ("Search", "검색"), ("Search all assets", "모든 에셋 검색"), ("Search commands or keys", "명령 또는 키 검색"), ("Seed", "시드"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7badff49 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "Preenchimento"), ("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"), ("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"), + ("Filter", "Filtro"), ("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"), ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), @@ -701,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "Arranhões"), ("Screen", "Tela"), ("Screenshot of the viewport", "Captura de tela da viewport"), + ("Search", "Pesquisar"), ("Search all assets", "Pesquisar em todos os recursos"), ("Search commands or keys", "Pesquisar comandos ou teclas"), ("Seed", "Semente"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..4afec91d 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -286,6 +286,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Fill", "填充"), ("Fill the closed path (lasso)", "填充闭合路径(套索)"), ("Fill the path (close it first)", "填充路径(请先闭合)"), + ("Filter", "滤镜"), ("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"), ("Filters", "滤镜"), ("Fine noise", "细噪波"), @@ -647,6 +648,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Scratches", "划痕"), ("Screen", "滤色"), ("Screenshot of the viewport", "视口截图"), + ("Search", "搜索"), ("Search all assets", "搜索所有资产"), ("Search commands or keys", "搜索命令或按键"), ("Seed", "随机种子"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..4db0acd7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod control; pub mod dock; pub mod docking; pub mod export_templates; +mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; @@ -26,6 +27,8 @@ mod preview_worker; pub mod profile; pub mod properties_popup; pub mod render_mode; +mod resource_picker; +mod resource_picker_item; pub mod shelf; pub mod shelf_preview; pub mod state; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..3f645eeb 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -305,6 +305,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str { } } +/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; @@ -319,6 +320,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } + // Escape closes an open popup first, before the Properties popup or the stroke + let popup_open = egui::Popup::is_any_open(ctx); + let active_shortcuts = crate::keymap::active(&app.ui.keymap); let mut commands_to_invoke: Vec<&str> = Vec::new(); ctx.input_mut(|input| { @@ -337,9 +341,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); app.session.tool.path.editing = None; diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs new file mode 100644 index 00000000..5b119c2f --- /dev/null +++ b/crates/ui-egui/src/resource_picker.rs @@ -0,0 +1,126 @@ +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name + +use egui::{Id, Response, Stroke, Ui}; + +use crate::i18n::tr; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shelf; +use crate::shelf_preview::ShelfPreview; +use crate::theme::Tokens; +use crate::thumbs::Thumbs; + +/// Four shelf tiles and the scrollbar +const PICKER_WIDTH: f32 = 320.0; +/// The grid's height, fixed so the popup keeps its place while searching +const PICKER_HEIGHT: f32 = 340.0; +const CURRENT_OUTLINE_WIDTH: f32 = 1.5; +const TILE_ROUNDING: f32 = 3.0; + +/// Opens the picker `popup_id` with an empty, focused search field, or closes it +pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { + if egui::Popup::is_id_open(ctx, popup_id) { + egui::Popup::close_id(ctx, popup_id); + return; + } + + egui::Popup::open_id(ctx, popup_id); + ctx.data_mut(|data| { + data.insert_temp(search_id(popup_id), String::new()); + data.insert_temp(focus_id(popup_id), true); + }); +} + +/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) +pub(crate) fn show( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + current: Option<&str>, + items: impl FnOnce(&mut Thumbs) -> Vec, + preview: impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let ctx = slot.ctx.clone(); + if !egui::Popup::is_id_open(&ctx, popup_id) { + return None; + } + + let items = items(thumbs); + let mut picked = None; + egui::Popup::from_response(slot) + .id(popup_id) + .open_memory(None) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::BOTTOM_END) + .width(PICKER_WIDTH) + .show(|ui| { + ui.set_width(PICKER_WIDTH); + let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let query = search_field(ui, popup_id, just_opened); + egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { + // A search that leaves few tiles must not shrink the popup, or egui moves it + ui.set_min_height(PICKER_HEIGHT); + picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + }); + }); + + if picked.is_some() { + egui::Popup::close_id(&ctx, popup_id); + } + picked +} + +/// The search field, focused the frame the picker opens; returns the lowercase query +fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { + let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); + let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY)); + if just_opened { + field.request_focus(); + } + + let query = search.trim().to_lowercase(); + ui.data_mut(|data| data.insert_temp(search_id(popup_id), search)); + query +} + +/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked +fn grid( + ui: &mut Ui, + thumbs: &mut Thumbs, + items: &[ResourcePickerItem], + query: &str, + current: Option<&str>, + reveal_current: bool, + preview: &impl Fn(&'static str) -> ShelfPreview, +) -> Option<&'static str> { + let tk = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); + let mut picked = None; + for group in shelf::categories(&shown, |item| item.group) { + shelf::header(ui, group); + shelf::tiles(ui, |ui| { + for item in shown.iter().filter(|item| item.group == group) { + let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); + if current == Some(item.id) { + if reveal_current { + response.scroll_to_me(Some(egui::Align::Center)); + } + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(item.id); + } + } + }); + } + picked +} + +/// Where the picker keeps its search text +fn search_id(popup_id: Id) -> Id { + popup_id.with("search") +} + +/// Set while the picker waits for its first frame open +fn focus_id(popup_id: Id) -> Id { + popup_id.with("focus") +} diff --git a/crates/ui-egui/src/resource_picker_item.rs b/crates/ui-egui/src/resource_picker_item.rs new file mode 100644 index 00000000..5b9e8071 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_item.rs @@ -0,0 +1,9 @@ +//! One choice offered by a resource picker + +/// A resource the picker offers: its id, translated label and group, and its thumbnail +pub(crate) struct ResourcePickerItem { + pub id: &'static str, + pub label: &'static str, + pub group: &'static str, + pub thumbnail: Option, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..55ef400f 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -266,7 +266,7 @@ fn drag_preview(ctx: &egui::Context) { p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong); } -fn matches(filter: &str, texts: &[&str]) -> bool { +pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool { filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter)) } @@ -275,13 +275,13 @@ fn title(ui: &mut Ui, text: &str) { ui.label(RichText::new(text).strong().color(tk.text_strong)); } -fn header(ui: &mut Ui, text: &str) { +pub(crate) fn header(ui: &mut Ui, text: &str) { let tk = Tokens::get(ui.ctx()); ui.add_space(2.0); ui.label(RichText::new(text).size(11.0).color(tk.text_dim)); } -fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { +pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(4.0, 4.0); body(ui); @@ -290,7 +290,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { } /// The distinct categories of `items`, in order of first appearance. -fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { +pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { let mut out: Vec<&'static str> = Vec::new(); for c in items.iter().map(category) { if !out.contains(&c) { @@ -586,7 +586,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: } /// Asset tile with optional dragging and a larger hover preview -fn tile( +pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, tex: Option<&egui::TextureHandle>, diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs new file mode 100644 index 00000000..31daef69 --- /dev/null +++ b/crates/ui-egui/tests/filter_picker.rs @@ -0,0 +1,81 @@ +//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, Filter, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot +fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let effect = LayerId(effect["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The kind of effect `effect` now +fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind { + harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone() +} + +/// Clicks the Invert slot, which opens its picker +fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) { + harness.get_by_role_and_label(Role::ComboBox, "Invert").click(); + harness.run_steps(3); + assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker"); +} + +#[test] +fn picking_from_the_slot_swaps_the_filter() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // The picker's search field has the focus as it opens + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match"); + + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker"); +} + +#[test] +fn escape_closes_the_picker_without_changes() { + let (mut harness, effect) = app_with_invert(); + open_picker(&mut harness); + + // Without the search field's focus, the painting shortcuts see Escape first + harness.ctx.memory_mut(|memory| memory.stop_text_input()); + harness.run_steps(2); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); +} + +#[test] +fn add_filter_adds_a_filter_and_selects_it() { + let (mut harness, _) = app_with_invert(); + harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + harness.run_steps(3); + + harness.get_by_label("Add filter").click(); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); +} From c827d1b910c0a8eb625d396289989e148244c30d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:48:32 +0000 Subject: [PATCH 078/275] Drop a shelf image on the texture set under the cursor, as a channel or a mask An image dragged over the 3D view highlights the texture set under the cursor, as materials do. A drop opens a menu at the drop point: Mask, then that set's channels. A pick selects the set and places the decal there with the image in the picked channel, or as the gray mask of a new fill layer. A click elsewhere places nothing; the background opens no menu. layer.add.decal takes channel (a channel id, default baseColor, or "mask") and adds the decal to the set under the point, selecting it, as one undo step. layer.decal.set takes effect to edit a mask decal, so the view's frame and handles work on it too, and a new image stays in the channel the decal was placed in. One-value channels and masks read an image's gray instead of its red. --- crates/compose/src/eval.rs | 49 ++++--- crates/engine/src/decal_cmds.rs | 209 +++++++++++++++++++--------- crates/engine/src/set_cmds.rs | 12 +- crates/engine/tests/painter_gaps.rs | 81 +++++++++++ crates/ui-egui/src/decal_drop.rs | 79 +++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 40 ++++-- crates/ui-egui/src/viewport.rs | 112 +++++++++------ crates/ui-egui/tests/shelf_drop.rs | 71 +++++++++- 18 files changed, 518 insertions(+), 145 deletions(-) create mode 100644 crates/ui-egui/src/decal_drop.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..308d11c2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1129,39 +1129,42 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } - fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] { - match s { - Source::Uniform(v) => *v, + fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + match source { + Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { - let (c, proj, _) = self.projected(proj); - let t = procedural(pattern, proj, &c); - mix3(*low, *high, t) + let (coords, projection, _) = self.projected(projection); + let amount = procedural(pattern, projection, &coords); + mix3(*low, *high, amount) } Source::Image { name, normal_format } => { - let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; - let (c, proj, _) = self.projected(proj); - let mut acc = [0.0f32; 4]; - for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) { - let s = img.sample(uv.x, uv.y); - for k in 0..4 { - acc[k] += s[k] * w; + let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; + + let (coords, projection, _) = self.projected(projection); + let mut sum = [0.0f32; 4]; + for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + *total += value * weight; } } + + let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], - ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], - ChannelKind::Scalar => [acc[0]; 3], - ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], + ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default. - let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); - let v = v.unwrap_or_else(|| channel.default_value()); + // An anchor not evaluated yet (above this layer, hidden) reads the channel default + let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); + let value = anchored.unwrap_or_else(|| channel.default_value()); let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(v); 3] } else { v } + if gray { [lum(value); 3] } else { value } } } } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index e937b6f5..f3ec8b28 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -2,12 +2,12 @@ //! (a decal fill with a planar projection), as a fill layer with a decal projection. use serde_json::{Value, json}; -use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source}; +use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source}; use texturecraft_geom::glam::{Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p}; use crate::tool_cmds::viewport_of; -use crate::{Result, Session, cmd}; +use crate::{Result, Session, StackTarget, cmd}; pub fn specs() -> Vec { vec![ @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -42,43 +42,50 @@ fn vec3(p: &Value, key: &str) -> Option { } } -/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view -/// center by default) or `position` + `normal`. None when `optional` and neither is given. -fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { - if let Some(pos) = vec3(p, "position") { - let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; - return Ok(Some((pos, n))); +/// Where a decal goes and the texture set it lands on, from `x`/`y` (viewport pixels, the view center by default) or `position` + `normal` (on the active set); None when `optional` and neither is given +fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { + if let Some(position) = vec3(p, "position") { + let normal = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; + return Ok(Some((position, normal, s.ts()))); } - let vp = viewport_of(s, p); + + let viewport = viewport_of(s, p); let at = match (f32p(p, "x"), f32p(p, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), _ if optional => return Ok(None), - _ => vp * 0.5, + _ => viewport * 0.5, }; - let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; - if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) { - return Err(bad(cmd, "that surface belongs to another texture set")); - } - Ok(Some((hit.pos, hit.nrm))) + let hit = s.pick(at, viewport).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; + let ts = s.texture_set_of_material(hit.material).ok_or_else(|| bad(cmd, "that surface has no texture set"))?; + Ok(Some((hit.pos, hit.nrm, ts))) } +/// A new decal's height, relative to the mesh diagonal +const DEFAULT_HEIGHT: f32 = 0.25; + +/// The smallest decal side or depth, relative to the mesh diagonal +const MIN_SIZE: f32 = 1e-4; + +/// The largest decal side or depth, relative to the mesh diagonal +const MAX_SIZE: f32 = 10.0; + /// The mesh's diagonal (decal sizes are relative to it). fn mesh_size(s: &Session) -> f32 { let (lo, hi) = s.mesh.bounds(); (hi - lo).length().max(1e-3) } -/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`). -fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { - let v = p.get("size")?; - let size = match v.as_array() { - Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32], +/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits +fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = p.get("size")?; + let size = match value.as_array() { + Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { - let h = v.as_f64()? as f32; - [h * aspect, h] + let height = value.as_f64()? as f32; + [height * aspect, height] } }; - size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) + size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE))) } /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on @@ -96,11 +103,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { fn add(s: &mut Session, p: &Value) -> Result { let cmd = "layer.add.decal"; let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; - let aspect = img.width as f32 / img.height.max(1) as f32; - let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; - let diag = mesh_size(s); - let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]); + let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; + let aspect = resource.width as f32 / resource.height.max(1) as f32; + let (center, normal, ts) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; + + // None: the image masks a new fill layer + let target = match strp(p, "channel") { + Some("mask") => None, + _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + }; + let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + if let Some(channel) = target + && !set_channels.contains(&channel) + { + return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + } + + let mesh_diagonal = mesh_size(s); + let default_height = mesh_diagonal * DEFAULT_HEIGHT; + let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); let decal = Decal { center: center.to_array(), normal: normal.to_array(), @@ -108,68 +129,130 @@ fn add(s: &mut Session, p: &Value) -> Result { size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)), + // By default it reaches half its larger side into the surface + depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), }; - let ts = s.ts(); - let base = - strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string()); + + // A decal dropped on another texture set goes there and selects it, as a dropped material does + if ts != s.ts() { + crate::set_cmds::select_set(s, ts); + } + + let base = strp(p, "name") + .map(str::to_string) + .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); let name = s.doc.project.next_layer_name(ts, &base); - let id = s.edit("Add decal", |s| { + let (id, mask_effect) = s.edit("Add decal", |s| { let id = s.doc.project.alloc_id(); + let Some(channel) = target else { + let effect_id = s.doc.project.alloc_id(); + let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + layer.mask = Some(mask); + crate::layer_cmds::insert_selected(s, layer)?; + s.target = StackTarget::Effect(effect_id); + return Ok((id, Some(effect_id))); + }; + let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor])) + fill.sources.insert(channel, Source::image(image.clone())); + crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + Ok((id, None)) })?; - Ok(json!({ "layer": id.0, "decal": decal })) + Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`. -fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result { +/// The decal of fill layer `id`, or of mask fill effect `effect` when given +fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { + if let Some(effect) = effect { + return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), + _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), + }; + } + match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d), + LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), } } fn set(s: &mut Session, p: &Value) -> Result { let cmd = "layer.decal.set"; - let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?; - let mut d = decal_of(s, cmd, id)?; - let diag = mesh_size(s); - if let Some((center, normal)) = placement(s, cmd, p, true)? { - (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); + let effect = u64p(p, "effect").map(LayerId); + let id = match effect { + Some(effect) => s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?, + None => s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|layer| layer.id).ok_or_else(|| bad(cmd, "no layer"))?, + }; + let mut decal = decal_of(s, cmd, id, effect)?; + let mesh_diagonal = mesh_size(s); + if let Some((center, normal, ts)) = placement(s, cmd, p, true)? { + // A decal layer stays in its texture set + if ts != s.ts() { + return Err(bad(cmd, "that surface belongs to another texture set")); + } + + (decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); } if p.get("up").is_some() { - d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); + decal.up = decal_up(s, cmd, p, Vec3::from(decal.normal))?.to_array(); } - if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { - d.size = size; + if let Some(size) = size_param(p, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) { + decal.size = size; } - if let Some(r) = f32p(p, "rotation") { - d.rotation = r.rem_euclid(360.0); + if let Some(rotation) = f32p(p, "rotation") { + decal.rotation = rotation.rem_euclid(360.0); } - if let Some(o) = p.get("offset").and_then(Value::as_array) { - let v: Vec = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; - d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)]; + if let Some(offset) = p.get("offset").and_then(Value::as_array) { + let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); + let [right, up] = values.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; + + decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; } - if let Some(v) = f32p(p, "depth") { - d.depth = v.clamp(diag * 1e-4, diag * 10.0); + if let Some(depth) = f32p(p, "depth") { + decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); } + let image = strp(p, "image").map(str::to_string); if let Some(name) = &image && !s.doc.resources.contains_key(name) { return Err(bad(cmd, format!("no image resource `{name}`"))); } + s.edit("Edit decal", |s| { - if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind { - f.projection = Projection::Decal(d); - if let Some(name) = image { - f.sources.insert(Channel::BaseColor, Source::image(name)); + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection }) = s.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *projection = Projection::Decal(decal); + if let Some(image) = image { + *source = Source::image(image); + } + } + } else if let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id)?.kind { + fill.projection = Projection::Decal(decal); + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} } } Ok(()) })?; - Ok(json!({ "layer": id.0, "decal": d })) + Ok(json!({ "layer": id.0, "decal": decal })) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..3f394e23 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -75,12 +75,20 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let ts = u64p(p, "ts") + .map(|index| index as usize) + .filter(|index| *index < s.set_count()) + .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + select_set(s, ts); + Ok(json!({ "ts": ts })) +} + +/// Make texture set `ts` the active one, on its content stack +pub(crate) fn select_set(s: &mut Session, ts: usize) { s.cancel_stroke(); s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); - Ok(json!({ "ts": ts })) } fn resolution(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 814ea08b..c150de79 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -34,6 +34,9 @@ fn red(v: [f32; 3]) -> bool { v[0] > 0.85 && v[1] < 0.15 } +/// Distance between the view points searched for a texture set +const SEARCH_STEP: f32 = 10.0; + 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(); @@ -345,6 +348,84 @@ fn decal_drags_merge_into_one_undo_step() { assert_eq!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["layers"], start); } +/// A decal dropped on another texture set lands there and selects it, in one undo step +#[test] +fn a_decal_on_another_texture_set_selects_that_set() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.update(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let selected = s.ts(); + let (columns, rows) = ((s.viewport.x / SEARCH_STEP) as u32, (s.viewport.y / SEARCH_STEP) as u32); + let other_set_pixel = (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&pixel| s.texture_set_at(pixel, s.viewport).is_some_and(|ts| ts != selected)) + .expect("the material ball shows both of its texture sets"); + let other = s.texture_set_at(other_set_pixel, s.viewport).unwrap(); + let steps = s.history_labels().len(); + + let drop = json!({"image": name, "x": other_set_pixel.x, "y": other_set_pixel.y, "viewport": [s.viewport.x, s.viewport.y]}); + let layer = id(execute(&mut s, "layer.add.decal", &drop).unwrap(), "layer"); + + assert_eq!(s.ts(), other, "the set under the point is selected"); + assert_eq!(s.doc.project.locate(layer).map(|(ts, _, _)| ts), Some(other), "the decal is in that set"); + assert_eq!(s.selected_layer(), Some(layer)); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.locate(layer).is_none(), "one undo takes the decal away"); + + let background = json!({"image": name, "x": 2, "y": 2, "viewport": [s.viewport.x, s.viewport.y]}); + assert!(s.texture_set_at(Vec2::new(2.0, 2.0), s.viewport).is_none()); + assert!(execute(&mut s, "layer.add.decal", &background).is_err(), "the background still takes nothing"); +} + +/// A decal's image goes in the channel asked for, or masks a new fill layer +#[test] +fn a_decal_image_fills_a_chosen_channel_or_a_mask() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); + + let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); + assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); + + let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); + let masked = id(added.clone(), "layer"); + let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); + assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); + + let effect = &added["maskEffect"]; + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); + assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); +} + +/// A decal's new image stays in the channel the decal was placed in, read as gray there +#[test] +fn a_channel_decal_reads_its_image_as_gray_and_keeps_its_channel() { + let mut s = session(); + let white = s.import_resource_bytes("white.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let green = s.import_resource_bytes("green.png", png(8, 8, |_, _| [0, 255, 0, 255])).unwrap(); + let place = json!({"image": white, "channel": "roughness", "x": 200, "y": 200, "size": 0.5}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "image": green})).unwrap(); + + assert_eq!(s.doc.project.layer(layer).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + let roughness = at(&mut s, Channel::Roughness, 200.0, 200.0)[0]; + assert!((roughness - texturecraft_engine::core::lum([0.0, 1.0, 0.0])).abs() < 0.02, "green reads as its gray, not its red: {roughness}"); +} + /// The Geometry mask tool: a click toggles the selected layer on the part under it. #[test] fn geometry_mask_tool_toggles_the_clicked_part() { diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs new file mode 100644 index 00000000..0bb95f65 --- /dev/null +++ b/crates/ui-egui/src/decal_drop.rs @@ -0,0 +1,79 @@ +//! A shelf image dropped on the 3D view waits for a menu pick at the drop point: a mask, or a channel of the texture set under it + +use egui::{Id, Pos2, Ui, Vec2}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// What the menu offers besides the texture set's channels: a new fill layer masked by the image +const MASK_CHOICE: &str = "mask"; + +/// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked +#[derive(Clone)] +pub struct DecalDrop { + /// The image resource + pub image: String, + /// The texture set under the drop point + pub texture_set: usize, + /// The drop point in view pixels + pub view_position: Vec2, + /// The 3D view's size in pixels + pub view_size: Vec2, + /// The drop point on screen, where the menu opens + pub screen_position: Pos2, +} + +impl DecalDrop { + fn menu_id() -> Id { + Id::unique("decal_drop_menu") + } + + /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits + pub fn open(self, ui: &Ui) { + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); + } + + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { + let id = Self::menu_id(); + let Some(drop) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; + + let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); + let mut picked = None; + let shown = egui::Popup::new(id, ui.ctx().clone(), egui::PopupAnchor::Position(drop.screen_position), response.layer_id) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + if ui.button(tr("Mask")).clicked() { + picked = Some(MASK_CHOICE); + } + ui.separator(); + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } + } + }); + + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + ui.ctx().data_mut(|data| data.remove::(id)); + } + + let Some(channel) = picked else { return }; + + app.run( + "layer.add.decal", + json!({ + "image": drop.image, + "channel": channel, + "x": drop.view_position.x, + "y": drop.view_position.y, + "viewport": [drop.view_size.x, drop.view_size.y], + }), + ); + } +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..4c3fb853 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -457,6 +457,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "أرجواني / أخضر"), ("Main shader", "المظلل الرئيسي"), ("Marble veins", "عروق الرخام"), + ("Mask", "قناع"), ("Mask Editor: Edge wear", "محرر الأقنعة: تآكل الحواف"), ("Mask value (gray)", "قيمة القناع (رمادي)"), ("Mask with height", "قناع بالارتفاع"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..dda80253 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -484,6 +484,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / Grün"), ("Main shader", "Haupt-Shader"), ("Marble veins", "Marmoradern"), + ("Mask", "Maske"), ("Mask Editor: Edge wear", "Masken-Editor: Kantenabnutzung"), ("Mask value (gray)", "Maskenwert (Grau)"), ("Mask with height", "Mit Höhe maskieren"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..d5e1edcd 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -475,6 +475,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Sombreador principal"), ("Marble veins", "Vetas de mármol"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscaras: desgaste de bordes"), ("Mask value (gray)", "Valor de máscara (gris)"), ("Mask with height", "Enmascarar con la altura"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..39532da0 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -490,6 +490,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / vert"), ("Main shader", "Shader principal"), ("Marble veins", "Veines de marbre"), + ("Mask", "Masque"), ("Mask Editor: Edge wear", "Éditeur de masque : usure des arêtes"), ("Mask value (gray)", "Valeur du masque (gris)"), ("Mask with height", "Masquer avec la hauteur"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..bfb32ec8 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -481,6 +481,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principale"), ("Marble veins", "Venature marmo"), + ("Mask", "Maschera"), ("Mask Editor: Edge wear", "Editor maschera: Usura bordi"), ("Mask value (gray)", "Valore maschera (grigio)"), ("Mask with height", "Maschera con altezza"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d053cd61 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -469,6 +469,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "マゼンタ / グリーン"), ("Main shader", "メインシェーダー"), ("Marble veins", "大理石の筋"), + ("Mask", "マスク"), ("Mask Editor: Edge wear", "マスクエディター: エッジの摩耗"), ("Mask value (gray)", "マスク値 (グレー)"), ("Mask with height", "ハイトでマスク"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..f64e9805 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -463,6 +463,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "마젠타 / 녹색"), ("Main shader", "메인 셰이더"), ("Marble veins", "대리석 무늬"), + ("Mask", "마스크"), ("Mask Editor: Edge wear", "마스크 에디터: 모서리 마모"), ("Mask value (gray)", "마스크 값 (회색)"), ("Mask with height", "높이로 마스크"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..5b95ce82 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -472,6 +472,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principal"), ("Marble veins", "Veios de mármore"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscara: Desgaste de bordas"), ("Mask value (gray)", "Valor da máscara (cinza)"), ("Mask with height", "Mascarar com altura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..3b616067 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -430,6 +430,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "洋红 / 绿色"), ("Main shader", "主着色器"), ("Marble veins", "大理石纹"), + ("Mask", "遮罩"), ("Mask Editor: Edge wear", "遮罩编辑器:边缘磨损"), ("Mask value (gray)", "遮罩值(灰度)"), ("Mask with height", "用高度遮罩"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..50f886e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -9,6 +9,7 @@ pub mod bake_mode; pub mod control; +mod decal_drop; pub mod dock; pub mod docking; pub mod export_templates; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..62fd8592 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -2,7 +2,7 @@ //! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. //! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas //! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there. +//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; @@ -20,6 +20,7 @@ use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; @@ -88,6 +89,11 @@ impl Asset { pub fn is_material(&self) -> bool { matches!(self, Asset::Material(_) | Asset::Library(_)) } + + /// Assets a 3D view drop puts on the texture set under the pointer + pub fn goes_onto_set(&self) -> bool { + self.is_material() || matches!(self, Asset::Texture(_)) + } } /// The drag-and-drop payload of a shelf tile. @@ -143,17 +149,17 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (decals where they drop, on that set) View3d, } -/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to -pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { +/// The texture set under the pointer while a shelf material or image is dragged over the 3D view `response`: the set a drop there goes to +pub fn drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { if app.ui.mode != crate::state::Mode::Painting { return None; } - response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + response.dnd_hover_payload::().filter(|drag| drag.asset.goes_onto_set())?; set_under_pointer(app, ui, response) } @@ -163,12 +169,16 @@ fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) } -/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material or image goes to the texture set under the pointer, highlighted by the view itself ([`drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; } + if zone == DropZone::View3d { + DecalDrop::show_menu(app, ui, response); + } + let tokens = Tokens::get(ui.ctx()); let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, @@ -176,7 +186,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } @@ -185,11 +195,19 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); - } // The background takes nothing + (Asset::Texture(name), Some(position)) => { + let Some(texture_set) = set_under_pointer(app, ui, response) else { return }; + + let drop = DecalDrop { + image: name.clone(), + texture_set, + view_position: position - response.rect.min, + view_size: response.rect.size(), + screen_position: position, + }; + drop.open(ui); + } (asset, _) if onto_set(asset) => { let Some(ts) = set_under_pointer(app, ui, response) else { return }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..1855438a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -223,9 +223,9 @@ fn shade(app: &TextureCraftApp) -> Shade { } } -/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +/// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { - let set = crate::shelf::material_drop_set(app, ui, response)?; + let set = crate::shelf::drop_set(app, ui, response)?; let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) @@ -622,7 +622,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + // Shelf drops: a material goes above the selection of the set under the pointer, an image opens the decal menu there, an alpha goes on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began @@ -691,16 +691,18 @@ impl DecalGrab { } } -/// A decal handle being dragged (kept in egui's memory between frames). +/// A decal handle being dragged (kept in egui's memory between frames) #[derive(Clone, Copy, Debug)] struct DecalDrag { layer: texturecraft_engine::core::LayerId, + /// The mask fill effect holding the decal, when it was placed as a mask + effect: Option, grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then. + /// Where the drag started, the decal's center on screen and the decal then from: Pos2, center: Pos2, start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it. + /// The drag made its undo step: later updates merge into it stepped: bool, } @@ -711,34 +713,51 @@ fn decal_drag_id() -> egui::Id { /// Screen distance from the top edge to the rotation handle (points). const DECAL_KNOB: f32 = 24.0; -/// The selected decal layer (its content, not its mask) as the 3D view shows it. +/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it struct DecalFrame { layer: texturecraft_engine::core::LayerId, + /// The selected mask fill effect holding the decal, when it was placed as a mask + effect: Option, decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left. + /// Top left, top right, bottom right, bottom left corners: [Pos2; 4], center: Pos2, - /// The middle of the top edge and the rotation handle above it. + /// The middle of the top edge and the rotation handle above it top: Pos2, knob: Pos2, } impl DecalFrame { fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - use texturecraft_engine::core::{Fill, LayerKind, Projection}; - if app.ui.mode != crate::state::Mode::Painting || app.session.target != texturecraft_engine::StackTarget::Content { + use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; + if app.ui.mode != crate::state::Mode::Painting { return None; } - let p = &app.session.doc.project; - let layer = app.session.selected_layer().and_then(|id| p.content_layer(id))?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - let [a, b, c, d] = decal_corners(decal)?.map(|q| project(app, rect, q)); - let corners = [a?, b?, c?, d?]; + + let layers = &app.session.doc.project; + let (layer, effect, decal) = match app.session.target { + StackTarget::Content => { + let layer = app.session.selected_layer().and_then(|id| layers.content_layer(id))?; + let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; + + (layer.id, None, decal) + } + StackTarget::Effect(effect) => { + let (owner, mask_effect) = layers.effect(effect)?; + let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), decal) + } + StackTarget::Mask => return None, + }; + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); + let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; let center = project(app, rect, decal_axes(decal)?.0)?; let top = corners[0].lerp(corners[1], 0.5); let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer: layer.id, decal: *decal, corners, center, top, knob }) + Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) } /// The handle under screen point `p`. @@ -759,51 +778,56 @@ impl DecalFrame { } } -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates -/// live). Returns whether a decal drag owns the pointer. +/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { let ctx = ui.ctx(); let frame = DecalFrame::of(app, rect); - let mut drag = ctx.data(|d| d.get_temp::(decal_drag_id())).filter(|d| frame.as_ref().is_some_and(|f| f.layer == d.layer)); + let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); + let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); if resp.drag_started_by(PointerButton::Primary) - && let (Some(f), Some(from)) = (&frame, ctx.input(|i| i.pointer.press_origin())) - && let Some(grab) = f.grab(from) + && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = frame.grab(from) { - drag = Some(DecalDrag { layer: f.layer, grab, from, center: f.center, start: f.decal, stepped: false }); + drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); } - let Some(mut d) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|m| m.remove::(decal_drag_id())); - if let (Some(f), Some(h)) = (&frame, resp.hover_pos()) - && let Some(g) = f.grab(h) + + let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { + ctx.data_mut(|data| data.remove::(decal_drag_id())); + if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) + && let Some(grab) = frame.grab(hover) { - ctx.set_cursor_icon(g.cursor(false)); + ctx.set_cursor_icon(grab.cursor(false)); } return false; }; - ctx.set_cursor_icon(d.grab.cursor(true)); - if let Some(p) = resp.interact_pointer_pos().filter(|_| ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match d.grab { + + ctx.set_cursor_icon(drag.grab.cursor(true)); + if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { + let mut params = match drag.grab { DecalGrab::Move => { - let q = d.center + (p - d.from) - rect.left_top(); - let vp = app.session.viewport; - json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}) + let target = drag.center + (pointer - drag.from) - rect.left_top(); + let viewport = app.session.viewport; + json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) } DecalGrab::Scale => { - let k = (p - d.center).length() / (d.from - d.center).length().max(1.0); - json!({"size": [d.start.size[0] * k, d.start.size[1] * k]}) + let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); + json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) } DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up. - let angle = |v: egui::Vec2| (-v.y).atan2(v.x).to_degrees(); - json!({"rotation": d.start.rotation + angle(p - d.center) - angle(d.from - d.center)}) + // Screen y points down: counter-clockwise angles turn the decal's right toward its up + let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); + json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) } }; - params["layer"] = json!(d.layer.0); - params["merge"] = json!(d.stepped); - // Off the mesh while moving: the decal waits where it is. - d.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); + params["layer"] = json!(drag.layer.0); + if let Some(effect) = drag.effect { + params["effect"] = json!(effect.0); + } + params["merge"] = json!(drag.stepped); + // Off the mesh while moving: the decal waits where it is + drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); } - ctx.data_mut(|m| m.insert_temp(decal_drag_id(), d)); + ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); true } diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 5b35cc06..7bb94a04 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -1,7 +1,9 @@ -//! A shelf material dropped on the 3D view goes to the texture set under the pointer +//! A shelf material or image dropped on the 3D view goes to the texture set under the pointer; an image first asks what it becomes use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; @@ -9,6 +11,9 @@ use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; +/// How far from the drop point the drop menu's items can be +const MENU_REACH: f32 = 60.0; + /// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -33,7 +38,12 @@ fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos /// Drop a built-in shelf material at `position`, as a drag from the shelf ends there fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + drop_asset(harness, Asset::Material("iron_rusted"), position); +} + +/// Drop shelf `asset` at `position`, as a drag from the shelf ends there +fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() }); harness.hover_at(position); harness.run_steps(2); @@ -70,3 +80,60 @@ fn a_material_dropped_on_the_background_changes_nothing() { assert_eq!(stack_sizes(&harness), stacks); assert_eq!(harness.state().session.history_labels().len(), history); } + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); + harness.run_steps(2); + + let position = point_over(&harness, position_over); + drop_asset(&mut harness, Asset::Texture(name), position); + // The menu's first frame only measures it + harness.run_steps(2); + (harness, position) +} + +#[test] +fn an_image_dropped_on_another_set_asks_for_a_channel_then_goes_to_that_set() { + let (mut harness, position) = drop_image(Some(1)); + let before = stack_sizes(&harness); + + // The menu item nearest the drop point (Properties may show the same name) + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + + let app = harness.state(); + assert_eq!(app.session.ts(), 1, "the set under the drop point is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1]); + let layer = app.session.selected_layer().and_then(|id| app.session.doc.project.layer(id).ok()).unwrap(); + assert_eq!(layer.channels.keys().copied().collect::>(), [Channel::Roughness], "the image fills the picked channel"); +} + +/// Whether the drop menu is open at `position` (its Mask item near there) +fn menu_open(harness: &Harness<'_, TextureCraftApp>, position: Pos2) -> bool { + harness.query_all_by_label("Mask").any(|node| node.rect().center().distance(position) < MENU_REACH) +} + +#[test] +fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { + let (mut harness, position) = drop_image(Some(1)); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + assert!(menu_open(&harness, position)); + + // A click elsewhere closes the menu + let corner = harness.state().viewport_rect.min + egui::vec2(SEARCH_STEP, SEARCH_STEP); + harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!menu_open(&harness, position)); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); + + let (harness, position) = drop_image(None); + assert!(!menu_open(&harness, position), "the background opens no menu"); +} From a1d010ccb2f131c867f4551f1d12f1fa47911052 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 08:20:33 +0000 Subject: [PATCH 079/275] Curvature generators: mode and detail sizes Curvature and edge wear generators read the baked curvature map one texel at a time, so they only marked the sharpest edges. They now take a mode (edges, cavities, both, raw) and seven detail size weights: the map itself and the map blurred at 1 to 32 texels at 2K, padded past the UV islands and built once per map and layout. Each size's edges and cavities combine like a screen blend. New curvature and edge wear generators use detail sizes. Generators saved without them, and smart masks, read the map exactly as before. --- crates/compose/src/curvature_size_level.rs | 42 ++++ crates/compose/src/curvature_sizes.rs | 133 +++++++++++++ crates/compose/src/eval.rs | 215 +++++++++++++++------ crates/compose/src/lib.rs | 2 + crates/core/src/layer.rs | 31 ++- crates/core/src/layer/curvature_detail.rs | 22 +++ crates/core/src/layer/curvature_mode.rs | 34 ++++ crates/core/src/lib.rs | 5 +- crates/engine/src/inspect.rs | 59 +++--- crates/engine/src/mask_cmds.rs | 140 ++++++++------ crates/engine/src/smart_masks.rs | 6 +- crates/engine/tests/session.rs | 20 ++ crates/ui-egui/src/dock.rs | 185 +++++++++++------- crates/ui-egui/src/i18n/ar.rs | 9 + crates/ui-egui/src/i18n/de.rs | 9 + crates/ui-egui/src/i18n/es.rs | 9 + crates/ui-egui/src/i18n/fr.rs | 9 + crates/ui-egui/src/i18n/it.rs | 9 + crates/ui-egui/src/i18n/ja.rs | 9 + crates/ui-egui/src/i18n/ko.rs | 9 + crates/ui-egui/src/i18n/pt_br.rs | 9 + crates/ui-egui/src/i18n/zh_hans.rs | 6 + 22 files changed, 753 insertions(+), 219 deletions(-) create mode 100644 crates/compose/src/curvature_size_level.rs create mode 100644 crates/compose/src/curvature_sizes.rs create mode 100644 crates/core/src/layer/curvature_detail.rs create mode 100644 crates/core/src/layer/curvature_mode.rs diff --git a/crates/compose/src/curvature_size_level.rs b/crates/compose/src/curvature_size_level.rs new file mode 100644 index 00000000..aa09d747 --- /dev/null +++ b/crates/compose/src/curvature_size_level.rs @@ -0,0 +1,42 @@ +/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers. +pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0; + +/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map. +pub struct CurvatureSizeLevel { + pub step: u32, + pub width: u32, + pub height: u32, + pub deviation: Vec, +} + +impl CurvatureSizeLevel { + /// The deviation at map texel `(x, y)`, bilinear between the stored texels. + pub fn sample(&self, x: u32, y: u32) -> f32 { + if self.width == 0 || self.height == 0 { + return 0.0; + } + + let to_level = |texel: u32| (texel as f32 + 0.5) / self.step as f32 - 0.5; + let (level_x, level_y) = (to_level(x).max(0.0), to_level(y).max(0.0)); + let (x0, y0) = ((level_x.floor() as u32).min(self.width - 1), (level_y.floor() as u32).min(self.height - 1)); + let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1)); + let (blend_x, blend_y) = (level_x - x0 as f32, level_y - y0 as f32); + let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE); + let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x; + let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x; + top + (bottom - top) * blend_y + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn samples_blend_the_stored_texels() { + let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] }; + assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1"); + assert!((level.sample(3, 0) - 0.25).abs() < 1e-3); + assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends"); + } +} diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs new file mode 100644 index 00000000..c2dfe755 --- /dev/null +++ b/crates/compose/src/curvature_sizes.rs @@ -0,0 +1,133 @@ +//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. + +use std::sync::{Arc, Mutex, Weak}; + +use rayon::prelude::*; +use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; +use crate::eval::{Inputs, blur}; + +/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. +pub struct CurvatureSizes { + pub levels: Vec, +} + +/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. +type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +impl CurvatureSizes { + /// The sizes of the texture set `inp` composites (None without a baked curvature map). + pub fn of(inp: &Inputs) -> Option> { + let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; + let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); + let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); + let working_size = (inp.gbuf.width, inp.gbuf.height); + + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); + let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { + same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales + }); + if let Some((.., sizes)) = cached { + return Some(sizes.clone()); + } + + // Covered working texels mark where they land in the bake atlas + let mut covered = vec![false; (width * height) as usize]; + for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + *slot = true; + } + } + } + + let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); + cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); + Some(sizes) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. + fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); + let deviation: Vec = + padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); + let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height)); + + let levels = CurvatureDetail::SIZES + .iter() + .skip(1) + .map(|size| { + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser + let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; + let step = (radius / 2).max(1).next_power_of_two(); + + let mut blurred = deviation.clone(); + for block_y in (0..height).step_by(block_height as usize) { + for block_x in (0..width).step_by(block_width as usize) { + let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y)); + blur_block(&mut blurred, width, region, radius); + } + } + coarsen(&blurred, (width, height), step) + }) + .collect(); + CurvatureSizes { levels } + } +} + +/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { + let mut block: Vec = + (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, w as usize, h as usize, radius as usize); + + for (row, values) in block.chunks(w as usize).enumerate() { + let start = ((y0 + row as u32) * width + x0) as usize; + if let Some(target) = data.get_mut(start..start + values.len()) { + target.copy_from_slice(values); + } + } +} + +/// `data` averaged over `step × step` squares (the last ones clipped to the map). +fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { + let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); + let deviation = (0..coarse_width * coarse_height) + .into_par_iter() + .map(|cell| { + let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width); + let columns = cell_x * step..((cell_x + 1) * step).min(width); + let rows = cell_y * step..((cell_y + 1) * step).min(height); + let count = (columns.len() * rows.len()).max(1) as f32; + let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize)); + let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::() / count; + (mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16 + }) + .collect(); + CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, deviation } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn padding_keeps_an_island_border_from_reading_flat() { + let left_half = |texel: u32| texel % 64 < 32; + let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..64 * 64).map(left_half).collect(); + let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); + for level in &sizes.levels { + assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..412cfe58 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,17 +4,20 @@ use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, + blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::below::{Band, BelowCache, Level}; +use crate::curvature_sizes::CurvatureSizes; use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; @@ -204,6 +207,8 @@ struct EffectPlan<'a> { opacity: f32, data: Option>, preview: bool, + /// The curvature detail sizes a generator with detail reads. + curvature_sizes: Option>, } struct MaskPlan<'a> { @@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] { [cs, -sn] } +/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white). +const MAP_GAIN: f32 = 2.0; + +/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength. +const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2; + /// Samples along a directional or slope blur at most (beyond, samples spread out). const LINE_SAMPLES: i32 = 24; @@ -423,7 +434,7 @@ const FIX: f64 = (1u64 << 24) as f64; /// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. /// Rows (and columns, transposed) blur in parallel. -fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { +pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; let mut v: Vec = data.par_iter().map(fix).collect(); blur_rows(&mut v, w, r); @@ -808,12 +819,14 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), }; + let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { kind: &e.kind, blend: e.blend, opacity: e.opacity, data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, preview: previews(inp, target), + curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } }) .collect() @@ -1166,94 +1179,130 @@ impl<'a, 'b> Texel<'a, 'b> { } } - fn generator(&mut self, g: &Generator) -> f32 { - let c = self.coords(); - let s = match g.kind { - GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, - GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5), - GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), - GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), - GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let coords = self.coords(); + let signal = match (generator.kind, &generator.detail) { + (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes), + (GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, + (GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5), + (GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0), + (GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0), + (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, + (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let th = 1.0 - g.level.clamp(0.0, 1.0); - let soft = g.softness.max(1e-3); - let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } + let signal = if generator.noise_amount > 0.0 { + signal + (world_noise(coords.pos, generator.noise_scale, generator.seed) - 0.5) * generator.noise_amount + } else { + signal + }; + + // A smooth step from black to white over 2 × softness around 1 − level + let threshold = 1.0 - generator.level.clamp(0.0, 1.0); + let softness = generator.softness.max(1e-3); + let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); + let value = ramp * ramp * (3.0 - 2.0 * ramp); + if generator.invert { 1.0 - value } else { value } } - fn mask(&mut self, m: &MaskPlan) -> f32 { - let mut v = m.background; - let mut skip = 0; - if let Some((k, field)) = m.start - && let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied()) - { - v = f; - skip = k + 1; + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { + let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + + let working_size = (self.res, self.inp.gbuf.height); + let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + + let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); + let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); + let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let (mut edges, mut cavities) = (0.0f32, 0.0f32); + for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { + let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; + + let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size }; + let weight = weight.clamp(0.0, 1.0); + edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0)); + cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - for e in m.effects.iter().skip(skip) { - let o = e.opacity.clamp(0.0, 1.0); - match e.kind { + + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } + } + + fn mask(&mut self, plan: &MaskPlan) -> f32 { + let mut value = plan.background; + let mut skip = 0; + if let Some((filtered_index, field)) = plan.start + && let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied()) + { + value = filtered; + skip = filtered_index + 1; + } + + for effect in plan.effects.iter().skip(skip) { + let opacity = effect.opacity.clamp(0.0, 1.0); + match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { - let (mut pv, mut cov) = match e.data.as_deref() { - Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))), + let (mut painted, mut cov) = match effect.data.as_deref() { + Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; - if e.preview - && let Some(p) = self.inp.preview + if effect.preview + && let Some(preview) = self.inp.preview { - let a = (self.stroke * p.opacity).clamp(0.0, 1.0); - if p.erase { - pv *= 1.0 - a; - cov *= 1.0 - a; + let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + if preview.erase { + painted *= 1.0 - stroke; + cov *= 1.0 - stroke; } else { - pv = p.mask_value * a + pv * (1.0 - a); - cov = a + cov * (1.0 - a); + painted = preview.mask_value * stroke + painted * (1.0 - stroke); + cov = stroke + cov * (1.0 - stroke); } } if cov > 0.0 { - let val = pv / cov.max(1e-5); - v += (blend1(e.blend, v, val) - v) * cov * o; + let layer_value = painted / cov.max(1e-5); + value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity; } } EffectKind::Fill { source, projection } => { - let val = self.source(source, projection, ChannelKind::Scalar)[0]; - v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection); + let fill = self.source(source, projection, ChannelKind::Scalar)[0]; + value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection); } - EffectKind::Generator(g) => { - let val = self.generator(g); - v += (blend1(e.blend, v, val) - v) * o; + EffectKind::Generator(generator) => { + let generated = self.generator(generator, effect.curvature_sizes.as_deref()); + value += (blend1(effect.blend, value, generated) - value) * opacity; } - EffectKind::Levels(l) => v += (l.apply(v) - v) * o, - EffectKind::Filter(f) => { - // A mask is gray (HSL only changes its lightness); neighbourhood filters come - // precomputed through `MaskPlan::start`. - let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]); - v += (val - v) * o; + EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity, + EffectKind::Filter(filter) => { + // A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start` + let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); + value += (filtered - value) * opacity; } EffectKind::ColorSelection { colors, tolerance } => { let id = self.baked_color(BakedMap::Id); - let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance)); - let val = if hit { 1.0 } else { 0.0 }; - v += (blend1(e.blend, v, val) - v) * o; + let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); + let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; + value += (blend1(effect.blend, value, selected) - value) * opacity; } - EffectKind::Compare { op, value, tolerance } => { + EffectKind::Compare { op, value: compared, tolerance } => { let pass = match op { - CompareOp::LesserThan => v < *value, - CompareOp::GreaterThan => v > *value, - CompareOp::WithinTolerance => (v - value).abs() <= *tolerance, + CompareOp::LesserThan => value < *compared, + CompareOp::GreaterThan => value > *compared, + CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, }; - let val = if pass { 1.0 } else { 0.0 }; - v += (val - v) * o; + let result = if pass { 1.0 } else { 0.0 }; + value += (result - value) * opacity; } - // Content-only effects. + // Content-only effects EffectKind::Material(_) | EffectKind::Anchor => {} } } - v.clamp(0.0, 1.0) + value.clamp(0.0, 1.0) } /// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop` @@ -2455,6 +2504,44 @@ mod tests { assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs"); } + #[test] + fn larger_curvature_detail_sizes_reach_further_from_an_edge() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256); + fixture.project.texture_sets[0].resolution = 256; + let ridge: Vec = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect(); + fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() }; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec { + let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights }; + let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = Default::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: BlockScales::default(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::>()).unwrap() + }; + + // The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth + let (ridge, five_texels_away) = (8, 3); + let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]); + let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}"); + assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}"); + } + #[test] fn blur_filter_softens_mask_edges() { let mut f = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 01365a27..fe57e611 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -9,6 +9,8 @@ mod baked_maps; pub mod below; +mod curvature_size_level; +pub mod curvature_sizes; pub mod display; pub mod eval; pub mod pattern; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 551c9803..19c82f61 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize}; use crate::{BlendMode, Channel, ChannelKind, lum}; +mod curvature_detail; +mod curvature_mode; + +pub use curvature_detail::CurvatureDetail; +pub use curvature_mode::CurvatureMode; + /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct LayerId(pub u64); @@ -540,17 +546,27 @@ pub struct Generator { /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, + /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub detail: Option, } impl Generator { pub fn new(kind: GeneratorKind) -> Generator { let (level, softness, noise_amount) = match kind { - GeneratorKind::EdgeWear => (0.6, 0.12, 0.5), + GeneratorKind::EdgeWear => (0.5, 0.25, 0.3), + GeneratorKind::Curvature => (0.5, 0.5, 0.0), GeneratorKind::Dirt => (0.55, 0.25, 0.35), GeneratorKind::ThinAreas => (0.3, 0.2, 0.0), _ => (0.5, 0.25, 0.0), }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false } + let detail = match kind { + GeneratorKind::Curvature => Some(CurvatureDetail::default()), + // Worn edges are thin lines: mostly the finer sizes + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + _ => None, + }; + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } } } @@ -1050,6 +1066,17 @@ impl Effect { mod tests { use super::*; + #[test] + fn curvature_generators_saved_before_detail_sizes_load_without_them() { + let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); + assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes"); + + saved.as_object_mut().unwrap().remove("detail"); + let loaded: Generator = serde_json::from_value(saved).unwrap(); + assert_eq!(loaded.detail, None); + assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes"); + } + #[test] fn levels_map_range_and_gamma() { let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs new file mode 100644 index 00000000..f843eac9 --- /dev/null +++ b/crates/core/src/layer/curvature_detail.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +use super::curvature_mode::CurvatureMode; + +/// How a curvature generator reads the curvature map: its mode and how much each detail size adds. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct CurvatureDetail { + pub mode: CurvatureMode, + /// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first. + pub weights: [f32; CurvatureDetail::SIZES.len()], +} + +impl CurvatureDetail { + /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. + pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; +} + +impl Default for CurvatureDetail { + fn default() -> Self { + CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + } +} diff --git a/crates/core/src/layer/curvature_mode.rs b/crates/core/src/layer/curvature_mode.rs new file mode 100644 index 00000000..a4183e7a --- /dev/null +++ b/crates/core/src/layer/curvature_mode.rs @@ -0,0 +1,34 @@ +use serde::{Deserialize, Serialize}; + +/// Which side of the curvature map a curvature generator shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum CurvatureMode { + /// Convex edges white. + #[default] + Edges, + /// Concave cavities white. + Cavities, + /// Edges and cavities both white. + Both, + /// Signed curvature around mid gray (cavities dark, edges light). + Raw, +} + +impl CurvatureMode { + pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw]; + + pub fn label(self) -> &'static str { + match self { + CurvatureMode::Edges => "Edges", + CurvatureMode::Cavities => "Cavities", + CurvatureMode::Both => "Edges and cavities", + CurvatureMode::Raw => "Raw curvature", + } + } + + /// The mode named `name` (its variant or label, any case). + pub fn parse(name: &str) -> Option { + let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], ""); + CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name)) + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 72adf044..75ea2405 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,8 +24,9 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, - LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, + LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, + hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 347b7390..ae73a3a7 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -2,7 +2,7 @@ //! without a screenshot. use serde_json::{Value, json}; -use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source}; +use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source}; use crate::Session; use crate::session::StackTarget; @@ -34,38 +34,45 @@ fn fill_json(f: &Fill) -> Value { } /// A mask or content (`content`) effect. -fn effect_json(s: &Session, e: &Effect, content: bool) -> Value { - let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity }); - match &e.kind { - EffectKind::Generator(g) => { - ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }) - } - EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]), +fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { + let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); + let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); + let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); + + match &effect.kind { + EffectKind::Generator(generator) => out["generator"] = generator_json(generator), + EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), EffectKind::Path(paths) => { - ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::>()); - ej["tiles"] = json!(if content { - s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::() - } else { - s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0) - }); + out["paths"] = json!( + paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::>() + ); + out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() }); } - EffectKind::Paint if content => { - ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::()) - } - EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)), - EffectKind::Fill { source, .. } => ej["source"] = source_json(source), - EffectKind::Material(f) => ej["fill"] = fill_json(f), - EffectKind::Filter(f) => { - ej["filter"] = json!(f); - match f { - Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]), - Filter::Blur { radius } => ej["radius"] = json!(radius), + EffectKind::Paint if content => out["tiles"] = json!(content_tiles()), + EffectKind::Paint => out["tiles"] = json!(mask_tiles()), + EffectKind::Fill { source, .. } => out["source"] = source_json(source), + EffectKind::Material(fill) => out["fill"] = fill_json(fill), + EffectKind::Filter(filter) => { + out["filter"] = json!(filter); + match filter { + Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]), + Filter::Blur { radius } => out["radius"] = json!(radius), _ => {} } } _ => {} } - ej + out +} + +/// A generator's settings, with its curvature mode and detail size weights when it has them. +fn generator_json(generator: &Generator) -> Value { + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert }); + if let Some(detail) = &generator.detail { + out["mode"] = json!(format!("{:?}", detail.mode)); + out["sizes"] = json!(detail.weights); + } + out } fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 2656bd15..41cecca8 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -2,8 +2,8 @@ use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind, - Project, Source, + BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, + Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -314,39 +314,67 @@ fn add_fill(s: &mut Session, p: &Value) -> Result { push_effect(s, p, EffectKind::Fill { source, projection }, blend) } -fn generator_from(p: &Value, g: &mut Generator) { - if let Some(v) = f32p(p, "level") { - g.level = v.clamp(0.0, 1.0); +/// Apply the generator parameters in `params` to `generator` (`command` names it in errors). +fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> { + if let Some(level) = f32p(params, "level") { + generator.level = level.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "softness") { - g.softness = v.clamp(0.0, 1.0); + if let Some(softness) = f32p(params, "softness") { + generator.softness = softness.clamp(0.0, 1.0); } - if let Some(v) = f32p(p, "noise") { - g.noise_amount = v.clamp(0.0, 2.0); + if let Some(noise) = f32p(params, "noise") { + generator.noise_amount = noise.clamp(0.0, 2.0); } - if let Some(v) = f32p(p, "noiseScale") { - g.noise_scale = v.clamp(0.01, 1000.0); + if let Some(noise_scale) = f32p(params, "noiseScale") { + generator.noise_scale = noise_scale.clamp(0.01, 1000.0); } - if let Some(v) = u64p(p, "seed") { - g.seed = v as u32; + if let Some(seed) = u64p(params, "seed") { + generator.seed = seed as u32; } - if let Some(v) = boolp(p, "invert") { - g.invert = v; + if let Some(invert) = boolp(params, "invert") { + generator.invert = invert; } - if let Some(d) = color_param(p, "direction") { - g.direction = d; + if let Some(direction) = color_param(params, "direction") { + generator.direction = direction; } + + // A mode or sizes also give a curvature generator saved before detail sizes its detail + let mode = + strp(params, "mode").map(|name| CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))).transpose()?; + let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?; + if mode.is_none() && weights.is_none() { + return Ok(()); + } + if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes")); + } + + let detail = generator.detail.get_or_insert_with(CurvatureDetail::default); + if let Some(mode) = mode { + detail.mode = mode; + } + if let Some(weights) = weights { + detail.weights = weights; + } + Ok(()) } -fn add_generator(s: &mut Session, p: &Value) -> Result { - let kind = match strp(p, "generator") { - Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?, +/// The detail size weights in `value`: one number (0..1) per size of [`CurvatureDetail::SIZES`], finest first. +fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> { + let weights: Vec = + value.as_array().map(|items| items.iter().filter_map(Value::as_f64).map(|weight| (weight as f32).clamp(0.0, 1.0)).collect()).unwrap_or_default(); + weights.try_into().map_err(|_| bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()))) +} + +fn add_generator(session: &mut Session, params: &Value) -> Result { + let kind = match strp(params, "generator") { + Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, None => GeneratorKind::EdgeWear, }; - let mut g = Generator::new(kind); - generator_from(p, &mut g); - let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal); - push_effect(s, p, EffectKind::Generator(g), blend) + let mut generator = Generator::new(kind); + generator_from("effect.add.generator", params, &mut generator)?; + let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); + push_effect(session, params, EffectKind::Generator(generator), blend) } pub(crate) fn levels_from(p: &Value, l: &mut Levels) { @@ -413,55 +441,57 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) }) } -fn set(s: &mut Session, p: &Value) -> Result { - let eid = effect_id(s, p, "effect.set")?; - let blend = blend_param("effect.set", p, "blend")?; - // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone - // re-targets the current one. - let anchor = match s.doc.project.effect(eid) { +fn set(session: &mut Session, params: &Value) -> Result { + let target = effect_id(session, params, "effect.set")?; + let blend = blend_param("effect.set", params, "blend")?; + + // A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone re-targets the current one + let anchor = match session.doc.project.effect(target) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { Source::Anchor { anchor, channel } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; - let channel_param = channel_param("effect.set", p, "anchorChannel")?; - match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { - Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?), + let channel_param = channel_param("effect.set", params, "anchorChannel")?; + match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) { + Some(anchor) => Some(anchor_source(session, "effect.set", owner, anchor, channel_param.unwrap_or(channel))?), None => None, } } _ => None, }; - s.edit("Edit effect", |s| { - let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?; - if let Some(v) = boolp(p, "visible") { - e.visible = v; + + session.edit("Edit effect", |session| { + let effect = session.doc.project.effect_mut(target).ok_or_else(|| bad("effect.set", format!("no effect {}", target.0)))?; + if let Some(visible) = boolp(params, "visible") { + effect.visible = visible; } - if let Some(b) = blend { - e.blend = b; + if let Some(blend) = blend { + effect.blend = blend; } - if let Some(o) = f32p(p, "opacity") { - e.opacity = o.clamp(0.0, 1.0); + if let Some(opacity) = f32p(params, "opacity") { + effect.opacity = opacity.clamp(0.0, 1.0); } - if let Some(n) = name_param(p) { - e.name = n.to_string(); + if let Some(name) = name_param(params) { + effect.name = name.to_string(); } - match &mut e.kind { - EffectKind::Generator(g) => generator_from(p, g), - EffectKind::Levels(l) => levels_from(p, l), - EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?, + + match &mut effect.kind { + EffectKind::Generator(generator) => generator_from("effect.set", params, generator)?, + EffectKind::Levels(levels) => levels_from(params, levels), + EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, "effect.set")?, EffectKind::Fill { source, .. } => { - if let Some(a) = anchor { - *source = a; - } else if let Some(x) = f32p(p, "value") + if let Some(anchor) = anchor { + *source = anchor; + } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. }) { - *source = Source::Uniform([x.clamp(0.0, 1.0); 3]); + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { - if let Some(x) = f32p(p, "tolerance") { - *tolerance = x.clamp(0.0, 1.0); + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); } } _ => {} diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 5038abbb..dd0111f3 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> { const UP: [f32; 3] = [0.0, 1.0, 0.0]; -/// A mesh-map generator with explicit threshold, softness and noise breakup. +/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes). pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) }) } /// A direction or position generator (`invert` flips the result). pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind { - EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) }) + EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } /// A triplanar grayscale pattern fill. diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 02be7a8d..e7e38614 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -380,3 +380,23 @@ fn background_resizes_match_the_command_and_keep_later_edits() { b.update(); assert_eq!(b.caches[0].size, (512, 512)); } + +#[test] +fn curvature_generators_take_a_mode_and_detail_sizes() { + let mut state = session(); + execute(&mut state, "layer.add.fill", &json!({})).unwrap(); + execute(&mut state, "mask.add.black", &Value::Null).unwrap(); + let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap(); + let effect = added["effect"].clone(); + + execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); + + let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]})); + assert!(too_few.is_err(), "sizes takes one weight per detail size"); + let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"})); + assert!(unknown.is_err(), "unknown modes are rejected"); + let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"})); + assert!(dirt.is_err(), "only curvature generators have a mode"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..55e9e8f3 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -5,8 +5,8 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, - Projection, Source, + BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, + LinkParam, MaterialLink, ProceduralKind, Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -1873,63 +1873,42 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) { let tk = Tokens::get(ui.ctx()); - let Some((_, e)) = app.session.doc.project.effect(eid).map(|(l, e)| (l, e.clone())) else { return }; + let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return }; + let id = eid.0; ui.horizontal(|ui| { ui.label(tr("Blending")); - egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(e.blend.label())).show_ui(ui, |ui| { - for m in BlendMode::all() { - if ui.selectable_label(m == e.blend, tr(m.label())).clicked() { - app.run("effect.set", json!({"effect": id, "blend": format!("{m:?}")})); + egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| { + for mode in BlendMode::all() { + if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() { + app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")})); } } }); }); - let mut op = e.opacity; - if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "opacity": op, "merge": merge})); + let mut opacity = effect.opacity; + if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge})); } ui.separator(); - match &e.kind { - EffectKind::Generator(g) => { - ui.label(caption(tr("Generator"))); - egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(g.kind.label())).show_ui(ui, |ui| { - for k in GeneratorKind::ALL { - if ui.selectable_label(k == g.kind, tr(k.label())).clicked() { - // Replace the generator kind: remove and add keeps ordering simple. - app.run("effect.remove", json!({"effect": id})); - app.run("effect.add.generator", json!({"generator": format!("{k:?}")})); - } - } - }); - let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale); - let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); - let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2); - let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); - let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1); - let mut inv = g.invert; - let r5 = ui.checkbox(&mut inv, tr("Invert")); - if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) { - app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge})); - } - if !app.session.doc.baked.contains_key(&app.session.ts()) { - ui.label( - RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning), - ); - } - } - EffectKind::Levels(l) => { + + match &effect.kind { + EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), + EffectKind::Levels(levels) => { ui.label(caption(tr("Levels"))); - levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); - let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; + levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high)); + let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]; let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; let mut edit = None; - for (i, label) in labels.iter().enumerate() { - let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2)); + for (index, label) in labels.iter().enumerate() { + let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; + edit = edit.or(slider_edit(ui, label, &mut values[index], range, 2)); } if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge})); + app.run( + "effect.set", + json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}), + ); } } EffectKind::Fill { source, .. } => { @@ -1945,25 +1924,25 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (a, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*a), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": a.0})); + for (anchor, label) in &anchors { + if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } } }); match source { - Source::Uniform(v) => { - let mut x = v[0]; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) { - app.run("effect.set", json!({"effect": id, "value": x, "merge": merge})); + Source::Uniform(color) => { + let mut value = color[0]; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } Source::Anchor { channel, .. } => { - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == *channel, tr(c.label())).clicked() { - app.run("effect.set", json!({"effect": id, "anchorChannel": c.id()})); + for option in channels { + if ui.selectable_label(option == *channel, tr(option.label())).clicked() { + app.run("effect.set", json!({"effect": id, "anchorChannel": option.id()})); } } }); @@ -1975,10 +1954,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim)); } } - EffectKind::Material(f) => { + EffectKind::Material(fill) => { ui.label(caption(tr("Fill"))); - let on: Vec = f.sources.keys().copied().collect(); - fill_editor(app, ui, f, &json!({"effect": id}), &on, layer.id); + let enabled: Vec = fill.sources.keys().copied().collect(); + fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id); } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); @@ -1988,7 +1967,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } EffectKind::Paint => { - let hint = if layer.content_effects.iter().any(|x| x.id == eid) { + let hint = if layer.content_effects.iter().any(|content| content.id == eid) { tr("Paint on the mesh to edit the layer content.") } else { tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") @@ -2002,30 +1981,102 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: .color(tk.text_dim), ); let editing = app.session.tool.path.editing; - for i in 0..paths.len() { + for index in 0..paths.len() { ui.horizontal(|ui| { - let on = editing == Some((eid, i)); - if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() { - if on { + let selected = editing == Some((eid, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { app.run("tool.path", json!({"clear": true})); } else { - app.run("path.edit", json!({"effect": id, "index": i})); + app.run("path.edit", json!({"effect": id, "index": index})); } } if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() { - app.run("path.remove", json!({"effect": id, "index": i})); + app.run("path.remove", json!({"effect": id, "index": index})); } }); } tool_properties(app, ui); } - EffectKind::Filter(f) => filter_properties(app, ui, id, f), + EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } } } +/// The settings of generator effect `id`. +fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { + let tk = Tokens::get(ui.ctx()); + ui.label(caption(tr("Generator"))); + egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { + for kind in GeneratorKind::ALL { + if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() { + // Replace the generator kind: remove and add keeps ordering simple + app.run("effect.remove", json!({"effect": id})); + app.run("effect.add.generator", json!({"generator": format!("{kind:?}")})); + } + } + }); + + let (mut level, mut softness, mut noise, mut noise_scale, mut invert) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert); + let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); + let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); + let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); + let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) { + app.run( + "effect.set", + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}), + ); + } + + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { + curvature_detail_properties(app, ui, id, generator.detail.as_ref()); + } + if !app.session.doc.baked.contains_key(&app.session.ts()) { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); + } +} + +/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). +fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { + let tk = Tokens::get(ui.ctx()); + let shown = detail.cloned().unwrap_or_default(); + combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| { + for mode in CurvatureMode::ALL { + if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() { + app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")})); + } + } + }); + + ui.label(caption(tr("Detail sizes"))); + let mut weights = shown.weights; + let mut edit = None; + for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) { + edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2)); + } + if let Some(merge) = edit { + app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge})); + } + if detail.is_none() { + ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim)); + } +} + +/// The translated name of curvature mode `mode`. +fn curvature_mode_label(mode: CurvatureMode) -> &'static str { + match mode { + CurvatureMode::Edges => tr("Edges"), + CurvatureMode::Cavities => tr("Cavities"), + CurvatureMode::Both => tr("Edges and cavities"), + CurvatureMode::Raw => tr("Raw curvature"), + } +} + /// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel /// picked here), with the input range marked. Recomputed after a document change once no /// pointer button is held, so dragging a slider keeps the last one. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..a76cabf0 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1035,4 +1035,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Edges", "الحواف"), + ("Cavities", "التجاويف"), + ("Edges and cavities", "الحواف والتجاويف"), + ("Raw curvature", "الانحناء الخام"), + ("Detail sizes", "أحجام التفاصيل"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..7135f142 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1078,4 +1078,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Edges", "Kanten"), + ("Cavities", "Vertiefungen"), + ("Edges and cavities", "Kanten und Vertiefungen"), + ("Raw curvature", "Rohe Krümmung"), + ("Detail sizes", "Detailgrößen"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..3c5e03ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1063,4 +1063,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Edges", "Bordes"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordes y cavidades"), + ("Raw curvature", "Curvatura sin procesar"), + ("Detail sizes", "Tamaños de detalle"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..1c55b5ee 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1087,4 +1087,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Edges", "Arêtes"), + ("Cavities", "Cavités"), + ("Edges and cavities", "Arêtes et cavités"), + ("Raw curvature", "Courbure brute"), + ("Detail sizes", "Tailles de détail"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a84b16d1 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1072,4 +1072,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Edges", "Bordi"), + ("Cavities", "Cavità"), + ("Edges and cavities", "Bordi e cavità"), + ("Raw curvature", "Curvatura grezza"), + ("Detail sizes", "Dimensioni del dettaglio"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..3f2fa7e6 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1057,4 +1057,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Edges", "エッジ"), + ("Cavities", "くぼみ"), + ("Edges and cavities", "エッジとくぼみ"), + ("Raw curvature", "生の曲率"), + ("Detail sizes", "ディテールサイズ"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..e0513259 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1045,4 +1045,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Edges", "가장자리"), + ("Cavities", "오목한 부분"), + ("Edges and cavities", "가장자리와 오목한 부분"), + ("Raw curvature", "원시 곡률"), + ("Detail sizes", "디테일 크기"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..65e55fa2 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1060,4 +1060,13 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Edges", "Bordas"), + ("Cavities", "Cavidades"), + ("Edges and cavities", "Bordas e cavidades"), + ("Raw curvature", "Curvatura bruta"), + ("Detail sizes", "Tamanhos de detalhe"), + ( + "Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", + "Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..e41e91d4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1003,4 +1003,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Edges", "边缘"), + ("Cavities", "凹陷"), + ("Edges and cavities", "边缘和凹陷"), + ("Raw curvature", "原始曲率"), + ("Detail sizes", "细节尺寸"), + ("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"), ]; From 906dcf324e2ed8de2f72cd630ec992fa0324aceb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 01:17:47 +0000 Subject: [PATCH 080/275] Curvature detail: name the tuned weights, clean up the effect plans and blur --- crates/compose/src/eval.rs | 38 +++++++++++------------ crates/core/src/layer.rs | 3 +- crates/core/src/layer/curvature_detail.rs | 8 ++++- 3 files changed, 27 insertions(+), 22 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 412cfe58..1eb29882 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -432,15 +432,15 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3 /// the region it is computed in, so tiles composited in any grouping agree exactly. const FIX: f64 = (1u64 << 24) as f64; -/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns. -/// Rows (and columns, transposed) blur in parallel. -pub(crate) fn blur(data: &mut [f32], w: usize, h: usize, r: usize) { - let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; - let mut v: Vec = data.par_iter().map(fix).collect(); - blur_rows(&mut v, w, r); - let mut t = transpose(&v, w, h); - blur_rows(&mut t, h, r); - data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32); +/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel. +pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) { + let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 }; + let mut fixed: Vec = data.par_iter().map(to_fixed).collect(); + blur_rows(&mut fixed, width, radius); + + let mut columns = transpose(&fixed, width, height); + blur_rows(&mut columns, height, radius); + data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } /// Three box blurs of radius `r` along every row (`w` long) of `data`. @@ -813,18 +813,18 @@ struct Node<'a> { fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { effects .iter() - .filter(|e| e.visible) - .map(|e| { - let (img, target) = match channel { - Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)), - None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)), + .filter(|effect| effect.visible) + .map(|effect| { + let (image, target) = match channel { + Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), + None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&e.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); EffectPlan { - kind: &e.kind, - blend: e.blend, - opacity: e.opacity, - data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None }, + kind: &effect.kind, + blend: effect.blend, + opacity: effect.opacity, + data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, preview: previews(inp, target), curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, } diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 19c82f61..37ce47e8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -562,8 +562,7 @@ impl Generator { }; let detail = match kind { GeneratorKind::Curvature => Some(CurvatureDetail::default()), - // Worn edges are thin lines: mostly the finer sizes - GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0] }), + GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index f843eac9..826b9823 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -13,10 +13,16 @@ pub struct CurvatureDetail { impl CurvatureDetail { /// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii. pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0]; + + /// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly. + pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15]; + + /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. + pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; } impl Default for CurvatureDetail { fn default() -> Self { - CurvatureDetail { mode: CurvatureMode::Edges, weights: [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15] } + CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS } } } From 1a0fc5fec8d28085d2b0b17630d63e3cb2fe3481 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 11:51:43 +0000 Subject: [PATCH 081/275] Curvature detail: build only the sizes in use, map coverage on all cores --- crates/compose/src/curvature_sizes.rs | 160 ++++++++++++++++------ crates/compose/src/eval.rs | 51 +++++-- crates/core/src/layer/curvature_detail.rs | 8 ++ 3 files changed, 167 insertions(+), 52 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index c2dfe755..7b6014e0 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -1,5 +1,6 @@ //! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; @@ -11,52 +12,55 @@ use crate::eval::{Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { - pub levels: Vec, + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, } -/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. -type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); static CACHE: Mutex> = Mutex::new(Vec::new()); impl CurvatureSizes { - /// The sizes of the texture set `inp` composites (None without a baked curvature map). - pub fn of(inp: &Inputs) -> Option> { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); - let working_size = (inp.gbuf.width, inp.gbuf.height); - - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(source, ..)| source.strong_count() > 0); - let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); - let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { - same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales - }); - if let Some((.., sizes)) = cached { + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { return Some(sizes.clone()); } - // Covered working texels mark where they land in the bake atlas - let mut covered = vec![false; (width * height) as usize]; - for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { - let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; - if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { - let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); - if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { - *slot = true; - } - } - } - - let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); - cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); - Some(sizes) + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) } - /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. - fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at the sizes `needed` marks; sizes already in `built` are kept as they are. + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); let deviation: Vec = padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); @@ -65,7 +69,15 @@ impl CurvatureSizes { let levels = CurvatureDetail::SIZES .iter() .skip(1) - .map(|size| { + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let step = (radius / 2).max(1).next_power_of_two(); @@ -77,13 +89,55 @@ impl CurvatureSizes { blur_block(&mut blurred, width, region, radius); } } - coarsen(&blurred, (width, height), step) + Some(Arc::new(coarsen(&blurred, (width, height), step))) }) .collect(); CurvatureSizes { levels } } } +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any. +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)).map(|(.., sizes)| sizes.clone()) +} + +/// Cache `sizes`, keeping the sizes another thread cached meanwhile, and return what the cache holds now. +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + return sizes; + }; + + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + *cached_sizes = Arc::new(CurvatureSizes { levels }); + cached_sizes.clone() +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) that the covered working texels of `inp` land on. +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + /// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { let mut block: Vec = @@ -122,12 +176,40 @@ mod tests { #[test] fn padding_keeps_an_island_border_from_reading_flat() { - let left_half = |texel: u32| texel % 64 < 32; - let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); - let covered: Vec = (0..64 * 64).map(left_half).collect(); - let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); - for level in &sizes.levels { - assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1eb29882..e8fd391b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -771,28 +771,48 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -810,7 +830,7 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -819,14 +839,17 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, + }; EffectPlan { kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, - data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, + curvature_sizes, } }) .collect() @@ -1215,7 +1238,9 @@ impl<'a, 'b> Texel<'a, 'b> { let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); - let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; let (mut edges, mut cavities) = (0.0f32, 0.0f32); for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index 826b9823..75c9d36a 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -19,6 +19,14 @@ impl CurvatureDetail { /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; + + /// How many sizes are blurred copies of the map (all but the first). + pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1; + + /// Which blurred sizes this detail reads: those with a weight above 0. + pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] { + std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0)) + } } impl Default for CurvatureDetail { From 508c4bb2aaba8c3a7a5e7af481516fdbff69eeb8 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 02:49:47 +0000 Subject: [PATCH 082/275] Keep the click that dismisses the image drop menu from painting The views don't paint while a dropped image waits for its menu pick, so a click on the mesh outside the menu only closes it. Also document Texel::source and DecalDrop::menu_id. --- crates/compose/src/eval.rs | 1 + crates/ui-egui/src/decal_drop.rs | 6 ++++++ crates/ui-egui/src/viewport.rs | 7 +++++-- crates/ui-egui/tests/shelf_drop.rs | 13 +++++++++---- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 308d11c2..9dba941a 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1129,6 +1129,7 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 0bb95f65..1dfba5f2 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -25,6 +25,7 @@ pub struct DecalDrop { } impl DecalDrop { + /// Where the waiting drop and its menu's state are kept fn menu_id() -> Id { Id::unique("decal_drop_menu") } @@ -34,6 +35,11 @@ impl DecalDrop { ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); } + /// Whether a drop waits for its menu pick: the views don't paint meanwhile, so the click that dismisses the menu paints nothing + pub fn waiting(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(Self::menu_id()).is_some()) + } + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1855438a..ec58ce89 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -13,6 +13,7 @@ use texturecraft_engine::{Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; @@ -571,7 +572,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !focus_pick && placing.is_none() && touch.is_none() - && !decal_drag; + && !decal_drag + && !DecalDrop::waiting(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); @@ -1236,7 +1238,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let painting = + app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !DecalDrop::waiting(ui.ctx()); if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 7bb94a04..36a89de6 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -3,6 +3,7 @@ use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use texturecraft_engine::Tool; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; @@ -125,10 +126,14 @@ fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); assert!(menu_open(&harness, position)); - // A click elsewhere closes the menu - let corner = harness.state().viewport_rect.min + egui::vec2(SEARCH_STEP, SEARCH_STEP); - harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + // A click elsewhere on the mesh closes the menu and fills nothing there (a polygon fill click records a step in this harness) + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let elsewhere = point_over(&harness, Some(0)); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); assert!(!menu_open(&harness, position)); assert_eq!(stack_sizes(&harness), stacks); From 63fc9936441f4ca70056ccb183f7d0610274620d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 22:21:43 +0000 Subject: [PATCH 083/275] Tidy the Shader Settings, History and Log panels Shader Settings starts with the shader model; its description moves to the model's tooltip. The height to normal strength stays in the texture set settings only. Subsurface scattering and Transmission are collapsible sections. The History and Log lists fill their panel's height. --- crates/ui-egui/src/windows.rs | 154 +++++++++++++++------------ crates/ui-egui/tests/list_panels.rs | 73 +++++++++++++ crates/ui-egui/tests/shader_panel.rs | 30 ++++++ 3 files changed, 190 insertions(+), 67 deletions(-) create mode 100644 crates/ui-egui/tests/list_panels.rs create mode 100644 crates/ui-egui/tests/shader_panel.rs diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..e9a9e7a6 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -13,7 +13,7 @@ use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; -use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; +use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { start(app, ctx); @@ -225,18 +225,23 @@ fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The Shader Settings panel body (a dock tab). +/// Wide enough for the longer shader model name +const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; + +/// Width of the scatter color swatch +const SCATTER_SWATCH_WIDTH: f32 = 44.0; + +/// Index of refraction slider range: air to well past diamond (2.42) +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; + +/// The Shader Settings panel body (a dock tab) pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let mut d = app.session.doc.project.display.clone(); - let before = d.clone(); - let model = |sg: bool| if sg { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; - egui::ComboBox::from_id_salt("shader_model").width(260.0).selected_text(model(d.spec_gloss)).show_ui(ui, |ui| { - for sg in [false, true] { - ui.selectable_value(&mut d.spec_gloss, sg, model(sg)); - } - }); - let channels = if d.spec_gloss { + let tokens = Tokens::get(ui.ctx()); + let mut display = app.session.doc.project.display.clone(); + let before = display.clone(); + + let model_name = |spec_gloss: bool| if spec_gloss { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; + let channels = if display.spec_gloss { tr("Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).") } else { tr("Base color, Metallic, Roughness and Specular level.") @@ -247,75 +252,90 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { let optional = tr( "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", ); - ui.label(RichText::new(format!("{model_text} {channels} {optional}")).color(tk.text_dim)); + + egui::ComboBox::from_id_salt("shader_model") + .width(SHADER_MODEL_COMBO_WIDTH) + .selected_text(model_name(display.spec_gloss)) + .show_ui(ui, |ui| { + for spec_gloss in [false, true] { + ui.selectable_value(&mut display.spec_gloss, spec_gloss, model_name(spec_gloss)); + } + }) + .response + .on_hover_text(format!("{model_text} {channels} {optional}")); ui.add_space(6.0); - ui.checkbox(&mut d.parallax, tr("Parallax occlusion (height channel)")) + + ui.checkbox(&mut display.parallax, tr("Parallax occlusion (height channel)")) .on_hover_text(tr("Offsets the textures by the height channel, at the height to normal strength")); - ui.checkbox(&mut d.displacement, tr("Displacement (height channel)")).on_hover_text(tr( + ui.checkbox(&mut display.displacement, tr("Displacement (height channel)")).on_hover_text(tr( "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", )); + slider(ui, tr("AO intensity"), &mut display.ao_intensity, 0.0..=1.0, 2); ui.add_space(6.0); - ui.label(caption(tr("Subsurface scattering"))); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Scatter color")).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| color_swatch(ui, "shader_scatter_color", &mut d.scatter_color, 44.0)) - }) - .response - .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); - slider(ui, tr("Scatter radius"), &mut d.scatter_radius, 0.0..=1.0, 3) - .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); - ui.add_space(6.0); - ui.label(caption(tr("Transmission"))); - slider(ui, tr("Index of refraction"), &mut d.ior, 1.0..=3.0, 2) - .on_hover_text(tr("How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42")); - if d != before { - app.session.doc.project.display = d; - } - let ts = app.session.ts(); - if let Some(set) = app.session.doc.project.texture_sets.get(ts) { - let mut hs = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { - app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs, "merge": merge})); - } - } - let mut ao = app.session.doc.project.display.ao_intensity; - if slider(ui, tr("AO intensity"), &mut ao, 0.0..=1.0, 2).changed() { - app.session.doc.project.display.ao_intensity = ao; + + section(ui, "shader_subsurface", tr("Subsurface scattering"), true, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Scatter color")).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + color_swatch(ui, "shader_scatter_color", &mut display.scatter_color, SCATTER_SWATCH_WIDTH) + }) + }) + .response + .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); + slider(ui, tr("Scatter radius"), &mut display.scatter_radius, 0.0..=1.0, 3) + .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); + }); + section(ui, "shader_transmission", tr("Transmission"), true, |ui| { + slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + )); + }); + + if display != before { + app.session.doc.project.display = display; } } -/// The History panel body (a dock tab). +/// The History panel body (a dock tab) pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); - // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative. + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - let n = done.len() as i64; - let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim)) - .chain(done.iter().map(RichText::new)) - .chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim))); - for (i, text) in rows.enumerate() { - // Row i is the state after i steps. - let steps = n - i as i64; - if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + + // Bottom up: the Undo and Redo row keeps its place under a list that fills the rest of the panel + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { + app.run("edit.undo", json!({})); } - } + if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { + app.run("edit.redo", json!({})); + } + }); + + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let done_count = done.len() as i64; + let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) + .chain(done.iter().map(RichText::new)) + .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", label)])).color(tokens.text_dim))); + for (row, text) in rows.enumerate() { + // Each row is the state after that many steps + let steps = done_count - row as i64; + if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { + jump = steps; + } + } + }); + }); }); + if jump > 0 { app.run("edit.undo", json!({ "steps": jump })); } else if jump < 0 { app.run("edit.redo", json!({ "steps": -jump })); } - ui.horizontal(|ui| { - if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { - app.run("edit.undo", json!({})); - } - if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { - app.run("edit.redo", json!({})); - } - }); } /// What the start window was asked for. @@ -676,11 +696,11 @@ fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.about = open; } -/// The Log panel body (a dock tab). +/// The Log panel body (a dock tab) pub(crate) fn log(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().max_height(300.0).stick_to_bottom(true).show(ui, |ui| { - for l in &app.session.log { - ui.label(RichText::new(l).monospace()); + egui::ScrollArea::vertical().auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + for line in &app.session.log { + ui.label(RichText::new(line).monospace()); } }); } diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs new file mode 100644 index 00000000..7b6ace60 --- /dev/null +++ b/crates/ui-egui/tests/list_panels.rs @@ -0,0 +1,73 @@ +//! The History and Log lists fill their panel instead of stopping at a fixed height + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel}; + +/// The list heights the panels used to stop at +const OLD_HISTORY_HEIGHT: f32 = 320.0; +const OLD_LOG_HEIGHT: f32 = 300.0; + +/// Leaves the left column (where the panel is docked) between 700 and 800 points tall +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 860.0); + +/// Right of the left column (11.5% of the window, about 184 points) and left of every other panel's scroll bar +const LEFT_COLUMN_MAX_X: f32 = 300.0; + +/// Enough rows to overflow the tallest panel +const ROWS: usize = 80; + +/// Small texture and bake sizes keep the sample session fast; the panels don't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Dock `panel` in the full-height left column, where the Assets panel is by default +fn dock_in_left_column(harness: &mut Harness<'_, TextureCraftApp>, panel: &str) { + // Each panel name appears once in the saved dock: in the layout or in the hidden list + let saved = serde_json::to_string(&harness.state().ui.dock).unwrap(); + let placeholder = "\"swapped-out\""; + let swapped = saved.replace("\"Assets\"", placeholder).replace(&format!("\"{panel}\""), "\"Assets\"").replace(placeholder, &format!("\"{panel}\"")); + harness.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); +} + +/// The height of the list's scroll bar, which runs the visible height of the list +fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let bar = harness.get_all_by_role(Role::ScrollBar).find(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X).expect("a scroll bar in the left column"); + bar.rect().height() +} + +#[test] +fn the_history_list_fills_a_tall_panel() { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let layer = session.selected_layer().unwrap(); + for step in 0..ROWS { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": format!("Step {step}")})).unwrap(); + } + + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + dock_in_left_column(&mut harness, "History"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::History)); + let height = list_height(&harness); + assert!(height > OLD_HISTORY_HEIGHT, "the history list is {height} points tall"); +} + +#[test] +fn the_log_list_fills_a_tall_panel() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.log.extend((0..ROWS).map(|line| format!("Log line {line}"))); + dock_in_left_column(&mut harness, "Log"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::Log)); + let height = list_height(&harness); + assert!(height > OLD_LOG_HEIGHT, "the log list is {height} points tall"); +} diff --git a/crates/ui-egui/tests/shader_panel.rs b/crates/ui-egui/tests/shader_panel.rs new file mode 100644 index 00000000..805420cb --- /dev/null +++ b/crates/ui-egui/tests/shader_panel.rs @@ -0,0 +1,30 @@ +//! Shader Settings shows each of its settings once: the height strength lives in the texture set settings + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +#[test] +fn shader_settings_leave_the_height_strength_to_the_texture_set_settings() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Shader); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.query_by_label("AO intensity").is_some(), "the Shader Settings panel is shown"); + // Texture Set Settings, the slider's other home, sits behind Layers in the default layout, so any match is in Shader Settings + assert!(!harness.state().ui.dock.is_visible(Panel::TextureSetSettings), "Texture Set Settings is behind Layers"); + assert!(harness.query_by_label("Height to normal strength").is_none()); +} From f5d07ced6b4c16721ea9ddae3d122daa1a7ffbf1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 22:25:41 +0000 Subject: [PATCH 084/275] Pick the display tone mapping from a dropdown The AO intensity is set in Shader Settings, so Display Settings no longer repeats it. --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/windows.rs | 13 +++++++----- crates/ui-egui/tests/display_panel.rs | 30 +++++++++++++++++++++++++++ 11 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/tests/display_panel.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..9f2bf4f9 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -60,7 +60,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "دائماً"), ("Ambient Occlusion", "الانسداد المحيطي (AO)"), ("Ambient occlusion", "الانسداد المحيطي (AO)"), - ("Ambient occlusion intensity", "شدة الانسداد المحيطي"), ("Amount", "المقدار"), ("Anchor point", "نقطة ارتكاز"), ("Anchor: {name}", "نقطة ارتكاز: {name}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..df242dd0 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Immer"), ("Ambient Occlusion", "Ambient Occlusion"), ("Ambient occlusion", "Ambient occlusion"), - ("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"), ("Amount", "Stärke"), ("Anchor point", "Ankerpunkt"), ("Anchor: {name}", "Anker: {name}"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..175bc1b0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -60,7 +60,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Siempre"), ("Ambient Occlusion", "Oclusión ambiental"), ("Ambient occlusion", "Oclusión ambiental"), - ("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"), ("Amount", "Cantidad"), ("Anchor point", "Punto de anclaje"), ("Anchor: {name}", "Anclaje: {name}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..53a3c001 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -66,7 +66,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Toujours"), ("Ambient Occlusion", "Occlusion ambiante"), ("Ambient occlusion", "Occlusion ambiante"), - ("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"), ("Amount", "Quantité"), ("Anchor point", "Point d'ancrage"), ("Anchor: {name}", "Ancrage : {name}"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..89179b4a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Sempre"), ("Ambient Occlusion", "Occlusione ambientale"), ("Ambient occlusion", "Occlusione ambientale"), - ("Ambient occlusion intensity", "Intensità occlusione ambientale"), ("Amount", "Quantità"), ("Anchor point", "Punto di ancoraggio"), ("Anchor: {name}", "Ancoraggio: {name}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..74bfdc87 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -66,7 +66,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "常に"), ("Ambient Occlusion", "アンビエントオクルージョン"), ("Ambient occlusion", "アンビエントオクルージョン"), - ("Ambient occlusion intensity", "アンビエントオクルージョンの強度"), ("Amount", "量"), ("Anchor point", "アンカーポイント"), ("Anchor: {name}", "アンカー: {name}"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..1ab57f1c 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "항상"), ("Ambient Occlusion", "앰비언트 오클루전"), ("Ambient occlusion", "앰비언트 오클루전"), - ("Ambient occlusion intensity", "앰비언트 오클루전 강도"), ("Amount", "양"), ("Anchor point", "앵커 포인트"), ("Anchor: {name}", "앵커: {name}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7bc898ec 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Sempre"), ("Ambient Occlusion", "Oclusão de ambiente"), ("Ambient occlusion", "Oclusão de ambiente"), - ("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"), ("Amount", "Quantidade"), ("Anchor point", "Ponto de ancoragem"), ("Anchor: {name}", "Âncora: {name}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..c161e7f7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -54,7 +54,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "始终"), ("Ambient Occlusion", "环境光遮蔽"), ("Ambient occlusion", "环境光遮蔽"), - ("Ambient occlusion intensity", "环境光遮蔽强度"), ("Amount", "数量"), ("Anchor point", "锚点"), ("Anchor: {name}", "锚点:{name}"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index e9a9e7a6..0d27fa87 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -156,10 +156,14 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.checkbox(&mut ortho, tr("Orthographic")).changed() { app.run("camera.set", json!({"ortho": ortho})); } - ui.horizontal(|ui| { - ui.label(tr("Tone mapping")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::Linear, tr("Linear")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::AcesFilmic, tr("ACES filmic")); + let tone_mapping_name = |tone_mapping: ToneMapping| match tone_mapping { + ToneMapping::Linear => tr("Linear"), + ToneMapping::AcesFilmic => tr("ACES filmic"), + }; + combo(ui, tr("Tone mapping"), tone_mapping_name(d.tone_mapping), |ui| { + for tone_mapping in [ToneMapping::Linear, ToneMapping::AcesFilmic] { + ui.selectable_value(&mut d.tone_mapping, tone_mapping, tone_mapping_name(tone_mapping)); + } }); cameras(app, ui); ui.add_space(6.0); @@ -177,7 +181,6 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.add_space(6.0); ui.label(caption(tr("Viewer settings"))); - slider(ui, tr("Ambient occlusion intensity"), &mut d.ao_intensity, 0.0..=1.0, 2); ui.checkbox(&mut app.ui.wireframe_3d, tr("Show wireframe in the 3D view")); ui.checkbox(&mut app.ui.uv_wireframe, tr("Show UV wireframe in the 2D view")); ui.checkbox(&mut d.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); diff --git a/crates/ui-egui/tests/display_panel.rs b/crates/ui-egui/tests/display_panel.rs new file mode 100644 index 00000000..9c72f884 --- /dev/null +++ b/crates/ui-egui/tests/display_panel.rs @@ -0,0 +1,30 @@ +//! Display Settings picks its tone mapping from a dropdown and leaves the AO intensity to Shader Settings + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +#[test] +fn display_picks_the_tone_mapping_from_a_dropdown() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Display); + harness.run_steps(STARTUP_FRAMES); + + let tone_mapping = harness.get_all_by_role(Role::ComboBox).find(|combo| combo.accesskit_node().value().as_deref() == Some("ACES filmic")); + assert!(tone_mapping.is_some(), "the tone mapping is a dropdown showing ACES filmic"); + assert!(harness.query_by_label("Ambient occlusion intensity").is_none(), "the AO intensity is in Shader Settings"); +} From 1a58c57f64e75699dda1e03a1666dcf3b591f020 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 00:26:23 +0000 Subject: [PATCH 085/275] Section reset: keyboard focus outline, tests over every section The reset icon draws an outline while it has keyboard focus and is left out of Tab order while its section is at its defaults. The tests now run every brush section: enabled and disabled state, the reset folds nothing in either state, and Enter on the focused icon resets. --- crates/ui-egui/src/widgets.rs | 20 ++++- crates/ui-egui/tests/brush_section_reset.rs | 98 +++++++++++++++------ 2 files changed, 87 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 80b7fa90..d51af0b0 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -276,6 +276,12 @@ const SECTION_RESET_ICON_SIZE: f32 = 14.0; /// How much of `text_dim` the reset icon keeps while its section is at its defaults const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; +/// Gap between the reset icon's glyph and its keyboard focus outline +const SECTION_RESET_FOCUS_MARGIN: f32 = 2.0; + +/// Corner radius of the reset icon's keyboard focus outline +const SECTION_RESET_FOCUS_CORNER_RADIUS: u8 = 3; + /// The header row and body of [`section`]; `reset_at_default` adds the reset icon fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); @@ -298,18 +304,28 @@ fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, r // Registered after the header so the icon, not the header, takes its clicks let mut reset_clicked = false; if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { - let response = ui.interact(rect, id.with("reset"), Sense::click()).on_hover_text(tr("Reset to defaults")); + // At the defaults the icon is inert, so Tab skips it + let sense = if at_default { Sense::CLICK } else { Sense::click() }; + let response = ui.interact(rect, id.with("reset"), sense).on_hover_text(tr("Reset to defaults")); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, tr("Reset to defaults"))); + let focused = response.has_focus(); let color = if at_default { tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) - } else if response.hovered() { + } else if response.hovered() || focused { tokens.text_strong } else { tokens.text_dim }; let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + + // Enter or Space on the focused icon resets, so keyboard focus needs an outline + if focused { + let outline = rect.expand(SECTION_RESET_FOCUS_MARGIN); + ui.painter().rect_stroke(outline, CornerRadius::same(SECTION_RESET_FOCUS_CORNER_RADIUS), ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + reset_clicked = response.clicked() && !at_default; } diff --git a/crates/ui-egui/tests/brush_section_reset.rs b/crates/ui-egui/tests/brush_section_reset.rs index 198b618c..9df12c7f 100644 --- a/crates/ui-egui/tests/brush_section_reset.rs +++ b/crates/ui-egui/tests/brush_section_reset.rs @@ -1,7 +1,7 @@ //! Each brush section header has a reset icon that puts only that section's settings back to their defaults use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{Alignment, BrushSettings, Particles, Symmetry}; use texturecraft_ui_egui::TextureCraftApp; @@ -17,6 +17,27 @@ const SETTLE_FRAMES: usize = 3; /// Puts one section's fields of the first brush back to the second's values type SectionReset = fn(&mut BrushSettings, &BrushSettings); +/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ + ("Size", "Minimum size (%)", true, |brush, defaults| { + (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) + }), + ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", "Size jitter", false, |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", "Backface culling", false, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse and symmetry", "Lazy mouse distance", false, |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), +]; + /// A brush that differs from the defaults in every field a section shows, within the valid ranges fn changed_brush() -> BrushSettings { BrushSettings { @@ -74,26 +95,10 @@ fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { #[test] fn each_reset_puts_back_only_its_own_section() { let defaults = BrushSettings::default(); - let sections: [(&str, SectionReset); 7] = [ - ("Size", |brush, defaults| (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space)), - ("Flow and opacity", |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) - }), - ("Angle", |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), - ("Jitters", |brush, defaults| { - (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = - (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) - }), - ("Alignment and culling", |brush, defaults| { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = - (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) - }), - ("Particles", |brush, defaults| brush.particles = defaults.particles), - ("Lazy mouse and symmetry", |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), - ]; - for (title, reset_section) in sections { + for (title, _, _, reset_section) in SECTIONS { let mut harness = app_with_brush(changed_brush()); + assert!(!reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is enabled once its section changed"); click_reset(&mut harness, title); let mut expected = changed_brush(); @@ -102,22 +107,57 @@ fn each_reset_puts_back_only_its_own_section() { } } +/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let icon = reset_icon(harness, title).rect(); + harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + harness.run_steps(SETTLE_FRAMES); +} + #[test] fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { - let mut harness = app_with_brush(changed_brush()); + for flip_first in [false, true] { + let mut harness = app_with_brush(changed_brush()); + if flip_first { + for (title, _, _, _) in SECTIONS { + click_header(&mut harness, title); + } + } - click_reset(&mut harness, "Size"); - assert!(harness.query_by_label("Minimum size (%)").is_some(), "Size starts open and stays open"); - - click_reset(&mut harness, "Jitters"); - assert!(harness.query_by_label("Size jitter").is_none(), "Jitters starts closed and stays closed"); + for (title, body_label, starts_open, _) in SECTIONS { + let open = starts_open != flip_first; + click_reset(&mut harness, title); + assert_eq!(harness.query_by_label(body_label).is_some(), open, "{title} stays {}", if open { "open" } else { "closed" }); + } + } } #[test] -fn at_the_defaults_the_reset_icon_does_nothing() { +fn at_the_defaults_the_reset_icons_are_inert() { let mut harness = app_with_brush(BrushSettings::default()); - click_reset(&mut harness, "Size"); - assert_eq!(harness.state().session.tool.brush, BrushSettings::default()); - assert!(harness.query_by_label("Minimum size (%)").is_some(), "the click doesn't reach the header"); + for (title, body_label, starts_open, _) in SECTIONS { + assert!(reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is disabled at the defaults"); + + click_reset(&mut harness, title); + assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + } +} + +#[test] +fn enter_on_the_focused_reset_icon_resets() { + let mut harness = app_with_brush(changed_brush()); + + reset_icon(&harness, "Size").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); + + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + let (brush, defaults) = (&harness.state().session.tool.brush, BrushSettings::default()); + assert_eq!((brush.size, brush.min_size, brush.screen_space), (defaults.size, defaults.min_size, defaults.screen_space)); } From 346a0b24f53339015d6c173d038d7059e6fa94ea Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 00:26:26 +0000 Subject: [PATCH 086/275] Bake visualization: test every branch of VertexReach::missed A table over distance starts (painted amount 1 and 2) and a cage-mesh start covers both inclusive ends of the ray range, a name mismatch and Ignore Backface both ways. Also test a request with no high poly. --- crates/bake/src/test/high_poly_reach.rs | 24 ++++++++++++ crates/bake/src/test/vertex_reach.rs | 51 +++++++++++++++++++++++++ crates/bake/src/tests.rs | 3 ++ 3 files changed, 78 insertions(+) create mode 100644 crates/bake/src/test/vertex_reach.rs diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index bb8753f8..e6d66d07 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -196,3 +196,27 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { ); } } + +#[test] +fn without_a_high_poly_no_vertex_has_a_reach() { + let low = primitives::plane(1.0, 4); + let low_bvh = Bvh::new(&low); + let bake_settings = settings(16, &[BakedMap::Normal]); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: None, + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + + let reach = HighPolyReach::new(&request).unwrap(); + assert!(reach.vertices.is_empty()); + // Any cage distances: there is no vertex to miss + assert_eq!(reach.missed(0, 0.02, 0.01), None); +} diff --git a/crates/bake/src/test/vertex_reach.rs b/crates/bake/src/test/vertex_reach.rs new file mode 100644 index 00000000..7675e8dc --- /dev/null +++ b/crates/bake/src/test/vertex_reach.rs @@ -0,0 +1,51 @@ +use crate::{RayStart, VertexReach}; +use texturecraft_geom::glam::Vec3; + +/// Cage distances in world units; every case's ray runs down the Y axis from 0.5 to -0.25 +const FRONTAL: f32 = 0.5; +const REAR: f32 = 0.25; + +/// A frontal distance a cage-mesh start must ignore: its ray starts on the cage +const IGNORED_FRONTAL: f32 = 9.0; + +/// How far past an end of the ray's range a vertex counts as outside it +const PAST_THE_END: f32 = 1e-3; + +/// A vertex at `height` above the low-poly point at the origin, its triangles facing `facing` +fn vertex(start: RayStart, height: f32, facing: Vec3, name_matches: bool) -> VertexReach { + VertexReach { low_position: Vec3::ZERO, start, high_position: Vec3::new(0.0, height, 0.0), high_facing: facing, name_matches } +} + +#[test] +fn a_vertex_is_missed_outside_the_ray_range_on_another_part_or_facing_away() { + // A painted cage amount of 2 doubles the frontal distance + let starts = [ + (RayStart::Distance { up: Vec3::Y, scale: 1.0 }, FRONTAL), + (RayStart::Distance { up: Vec3::Y, scale: 2.0 }, FRONTAL / 2.0), + (RayStart::CageMesh(Vec3::new(0.0, -FRONTAL, 0.0)), IGNORED_FRONTAL), + ]; + let (top, bottom) = (FRONTAL, -REAR); + // Height, facing, name matches, ignore backface: missed + let cases = [ + (top, Vec3::Y, true, false, false), + (bottom, Vec3::Y, true, false, false), + (0.0, Vec3::Y, true, false, false), + (top + PAST_THE_END, Vec3::Y, true, false, true), + (bottom - PAST_THE_END, Vec3::Y, true, false, true), + (0.0, Vec3::Y, false, false, true), + (0.0, Vec3::NEG_Y, true, false, false), + (0.0, Vec3::NEG_Y, true, true, true), + (0.0, Vec3::Y, true, true, false), + ]; + + for (start, frontal) in starts { + for (height, facing, name_matches, ignore_backface, missed) in cases { + let reach = vertex(start, height, facing, name_matches); + assert_eq!( + reach.missed(frontal, REAR, ignore_backface), + missed, + "{start:?} at height {height}, facing {facing}, name matches {name_matches}, ignore backface {ignore_backface}" + ); + } + } +} diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index c834da7a..abfccaac 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -29,6 +29,9 @@ mod normal_map_curvature; #[path = "test/tile_selection.rs"] mod tile_selection; +#[path = "test/vertex_reach.rs"] +mod vertex_reach; + fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings { with_rays( { From c3a59ed421996439db27424de589989a6d91c784 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 01:40:50 +0100 Subject: [PATCH 087/275] Keep the anchored brush outline when a Ctrl+right drag leaves the 2D view The outline is drawn at the press origin for the whole adjustment drag; only the system-pointer hiding depends on the pointer being in the view. Co-Authored-By: Claude Sonnet 5.5 --- crates/ui-egui/src/viewport.rs | 14 ++++++++++---- crates/ui-egui/tests/brush_cursor_2d.rs | 25 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 2443e182..9c7c8808 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1054,7 +1054,9 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, resp: &egui::Response, adjustin let Some(right) = brush_drag_button(resp).filter(|_| adjusting) else { return }; let Some(at) = ui.input(|i| i.pointer.press_origin()) else { return }; // The pointer would cover the values; the brush cursor stays where the drag began. - ui.ctx().set_cursor_icon(egui::CursorIcon::None); + if ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| resp.rect.contains(p)) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } let b = &app.session.tool.brush; let text = if right { format!("{} {:.1} {} {:.0}", tr("Size"), b.size / 0.25 * 100.0, tr("Hardness"), b.hardness * 100.0) @@ -1296,13 +1298,15 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Brush cursor: the stamp's size and hardness at the pointer, as in the 3D view. let cursor_mode = app.ui.mode == crate::state::Mode::Painting && !alt && !v_held; + let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); if cursor_mode && !path_tool && brush_tool(app.session.tool.tool) && !response.dragged_by(PointerButton::Middle) // During a drag egui keeps reporting a hover position after the pointer left the view: - // the system pointer is hidden only while the pointer is really over it. - && ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) + // the system pointer is hidden only while the pointer is really over it. A Ctrl+drag that + // changes the brush keeps its outline at the press origin wherever the pointer goes. + && (adjusting || pointer_in_view) // While a Ctrl+drag changes the brush, its cursor stays where the drag began. && let Some(hp) = if adjusting { ui.input(|i| i.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } // The view header's pickers keep the normal pointer. @@ -1310,7 +1314,9 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin { // The stamp's radius as `continue_stroke_uv` paints it, including a light pen's smaller footprint. let r = (to_screen(app.session.tool.brush.uv_stamp_radius(pen_pressure(ui)), 0.0).x - to_screen(0.0, 0.0).x).abs().max(1.5); - ui.ctx().set_cursor_icon(egui::CursorIcon::None); + if pointer_in_view { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + } brush_cursor_2d(&painter, hp, r, app.session.tool.brush.hardness); } brush_readout(app, ui, &response, adjusting); diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index 3b7cca9c..8f790099 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -116,3 +116,28 @@ fn dragging_out_of_the_2d_view_brings_the_system_pointer_back() { h.event(Event::PointerButton { pos: outside, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }); h.run_steps(2); } + +#[test] +fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { + let mut h = harness(); + let c = egui::pos2(800.0, 480.0); + let ctrl = egui::Modifiers::COMMAND; + h.hover_at(c); + h.run_steps(2); + h.event(Event::ModifiersChanged(ctrl)); + h.event(Event::PointerButton { pos: c, button: egui::PointerButton::Secondary, pressed: true, modifiers: ctrl }); + h.run_steps(2); + // Drag a little inside the view: the outline is anchored and the pointer hidden. + h.hover_at(c + egui::vec2(10.0, 0.0)); + h.run_steps(3); + assert_eq!(rings_at(&h, c).len(), 1, "anchored outline while the pointer is in the view"); + assert_eq!(cursor(&h), CursorIcon::None); + // Carry the pointer out of the view: the outline stays at the anchor, the system pointer is back. + h.hover_at(egui::pos2(2.0, 2.0)); + h.run_steps(3); + assert_eq!(rings_at(&h, c).len(), 1, "the outline stays at the press origin outside the view"); + assert_ne!(cursor(&h), CursorIcon::None, "outside the view the pointer is visible"); + h.event(Event::PointerButton { pos: egui::pos2(2.0, 2.0), button: egui::PointerButton::Secondary, pressed: false, modifiers: ctrl }); + h.event(Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); +} From e2a69c4d121de6260443b871819e3cf077e2625d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:15:26 +0000 Subject: [PATCH 088/275] Filter picker: Add filter opens the picker, same-id set edits in place Add filter still adds a neutral HSL filter, and its slot now opens the picker straight away; Esc keeps the HSL and one undo removes it. effect.set naming the filter the effect already is edits its parameters instead of rebuilding it from defaults. The picker's filter list is worked out once. The slot cuts long names short between the thumbnail and the caret, stays highlighted while its picker is open and shows an outline while it has keyboard focus. More engine tests: a swap on a mask, an explicit name, refused swaps leave no change and no undo step. --- crates/engine/src/filter_lib.rs | 7 +++ crates/engine/src/mask_cmds.rs | 12 ++++- crates/engine/tests/filter_swap.rs | 61 ++++++++++++++++++++++++- crates/ui-egui/src/dock.rs | 12 ++++- crates/ui-egui/src/filter_slot.rs | 65 +++++++++++++++++++++------ crates/ui-egui/tests/filter_picker.rs | 54 ++++++++++++++++++++-- 6 files changed, 190 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 0f0fd952..7856f565 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -26,6 +26,13 @@ impl FilterDef { } } +/// The library entries that build filter effects, in shelf order, worked out once +pub fn filter_effects() -> &'static [&'static FilterDef] { + static FILTER_EFFECTS: std::sync::LazyLock> = + std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect()); + &FILTER_EFFECTS +} + const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef { FilterDef { id, label, group, mask } } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index bd545fbc..97003298 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", has_layer, set ), @@ -435,7 +435,9 @@ fn set(s: &mut Session, p: &Value) -> Result { _ => None, }; + // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(p, "filter") { + Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(s, effect) == Some(def.id)) => None, Some(filter) => Some(swapped_filter(s, effect, filter, p)?), None => None, }; @@ -492,6 +494,14 @@ fn set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The library id of the filter effect `effect` is, if it is one +fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { + match &s.doc.project.effect(effect)?.1.kind { + EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id), + _ => None, + } +} + /// Filter `id` built with `p` and its label, to replace filter effect `effect` fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> { const CMD: &str = "effect.set"; diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index 87341c60..ed39fa6e 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -78,7 +78,65 @@ fn a_mask_refuses_a_content_only_filter() { assert!(err.to_string().contains("not on masks"), "{err}"); assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert))); - execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).expect("a mask takes a filter that works on masks"); +} + +#[test] +fn a_mask_filter_swaps_in_place_on_the_mask() { + let mut s = session(); + let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap(); + + execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, swapped); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind); + assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4)); + let layer = s.selected_layer().unwrap(); + let mask_order: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask_order, vec![below, swapped, above]); +} + +#[test] +fn naming_the_current_filter_edits_it_in_place() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap(); + + let blur = effect(&s, id); + assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind); +} + +#[test] +fn a_name_given_with_the_swap_wins() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); + + execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap(); + + let swapped = effect(&s, id); + assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind); + assert_eq!(swapped.name, "Edges"); +} + +#[test] +fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { + let mut s = session(); + let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"})); + execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); + let before = effect(&s, id); + + for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); + } + + assert_eq!(effect(&s, id), before); + // The last step is still the blend, opacity and name edit + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect(&s, id).name, "Invert"); } #[test] @@ -88,6 +146,7 @@ fn only_filter_effects_swap_and_only_to_filters() { let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"})); assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect"); + assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill"); assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err()); assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert))); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 13604e91..4931d071 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -19,7 +19,7 @@ use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; -/// The filter Add filter adds: at its defaults it changes nothing until the slot swaps it +/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it const NEW_FILTER: &str = "hsl"; const FILTER_SWATCH_WIDTH: f32 = 36.0; const FILTER_HINT_SIZE: f32 = 10.5; @@ -240,7 +240,15 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { if app.session.selected_layer() != Some(layer.id) { app.run("layer.select", json!({"layer": layer.id.0})); } - app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + + let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); + // The neutral filter is a placeholder: its slot opens the picker to choose the real one + if command == "effect.add.filter" + && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) + { + crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); + } + ui.close(); } } diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 7a143612..bf169e22 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -4,7 +4,7 @@ use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::{Filter, LayerId}; -use texturecraft_engine::filter_lib::{FILTERS, find}; +use texturecraft_engine::filter_lib::{filter_effects, find}; use crate::TextureCraftApp; use crate::i18n::tr; @@ -13,9 +13,11 @@ use crate::resource_picker_item::ResourcePickerItem; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; use crate::thumbs::Thumbs; +use crate::widgets::elided; const SLOT_HEIGHT: f32 = 52.0; const SLOT_ROUNDING: f32 = 3.0; +const BORDER_WIDTH: f32 = 1.0; const THUMBNAIL_SIZE: f32 = 40.0; const THUMBNAIL_INSET: f32 = 6.0; const CAPTION_FONT_SIZE: f32 = 11.0; @@ -24,6 +26,8 @@ const NAME_FONT_SIZE: f32 = 13.0; const LINE_GAP: f32 = 15.0; const CARET_INSET: f32 = 14.0; const CARET_FONT_SIZE: f32 = 14.0; +/// Gap between the slot and its keyboard focus outline +const FOCUS_MARGIN: f32 = 2.0; /// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) { @@ -35,17 +39,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name)); - paint(ui, rect, response.hovered(), thumbnail.as_ref(), name); let popup = ui.make_persistent_id(("filter_picker", effect)); - if response.clicked() { + let open_requested = take_open_request(&ctx, effect); + + if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) { resource_picker::toggle(&ctx, popup); } + let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); + paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + let items = |thumbs: &mut Thumbs| { - FILTERS + filter_effects() .iter() - .filter(|def| def.is_filter_effect() && (def.mask || !on_mask)) + .filter(|def| def.mask || !on_mask) .map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) }) .collect() }; @@ -55,6 +63,26 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: } } +/// Has the slot of filter effect `effect` open its picker if it shows this frame or the next, as Add filter does for the filter it adds +pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) { + let frame = ctx.cumulative_frame_nr(); + ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame))); +} + +/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses +fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { + let frame = ctx.cumulative_frame_nr(); + let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id())); + + // Properties can draw before or after the menu that asked, so a request lives for this frame and the next + request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1) +} + +/// Where the effect whose slot should open its picker waits +fn open_request_id() -> egui::Id { + egui::Id::new("filter_slot_open_request") +} + /// Whether filter effect `effect` sits in a mask rather than the layer content fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { let project = &app.session.doc.project; @@ -62,22 +90,31 @@ fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// The slot's box: thumbnail, "Filter" over the name, caret -fn paint(ui: &Ui, rect: Rect, hovered: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { +/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret +fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { let tk = Tokens::get(ui.ctx()); let painter = ui.painter(); - let (fill, border) = if hovered { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; - painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(1.0, border), egui::StrokeKind::Inside); + let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); + if focused { + painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(texture) = thumbnail { let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); } - let center = rect.center(); - painter.text(center - vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, tr("Filter"), FontId::proportional(CAPTION_FONT_SIZE), tk.text_dim); - painter.text(center + vec2(0.0, LINE_GAP * 0.5), Align2::CENTER_CENTER, name, FontId::proportional(NAME_FONT_SIZE), tk.text_strong); + // Long names are cut short rather than run under the thumbnail or the caret + let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; + let text_right = rect.right() - CARET_INSET * 2.0; + let text_center_x = (text_left + text_right) * 0.5; + let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + for (text, size, color, offset) in lines { + let galley = elided(painter, text, size, color, text_right - text_left); + painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); + } - let caret_color = if hovered { tk.text } else { tk.text_dim }; - painter.text(pos2(rect.right() - CARET_INSET, center.y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); + let caret_color = if highlighted { tk.text } else { tk.text_dim }; + painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); } diff --git a/crates/ui-egui/tests/filter_picker.rs b/crates/ui-egui/tests/filter_picker.rs index 31daef69..819dcc25 100644 --- a/crates/ui-egui/tests/filter_picker.rs +++ b/crates/ui-egui/tests/filter_picker.rs @@ -66,16 +66,64 @@ fn escape_closes_the_picker_without_changes() { assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); } -#[test] -fn add_filter_adds_a_filter_and_selects_it() { - let (mut harness, _) = app_with_invert(); +/// Opens the wand's Add effect menu and clicks Add filter +fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); harness.run_steps(3); harness.get_by_label("Add filter").click(); harness.run_steps(3); +} + +#[test] +fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot"); + assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter"); + + // The search field has the focus, and a search brings Sharpen into view + harness.event(egui::Event::Text("sharp".into())); + harness.run_steps(3); + harness.get_by_label("Sharpen").click(); + harness.run_steps(3); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added)); +} + +#[test] +fn escape_after_add_filter_keeps_the_neutral_filter() { + let (mut harness, _) = app_with_invert(); + add_filter_from_the_wand(&mut harness); + assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") }; + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + + harness.state_mut().run("edit.undo", Value::Null); + assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter"); +} + +#[test] +fn add_filter_on_a_mask_adds_it_to_the_mask() { + let (mut harness, _) = app_with_invert(); + let layer = harness.state().session.selected_layer().unwrap(); + // A new mask becomes the selected target, so the wand adds to it + harness.state_mut().run("mask.add.white", json!({"layer": layer.0})); + harness.run_steps(3); + + add_filter_from_the_wand(&mut harness); + + let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") }; + let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask"); + assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added)); + assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open"); + assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters"); } From c39d95b4c8a53da5791d513c76c8ae00e761de89 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:21:42 +0000 Subject: [PATCH 089/275] Filter swap: test that invalid parameters for the new filter are refused --- crates/engine/tests/filter_swap.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/tests/filter_swap.rs b/crates/engine/tests/filter_swap.rs index ed39fa6e..27103ab4 100644 --- a/crates/engine/tests/filter_swap.rs +++ b/crates/engine/tests/filter_swap.rs @@ -129,7 +129,12 @@ fn a_refused_swap_changes_nothing_and_adds_no_undo_step() { execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap(); let before = effect(&s, id); - for refused in [json!({"effect": id.0, "filter": "grayscale"}), json!({"effect": id.0, "filter": "nope"}), json!({"effect": id.0, "filter": "levels"})] { + for refused in [ + json!({"effect": id.0, "filter": "grayscale"}), + json!({"effect": id.0, "filter": "nope"}), + json!({"effect": id.0, "filter": "levels"}), + json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}), + ] { assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}"); } From 45ab0f42d9b26600f710dbf87e6a74aed7b35bfc Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:23:12 +0000 Subject: [PATCH 090/275] Image drop: clearer decal specs, layer/effect check, menu edge cases layer.add.decal's spec says the other-set selection is for x/y only and documents the maskEffect it returns; layer.decal.set's says image keeps the decal's channel or mask and refuses an effect given with another layer. The drop menu's channel list scrolls past 60% of the window. A waiting drop lets go once its menu goes undrawn (the 3D view hidden), and the click that closes the menu no longer moves a decal being placed. --- crates/engine/src/decal_cmds.rs | 10 ++++- crates/engine/tests/painter_gaps.rs | 3 ++ crates/ui-egui/src/decal_drop.rs | 39 +++++++++++++---- crates/ui-egui/src/viewport.rs | 3 +- crates/ui-egui/tests/shelf_drop.rs | 65 +++++++++++++++++++++++++++-- 5 files changed, 105 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index f3ec8b28..bd25c185 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer? | effect?: a mask fill effect id (a decal placed as a mask), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -185,6 +185,12 @@ fn set(s: &mut Session, p: &Value) -> Result { Some(effect) => s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?, None => s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|layer| layer.id).ok_or_else(|| bad(cmd, "no layer"))?, }; + if let (Some(effect), Some(layer)) = (effect, u64p(p, "layer")) + && layer != id.0 + { + return Err(bad(cmd, format!("effect {} is not in layer {layer}", effect.0))); + } + let mut decal = decal_of(s, cmd, id, effect)?; let mesh_diagonal = mesh_size(s); if let Some((center, normal, ts)) = placement(s, cmd, p, true)? { diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index c150de79..66f19612 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -408,6 +408,9 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); + let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); + assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); } /// A decal's new image stays in the channel the decal was placed in, read as gray there diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 1dfba5f2..4c2fd6db 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -9,6 +9,9 @@ use crate::i18n::tr; /// What the menu offers besides the texture set's channels: a new fill layer masked by the image const MASK_CHOICE: &str = "mask"; +/// The most of the window's height the channel list takes before it scrolls +const MENU_MAX_HEIGHT_SHARE: f32 = 0.6; + /// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked #[derive(Clone)] pub struct DecalDrop { @@ -32,18 +35,33 @@ impl DecalDrop { /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits pub fn open(self, ui: &Ui) { - ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), (self, frame))); } /// Whether a drop waits for its menu pick: the views don't paint meanwhile, so the click that dismisses the menu paints nothing pub fn waiting(ctx: &egui::Context) -> bool { - ctx.data(|data| data.get_temp::(Self::menu_id()).is_some()) + Self::current(ctx).is_some() + } + + /// The waiting drop; one whose menu went undrawn for a frame (the 3D view was hidden) is dropped instead of blocking the views + fn current(ctx: &egui::Context) -> Option { + let frame = ctx.cumulative_frame_nr(); + let (drop, menu_frame) = ctx.data(|data| data.get_temp::<(DecalDrop, u64)>(Self::menu_id()))?; + if frame > menu_frame + 1 { + ctx.data_mut(|data| data.remove::<(DecalDrop, u64)>(Self::menu_id())); + return None; + } + + Some(drop) } /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); - let Some(drop) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; + let Some(drop) = Self::current(ui.ctx()) else { return }; + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(id, (drop.clone(), frame))); let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); let mut picked = None; @@ -58,15 +76,20 @@ impl DecalDrop { picked = Some(MASK_CHOICE); } ui.separator(); - for channel in channels { - if ui.button(tr(channel.label())).clicked() { - picked = Some(channel.id()); + + // Many channels scroll instead of running off the window + let max_height = ui.ctx().content_rect().height() * MENU_MAX_HEIGHT_SHARE; + egui::ScrollArea::vertical().max_height(max_height).show(ui, |ui| { + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } } - } + }); }); if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { - ui.ctx().data_mut(|data| data.remove::(id)); + ui.ctx().data_mut(|data| data.remove::<(DecalDrop, u64)>(id)); } let Some(channel) = picked else { return }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index ec58ce89..f0229e25 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -542,11 +542,12 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // Decal placement: a click moves the decal being placed there + // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt + && !DecalDrop::waiting(ui.ctx()) && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 36a89de6..b278a397 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -8,6 +8,7 @@ use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; +use texturecraft_ui_egui::state::ViewLayout; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; @@ -82,14 +83,20 @@ fn a_material_dropped_on_the_background_changes_nothing() { assert_eq!(harness.state().session.history_labels().len(), history); } -/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) -fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { - let mut harness = sample_app(); - harness.state_mut().ui.prefs.language = "en".into(); +/// Import a small white image and return its resource name +fn import_white_image(harness: &mut Harness<'_, TextureCraftApp>) -> String { let mut png = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); harness.run_steps(2); + name +} + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let name = import_white_image(&mut harness); let position = point_over(&harness, position_over); drop_asset(&mut harness, Asset::Texture(name), position); @@ -142,3 +149,53 @@ fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { let (harness, position) = drop_image(None); assert!(!menu_open(&harness, position), "the background opens no menu"); } + +#[test] +fn hiding_the_3d_view_lets_go_of_a_waiting_image_drop() { + let (mut harness, position) = drop_image(Some(1)); + assert!(menu_open(&harness, position)); + + // Only the 3D view shows the menu, so a 2D-only layout would otherwise leave the views blocked + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(3); + + assert!(!menu_open(&harness, position), "the drop lapsed while its menu was hidden"); +} + +#[test] +fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { + let (mut harness, position) = drop_image(Some(1)); + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + let decal_layer = harness.state().session.selected_layer().unwrap(); + harness.state_mut().placing_decal = Some(decal_layer); + + let image = import_white_image(&mut harness); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); + + // A point on the same set, away from the menu + let rect = harness.state().viewport_rect; + let elsewhere = (1..(rect.width() / SEARCH_STEP) as usize) + .map(|step| Pos2::new(rect.max.x - step as f32 * SEARCH_STEP, position.y)) + .find(|point| { + let app = harness.state(); + let local = *point - rect.min; + point.distance(position) > MENU_REACH * 2.0 && app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport) == Some(1) + }) + .unwrap(); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); +} From 8334230ed15d4d5c0e6009a642f94d0ea547e6be Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:23:52 +0100 Subject: [PATCH 091/275] test(formats): a late entry error with all earlier entries fine is returned Co-Authored-By: Claude Opus 5.5 --- crates/formats/src/project_file/tests.rs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 1f85d26c..e5952be9 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -452,6 +452,32 @@ fn a_failing_entry_is_an_error_not_a_hang() { } } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_late_failing_entry_after_good_ones_is_its_own_error() { + // Only the last entry fails and nothing panics, so the error must come from that entry. + for (workers, budget) in [(4usize, 25u64), (4, u64::MAX), (2, 1)] { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| if i == 9 { Err(std::io::Error::other("late boom")) } else { w.write_all(&[i as u8; 100]) }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + let res = entries::parallel::write(&mut zip, list, workers, budget); + let _ = tx.send(res.map_err(|e| matches!(&e, FormatError::Io(io) if io.to_string() == "late boom"))); + }); + let res = + rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|e| panic!("save did not finish ({e}): {workers} workers, budget {budget}")); + assert_eq!(res, Err(true), "{workers} workers, budget {budget}"); + } +} + #[test] fn recovery_skips_unsupported_baked_map_entries() { let expected = sample().pf; From 284cb7d125aa98791d00e529b40b4111cb8eaa90 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:25:04 +0000 Subject: [PATCH 092/275] Refuse host paths in files entries for automation textureSet.meshMap.import takes its paths in files[].path, which authorize_command did not look at, so a control client could import an image from outside --read-root. Treat a path or dir in any files entry like a top-level one, and document that automation imports baked maps through resource_import plus textureSet.meshMap.set. --- crates/automation/src/workspace.rs | 35 ++++++++++++++++++++++-------- docs/control-protocol.md | 6 ++--- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 2015c090..1061db2d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -127,20 +127,20 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { AutomationError::Io(format!("{op} `{path}` failed: {e}")) } -/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`, -/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped -/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command -/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is -/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the -/// embedded mesh). +/// Host keys a command reads or writes a file through, at the top level or in each `files` entry +const HOST_PATH_KEYS: [&str; 2] = ["path", "dir"]; + +/// Refuses engine commands that would reach host paths around the workspace roots, so clients use the workspace tools pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); - let ok = match id { + let has_path = names_host_path(params) || params.get("files").and_then(Value::as_array).is_some_and(|files| files.iter().any(names_host_path)); + + // `file.save` is refused even without a path: a headless session's path is workspace-relative, not a host path + let allowed = match id { "file.close" | "file.removeUnused" => true, "file.reimportMesh" => !has_path, _ => !id.starts_with("file.") && !has_path, }; - if ok { + if allowed { Ok(()) } else { Err(bad(format!( @@ -149,6 +149,11 @@ pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError } } +/// Whether `params` names a host path or folder at its own top level +fn names_host_path(params: &Value) -> bool { + HOST_PATH_KEYS.iter().any(|key| params.get(key).is_some_and(|value| !value.is_null())) +} + #[cfg(test)] mod tests { use super::*; @@ -243,6 +248,18 @@ mod tests { assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok()); } + #[test] + fn nested_file_paths_are_denied() { + let outside_file = json!({"files": [{"path": "/etc/x_ao.png", "map": "ao"}]}); + assert!(authorize_command("textureSet.meshMap.import", &outside_file).is_err()); + + let one_of_many = json!({"files": [{"map": "ao"}, {"path": "/etc/x_ao.png"}]}); + assert!(authorize_command("textureSet.meshMap.import", &one_of_many).is_err()); + + let no_paths = json!({"files": [{"map": "ao"}, {"path": null}]}); + assert!(authorize_command("textureSet.meshMap.import", &no_paths).is_ok()); + } + /// Every registry command documenting a host path must be classified (fails when a new /// path-taking command is added without an automation policy). #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 734036ca..079788be 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -153,8 +153,8 @@ print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1 File › Save. Through `command_run`, every `file.*` command but `file.close` and `file.removeUnused` (and -`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir` (`resource.import`, -`material.save`, `material.load`, …), in both modes: use the workspace tools below. `resource.text` +`file.reimportMesh` without a `path`) is refused, and so is any command given a `path` or `dir`, at the top level or in +a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. | Tool | Params | Notes | @@ -170,7 +170,7 @@ takes a font family, not a path: it reads only the system's font folders. | `mesh_reimport` | `{path?, preserveStrokes?}` | Reimport the mesh from a file, or (no path) from the project's own copy; bridge mode supports only the latter | | `mesh_export` | `{path, format?}` | The mesh as obj, glb, usda, usdc or usdz below the write root (obj: its .mtl and textures, usda / usdc: textures next to it) → `{path, textures?}` | | `bake_mesh_add` | `{path, cage?}` | Add a high-definition mesh for baking, or set the cage → `{name, meshes}` | -| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); many baked map files at once, matched to sets and maps by file name: `textureSet.meshMap.import {files: [{path, map?}]}` | +| `resource_import` | `{path}` | Image resource (png, jpg, tga, tif, bmp, webp, exr, hdr) → its name, for `layer.add.image` / `tool.stencil`, or as a mesh map instead of baking it: `textureSet.meshMap.set {ts?, map, image}` (`textureSet.meshMap.clear {ts?, map}` empties the slot); call it once per baked map file (the desktop app's `textureSet.meshMap.import`, which takes host paths, is refused through `command_run`) | | `material_save` | `{path, layer?, name?}` | A layer or folder as a `.tcmat` smart material below the write root | | `material_load` | `{path}` | Add a `.tcmat` smart material, a MaterialCraft `.mcmat` material or a `.mcraft` package above the selection | | `textures_export` | `{dir, preset?, ts?, format?, padding?, size?}` | Writes files below the write root | From 6d3f7c216ddf478c8c3cb9227f759604653bf4f1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:26:54 +0000 Subject: [PATCH 093/275] Levels: paint the active handle on top Handles are painted with the dragged or hovered one last, so the handle drawn on top is the one the pointer grabs. Value labels keep the active handle first so its value wins over an overlapping neighbour's. --- crates/ui-egui/src/levels_editor.rs | 19 ++++++++++------ crates/ui-egui/tests/levels_editor.rs | 31 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 55e2d53d..575d734e 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -194,18 +194,17 @@ fn paint_output_gradient(ui: &Ui, strip: Rect) { painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); } -/// Each handle filled with its gray and its value beside it, the active one first and overlapping values left out +/// Each handle filled with its gray, the active one on top, and its value beside it, overlapping values left out fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels, typing: Option) { let track = track(rect); let tokens = Tokens::get(ui.ctx()); let painter = ui.painter(); - let font = egui::FontId::proportional(VALUE_FONT_SIZE); let is_active = |response: &Response| response.dragged() || response.hovered(); - let mut printed: Vec = Vec::new(); - let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); - by_priority.sort_by_key(|(_, response)| !is_active(response)); - for &(handle, ref response) in by_priority { + // Active handles last, so the one on top is the one the pointer grabs + let mut by_paint_order: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_paint_order.sort_by_key(|(_, response)| is_active(response)); + for &(handle, ref response) in by_paint_order { let x = track_x(&track, handle.position(levels)); let fill = match handle { LevelsHandle::InputLow => Color32::BLACK, @@ -222,6 +221,14 @@ fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Res }; let points_down = LevelsHandle::INPUT.contains(&handle); painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.0, outline))); + } + + // Active values first, so a neighbour's overlapping value gives way to them + let font = egui::FontId::proportional(VALUE_FONT_SIZE); + let mut printed: Vec = Vec::new(); + let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_priority.sort_by_key(|(_, response)| !is_active(response)); + for &(handle, ref response) in by_priority { if typing == Some(handle) { continue; } diff --git a/crates/ui-egui/tests/levels_editor.rs b/crates/ui-egui/tests/levels_editor.rs index c09246c4..a8aa7fc3 100644 --- a/crates/ui-egui/tests/levels_editor.rs +++ b/crates/ui-egui/tests/levels_editor.rs @@ -12,6 +12,12 @@ use texturecraft_ui_egui::TextureCraftApp; const HISTOGRAM_BUCKETS: usize = 64; const AUTO_MIN_SHARE: f64 = 0.001; +/// Labels of the five handles +const HANDLE_LABELS: [&str; 5] = ["Input low", "Input high", "Gamma", "Output low", "Output high"]; + +/// Corners of a handle's pentagon pointer +const HANDLE_POINTER_CORNERS: usize = 5; + /// A clouds mask under a levels effect added by `command` with `params`, selected, and its id fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -245,3 +251,28 @@ fn the_levels_filter_shows_the_same_editor() { harness.get_by_role_and_label(Role::Button, button); } } + +/// Bounds of the handle pointers in paint order, the last one drawn on top +fn painted_handles(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let centres = HANDLE_LABELS.map(|label| handle(harness, label)); + let pointers = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Path(path) if path.closed && path.points.len() == HANDLE_POINTER_CORNERS => Some(egui::Rect::from_points(&path.points)), + _ => None, + }); + pointers.filter(|bounds| centres.iter().any(|centre| bounds.expand(1.0).contains(*centre))).collect() +} + +#[test] +fn the_hovered_handle_is_painted_on_top() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert_eq!(painted_handles(&harness).len(), HANDLE_LABELS.len(), "every handle is painted once"); + + for label in HANDLE_LABELS { + let at = handle(&harness, label); + harness.hover_at(at); + harness.run_steps(2); + + let on_top = painted_handles(&harness).last().copied().unwrap(); + assert!(on_top.expand(1.0).contains(at), "{label} is painted last while hovered: {on_top:?} vs {at:?}"); + } +} From dd7bb51bd531205ace004614e3238a8196d5082e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:27:58 +0000 Subject: [PATCH 094/275] Bake visualization: pick up the reach even when nothing is drawn The reach job was only polled while the high poly was drawn, so leaving bake mode or hiding the high poly mid-reach kept busy() true and the view repainting every frame. Poll it at the start of every sync. The resend test now waits for the rebuilt cage's reach before checking that a resend starts none, so it no longer depends on thread timing. --- .../ui-egui/src/bake_scene/bake_scene_link.rs | 30 +++++++++++++++++-- crates/ui-egui/src/bake_scene/reach_link.rs | 27 +++++++++-------- 2 files changed, 43 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index 7f4459c6..b9cecaa9 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -47,6 +47,8 @@ impl BakeSceneLink { /// Add to `out` what the GPU needs to draw `visualization` this frame pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + self.reach.poll(); + let Some(visualization) = visualization else { return }; if visualization.high_poly { @@ -117,6 +119,10 @@ mod tests { const EVERYTHING: BakeVisualization = BakeVisualization { high_poly: true, cage: true, uv_seams: true, low_poly: true, only_set: None }; + /// How long a test waits for the reach worker: frames, and the pause between them + const WAIT_FRAMES: usize = 2000; + const WAIT_FRAME_PAUSE: std::time::Duration = std::time::Duration::from_millis(5); + /// The sample project with a high poly a little outside its low poly fn session() -> Session { const HIGH_POLY_OFFSET: f32 = 0.02; @@ -143,11 +149,11 @@ mod tests { /// Sync until the reach worked out on the worker thread colors the high poly; the share of vertices drawn red fn red_share(link: &mut BakeSceneLink, session: &Session, visualization: BakeVisualization) -> f32 { - for _ in 0..2000 { + for _ in 0..WAIT_FRAMES { if let Some((_, missed)) = sync(link, session, visualization).bake_high_missed { return missed.iter().sum::() / missed.len().max(1) as f32; } - std::thread::sleep(std::time::Duration::from_millis(5)); + std::thread::sleep(WAIT_FRAME_PAUSE); } panic!("the reach never arrived"); } @@ -175,6 +181,8 @@ mod tests { texturecraft_engine::execute(&mut session, "bake.settings", &json!({"ts": "all", "averageNormals": false})).unwrap(); let rebuilt = sync(&mut link, &session, EVERYTHING); assert_ne!(rebuilt.bake_cages.first().unwrap().2, *topology, "new settings rebuild the cage"); + // The rebuilt cage starts a new reach: let it finish so the last check sees only what the resend starts + red_share(&mut link, &session, EVERYTHING); link.resend(); let resent = sync(&mut link, &session, EVERYTHING); @@ -185,6 +193,24 @@ mod tests { assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn a_reach_finishes_while_nothing_is_drawn() { + let session = session(); + let no_high_poly = BakeVisualization { high_poly: false, ..EVERYTHING }; + for hidden in [None, Some(no_high_poly)] { + let mut link = BakeSceneLink::default(); + sync(&mut link, &session, EVERYTHING); + assert!(link.busy(), "the first frame starts working out the reach"); + + let finished = (0..WAIT_FRAMES).any(|_| { + std::thread::sleep(WAIT_FRAME_PAUSE); + link.sync(&session, hidden, &mut SceneSync::default()); + !link.busy() + }); + assert!(finished, "the view stops redrawing for a reach once it is done: {hidden:?}"); + } + } + #[test] fn the_red_follows_the_distances_and_the_selected_set() { let (mut session, mut link) = (session(), BakeSceneLink::default()); diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index 45527522..cdf0ca58 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -34,6 +34,21 @@ impl ReachLink { self.shown = None; } + /// Pick up the reach once the worker finishes; runs every frame, even when nothing is drawn, so `busy` clears + pub(super) fn poll(&mut self) { + let Some(job) = &self.job else { return }; + + match job.try_recv() { + Ok(reach) => { + self.reach = reach; + self.shown = None; + self.job = None; + } + Err(TryRecvError::Disconnected) => self.job = None, + Err(TryRecvError::Empty) => {} + } + } + /// Start a new reach when the high poly (sent under `high_id`) or a set's inputs changed, and color the high poly when the reach or the distances changed pub(super) fn sync(&mut self, session: &Session, high_id: u64, only_set: Option, out: &mut SceneSync) { let set_count = session.doc.project.texture_sets.len(); @@ -53,18 +68,6 @@ impl ReachLink { (self.keys, self.high_id) = (keys, high_id); } - if let Some(job) = &self.job { - match job.try_recv() { - Ok(reach) => { - self.reach = reach; - self.shown = None; - self.job = None; - } - Err(TryRecvError::Disconnected) => self.job = None, - Err(TryRecvError::Empty) => {} - } - } - // Colors wait for the reach being worked out: the old ones stay until it arrives if self.job.is_some() { return; From 8cdd5dc296eead1c9d6bc884c867bbe9a342294e Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:28:25 +0000 Subject: [PATCH 095/275] Filter slot: use Id::unique for the open request (Id::new is deprecated) --- crates/ui-egui/src/filter_slot.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index bf169e22..172017d9 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -80,7 +80,7 @@ fn take_open_request(ctx: &egui::Context, effect: u64) -> bool { /// Where the effect whose slot should open its picker waits fn open_request_id() -> egui::Id { - egui::Id::new("filter_slot_open_request") + egui::Id::unique("filter_slot_open_request") } /// Whether filter effect `effect` sits in a mask rather than the layer content From aecf9cd7ab4a7cf5c80e1a6703b45d6f8cc4d1b7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:29:28 +0100 Subject: [PATCH 096/275] Use as_chunks in the bake_tiles tests main added Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/bake_tiles.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/bake_tiles.rs b/crates/engine/tests/bake_tiles.rs index 3f000321..a7f3f1a0 100644 --- a/crates/engine/tests/bake_tiles.rs +++ b/crates/engine/tests/bake_tiles.rs @@ -57,7 +57,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { session.apply_bake(0, output).unwrap(); let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; - for row in pixels.chunks_exact(64) { + for row in pixels.as_chunks::<64>().0 { assert!(row[..32].iter().all(|value| *value > 0.99)); assert!(row[32..].iter().all(|value| *value == 0.25)); } @@ -81,7 +81,7 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { let baked = &session.doc.baked[&0]; assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64)); - for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) { + for row in baked.maps[&BakedMap::AmbientOcclusion].as_chunks::<128>().0 { assert!(row[..64].iter().all(|value| *value > 0.99)); assert!(row[64..].iter().all(|value| *value == 0.25)); } From cbe3c86acb76e6ddf98b4b77dd4a5eda836ee5a1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:32:06 +0000 Subject: [PATCH 097/275] Curvature detail: full-strength block borders, neutral raw curvature, stricter sizes Divide each blurred detail size by the share of the blur window inside its UV tile block, so texels near a block or map edge keep their strength instead of fading toward zero. Raw mode reads mid gray when there is no curvature to sample. The size cache keeps one layout per curvature map. Mask previews of hidden layers build their sizes once before the tiles run in parallel. effect.set rejects a sizes array with a non-numeric entry. --- crates/compose/src/curvature_sizes.rs | 77 ++++++++++++++++++++++++--- crates/compose/src/eval.rs | 53 ++++++++++++++---- crates/engine/src/mask_cmds.rs | 8 +-- crates/engine/tests/session.rs | 2 + 4 files changed, 120 insertions(+), 20 deletions(-) diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index 7b6014e0..0d9c3bc9 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -8,7 +8,7 @@ use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail}; use texturecraft_texel::dilate::{DilationMap, NONE}; use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE}; -use crate::eval::{Inputs, blur}; +use crate::eval::{BLUR_BOX_PASSES, Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { @@ -107,6 +107,8 @@ fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Opt fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + // One layout per curvature map: sizes built for an earlier tile layout or working size are dropped with it + cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature))); let sizes = Arc::new(sizes); cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); return sizes; @@ -138,20 +140,47 @@ fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { covered.into_iter().map(AtomicBool::into_inner).collect() } -/// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. -fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { +/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it. +fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) { + let rows = top..top + region_height; let mut block: Vec = - (y0..y0 + h).flat_map(|y| (x0..x0 + w).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); - blur(&mut block, w as usize, h as usize, radius as usize); + rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect(); + blur(&mut block, region_width as usize, region_height as usize, radius as usize); - for (row, values) in block.chunks(w as usize).enumerate() { - let start = ((y0 + row as u32) * width + x0) as usize; + // The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength + let column_weights = window_inside(region_width as usize, radius as usize); + let row_weights = window_inside(region_height as usize, radius as usize); + for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) { + for (value, column_weight) in values.iter_mut().zip(&column_weights) { + *value /= row_weight * column_weight; + } + } + + for (row, values) in block.chunks(region_width as usize).enumerate() { + let start = ((top + row as u32) * width + left) as usize; if let Some(target) = data.get_mut(start..start + values.len()) { target.copy_from_slice(values); } } } +/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in. +fn window_inside(length: usize, radius: usize) -> Vec { + let window = (2 * radius + 1) as f64; + let mut weights = vec![1.0f64; length]; + for _ in 0..BLUR_BOX_PASSES { + let running_totals: Vec = std::iter::once(0.0) + .chain(weights.iter().scan(0.0, |total, weight| { + *total += weight; + Some(*total) + })) + .collect(); + let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0); + weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect(); + } + weights.into_iter().map(|weight| weight as f32).collect() +} + /// `data` averaged over `step × step` squares (the last ones clipped to the map). fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32) -> CurvatureSizeLevel { let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step)); @@ -190,6 +219,40 @@ mod tests { } } + #[test] + fn uniform_curvature_keeps_its_strength_at_block_borders() { + let (map_width, map_height): (u32, u32) = (256, 256); + // Curvature 0.8 reads 0.3 above the neutral 0.5 at every size + const CURVATURE: f32 = 0.8; + let expected = CURVATURE - 0.5; + let curvature = vec![CURVATURE; (map_width * map_height) as usize]; + let covered = vec![true; curvature.len()]; + let block = (map_width / 2, map_height); + let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The map's corner, then the last texel of the left block and the first of the right one, halfway down + let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)]; + for level in sizes.levels.iter().flatten() { + for (x, y) in border_texels { + assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y)); + } + } + } + + #[test] + fn a_new_layout_replaces_the_sizes_of_the_old_one() { + let curvature = Arc::new(vec![0.5; 16]); + let scales = BlockScales::default(); + let entries_for_curvature = || { + let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count() + }; + + store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() }); + store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() }); + assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached"); + } + #[test] fn sizes_built_on_demand_match_a_full_build() { let map_size: u32 = 64; diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index e8fd391b..3a30c7d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -443,6 +443,9 @@ pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32); } +/// The box blurs `blur` runs along each axis +pub(crate) const BLUR_BOX_PASSES: usize = 3; + /// Three box blurs of radius `r` along every row (`w` long) of `data`. fn blur_rows(data: &mut [i64], w: usize, r: usize) { if w == 0 { @@ -450,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) { } data.par_chunks_mut(w).for_each(|row| { let mut tmp = vec![0i64; row.len()]; - for _ in 0..3 { + for _ in 0..BLUR_BOX_PASSES { box_line(row, &mut tmp, r); row.copy_from_slice(&tmp); } @@ -800,9 +803,14 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { - let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + prepare_mask_curvature_sizes(inp, masks); +} + +/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel. +fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { @@ -1230,11 +1238,19 @@ impl<'a, 'b> Texel<'a, 'b> { /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { - let Some(curvature) = self.baked(BakedMap::Curvature) else { return 0.0 }; + let combine = |edges: f32, cavities: f32| match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + }; + + // Without curvature to read the texel is flat: no edges or cavities + let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32]; - let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return 0.0 }; + let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) }; let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); @@ -1251,12 +1267,7 @@ impl<'a, 'b> Texel<'a, 'b> { cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0)); } - match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), - } + combine(edges, cavities) } fn mask(&mut self, plan: &MaskPlan) -> f32 { @@ -1972,6 +1983,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + let fields = neighbourhood_fields(inputs, &channels, &coordinates); let tiles: HashMap<(u32, u32), Vec> = coordinates .par_iter() @@ -2025,6 +2040,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option