From bced280aa17b1e27b24169f5a781397d78854e47 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Mon, 2 Nov 2026 07:06:07 +0000 Subject: [PATCH 01/15] 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 132f5d1f065f814ac6326a7f2cc82d42d743f019 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Tue, 3 Nov 2026 21:27:42 +0000 Subject: [PATCH 02/15] 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 d00d0e92643b2ca3e9913bd1435b2fb4d1c8d8e2 Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Tue, 3 Nov 2026 22:19:19 -0500 Subject: [PATCH 03/15] 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 04/15] =?UTF-8?q?=F0=9F=93=9D=20CodeRabbit=20Chat:=20Repla?= =?UTF-8?q?ce=20reference=20product=20and=20vendor=20names=20in=20AGENTS.m?= =?UTF-8?q?d=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 05/15] 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 06/15] 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 07/15] 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 08/15] 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 09/15] 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 10/15] 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 11/15] 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 12/15] 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 13/15] 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 14/15] 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 15/15] 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}"); +}