diff --git a/crates/bake/src/bake_passes.rs b/crates/bake/src/bake_passes.rs new file mode 100644 index 00000000..eb7d5846 --- /dev/null +++ b/crates/bake/src/bake_passes.rs @@ -0,0 +1,72 @@ +use crate::cage::RayFrame; +use crate::map::BakeContext; +use crate::tracing::{CpuTracer, Tracer}; +use crate::{BakeError, BakeOutput, BakeRequest, MeshExtent, Progress}; +use std::sync::atomic::Ordering::Relaxed; +use texturecraft_core::{BakeSettings, BakedMap}; + +/// Map passes over one immutable request share the fitted cage and prepared skew. +pub struct BakePasses<'a> { + request: BakeRequest<'a>, + frame: Option<(MeshExtent, RayFrame<'a>)>, +} + +impl<'a> BakePasses<'a> { + pub fn new(request: BakeRequest<'a>) -> Self { + Self { request, frame: None } + } + + /// Bake one selected map, including the CPU fallback used by a normal bake. + pub fn bake_map( + &mut self, + map: BakedMap, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + ) -> Result { + let mut settings = self.request.settings.clone(); + settings.maps.select([map]); + self.run(&settings, progress, excluded_tiles, tracer, super::STRIP_TEXELS) + } + + pub(super) fn run( + &mut self, + settings: &BakeSettings, + progress: &Progress, + excluded_tiles: &[(u32, u32)], + tracer: Option<&dyn Tracer>, + strip_texels: usize, + ) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); + } + + let request = BakeRequest { settings, ..self.request }; + super::validate(&request)?; + if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { + return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + } + + // Validate each pass separately so earlier maps can finish before a later map fails + let (extent, frame) = match &mut self.frame { + Some(geometry) => geometry, + None => { + let extent = MeshExtent::of(request.mesh)?; + self.frame.insert((extent, RayFrame::new(&self.request, extent)?)) + } + }; + let context = BakeContext::with_frame(&request, *extent, frame); + let bake = |tracer: &dyn Tracer| super::bake_prepared(&request, &context, progress, strip_texels, tracer, excluded_tiles); + match tracer { + Some(tracer) => match bake(tracer) { + Err(BakeError::Tracer(error)) => { + let mut output = bake(&CpuTracer)?; + output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); + Ok(output) + } + result => result, + }, + None => bake(&CpuTracer), + } + } +} diff --git a/crates/bake/src/cage.rs b/crates/bake/src/cage.rs index d2c7d7f3..d2c8a592 100644 --- a/crates/bake/src/cage.rs +++ b/crates/bake/src/cage.rs @@ -1,7 +1,9 @@ //! Where the bake's transfer rays start, shared by the bake and the cage the 3D view draws mod cage_shell; +mod fitted_cage; mod high_poly_reach; +mod name_keys; mod ray_frame; mod ray_start; mod vertex_reach; @@ -9,6 +11,7 @@ mod vertex_reach; #[cfg(test)] pub(crate) use cage_shell::CORNERS; pub use cage_shell::CageShell; +pub(crate) use fitted_cage::FittedCage; pub use high_poly_reach::HighPolyReach; pub(crate) use ray_frame::RayFrame; pub use ray_start::RayStart; diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs new file mode 100644 index 00000000..079d94b0 --- /dev/null +++ b/crates/bake/src/cage/fitted_cage.rs @@ -0,0 +1,231 @@ +use super::name_keys::NameKeys; +use crate::map::interpolate; +use crate::{BakeRequest, HighPoly, MeshExtent}; +use rayon::prelude::*; +use std::borrow::Cow; +use std::collections::{HashMap, VecDeque}; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec3; + +/// How much farther than the high poly the cage reaches, as a fraction of the fitted distance: the fit reads both meshes at their vertices only. Tuned with [`MARGIN_PER_DIAGONAL`] on two production meshes: the tightest pair whose rays miss no more texels than the default distances do +const MARGIN_PER_DISTANCE: f32 = 0.5; + +/// The least the cage reaches each way, as a fraction of the mesh diagonal, so a high poly lying on the low poly is still inside +const MARGIN_PER_DIAGONAL: f32 = 4e-3; + +/// How many times farther than the nearest high-poly point a low-poly vertex's ray may find the high poly: beyond it (a surface more than about 75 degrees off the ray) the ray has left the vertex's own part +const MAX_RAY_PER_NEAREST_DISTANCE: f32 = 4.0; + +/// Bound temporary high-vertex projections while giving Rayon thousands of independent queries per batch +const PROJECTION_BATCH_VERTICES: usize = 8192; + +/// The automatic cage: how far the transfer rays start in front of each low-poly vertex and how far they run behind it, fitted to the high poly +pub(crate) struct FittedCage { + /// (front, rear) in world units per low-poly vertex; `None` on parts no high poly is near + distances: Vec>, +} + +impl FittedCage { + /// Fit the cage of `request`'s low poly around `high` along `ray_normals` (where parts welded back to back cancelled a vertex's normal out, along its own): each low-poly vertex reaches the high poly straight in front of or behind it, and each high-poly vertex pushes the corners of its nearest low-poly triangle out (or in) to its height. Vertices neither finds take their neighbours' distances; a part the high poly reaches nowhere gets none + pub(crate) fn new(request: &BakeRequest, high: HighPoly, welded_indices: &[u32], ray_normals: &[Vec3], extent: MeshExtent) -> FittedCage { + let low = request.mesh; + let keys = NameKeys::of(request, high); + let welded_indices = welded_within_groups(welded_indices, &keys.low_vertices); + let welded = |vertex: usize| welded_indices.get(vertex).copied().unwrap_or(0) as usize; + let welded_count = welded_indices.iter().max().map_or(0, |last| *last as usize + 1); + + let fitting_normals = fitting_normals(low, ray_normals); + let mut reach: Vec> = vec![None; welded_count]; + let mut widen = |vertex: usize, height: f32| { + if let Some(distances) = reach.get_mut(welded(vertex)) { + let (front, rear) = distances.unwrap_or((0.0, 0.0)); + *distances = Some((front.max(height), rear.max(-height))); + } + }; + + for (vertex, height) in heights_at_low_vertices(low, high, &fitting_normals, &keys, extent.diagonal).into_iter().enumerate() { + if let Some(height) = height { + widen(vertex, height); + } + } + let mut projected = Vec::new(); + for (batch, positions) in high.mesh.positions.chunks(PROJECTION_BATCH_VERTICES).enumerate() { + let first = batch * PROJECTION_BATCH_VERTICES; + positions + .par_iter() + .enumerate() + .map(|(index, &position)| project_high_vertex(request, &fitting_normals, &keys, first + index, position)) + .collect_into_vec(&mut projected); + + for (triangle, height) in projected.drain(..).flatten() { + for corner in low.tri(triangle).into_iter().flatten() { + widen(corner, height); + } + } + } + drop(projected); + + spread_to_neighbours(&mut reach, low.indices.as_chunks::<3>().0.iter().map(|corners| corners.map(|corner| welded(corner as usize)))); + + let floor = MARGIN_PER_DIAGONAL * extent.diagonal; + let padded = |distance: f32| distance * (1.0 + MARGIN_PER_DISTANCE) + floor; + let distances = + (0..low.positions.len()).map(|vertex| reach.get(welded(vertex)).copied().flatten().map(|(front, rear)| (padded(front), padded(rear)))).collect(); + + FittedCage { distances } + } + + /// The (front, rear) distances at `barycentric` of triangle `triangle` of the low poly `low` the cage was fitted to; `None` where the high poly reaches no corner + pub(crate) fn distances(&self, low: &Mesh, triangle: u32, barycentric: [f32; 2]) -> Option<(f32, f32)> { + let corners = low.tri(triangle as usize)?; + let [first, second, third] = [0, 1, 2].map(|corner| self.distances.get(corners[corner]).copied().flatten()); + let ((first_front, first_rear), (second_front, second_rear), (third_front, third_rear)) = (first?, second?, third?); + let [second_weight, third_weight] = barycentric; + let first_weight = 1.0 - second_weight - third_weight; + + Some(( + first_front * first_weight + second_front * second_weight + third_front * third_weight, + first_rear * first_weight + second_rear * second_weight + third_rear * third_weight, + )) + } +} + +/// `welded_indices` with the vertices of different mesh-name groups (`vertex_keys`, empty when names don't matter) kept apart, so a group's distances come only from its own high poly and never spread into another group +fn welded_within_groups<'a>(welded_indices: &'a [u32], vertex_keys: &[u32]) -> Cow<'a, [u32]> { + if vertex_keys.is_empty() { + return Cow::Borrowed(welded_indices); + } + + let mut indices: HashMap<(u32, Option), u32> = HashMap::new(); + welded_indices + .iter() + .enumerate() + .map(|(vertex, &welded)| { + let next = indices.len() as u32; + *indices.entry((welded, vertex_keys.get(vertex).copied())).or_insert(next) + }) + .collect() +} + +/// `ray_normals`, except where parts welded back to back cancelled a vertex's normal out: there, the vertex's own normal, the direction its transfer rays fall back to +fn fitting_normals<'a>(low: &Mesh, ray_normals: &'a [Vec3]) -> Cow<'a, [Vec3]> { + if !ray_normals.contains(&Vec3::ZERO) { + return Cow::Borrowed(ray_normals); + } + + ray_normals + .iter() + .enumerate() + .map(|(vertex, &welded_normal)| { + if welded_normal != Vec3::ZERO { + return welded_normal; + } + + low.normals.get(vertex).and_then(|normal| normal.try_normalize()).unwrap_or(welded_normal) + }) + .collect() +} + +/// Per low-poly vertex, how far along its ray normal the high-poly surface in front of it (positive) or behind it (negative) is. A ray that only finds a surface much farther than the nearest high-poly point (within `max_distance`) found another part, so the vertex takes that nearest point's height instead +fn heights_at_low_vertices(low: &Mesh, high: HighPoly, ray_normals: &[Vec3], keys: &NameKeys, max_distance: f32) -> Vec> { + low.positions + .par_iter() + .zip(ray_normals) + .enumerate() + .map(|(vertex, (&position, &up))| { + let low_key = keys.low_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(low_key, keys.high_triangles.get(triangle as usize)); + let nearest = high.bvh.nearest(position, max_distance, &rays_reach)?; + let nearest_position = interpolate(high.mesh, &high.mesh.positions, nearest.tri, [nearest.u, nearest.v])?; + let ray_limit = nearest.t * MAX_RAY_PER_NEAREST_DISTANCE + MARGIN_PER_DIAGONAL * max_distance; + let distance = |direction: Vec3| high.bvh.closest_filtered(position, direction, ray_limit, &rays_reach).map(|hit| hit.t); + + Some(match (distance(up), distance(-up)) { + (Some(front), Some(rear)) if front <= rear => front, + (Some(front), None) => front, + (_, Some(rear)) => -rear, + (None, None) => (nearest_position - position).dot(up), + }) + }) + .collect() +} + +/// The nearest matching low-poly triangle and signed height of one high-poly vertex +fn project_high_vertex(request: &BakeRequest, ray_normals: &[Vec3], keys: &NameKeys, vertex: usize, position: Vec3) -> Option<(usize, f32)> { + let low = request.mesh; + let high_key = keys.high_vertices.get(vertex); + let rays_reach = |triangle: u32| NameKeys::matches(keys.low_triangles.get(triangle as usize), high_key); + let nearest = request.bvh.nearest(position, f32::INFINITY, &rays_reach)?; + let barycentric = [nearest.u, nearest.v]; + let low_position = interpolate(low, &low.positions, nearest.tri, barycentric)?; + let up = interpolate(low, ray_normals, nearest.tri, barycentric)?.try_normalize()?; + + Some((nearest.tri as usize, (position - low_position).dot(up))) +} + +/// Give each vertex without distances the largest of its nearest fitted neighbours', walking outward along the edges of `triangles` +fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterator) { + // Only unfitted vertices adjacent to a fitted region can gain distances + if reach.iter().all(Option::is_some) || reach.iter().all(Option::is_none) { + return; + } + + let mut neighbours = vec![Vec::new(); reach.len()]; + for corners in triangles { + for (corner, next) in [(0, 1), (1, 2), (2, 0)] { + if let (true, Some(list)) = (corners[next] < reach.len(), neighbours.get_mut(corners[corner])) { + list.push(corners[next]); + } + if let (true, Some(list)) = (corners[corner] < reach.len(), neighbours.get_mut(corners[next])) { + list.push(corners[corner]); + } + } + } + + // Propagate distances from the preceding breadth-first layer + let mut steps: Vec> = reach.iter().map(|distances| distances.map(|_| 0)).collect(); + let mut queue: VecDeque = (0..reach.len()).filter(|vertex| reach[*vertex].is_some()).collect(); + while let Some(vertex) = queue.pop_front() { + let (Some((front, rear)), Some(step)) = (reach[vertex], steps[vertex]) else { continue }; + + for &neighbour in &neighbours[vertex] { + match steps[neighbour] { + None => { + steps[neighbour] = Some(step + 1); + reach[neighbour] = Some((front, rear)); + queue.push_back(neighbour); + } + Some(neighbour_step) if neighbour_step == step + 1 => { + let (neighbour_front, neighbour_rear) = reach[neighbour].unwrap_or((0.0, 0.0)); + reach[neighbour] = Some((neighbour_front.max(front), neighbour_rear.max(rear))); + } + Some(_) => {} + } + } + } +} + +#[cfg(test)] +mod tests { + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // The coincident pairs span different mesh-name groups + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]).as_ref(), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]).as_ref(), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]).as_ref(), [0, 0, 1], "without name matching nothing changes"); + } + + #[test] + fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { + // A strip of triangles 0-1-2, 1-2-3, 2-3-4: vertices 0 and 4 are fitted + let mut reach = vec![Some((1.0, 0.5)), None, None, None, Some((3.0, 0.25))]; + + spread_to_neighbours(&mut reach, [[0, 1, 2], [1, 2, 3], [2, 3, 4]].into_iter()); + + assert_eq!(reach[1], Some((1.0, 0.5)), "one step from vertex 0 only"); + assert_eq!(reach[3], Some((3.0, 0.25)), "one step from vertex 4 only"); + assert_eq!(reach[2], Some((3.0, 0.5)), "one step from both: the larger of each"); + } +} diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index 2f461343..b227ca06 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -75,7 +75,7 @@ impl HighPolyReach { } /// Each vertex's mesh-name key, from the first triangle that uses it -fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { +pub(super) fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { diff --git a/crates/bake/src/cage/name_keys.rs b/crates/bake/src/cage/name_keys.rs new file mode 100644 index 00000000..077cd826 --- /dev/null +++ b/crates/bake/src/cage/name_keys.rs @@ -0,0 +1,38 @@ +use super::high_poly_reach::vertex_keys; +use crate::map::transfer_keys; +use crate::tracing::ANY; +use crate::{BakeRequest, HighPoly}; +use texturecraft_core::MeshMatchMode; + +/// The mesh-name keys of a bake's low and high poly, per triangle and per vertex; all empty when every ray may hit every part +#[derive(Default)] +pub(super) struct NameKeys { + pub(super) low_triangles: Vec, + pub(super) low_vertices: Vec, + pub(super) high_triangles: Vec, + pub(super) high_vertices: Vec, +} + +impl NameKeys { + /// The keys `request` bakes with against `high`: filled only when it matches by mesh name + pub(super) fn of(request: &BakeRequest, high: HighPoly) -> NameKeys { + match request.settings.high_poly.match_mode { + MeshMatchMode::Always => NameKeys::default(), + MeshMatchMode::ByMeshName => { + let (low_triangles, high_triangles) = transfer_keys(request); + NameKeys { + low_vertices: vertex_keys(request.mesh, &low_triangles), + high_vertices: vertex_keys(high.mesh, &high_triangles), + low_triangles, + high_triangles, + } + } + } + } + + /// Whether a ray from the low-poly part keyed `low_key` may hit the high-poly part keyed `high_key`; a missing key is a part any ray may hit + pub(super) fn matches(low_key: Option<&u32>, high_key: Option<&u32>) -> bool { + let low_key = low_key.copied().unwrap_or(ANY); + low_key == ANY || low_key == high_key.copied().unwrap_or(ANY) + } +} diff --git a/crates/bake/src/cage/ray_frame.rs b/crates/bake/src/cage/ray_frame.rs index e8692cf2..590e52e1 100644 --- a/crates/bake/src/cage/ray_frame.rs +++ b/crates/bake/src/cage/ray_frame.rs @@ -1,4 +1,4 @@ -use super::RayStart; +use super::{FittedCage, RayStart}; use crate::MeshExtent; use crate::map::{interpolate, welded}; use crate::skew::PreparedSkew; @@ -7,11 +7,12 @@ use texturecraft_core::CageType; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, Surface}; -/// What decides where transfer rays start: the cage mesh or the averaged normals, skew and painted cage amount +/// What decides where transfer rays start: the cage mesh, the automatic cage's fitted distances, or the averaged normals, skew and painted cage amount pub(crate) struct RayFrame<'a> { mesh: &'a Mesh, ray_normals: Vec, cage: Option<&'a Mesh>, + fitted: Option, skew: Option>, cage_paint: Option<&'a BakePaintMap>, /// Cage-file offsets this short count as none: the ray starts from the distance-based cage instead @@ -23,18 +24,24 @@ pub(crate) struct RayFrame<'a> { impl<'a> RayFrame<'a> { pub(crate) fn new(request: &BakeRequest<'a>, extent: MeshExtent) -> Result, BakeError> { let settings = request.settings; - let ray_normals = match settings.cage.average_normals && request.high.is_some() { + + // The automatic cage is one closed shell, so its rays always follow the averaged normals + let automatic_high = request.high.filter(|_| settings.cage.kind == CageType::Automatic); + let (ray_normals, fitted) = match (settings.cage.average_normals || automatic_high.is_some()) && request.high.is_some() { true => { let (welded_indices, _, normals) = welded(request.mesh, extent.diagonal); - welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect() + let ray_normals: Vec = welded_indices.iter().map(|index| normals.get(*index as usize).copied().unwrap_or(Vec3::Y)).collect(); + let fitted = automatic_high.map(|high| FittedCage::new(request, high, &welded_indices, &ray_normals, extent)); + (ray_normals, fitted) } - false => Vec::new(), + false => (Vec::new(), None), }; Ok(RayFrame { mesh: request.mesh, ray_normals, cage: if settings.cage.kind == CageType::CustomFile { request.cage } else { None }, + fitted, skew: request.skew.map(|skew_map| PreparedSkew::new(skew_map, request.mesh, extent.scale, settings.skew)).transpose()?, cage_paint: request.cage_paint, ray_epsilon: extent.ray_epsilon(), @@ -54,6 +61,11 @@ impl<'a> RayFrame<'a> { } let averaged_normal = interpolate(self.mesh, &self.ray_normals, surface.tri, barycentric).and_then(Vec3::try_normalize).unwrap_or(surface.nrm); + let fitted_distances = self.fitted.as_ref().and_then(|fitted| fitted.distances(self.mesh, surface.tri, barycentric)); + if let Some((front, rear)) = fitted_distances { + return RayStart::Fitted { up: averaged_normal, front, rear }; + } + let up = match &self.skew { Some(skew) => skew.correct(self.mesh, surface, averaged_normal), None => averaged_normal, diff --git a/crates/bake/src/cage/ray_start.rs b/crates/bake/src/cage/ray_start.rs index c0c3923a..8c21bb9b 100644 --- a/crates/bake/src/cage/ray_start.rs +++ b/crates/bake/src/cage/ray_start.rs @@ -7,6 +7,8 @@ pub enum RayStart { CageMesh(Vec3), /// Out along `up` by the frontal distance times `scale` (the painted cage amount) Distance { up: Vec3, scale: f32 }, + /// Out along `up` by `front` world units and reaching `rear` past the low-poly point: the automatic cage's own distances + Fitted { up: Vec3, front: f32, rear: f32 }, } impl RayStart { @@ -15,6 +17,16 @@ impl RayStart { match *self { RayStart::CageMesh(offset) => position - offset, RayStart::Distance { up, scale } => position + up * frontal * scale, + RayStart::Fitted { up, front, .. } => position + up * front, + } + } + + /// The ray's direction, how far it runs to the low-poly point and how far past it, at `frontal` and `rear` world units of the distance settings + pub fn span(&self, frontal: f32, rear: f32) -> (Vec3, f32, f32) { + match *self { + RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length(), rear), + RayStart::Distance { up, scale } => (-up, frontal * scale, rear), + RayStart::Fitted { up, front, rear: fitted_rear } => (-up, front, fitted_rear), } } } diff --git a/crates/bake/src/cage/vertex_reach.rs b/crates/bake/src/cage/vertex_reach.rs index 34adea92..2c6df8e8 100644 --- a/crates/bake/src/cage/vertex_reach.rs +++ b/crates/bake/src/cage/vertex_reach.rs @@ -17,10 +17,7 @@ impl VertexReach { /// Whether the ray misses the vertex (or may not hit its part) at `frontal` and `rear` world units of cage distance; with `ignore_backface` it also misses a vertex whose triangles face away from the ray pub fn missed(&self, frontal: f32, rear: f32, ignore_backface: bool) -> bool { let origin = self.start.origin(self.low_position, frontal); - let (direction, front) = match self.start { - RayStart::CageMesh(offset) => (offset.normalize_or_zero(), offset.length()), - RayStart::Distance { up, scale } => (-up, frontal * scale), - }; + let (direction, front, rear) = self.start.span(frontal, rear); let along_ray = (self.high_position - origin).dot(direction); !self.name_matches || !(0.0..=front + rear).contains(&along_ray) || (ignore_backface && self.high_facing.dot(direction) > 0.0) diff --git a/crates/bake/src/lib.rs b/crates/bake/src/lib.rs index 1d99ab36..5c8c3ba8 100644 --- a/crates/bake/src/lib.rs +++ b/crates/bake/src/lib.rs @@ -5,6 +5,7 @@ mod bake_error; mod bake_output; +mod bake_passes; mod bake_request; mod cage; mod high_poly; @@ -14,6 +15,7 @@ mod progress; pub use bake_error::BakeError; pub use bake_output::BakeOutput; +pub use bake_passes::BakePasses; pub use bake_request::BakeRequest; pub use cage::{CageShell, HighPolyReach, RayStart, VertexReach}; pub use high_poly::HighPoly; @@ -149,7 +151,7 @@ fn alloc(count: usize, value: T) -> Result, BakeError> { } pub fn bake(request: &BakeRequest, progress: &Progress) -> Result { - bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[]) + bake_tiles(request, progress, &[], None) } /// Retry on the CPU if the supplied tracer fails @@ -159,19 +161,12 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) /// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result { - let tracer = tracer.unwrap_or(&CpuTracer); - match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) { - Err(BakeError::Tracer(error)) => { - let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?; - output.tracer = format!("CPU ({} unavailable: {error})", tracer.name()); - Ok(output) - } - result => result, - } + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, tracer, STRIP_TEXELS) } type OutRow<'a> = Vec<&'a mut [f32]>; +#[cfg(test)] fn bake_in_strips( request: &BakeRequest, progress: &Progress, @@ -179,9 +174,19 @@ fn bake_in_strips( tracer: &dyn Tracer, excluded_tiles: &[(u32, u32)], ) -> Result { - validate(request)?; - if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) { - return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into())); + BakePasses::new(*request).run(request.settings, progress, excluded_tiles, Some(tracer), strip_texels) +} + +fn bake_prepared( + request: &BakeRequest, + context: &map::BakeContext, + progress: &Progress, + strip_texels: usize, + tracer: &dyn Tracer, + excluded_tiles: &[(u32, u32)], +) -> Result { + if progress.cancel.load(Relaxed) { + return Err(BakeError::Cancelled); } let settings = request.settings; @@ -189,7 +194,6 @@ fn bake_in_strips( 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(); let mut scene = tracer.scene(&meshes)?; @@ -259,9 +263,10 @@ fn bake_in_strips( if progress.cancel.load(Relaxed) { return Err(BakeError::Cancelled); } + // Global sample indices keep noise unchanged across strip and batch sizes bake_rows( - &context, + context, &maps, request.mesh, &gbuffer, @@ -313,6 +318,7 @@ fn bake_in_strips( 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() }) } @@ -349,6 +355,7 @@ fn bake_rows( .collect() }) .collect(); + let row_offsets: Vec = samples_by_row .iter() .scan(0, |sample_count, row| { @@ -362,11 +369,12 @@ fn bake_rows( true => { let (rays, frontal_distances): (Vec, Vec) = samples().map(|sample| context.transfer_ray(&sample.surface, sample.bary)).unzip(); 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() + hits.into_par_iter().zip(&rays).zip(frontal_distances).map(|((hit, ray), front)| context.transfer(hit, front, ray.max_distance)).collect() } false => Vec::new(), }; 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<&map::Transfer>)> = samples_by_row @@ -379,6 +387,7 @@ fn bake_rows( } false => Vec::new(), }; + let queries: Vec = match context.ao.is_some() || context.bent.is_some() || context.thickness.is_some() { true => samples_by_row .par_iter() @@ -388,6 +397,7 @@ fn bake_rows( .collect(), false => Vec::new(), }; + // 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(); diff --git a/crates/bake/src/map/bake_context.rs b/crates/bake/src/map/bake_context.rs index bbeb623e..156d392f 100644 --- a/crates/bake/src/map/bake_context.rs +++ b/crates/bake/src/map/bake_context.rs @@ -1,7 +1,7 @@ use super::curvature::Curvature; use super::sampling::{pack, splitmix64, tangent_normal}; use super::{position_projection::PositionProjection, source::Source, traced::Traced, transfer::Transfer}; -use crate::cage::{RayFrame, RayStart}; +use crate::cage::RayFrame; use crate::tracing::{ANY, Hemisphere, Query, Ray, RayKind, RayScene, TraceMesh}; use crate::{BakeError, BakeRequest, MeshExtent}; use rayon::prelude::*; @@ -12,10 +12,13 @@ use texturecraft_geom::{Hit, Surface, surface_at}; const CURVATURE_CHUNK: usize = 1 << 15; +/// Height relative to the rays divides by the ray's length; this keeps a zero-length ray from dividing by zero +const SHORTEST_RAY: f32 = 1e-20; + pub(crate) struct BakeContext<'a> { low: Source<'a>, high: Option>, - ray_frame: RayFrame<'a>, + ray_frame: &'a RayFrame<'a>, settings: &'a BakeSettings, frontal: f32, rear: f32, @@ -28,11 +31,9 @@ pub(crate) struct BakeContext<'a> { } impl<'a> BakeContext<'a> { - pub(crate) fn new(request: &BakeRequest<'a>) -> Result, BakeError> { + pub(crate) fn with_frame(request: &BakeRequest<'a>, extent: MeshExtent, ray_frame: &'a RayFrame<'a>) -> Self { let settings = request.settings; - let extent = MeshExtent::of(request.mesh)?; let (low, high) = Source::of_request(request); - let ray_frame = RayFrame::new(request, extent)?; let (mesh_scale, ray_epsilon) = (extent.scale, extent.ray_epsilon()); let pass = |map: BakedMap, ray_settings: &RaySettings, kind: RayKind| { let half_angle_radians = (ray_settings.spread.clamp(0.0, 180.0) * 0.5).to_radians(); @@ -74,7 +75,7 @@ impl<'a> BakeContext<'a> { } let cage_units = ray_frame.cage_units; - Ok(BakeContext { + BakeContext { low, high, ray_frame, @@ -87,7 +88,7 @@ impl<'a> BakeContext<'a> { ao, bent, thickness, - }) + } } pub(crate) fn ignore_transfer_backface(&self) -> bool { @@ -109,21 +110,19 @@ impl<'a> BakeContext<'a> { pub(crate) fn transfer_ray(&self, surface: &Surface, barycentric: [f32; 2]) -> (Ray, f32) { let start = self.ray_frame.start(surface, barycentric); let origin = start.origin(surface.pos, self.frontal); - let (direction, front) = match start { - RayStart::CageMesh(offset) => (offset.normalize(), offset.length()), - RayStart::Distance { up, scale } => (-up, self.frontal * scale), - }; + let (direction, front, rear) = start.span(self.frontal, self.rear); 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) + (Ray { origin, direction, max_distance: front + rear, key }, front) } - pub(crate) fn transfer(&self, hit: Option, front: f32) -> Option { + /// What the transfer ray that ran `front` to the low poly and `ray_length` in all brought back from the high poly + pub(crate) fn transfer(&self, hit: Option, front: f32, ray_length: 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 }) + Some(Transfer { surface, bary: [hit.u, hit.v], t: hit.t, front, ray_length }) } pub(crate) fn query(&self, transfer: Option<&Transfer>, low_surface: &Surface, seed: u64) -> Query { @@ -245,7 +244,7 @@ impl<'a> BakeContext<'a> { 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 } + if relative_to_rays { (0.5 + height / hit.ray_length.max(SHORTEST_RAY)).clamp(0.0, 1.0) } else { height } }); 3] } BakedMap::Opacity if missed => [0.0; 3], diff --git a/crates/bake/src/map/transfer.rs b/crates/bake/src/map/transfer.rs index c1200053..46c67f28 100644 --- a/crates/bake/src/map/transfer.rs +++ b/crates/bake/src/map/transfer.rs @@ -5,4 +5,6 @@ pub(crate) struct Transfer { pub(super) bary: [f32; 2], pub(super) t: f32, pub(super) front: f32, + /// The whole ray, from the cage to its rear end + pub(super) ray_length: f32, } diff --git a/crates/bake/src/test/cage_shell.rs b/crates/bake/src/test/cage_shell.rs index 40edd3b8..a437c089 100644 --- a/crates/bake/src/test/cage_shell.rs +++ b/crates/bake/src/test/cage_shell.rs @@ -17,7 +17,9 @@ fn painted_map() -> BakePaintMap { fn assert_cage_matches_the_ray_origins(request: &BakeRequest) { let shell = CageShell::new(request).unwrap(); let corners = shell.corners(request.settings.cage.max_frontal); - let context = BakeContext::new(request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(request, extent).unwrap(); + let context = BakeContext::with_frame(request, extent, &frame); let triangles: Vec = request.mesh.triangles_of(request.material).collect(); assert_eq!(corners.len(), triangles.len() * 3); @@ -60,6 +62,12 @@ fn the_cage_corners_are_the_bake_ray_origins() { face_normals }; assert_cage_matches_the_ray_origins(&request(&face_normals)); + let automatic = { + let mut automatic = bake_settings.clone(); + automatic.cage.kind = CageType::Automatic; + automatic + }; + assert_cage_matches_the_ray_origins(&request(&automatic)); } #[test] diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs new file mode 100644 index 00000000..3cfec7a5 --- /dev/null +++ b/crates/bake/src/test/fitted_cage.rs @@ -0,0 +1,250 @@ +use super::{covered_values, settings, transfer}; +use crate::{BakeRequest, CageShell, HighPoly, HighPolyReach}; +use texturecraft_core::{BakeSettings, BakedMap, CageType, MeshMatchMode}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Bvh, Mesh, primitives}; + +/// A distance setting far larger than any fitted distance in these tests, to tell the two apart +const UNFITTED_DISTANCE: f32 = 0.5; + +/// Settings baking `maps` with the automatic cage, and distance settings no fitted cage comes near +fn automatic(maps: &[BakedMap]) -> BakeSettings { + let mut bake_settings = settings(32, maps); + bake_settings.cage.kind = CageType::Automatic; + bake_settings.cage.relative_to_bounding_box = false; + (bake_settings.cage.max_frontal, bake_settings.cage.max_rear) = (UNFITTED_DISTANCE, UNFITTED_DISTANCE); + bake_settings +} + +/// How far each corner of the automatic cage of the flat `low` around `high` rises above it, with the corner's low-poly position +fn cage_heights(low: &Mesh, high: &Mesh, bake_settings: &BakeSettings) -> Vec<(Vec3, f32)> { + let (low_bvh, high_bvh) = (Bvh::new(low), Bvh::new(high)); + let request = BakeRequest { + low_base_color: &[], + mesh: low, + bvh: &low_bvh, + material: 0, + settings: bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let shell = CageShell::new(&request).unwrap(); + let corners = shell.corners(bake_settings.cage.max_frontal); + shell.positions.iter().zip(corners).map(|(position, corner)| (*position, corner.y - position.y)).collect() +} + +/// Every submesh on the first material, so the cage shell of material 0 covers all the parts +fn one_material(mesh: &mut Mesh) { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } +} + +#[test] +fn the_automatic_cage_reaches_a_high_poly_the_default_distances_miss() { + let low = primitives::cube(1.0); + let high = primitives::sphere(0.8, 32, 16); + let opacity_of = |bake_settings: &BakeSettings| -> Vec { + let output = transfer(&low, &high, None, bake_settings).unwrap(); + covered_values(&low, &output, BakedMap::Opacity).into_iter().map(|(_, opacity)| opacity).collect() + }; + + let distance_based = opacity_of(&settings(32, &[BakedMap::Opacity])); + assert!(distance_based.contains(&0.0), "the sphere is beyond the default distances at the middle of each face"); + + let mut bake_settings = settings(32, &[BakedMap::Opacity]); + bake_settings.cage.kind = CageType::Automatic; + let fitted = opacity_of(&bake_settings); + assert!(fitted.iter().all(|opacity| *opacity == 1.0), "every ray of the automatic cage finds the sphere"); + + // The triangles at the sphere's poles have no area, so a pole vertex has no side to face the ray with + bake_settings.high_poly.ignore_backface = false; + let (low_bvh, high_bvh) = (Bvh::new(&low), Bvh::new(&high)); + let request = BakeRequest { + low_base_color: &[], + mesh: &low, + bvh: &low_bvh, + material: 0, + settings: &bake_settings, + high: Some(HighPoly { file_ids: &[], mesh: &high, bvh: &high_bvh, base_color: &[] }), + cage: None, + skew: None, + cage_paint: None, + tiles: (1, 1), + }; + let reach = HighPolyReach::new(&request).unwrap(); + for vertex in 0..high.positions.len() { + assert_eq!(reach.missed(vertex, 0.0, 0.0), Some(false), "high-poly vertex {vertex} is inside the cage whatever the distance settings"); + } +} + +#[test] +fn the_automatic_cage_stays_low_where_the_high_poly_is_low() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.2; + const RAISED_FROM_X: f32 = 0.25; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(1.0, 40); + for position in &mut high.positions { + position.y = if position.x > RAISED_FROM_X { RAISED_HEIGHT } else { LOW_HEIGHT }; + } + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + for (position, height) in heights { + if position.x < 0.0 { + assert!((LOW_HEIGHT..RAISED_HEIGHT / 2.0).contains(&height), "the cage at {position} hugs the low part: {height}"); + } else if position.x > RAISED_FROM_X + 0.125 { + assert!((RAISED_HEIGHT..RAISED_HEIGHT * 2.0).contains(&height), "the cage at {position} clears the raised part: {height}"); + } + } +} + +#[test] +fn a_ray_that_only_finds_a_far_surface_takes_the_nearest_surface_height_instead() { + const PATCH_HEIGHT: f32 = 0.02; + const CEILING_HEIGHT: f32 = 1.0; + + // A low-plane vertex beside the patch's edge: the patch is its nearest high poly, the ceiling is straight above it + const BESIDE_PATCH: Vec3 = Vec3::new(0.125, 0.0, 0.0); + + // Far enough that the ceiling's own corners are nearest to the low plane's border, not to the vertex tested + const CEILING_REACH: f32 = 1000.0; + + // The ceiling starts just past the patch's edge (x = 0), the patch covers the low plane's other half + const CEILING_FROM_X: f32 = 0.05; + const PATCH_SIZE: f32 = 0.5; + const SAME_POSITION: f32 = 1e-4; + + let low = primitives::plane(1.0, 8); + let mut high = primitives::plane(PATCH_SIZE, 1); + for position in &mut high.positions { + *position = Vec3::new(position.x - PATCH_SIZE / 2.0, PATCH_HEIGHT, position.z); + } + let ceiling = Mesh::from_parts( + vec![ + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, -CEILING_REACH), + Vec3::new(CEILING_FROM_X, CEILING_HEIGHT, CEILING_REACH), + Vec3::new(CEILING_REACH, CEILING_HEIGHT, 0.0), + ], + None, + vec![Default::default(); 3], + vec![0, 1, 2], + "ceiling", + ) + .unwrap(); + high.append(&ceiling); + + let heights = cage_heights(&low, &high, &automatic(&[BakedMap::Normal])); + + let (_, height) = heights.iter().find(|(position, _)| position.distance(BESIDE_PATCH) < SAME_POSITION).unwrap(); + assert!(*height < CEILING_HEIGHT / 2.0, "the cage beside the patch stays near the patch, not the ceiling: {height}"); +} + +#[test] +fn a_part_no_high_poly_part_matches_keeps_the_distance_settings() { + let mut low = primitives::plane(1.0, 2); + let mut high = primitives::plane(1.0, 2); + low.submeshes[0].name = "panel_low".into(); + high.submeshes[0].name = "door_high".into(); + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + assert!(heights.iter().all(|(_, height)| *height == UNFITTED_DISTANCE)); +} + +#[test] +fn a_part_meeting_another_part_takes_its_distances_from_its_own_high_poly_only() { + const LOW_HEIGHT: f32 = 0.01; + const RAISED_HEIGHT: f32 = 0.3; + + // Two low parts sharing the edge x = 0, under a low and a raised high-poly part matched by name + let part = |name: &str, side: f32, height: f32, subdivisions: usize| { + let mut part = primitives::plane(1.0, subdivisions); + for position in &mut part.positions { + *position += Vec3::new(side * 0.5, height, 0.0); + } + part.submeshes[0].name = name.into(); + part + }; + let mut low = part("left_low", -1.0, 0.0, 4); + low.append(&part("right_low", 1.0, 0.0, 4)); + let mut high = part("left_high", -1.0, LOW_HEIGHT, 8); + high.append(&part("right_high", 1.0, RAISED_HEIGHT, 8)); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = MeshMatchMode::ByMeshName; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The left part's triangles come first, three corners each + let left_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..left_corners] { + assert!(*height < RAISED_HEIGHT / 2.0, "the left part's cage at {position} stays near the left high poly: {height}"); + } +} + +#[test] +fn parts_back_to_back_fit_their_cages_along_their_own_normals() { + const SHEET_DISTANCE: f32 = 0.2; + + // A plane facing up and the same plane facing down, each facing its own high-poly sheet: welded, their normals cancel out + let named = |mut mesh: Mesh, name: &str| { + mesh.submeshes[0].name = name.into(); + mesh + }; + let facing_down = |mut mesh: Mesh| { + for normal in &mut mesh.normals { + *normal = -*normal; + } + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); + } + mesh + }; + let sheet = |height: f32| { + let mut sheet = primitives::plane(1.0, 8); + for position in &mut sheet.positions { + position.y = height; + } + sheet + }; + let mut low = named(primitives::plane(1.0, 4), "front_low"); + low.append(&named(facing_down(primitives::plane(1.0, 4)), "back_low")); + let mut high = named(sheet(SHEET_DISTANCE), "front_high"); + high.append(&named(facing_down(sheet(-SHEET_DISTANCE)), "back_high")); + for mesh in [&mut low, &mut high] { + one_material(mesh); + } + + for match_mode in [MeshMatchMode::Always, MeshMatchMode::ByMeshName] { + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = match_mode; + + let heights = cage_heights(&low, &high, &bake_settings); + + // The front part's triangles come first, three corners each + let front_corners = low.submeshes[0].count as usize; + for (position, height) in &heights[..front_corners] { + assert!( + (SHEET_DISTANCE..UNFITTED_DISTANCE).contains(height), + "{match_mode:?}: the front part's cage at {position} reaches the sheet above it, fitted: {height}" + ); + } + for (position, height) in &heights[front_corners..] { + assert!( + (-UNFITTED_DISTANCE..=-SHEET_DISTANCE).contains(height), + "{match_mode:?}: the back part's cage at {position} reaches the sheet below it, fitted: {height}" + ); + } + } +} diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index 8a4f83c4..b001737b 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -69,7 +69,9 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, max_frontal, max_rear).unwrap()); @@ -94,6 +96,7 @@ fn a_vertex_is_missed_exactly_when_the_bake_ray_misses_it() { } } } + assert!(checked[0] > 100 && checked[1] > 100, "both reached and missed vertices were compared: {checked:?}"); } @@ -173,11 +176,14 @@ fn matching_by_mesh_name_misses_the_parts_with_another_name() { tiles: (1, 1), }; let reach = HighPolyReach::new(&request).unwrap(); - let context = BakeContext::new(&request).unwrap(); + let extent = crate::MeshExtent::of(request.mesh).unwrap(); + let frame = crate::cage::RayFrame::new(&request, extent).unwrap(); + let context = BakeContext::with_frame(&request, extent, &frame); let (_, high_keys) = transfer_keys(&request); for (vertex, vertex_reach) in reach.vertices.iter().enumerate() { let (vertex_reach, missed) = (vertex_reach.unwrap(), reach.missed(vertex, 0.02, 0.01).unwrap()); + // On the line where the two parts meet, a ray reaches either part's triangles if vertex_reach.high_position.x.abs() < BOUNDARY { continue; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index eaa64cf2..7d94031e 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -20,6 +20,9 @@ mod bent_normal_space; #[path = "test/cage_shell.rs"] mod cage_shell; +#[path = "test/fitted_cage.rs"] +mod fitted_cage; + #[path = "test/high_poly_reach.rs"] mod high_poly_reach; diff --git a/crates/core/src/bake.rs b/crates/core/src/bake.rs index 4b21a20d..a40f5ab0 100644 --- a/crates/core/src/bake.rs +++ b/crates/core/src/bake.rs @@ -7,6 +7,8 @@ mod bake_antialiasing; mod bake_paint_target; mod bake_resolution; mod bake_settings; +mod bake_sync; +mod bake_sync_group; mod mesh_match_mode; mod skew_correction_method; pub use bake_paint_target::BakePaintTarget; @@ -45,6 +47,8 @@ pub use backface_mode::BackfaceMode; pub use bake_antialiasing::BakeAntialiasing; pub use bake_resolution::BakeResolution; pub use bake_settings::BakeSettings; +pub use bake_sync::BakeSync; +pub use bake_sync_group::BakeSyncGroup; pub use baked_map::BakedMap; pub use bent_normal_settings::BentNormalSettings; pub use cage_settings::CageSettings; diff --git a/crates/core/src/bake/bake_settings.rs b/crates/core/src/bake/bake_settings.rs index 8d121419..87962b5c 100644 --- a/crates/core/src/bake/bake_settings.rs +++ b/crates/core/src/bake/bake_settings.rs @@ -1,4 +1,4 @@ -use super::{CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; +use super::{BakeSync, BakeSyncGroup, CageSettings, CageType, CommonBakeSettings, HighPolySettings, MeshMapSettings, SkewSettings}; use serde::{Deserialize, Serialize}; /// Persisted clean-room bake settings, grouped by the controls they belong to @@ -10,6 +10,8 @@ pub struct BakeSettings { pub cage: CageSettings, pub skew: SkewSettings, pub maps: MeshMapSettings, + /// What this texture set shares with the others + pub sync: BakeSync, } impl BakeSettings { @@ -17,4 +19,17 @@ impl BakeSettings { pub fn skew_applies(&self) -> bool { !self.high_poly.use_low_as_high && self.cage.kind == CageType::DistanceBased && self.cage.average_normals } + + /// Take `group`'s settings from `source`, keeping whether this set is baked and which maps it bakes + pub fn copy_group(&mut self, source: &BakeSettings, group: BakeSyncGroup) { + match group { + BakeSyncGroup::Common => { + self.common = CommonBakeSettings { is_enabled: self.common.is_enabled, ..source.common }; + self.high_poly = source.high_poly.clone(); + self.cage = source.cage; + self.skew = source.skew; + } + BakeSyncGroup::Map(map) => self.maps.copy_parameters(map, &source.maps), + } + } } diff --git a/crates/core/src/bake/bake_sync.rs b/crates/core/src/bake/bake_sync.rs new file mode 100644 index 00000000..e53a4def --- /dev/null +++ b/crates/core/src/bake/bake_sync.rs @@ -0,0 +1,40 @@ +use super::{BakeSyncGroup, BakedMap}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +/// Which of a texture set's bake settings it shares with every other texture set sharing them; all are shared at first, as in the reference +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct BakeSync { + /// Shares Common Settings: output, high poly, cage and skew correction + pub common: bool, + /// The map types whose settings it shares + pub maps: BTreeSet, +} + +impl Default for BakeSync { + fn default() -> Self { + Self { common: true, maps: BakedMap::ALL.into_iter().collect() } + } +} + +impl BakeSync { + pub fn shares(&self, group: BakeSyncGroup) -> bool { + match group { + BakeSyncGroup::Common => self.common, + BakeSyncGroup::Map(map) => self.maps.contains(&map), + } + } + + pub fn set_shares(&mut self, group: BakeSyncGroup, shares: bool) { + match group { + BakeSyncGroup::Common => self.common = shares, + BakeSyncGroup::Map(map) if shares => { + self.maps.insert(map); + } + BakeSyncGroup::Map(map) => { + self.maps.remove(&map); + } + } + } +} diff --git a/crates/core/src/bake/bake_sync_group.rs b/crates/core/src/bake/bake_sync_group.rs new file mode 100644 index 00000000..c9007dbf --- /dev/null +++ b/crates/core/src/bake/bake_sync_group.rs @@ -0,0 +1,8 @@ +use super::BakedMap; + +/// A part of the bake settings texture sets can share: Common Settings, or one map type's settings +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum BakeSyncGroup { + Common, + Map(BakedMap), +} diff --git a/crates/core/src/bake/cage_type.rs b/crates/core/src/bake/cage_type.rs index 1985055f..a894235c 100644 --- a/crates/core/src/bake/cage_type.rs +++ b/crates/core/src/bake/cage_type.rs @@ -4,5 +4,7 @@ use serde::{Deserialize, Serialize}; pub enum CageType { #[default] DistanceBased, + /// Distances fitted to the high poly at every low-poly vertex + Automatic, CustomFile, } diff --git a/crates/core/src/bake/common_bake_settings.rs b/crates/core/src/bake/common_bake_settings.rs index 3f743fff..a39ef77f 100644 --- a/crates/core/src/bake/common_bake_settings.rs +++ b/crates/core/src/bake/common_bake_settings.rs @@ -21,8 +21,8 @@ impl Default for CommonBakeSettings { resolution: BakeResolution::R2048, resolution_height: None, antialiasing: BakeAntialiasing::None, - dilation: 1, - apply_diffusion: true, + dilation: 32, + apply_diffusion: false, } } } diff --git a/crates/core/src/bake/mesh_map_settings.rs b/crates/core/src/bake/mesh_map_settings.rs index c0a38673..281d5c98 100644 --- a/crates/core/src/bake/mesh_map_settings.rs +++ b/crates/core/src/bake/mesh_map_settings.rs @@ -68,6 +68,22 @@ impl MeshMapSettings { *enabled = is_enabled; } + /// Take `map`'s parameters from `source`, keeping whether it is checked + pub fn copy_parameters(&mut self, map: BakedMap, source: &MeshMapSettings) { + match map { + BakedMap::Normal => self.normal.parameters = source.normal.parameters, + BakedMap::WorldNormal => self.world_normal.parameters = source.world_normal.parameters, + BakedMap::Id => self.id.parameters = source.id.parameters, + BakedMap::AmbientOcclusion => self.ao.parameters = source.ao.parameters, + BakedMap::Curvature => self.curvature.parameters = source.curvature.parameters, + BakedMap::Position => self.position.parameters = source.position.parameters, + BakedMap::Thickness => self.thickness.parameters = source.thickness.parameters, + BakedMap::Height => self.height.parameters = source.height.parameters, + BakedMap::BentNormal => self.bent_normal.parameters = source.bent_normal.parameters, + BakedMap::Opacity => self.opacity.parameters = source.opacity.parameters, + } + } + pub fn enabled(&self) -> impl Iterator { BakedMap::ALL.into_iter().filter(|map| self.is_enabled(*map)) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0662670a..eedf93ec 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -80,11 +80,11 @@ pub const FULL_TURN_DEGREES: f32 = 360.0; pub use anisotropic_kuwahara::AnisotropicKuwahara; pub use backface::Backface; pub use bake::{ - 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, + AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, BakeSync, + BakeSyncGroup, 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 bevel::Bevel; pub use bevel_blur::BevelBlur; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 649f4f6d..db74dc2a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -478,6 +478,23 @@ impl Project { self.texture_sets.get_mut(ts).ok_or(CoreError::NoTextureSet(ts)) } + /// The texture sets an edit of `group` on texture set `active` reaches: every set sharing `group` with it, or `active` alone + pub fn bake_synced_sets(&self, active: usize, group: BakeSyncGroup) -> Vec { + match self.texture_sets.get(active) { + Some(set) if set.bake.sync.shares(group) => { + self.texture_sets.iter().enumerate().filter(|(_, set)| set.bake.sync.shares(group)).map(|(index, _)| index).collect() + } + Some(_) => vec![active], + None => Vec::new(), + } + } + + /// The set whose `group` settings the sets joining a sync of `members` take: one of them already sharing the group, else `active` when it is one of them, else the first + pub fn bake_sync_source(&self, group: BakeSyncGroup, members: &[usize], active: usize) -> Option { + let staying = members.iter().copied().find(|index| self.texture_sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); + staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()) + } + pub fn layer(&self, id: LayerId) -> Result<&Layer> { self.layers.get(&id).ok_or(CoreError::NoLayer(id)) } @@ -787,6 +804,23 @@ mod tests { p } + #[test] + fn a_sync_takes_settings_from_a_staying_member_else_the_active_set_else_the_first() { + let group = BakeSyncGroup::Common; + let mut project = project(); + for name in ["Legs", "Arms"] { + project.texture_sets.push(TextureSet::new(name, 0, 512)); + } + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake.sync.set_shares(group, index == 2); + } + + assert_eq!(project.bake_sync_source(group, &[0, 1, 2], 0), Some(2), "a member already sharing the group"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 1), Some(1), "the active set when it joins"); + assert_eq!(project.bake_sync_source(group, &[0, 1], 2), Some(0), "else the first member"); + assert_eq!(project.bake_sync_source(group, &[], 0), None); + } + fn paint(p: &mut Project, name: &str) -> Layer { Layer::new(p.alloc_id(), name, LayerKind::Paint, &Channel::DEFAULT_SET) } diff --git a/crates/core/tests/bake_settings.rs b/crates/core/tests/bake_settings.rs index 1616604f..80fda4b8 100644 --- a/crates/core/tests/bake_settings.rs +++ b/crates/core/tests/bake_settings.rs @@ -13,10 +13,11 @@ fn reference_defaults_cover_common_and_per_map_settings() { 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}, + "common": {"is_enabled": true, "resolution": "R2048", "resolution_height": null, "antialiasing": "None", "dilation": 32, "apply_diffusion": false}, "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": {"method": "MeshNormalsBased", "edge_protection": false, "edge_distance": 0.15, "edge_contrast": 0.5}, + "sync": {"common": true, "maps": ["Normal", "WorldNormal", "Id", "AmbientOcclusion", "Curvature", "Position", "Thickness", "Height", "BentNormal", "Opacity"]}, "id": {"source": "MaterialColor", "generator": "HueShift"}, "ao": {"rays": rays, "ignore_backface": "Never", "self_occlusion": "Always", "attenuation": "Linear", "ground_plane": {"enabled": false, "offset": 0.0}}, "curvature": { @@ -81,7 +82,7 @@ fn all_dropdowns_store_enum_choices() { assert_choices(&[bake::SkewCorrectionMethod::MeshNormalsBased, bake::SkewCorrectionMethod::FaceNormalsBased]); assert_choices(&bake::BakeResolution::ALL); assert_choices(&bake::BakeAntialiasing::ALL); - assert_choices(&[bake::CageType::DistanceBased, bake::CageType::CustomFile]); + assert_choices(&[bake::CageType::DistanceBased, bake::CageType::Automatic, bake::CageType::CustomFile]); assert_choices(&[bake::CurvatureMethod::NormalMap, bake::CurvatureMethod::Mesh]); assert_choices(&[ bake::IdColorSource::VertexColor, @@ -126,7 +127,8 @@ fn nested_settings_round_trip_per_texture_set() { 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.common.apply_diffusion = true; + settings.sync.set_shares(bake::BakeSyncGroup::Map(bake::BakedMap::Height), false); settings.high_poly.ignore_backface_suffix = "_two_sided".into(); settings.cage.kind = bake::CageType::CustomFile; settings.skew.edge_protection = true; diff --git a/crates/engine/src/bake/bake_checks.rs b/crates/engine/src/bake/bake_checks.rs index 3ea93729..f25ed63c 100644 --- a/crates/engine/src/bake/bake_checks.rs +++ b/crates/engine/src/bake/bake_checks.rs @@ -39,7 +39,7 @@ impl Session { pub fn bake_name_pairs(&self, texture_set: usize) -> Result>> { let set = self.doc.project.texture_set(texture_set)?; let settings = &set.bake.high_poly; - let high = self.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); + let high = self.doc.bake_meshes.merged_high().filter(|_| settings.match_mode == MeshMatchMode::ByMeshName && !settings.use_low_as_high); Ok(high.map(|high| NamePair::list(&self.mesh, set.material, &high.mesh, settings))) } diff --git a/crates/engine/src/bake/bake_mesh.rs b/crates/engine/src/bake/bake_mesh.rs index 0d4d5ffe..bcdb2bcc 100644 --- a/crates/engine/src/bake/bake_mesh.rs +++ b/crates/engine/src/bake/bake_mesh.rs @@ -6,6 +6,8 @@ use texturecraft_geom::{BaseColor, Mesh}; #[derive(Clone, Debug)] pub struct BakeMesh { pub name: String, + /// The folder the file was read from, when it was picked from disk this session (projects don't keep it) + pub folder: Option, pub bytes: Arc>, 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 index da0e4a97..b609e106 100644 --- a/crates/engine/src/bake/bake_meshes.rs +++ b/crates/engine/src/bake/bake_meshes.rs @@ -2,8 +2,7 @@ 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. +/// The high-definition meshes and the cage; undo and redo restore them with the document #[derive(Clone, Debug, Default)] pub struct BakeMeshes { pub(crate) low_base_color: OnceLock>, diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 24629b56..a617d97b 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,7 +1,7 @@ use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; -use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; +use texturecraft_bake::{BakeOutput, BakePaintMap, BakePasses, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; use texturecraft_compose::BakedMaps; use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; @@ -46,13 +46,13 @@ impl BakeTask { let total = maps.len(); let mut combined: Option = None; + let mut passes = BakePasses::new(self.request()); for (index, map) in maps.iter().copied().enumerate() { - let mut settings = self.settings.clone(); - settings.maps.select([map]); - let mut output = self.run_with(&settings, progress)?; + let mut output = passes.bake_map(map, progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; let Some(data) = output.maps.remove(&map) else { continue }; if combined.is_none() { - // Retain unchecked maps once, using the full selection rather than this one-map pass. + // Restore unchecked maps once from the full selection super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?; } @@ -86,34 +86,34 @@ impl BakeTask { } pub fn run(&self, progress: &Progress) -> Result { - let mut output = self.run_with(&self.settings, progress)?; + let mut output = bake_tiles(&self.request(), progress, &self.excluded_tiles, self.tracer.as_deref()).map_err(bake_error)?; + super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; Ok(output) } - fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result { + fn request(&self) -> BakeRequest<'_> { 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 { + BakeRequest { low_base_color: &self.low_base_color, mesh: &self.mesh, bvh: &self.bvh, material: self.material, - settings, + settings: &self.settings, high, cage: self.cage.as_deref(), skew: self.skew.as_deref(), cage_paint: self.cage_paint.as_deref(), tiles: self.tiles, - }; - - let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref()) - .map_err(|error| EngineError::Other(format!("bake failed: {error}")))?; - super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; - Ok(output) + } } } +fn bake_error(error: texturecraft_bake::BakeError) -> EngineError { + EngineError::Other(format!("bake failed: {error}")) +} + #[cfg(test)] mod tests { use super::*; @@ -124,6 +124,42 @@ mod tests { const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height]; const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height]; + #[test] + fn preview_resamples_only_the_displayed_map_for_excluded_tiles() { + const PREVIOUS_WIDTH: u32 = 256; + const PREVIEW_TILE_PIXELS: u32 = 64; + const PREVIOUS_OPACITY: f32 = 0.25; + let mut session = Session::new_project("Preview", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let selected = BakedMap::Opacity; + session.doc.baked.insert( + 0, + BakedMaps { + resolution: PREVIOUS_WIDTH, + maps: [selected, BakedMap::WorldNormal, BakedMap::Normal, BakedMap::Height, BakedMap::Position, BakedMap::AmbientOcclusion] + .into_iter() + .map(|map| (map, Arc::new(vec![PREVIOUS_OPACITY; PREVIOUS_WIDTH as usize * (PREVIOUS_WIDTH as usize / 2) * map.components()]))) + .collect(), + }, + ); + + let mut task = session.bake_map_preview_task(0, selected).unwrap(); + task.settings.common.resolution = texturecraft_core::BakeResolution::from_pixels(PREVIEW_TILE_PIXELS).unwrap(); + task.settings.common.dilation = 0; + task.tracer = None; + super::super::preserve_tiles::take_retained_allocations(); + let output = task.run(&Progress::new()).unwrap(); + + let retained_maps = super::super::preserve_tiles::take_retained_allocations(); + let other_output_bytes = + output.maps.iter().filter(|(map, _)| **map != selected).map(|(_, pixels)| std::mem::size_of_val(pixels.as_slice())).sum::(); + eprintln!("atlas={}x{} retained_maps={retained_maps:?} other_output_bytes={other_output_bytes}", output.resolution, output.height); + let row = &output.maps[&selected][..output.resolution as usize]; + assert!(row[..PREVIEW_TILE_PIXELS as usize].iter().any(|&opacity| opacity > PREVIOUS_OPACITY), "the included tile bakes"); + assert!(row[PREVIEW_TILE_PIXELS as usize..].iter().all(|&opacity| opacity == PREVIOUS_OPACITY), "the excluded tile keeps its previous pixels"); + assert!(retained_maps.is_empty(), "the preview never allocates buffers for maps it will discard"); + } + fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask { let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap(); diff --git a/crates/engine/src/bake/high_poly_load.rs b/crates/engine/src/bake/high_poly_load.rs new file mode 100644 index 00000000..7a69d30e --- /dev/null +++ b/crates/engine/src/bake/high_poly_load.rs @@ -0,0 +1,75 @@ +use std::sync::Arc; + +use texturecraft_formats::MeshFile; + +use super::mesh_map_command::{ADD_HIGH_POLY_LABEL, parse_mesh, unique_name}; +use super::{BakeMesh, BakeMeshes, MergedHigh}; +use crate::{Result, Session}; + +/// A high poly file parsed and merged with the meshes it joins, which a worker thread can prepare while the session stays in use +pub struct HighPolyLoad { + /// The name the file was picked by, before it was made unique in the list + file_name: String, + added: BakeMesh, + /// The list the mesh joined, with it at the end + high: Vec, + /// `high` as bakes see it + merged: Option, + /// Files the mesh refers to that could not be read, as messages for the log + warnings: Vec, +} + +impl HighPolyLoad { + /// Parse `file` and merge it with the high polys of `meshes` + pub fn prepare(meshes: &BakeMeshes, file: MeshFile) -> Result { + let mut added = parse_mesh(&file.name, file.bytes)?; + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&file.name, &taken); + + let mut joined = BakeMeshes { high: meshes.high.clone(), ..Default::default() }; + joined.high.push(added.clone()); + joined.rebuild(); + Ok(Self { file_name: file.name, added, high: joined.high, merged: joined.merged, warnings: file.warnings }) + } + + /// Read the mesh file at `path`, then [`HighPolyLoad::prepare`] it + #[cfg(not(target_arch = "wasm32"))] + pub fn read(meshes: &BakeMeshes, path: &str) -> Result { + Self::prepare(meshes, crate::file_cmds::read_mesh("bake.highPoly.add", path)?) + } + + /// Whether `current` is still the list this mesh was merged into + fn joins(&self, current: &[BakeMesh]) -> bool { + let joined = &self.high[..self.high.len() - 1]; + joined.len() == current.len() + && joined.iter().zip(current).all(|(joined, current)| joined.name == current.name && Arc::ptr_eq(&joined.mesh, ¤t.mesh)) + } +} + +impl Session { + /// Add a prepared high poly as one undo step; every texture set then bakes from the high polys. Returns its name + pub fn apply_high_poly_load(&mut self, load: HighPolyLoad) -> String { + let before = self.doc.clone(); + let meshes = &mut self.doc.bake_meshes; + let mut added = load.added.clone(); + if load.joins(&meshes.high) { + meshes.high = load.high; + meshes.merged = load.merged; + } else { + // The list changed while the file loaded, so the mesh joins the list as it is now + let taken: Vec<&str> = meshes.high.iter().map(|high| high.name.as_str()).collect(); + added.name = unique_name(&load.file_name, &taken); + meshes.high.push(added.clone()); + meshes.rebuild(); + } + + let textures = added.base_color.iter().flatten().filter(|color| !color.texels.is_empty()).count(); + self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", added.name, added.mesh.triangle_count())); + self.log.warnings("Baker", load.warnings); + for set in &mut self.doc.project.texture_sets { + set.bake.high_poly.use_low_as_high = false; + } + self.push_history(ADD_HIGH_POLY_LABEL, before); + added.name + } +} diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index fef27ea3..3a32bfa9 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -9,19 +9,26 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock}; use texturecraft_core::BakePaintTarget; -use super::{BakeCageInputs, MergedHigh}; +use super::{BakeCageInputs, HighPolyLoad, MergedHigh}; use crate::{BakeMesh, BakeTask, StreamedBake}; use serde_json::{Value, json}; use texturecraft_bake::tracing::Tracer; use texturecraft_bake::{BakeOutput, BakePaintMap, MAX_RAYS, Progress}; use texturecraft_core::{ - BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, SelfOcclusion, + BackfaceMode, BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap, CurvatureMethod, PositionMode, RayDistribution, RaySettings, + SelfOcclusion, }; use texturecraft_geom::Mesh; use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p}; use crate::{EngineError, Result, Session, cmd}; +/// Undo step names of the bake mesh edits +pub(super) const ADD_HIGH_POLY_LABEL: &str = "Add high poly mesh"; +const REMOVE_HIGH_POLY_LABEL: &str = "Remove high poly mesh"; +const SET_CAGE_LABEL: &str = "Load cage mesh"; +const REMOVE_CAGE_LABEL: &str = "Remove cage mesh"; + pub(super) fn specs() -> Vec { vec![ cmd!( @@ -29,7 +36,7 @@ pub(super) fn specs() -> Vec { "Bake mesh maps", ["Mode"], None, - "{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}", + "{ts?: index|[indices]|\"all\"|\"selected\", cpu?: true (skip the GPU), ...any bake.settings parameter} → {baked, tracer: [where each set's rays ran]}; settings reach sync partners, only the requested sets bake", always, bake_run ), @@ -55,8 +62,11 @@ pub(super) fn specs() -> Vec { cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))), cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set), cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| { - s.bake_meshes.cage = None; - s.modified = true; + if s.doc.bake_meshes.cage.is_some() { + let before = s.doc.clone(); + s.doc.bake_meshes.cage = None; + s.push_history(REMOVE_CAGE_LABEL, before); + } Ok(meshes_json(s)) }), ] @@ -86,36 +96,61 @@ fn chosen_tracer(installed: Option<&Arc>, enabled: bool) -> Option String { +/// A mesh file name made unique among `taken` (and safe as a project file entry) +pub(super) 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"); let base = texturecraft_formats::sanitize_resource_name(leaf); let mut name = base.clone(); - let mut n = 2; + let mut suffix = 2; while taken.contains(&name.as_str()) { - name = format!("{n}_{base}"); - n += 1; + name = format!("{suffix}_{base}"); + suffix += 1; } name } -fn parse_mesh(file_name: &str, bytes: Vec) -> Result { - let h = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; - let base_color = h.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); - Ok(BakeMesh { name: file_name.to_string(), bytes: Arc::new(bytes), mesh: Arc::new(h.mesh), base_color }) +pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { + let imported = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?; + let base_color = imported.base_color.into_iter().map(|c| c.map(Arc::new)).collect(); + let folder = std::path::Path::new(file_name).parent().map(|folder| folder.display().to_string()).filter(|folder| !folder.is_empty()); + Ok(BakeMesh { name: file_name.to_string(), folder, bytes: Arc::new(bytes), mesh: Arc::new(imported.mesh), base_color }) } impl Session { + /// The bake of texture set `texture_set`'s checked maps pub fn bake_task(&self, texture_set: usize) -> Result { + self.bake_task_of(texture_set, None) + } + + /// The bake of texture set `texture_set`'s map `map` alone, checked or not + pub fn bake_task_only(&self, texture_set: usize, map: BakedMap) -> Result { + self.bake_task_of(texture_set, Some(map)) + } + + /// Prepare a display-only bake, retaining previous pixels only for the displayed map's excluded UV tiles + pub fn bake_map_preview_task(&self, texture_set: usize, map: BakedMap) -> Result { + let mut task = self.bake_task_only(texture_set, map)?; + task.previous_maps.maps.retain(|&previous_map, _| previous_map == map); + Ok(task) + } + + fn bake_task_of(&self, texture_set: usize, only: Option) -> Result { let set = self.doc.project.texture_set(texture_set)?; if !set.has_enabled_bake_tiles() { return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name))); } - 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 + let mut settings = set.bake.clone(); + if let Some(map) = only { + settings.maps.select([map]); + } + + // Read from the maps that bake, so a map baked alone while unchecked still gets the colours + let needs_low_color = settings.maps.opacity.is_enabled + || (settings.maps.id.is_enabled && settings.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor); + let low_base_color = if needs_low_color && (settings.high_poly.use_low_as_high || self.doc.bake_meshes.high.is_empty()) { + self.doc + .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) @@ -146,7 +181,7 @@ impl Session { mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, - settings: set.bake.clone(), + settings, high, cage, skew, @@ -179,7 +214,7 @@ impl Session { /// The merged high polys texture set `texture_set` bakes from, unless it bakes from the low poly fn bake_high(&self, texture_set: usize) -> Result> { let set = self.doc.project.texture_set(texture_set)?; - Ok(if set.bake.high_poly.use_low_as_high { None } else { self.bake_meshes.merged.clone() }) + Ok(if set.bake.high_poly.use_low_as_high { None } else { self.doc.bake_meshes.merged.clone() }) } /// Texture set `texture_set`'s cage mesh when it bakes from a high poly with a Custom File cage @@ -189,7 +224,7 @@ impl Session { return Ok(None); } - let cage = self.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; + let cage = self.doc.bake_meshes.cage.as_ref().ok_or_else(|| EngineError::Other("Custom File requires a cage mesh".into()))?; Ok(Some(cage.mesh.clone())) } @@ -260,74 +295,79 @@ impl Session { Ok(tracer) } - /// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and - /// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name. + /// Add a high-definition mesh from file bytes as one undo step; every texture set then bakes from the high polys. Returns its name pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect(); - m.name = unique_name(file_name, &taken); - let textures = m.base_color.iter().flatten().filter(|c| !c.texels.is_empty()).count(); - self.log.info("Baker", format!("High poly {}: {} triangles, {textures} base color textures", m.name, m.mesh.triangle_count())); - let name = m.name.clone(); - self.bake_meshes.high.push(m); - self.bake_meshes.rebuild(); - for set in &mut self.doc.project.texture_sets { - set.bake.high_poly.use_low_as_high = false; - } - self.modified = true; - Ok(name) + let file = texturecraft_formats::MeshFile { name: file_name.to_string(), bytes, warnings: Vec::new() }; + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?; + Ok(self.apply_high_poly_load(load)) } - /// Remove high-definition mesh `index`. + /// Remove high-definition mesh `index` as one undo step pub fn remove_high_poly(&mut self, index: usize) -> Result { - if index >= self.bake_meshes.high.len() { + if index >= self.doc.bake_meshes.high.len() { return Err(EngineError::Other(format!("no high poly mesh {index}"))); } - let removed = self.bake_meshes.high.remove(index); - self.bake_meshes.rebuild(); - self.modified = true; + + let before = self.doc.clone(); + let removed = self.doc.bake_meshes.high.remove(index); + self.doc.bake_meshes.rebuild(); + self.push_history(REMOVE_HIGH_POLY_LABEL, before); Ok(removed) } - /// Use a cage mesh (same triangles as the low poly) from file bytes. + /// Use a cage mesh (same triangles as the low poly) from file bytes as one undo step. Returns its name pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - let mut m = parse_mesh(file_name, bytes)?; - if m.mesh.triangle_count() != self.mesh.triangle_count() { - return Err(EngineError::Other(format!( - "the cage has {} triangles but the low poly has {}; export the cage from the low poly", - m.mesh.triangle_count(), - self.mesh.triangle_count() - ))); - } - m.name = unique_name(file_name, &[]); - m.base_color.clear(); - let name = m.name.clone(); - self.bake_meshes.cage = Some(m); - self.modified = true; + let cage = self.cage_from_bytes(file_name, bytes)?; + let name = cage.name.clone(); + let before = self.doc.clone(); + self.doc.bake_meshes.cage = Some(cage); + self.push_history(SET_CAGE_LABEL, before); Ok(name) } - /// Add mesh file `f` as a high-definition mesh, or set it as the cage, logging what it could - /// not fold in. Replies like `bake.highPoly.add` / `bake.cage.set`: `{name, meshes}`. - pub fn add_bake_mesh(&mut self, f: texturecraft_formats::MeshFile, cage: bool) -> Result { - let name = if cage { self.set_cage_bytes(&f.name, f.bytes)? } else { self.add_high_poly_bytes(&f.name, f.bytes)? }; - self.log.warnings("Baker", f.warnings); + /// Parse a cage mesh file, refusing one whose triangles are not the low poly's + fn cage_from_bytes(&self, file_name: &str, bytes: Vec) -> Result { + let mut cage = parse_mesh(file_name, bytes)?; + if cage.mesh.triangle_count() != self.mesh.triangle_count() { + return Err(EngineError::Other(format!( + "the cage has {} triangles but the low poly has {}; export the cage from the low poly", + cage.mesh.triangle_count(), + self.mesh.triangle_count() + ))); + } + + cage.name = unique_name(file_name, &[]); + cage.base_color.clear(); + Ok(cage) + } + + /// Add mesh file `file` as a high poly or the cage, logging what it could not fold in; replies `{name, meshes}` like `bake.highPoly.add` / `bake.cage.set` + pub fn add_bake_mesh(&mut self, file: texturecraft_formats::MeshFile, cage: bool) -> Result { + let name = if cage { + let name = self.set_cage_bytes(&file.name, file.bytes)?; + self.log.warnings("Baker", file.warnings); + name + } else { + let load = HighPolyLoad::prepare(&self.doc.bake_meshes, file)?; + self.apply_high_poly_load(load) + }; Ok(json!({ "name": name, "meshes": meshes_json(self) })) } - /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped. + /// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped pub(crate) fn load_bake_meshes(&mut self, high: Vec, cage: Option) { for (name, bytes) in high { match parse_mesh(&name, bytes) { - Ok(m) => self.bake_meshes.high.push(m), + Ok(m) => self.doc.bake_meshes.high.push(m), Err(e) => self.log.warn("Baker", format!("skipped high poly mesh: {e}")), } } - self.bake_meshes.rebuild(); - if let Some((name, bytes)) = cage - && let Err(e) = self.set_cage_bytes(&name, bytes) - { - self.log.warn("Baker", format!("skipped cage mesh: {e}")); + self.doc.bake_meshes.rebuild(); + if let Some((name, bytes)) = cage { + match self.cage_from_bytes(&name, bytes) { + Ok(cage) => self.doc.bake_meshes.cage = Some(cage), + Err(e) => self.log.warn("Baker", format!("skipped cage mesh: {e}")), + } } } @@ -356,10 +396,10 @@ impl Session { .collect() } - /// The bake meshes for a project file: (high polys, cage). + /// The bake meshes for a project file: (high polys, cage) pub(crate) fn saved_bake_meshes(&self) -> (Vec, Option) { - let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone()); - (self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry)) + let entry = |mesh: &BakeMesh| (mesh.name.clone(), mesh.bytes.as_ref().clone()); + (self.doc.bake_meshes.high.iter().map(entry).collect(), self.doc.bake_meshes.cage.as_ref().map(entry)) } } @@ -367,7 +407,7 @@ impl Session { 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 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)| { + json!({ "highPoly": s.doc.bake_meshes.high.iter().map(one).collect::>(), "cage": s.doc.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::>() }) @@ -390,14 +430,18 @@ fn high_add(s: &mut Session, p: &Value) -> Result { fn high_remove(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { - s.bake_meshes.high.clear(); - s.bake_meshes.rebuild(); - s.modified = true; + if !s.doc.bake_meshes.high.is_empty() { + let before = s.doc.clone(); + s.doc.bake_meshes.high.clear(); + s.doc.bake_meshes.rebuild(); + s.push_history(REMOVE_HIGH_POLY_LABEL, before); + } return Ok(meshes_json(s)); } + let index = match (u64p(p, "index"), strp(p, "name")) { (Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX), - (None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, + (None, Some(n)) => s.doc.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?, (None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")), }; s.remove_high_poly(index)?; @@ -408,18 +452,25 @@ fn cage_set(s: &mut Session, p: &Value) -> Result { s.add_bake_mesh(read_mesh_file("bake.cage.set", p)?, true) } -/// Texture sets named by `ts` (default: the active one). -fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result> { - let n = s.set_count(); - 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.common.is_enabled)).collect()) +/// Texture sets named by `ts` (default: the active one) +pub(super) fn sets_param(session: &Session, command: &str, params: &Value) -> Result> { + let set_count = session.set_count(); + let parse_index = |value: &Value| { + value + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < set_count) + .ok_or_else(|| bad(command, format!("invalid texture set {value}"))) + }; + + match params.get("ts") { + Some(Value::String(selection)) if selection == "all" => Ok((0..set_count).collect()), + Some(Value::String(selection)) if selection == "selected" => { + Ok(session.doc.project.texture_sets.iter().enumerate().filter_map(|(index, set)| set.bake.common.is_enabled.then_some(index)).collect()) } - Some(Value::Array(a)) => a.iter().map(one).collect(), - Some(v) => Ok(vec![one(v)?]), - None => Ok(vec![s.ts()]), + Some(Value::Array(indices)) => indices.iter().map(parse_index).collect(), + Some(value) => Ok(vec![parse_index(value)?]), + None => Ok(vec![session.ts()]), } } @@ -465,14 +516,20 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> 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, boolp(params, "preset") == Some(true), None)?; - let is_enabled = settings.common.is_enabled; - *settings = replacement; + let (is_enabled, sync) = (settings.common.is_enabled, std::mem::take(&mut settings.sync)); + + // Sync membership is not a setting: only `bake.sync` changes it + *settings = BakeSettings { sync, ..replacement }; if boolp(params, "preserveEnabled") == Some(true) { settings.common.is_enabled = is_enabled; } } if let Some(patch) = params.get("patch") { + if patch.get("sync").is_some() { + return Err(bad(command, "use bake.sync to change sync membership")); + } + let mut model = json!(settings); model_patch::apply_patch(&mut model, patch, command)?; let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; @@ -708,19 +765,57 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< } fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { - 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(()) - })?; - } + let targets = updated_settings(session, params, command)?; + let sets = targets.iter().map(|(index, _)| *index).collect(); + let next = with_sync_partners(&session.doc.project, targets, command)?; + + super::sync_command::store(session, "Bake Settings", next)?; Ok(sets) } +/// `targets` plus every set sharing a sync group with a target, which takes the fields the target changed in that group; fails when a set's values come out inconsistent +fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { + let targets: BTreeMap = targets.into_iter().collect(); + + // Each explicit target already has its final settings + if targets.len() == project.texture_sets.len() { + return Ok(targets.into_iter().collect()); + } + + let mut next: BTreeMap = BTreeMap::new(); + for (target, settings) in &targets { + let Some(before) = project.texture_sets.get(*target).map(|set| &set.bake) else { continue }; + + if before == settings { + continue; + } + + let Some(changed) = model_patch::changed_fields(&json!(before), &json!(settings)) else { continue }; + + let groups = std::iter::once(BakeSyncGroup::Common).chain(BakedMap::ALL.map(BakeSyncGroup::Map)); + for group in groups { + for partner in project.bake_synced_sets(*target, group).into_iter().filter(|partner| !targets.contains_key(partner)) { + let Some(set) = project.texture_sets.get(partner) else { continue }; + + let entry = next.entry(partner).or_insert_with(|| set.bake.clone()); + + let mut model = json!(entry); + model_patch::apply_patch(&mut model, &changed, command)?; + let patched: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?; + entry.copy_group(&patched, group); + } + } + } + + // A copied value can conflict with a partner's retained settings + for settings in next.values() { + validate_model_settings(settings, command, false, Some(settings))?; + } + + next.extend(targets); + Ok(next.into_iter().collect()) +} + fn settings(session: &mut Session, params: &Value) -> Result { let sets = set_settings(session, params, "bake.settings")?; let result: Vec = sets @@ -748,11 +843,15 @@ fn bake_run(session: &mut Session, params: &Value) -> Result { return Ok(json!({"baked": [], "tracer": []})); } + let next = with_sync_partners(&session.doc.project, next, "bake.run")?; 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 tracers = Vec::with_capacity(sets.len()); + for &index in &sets { let mut task = session.bake_task(index)?; if cpu { task.tracer = None; @@ -823,3 +922,26 @@ mod gpu_raytracing_tests { assert!(chosen_tracer(None, true).is_none(), "no installed tracer bakes on the CPU"); } } + +#[cfg(test)] +mod bake_task_tests { + use std::sync::Arc; + + use texturecraft_core::BakedMap; + + #[test] + fn a_map_baked_alone_while_unchecked_still_reads_the_low_polys_colours() { + let mut session = crate::sample_session(128, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + let colours = Arc::new(vec![None]); + + // The sample bakes when made, which already read the colours + session.doc.bake_meshes.low_base_color = Default::default(); + assert!(session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())).is_ok()); + + assert!(session.bake_task(0).unwrap().low_base_color.is_empty(), "the checked maps need no colours"); + let task = session.bake_task_only(0, BakedMap::Opacity).unwrap(); + assert!(Arc::ptr_eq(&task.low_base_color, &colours), "Opacity reads them"); + assert!(task.settings.maps.opacity.is_enabled); + } +} diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index ef9dc935..1be548db 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -5,6 +5,7 @@ mod bake_checks; mod bake_mesh; mod bake_meshes; mod bake_task; +mod high_poly_load; mod high_poly_missed; mod layout; mod merged_high; @@ -14,12 +15,14 @@ mod paint_command; mod preserve_tiles; mod streamed_bake; mod streamed_map; +mod sync_command; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; pub use bake_task::BakeTask; +pub use high_poly_load::HighPolyLoad; pub use high_poly_missed::{HIDDEN_HIGH_POLY_VERTEX, high_poly_missed}; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, set_gpu_raytracing, settings_params}; @@ -36,5 +39,6 @@ pub(crate) fn specs() -> Vec { let mut commands = mesh_map_command::specs(); commands.extend(paint_command::specs()); commands.extend(tile_command::specs()); + commands.extend(sync_command::specs()); commands } diff --git a/crates/engine/src/bake/model_patch.rs b/crates/engine/src/bake/model_patch.rs index 871d7dc8..6532f914 100644 --- a/crates/engine/src/bake/model_patch.rs +++ b/crates/engine/src/bake/model_patch.rs @@ -9,7 +9,8 @@ pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value { changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({})) } -fn changed_fields(before: &Value, after: &Value) -> Option { +/// The fields of `after` that differ from `before`, nested as a `bake.settings` patch; `None` when nothing changed +pub(super) fn changed_fields(before: &Value, after: &Value) -> Option { if before == after { return None; } diff --git a/crates/engine/src/bake/sync_command.rs b/crates/engine/src/bake/sync_command.rs new file mode 100644 index 00000000..3d379cf0 --- /dev/null +++ b/crates/engine/src/bake/sync_command.rs @@ -0,0 +1,353 @@ +//! Sharing bake settings between texture sets: live sync groups, and one-off copies from the bake menus + +use serde_json::{Value, json}; +use texturecraft_core::{BakeSettings, BakeSyncGroup, BakedMap}; + +use super::mesh_map_command::sets_param; +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::{Result, Session, cmd}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "bake.sync", + "Sync bake settings", + [], + None, + "{group: \"common\"|map id, ts: index|[indices]|\"all\"} → {group, ts}; exactly these texture sets share the group's settings from now on, and the ones added take the settings the group shares", + always, + sync + ), + cmd!( + "bake.copy", + "Copy bake settings", + [], + None, + "{what: \"settings\"|\"checked\"|\"check\", map?: id, from?: index (default: the active set), ts: index|[indices]|\"all\"} → {ts}; settings: every setting and which maps are checked, or with map that map's settings; checked: which maps are checked; check: check map. Settings also reach the sets sharing a group with a target, whose checkboxes stay their own", + always, + copy + ), + ] +} + +fn group_param(params: &Value, command: &str) -> Result { + match strp(params, "group") { + Some("common") => Ok(BakeSyncGroup::Common), + Some(id) => BakedMap::parse(id).map(BakeSyncGroup::Map).ok_or_else(|| bad(command, format!("unknown group {id}"))), + None => Err(bad(command, "`group` must be \"common\" or a mesh map id")), + } +} + +fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn sync(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.sync"; + let group = group_param(params, COMMAND)?; + let members = sets_param(session, COMMAND, params)?; + let sets = &session.doc.project.texture_sets; + + let source = session.doc.project.bake_sync_source(group, &members, session.ts()); + let source = source.and_then(|index| sets.get(index)).map(|set| set.bake.clone()); + + let next: Vec<(usize, BakeSettings)> = sets + .iter() + .enumerate() + .map(|(index, set)| { + let mut settings = set.bake.clone(); + let joins = members.contains(&index); + if let Some(source) = source.as_ref().filter(|_| joins && !settings.sync.shares(group)) { + settings.copy_group(source, group); + } + settings.sync.set_shares(group, joins); + (index, settings) + }) + .collect(); + store(session, "Sync bake settings", next)?; + Ok(json!({ "group": group_id(group), "ts": members })) +} + +fn copy(session: &mut Session, params: &Value) -> Result { + const COMMAND: &str = "bake.copy"; + + let map = match params.get("map") { + None | Some(Value::Null) => None, + Some(value) => Some(value.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(COMMAND, format!("invalid mesh map {value}")))?), + }; + let from = match params.get("from") { + None | Some(Value::Null) => session.ts(), + Some(value) => value.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad(COMMAND, "`from` must be a texture set index"))?, + }; + let source = session.doc.project.texture_set(from)?.bake.clone(); + let targets = sets_param(session, COMMAND, params)?; + let maps: Vec = map.map_or_else(|| BakedMap::ALL.to_vec(), |map| vec![map]); + + let mut next: Vec = session.doc.project.texture_sets.iter().map(|set| set.bake.clone()).collect(); + let mut explicit = vec![false; next.len()]; + for &index in &targets { + explicit[index] = true; + } + + match strp(params, "what") { + Some("settings") => { + let groups = map.map_or_else( + || std::iter::once(BakeSyncGroup::Common).chain(maps.iter().map(|map| BakeSyncGroup::Map(*map))).collect(), + |map| vec![BakeSyncGroup::Map(map)], + ); + for group in groups { + let shared = targets.iter().any(|&index| next[index].sync.shares(group)); + for (index, settings) in next.iter_mut().enumerate() { + if explicit[index] || (shared && settings.sync.shares(group)) { + settings.copy_group(&source, group); + } + } + } + if map.is_none() { + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| explicit[*index]) { + for map in BakedMap::ALL { + settings.maps.set_enabled(map, source.maps.is_enabled(map)); + } + } + } + } + Some(what @ ("checked" | "check")) => { + if what == "check" && map.is_none() { + return Err(bad(COMMAND, "`check` needs a `map`")); + } + + for (_, settings) in next.iter_mut().enumerate().filter(|(index, _)| explicit[*index]) { + for map in &maps { + settings.maps.set_enabled(*map, what == "check" || source.maps.is_enabled(*map)); + } + } + } + _ => return Err(bad(COMMAND, "`what` must be settings, checked or check")), + } + + store(session, "Copy bake settings", next.into_iter().enumerate().collect())?; + Ok(json!({ "ts": targets })) +} + +/// Write each set's `next` bake settings as one undo step labelled `label`; nothing when none changed +pub(super) fn store(session: &mut Session, label: &str, next: Vec<(usize, BakeSettings)>) -> Result<()> { + let changed = + |session: &Session| next.iter().any(|(index, settings)| session.doc.project.texture_sets.get(*index).is_some_and(|set| set.bake != *settings)); + if !changed(session) { + return Ok(()); + } + + session.edit(label, |session| { + for (index, settings) in next { + session.doc.project.texture_set_mut(index)?.bake = settings; + } + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{execute, sample_session}; + use texturecraft_core::BakeSettings; + + /// A dilation only presets may hold, above what an edit may set + const LEGACY_DILATION: u32 = 200; + + fn session() -> Session { + let session = sample_session(128, 32).unwrap(); + assert_eq!(session.set_count(), 2); + session + } + + fn bake(session: &Session, index: usize) -> &BakeSettings { + &session.doc.project.texture_sets[index].bake + } + + #[test] + fn projects_saved_before_sync_share_everything() { + let settings: BakeSettings = serde_json::from_value(json!({ "common": { "dilation": 4 } })).unwrap(); + assert!(settings.sync.common); + assert!(BakedMap::ALL.iter().all(|map| settings.sync.shares(BakeSyncGroup::Map(*map)))); + } + + #[test] + fn a_set_left_out_of_common_sync_keeps_its_own_common_settings() { + let mut session = session(); + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0, 1]); + + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + + assert_eq!(session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Common), [1]); + assert_eq!(session.doc.project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync is separate"); + + let reached = session.doc.project.bake_synced_sets(0, BakeSyncGroup::Common); + execute(&mut session, "bake.settings", &json!({ "ts": reached, "patch": { "common": { "dilation": 7 } } })).unwrap(); + + assert_eq!((bake(&session, 0).common.dilation, bake(&session, 1).common.dilation), (7, 32)); + } + + #[test] + fn a_set_joining_a_group_takes_its_settings_and_keeps_its_own_inclusion() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 3; + session.doc.project.texture_sets[1].bake.common.is_enabled = false; + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[1].bake.common.dilation = 5; + + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": "all" })).unwrap(); + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": "all" })).unwrap(); + + assert_eq!(bake(&session, 1).maps.ao.parameters, bake(&session, 0).maps.ao.parameters); + assert_eq!(bake(&session, 1).common.dilation, bake(&session, 0).common.dilation); + assert!(!bake(&session, 1).common.is_enabled, "whether the set bakes is its own"); + + session.undo().unwrap(); + + assert_eq!(bake(&session, 1).common.dilation, 5, "one undo per sync"); + } + + #[test] + fn copies_check_maps_and_carry_settings_without_linking() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "height", "ts": [0] })).unwrap(); + session.doc.project.texture_sets[0].bake.maps.height.parameters.scaling_divisor = 9.0; + + execute(&mut session, "bake.copy", &json!({ "what": "check", "map": "height", "ts": "all" })).unwrap(); + + assert!(bake(&session, 0).maps.height.is_enabled && bake(&session, 1).maps.height.is_enabled); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "map": "height", "from": 0, "ts": [1] })).unwrap(); + + assert_eq!(bake(&session, 1).maps.height.parameters.scaling_divisor, 9.0); + assert!(!bake(&session, 1).sync.shares(BakeSyncGroup::Map(BakedMap::Height)), "a copy does not link"); + + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + execute(&mut session, "bake.copy", &json!({ "what": "checked", "from": 0, "ts": [1] })).unwrap(); + + assert_eq!(bake(&session, 1).maps.enabled().collect::>(), [BakedMap::Normal]); + } + + #[test] + fn a_copy_reaches_the_sets_sharing_the_group_with_its_target() { + let mut session = session(); + let third = session.doc.project.texture_sets[1].clone(); + session.doc.project.texture_sets.push(third); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [0, 1] })).unwrap(); + session.doc.project.texture_sets[2].bake.maps.ao.parameters.rays.rays = 3; + let height_checked = !bake(&session, 0).maps.is_enabled(BakedMap::Height); + session.doc.project.texture_sets[2].bake.maps.set_enabled(BakedMap::Height, height_checked); + + execute(&mut session, "bake.copy", &json!({ "what": "settings", "from": 2, "ts": [0] })).unwrap(); + + assert_eq!((bake(&session, 0).maps.ao.parameters.rays.rays, bake(&session, 1).maps.ao.parameters.rays.rays), (3, 3), "set 1 shares AO with set 0"); + assert!(!bake(&session, 2).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion))); + assert_eq!(bake(&session, 0).maps.is_enabled(BakedMap::Height), height_checked, "every setting includes which maps are checked"); + assert_ne!(bake(&session, 1).maps.is_enabled(BakedMap::Height), height_checked, "the set sharing a group keeps its own checkboxes"); + } + + #[test] + fn loading_a_preset_on_one_set_keeps_its_sync_groups_and_reaches_the_sets_sharing_them() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "ambientOcclusion", "ts": [1] })).unwrap(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = 9; + preset.maps.ao.parameters.rays.rays = 5; + preset.sync = Default::default(); + + let params = json!({ "ts": 0, "model": preset, "preserveEnabled": true, "preset": true }); + execute(&mut session, "bake.settings", ¶ms).unwrap(); + + assert!(!bake(&session, 0).sync.shares(BakeSyncGroup::Map(BakedMap::AmbientOcclusion)), "a preset is settings, not membership"); + assert_eq!(bake(&session, 1).common.dilation, 9, "set 1 shares Common Settings with set 0"); + assert_ne!(bake(&session, 1).maps.ao.parameters.rays.rays, 5, "set 1 no longer shares AO with set 0"); + } + + #[test] + fn a_change_to_one_group_leaves_the_other_groups_of_the_sets_sharing_it_alone() { + let mut session = session(); + session.doc.project.texture_sets[1].bake.common.dilation = 3; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 6 } } } } } })).unwrap(); + + assert_eq!(bake(&session, 1).maps.ao.parameters.rays.rays, 6); + assert_eq!(bake(&session, 1).common.dilation, 3); + } + + #[test] + fn an_edit_that_would_leave_a_synced_set_with_an_invalid_interval_changes_no_set() { + let mut session = session(); + session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.max_distance = 0.5; + session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.max_distance = 0.05; + let before = session.doc.project.texture_sets.clone(); + + let patch = json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "min_distance": 0.1 } } } } } }); + assert!(execute(&mut session, "bake.settings", &patch).is_err(), "set 1 would get a minimum above its maximum"); + assert_eq!(session.doc.project.texture_sets, before); + } + + #[test] + fn a_preset_with_a_legacy_value_loads_on_a_set_sharing_it() { + let mut session = session(); + let mut preset = bake(&session, 0).clone(); + preset.common.dilation = LEGACY_DILATION; + + execute(&mut session, "bake.settings", &json!({ "ts": 0, "model": preset, "preset": true })).unwrap(); + + assert_eq!(bake(&session, 1).common.dilation, LEGACY_DILATION, "set 1 shares Common Settings with set 0"); + } + + #[test] + fn a_settings_patch_cannot_change_sync_membership() { + let mut session = session(); + let original_sync = bake(&session, 0).sync.clone(); + + let result = execute(&mut session, "bake.settings", &json!({ "ts": 0, "patch": { "sync": { "common": false }, "common": { "dilation": 7 } } })); + + assert!(result.is_err(), "membership changes must go through bake.sync"); + assert_eq!(bake(&session, 0).sync, original_sync); + assert_eq!(bake(&session, 0).common.dilation, bake(&session, 1).common.dilation); + } + + #[test] + fn invalid_copy_selectors_do_not_overwrite_other_settings() { + let mut session = session(); + execute(&mut session, "bake.sync", &json!({ "group": "common", "ts": [0] })).unwrap(); + execute(&mut session, "bake.settings", &json!({ "ts": 1, "dilation": 7 })).unwrap(); + let before = session.doc.project.texture_sets.clone(); + + for params in [json!({ "what": "settings", "ts": 1, "from": "invalid" }), json!({ "what": "settings", "ts": 1, "map": false })] { + let result = execute(&mut session, "bake.copy", ¶ms); + + assert!(result.is_err(), "invalid selector in {params}"); + assert_eq!(session.doc.project.texture_sets, before); + } + } + + #[test] + fn running_a_bake_shares_settings_without_baking_or_checking_maps_on_partners() { + let mut session = session(); + let previous_resolution = bake(&session, 0).common.resolution; + let partner_maps = bake(&session, 1).maps.clone(); + session.doc.baked.clear(); + + let result = execute(&mut session, "bake.run", &json!({ "ts": 0, "resolution": 64, "maps": ["opacity"], "cpu": true })).unwrap(); + + assert_eq!(result["baked"], json!([0])); + assert_ne!(bake(&session, 0).common.resolution, previous_resolution); + assert_eq!(bake(&session, 1).common.resolution, bake(&session, 0).common.resolution); + assert_eq!(bake(&session, 1).maps, partner_maps); + assert!(!session.doc.baked.contains_key(&1)); + + session.undo().unwrap(); + + assert_eq!(bake(&session, 0).common.resolution, previous_resolution); + assert_eq!(bake(&session, 1).common.resolution, previous_resolution); + assert!(session.doc.baked.is_empty()); + } +} diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 4898ae1a..d8a03d8b 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Bake preview", [], None, - "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. In Bake mode the app's map preview also shows here while Mesh Map Settings is in front. With neither {active: false} (setting `show` is then an error)", always, preview )] @@ -82,18 +82,25 @@ impl Session { /// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before /// changing the preview or view mode. This reads settings without preparing bake geometry. pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> { - let orders = sets - .iter() - .map(|&texture_set| { - let set = self.doc.project.texture_set(texture_set)?; - Ok((texture_set, set.bake.maps.enabled().collect())) - }) - .collect::>>()?; - + let orders = self.bake_preview_orders(sets, None)?; self.bake_preview_begin(orders); Ok(()) } + /// Validate the entire selection before a bake takes the view or starts its first worker. + pub fn bake_preview_orders(&self, sets: &[usize], only: Option) -> Result)>> { + sets.iter() + .map(|&texture_set| { + let set = self.doc.project.texture_set(texture_set)?; + let maps = match only { + Some(map) => vec![map], + None => set.bake.maps.enabled().collect(), + }; + Ok((texture_set, maps)) + }) + .collect() + } + /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view /// follows the newest map and every set shows neutral values until its maps arrive. The /// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 006bb979..67a56736 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -209,8 +209,12 @@ 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 { bake_paint: Default::default(), project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?; + + let mut s = Session::new( + Document { bake_meshes: Default::default(), 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); @@ -608,10 +612,7 @@ impl Session { Some(self.doc.project.mesh_path.as_str()).filter(|m| !m.is_empty() && std::path::Path::new(m).is_file()) } - /// Replace the mesh with `file` (or re-read the project's own copy) and keep the project: - /// texture sets map by material index. Nothing changes unless the new mesh fits the project. - /// With `preserve_strokes`, painted pixels follow the surface where the UVs changed. Replies - /// like `file.reimportMesh`: `{preserved?}`. + /// Replace the mesh with `file` (or re-read the project's own copy), keeping the project when the new mesh fits it; `preserve_strokes` moves painted pixels with the surface; replies `{preserved?}` pub fn reimport_mesh(&mut self, file: Option, preserve_strokes: bool) -> Result { let (mesh, source, warnings, mesh_file) = match file { Some(f) => { @@ -625,27 +626,29 @@ impl Session { None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")), }, }; + check_materials(&self.doc.project, &mesh)?; let mut doc = self.doc.clone(); if let Some((ext, _)) = &source { doc.project.mesh = format!("mesh.{ext}"); doc.project.mesh_file = mesh_file; } + let mut next = Session::new(doc, mesh, source)?; next.log.warnings("Importer", warnings); next.path = self.path.clone(); next.sync_images(); // The cage uses triangle indices and barycentrics, so it needs identical geometry - next.bake_meshes = self.bake_meshes.clone(); - next.bake_meshes.low_base_color = Default::default(); - if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { - next.bake_meshes.cage = None; + next.doc.bake_meshes.low_base_color = Default::default(); + if next.doc.bake_meshes.cage.is_some() && *next.mesh != *self.mesh { + next.doc.bake_meshes.cage = None; next.log.warn("Project", "the cage mesh was dropped: the low-poly mesh changed"); } if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs { next.log.warn("Project", "the skew map is laid over the old UV layout; check it in Bake mode"); } + next.modified = true; next.project_id = self.project_id; let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next)); @@ -1486,19 +1489,24 @@ f 1/1 2/2 3/3 std::fs::create_dir_all(&dir).unwrap(); let a = dir.join("a.obj"); std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); - // Same triangle count, other vertices. + + // Same triangle count, other vertices let b = dir.join("b.obj"); std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap(); - let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; - s.bake_meshes.cage = Some(cage); - let _ = s.bake_meshes.low_base_color.set(Err("old".into())); - // The same mesh again keeps the cage but not the cached colours. + let cage = crate::bake::BakeMesh { name: "cage".into(), folder: None, bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() }; + s.doc.bake_meshes.cage = Some(cage); + let _ = s.doc.bake_meshes.low_base_color.set(Err("old".into())); + + // The same mesh again keeps the cage but not the cached colours crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_some()); - assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + + assert!(s.doc.bake_meshes.cage.is_some()); + assert!(s.doc.bake_meshes.low_base_color.get().is_none(), "the colours are read again"); + crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap(); - assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh"); + + assert!(s.doc.bake_meshes.cage.is_none(), "the cage was made for another mesh"); std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index cb0519b8..148af463 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -94,7 +94,7 @@ pub mod uv_tile_cmds; pub mod view_cmds; pub mod warp_cmds; -pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; +pub use bake::{BakeMesh, BakeMeshes, BakeTask, HighPolyLoad, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; pub use commands::{CommandSpec, check_enabled, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 678d7bb7..ac0b8636 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -70,7 +70,14 @@ pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); project.texture_sets.push(set); - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() } + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + } } impl Session { @@ -129,12 +136,22 @@ impl Session { .first() .and_then(|t| t.stack.last().copied()) .ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?; + let resources: BTreeMap>> = project_file.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); - let source = Document { bake_paint: BTreeMap::new(), project: project_file.project, pixels: project_file.pixels, baked: BTreeMap::new(), resources }; + let source = Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project: project_file.project, + pixels: project_file.pixels, + baked: BTreeMap::new(), + resources, + }; + let id = self.edit("Add smart material", |s| { for (name, bytes) in &source.resources { s.doc.resources.entry(name.clone()).or_insert_with(|| Arc::clone(bytes)); } + let ts = s.ts(); let sel = s.selected_layer(); let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group()); @@ -144,6 +161,7 @@ impl Session { s.target = StackTarget::Content; Ok(id) })?; + self.sync_images(); Ok(id) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 58b5cbe7..cb69ffb3 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -31,6 +31,8 @@ pub struct Document { pub bake_paint: BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc>, /// Imported image resources by name: original file bytes. pub resources: BTreeMap>>, + /// High-definition meshes and cage for baking (saved inside the project) + pub bake_meshes: crate::BakeMeshes, } /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). @@ -426,8 +428,6 @@ pub struct Session { pub bvh: Arc, /// Original mesh file (saved inside the project); None for built-in meshes. pub mesh_source: Option<(String, Vec)>, - /// High-definition meshes and cage for baking (saved inside the project). - pub bake_meshes: crate::BakeMeshes, pub caches: Vec, pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, @@ -525,7 +525,6 @@ impl Session { mesh, bvh: Arc::new(bvh), mesh_source, - bake_meshes: Default::default(), caches, undo: Vec::new(), redo: Vec::new(), @@ -604,8 +603,7 @@ impl Session { Session::new_project_tiled(name, mesh, mesh_ref, mesh_source, resolution, None) } - /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` for every - /// set, `Some(false)` for none, `None` for the sets whose UVs leave tile 1001. + /// [`Session::new_project`] choosing the UV tile (UDIM) mode: `Some(true)` every set, `Some(false)` none, `None` the sets whose UVs leave tile 1001 pub fn new_project_tiled( name: &str, mesh: Mesh, @@ -628,11 +626,20 @@ impl Session { ts.stack.push(id); project.texture_sets.push(ts); } + let mut s = Session::new( - Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, + Document { + bake_meshes: Default::default(), + bake_paint: BTreeMap::new(), + project, + pixels: PixelStore::default(), + baked: BTreeMap::new(), + resources: BTreeMap::new(), + }, mesh, mesh_source, )?; + s.log.append(log); Ok(s) } diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index 6b98e571..bbe0e243 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -234,14 +234,17 @@ impl Session { .and_then(|root| pf.project.layers.get(&root)) .and_then(|l| l.mask.clone()) .ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?; + let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); let src = crate::session::Document { + bake_meshes: Default::default(), bake_paint: BTreeMap::new(), project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: BTreeMap::new(), }; + let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); self.edit(&format!("Apply smart mask {label}"), |s| { let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 4c5314ad..4035c0f1 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -65,22 +65,90 @@ fn high_poly_meshes_drive_the_bake_and_round_trip() { // 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::>(); + let names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| (high.name.clone(), high.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.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj")); assert_eq!(reloaded.doc.project.texture_sets[0].bake, session.doc.project.texture_sets[0].bake); execute(&mut session, "bake.highPoly.remove", &json!({ "name": "hp_high.obj" })).unwrap(); - assert!(session.bake_meshes.high.is_empty()); + + assert!(session.doc.bake_meshes.high.is_empty()); execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); - assert!(session.bake_meshes.cage.is_none()); + + assert!(session.doc.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 high_poly_and_cage_edits_are_undo_steps() { + let mut session = plane_session(); + execute(&mut session, "bake.settings", &json!({ "ts": "all", "useLowAsHigh": true })).unwrap(); + let low = session.mesh.as_ref().clone(); + let high_names = |session: &Session| session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect::>(); + let merged_triangles = |session: &Session| session.doc.bake_meshes.merged_high().map(|merged| merged.mesh.triangle_count()); + + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + + assert_eq!(session.undo_label(), Some("Add high poly mesh")); + assert!(!session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high); + + session.undo().unwrap(); + + assert!(high_names(&session).is_empty(), "undo takes the high poly out"); + assert_eq!(merged_triangles(&session), None, "bakes no longer see it"); + assert!(session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high, "the setting the add changed comes back"); + + session.redo().unwrap(); + + assert_eq!(high_names(&session), ["part_high.obj"]); + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + execute(&mut session, "bake.highPoly.remove", &json!({ "index": 0 })).unwrap(); + session.undo().unwrap(); + + assert_eq!(high_names(&session), ["part_high.obj"], "undo brings a removed high poly back"); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + session.undo().unwrap(); + + assert_eq!(merged_triangles(&session), Some(low.triangle_count())); + + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.undo().unwrap(); + + assert!(session.doc.bake_meshes.cage.is_none(), "undo takes the cage out"); + session.redo().unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + session.undo().unwrap(); + + assert_eq!(session.doc.bake_meshes.cage.as_ref().map(|cage| cage.name.as_str()), Some("cage.obj"), "undo brings a removed cage back"); + + let steps = session.history_labels().len(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.highPoly.remove", &json!({ "all": true })).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + execute(&mut session, "bake.cage.clear", &Value::Null).unwrap(); + + assert_eq!(session.history_labels().len(), steps + 2, "removing nothing adds no step"); +} + +#[test] +fn opening_a_project_with_bake_meshes_adds_no_undo_step() { + let mut session = plane_session(); + let low = session.mesh.as_ref().clone(); + session.add_high_poly_bytes("part_high.obj", obj(&low, 0.002, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + session.set_cage_bytes("cage.obj", obj(&low, 0.05, f32::MAX, [1.0; 3]).into_bytes()).unwrap(); + + let reloaded = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert!(reloaded.doc.bake_meshes.cage.is_some() && reloaded.doc.bake_meshes.merged_high().is_some()); + assert!(reloaded.history_labels().is_empty()); + assert!(!reloaded.modified, "a project just opened has nothing to save"); +} + #[test] fn malformed_high_poly_input_errors_cleanly() { let mut session = plane_session(); @@ -94,7 +162,7 @@ fn malformed_high_poly_input_errors_cleanly() { 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!(session.doc.bake_meshes.high.is_empty() && session.doc.bake_meshes.cage.is_none()); assert_eq!(session.doc.project, before, "failed imports preserve project settings"); } @@ -373,6 +441,7 @@ fn opacity_samples_a_textured_gltf_high_poly() { let low = session.mesh.as_ref().clone(); let png = quadrants_png(); 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); @@ -380,7 +449,7 @@ fn opacity_samples_a_textured_gltf_high_poly() { // 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); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color); } /// USDZ opacity uses the UsdPreviewSurface texture alpha @@ -441,15 +510,17 @@ fn opacity_samples_textures_next_to_a_high_poly() { // 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}"); + assert_eq!(reloaded.doc.bake_meshes.high[0].base_color, session.doc.bake_meshes.high[0].base_color, "{file}"); } // 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 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(); @@ -661,7 +732,8 @@ fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3])); execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap(); execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap(); - // 1x1 PNG as an image resource. + + // A single-pixel image resource let png = [ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00, @@ -685,7 +757,7 @@ fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() { execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap(); assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh"); - assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays"); + assert_eq!(s.doc.bake_meshes.high.len(), 1, "the high poly stays"); assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays"); assert!(s.modified, "the project differs from the saved one"); assert_eq!(s.images.len(), 1, "image resources are decoded in the new session"); diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs index 4b60f6f0..97dd4610 100644 --- a/crates/ui-egui/src/bake_job.rs +++ b/crates/ui-egui/src/bake_job.rs @@ -1,3 +1,5 @@ +use texturecraft_engine::core::BakedMap; + use crate::RunningBake; /// A background bake of one or more texture sets. @@ -7,4 +9,6 @@ pub struct BakeJob { pub total: usize, /// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied. pub mesh_id: u64, + /// The one map to bake (a row's quick bake) instead of the checked ones + pub only: Option, } diff --git a/crates/ui-egui/src/bake_mode/bake_checks.rs b/crates/ui-egui/src/bake_mode/bake_checks.rs index 36b91298..4245a5a1 100644 --- a/crates/ui-egui/src/bake_mode/bake_checks.rs +++ b/crates/ui-egui/src/bake_mode/bake_checks.rs @@ -50,7 +50,7 @@ pub(crate) fn cached_warnings(ctx: &egui::Context, session: &Session) -> Arc, Arc>)>(id)) && cached_key == key && cached_high.ptr_eq(&high) diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs index 5c4d02cc..143bbda7 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_panel.rs @@ -1,9 +1,11 @@ use egui::collapsing_header::CollapsingState; use egui::{Rect, Ui, vec2}; use egui_phosphor::regular as icon; +use texturecraft_engine::core::{BakeResolution, BakedMap}; use texturecraft_render::BakeOverlay; use super::BakeVisualizationToggles; +use super::map_preview_fold::MapPreviewFold; use super::section_opening::SectionOpening; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; @@ -25,6 +27,10 @@ const ROW_BUTTON_SIZE: f32 = 18.0; /// Width of an overlay's color swatch const SWATCH_WIDTH: f32 = 44.0; +/// The map preview's sizes and how the list names them +const PREVIEW_SIZES: [(BakeResolution, &str); 4] = + [(BakeResolution::R128, "128"), (BakeResolution::R256, "256"), (BakeResolution::R512, "512"), (BakeResolution::R1024, "1K")]; + /// The neutral material's quality steps: samples per pixel and their names const QUALITIES: [(u32, &str); 6] = [ (4, n_("Very Low (4 spp)")), @@ -37,6 +43,8 @@ const QUALITIES: [(u32, &str); 6] = [ /// The Baking Visualization panel in the top-left corner of bake mode's 3D view `view` pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: Rect) { + let matching_error_applies = super::matching_error_applies(&app.session); + let (shown, selected) = (app.live_preview.shown(), super::live_preview::map_settings_shown(app).map(|target| target.map)); let toggles = &mut app.ui.bake_visualization; let tokens = Tokens::get(ui.ctx()); egui::Area::new(ui.scope_id().with("bake_visualization_panel")).fixed_pos(view.left_top() + vec2(PANEL_MARGIN, PANEL_MARGIN)).constrain_to(view).show( @@ -46,20 +54,20 @@ pub(crate) fn bake_visualization_panel(app: &mut TextureCraftApp, ui: &Ui, view: egui::Frame::popup(ui.style()).fill(tokens.panel.gamma_multiply(PANEL_OPACITY)).show(ui, |ui| { ui.set_width(PANEL_WIDTH); - // Ids renamed with the reference defaults, so open/closed states saved by earlier builds don't carry over + // New section IDs keep legacy fold states separate let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("baking_visualization_open"), true); if header(ui, toggles, collapsing_state.is_open()).clicked() { collapsing_state.toggle(ui); } - collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles)); + collapsing_state.show_body_unindented(ui, |ui| sections(ui, toggles, matching_error_applies, shown, selected)); }); }, ); } -/// The panel's sections below its header -fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { +/// The panel's sections below its header; the Matching Error row greys unless `matching_error_applies` +fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, matching_error_applies: bool, shown: Option, selected: Option) { ui.horizontal(|ui| { ui.checkbox(&mut toggles.selected_set_only, tr("Show for Selected Texture Set Only")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -72,7 +80,7 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { let meshes_editable = !toggles.hide_baking_meshes; if collapsible(ui, "high_poly", tr("High Definition Mesh (HP)"), SectionOpening::Open, true, meshes_editable, |ui| { overlay_row(ui, "bake_high_poly_color", tr("Mesh"), &mut toggles.high_poly_mesh); - overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error); + ui.add_enabled_ui(matching_error_applies, |ui| overlay_row(ui, "bake_matching_error_color", tr("Matching Error"), &mut toggles.matching_error)); }) { toggles.reset_high_poly(); } @@ -100,6 +108,42 @@ fn sections(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { }) { toggles.reset_project_mesh(); } + + map_preview_section(ui, toggles, shown, selected); +} + +/// The Map Preview section: whether the selected map shows on the model, and the size it bakes at; it opens by itself while a preview shows +fn map_preview_section(ui: &mut Ui, toggles: &mut BakeVisualizationToggles, shown: Option, selected: Option) { + let fold_id = ui.make_persistent_id("map_preview_fold"); + let mut fold: MapPreviewFold = ui.ctx().data(|data| data.get_temp(fold_id)).unwrap_or_default(); + let section = section_id(ui, "map_preview"); + let mut state = CollapsingState::load_with_default_open(ui.ctx(), section, false); + if let Some(open) = fold.follow(shown, selected, !toggles.map_preview) { + state.set_open(open); + state.store(ui.ctx()); + } + let open_before = state.is_open(); + + let reset = collapsible(ui, "map_preview", tr("Map Preview"), SectionOpening::Closed, true, true, |ui| { + ui.checkbox(&mut toggles.map_preview, tr("Preview the Selected Map")); + ui.add_enabled_ui(toggles.map_preview, |ui| { + let size = &mut toggles.map_preview_size; + let selected = PREVIEW_SIZES.iter().find(|(option, _)| option == size).map_or("", |(_, name)| *name); + combo(ui, tr("Resolution"), selected, |ui| { + for (option, name) in PREVIEW_SIZES { + ui.selectable_value(size, option, name); + } + }); + }); + }); + let open_after = CollapsingState::load_with_default_open(ui.ctx(), section, false).is_open(); + if open_after != open_before { + fold.toggled(open_after); + } + ui.ctx().data_mut(|data| data.insert_temp(fold_id, fold)); + if reset { + toggles.reset_map_preview(); + } } /// The project mesh's neutral material (picked in the 3D view's view menu): its quality, roughness, metallic, occlusion strength and bent normal @@ -126,8 +170,7 @@ fn neutral_material(ui: &mut Ui, toggles: &mut BakeVisualizationToggles) { /// A section `title`, open or closed at first as `opening` says, with a reset button on its header when `resettable` and its contents greyed unless `editable`; returns whether the reset was clicked fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, resettable: bool, editable: bool, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); - let mut collapsing_state = - CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id(("baking_visualization_section", id)), opening == SectionOpening::Open); + let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), section_id(ui, id), opening == SectionOpening::Open); let (header, reset) = ui .horizontal(|ui| { ui.set_min_height(EYE_BUTTON_SIZE); @@ -151,12 +194,20 @@ fn collapsible(ui: &mut Ui, id: &str, title: &str, opening: SectionOpening, rese collapsing_state.toggle(ui); } + header.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + ui.ctx().accesskit_node_builder(header.id, |node| node.set_expanded(collapsing_state.is_open())); + crate::property_sheet::paint_keyboard_focus(ui, &header, &tokens); collapsing_state.show_body_indented(&header, ui, |ui| { ui.add_enabled_ui(editable, body); }); reset.is_some_and(|reset| reset.clicked()) } +/// The id a section keeps its open state under +fn section_id(ui: &Ui, id: &str) -> egui::Id { + ui.make_persistent_id(("baking_visualization_section", id)) +} + /// A checkbox for whether `overlay` shows, with its color swatch and an eyedropper for it on the right fn overlay_row(ui: &mut Ui, id: &str, label: &str, overlay: &mut BakeOverlay) { ui.horizontal(|ui| { diff --git a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs index bb99e09b..d638da81 100644 --- a/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs +++ b/crates/ui-egui/src/bake_mode/bake_visualization_toggles.rs @@ -1,4 +1,5 @@ use serde::{Deserialize, Serialize}; +use texturecraft_engine::core::BakeResolution; use texturecraft_render::{BakeOverlay, BakeVisualization, NeutralMaterial}; /// Opacity of the cage's surface and wireframe until changed @@ -20,6 +21,10 @@ pub struct BakeVisualizationToggles { /// Show the project mesh with [`Self::neutral`] instead of its painted material pub neutral_shown: bool, pub neutral: NeutralMaterial, + /// Show the selected map on the model while Mesh Map Settings shows its settings + pub map_preview: bool, + /// The size the map preview bakes at once a change settles + pub map_preview_size: BakeResolution, } impl Default for BakeVisualizationToggles { @@ -37,6 +42,9 @@ impl Default for BakeVisualizationToggles { project_mesh: shown(parts.low_poly), neutral_shown: true, neutral: NeutralMaterial::default(), + // Web builds bake on the UI thread, so the preview there is opt-in + map_preview: !cfg!(target_arch = "wasm32"), + map_preview_size: BakeResolution::R256, } } } @@ -85,6 +93,12 @@ impl BakeVisualizationToggles { self.missing_seams = Self::default().missing_seams; } + /// Put the Map Preview section back to its defaults + pub fn reset_map_preview(&mut self) { + let defaults = Self::default(); + (self.map_preview, self.map_preview_size) = (defaults.map_preview, defaults.map_preview_size); + } + /// Put the Project Mesh section back to its defaults pub fn reset_project_mesh(&mut self) { let defaults = Self::default(); diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 14dc7fd5..d49263d6 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -1,35 +1,95 @@ -use egui::{RichText, Ui}; +use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; use texturecraft_engine::core::BakedMap; use crate::TextureCraftApp; use crate::i18n::{baked_map_label, tr}; +use crate::theme::{Tokens, semibold}; -/// The texture set and selected map above Mesh Map Settings, each behind a dropdown to switch it -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap) { +/// The breadcrumb's line and the air under its hairline +const LINE_HEIGHT: f32 = 32.0; +const AIR_BELOW: f32 = 10.0; + +/// A caret's click square, and the air between a caret and its name +const CARET_BOX: f32 = 18.0; +const CARET_TO_NAME: f32 = 4.0; + +/// Air between the set's name and the next caret +const NAME_TO_CARET: f32 = 8.0; + +/// Size of the carets and of the reset glyph +const CARET_SIZE: f32 = 12.0; +const RESET_SIZE: f32 = 14.0; +const RESET_BOX: f32 = 20.0; + +/// Size of the names +const NAME_SIZE: f32 = 12.0; + +/// › texture set › map above Mesh Map Settings, each caret a menu to switch it, with ⟲ (Restore Defaults) at the right when the map has parameters; a long set name is cut with "…"; returns whether ⟲ was clicked +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, restorable: bool) -> bool { + let tokens = Tokens::get(ui.ctx()); let active_set = app.session.ts(); - let set_names: Vec = app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.name.clone()).collect(); + let (line, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_HEIGHT), Sense::hover()); + let center_y = line.center().y; + let painter = ui.painter().clone(); - ui.horizontal(|ui| { - ui.menu_button(icon::CARET_RIGHT, |ui| { - for (set_index, name) in set_names.iter().enumerate() { - if ui.selectable_label(set_index == active_set, name).clicked() { - app.run("textureSet.select", json!({ "ts": set_index })); - ui.close(); - } - } - }); - ui.label(set_names.get(active_set).map_or("", String::as_str)); + let mut x = line.left(); + let set_caret = caret(ui, &painter, &tokens, x, center_y, "texture_set_caret", tr("Switch Texture Set")); + x += CARET_BOX + CARET_TO_NAME; + let set_name = app.session.doc.project.texture_sets.get(active_set).map_or("", |set| set.name.as_str()); + let map_name = tr(baked_map_label(selected)); + let map_width = painter.layout_no_wrap(map_name.to_owned(), semibold(NAME_SIZE), tokens.text_strong).size().x; + let reset_width = if restorable { RESET_BOX } else { 0.0 }; + let set_room = line.right() - reset_width - map_width - CARET_TO_NAME - CARET_BOX - NAME_TO_CARET - x; + let set_galley = crate::widgets::elided(&painter, set_name, NAME_SIZE, tokens.text, set_room); + let set_width = set_galley.size().x; + painter.galley(pos2(x, center_y - set_galley.size().y / 2.0), set_galley, tokens.text); + x += set_width + NAME_TO_CARET; + let map_caret = caret(ui, &painter, &tokens, x, center_y, "map_caret", tr("Switch Mesh Map")); + x += CARET_BOX + CARET_TO_NAME; + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, map_name, semibold(NAME_SIZE), tokens.text_strong); - ui.menu_button(icon::CARET_RIGHT, |ui| { - for map in BakedMap::ALL { - if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { - app.ui.selected_baked_map = Some(map); - ui.close(); - } + egui::Popup::menu(&set_caret).show(|ui| { + for (set_index, set) in app.session.doc.project.texture_sets.iter().enumerate() { + if ui.selectable_label(set_index == active_set, &set.name).clicked() { + app.run("textureSet.select", json!({ "ts": set_index })); + break; } - }); - ui.label(RichText::new(tr(baked_map_label(selected))).strong()); + } }); + egui::Popup::menu(&map_caret).show(|ui| { + for map in BakedMap::ALL { + if ui.selectable_label(map == selected, tr(baked_map_label(map))).clicked() { + app.ui.selected_baked_map = Some(map); + } + } + }); + + let mut restore = false; + if restorable { + let rect = Rect::from_center_size(pos2(line.right() - RESET_BOX / 2.0, center_y), vec2(RESET_BOX, RESET_BOX)); + let response = ui.interact(rect, ui.scope_id().with("restore_defaults"), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, tr("Restore Defaults"))); + let response = response.on_hover_text(tr("Restore Defaults")); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(RESET_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + restore = response.clicked(); + } + + painter.line_segment([pos2(line.left(), line.bottom()), pos2(line.right(), line.bottom())], Stroke::new(1.0, tokens.separator)); + ui.add_space(AIR_BELOW); + restore +} + +/// A caret at `left` that opens a menu, answering as `label` +fn caret(ui: &mut Ui, painter: &egui::Painter, tokens: &Tokens, left: f32, center_y: f32, salt: &str, label: &str) -> egui::Response { + let rect = Rect::from_min_size(pos2(left, center_y - CARET_BOX / 2.0), vec2(CARET_BOX, CARET_BOX)); + let response = ui.interact(rect, ui.scope_id().with(salt), Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, true, label)); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, icon::CARET_RIGHT, FontId::proportional(CARET_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, tokens); + response } diff --git a/crates/ui-egui/src/bake_mode/common_settings.rs b/crates/ui-egui/src/bake_mode/common_settings.rs index 1953d2d3..7aac6239 100644 --- a/crates/ui-egui/src/bake_mode/common_settings.rs +++ b/crates/ui-egui/src/bake_mode/common_settings.rs @@ -1,139 +1,161 @@ -use super::controls::{choice, hint, integer, number, section, text_input}; +use super::controls::{choice, integer, number, section, text_input}; use crate::TextureCraftApp; use crate::i18n::tr; -use crate::theme::Tokens; -use crate::widgets::icon_button; -use egui::Ui; +use crate::property_sheet::{FileListAdd, FileRow, PropertySheet}; use egui_phosphor::regular as icon; use serde_json::{Map, Value, json}; use texturecraft_engine::core::{ BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod, }; -/// How many rows the high poly list box is tall -const HIGH_POLY_LIST_ROWS: f32 = 5.0; +/// The high poly list is never shorter than this many rows, so it reads as a list while empty +const HIGH_POLY_LIST_MIN_ROWS: usize = 2; -/// Space between the panel's sections, in points -const SECTION_GAP: f32 = 8.0; +/// The Cage and Skew Correction ⟲ menus' items, in their order: reset the parameters, clear the paint strokes, both +const RESET_PARAMETERS: usize = 0; +const CLEAR_STROKES: usize = 1; +const RESET_AND_CLEAR: usize = 2; + +/// The cage list holds one file, so one row shows while it is empty +const CAGE_LIST_MIN_ROWS: usize = 1; + +/// Largest cage distance the sliders offer, and their decimals (relative to the bounding box, the reference's range) +const MAX_CAGE_DISTANCE: f32 = 0.05; +const CAGE_DISTANCE_DECIMALS: usize = 4; + +/// A paint brush's first value: half the frontal distance for the cage, full correction for skew +const CAGE_BRUSH_VALUE: f32 = 0.5; +const SKEW_BRUSH_VALUE: f32 = 1.0; + +/// The paint brush's radius range, in UV units +const BRUSH_RADIUS: std::ops::RangeInclusive = 0.002..=0.2; /// Widest dilation the slider offers, in texels (the bake settings command accepts the same) const MAX_DILATION_WIDTH: u32 = 128; -/// The output and high-poly sections, then cage and skew, greyed with the reason when they can't apply -pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option { +/// The Common Settings, Cage and Skew Correction sections, cage and skew greyed with the reason when they can't apply +pub(super) fn show(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, settings: &mut BakeSettings) -> Option { let mut reset = Map::new(); - ui.push_id("common", |ui| { - // Restore Defaults keeps whether the texture set is included in the bake - let is_enabled = settings.common.is_enabled; - if section(ui, tr("Common Parameters"), |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..=MAX_DILATION_WIDTH); - ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion")); - }) { - settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() }; - let mut defaults = json!(settings.common); - if let Some(fields) = defaults.as_object_mut() { - fields.remove("is_enabled"); - } - reset.insert("common".into(), defaults); - } - }); + let has_high = !app.session.doc.bake_meshes.high.is_empty(); + let common_reset = section(sheet, tr("Common Settings"), &[], |sheet| { + sheet.sub_header(tr("Output Settings"), |sheet| { + output_size(sheet, &mut settings.common); + let antialiasing = BakeAntialiasing::ALL.map(|option| (option, antialiasing_label(option))); + choice(sheet, tr("Antialiasing"), &mut settings.common.antialiasing, &antialiasing); + integer(sheet, tr("Dilation Width"), &mut settings.common.dilation, 0..=MAX_DILATION_WIDTH); + sheet.check(tr("Apply Diffusion"), &mut settings.common.apply_diffusion); + }); + sheet.sub_header(tr("High-Poly Parameters"), |sheet| { + sheet.check(tr("Use Low Poly Mesh as High Poly Mesh"), &mut settings.high_poly.use_low_as_high); + high_poly_scene(app, sheet); - // Without a high poly the reference shows everything that needs one greyed, not hidden - let has_high = !app.session.bake_meshes.high.is_empty(); - ui.add_space(SECTION_GAP); - ui.push_id("high_poly", |ui| { - if section(ui, tr("High-Poly Parameters"), |ui| { - ui.checkbox(&mut settings.high_poly.use_low_as_high, tr("Use Low Poly Mesh as High Poly Mesh")); - high_poly_scene(app, ui); - ui.add_enabled_ui(has_high, |ui| { - ui.checkbox(&mut settings.high_poly.ignore_backface, tr("Ignore Backface")); + // Keep high-poly controls visible when their input is missing + sheet.greyed(has_high, Some(tr("These settings apply once a high poly mesh is loaded.")), |sheet| { + sheet.check(tr("Ignore Backface"), &mut settings.high_poly.ignore_backface); choice( - ui, + sheet, 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); + text_input(sheet, tr("Low Poly Mesh Suffix"), &mut settings.high_poly.low_suffix); + text_input(sheet, tr("High Poly Mesh Suffix"), &mut settings.high_poly.high_suffix); + text_input(sheet, tr("Ignore Backface Suffix"), &mut settings.high_poly.ignore_backface_suffix); }); - }) { - settings.high_poly = Default::default(); - reset.insert("high_poly".into(), json!(settings.high_poly)); + }); + }); + if common_reset.is_some() { + // Restoring keeps whether the texture set is included in the bake + settings.common = CommonBakeSettings { is_enabled: settings.common.is_enabled, ..CommonBakeSettings::default() }; + let mut defaults = json!(settings.common); + if let Some(fields) = defaults.as_object_mut() { + fields.remove("is_enabled"); + } + reset.insert("common".into(), defaults); + settings.high_poly = Default::default(); + reset.insert("high_poly".into(), json!(settings.high_poly)); + } + + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Cage Parameters"), tr("Clear All Cage Paint Strokes"), tr("Reset and Clear All")); + let cage_reset = section(sheet, tr("Cage"), &menu, |sheet| { + // The cage steers rays toward a separate high poly, so it has nothing to do without one + let cage_applies = has_high && !settings.high_poly.use_low_as_high; + let reason = if has_high { + tr("The cage is not used while the low poly mesh is used as the high poly mesh.") + } else { + tr("The cage applies once a high poly mesh is loaded.") + }; + sheet.greyed(cage_applies, Some(reason), |sheet| { + choice( + sheet, + tr("Cage Type"), + &mut settings.cage.kind, + &[ + (CageType::DistanceBased, tr("Distance-Based")), + (CageType::Automatic, tr("Automatic (Experimental)")), + (CageType::CustomFile, tr("Custom File")), + ], + ); + if settings.cage.kind == CageType::DistanceBased { + paint_button(app, sheet, BakePaintTarget::Cage); + sheet.indented(|sheet| { + number(sheet, tr("Max Frontal Distance"), &mut settings.cage.max_frontal, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + number(sheet, tr("Max Rear Distance"), &mut settings.cage.max_rear, 0.0..=MAX_CAGE_DISTANCE, CAGE_DISTANCE_DECIMALS); + sheet.check(tr("Relative to Bounding Box"), &mut settings.cage.relative_to_bounding_box); + sheet.check(tr("Average Normals"), &mut settings.cage.average_normals); + }); + } + }); + + // A loaded cage stays listed and removable while the cage can't apply, so a saved one can still be dropped + if settings.cage.kind == CageType::CustomFile { + cage_file(app, sheet, cage_applies); } }); - - ui.add_space(SECTION_GAP); - ui.push_id("cage", |ui| { - if section(ui, tr("Cage"), |ui| { - // The cage steers rays toward a separate high poly, so it has nothing to do without one - let cage_applies = has_high && !settings.high_poly.use_low_as_high; - if !has_high { - hint(ui, tr("The cage applies once a high poly mesh is loaded.")); - } else if !cage_applies { - hint(ui, tr("The cage is not used while the low poly mesh is used as the high poly mesh.")); - } - ui.add_enabled_ui(cage_applies, |ui| { - choice( - ui, - tr("Cage Type"), - &mut settings.cage.kind, - &[(CageType::DistanceBased, tr("Distance-Based")), (CageType::CustomFile, tr("Custom File"))], - ); - if settings.cage.kind == CageType::DistanceBased { - 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")); - ui.checkbox(&mut settings.cage.average_normals, tr("Average Normals")); - } - }); - if settings.cage.kind == CageType::CustomFile { - cage_file(app, ui, cage_applies); - } - }) { + if let Some(item) = cage_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.cage = Default::default(); reset.insert("cage".into(), json!(settings.cage)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.cage.reset", json!({})); + } + } - // Shown greyed when it can't apply, as the reference does, with the reason on top + // Explain why the disabled control is unavailable let skew_applies = has_high && settings.skew_applies(); - ui.add_space(SECTION_GAP); - ui.push_id("skew", |ui| { - if section(ui, tr("Skew Correction"), |ui| { - if !skew_applies { - hint(ui, skew_unavailable_reason(settings, has_high)); - } - ui.add_enabled_ui(skew_applies, |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); + let mut menu = [""; 3]; + (menu[RESET_PARAMETERS], menu[CLEAR_STROKES], menu[RESET_AND_CLEAR]) = + (tr("Reset Skew Correction Parameters"), tr("Clear All Skew Paint Strokes"), tr("Reset and Clear All")); + let skew_reset = section(sheet, tr("Skew Correction"), &menu, |sheet| { + sheet.greyed(skew_applies, Some(skew_unavailable_reason(settings, has_high)), |sheet| { + paint_button(app, sheet, BakePaintTarget::Skew); + sheet.check(tr("Edge Protection"), &mut settings.skew.edge_protection); + sheet.greyed(settings.skew.edge_protection, None, |sheet| { + sheet.indented(|sheet| { + number(sheet, tr("Edge Distance"), &mut settings.skew.edge_distance, 0.0..=1.0, 2); + number(sheet, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2); + }); }); - }) { + choice( + sheet, + tr("Skew Correction Method"), + &mut settings.skew.method, + &[(SkewCorrectionMethod::MeshNormalsBased, tr("Mesh Normals Based")), (SkewCorrectionMethod::FaceNormalsBased, tr("Face Normals Based"))], + ); + }); + }); + if let Some(item) = skew_reset { + if matches!(item, RESET_PARAMETERS | RESET_AND_CLEAR) { settings.skew = Default::default(); reset.insert("skew".into(), json!(settings.skew)); } - }); + if matches!(item, CLEAR_STROKES | RESET_AND_CLEAR) { + app.run("bake.skew.clear", json!({})); + } + } (!reset.is_empty()).then_some(Value::Object(reset)) } @@ -146,130 +168,127 @@ fn skew_unavailable_reason(settings: &BakeSettings, has_high: bool) -> &'static tr("Skew Correction is not available while the low poly mesh is used as the high poly mesh.") } else if settings.cage.kind == CageType::CustomFile { tr("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself.") + } else if settings.cage.kind == CageType::Automatic { + tr("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is.") } else { tr("Skew Correction needs Average Normals turned on in the cage settings.") } } -fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) { - ui.label(tr("Output Size")); - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let dropdown_width = ((ui.available_width() - button_size - ui.spacing().item_spacing.x * 2.0) / 2.0).max(40.0); - let resolution = |ui: &mut Ui, id: &str, value: &mut BakeResolution| { - egui::ComboBox::from_id_salt(id).width(dropdown_width).selected_text(value.pixels().to_string()).show_ui(ui, |ui| { - for resolution in BakeResolution::ALL { - 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, button_size).clicked() { - settings.resolution_height = if locked { Some(settings.resolution) } else { None }; - } - }); +/// How the Antialiasing dropdown names `antialiasing` +pub(super) fn antialiasing_label(antialiasing: BakeAntialiasing) -> &'static str { + match antialiasing { + BakeAntialiasing::None => tr("None"), + BakeAntialiasing::Subsampling2x2 => tr("Subsampling 2x2"), + BakeAntialiasing::Subsampling4x4 => tr("Subsampling 4x4"), + BakeAntialiasing::Subsampling8x8 => tr("Subsampling 8x8"), + } } -/// The high poly meshes as a list box, with + to add some and − to remove the selected one -fn high_poly_scene(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - let names: Vec = app.session.bake_meshes.high.iter().map(|mesh| mesh.name.clone()).collect(); - let selected_id = ui.make_persistent_id("high_poly_selected"); - let mut selected = ui.data(|data| data.get_temp::(selected_id)).filter(|index| *index < names.len()); +/// The smallest output size offered, as in the reference; a project saved with a smaller one keeps it +const SMALLEST_OUTPUT_SIZE: u32 = 32; - ui.label(tr("High Poly Scene")); - let (mut add, mut remove) = (false, false); - ui.horizontal_top(|ui| { - let button_size = ui.spacing().interact_size.y; - let list_width = (ui.available_width() - button_size - ui.spacing().item_spacing.x).max(0.0); - let list_height = HIGH_POLY_LIST_ROWS * ui.spacing().interact_size.y; - egui::Frame::NONE.fill(tokens.field).stroke(egui::Stroke::new(1.0, tokens.field_border)).corner_radius(tokens.cr()).show(ui, |ui| { - ui.set_min_size(egui::vec2(list_width, list_height)); - ui.set_max_width(list_width); - egui::ScrollArea::both().id_salt("high_poly_list").max_height(list_height).auto_shrink([false; 2]).show(ui, |ui| { - for (index, name) in names.iter().enumerate() { - if ui.selectable_label(selected == Some(index), name).on_hover_text(name).clicked() { - selected = Some(index); - } - } - }); - }); - ui.vertical(|ui| { - add = icon_button(ui, icon::PLUS, tr("Add High-Poly Meshes"), false, button_size).clicked(); - remove = ui.add_enabled_ui(selected.is_some(), |ui| icon_button(ui, icon::MINUS, tr("Remove"), false, button_size)).inner.clicked(); - }); - }); +/// Width, the link, then the height it ties to the width, as in the reference +fn output_size(sheet: &mut PropertySheet<'_>, settings: &mut CommonBakeSettings) { + let sizes: Vec = BakeResolution::ALL.into_iter().filter(|resolution| resolution.pixels() >= SMALLEST_OUTPUT_SIZE).collect(); + let mut linked = settings.resolution_height.is_none(); + let height = settings.resolution_height.unwrap_or(settings.resolution); + let picked = sheet.dropdown_pair_above( + tr("Output Size"), + [settings.resolution, height], + &sizes, + |size| size.pixels().to_string(), + &mut linked, + tr("Lock Output Size"), + ); + match picked { + Some((0, size)) => settings.resolution = size, + Some((_, size)) => settings.resolution_height = Some(size), + None => {} + } + if linked { + settings.resolution_height = None; + } else if settings.resolution_height.is_none() { + settings.resolution_height = Some(settings.resolution); + } +} - if let (true, Some(index)) = (remove, selected) { +/// The high poly meshes, one row each with × to remove it, and + beside them to add some; files still loading show greyed +fn high_poly_scene(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + #[cfg(not(target_arch = "wasm32"))] + let loading: Vec = + app.high_poly_job.iter().flat_map(|job| job.file_names()).map(|name| crate::i18n::trf("Loading {name}...", &[("name", &name)])).collect(); + #[cfg(target_arch = "wasm32")] + let loading: [String; 0] = []; + + let meshes = &app.session.doc.bake_meshes.high; + let rows: Vec> = meshes + .iter() + .map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }) + .chain(loading.iter().map(|name| FileRow { name, folder: None, loading: true })) + .collect(); + let answer = sheet.file_list( + tr("High Poly Scene"), + &rows, + HIGH_POLY_LIST_MIN_ROWS, + FileListAdd { glyph: icon::PLUS, label: tr("Add High-Poly Meshes"), enabled: true }, + tr("Remove"), + ); + if let Some(index) = answer.removed { app.run("bake.highPoly.remove", json!({ "index": index })); - selected = None; } - ui.data_mut(|data| { - if let Some(index) = selected { - data.insert_temp(selected_id, index); - } else { - data.remove_temp::(selected_id); - } - }); - if add { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), false); + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), false); } } -/// The cage file row; while the cage can't `apply` only removing a loaded one stays available, so a saved cage can still be dropped -fn cage_file(app: &mut TextureCraftApp, ui: &mut Ui, apply: bool) { - ui.add_enabled(apply, egui::Label::new(tr("Cage Scene"))); - let cage = app.session.bake_meshes.cage.as_ref().map(|mesh| mesh.name.clone()); - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - let label_width = (ui.available_width() - 2.0 * (button_size + ui.spacing().item_spacing.x)).max(0.0); - ui.add_enabled_ui(apply, |ui| { - ui.add_sized([label_width, ui.spacing().interact_size.y], egui::Label::new(cage.as_deref().unwrap_or("")).truncate()); - if icon_button(ui, icon::FOLDER_OPEN, tr("Load Cage"), false, button_size).clicked() { - crate::web_files::import_bake_mesh(app, &ui.ctx().clone(), true); - } - }); - if cage.is_some() && icon_button(ui, icon::TRASH, tr("Remove Cage"), false, button_size).clicked() { - app.run("bake.cage.clear", json!({})); - } - }); +/// The cage file's row, with the folder button that loads one while the cage `applies` +fn cage_file(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, applies: bool) { + let cage = app.session.doc.bake_meshes.cage.as_ref(); + let rows: Vec> = cage.iter().map(|mesh| FileRow { name: &mesh.name, folder: mesh.folder.as_deref(), loading: false }).collect(); + let answer = sheet.file_list( + tr("Cage Scene"), + &rows, + CAGE_LIST_MIN_ROWS, + FileListAdd { glyph: icon::FOLDER_OPEN, label: tr("Load Cage"), enabled: applies }, + tr("Remove Cage"), + ); + if answer.removed.is_some() { + app.run("bake.cage.clear", json!({})); + } + if answer.add { + crate::web_files::import_bake_mesh(app, &sheet.ui.ctx().clone(), true); + } } -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"), +/// "Paint Cage" or "Paint Skew Correction", held down as "Stop Painting" while that brush is on, with the brush sliders under it +fn paint_button(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, target: BakePaintTarget) { + let label = match target { + BakePaintTarget::Cage => tr("Paint Cage"), + BakePaintTarget::Skew => tr("Paint Skew Correction"), }; 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() { + let (glyph, text) = if active { (icon::PROHIBIT, tr("Stop Painting")) } else { (icon::PENCIL_SIMPLE, label) }; + if sheet.wide_button(glyph, text, active).clicked() { brush.on = !active; if brush.target != target { brush.value = match target { - BakePaintTarget::Cage => 0.5, - BakePaintTarget::Skew => 1.0, + BakePaintTarget::Cage => CAGE_BRUSH_VALUE, + BakePaintTarget::Skew => SKEW_BRUSH_VALUE, }; } brush.target = target; } 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); + sheet.indented(|sheet| { + number(sheet, tr("Radius"), &mut brush.radius, BRUSH_RADIUS, 3); + number(sheet, tr("Value"), &mut brush.value, 0.0..=1.0, 2); + number(sheet, 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; } } 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/controls.rs b/crates/ui-egui/src/bake_mode/controls.rs index f260bf7c..a8c78922 100644 --- a/crates/ui-egui/src/bake_mode/controls.rs +++ b/crates/ui-egui/src/bake_mode/controls.rs @@ -1,88 +1,55 @@ -use crate::i18n::tr; -use crate::theme::{Tokens, caption}; -use egui::collapsing_header::CollapsingState; -use egui::{RichText, Ui}; +//! The bake panels' settings on the property sheet: labels above full-width controls, as the reference's bake panels lay them out -/// A section's title bar with its chevron; clicking it opens or closes the section -fn section_header(ui: &mut Ui, title: &str, collapsing_state: &mut CollapsingState) { - let tokens = Tokens::get(ui.ctx()); - let 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); - ui.add(egui::Label::new(caption(title).color(tokens.text_strong)).selectable(false)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.allocate_exact_size(egui::vec2(ui.spacing().indent, ui.spacing().icon_width), egui::Sense::hover()).0 - }) - .inner - }) - .inner - }); +use crate::property_sheet::PropertySheet; - let response = ui.interact(header.response.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(header.inner, egui::Label::new(chevron).selectable(false)); -} - -/// A collapsible section with `contents` and Restore Defaults; returns whether that was clicked -pub(super) fn section(ui: &mut Ui, title: &str, contents: impl FnOnce(&mut Ui)) -> bool { - let mut collapsing_state = CollapsingState::load_with_default_open(ui.ctx(), ui.make_persistent_id("section"), true); - section_header(ui, title, &mut collapsing_state); - - 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); +/// A folding section with `contents` under its caption; its reset glyph resets at once, or opens `reset_menu` when not empty. Returns the reset choice: `Some(0)` for a plain reset, else the chosen item of `reset_menu` (from 0) +pub(super) fn section(sheet: &mut PropertySheet<'_>, title: &str, reset_menu: &[&str], contents: impl FnOnce(&mut PropertySheet<'_>)) -> Option { + let section = sheet.fold_section(title, true); + let mut chosen = None; + if reset_menu.is_empty() { + chosen = section.reset.clicked().then_some(0); + } else { + // Hanging left from the glyph at the panel's right edge, so it stays inside the panel + egui::Popup::menu(§ion.reset).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + for (index, item) in reset_menu.iter().enumerate() { + if ui.button(*item).clicked() { + chosen = Some(index); + } } - }) - .response - .labelled_by(caption.id); + }); + } + if section.open { + contents(sheet); + } + chosen } -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()) { +/// A dropdown of `options`, each with its shown name +pub(super) fn choice(sheet: &mut PropertySheet<'_>, label: &str, value: &mut T, options: &[(T, &str)]) { + let values: Vec = options.iter().map(|(option, _)| *option).collect(); + let name = |option: T| options.iter().find(|(candidate, _)| *candidate == option).map_or("", |(_, name)| *name).to_owned(); + if let Some(picked) = sheet.dropdown_above(label, *value, &values, name) { + *value = picked; + } +} + +/// A slider whose dragged values keep `decimals` places +pub(super) fn number(sheet: &mut PropertySheet<'_>, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) { + if sheet.slider_above(label, value, range.clone(), decimals).is_some() { 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) { +/// A slider of whole numbers +pub(super) fn integer(sheet: &mut PropertySheet<'_>, 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() { + if sheet.slider_above(label, &mut number_value, *range.start() as f32..=*range.end() as f32, 0).is_some() { *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)); +/// A one-line text field +pub(super) fn text_input(sheet: &mut PropertySheet<'_>, label: &str, value: &mut String) { + sheet.text_field_above(label, value); } diff --git a/crates/ui-egui/src/bake_mode/glyph_look.rs b/crates/ui-egui/src/bake_mode/glyph_look.rs new file mode 100644 index 00000000..db9f8bc6 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/glyph_look.rs @@ -0,0 +1,9 @@ +/// How a baker row's glyph button shows its state +#[derive(Clone, Copy, PartialEq)] +pub(super) enum GlyphLook { + Plain, + /// Bright: what it stands for is on (the set shares these settings) + Lit, + /// Held down in a box: the view it toggles is showing + Pressed, +} diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs new file mode 100644 index 00000000..06394cb6 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -0,0 +1,333 @@ +//! The map preview: while Mesh Map Settings shows a map's settings, the 3D view shows that map on the model, re-baked small on a worker as the settings change + +use crate::bake_scene::SharedHandle; +use std::collections::BTreeMap; +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::mpsc::TryRecvError; + +use texturecraft_engine::StreamedMap; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakePaintTarget, BakeResolution, BakedMap}; + +use super::live_preview_target::LivePreviewTarget; +use super::preview_input::PreviewInput; +use super::running_preview::RunningPreview; +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::state::Mode; + +/// Sizes a dragged slider's previews step through, smallest first +const DRAG_SIZES: [BakeResolution; 5] = [BakeResolution::R64, BakeResolution::R128, BakeResolution::R256, BakeResolution::R512, BakeResolution::R1024]; + +/// A drag preview this quick bakes one size up next time +const DRAG_STEP_UP_SECONDS: f64 = 0.07; + +/// A drag preview this slow bakes one size down next time +const DRAG_STEP_DOWN_SECONDS: f64 = 0.14; + +/// How often the view looks for a finished preview: about one frame at 60 Hz, so it shows at once +const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16); + +/// The map preview's state: what it shows, what its picture was made from (and the session revision and size it was last checked at), the bake running for it, the drag change waiting for it, whether a drag still needs the full-size bake, whether its last bake could not start, and each map's drag size on this machine +#[derive(Default)] +pub(crate) struct LivePreview { + shown: Option, + made_from: Option, + checked_at: Option<(u64, BakeResolution)>, + cannot_bake: bool, + running: Option, + drag_waiting: bool, + refine_on_release: bool, + drag_sizes: BTreeMap, +} + +impl LivePreview { + /// The map the preview shows now, if any + pub(crate) fn shown(&self) -> Option { + self.shown.map(|target| target.map) + } + + /// Stop the preview and give the 3D view back; a real bake calls this before it takes the view + pub(crate) fn release(&mut self, session: &mut texturecraft_engine::Session) { + self.cancel(); + self.refine_on_release = false; + self.made_from = None; + self.checked_at = None; + self.cannot_bake = false; + if self.shown.take().is_some() { + session.bake_preview_end(); + } + } + + fn cancel(&mut self) { + self.drag_waiting = false; + self.running = None; + } + + /// The size `map` bakes at while a slider drags: it starts small, follows how fast this machine bakes it, and never passes `chosen` + fn drag_size(&self, map: BakedMap, chosen: BakeResolution) -> BakeResolution { + let learned = self.drag_sizes.get(&map).copied().unwrap_or_else(|| first_drag_size(map)); + if learned.pixels() > chosen.pixels() { chosen } else { learned } + } + + /// A drag preview of `map` at `size` took `seconds`: step its drag size up or down one size, never past `chosen` + fn learn_drag_size(&mut self, map: BakedMap, size: BakeResolution, seconds: f64, chosen: BakeResolution) { + let Some(index) = DRAG_SIZES.iter().position(|step| *step == size) else { return }; + + let next = if seconds < DRAG_STEP_UP_SECONDS { + DRAG_SIZES.get(index + 1).copied().filter(|bigger| bigger.pixels() <= chosen.pixels()).unwrap_or(size) + } else if seconds > DRAG_STEP_DOWN_SECONDS { + index.checked_sub(1).and_then(|smaller| DRAG_SIZES.get(smaller).copied()).unwrap_or(size) + } else { + size + }; + self.drag_sizes.insert(map, next); + } +} + +/// The texture set and the map whose settings a Mesh Map Settings panel in front shows, in Bake mode +pub(crate) fn map_settings_shown(app: &TextureCraftApp) -> Option { + let set = app.session.ts(); + let settings = &app.session.doc.project.texture_sets.get(set)?.bake; + let shows = app.ui.mode == Mode::Baking && app.ui.dock.is_visible(Panel::MeshMapSettings); + shows.then(|| LivePreviewTarget { set, map: super::selected_map(app.ui.selected_baked_map, settings) }) +} + +/// What the preview should show: the map whose settings show, while the preview is on and no real bake runs +fn wanted(app: &TextureCraftApp) -> Option { + map_settings_shown(app).filter(|_| app.ui.bake_visualization.map_preview && app.bake.is_none()) +} + +/// A slider dragged in Mesh Map Settings changed a setting: a running drag bake finishes and shows before the newest value bakes, so pictures keep coming while the slider moves +pub(crate) fn slider_dragged(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(target) = app.live_preview.shown else { return }; + + app.live_preview.refine_on_release = true; + + // Web builds bake on the UI thread, so they wait for the release; a set that can't bake waits too + if cfg!(target_arch = "wasm32") || app.live_preview.cannot_bake { + return; + } + + if app.live_preview.running.as_ref().is_some_and(|running| running.dragging) { + app.live_preview.drag_waiting = true; + } else { + let size = app.live_preview.drag_size(target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, target, size, true); + } +} + +/// Once a frame: follow what the preview should show, bake again when its picture is out of date, and take a finished bake +pub(crate) fn poll(app: &mut TextureCraftApp, ctx: &egui::Context) { + // A new session (a project opened, the mesh replaced) has no preview layer: start over + if app.live_preview.shown.is_some() && !app.session.bake_preview_active() { + app.live_preview.release(&mut app.session); + } + + let wanted = wanted(app); + if wanted != app.live_preview.shown { + app.live_preview.release(&mut app.session); + if let Some(target) = wanted { + show(app, ctx, target); + } + } + + // Refine after release and refresh after external edits + if let Some(target) = app.live_preview.shown { + let released = app.live_preview.refine_on_release && ctx.dragged_id().is_none(); + let chosen = app.ui.bake_visualization.map_preview_size; + + // Compare input snapshots only after an edit or a size change + let check = (app.session.revision, chosen); + let unchecked = app.live_preview.checked_at != Some(check); + let out_of_date = unchecked && !app.live_preview.refine_on_release && app.live_preview.made_from != input(app, target, chosen); + if unchecked && !app.live_preview.refine_on_release { + app.live_preview.checked_at = Some(check); + } + if released || out_of_date { + app.live_preview.refine_on_release = false; + start(app, ctx, target, chosen, false); + } + } + + take_finished(app, ctx); +} + +/// Show a finished preview bake, learn the drag size from it, and start the drag change that waited for it; a failed one goes to the Log +fn take_finished(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(running) = &app.live_preview.running else { return }; + + ctx.request_repaint_after(POLL_INTERVAL); + let finished = match running.receiver.try_recv() { + Err(TryRecvError::Empty) => return, + Ok(finished) => finished, + Err(TryRecvError::Disconnected) => Err(texturecraft_engine::EngineError::Other(tr("The map preview worker stopped").into())), + }; + let Some(running) = app.live_preview.running.take() else { return }; + + // A failure keeps the old picture and says why + let mut output = match finished { + Ok(output) => output, + Err(error) => { + let map = tr(baked_map_label(running.target.map)); + app.session.log.warn("Baker", trf("The {map} preview failed: {error}", &[("map", &map), ("error", &error.to_string())])); + app.live_preview.drag_waiting = false; + return; + } + }; + + if running.dragging { + let seconds = ctx.input(|input| input.time) - running.started; + app.live_preview.learn_drag_size(running.target.map, running.size, seconds, app.ui.bake_visualization.map_preview_size); + } + if let Some(data) = output.maps.remove(&running.target.map) { + let streamed = StreamedMap { map: running.target.map, index: 0, total: 1, resolution: output.resolution, height: output.height, data: Arc::new(data) }; + app.session.bake_preview_map(running.target.set, streamed); + } + + // The newest drag change waited for this picture + if std::mem::take(&mut app.live_preview.drag_waiting) && app.live_preview.refine_on_release { + let size = app.live_preview.drag_size(running.target.map, app.ui.bake_visualization.map_preview_size); + start(app, ctx, running.target, size, true); + } +} + +/// Start showing `target`: the map's last real bake at once when there is one (it may predate the settings), then a preview bake at the chosen size +fn show(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget) { + app.session.bake_preview_begin(vec![(target.set, vec![target.map])]); + app.live_preview.shown = Some(target); + + let baked = app.session.baked(target.set).and_then(|baked| baked.maps.get(&target.map).map(|data| (baked.resolution, data.clone()))); + if let Some((resolution, data)) = baked { + let height = (data.len() / target.map.components()).checked_div(resolution as usize).unwrap_or(0) as u32; + app.session.bake_preview_map(target.set, StreamedMap { map: target.map, index: 0, total: 1, resolution, height, data }); + } + start(app, ctx, target, app.ui.bake_visualization.map_preview_size, false); +} + +/// What a preview of `target` at `size` would be made from now +fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) -> Option { + let set = app.session.doc.project.texture_sets.get(target.set)?; + let meshes = &app.session.doc.bake_meshes; + let painted = [BakePaintTarget::Skew, BakePaintTarget::Cage].map(|kind| SharedHandle::of(app.session.doc.bake_paint.get(&(target.set, kind)))); + let previous_pixels = app.session.doc.baked.get(&target.set).filter(|_| !set.bake_excluded_tiles.is_empty()).and_then(|baked| baked.maps.get(&target.map)); + + Some(PreviewInput { + settings: set.bake.clone(), + mesh_id: app.session.mesh_id, + uv_tiles: set.uv_tiles.clone(), + excluded_tiles: set.bake_excluded_tiles.clone(), + tile_resolutions: set.tile_resolutions.clone(), + high: SharedHandle::of(meshes.merged_high().map(|source| &source.mesh)), + cage: SharedHandle::of(meshes.cage.as_ref().map(|source| &source.mesh)), + previous_pixels: SharedHandle::of(previous_pixels), + painted, + size, + }) +} + +/// Bake `target`'s map alone at `size` on the preview pool (`dragging`: for a slider still moving), cancelling the preview bake still running +fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarget, size: BakeResolution, dragging: bool) { + app.live_preview.cancel(); + app.live_preview.made_from = input(app, target, size); + let mut task = match app.session.bake_map_preview_task(target.set, target.map) { + Ok(task) => task, + Err(error) => { + // Log only the first failure until a bake can start + if !app.live_preview.cannot_bake { + let map = tr(baked_map_label(target.map)); + app.session.log.warn("Baker", trf("The {map} preview can't bake: {error}", &[("map", &map), ("error", &error.to_string())])); + } + app.live_preview.cannot_bake = true; + return; + } + }; + app.live_preview.cannot_bake = false; + + let own = task.settings.common.resolution; + let size = if own.pixels() < size.pixels() { own } else { size }; + task.settings.common.resolution = size; + task.settings.common.resolution_height = None; + + let progress = Arc::new(Progress::new()); + let worker_progress = progress.clone(); + + let pending = Arc::new(Mutex::new(Some(task))); + let worker_task = pending.clone(); + let run = move || { + let task = worker_task.lock().unwrap_or_else(|error| error.into_inner()).take(); + let task = task.ok_or_else(|| texturecraft_engine::EngineError::Other("bake cancelled".into()))?; + task.run(&worker_progress) + }; + + // The preview pool keeps bake setup off the UI thread + let receiver = match preview_pool() { + Some(pool) => { + let (sender, receiver) = std::sync::mpsc::channel(); + pool.spawn(move || { + let _ = sender.send(run()); + }); + receiver + } + None => crate::spawn_worker("texturecraft-map-preview", run), + }; + let started = ctx.input(|input| input.time); + app.live_preview.running = Some(RunningPreview { target, size, started, dragging, progress, receiver, pending }); +} + +/// A dragged slider's first preview size before this machine's speed is known: 64 for the ray-traced bakers (well over 100 ms at 128 on a 4-core machine), else 128 +fn first_drag_size(map: BakedMap) -> BakeResolution { + match map { + BakedMap::AmbientOcclusion | BakedMap::Thickness | BakedMap::BentNormal | BakedMap::Curvature => BakeResolution::R64, + _ => BakeResolution::R128, + } +} + +/// The preview bakes' own thread pool, a thread short of the cores, so the UI's parallel work never waits behind a preview; None where no pool can start +#[cfg(not(target_arch = "wasm32"))] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |cores| cores.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|index| format!("texturecraft-map-preview-{index}")).build(); + if let Err(error) = &pool { + log::warn!("map previews share the global thread pool: {error}"); + } + pool.ok() + }) + .as_ref() +} + +/// Web builds have no threads: the preview bakes on the UI thread +#[cfg(target_arch = "wasm32")] +fn preview_pool() -> Option<&'static rayon::ThreadPool> { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_drag_size_steps_up_while_fast_down_while_slow_and_never_past_the_chosen_size() { + let mut preview = LivePreview::default(); + let map = BakedMap::AmbientOcclusion; + let largest = BakeResolution::R1024; + let start = preview.drag_size(map, largest); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + let bigger = preview.drag_size(map, largest); + assert!(bigger.pixels() > start.pixels(), "a quick bake steps up"); + + preview.learn_drag_size(map, bigger, DRAG_STEP_DOWN_SECONDS * 2.0, largest); + assert_eq!(preview.drag_size(map, largest), start, "a slow bake steps back down"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, start); + assert_eq!(preview.drag_size(map, largest), start, "never steps past the chosen size"); + + preview.learn_drag_size(map, start, DRAG_STEP_UP_SECONDS / 2.0, largest); + assert_eq!(preview.drag_size(map, start), start, "a smaller chosen size caps what was learned"); + } +} diff --git a/crates/ui-egui/src/bake_mode/live_preview_target.rs b/crates/ui-egui/src/bake_mode/live_preview_target.rs new file mode 100644 index 00000000..17e88085 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/live_preview_target.rs @@ -0,0 +1,8 @@ +use texturecraft_engine::core::BakedMap; + +/// One map of one texture set, as the map preview shows it +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct LivePreviewTarget { + pub(crate) set: usize, + pub(crate) map: BakedMap, +} diff --git a/crates/ui-egui/src/bake_mode/map_preview_fold.rs b/crates/ui-egui/src/bake_mode/map_preview_fold.rs new file mode 100644 index 00000000..04fa8732 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_preview_fold.rs @@ -0,0 +1,69 @@ +use texturecraft_engine::core::BakedMap; + +/// The Map Preview section's fold: it opens while a preview shows and folds when the preview goes away; folded by hand on a map, it stays folded until another map is picked +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct MapPreviewFold { + /// The map the preview showed last frame + pub(super) shown: Option, + /// The map the user folded the section on while its preview showed + pub(super) folded_for: Option, +} + +impl MapPreviewFold { + /// Whether the section should open (Some(true)) or fold (Some(false)) this frame, or stay as it is; `selected` is the map whose settings show, `switched_off` whether the preview is turned off + pub(super) fn follow(&mut self, shown: Option, selected: Option, switched_off: bool) -> Option { + // Only another map ends it; no map at all (Common Settings in front) keeps it + if selected.is_some() && selected != self.folded_for { + self.folded_for = None; + } + if shown == self.shown { + return None; + } + + self.shown = shown; + match shown { + Some(map) => (self.folded_for != Some(map)).then_some(true), + // Turning the preview off from inside the section leaves it open until the user moves on + None => (!(switched_off && selected.is_some())).then_some(false), + } + } + + /// The user folded or opened the section by hand + pub(super) fn toggled(&mut self, open: bool) { + self.folded_for = if open { None } else { self.shown }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_section_opens_with_a_preview_and_folds_when_it_goes() { + let mut fold = MapPreviewFold::default(); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), Some(true)); + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "no change, no move"); + assert_eq!(fold.follow(None, None, false), Some(false)); + } + + #[test] + fn folded_by_hand_it_stays_folded_until_another_map_is_picked() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + fold.toggled(false); + fold.follow(None, None, false); + + assert_eq!(fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false), None, "same map: stays folded"); + assert_eq!(fold.follow(Some(BakedMap::Curvature), Some(BakedMap::Curvature), false), Some(true)); + } + + #[test] + fn switching_the_preview_off_leaves_the_section_open() { + let mut fold = MapPreviewFold::default(); + fold.follow(Some(BakedMap::AmbientOcclusion), Some(BakedMap::AmbientOcclusion), false); + + assert_eq!(fold.follow(None, Some(BakedMap::AmbientOcclusion), true), None); + } +} diff --git a/crates/ui-egui/src/bake_mode/map_settings.rs b/crates/ui-egui/src/bake_mode/map_settings.rs index 5168d341..832503c1 100644 --- a/crates/ui-egui/src/bake_mode/map_settings.rs +++ b/crates/ui-egui/src/bake_mode/map_settings.rs @@ -1,6 +1,6 @@ -use super::controls::{choice, hint, integer, number}; +use super::controls::{choice, integer, number}; use crate::i18n::tr; -use egui::Ui; +use crate::property_sheet::PropertySheet; use serde::Serialize; use serde_json::{Value, json}; use texturecraft_engine::core::{ @@ -9,89 +9,111 @@ use texturecraft_engine::core::{ RayDistribution, RaySettings, SelfOcclusion, ThicknessNormalization, ThicknessSettings, }; -/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so -pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option { +/// Most secondary rays a slider offers, as the reference's does (the bake settings command accepts the same) +const MAX_SECONDARY_RAYS: u32 = 256; + +/// Smallest distance, radius or divisor a slider offers: the bake settings command's lower limit +const SHORTEST_DISTANCE: f32 = 0.00001; + +/// Whether `map` has parameters (and so a Restore Defaults) +pub(super) fn has_parameters(map: BakedMap) -> bool { + !matches!(map, BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity) +} + +/// Draw `map`'s parameters; `restore` sets them back to the defaults. Maps without parameters say so +pub(super) fn show(sheet: &mut PropertySheet<'_>, map: BakedMap, settings: &mut MeshMapSettings, restore: bool) -> Option { match map { BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => { - hint(ui, tr("No Parameters")); + sheet.dim_line(tr("No Parameters")); None } - BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id), - BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion), - BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature), - BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position), - BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness), - BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height), - BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal), + BakedMap::Id => parameters(sheet, "id", &mut settings.id.parameters, restore, id), + BakedMap::AmbientOcclusion => parameters(sheet, "ao", &mut settings.ao.parameters, restore, ambient_occlusion), + BakedMap::Curvature => parameters(sheet, "curvature", &mut settings.curvature.parameters, restore, curvature), + BakedMap::Position => parameters(sheet, "position", &mut settings.position.parameters, restore, position), + BakedMap::Thickness => parameters(sheet, "thickness", &mut settings.thickness.parameters, restore, thickness), + BakedMap::Height => parameters(sheet, "height", &mut settings.height.parameters, restore, height), + BakedMap::BentNormal => parameters(sheet, "bent_normal", &mut settings.bent_normal.parameters, restore, bent_normal), } } -/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters -fn parameters(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option { - controls(ui, parameters); - ui.add_space(6.0); - - let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner; - if restore.clicked() { +/// A map's controls; on `restore` only its parameters go back to the defaults +fn parameters( + sheet: &mut PropertySheet<'_>, + map_key: &str, + parameters: &mut T, + restore: bool, + controls: impl FnOnce(&mut PropertySheet<'_>, &mut T), +) -> Option { + controls(sheet, parameters); + if restore { *parameters = T::default(); return Some(json!({"maps": {map_key: {"parameters": parameters}}})); } None } -fn id(ui: &mut Ui, settings: &mut IdSettings) { +/// Settings that belong to the one above: indented under it, greyed while it rules them out +fn dependent(sheet: &mut PropertySheet<'_>, applies: bool, body: impl FnOnce(&mut PropertySheet<'_>)) { + sheet.greyed(applies, None, |sheet| sheet.indented(body)); +} + +fn id(sheet: &mut PropertySheet<'_>, settings: &mut IdSettings) { choice( - ui, + sheet, 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::MeshId, tr("Mesh ID / Polygroup")), (IdColorSource::Submesh, tr("Submesh")), ], ); - if matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh) { + + // Keep dependent controls visible when disabled + let generates_colors = matches!(settings.source, IdColorSource::FileId | IdColorSource::MeshId | IdColorSource::Submesh); + dependent(sheet, generates_colors, |sheet| { choice( - ui, + sheet, 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 { +fn rays(sheet: &mut PropertySheet<'_>, settings: &mut RaySettings) { + integer(sheet, tr("Secondary Rays"), &mut settings.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Min Occluder Distance"), &mut settings.min_distance, SHORTEST_DISTANCE..=1.0, 5); + number(sheet, tr("Max Occluder Distance"), &mut settings.max_distance, SHORTEST_DISTANCE..=if settings.relative_to_bounding_box { 1.0 } else { 10.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut settings.relative_to_bounding_box) && 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"))]); + number(sheet, tr("Spread Angle"), &mut settings.spread, 0.0..=180.0, 0); + choice(sheet, tr("Distribution"), &mut settings.distribution, &[(RayDistribution::Uniform, tr("Uniform")), (RayDistribution::Cosine, tr("Cosine"))]); } -fn backface(ui: &mut Ui, settings: &mut BackfaceMode) { +fn backface(sheet: &mut PropertySheet<'_>, settings: &mut BackfaceMode) { choice( - ui, + sheet, 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 occlusion(sheet: &mut PropertySheet<'_>, label: &str, settings: &mut SelfOcclusion) { + choice(sheet, 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); +fn ambient_occlusion(sheet: &mut PropertySheet<'_>, settings: &mut AmbientOcclusionSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Attenuation"), &mut settings.attenuation, &[ @@ -100,94 +122,104 @@ fn ambient_occlusion(ui: &mut Ui, settings: &mut AmbientOcclusionSettings) { (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); - } + sheet.check(tr("Ground Plane"), &mut settings.ground_plane.enabled); + dependent(sheet, settings.ground_plane.enabled, |sheet| number(sheet, tr("Ground Plane Offset"), &mut settings.ground_plane.offset, 0.0..=100.0, 2)); } -fn curvature(ui: &mut Ui, settings: &mut CurvatureSettings) { +fn curvature(sheet: &mut PropertySheet<'_>, settings: &mut CurvatureSettings) { choice( - ui, + sheet, tr("Method"), &mut settings.method, - &[(CurvatureMethod::NormalMap, tr("Generate from Normal Map")), (CurvatureMethod::Mesh, tr("Generate from Mesh"))], + &[(CurvatureMethod::Mesh, tr("Generate from Mesh")), (CurvatureMethod::NormalMap, tr("Generate from Normal Map"))], ); 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); - } + number(sheet, tr("Details"), &mut settings.normal_map.details, 0.0..=1.0, 2); + sheet.check(tr("Enable Seams"), &mut settings.normal_map.enable_seams); + let seams = settings.normal_map.enable_seams; + dependent(sheet, seams, |sheet| number(sheet, 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 { + integer(sheet, tr("Secondary Rays"), &mut mesh.rays, 1..=MAX_SECONDARY_RAYS); + number(sheet, tr("Sampling Radius"), &mut mesh.sampling_radius, SHORTEST_DISTANCE..=if mesh.relative_to_bounding_box { 10.0 } else { 1.0 }, 5); + if sheet.check(tr("Relative to Bounding Box"), &mut mesh.relative_to_bounding_box) && !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); - } + occlusion(sheet, tr("Self Intersection"), &mut mesh.self_intersection); + sheet.check(tr("Auto Tonemapping (per UV Tile)"), &mut mesh.auto_tonemapping); + dependent(sheet, !mesh.auto_tonemapping, |sheet| { + number(sheet, tr("Value Bounds Min"), &mut mesh.value_min, -10.0..=10.0, 2); + number(sheet, 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")]); +fn position(sheet: &mut PropertySheet<'_>, settings: &mut PositionSettings) { + // Axis selection applies only in One Axis mode + let mut one_axis = settings.axis != PositionAxis::All; + choice(sheet, tr("Mode"), &mut one_axis, &[(false, tr("All Axis")), (true, tr("One Axis"))]); + if one_axis && settings.axis == PositionAxis::All { + settings.axis = PositionAxis::X; + } else if !one_axis { + settings.axis = PositionAxis::All; + } + dependent(sheet, one_axis, |sheet| { + let mut axis = if one_axis { settings.axis } else { PositionAxis::X }; + choice(sheet, tr("Axis"), &mut axis, &[(PositionAxis::X, "X"), (PositionAxis::Y, "Y"), (PositionAxis::Z, "Z")]); + if one_axis { + settings.axis = axis; + } + }); choice( - ui, + sheet, tr("Normalization Type"), &mut settings.normalization, &[(PositionMode::BoundingBox, tr("BBox")), (PositionMode::BoundingSphere, tr("BSphere")), (PositionMode::None, tr("None"))], ); choice( - ui, + sheet, 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); +fn thickness(sheet: &mut PropertySheet<'_>, settings: &mut ThicknessSettings) { + rays(sheet, &mut settings.rays); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); choice( - ui, + sheet, tr("Normalization"), &mut settings.normalization, &[ (ThicknessNormalization::RelativeToRayDistances, tr("Relative to Ray Distances")), - (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max")), + (ThicknessNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (ThicknessNormalization::None, tr("None")), ], ); } -fn height(ui: &mut Ui, settings: &mut HeightSettings) { +fn height(sheet: &mut PropertySheet<'_>, settings: &mut HeightSettings) { choice( - ui, + sheet, 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::RelativeToLowMesh, tr("Relative to Low Mesh (per UV Tile)")), + (HeightNormalization::RelativeToMinMax, tr("Relative to Min/Max (per UV Tile)")), (HeightNormalization::Manual, tr("Manual")), ], ); - if settings.normalization == HeightNormalization::Manual { - number(ui, tr("Scaling Divisor"), &mut settings.scaling_divisor, 0.00001..=100.0, 5); - } + let manual = settings.normalization == HeightNormalization::Manual; + dependent(sheet, manual, |sheet| number(sheet, tr("Scaling Divisor"), &mut settings.scaling_divisor, SHORTEST_DISTANCE..=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); +fn bent_normal(sheet: &mut PropertySheet<'_>, settings: &mut BentNormalSettings) { + rays(sheet, &mut settings.rays); + backface(sheet, &mut settings.ignore_backface); + occlusion(sheet, tr("Self Occlusion"), &mut settings.self_occlusion); } diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs new file mode 100644 index 00000000..fe7e96b3 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -0,0 +1,90 @@ +use std::collections::BTreeMap; +use std::sync::{Arc, Weak}; + +use egui::{ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::core::{BakedMap, BlockScales}; + +/// Side of a thumbnail's texture, in pixels (twice the row's square, for high-density screens) +const THUMBNAIL_PIXELS: u32 = 44; + +/// A thumbnail's texture, with the baked data, the working size and the UV tiles' scales it was drawn from +type Thumbnail = (Weak>, (u32, u32), BlockScales, TextureHandle); + +/// The Mesh Map Bakers rows' thumbnails of the baked maps, redrawn when a map is baked again +#[derive(Default)] +pub struct MapThumbnails { + mesh_id: Option, + textures: BTreeMap<(usize, BakedMap), Thumbnail>, +} + +impl MapThumbnails { + pub(crate) fn retain_mesh(&mut self, mesh_id: u64) { + if self.mesh_id != Some(mesh_id) { + self.textures.clear(); + self.mesh_id = Some(mesh_id); + } + } + + /// The thumbnail of `map` as texture set `texture_set` has it baked (a running bake's finished maps included), `None` before it is baked + pub fn texture(&mut self, context: &egui::Context, session: &Session, texture_set: usize, map: BakedMap) -> Option { + self.retain_mesh(session.mesh_id); + let key = (texture_set, map); + let baked = session.bake_preview_baked(texture_set).filter(|preview| preview.maps.contains_key(&map)).or_else(|| session.doc.baked.get(&texture_set)); + let (Some(data), Some(cache)) = (baked.and_then(|baked| baked.maps.get(&map)), session.caches.get(texture_set)) else { + self.textures.remove(&key); + return None; + }; + + if let Some((drawn_from, working_size, block_scales, texture)) = self.textures.get(&key) + && drawn_from.ptr_eq(&Arc::downgrade(data)) + && *working_size == cache.size + && *block_scales == cache.composite.block_scales + { + return Some(texture.clone()); + } + + let rgba = texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, THUMBNAIL_PIXELS, cache.size, &cache.composite.block_scales); + let side = THUMBNAIL_PIXELS as usize; + let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); + let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); + self.textures.insert(key, (Arc::downgrade(data), cache.size, cache.composite.block_scales.clone(), texture.clone())); + Some(texture) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_thumbnail_is_kept_until_its_map_is_baked_again() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let context = egui::Context::default(); + let mut thumbnails = MapThumbnails::default(); + let map = *session.doc.baked[&0].maps.keys().next().expect("the sample has a baked map"); + + let first = thumbnails.texture(&context, &session, 0, map).expect("a baked map has a thumbnail"); + assert_eq!(first.size(), [THUMBNAIL_PIXELS as usize; 2]); + assert_eq!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "the same bake reuses its texture"); + + let baked = session.doc.baked.get_mut(&0).unwrap(); + let rebaked = baked.maps[&map].as_ref().clone(); + baked.maps.insert(map, Arc::new(rebaked)); + + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), first.id(), "a new bake is drawn again"); + + let mut tiled = + texturecraft_engine::Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap(); + let tiled_set = &mut tiled.doc.project.texture_sets[0]; + let tile = *tiled_set.uv_tiles.first().expect("the UDIM plane has UV tiles"); + tiled_set.tile_resolutions.insert(tile, 128); + let second = thumbnails.texture(&context, &session, 0, map).unwrap(); + session.caches[0].composite.block_scales = tiled_set.block_scales(); + assert_ne!(thumbnails.texture(&context, &session, 0, map).unwrap().id(), second.id(), "a UV tile resolution edit draws it again"); + + session.doc.baked.get_mut(&0).unwrap().maps.remove(&map); + + assert!(thumbnails.texture(&context, &session, 0, map).is_none(), "a map not baked has none"); + } +} diff --git a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs index 059af550..7ec44f70 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,45 +1,125 @@ -use egui::{Align, Layout, RichText, Sense, Stroke, Ui, UiBuilder, vec2}; +use egui::{Align, CornerRadius, FontId, Layout, Pos2, Rect, Sense, Stroke, Ui, UiBuilder, pos2, vec2}; use egui_phosphor::regular as icon; use serde_json::json; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use super::glyph_look::GlyphLook; +use super::set_picker::SetPicker; +use super::set_picker_purpose::SetPickerPurpose; use crate::TextureCraftApp; use crate::docking::Panel; use crate::i18n::{baked_map_label, tr, trf}; -use crate::theme::Tokens; +use crate::property_sheet::{CHECK_SIZE, paint_check}; +use crate::theme::{Tokens, semibold}; -/// Height of one baker row, in points -const ROW_HEIGHT: f32 = 24.0; -/// Inset of a row's checkbox and name from its left edge, in points +/// The presets menu's least width, and its name field's, room for a typical preset name +const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; +const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; + +/// How far past its box a row's check takes clicks, so it is easy to hit +const CHECK_HIT_AIR: f32 = 3.0; + +/// Height of the header's buttons, the air inside them beside their words, and between the glyph and the words +const HEADER_BUTTON_HEIGHT: f32 = 24.0; +const HEADER_BUTTON_PADDING: f32 = 10.0; +const HEADER_GLYPH_GAP: f32 = 6.0; +/// Air above the header and between its buttons +const HEADER_AIR: f32 = 6.0; +const HEADER_GAP: f32 = 6.0; +/// Height of one baker row, and of the Check All row +const ROW_HEIGHT: f32 = 28.0; +/// Inset of a row's check from its left edge const ROW_INSET: f32 = 6.0; +/// Side of a row's map thumbnail, and the air on its sides +const THUMBNAIL_SIZE: f32 = 22.0; +const THUMBNAIL_AIR: f32 = 9.0; +/// Side of a row's icon buttons and of the list menu button +const ROW_BUTTON_SIZE: f32 = 20.0; +/// Size of a row's glyphs +const ROW_GLYPH_SIZE: f32 = 14.0; +/// Size of the map names +const NAME_SIZE: f32 = 12.0; +/// Corner radius of a row's face and of a held-down glyph's box +const ROW_RADIUS: u8 = 4; +/// Opacity of a hovered row's face, against the selected row's full one +const HOVER_FACE_OPACITY: f32 = 0.5; +/// Air above and below the hairline under Check All +const RULE_AIR: f32 = 4.0; -/// The Common Settings button, Check All, and one row per map (checkbox enables, click selects) +/// The Common Settings button (with the sync icon when there are several texture sets), Check All with the list menu, and one row per map (checkbox enables, click selects) pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { - if ui.button(format!("{} {}", icon::GEAR, tr("Common Settings"))).clicked() { - app.ui.dock.focus(Panel::CommonSettings); - } + let several_sets = app.session.doc.project.texture_sets.len() > 1; + ui.add_space(HEADER_AIR); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = HEADER_GAP; + if header_button(ui, icon::GEAR, tr("Common Settings")).clicked() { + app.ui.dock.focus(Panel::CommonSettings); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Common); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; + let sync = glyph_button(ui, slot, glyph, tr("Synchronize Common Settings"), look); + if sync.clicked() { + SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Common)); + } + } + presets_menu(app, ui, settings); + }); + }); - presets_menu(app, ui, settings); + SetPicker::show(app, &ui.ctx().clone()); - ui.add_space(4.0); - check_all(ui, settings); - ui.separator(); + ui.add_space(RULE_AIR); + check_all_row(app, ui, settings); + ui.add_space(RULE_AIR); + let rule = ui.available_rect_before_wrap(); + ui.painter().hline(rule.x_range(), rule.top(), Stroke::new(1.0, Tokens::get(ui.ctx()).separator)); + ui.add_space(RULE_AIR); let selected = super::selected_map(app.ui.selected_baked_map, settings); + let check_drag_id = ui.scope_id().with("check_drag"); + let drag_from_id = ui.scope_id().with("check_drag_from"); + let mut check_drag: Option = ui.data(|data| data.get_temp(check_drag_id)); + let drag_from: Option = ui.data(|data| data.get_temp(drag_from_id)); for map in BakedMap::ALL { - if ui.push_id(map, |ui| row(ui, map, settings, map == selected)).inner { + if ui.push_id(map, |ui| row(app, ui, map, settings, map == selected, &mut check_drag, drag_from)).inner { app.ui.selected_baked_map = Some(map); app.ui.dock.focus(Panel::MeshMapSettings); } } + + // Keep the drag state until the release click has been handled + let is_held = ui.input(|input| input.pointer.primary_down()); + let pointer = ui.input(|input| input.pointer.latest_pos()); + ui.data_mut(|data| { + if let (Some(value), true) = (check_drag, is_held) { + data.insert_temp(check_drag_id, value); + + // A pointer back from outside the window starts a new line, so rows it never crossed stay as they were + if let Some(pointer) = pointer { + data.insert_temp(drag_from_id, pointer); + } else { + data.remove_temp::(drag_from_id); + } + } else { + data.remove_temp::(check_drag_id); + data.remove_temp::(drag_from_id); + } + }); } /// The Presets menu: save the active set's settings under a name, load or delete a saved one, copy to all sets fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) { - ui.menu_button(format!("{} {}", icon::SLIDERS_HORIZONTAL, tr("Presets")), |ui| { - ui.set_min_width(220.0); + let (slot, _) = ui.allocate_exact_size(vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE), Sense::hover()); + let button = glyph_button(ui, slot, icon::SLIDERS_HORIZONTAL, tr("Presets"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + ui.set_min_width(PRESETS_MENU_MIN_WIDTH); ui.horizontal(|ui| { - let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(130.0); + let name_edit = egui::TextEdit::singleline(&mut app.ui.bake_preset_name).hint_text(tr("Preset name")).desired_width(PRESET_NAME_FIELD_WIDTH); let enter = ui.add(name_edit).lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); let can_save = !app.ui.bake_preset_name.trim().is_empty(); if (ui.add_enabled(can_save, egui::Button::new(tr("Save Preset"))).clicked() || (enter && can_save)) @@ -90,45 +170,263 @@ fn presets_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &BakeSettings) }); } -/// Enable every map, or disable them all when every map is already enabled -fn check_all(ui: &mut Ui, settings: &mut BakeSettings) { +/// Check All (mixed while only some maps are checked; a click checks them all, or unchecks them when all are) with the ≡ menu at the right +fn check_all_row(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let tokens = Tokens::get(ui.ctx()); let enabled_count = BakedMap::ALL.into_iter().filter(|map| settings.maps.is_enabled(*map)).count(); - let mut all_enabled = enabled_count == BakedMap::ALL.len(); - let some_enabled = enabled_count > 0 && !all_enabled; + let all_enabled = enabled_count == BakedMap::ALL.len(); + let state = match enabled_count { + 0 => Some(false), + _ if all_enabled => Some(true), + _ => None, + }; - if ui.add(egui::Checkbox::new(&mut all_enabled, tr("Check All")).indeterminate(some_enabled)).changed() { + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::hover()); + let label = tr("Check All"); + let galley = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let hit = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(check.right() + THUMBNAIL_AIR + galley.size().x, rect.bottom())); + let response = ui.interact(hit, ui.scope_id().with("check_all"), Sense::click()); + response.widget_info(|| match state { + Some(on) => egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, label), + None => egui::WidgetInfo::labeled(egui::Role::CheckBox, true, label), + }); + paint_check(ui.painter(), &tokens, check, state, response.hovered()); + ui.painter().galley(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - galley.size().y / 2.0), galley, tokens.text); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + if response.clicked() { for map in BakedMap::ALL { - settings.maps.set_enabled(map, all_enabled); + settings.maps.set_enabled(map, !all_enabled); } } + + let menu = Rect::from_center_size(pos2(rect.right() - ROW_BUTTON_SIZE / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + let mut menu_ui = ui.new_child(UiBuilder::new().max_rect(menu)); + list_menu(app, &mut menu_ui, settings); +} + +/// The ≡ menu beside Check All: check states, and copying them or every setting to other texture sets +fn list_menu(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) { + let button = glyph_button(ui, ui.max_rect(), icon::LIST, tr("Mesh Map Bakers Menu"), GlyphLook::Plain); + egui::Popup::menu(&button).align(egui::RectAlign::BOTTOM_END).align_alternatives(&[egui::RectAlign::BOTTOM_START]).show(|ui| { + if ui.button(tr("Check All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, true)); + } + if ui.button(tr("Uncheck All Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, false)); + } + if ui.button(tr("Invert Checked Mesh Maps")).clicked() { + BakedMap::ALL.into_iter().for_each(|map| settings.maps.set_enabled(map, !settings.maps.is_enabled(map))); + } + copy_items(app, ui, &button, "checked", None, [tr("Apply Checked to More Texture Sets..."), tr("Apply Checked to All Texture Sets")]); + ui.separator(); + copy_items(app, ui, &button, "settings", None, [tr("Sync All Settings to More Texture Sets..."), tr("Sync All Settings to All Texture Sets")]); + }); +} + +/// A copy's two menu items: "...more Texture Sets..." opens the set picker, "...all Texture Sets" copies to every set +fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, opener: &egui::Response, what: &'static str, map: Option, [more, all]: [&str; 2]) { + // With one texture set there is nothing to copy to + let several_sets = app.session.doc.project.texture_sets.len() > 1; + if ui.add_enabled(several_sets, egui::Button::new(more)).clicked() { + SetPicker::open(app, opener, SetPickerPurpose::Copy { what, map }); + ui.close(); + } + if ui.add_enabled(several_sets, egui::Button::new(all)).clicked() { + let from = app.session.ts(); + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": from, "ts": "all" })); + ui.close(); + } } -/// One baker row; returns whether the row (not its checkbox) was clicked -fn row(ui: &mut Ui, map: BakedMap, settings: &mut BakeSettings, is_selected: bool) -> bool { +/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses; `drag_from`: where that drag's pointer was last frame); returns whether the row itself was clicked +fn row( + app: &mut TextureCraftApp, + ui: &mut Ui, + map: BakedMap, + settings: &mut BakeSettings, + is_selected: bool, + check_drag: &mut Option, + drag_from: Option, +) -> bool { + let several_sets = app.session.doc.project.texture_sets.len() > 1; let tokens = Tokens::get(ui.ctx()); let name = tr(baked_map_label(map)); let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_HEIGHT), Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, is_selected, name)); - let painter = ui.painter(); + let hovered = ui.rect_contains_pointer(rect); if is_selected { - painter.rect_filled(rect, tokens.cr(), tokens.row_selected); - painter.rect_stroke(rect, tokens.cr(), Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, tokens.cr(), tokens.row_hover); + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover); + } else if hovered { + ui.painter().rect_filled(rect, CornerRadius::same(ROW_RADIUS), tokens.row_hover.gamma_multiply(HOVER_FACE_OPACITY)); } - painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); - // Added after the row's own response, so the checkbox takes the clicks over it - let content_rect = rect.shrink2(vec2(ROW_INSET, 0.0)); - let mut content = ui.new_child(UiBuilder::new().max_rect(content_rect).layout(Layout::left_to_right(Align::Center))); - let mut is_enabled = settings.maps.is_enabled(map); - let checkbox = content.checkbox(&mut is_enabled, ""); - let text = if is_selected { RichText::new(name).strong() } else { RichText::new(name) }; - let label = content.add(egui::Label::new(text).selectable(false).truncate()); - if checkbox.labelled_by(label.id).changed() { - settings.maps.set_enabled(map, is_enabled); + // Added after the row's own response, so the check and icons take the clicks over it + let check = Rect::from_center_size(pos2(rect.left() + ROW_INSET + CHECK_SIZE / 2.0, rect.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + let checkbox = ui.interact(check.expand(CHECK_HIT_AIR), ui.scope_id().with("include"), Sense::click()).on_hover_text(tr("Include in Bake")); + checkbox.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, settings.maps.is_enabled(map), name)); + let is_dragged_over = drag_check(ui, &checkbox, rect, settings.maps.is_enabled(map), check_drag, drag_from); + if let Some(value) = check_drag.filter(|_| is_dragged_over) { + settings.maps.set_enabled(map, value); + } else if checkbox.clicked() && check_drag.is_none() { + settings.maps.set_enabled(map, !settings.maps.is_enabled(map)); + } + paint_check(ui.painter(), &tokens, check, Some(settings.maps.is_enabled(map)), checkbox.hovered()); + + crate::property_sheet::paint_keyboard_focus(ui, &checkbox, &tokens); + let texture = app.bake_map_thumbnails.texture(ui.ctx(), &app.session, app.session.ts(), map); + let thumbnail_rect = Rect::from_min_size(pos2(check.right() + THUMBNAIL_AIR, rect.center().y - THUMBNAIL_SIZE / 2.0), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + thumbnail(ui, thumbnail_rect, texture.as_ref()); + + let mut icons_left = rect.right(); + let focus_in_row = || { + ui.memory(|memory| memory.focused()) + .and_then(|id| ui.ctx().read_response(id)) + .is_some_and(|widget| widget.layer_id == ui.layer_id() && rect.contains(widget.rect.center())) + }; + if is_selected || hovered || focus_in_row() { + let mut next_icon = || { + let slot = + Rect::from_center_size(pos2(icons_left - ROW_BUTTON_SIZE / 2.0 - ROW_INSET / 2.0, rect.center().y), vec2(ROW_BUTTON_SIZE, ROW_BUTTON_SIZE)); + icons_left = slot.left() - ROW_INSET / 2.0; + slot + }; + if several_sets { + let shares = settings.sync.shares(BakeSyncGroup::Map(map)); + let look = if shares { GlyphLook::Lit } else { GlyphLook::Plain }; + let glyph = if shares { icon::LINK } else { icon::LINK_BREAK }; + let sync = glyph_button(ui, next_icon(), glyph, &trf("Synchronize {map} Settings", &[("map", &name)]), look); + if sync.clicked() { + SetPicker::open(app, &sync, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + } + } + let baking = app.bake_progress().is_some(); + let bolt = next_icon(); + let bolt_label = trf("Bake {map} Only", &[("map", &name)]); + if ui.add_enabled_ui(!baking, |ui| glyph_button(ui, bolt, icon::LIGHTNING, &bolt_label, GlyphLook::Plain)).inner.clicked() { + let active = app.session.ts(); + app.start_bake_of(vec![active], Some(map)); + } + let shown = app.session.view == ViewMode::MeshMap(map); + let look = if shown { GlyphLook::Pressed } else { GlyphLook::Plain }; + if glyph_button(ui, next_icon(), icon::EYE, &trf("Show {map} in the Viewport", &[("map", &name)]), look).clicked() { + let mode = if shown { "material".to_owned() } else { format!("map:{}", map.id()) }; + app.run("viewport.view", json!({ "mode": mode })); + } + } + + let name_left = thumbnail_rect.right() + THUMBNAIL_AIR; + let font = if is_selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let color = if is_selected { tokens.text_strong } else { tokens.text }; + let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), font, color); + job.wrap = egui::text::TextWrapping::truncate_at_width((icons_left - name_left).max(0.0)); + let galley = ui.painter().layout_job(job); + + // Expose the full label when its text is elided + let response = if galley.elided { response.on_hover_text(name) } else { response }; + ui.painter().galley(pos2(name_left, rect.center().y - galley.size().y / 2.0), galley, color); + + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + let mut popup = egui::Popup::context_menu(&response); + let restore_focus = popup.is_open() && ui.input(|input| input.key_pressed(egui::Key::Escape)); + if response.has_focus() + && ui.input_mut(|input| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu)) + { + popup = popup.anchor(&response).open_memory(Some(egui::SetOpenCommand::Bool(true))); + } else if !response.secondary_clicked() && popup.is_open() && egui::Popup::position_of_id(ui.ctx(), popup.get_id()).is_none() { + popup = popup.anchor(&response); + } + + popup.show(|ui| { + let labels = |more: &str, all: &str| [trf(more, &[("map", &name)]), trf(all, &[("map", &name)])]; + let [check_more, check_all] = labels("Check {map} for More Texture Sets...", "Check {map} for All Texture Sets"); + copy_items(app, ui, &response, "check", Some(map), [&check_more, &check_all]); + ui.separator(); + let [apply_more, apply_all] = labels("Apply {map} Settings to More Texture Sets...", "Apply {map} Settings to All Texture Sets"); + copy_items(app, ui, &response, "settings", Some(map), [&apply_more, &apply_all]); + ui.separator(); + if ui.add_enabled(several_sets, egui::Button::new(tr("Sync Settings..."))).clicked() { + SetPicker::open(app, &response, SetPickerPurpose::Sync(BakeSyncGroup::Map(map))); + ui.close(); + } + }); + if restore_focus { + response.request_focus(); } response.clicked() } + +/// Start a checkbox drag at a primary press on `checkbox`; returns whether the drag's pointer crossed this row's checkbox column (the whole row height counts) since `drag_from` +fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option, drag_from: Option) -> bool { + let is_primary = ui.input(|input| input.pointer.primary_down()); + if check_drag.is_none() && is_primary && checkbox.is_pointer_button_down_on() { + *check_drag = Some(!is_enabled); + } + let Some(pointer) = ui.input(|input| input.pointer.latest_pos()).filter(|_| check_drag.is_some()) else { + return false; + }; + + let column = Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range()); + ui.rect_contains_pointer(column) || crosses(column, drag_from.unwrap_or(pointer), pointer) +} + +/// Whether the straight line from `from` to `to` passes through `rect`, so a row skipped between two frames still counts +fn crosses(rect: Rect, from: Pos2, to: Pos2) -> bool { + if !rect.intersects(Rect::from_two_pos(from, to)) { + return false; + } + + // Test the last separating axis, perpendicular to the drag + let normal = (to - from).rot90(); + (rect.center() - from).dot(normal).abs() <= (rect.size() * 0.5).dot(normal.abs()) +} + +/// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal +fn thumbnail(ui: &Ui, rect: Rect, texture: Option<&egui::TextureHandle>) { + let tokens = Tokens::get(ui.ctx()); + let stroke = Stroke::new(1.0, tokens.text_dim); + match texture { + Some(texture) => { + egui::Image::new(texture).paint_at(ui, rect); + } + None => { + ui.painter().line_segment([rect.left_bottom(), rect.right_top()], stroke); + ui.painter().rect_stroke(rect, 0.0, stroke, egui::StrokeKind::Inside); + } + } +} + +/// A glyph in `rect` that answers clicks as `label`, its tooltip +fn glyph_button(ui: &mut Ui, rect: Rect, glyph: &str, label: &str, look: GlyphLook) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(label), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), look != GlyphLook::Plain, label)); + let response = response.on_hover_text(label); + if look == GlyphLook::Pressed { + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), tokens.separator, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + } + let color = if look == GlyphLook::Plain && !response.hovered() { tokens.text_dim } else { tokens.text_strong }; + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, glyph, FontId::proportional(ROW_GLYPH_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response +} + +/// One of the header's bordered buttons, sized to its glyph and words +fn header_button(ui: &mut Ui, glyph: &str, text: &str) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let icon = ui.painter().layout_no_wrap(glyph.to_owned(), FontId::proportional(ROW_GLYPH_SIZE), tokens.text); + let words = ui.painter().layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + let width = 2.0 * HEADER_BUTTON_PADDING + icon.size().x + HEADER_GLYPH_GAP + words.size().x; + let (rect, response) = ui.allocate_exact_size(vec2(width, HEADER_BUTTON_HEIGHT), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(ROW_RADIUS), fill, Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Inside); + let x = rect.left() + HEADER_BUTTON_PADDING; + ui.painter().galley(pos2(x, rect.center().y - icon.size().y / 2.0), icon.clone(), tokens.text); + ui.painter().galley(pos2(x + icon.size().x + HEADER_GLYPH_GAP, rect.center().y - words.size().y / 2.0), words, tokens.text); + crate::property_sheet::paint_keyboard_focus(ui, &response, &tokens); + response +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 2ae7f095..3acf83a0 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -6,6 +6,13 @@ mod bake_visualization_panel; mod bake_visualization_toggles; mod breadcrumb; mod common_settings; +mod glyph_look; +mod live_preview; +mod live_preview_target; +mod map_preview_fold; +mod preview_input; +mod running_preview; +pub(crate) use live_preview::LivePreview; mod section_opening; pub(crate) use bake_checks::bake_warnings; pub use bake_paint_brush::BakePaintBrush; @@ -13,19 +20,31 @@ pub(crate) use bake_visualization_panel::bake_visualization_panel; pub use bake_visualization_toggles::BakeVisualizationToggles; mod controls; mod map_settings; +mod map_thumbnails; mod mesh_map_bakers; +pub use map_thumbnails::MapThumbnails; +mod set_picker; +mod set_picker_purpose; +mod set_picker_row; use egui::{Ui, vec2}; use egui_phosphor::regular as icon; use serde_json::{Value, json}; +use texturecraft_engine::Session; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, CageType}; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; +use crate::property_sheet::PropertySheet; use crate::state::Mode; use crate::widgets::{icon_button, primary_button}; +/// Whether the high poly shows its matching error for `session`'s selected texture set: the automatic cage has no distances to fall short, as in the reference +pub(crate) fn matching_error_applies(session: &Session) -> bool { + session.doc.project.texture_sets.get(session.ts()).is_none_or(|set| set.bake.cage.kind != CageType::Automatic) +} + 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() { @@ -156,20 +175,41 @@ pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return }; let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake); - breadcrumb::show(app, ui, selected); - ui.separator(); - edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| { - ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner + let restore = ui.horizontal(|ui| { + ui.add_space(crate::property_sheet::SIDE_PADDING_POINTS); + ui.vertical(|ui| { + ui.set_width(ui.available_width() - crate::property_sheet::SIDE_PADDING_POINTS); + breadcrumb::show(app, ui, selected, map_settings::has_parameters(selected)) + }) + .inner }); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Map(selected))); + let changed = edit_settings(app, ui, "mesh_map_settings", texture_sets, |_, ui, settings| { + PropertySheet::show(ui, ("mesh_map_settings_sheet", selected), |sheet| map_settings::show(sheet, selected, &mut settings.maps, restore.inner)) + }); + + // Other changes reach the preview through its check of what its picture was made from + if changed && ui.ctx().dragged_id().is_some() { + let ctx = ui.ctx().clone(); + live_preview::slider_dragged(app, &ctx); + } +} + +/// Once a frame: the map preview follows the selected map and takes its finished bakes +pub(crate) fn poll_live_preview(app: &mut TextureCraftApp, ctx: &egui::Context) { + live_preview::poll(app, ctx); } /// The Common Settings panel: output, high poly, cage and skew settings pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) { - edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show); + let texture_sets = json!(app.session.doc.project.bake_synced_sets(app.session.ts(), BakeSyncGroup::Common)); + edit_settings(app, ui, "bake_common_settings", texture_sets, |app, ui, settings| { + PropertySheet::show(ui, "bake_common_sheet", |sheet| common_settings::show(app, sheet, settings)) + }); } /// The map whose settings show: the chosen one, else the first enabled map, else Normal -fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { +pub(super) fn selected_map(selection: Option, settings: &BakeSettings) -> BakedMap { selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal) } @@ -180,14 +220,14 @@ fn edit_settings( scroll_id: &str, texture_sets: Value, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option, -) { +) -> bool { 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 Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return false }; let mut settings = before.clone(); let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner; if settings == before && reset.is_none() { - return; + return false; } let mut patch = settings_patch(&before, &settings); @@ -195,6 +235,7 @@ fn edit_settings( fields.extend(reset); } app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch })); + true } /// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material diff --git a/crates/ui-egui/src/bake_mode/preview_input.rs b/crates/ui-egui/src/bake_mode/preview_input.rs new file mode 100644 index 00000000..5446129b --- /dev/null +++ b/crates/ui-egui/src/bake_mode/preview_input.rs @@ -0,0 +1,23 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use crate::bake_scene::SharedHandle; +use texturecraft_engine::bake::BakePaintMap; +use texturecraft_engine::core::{BakeResolution, BakeSettings}; +use texturecraft_engine::geom::Mesh; + +/// What a map preview picture is made from, everything its bake reads: when any of it changes, the picture is out of date +#[derive(Clone, Debug, PartialEq)] +pub(super) struct PreviewInput { + pub(super) settings: BakeSettings, + pub(super) mesh_id: u64, + /// The set's UV tiles, the ones left out of the bake, and their resolutions + pub(super) uv_tiles: Vec, + pub(super) excluded_tiles: BTreeSet, + pub(super) tile_resolutions: BTreeMap, + /// The high polys', the cage's and the set's painted maps' shared buffers: a file loaded again under the same name is another buffer + pub(super) high: SharedHandle, + pub(super) cage: SharedHandle, + pub(super) painted: [SharedHandle; 2], + pub(super) previous_pixels: SharedHandle>, + pub(super) size: BakeResolution, +} diff --git a/crates/ui-egui/src/bake_mode/running_preview.rs b/crates/ui-egui/src/bake_mode/running_preview.rs new file mode 100644 index 00000000..fa49b091 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/running_preview.rs @@ -0,0 +1,26 @@ +use std::sync::mpsc::Receiver; +use std::sync::{Arc, Mutex}; + +use texturecraft_engine::Result; +use texturecraft_engine::bake::{BakeOutput, BakeTask, Progress}; +use texturecraft_engine::core::BakeResolution; + +use super::live_preview_target::LivePreviewTarget; + +/// A map preview bake on its worker: its size, when it started (app time) and whether a dragged slider asked for it +pub(super) struct RunningPreview { + pub(super) target: LivePreviewTarget, + pub(super) size: BakeResolution, + pub(super) started: f64, + pub(super) dragging: bool, + pub(super) pending: Arc>>, + pub(super) progress: Arc, + pub(super) receiver: Receiver>, +} + +impl Drop for RunningPreview { + fn drop(&mut self) { + self.progress.cancel(); + self.pending.lock().unwrap_or_else(|error| error.into_inner()).take(); + } +} diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs new file mode 100644 index 00000000..ffcff713 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -0,0 +1,367 @@ +//! The dialog that picks texture sets: which ones share settings, or which ones a copy goes to + +use std::sync::Arc; +use texturecraft_engine::Session; + +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; +use serde_json::{Value, json}; +use texturecraft_engine::bake::settings_patch; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, Project}; + +use super::common_settings::antialiasing_label; +use super::set_picker_purpose::SetPickerPurpose; +use super::set_picker_row::SetPickerRow; +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::property_sheet::PropertySheet; +use crate::theme::{Tokens, semibold}; + +/// Width of the dialog, in points +const DIALOG_WIDTH: f32 = 420.0; + +/// The title bar: its height, the gear's and the title's left edges, and the glyph and title sizes +const TITLE_BAR_HEIGHT: f32 = 30.0; +const TITLE_GEAR_CENTER: f32 = 19.0; +const TITLE_TEXT_LEFT: f32 = 34.0; +const TITLE_GLYPH_SIZE: f32 = 14.0; +const TITLE_TEXT_SIZE: f32 = 12.0; + +/// Air under the title bar and above the buttons, and around the dialog's edge +const BODY_AIR: f32 = 12.0; +const BUTTONS_AIR: f32 = 18.0; +const EDGE_AIR: f32 = 12.0; + +/// OK and Cancel: their size, the air between them, their corners +const BUTTON_SIZE: egui::Vec2 = vec2(88.0, 24.0); +const BUTTON_GAP: f32 = 8.0; +const DIALOG_RADIUS: u8 = 4; + +/// An open picker: what it is for, and per texture set whether it is ticked +#[derive(Clone, Debug)] +pub(super) struct SetPicker { + purpose: SetPickerPurpose, + chosen: Vec, + mesh_id: u64, + active: usize, + opener: egui::Id, + cached: Option<(u64, &'static str, Arc<[SetPickerRow]>)>, +} + +impl SetPicker { + fn id() -> egui::Id { + egui::Id::unique("bake_set_picker") + } + + /// Open the picker for `purpose`; a sync picker starts with the sets sharing the group ticked, a copy picker with none + pub(super) fn open(app: &TextureCraftApp, opener: &egui::Response, purpose: SetPickerPurpose) { + let chosen = app + .session + .doc + .project + .texture_sets + .iter() + .map(|set| match purpose { + SetPickerPurpose::Sync(group) => set.bake.sync.shares(group), + SetPickerPurpose::Copy { .. } => false, + }) + .collect(); + opener.ctx.data_mut(|data| { + data.insert_temp(Self::id(), SetPicker { purpose, chosen, mesh_id: app.session.mesh_id, active: app.session.ts(), opener: opener.id, cached: None }) + }); + } + + /// The open picker, if any; OK runs its command + pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { + // The opener can receive focus again once the modal layer has left egui's focus order + if ctx.memory(|memory| memory.top_modal_layer().is_none()) + && let Some(opener) = ctx.data_mut(|data| data.remove_temp::>(Self::id()).flatten()) + { + ctx.memory_mut(|memory| memory.request_focus(opener)); + } + + return; + }; + + let active = app.session.ts(); + if picker.mesh_id != app.session.mesh_id || picker.active != active || picker.chosen.len() != app.session.set_count() { + ctx.data_mut(|data| data.remove::(Self::id())); + return; + } + + let opening = picker.cached.is_none() && ctx.memory(|memory| memory.top_modal_layer().is_none()); + let rows = picker.visible_rows(&app.session, active); + let tokens = Tokens::get(ctx); + let frame = egui::Frame::new() + .fill(tokens.panel) + .stroke(Stroke::new(1.0, tokens.button_border)) + .corner_radius(CornerRadius::same(DIALOG_RADIUS)) + .inner_margin(0); + let modal = egui::Modal::new(Self::id().with("modal")).frame(frame).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let closed = title_bar(ui, &tokens, &picker.title(), opening); + ui.add_space(BODY_AIR); + PropertySheet::show(ui, "bake_set_picker_sheet", |sheet| picker.list(sheet, &rows)); + ui.add_space(BUTTONS_AIR); + let (ok, cancel) = buttons(ui, &tokens); + ui.add_space(EDGE_AIR); + (ok, cancel || closed) + }); + + let (ok, cancel) = modal.inner; + if ok { + picker.apply(app, active); + } + if ok || cancel || modal.should_close() { + ctx.data_mut(|data| { + data.remove::(Self::id()); + data.insert_temp(Self::id(), Some(picker.opener)); + }); + ctx.request_repaint(); + } else { + ctx.data_mut(|data| data.insert_temp(Self::id(), picker)); + } + } + + /// The listed sets + fn rows(&self, project: &Project, active: usize) -> Vec { + let chosen: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); + project + .texture_sets + .iter() + .enumerate() + // A copy goes from the active set, so it isn't listed + .filter(|(index, _)| matches!(self.purpose, SetPickerPurpose::Sync(_)) || *index != active) + .map(|(index, set)| { + let note = match self.purpose { + // Include this row when predicting its sync source + SetPickerPurpose::Sync(group) if !set.bake.sync.shares(group) => { + let mut members = chosen.clone(); + if let Err(slot) = members.binary_search(&index) { + members.insert(slot, index); + } + project + .bake_sync_source(group, &members, active) + .filter(|source| *source != index) + .and_then(|source| project.texture_sets.get(source)) + .and_then(|source| differing_values(&set.bake, &source.bake, group)) + } + _ => None, + }; + SetPickerRow { index, name: set.name.clone(), note } + }) + .collect() + } + + fn visible_rows(&mut self, session: &Session, active: usize) -> Arc<[SetPickerRow]> { + let language = crate::i18n::current().code; + if let Some((revision, cached_language, rows)) = &self.cached + && *revision == session.revision + && *cached_language == language + { + return rows.clone(); + } + + let rows: Arc<[SetPickerRow]> = self.rows(&session.doc.project, active).into(); + self.cached = Some((session.revision, language, rows.clone())); + rows + } + + fn title(&self) -> String { + match self.purpose { + SetPickerPurpose::Sync(group) => trf("{settings} Sync", &[("settings", &group_label(group))]), + SetPickerPurpose::Copy { what: "checked", .. } => tr("Apply Checked to More Texture Sets").to_owned(), + SetPickerPurpose::Copy { what: "check", map: Some(map) } => trf("Check {map} for More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { map: Some(map), .. } => trf("Apply {map} Settings to More Texture Sets", &[("map", &tr(baked_map_label(map)))]), + SetPickerPurpose::Copy { .. } => tr("Sync All Settings to More Texture Sets").to_owned(), + } + } + + /// The master check and one check per listed set, indented under it + fn list(&mut self, sheet: &mut PropertySheet<'_>, rows: &[SetPickerRow]) { + let ticked = rows.iter().filter(|row| self.chosen.get(row.index).copied().unwrap_or(false)).count(); + let all_ticked = ticked == rows.len(); + let label = if all_ticked { tr("Deselect All") } else { tr("Select All") }; + let state = if ticked == 0 { Some(false) } else { all_ticked.then_some(true) }; + if sheet.check_mixed(label, state).clicked() { + self.cached = None; + for row in rows { + if let Some(chosen) = self.chosen.get_mut(row.index) { + *chosen = !all_ticked; + } + } + } + sheet.indented(|sheet| { + for row in rows { + let Some(chosen) = self.chosen.get_mut(row.index) else { continue }; + if sheet.check_noted(&row.name, Some(*chosen), row.note.as_deref()).clicked() { + self.cached = None; + *chosen = !*chosen; + } + } + }); + } + + fn apply(&self, app: &mut TextureCraftApp, active: usize) { + let ticked: Vec = self.chosen.iter().enumerate().filter(|(_, chosen)| **chosen).map(|(index, _)| index).collect(); + match self.purpose { + SetPickerPurpose::Sync(group) => { + app.run("bake.sync", json!({ "group": group_id(group), "ts": ticked })); + } + SetPickerPurpose::Copy { what, map } if !ticked.is_empty() => { + app.run("bake.copy", json!({ "what": what, "map": map.map(BakedMap::id), "from": active, "ts": ticked })); + } + SetPickerPurpose::Copy { .. } => {} + } + } +} + +/// The group as the `bake.sync` command names it +pub(super) fn group_id(group: BakeSyncGroup) -> &'static str { + match group { + BakeSyncGroup::Common => "common", + BakeSyncGroup::Map(map) => map.id(), + } +} + +fn group_label(group: BakeSyncGroup) -> String { + match group { + BakeSyncGroup::Common => tr("Common Settings").to_owned(), + BakeSyncGroup::Map(map) => trf("{map} Settings", &[("map", &tr(baked_map_label(map)))]), + } +} + +/// The title bar: gear, title, and × at the right; returns whether × was clicked +fn title_bar(ui: &mut Ui, tokens: &Tokens, title: &str, opening: bool) -> bool { + let (bar, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, TITLE_BAR_HEIGHT), Sense::hover()); + let top = CornerRadius { nw: DIALOG_RADIUS, ne: DIALOG_RADIUS, sw: 0, se: 0 }; + ui.painter().rect_filled(bar, top, tokens.chrome); + let center_y = bar.center().y; + ui.painter().text(pos2(bar.left() + TITLE_GEAR_CENTER, center_y), Align2::CENTER_CENTER, icon::GEAR, FontId::proportional(TITLE_GLYPH_SIZE), tokens.text); + let text = Rect::from_min_max(pos2(bar.left() + TITLE_TEXT_LEFT, bar.top()), pos2(bar.right() - TITLE_BAR_HEIGHT, bar.bottom())); + let label = egui::Label::new(RichText::new(title).font(semibold(TITLE_TEXT_SIZE)).color(tokens.text_strong)).truncate(); + ui.scope_builder(egui::UiBuilder::new().max_rect(text).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| ui.add(label)); + + let close = Rect::from_center_size(pos2(bar.right() - TITLE_BAR_HEIGHT / 2.0, center_y), vec2(TITLE_BAR_HEIGHT, TITLE_BAR_HEIGHT)); + let response = ui.interact(close, ui.scope_id().with("close"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Close"))); + if opening { + response.request_focus(); + } + + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(close.center(), Align2::CENTER_CENTER, icon::X, FontId::proportional(TITLE_TEXT_SIZE), color); + crate::property_sheet::paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +/// OK then Cancel at the right, both neutral; returns (OK, Cancel) clicked +fn buttons(ui: &mut Ui, tokens: &Tokens) -> (bool, bool) { + let (row, _) = ui.allocate_exact_size(vec2(DIALOG_WIDTH, BUTTON_SIZE.y), Sense::hover()); + let cancel = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.top()), BUTTON_SIZE); + let ok = cancel.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0)); + (dialog_button(ui, tokens, ok, tr("OK")), dialog_button(ui, tokens, cancel, tr("Cancel"))) +} + +fn dialog_button(ui: &mut Ui, tokens: &Tokens, rect: Rect, text: &str) -> bool { + let response = ui.interact(rect, ui.scope_id().with(text), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(DIALOG_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(TITLE_TEXT_SIZE), tokens.text); + crate::property_sheet::paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +/// What `set` holds in `group` that differs from `source`, dim beside it: output size and antialiasing by value, the rest counted +fn differing_values(set: &BakeSettings, source: &BakeSettings, group: BakeSyncGroup) -> Option { + let mut taken = set.clone(); + taken.copy_group(source, group); + let mut patch = settings_patch(set, &taken); + let mut values = Vec::new(); + if let Some(common) = patch.get_mut("common").and_then(Value::as_object_mut) { + let resolution = common.remove("resolution").is_some(); + let height = common.remove("resolution_height").is_some(); + if resolution || height { + values.push(match set.common.output_size() { + (width, height) if width == height => width.to_string(), + (width, height) => format!("{width} × {height}"), + }); + } + if common.remove("antialiasing").is_some() { + values.push(tr(antialiasing_label(set.common.antialiasing)).to_owned()); + } + } + let rest = leaf_count(&patch); + match (values.is_empty(), rest) { + (true, 0) => None, + (true, 1) => Some(tr("1 differing setting").to_owned()), + (true, count) => Some(trf("{count} differing settings", &[("count", &count.to_string())])), + (false, 0) => Some(values.join(" · ")), + (false, count) => Some(trf("{values} · {count} more", &[("values", &values.join(" · ")), ("count", &count.to_string())])), + } +} + +/// How many plain values a settings patch changes +fn leaf_count(patch: &Value) -> usize { + match patch { + Value::Object(fields) => fields.values().map(leaf_count).sum(), + _ => 1, + } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; + + use super::{SetPicker, SetPickerPurpose, differing_values}; + + #[test] + fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.resolution = BakeResolution::R1024; + set.common.antialiasing = BakeAntialiasing::Subsampling4x4; + set.common.dilation = 8; + set.high_poly.ignore_backface = !source.high_poly.ignore_backface; + + let note = differing_values(&set, &source, BakeSyncGroup::Common); + + assert_eq!(note.as_deref(), Some("1024 · Subsampling 4x4 · 2 more")); + } + + #[test] + fn a_set_matching_the_group_shows_nothing_and_other_groups_are_not_compared() { + let source = BakeSettings::default(); + let mut set = BakeSettings::default(); + set.common.is_enabled = false; + set.maps.ao.parameters.rays.rays = 16; + + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Common), None); + assert_eq!(differing_values(&set, &source, BakeSyncGroup::Map(BakedMap::AmbientOcclusion)).as_deref(), Some("1 differing setting")); + } + + #[test] + fn the_note_compares_with_the_set_the_sync_will_take_settings_from() { + let ao = BakeSyncGroup::Map(BakedMap::AmbientOcclusion); + let mut project = texturecraft_engine::sample_session(256, 64).unwrap().doc.project; + let third = project.texture_sets[1].clone(); + project.texture_sets.push(third); + for (index, set) in project.texture_sets.iter_mut().enumerate() { + set.bake = BakeSettings::default(); + set.bake.sync.set_shares(ao, index == 0); + } + project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16; + + // Set 0 leaves the group and sets 1 and 2 join with set 1 active: set 2 takes set 1's values, not set 0's + let picker = + SetPicker { purpose: SetPickerPurpose::Sync(ao), chosen: vec![false, true, true], mesh_id: 0, active: 1, opener: egui::Id::NULL, cached: None }; + let rows = picker.rows(&project, 1); + let note = |index: usize| rows.iter().find(|row| row.index == index).and_then(|row| row.note.clone()); + + assert_eq!(note(2).as_deref(), Some("1 differing setting")); + assert_eq!(note(1), None, "the source itself has nothing to take"); + } +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_purpose.rs b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs new file mode 100644 index 00000000..f2b21b50 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_purpose.rs @@ -0,0 +1,10 @@ +use texturecraft_engine::core::{BakeSyncGroup, BakedMap}; + +/// What a texture set picker does with the sets chosen in it +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum SetPickerPurpose { + /// Exactly the chosen sets share the group's settings + Sync(BakeSyncGroup), + /// Copy from the active set to the chosen ones: `what` as the `bake.copy` command takes it, for one map or for all + Copy { what: &'static str, map: Option }, +} diff --git a/crates/ui-egui/src/bake_mode/set_picker_row.rs b/crates/ui-egui/src/bake_mode/set_picker_row.rs new file mode 100644 index 00000000..05eca577 --- /dev/null +++ b/crates/ui-egui/src/bake_mode/set_picker_row.rs @@ -0,0 +1,8 @@ +/// One texture set listed in the set picker +#[derive(Debug)] +pub(super) struct SetPickerRow { + pub(super) index: usize, + pub(super) name: String, + /// For a set not yet sharing a sync group, the values it would give up + pub(super) note: Option, +} diff --git a/crates/ui-egui/src/bake_scene.rs b/crates/ui-egui/src/bake_scene.rs index 1a30780e..82f4a3d3 100644 --- a/crates/ui-egui/src/bake_scene.rs +++ b/crates/ui-egui/src/bake_scene.rs @@ -7,5 +7,7 @@ mod cage_upload; mod reach_link; mod shared_handle; +pub(crate) use shared_handle::SharedHandle; + pub use bake_scene_link::BakeSceneLink; pub use cage_upload::CageUpload; diff --git a/crates/ui-egui/src/bake_scene/bake_scene_link.rs b/crates/ui-egui/src/bake_scene/bake_scene_link.rs index 766a43c2..4055fd47 100644 --- a/crates/ui-egui/src/bake_scene/bake_scene_link.rs +++ b/crates/ui-egui/src/bake_scene/bake_scene_link.rs @@ -14,6 +14,8 @@ use crate::gpu::SceneSync; /// What the GPU has of bake mode's visualization: the high poly, each set's cage and the missing seams #[derive(Default)] pub struct BakeSceneLink { + mesh_id: Option, + clear_gpu: bool, /// The high poly sent to the GPU and the id it was sent under (each new high poly gets the next one) high: SharedHandle, high_id: u64, @@ -31,6 +33,7 @@ pub struct BakeSceneLink { impl BakeSceneLink { /// Send everything again (the GPU lost what it was sent); the cage shells and the reach worked out on the CPU stay pub fn resend(&mut self) { + self.clear_gpu = true; self.high_sent = false; self.sent_cage_count = None; self.seams_mesh_id = None; @@ -47,12 +50,25 @@ impl BakeSceneLink { /// Add to `out` what the GPU needs to draw `visualization` this frame pub fn sync(&mut self, session: &Session, visualization: Option, out: &mut SceneSync) { + if self.mesh_id.replace(session.mesh_id).is_some_and(|previous| previous != session.mesh_id) { + self.high = Default::default(); + self.reach.reset_for_mesh(); + self.cages.clear(); + self.resend(); + } + + if std::mem::take(&mut self.clear_gpu) { + out.bake_high = Some((None, self.high_id)); + out.bake_cage_count = Some(0); + out.missing_seams = Some((session.mesh_id, Vec::new())); + } + self.reach.poll(); let Some(visualization) = visualization else { return }; if visualization.high_poly.shown { - let high = session.bake_meshes.merged_high().map(|high| high.mesh.clone()); + let high = session.doc.bake_meshes.merged_high().map(|high| high.mesh.clone()); let handle = SharedHandle::of(high.as_ref()); if handle != self.high { self.high = handle; @@ -228,6 +244,27 @@ mod tests { assert!(!link.busy(), "a lost frame doesn't work out the reach again"); } + #[test] + fn switching_projects_releases_hidden_cage_shells_and_renderer_buffers() { + let mut link = BakeSceneLink::default(); + for _ in 0..2 { + let project = session(); + let mut frame = sync(&mut link, &project, everything()); + let shells: Vec<_> = frame.bake_cages.drain(..).filter_map(|(_, cage, _)| cage.map(|upload| Arc::downgrade(&upload.shell))).collect(); + assert!(shells.len() > 1); + + let empty = Session::new_project("Empty", texturecraft_engine::geom::primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let mut hidden = SceneSync::default(); + link.sync(&empty, None, &mut hidden); + + let retained = shells.iter().filter(|shell| shell.strong_count() > 0).count(); + eprintln!("hidden project replacement: previous_shells={} retained={retained}", shells.len()); + assert_eq!(retained, 0); + assert!(matches!(hidden.bake_high, Some((None, _)))); + assert_eq!(hidden.bake_cage_count, Some(0)); + } + } + #[test] fn a_hidden_high_poly_leaves_the_gpu_and_comes_back_without_a_new_reach() { let (session, mut link) = (session(), BakeSceneLink::default()); diff --git a/crates/ui-egui/src/bake_scene/cage_shell_key.rs b/crates/ui-egui/src/bake_scene/cage_shell_key.rs index 44e17eca..126c7f06 100644 --- a/crates/ui-egui/src/bake_scene/cage_shell_key.rs +++ b/crates/ui-egui/src/bake_scene/cage_shell_key.rs @@ -2,12 +2,12 @@ use std::collections::BTreeMap; use texturecraft_engine::Session; use texturecraft_engine::bake::BakePaintMap; -use texturecraft_engine::core::{BakePaintTarget, CageType, SkewSettings}; +use texturecraft_engine::core::{BakePaintTarget, CageType, HighPolySettings, SkewSettings}; use texturecraft_engine::geom::Mesh; use super::shared_handle::SharedHandle; -/// Everything a texture set's cage shell is built from except the distances, which only move its corners +/// Everything a texture set's cage shell and ray reach are built from except the distances, which only move its corners #[derive(Clone, Debug, PartialEq)] pub(super) struct CageShellKey { mesh_id: u64, @@ -19,7 +19,8 @@ pub(super) struct CageShellKey { cage_kind: CageType, relative_to_bounding_box: bool, average_normals: bool, - use_low_as_high: bool, + /// Whether the set has a cage at all, the name matching the automatic cage fits by and the backfaces the reach leaves out + high_poly: HighPolySettings, skew: SkewSettings, /// The painted skew and cage maps paint: [SharedHandle; 2], @@ -31,17 +32,37 @@ impl CageShellKey { let paint = |target| SharedHandle::of(session.doc.bake_paint.get(&(texture_set, target))); Some(CageShellKey { mesh_id: session.mesh_id, - high: SharedHandle::of(session.bake_meshes.merged_high().map(|high| &high.mesh)), - cage_file: SharedHandle::of(session.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), + high: SharedHandle::of(session.doc.bake_meshes.merged_high().map(|high| &high.mesh)), + cage_file: SharedHandle::of(session.doc.bake_meshes.cage.as_ref().map(|cage| &cage.mesh)), material: set.material, uv_tiles: set.uv_tiles.clone(), tile_resolutions: set.tile_resolutions.clone(), cage_kind: set.bake.cage.kind, relative_to_bounding_box: set.bake.cage.relative_to_bounding_box, average_normals: set.bake.cage.average_normals, - use_low_as_high: set.bake.high_poly.use_low_as_high, + high_poly: set.bake.high_poly.clone(), skew: set.bake.skew, paint: [paint(BakePaintTarget::Skew), paint(BakePaintTarget::Cage)], }) } } + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::MeshMatchMode; + use texturecraft_engine::geom::primitives; + + #[test] + fn the_key_changes_with_the_name_matching_the_automatic_cage_is_fitted_by() { + let mut session = Session::new_project("Cage", primitives::plane(1.0, 1), "plane", None, 128).unwrap(); + let before = CageShellKey::of(&session, 0); + + session.doc.project.texture_sets[0].bake.high_poly.match_mode = MeshMatchMode::ByMeshName; + let by_name = CageShellKey::of(&session, 0); + session.doc.project.texture_sets[0].bake.high_poly.high_suffix = "_hp".into(); + + assert_ne!(before, by_name); + assert_ne!(by_name, CageShellKey::of(&session, 0)); + } +} diff --git a/crates/ui-egui/src/bake_scene/reach_link.rs b/crates/ui-egui/src/bake_scene/reach_link.rs index f94ed3d5..68399feb 100644 --- a/crates/ui-egui/src/bake_scene/reach_link.rs +++ b/crates/ui-egui/src/bake_scene/reach_link.rs @@ -2,7 +2,6 @@ use std::sync::mpsc::{Receiver, TryRecvError}; use texturecraft_engine::Session; use texturecraft_engine::bake::{HighPolyReach, high_poly_missed}; -use texturecraft_engine::core::HighPolySettings; use super::cage_shell_key::CageShellKey; use crate::gpu::SceneSync; @@ -13,8 +12,8 @@ type ShownDistances = (Vec<(f32, f32)>, Option); /// The red on the high poly: each texture set's ray reach, worked out on a worker thread, and the distances the GPU's colors show #[derive(Default)] pub(super) struct ReachLink { - /// Each set's ray inputs and high-poly settings (backfaces, name matching), and the id of the high poly, the reach was started for - keys: Vec>, + /// Each set's ray inputs, and the id of the high poly, the reach was started for + keys: Vec>, high_id: u64, job: Option>>>, reach: Vec>, @@ -23,6 +22,11 @@ pub(super) struct ReachLink { } impl ReachLink { + pub(super) fn reset_for_mesh(&mut self) { + // Keep at most one worker across project switches and discard its obsolete result + *self = Self { job: self.job.take(), ..Default::default() }; + } + /// Whether a reach is being worked out (the view must keep drawing to pick it up) pub(super) fn busy(&self) -> bool { self.job.is_some() @@ -39,7 +43,9 @@ impl ReachLink { match job.try_recv() { Ok(reach) => { - self.reach = reach; + if !self.keys.is_empty() { + self.reach = reach; + } self.shown = None; self.job = None; } @@ -56,14 +62,7 @@ impl ReachLink { } let set_count = session.doc.project.texture_sets.len(); - let keys: Vec> = session - .doc - .project - .texture_sets - .iter() - .enumerate() - .map(|(texture_set, set)| Some((CageShellKey::of(session, texture_set)?, set.bake.high_poly.clone()))) - .collect(); + let keys: Vec> = (0..set_count).map(|texture_set| CageShellKey::of(session, texture_set)).collect(); if keys != self.keys || high_id != self.high_id { // The GPU keeps displayed colors; stale CPU arrays need not overlap the rebuild @@ -87,7 +86,7 @@ impl ReachLink { return; } - let Some(vertex_count) = session.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; + let Some(vertex_count) = session.doc.bake_meshes.merged_high().map(|high| high.mesh.positions.len()) else { return }; out.bake_high_missed = Some((self.high_id, high_poly_missed(&self.reach, &shown.0, only_set, vertex_count))); self.shown = Some(shown); @@ -103,6 +102,21 @@ mod tests { use texturecraft_engine::core::BakePaintTarget; use texturecraft_engine::geom::primitives; + #[test] + fn switching_projects_waits_for_old_work_and_discards_its_result() { + let (sender, receiver) = mpsc::channel(); + let mut link = ReachLink { job: Some(receiver), ..Default::default() }; + + link.reset_for_mesh(); + + assert!(link.busy(), "a project switch must keep the single running worker"); + sender.send(vec![Some(HighPolyReach::default())]).unwrap(); + link.poll(); + + assert!(!link.busy()); + assert!(link.reach.is_empty(), "a hidden scene must release the previous project's result"); + } + #[test] fn rebuilding_reach_releases_previous_vertex_arrays_before_starting_work() { const PREVIOUS_SET_COUNT: usize = 2; @@ -164,7 +178,7 @@ mod tests { link.sync(&session, 2, None, &mut out); let (high_id, missed) = out.bake_high_missed.unwrap(); assert_eq!(high_id, 2); - assert_eq!(missed, vec![0.0; session.bake_meshes.merged_high().unwrap().mesh.positions.len()]); + assert_eq!(missed, vec![0.0; session.doc.bake_meshes.merged_high().unwrap().mesh.positions.len()]); assert!(link.reach[0].is_none(), "the latest setting bakes without a high poly"); } } diff --git a/crates/ui-egui/src/bake_scene/shared_handle.rs b/crates/ui-egui/src/bake_scene/shared_handle.rs index 15ceb1d8..418d3953 100644 --- a/crates/ui-egui/src/bake_scene/shared_handle.rs +++ b/crates/ui-egui/src/bake_scene/shared_handle.rs @@ -2,10 +2,10 @@ use std::sync::{Arc, Weak}; /// Which shared value a key refers to, without keeping the value alive; the held `Weak` keeps its address from being reused, so a new value never passes for it #[derive(Debug)] -pub(super) struct SharedHandle(Option>); +pub(crate) struct SharedHandle(Option>); impl SharedHandle { - pub(super) fn of(value: Option<&Arc>) -> SharedHandle { + pub(crate) fn of(value: Option<&Arc>) -> SharedHandle { SharedHandle(value.map(Arc::downgrade)) } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 761928ec..c900230b 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -262,8 +262,8 @@ pub(crate) const TAB_HEIGHT: f32 = 30.0; /// Width of the bake layout's texture set and mesh map bakers column in points: the reference's scaled to our larger font const BAKERS_COLUMN_WIDTH: f32 = 232.0; -/// Width of the bake layout's common and mesh map settings column, in points -const SETTINGS_COLUMN_WIDTH: f32 = 330.0; +/// Width of the bake layout's common and mesh map settings column, in points: both tab names fit beside the × +const SETTINGS_COLUMN_WIDTH: f32 = 380.0; /// Height of the log under the bake layout's columns, in points const BAKING_LOG_HEIGHT: f32 = 160.0; /// Share of the first bake column the texture set list takes above the mesh map bakers diff --git a/crates/ui-egui/src/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs new file mode 100644 index 00000000..d3a621c3 --- /dev/null +++ b/crates/ui-egui/src/high_poly_job.rs @@ -0,0 +1,85 @@ +use std::collections::VecDeque; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::time::Duration; + +use texturecraft_engine::{EngineError, HighPolyLoad, Result}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; + +/// How often the app looks for the worker's answer while a file loads +const POLL_INTERVAL: Duration = Duration::from_millis(30); + +/// High poly files loading on a worker thread, one after the other, so a large mesh does not freeze the app +pub struct HighPolyJob { + /// The file being loaded + pub current: String, + /// The worker's answer for `current` + answer: Receiver>, + /// The files still to load, in order + pub queue: VecDeque, + /// The project the files are for: they are dropped once another project is open + project: u64, +} + +impl HighPolyJob { + /// The names of the files being loaded and waiting, without their folders + pub fn file_names(&self) -> impl Iterator { + std::iter::once(&self.current).chain(&self.queue).map(|path| std::path::Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path)) + } +} + +impl TextureCraftApp { + /// Add the mesh files at `paths` as high polys, read and parsed on a worker thread + pub fn load_high_polys(&mut self, paths: impl IntoIterator) { + let mut paths: VecDeque = paths.into_iter().collect(); + match &mut self.high_poly_job { + Some(job) if job.project == self.session.project_id => job.queue.append(&mut paths), + _ => self.load_next_high_poly(paths), + } + } + + /// Start loading the first of `queue`, on top of the high polys the session has now + fn load_next_high_poly(&mut self, mut queue: VecDeque) { + self.high_poly_job = queue.pop_front().map(|current| { + let mut meshes = texturecraft_engine::BakeMeshes::default(); + meshes.high.clone_from(&self.session.doc.bake_meshes.high); + let path = current.clone(); + let answer = crate::spawn_worker("texturecraft-high-poly", move || HighPolyLoad::read(&meshes, &path)); + HighPolyJob { current, answer, queue, project: self.session.project_id } + }); + } + + /// Add a loaded high poly to the session (once no paint stroke is running) and start on the next file; drop them all once another project is open + pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { + let Some(job) = &self.high_poly_job else { return }; + + if job.project != self.session.project_id { + self.high_poly_job = None; + self.toast(tr("The project changed while the high polys loaded, so they were not added"), true); + return; + } + + context.request_repaint_after(POLL_INTERVAL); + + // An unfinished stroke can restore its starting document + if self.session.stroke_active() { + return; + } + + let loaded = match job.answer.try_recv() { + Ok(loaded) => loaded, + Err(TryRecvError::Empty) => return, + Err(TryRecvError::Disconnected) => Err(EngineError::Other(tr("The mesh loading worker stopped").into())), + }; + let Some(job) = self.high_poly_job.take() else { return }; + + match loaded { + Ok(load) => { + self.session.apply_high_poly_load(load); + } + Err(error) => self.toast(trf("Couldn't import {name}: {error}", &[("name", &job.current), ("error", &error.to_string())]), true), + } + self.load_next_high_poly(job.queue); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c2df800e..66200f60 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -57,6 +57,8 @@ mod generator_wear_rows; pub mod gpu; mod gray_slider; mod grid_tile; +#[cfg(not(target_arch = "wasm32"))] +mod high_poly_job; mod histogram_cache; pub mod i18n; pub mod id_color_pick; @@ -193,6 +195,8 @@ use texturecraft_engine::bake::Progress; pub use bake_job::BakeJob; pub use control::ControlRequest; +#[cfg(not(target_arch = "wasm32"))] +pub use high_poly_job::HighPolyJob; pub use running_bake::RunningBake; pub use state::UiState; @@ -275,12 +279,19 @@ pub struct TextureCraftApp { /// The Import PBR textures dialog while it is open. pub pbr_import: Option, pub resize: Option, + /// High poly files being loaded for the bake + #[cfg(not(target_arch = "wasm32"))] + pub high_poly_job: Option, pub link_cooks: Vec, #[cfg(not(target_arch = "wasm32"))] link_imports: Vec, pub thumbs: thumbs::Thumbs, /// The Layers panel's thumbnails and folded groups. pub layer_panel: layer_panel::LayerPanel, + /// The Mesh Map Bakers rows' thumbnails + pub(crate) bake_map_thumbnails: bake_mode::MapThumbnails, + /// The map preview: the selected map on the model while Mesh Map Settings shows it + pub(crate) live_preview: bake_mode::LivePreview, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -416,11 +427,15 @@ impl TextureCraftApp { bake_report: Default::default(), pbr_import: None, resize: None, + #[cfg(not(target_arch = "wasm32"))] + high_poly_job: None, link_cooks: Vec::new(), #[cfg(not(target_arch = "wasm32"))] link_imports: Vec::new(), thumbs: thumbs::Thumbs::default(), layer_panel: layer_panel::LayerPanel::default(), + bake_map_thumbnails: bake_mode::MapThumbnails::default(), + live_preview: bake_mode::LivePreview::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, @@ -610,24 +625,33 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY, show_log: false }); } - /// Start baking texture sets in the background, one after another. Invalid set indices - /// show an error without starting a preview or queuing any work. + /// Bake texture sets in the background, one after another; invalid set indices show an error without starting anything pub fn start_bake(&mut self, sets: Vec) { + self.start_bake_of(sets, None); + } + + /// Bake `sets`: only map `only` when given, else each set's checked maps + pub fn start_bake_of(&mut self, sets: Vec, only: Option) { if self.bake.is_some() || sets.is_empty() { return; } - // Restore the picker's view before the preview starts following baked maps - id_color_pick::IdColorPick::end(self); + let orders = match self.session.bake_preview_orders(&sets, only) { + Ok(orders) => orders, + Err(error) => { + self.toast(error.to_string(), true); + return; + } + }; - if let Err(error) = self.session.bake_preview_begin_for(&sets) { - self.toast(error.to_string(), true); - return; - } + // Restore the previous view before the real bake takes it over + self.live_preview.release(&mut self.session); + id_color_pick::IdColorPick::end(self); + self.session.bake_preview_begin(orders); let total = sets.len(); self.bake_report = bake_report::BakeReport::started(self.last_time); - self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id }); + self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id, only }); } /// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer @@ -724,8 +748,7 @@ impl TextureCraftApp { } } - /// Show at most one streamed map per frame, then apply the set as one undo step after - /// its map channel closes. Closing the preview alone does not stop the background bake. + /// Show at most one streamed map per frame, then apply the set as one undo step once its map channel closes; closing the preview alone does not stop the bake fn poll_bake(&mut self, ctx: &egui::Context) { // Leaving Bake mode puts the view mode back; the bake goes on if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { @@ -733,8 +756,10 @@ impl TextureCraftApp { } let Some(job) = self.bake.as_mut() else { - // A preview whose bake is gone must not keep the view - self.session.bake_preview_end(); + // A preview whose bake is gone must not keep the view; the map preview keeps its own + if self.live_preview.shown().is_none() { + self.session.bake_preview_end(); + } return; }; @@ -747,7 +772,7 @@ impl TextureCraftApp { return; } - ctx.request_repaint_after(std::time::Duration::from_millis(50)); + ctx.request_repaint_after(BAKE_POLL_INTERVAL); if let Some(running) = &job.current { let set_index = running.set_index; @@ -798,8 +823,14 @@ impl TextureCraftApp { } let set_index = job.queue.remove(0); + let only = job.only; + self.session.bake_preview_set_current(set_index); - match self.session.bake_task(set_index) { + let task = match only { + Some(map) => self.session.bake_task_only(set_index, map), + None => self.session.bake_task(set_index), + }; + match task { Ok(task) => { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); @@ -810,7 +841,9 @@ impl TextureCraftApp { let receiver = spawn_worker("texturecraft-bake", move || { task.run_streaming(&worker_progress, &mut |map| { worker_done.fetch_add(1, Ordering::Relaxed); - let _ = sender.send(map); + if sender.send(map).is_err() { + worker_progress.cancel(); + } }) }); @@ -1026,6 +1059,9 @@ struct CameraGlide { const GLIDE_SECONDS: f64 = 0.35; +/// How often a running bake is checked for finished maps: often enough that each shows within a few frames +const BAKE_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(50); + /// The share of the running frame rate and frame time averages each frame keeps (an average over about ten frames) const FRAME_AVERAGE_KEEP: f32 = 0.9; /// The interface scale applied: wider than the Settings slider, so a scale set elsewhere still applies within reason @@ -1117,7 +1153,11 @@ impl eframe::App for TextureCraftApp { } } self.poll_bake(ctx); + self.bake_map_thumbnails.retain_mesh(self.session.mesh_id); + bake_mode::poll_live_preview(self, ctx); self.poll_resize(ctx); + #[cfg(not(target_arch = "wasm32"))] + self.poll_high_poly_job(ctx); self.poll_link_cooks(ctx); #[cfg(not(target_arch = "wasm32"))] self.poll_link_imports(ctx); diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 5917a337..122857cb 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -159,7 +159,8 @@ impl PropertySheet<'_> { pub(super) fn dropdown_button_led(&mut self, rect: Rect, value: &str, lead: impl FnOnce(&Painter) -> f32) -> Response { let id = self.next_id(); let response = self.ui.interact(rect, id, Sense::click()); - response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, true, value)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(Role::ComboBox, enabled, value)); let tokens = self.tokens; let painter = self.ui.painter(); painter.rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), if response.hovered() { tokens.row_hover } else { tokens.button }); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs new file mode 100644 index 00000000..8563df58 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -0,0 +1,173 @@ +//! A list of loaded files under its label, one row per file, with its add button beside it + +use egui::{Align2, CornerRadius, FontId, Rect, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::FileListAdd; +use super::stacked_rows::{LABEL_LINE, STACK_ROW_AIR}; +use super::{CONTROL_RADIUS, FileListResponse, FileRow, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// One file's row, and the list's inner margin above and below its rows +const FILE_ROW_HEIGHT: f32 = 40.0; +const LIST_MARGIN: f32 = 2.0; + +/// The add button's square and the room it takes beside the list +const ADD_BUTTON_SIZE: f32 = 28.0; +const ADD_BUTTON_ROOM: f32 = 34.0; + +/// Where a row's cube sits, where its words start, and its × from the list's right edge +const CUBE_CENTER: f32 = 16.0; +const CUBE_SIZE: f32 = 14.0; +const NAME_LEFT: f32 = 32.0; +const REMOVE_INSET: f32 = 14.0; +const REMOVE_SIZE: f32 = 12.0; +const REMOVE_BOX: f32 = 18.0; + +/// The name's and the folder's centres from the row's top, when the row shows both +const NAME_CENTER: f32 = 13.0; +const FOLDER_CENTER: f32 = 28.0; + +/// The hairline between rows stops this far from the list's sides +const DIVIDER_INSET: f32 = 8.0; + +/// Size of the add button's glyph +const ADD_GLYPH_SIZE: f32 = 14.0; + +/// What stands for the folders left out of a shortened path +const ELLIPSIS: &str = "…"; + +impl PropertySheet<'_> { + /// `rows` in a box at least `min_rows` tall, with the `add` button beside it; each loaded file's × (`remove_label`) asks to remove it + pub(crate) fn file_list(&mut self, label: &str, rows: &[FileRow<'_>], min_rows: usize, add: FileListAdd<'_>, remove_label: &str) -> FileListResponse { + let line = self.take(LABEL_LINE); + let tokens = self.tokens; + self.ui.painter().text(pos2(self.left, line.center().y), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), tokens.text); + + let height = rows.len().max(min_rows) as f32 * FILE_ROW_HEIGHT + 2.0 * LIST_MARGIN; + let area = self.take(height); + let list = Rect::from_min_max(pos2(self.left, area.top()), pos2(self.right - ADD_BUTTON_ROOM, area.bottom())); + let list_id = self.next_id(); + let list_response = self.ui.interact(list, list_id, Sense::hover()); + let enabled = self.ui.is_enabled(); + list_response.widget_info(|| WidgetInfo::labeled(egui::Role::List, enabled, label)); + self.ui.painter().rect(list, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + let mut answer = FileListResponse::default(); + for (index, row) in rows.iter().enumerate() { + let top = list.top() + LIST_MARGIN + index as f32 * FILE_ROW_HEIGHT; + let rect = Rect::from_min_max(pos2(list.left(), top), pos2(list.right(), top + FILE_ROW_HEIGHT)); + if index > 0 { + let divider = [pos2(list.left() + DIVIDER_INSET, top), pos2(list.right() - DIVIDER_INSET, top)]; + self.ui.painter().line_segment(divider, Stroke::new(1.0, tokens.separator)); + } + if self.file_row(rect, row, remove_label) { + answer.removed = Some(index); + } + } + + let add_rect = Rect::from_min_size(pos2(self.right - ADD_BUTTON_SIZE, area.top()), vec2(ADD_BUTTON_SIZE, ADD_BUTTON_SIZE)); + let add_id = self.next_id(); + let can_add = add.enabled && enabled; + let add_response = self.ui.interact(add_rect, add_id, if can_add { Sense::click() } else { Sense::hover() }); + add_response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, can_add, add.label)); + let add_response = self.tip(add_response, add.label); + let fill = if can_add && add_response.hovered() { tokens.row_hover } else { tokens.button }; + let glyph_color = if can_add { tokens.text } else { tokens.text_dim }; + let painter = self.ui.painter(); + painter.rect(add_rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + painter.text(add_rect.center(), Align2::CENTER_CENTER, add.glyph, FontId::proportional(ADD_GLYPH_SIZE), glyph_color); + self.paint_control_focus(&add_response); + answer.add = can_add && add_response.clicked(); + + self.drawn(area.bottom()); + self.space(2.0 * STACK_ROW_AIR); + answer + } + + /// One file's row in `rect`; returns whether its × was clicked + fn file_row(&mut self, rect: Rect, row: &FileRow<'_>, remove_label: &str) -> bool { + let tokens = self.tokens; + let words_right = rect.right() - REMOVE_INSET - REMOVE_BOX / 2.0; + let name_color = if row.loading { tokens.text_dim } else { tokens.text }; + let name_font = if row.loading { FontId::proportional(TEXT_SIZE) } else { semibold(TEXT_SIZE) }; + let name_y = if row.folder.is_some() { rect.top() + NAME_CENTER } else { rect.center().y }; + let painter = self.ui.painter().clone(); + painter.text(pos2(rect.left() + CUBE_CENTER, rect.center().y), Align2::CENTER_CENTER, ic::CUBE, FontId::proportional(CUBE_SIZE), tokens.text_dim); + let mut job = egui::text::LayoutJob::simple_singleline(row.name.to_owned(), name_font, name_color); + job.wrap = egui::text::TextWrapping::truncate_at_width((words_right - rect.left() - NAME_LEFT).max(0.0)); + let name = painter.layout_job(job); + painter.galley(pos2(rect.left() + NAME_LEFT, name_y - name.size().y / 2.0), name, name_color); + if let Some(folder) = row.folder { + let shown = folder_galley(&painter, folder, words_right - rect.left() - NAME_LEFT, tokens.text_dim); + painter.galley(pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER - shown.size().y / 2.0), shown, tokens.text_dim); + } + + let words = Rect::from_min_max(pos2(rect.left(), rect.top()), pos2(words_right, rect.bottom())); + let words_id = self.next_id(); + let words_response = self.ui.interact(words, words_id, Sense::hover()); + let enabled = self.ui.is_enabled() && !row.loading; + words_response.widget_info(|| WidgetInfo::labeled(egui::Role::ListItem, enabled, row.name)); + let full = match row.folder { + Some(folder) => format!("{}\n{folder}", row.name), + None => row.name.to_owned(), + }; + self.tip(words_response, &full); + if row.loading { + return false; + } + + let remove = Rect::from_center_size(pos2(rect.right() - REMOVE_INSET, rect.center().y), vec2(REMOVE_BOX, REMOVE_BOX)); + let id = self.next_id(); + let response = self.ui.interact(remove, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Button, self.ui.is_enabled(), remove_label)); + let response = self.tip(response, remove_label); + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(remove.center(), Align2::CENTER_CENTER, ic::X, FontId::proportional(REMOVE_SIZE), color); + self.paint_control_focus(&response); + response.clicked() + } +} + +/// `folder` shortened to fit `room`, cut with "…" when even its first and last folders are too wide +fn folder_galley(painter: &egui::Painter, folder: &str, room: f32, color: egui::Color32) -> std::sync::Arc { + crate::widgets::elided(painter, shortened_folder(painter, folder, room), SMALL_TEXT_SIZE, color, room) +} + +/// `folder` with folders after its first one left out, from the second on, until it fits in `room` +fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String { + let fits = |text: &str| painter.layout_no_wrap(text.to_owned(), FontId::proportional(SMALL_TEXT_SIZE), egui::Color32::WHITE).size().x <= room; + let mut parts: Vec<&str> = folder.split(['/', '\\']).collect(); + let mut shown = parts.join("/"); + while !fits(&shown) && parts.len() > 2 { + if parts[1] == ELLIPSIS { + parts.remove(2); + } else { + parts[1] = ELLIPSIS; + } + shown = parts.join("/"); + } + shown +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_folder_too_long_even_when_shortened_is_cut_to_its_room() { + let room = 120.0; + let folder = format!("C:\\{}", "W".repeat(80)); + let mut laid_out = None; + let mut output = egui::Context::default().run_ui(egui::RawInput::default(), |ui| { + laid_out = Some(folder_galley(ui.painter(), &folder, room, egui::Color32::WHITE)); + }); + + // The font atlas upload is not under test + output.textures_delta.clear(); + let galley = laid_out.unwrap(); + + assert!(galley.size().x <= room); + assert_eq!(galley.rows[0].glyphs.last().map(|glyph| glyph.chr), Some('…')); + } +} diff --git a/crates/ui-egui/src/property_sheet/file_list_add.rs b/crates/ui-egui/src/property_sheet/file_list_add.rs new file mode 100644 index 00000000..f790083e --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_add.rs @@ -0,0 +1,6 @@ +/// A file list's add button: its glyph, its label (also its tooltip) and whether it can add now +pub(crate) struct FileListAdd<'a> { + pub(crate) glyph: &'a str, + pub(crate) label: &'a str, + pub(crate) enabled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/file_list_response.rs b/crates/ui-egui/src/property_sheet/file_list_response.rs new file mode 100644 index 00000000..e0b24c24 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_list_response.rs @@ -0,0 +1,6 @@ +/// What a file list answered: its add button clicked, or a file's × clicked +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct FileListResponse { + pub(crate) add: bool, + pub(crate) removed: Option, +} diff --git a/crates/ui-egui/src/property_sheet/file_row.rs b/crates/ui-egui/src/property_sheet/file_row.rs new file mode 100644 index 00000000..1d7bf0c0 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/file_row.rs @@ -0,0 +1,7 @@ +/// One file of a file list: its name, the folder it was read from when known, and whether it is still loading +#[derive(Clone, Copy)] +pub(crate) struct FileRow<'a> { + pub(crate) name: &'a str, + pub(crate) folder: Option<&'a str>, + pub(crate) loading: bool, +} diff --git a/crates/ui-egui/src/property_sheet/fold_section.rs b/crates/ui-egui/src/property_sheet/fold_section.rs new file mode 100644 index 00000000..7f8e1d3d --- /dev/null +++ b/crates/ui-egui/src/property_sheet/fold_section.rs @@ -0,0 +1,7 @@ +use egui::Response; + +/// What a folding section's caption answered: whether its rows show, and its reset glyph +pub(crate) struct FoldSection { + pub(crate) open: bool, + pub(crate) reset: Response, +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 0a890707..a9097cd7 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -13,6 +13,11 @@ mod compare_row; mod compare_row_response; mod eye_toggle; mod factor_slider; +mod file_list; +mod file_list_add; +mod file_list_response; +mod file_row; +mod fold_section; mod gradient_rows; mod group; mod hold_pad; @@ -44,6 +49,7 @@ mod slot; mod slot_response; mod source_card; mod stack_slider; +mod stacked_rows; mod switch_control; mod tooltip; mod track; @@ -57,6 +63,10 @@ pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; pub(crate) use compare_row_response::CompareRowResponse; +pub(crate) use file_list_add::FileListAdd; +pub(crate) use file_list_response::FileListResponse; +pub(crate) use file_row::FileRow; +pub(crate) use fold_section::FoldSection; pub(crate) use id_color_row_response::IdColorRowResponse; pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; @@ -71,6 +81,13 @@ pub(crate) use sheet::PropertySheet; pub(crate) use size_columns_response::SizeColumnsResponse; pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; +pub(crate) use stacked_rows::{CHECK_SIZE, paint_check}; + +pub(crate) fn paint_keyboard_focus(ui: &egui::Ui, response: &egui::Response, tokens: &crate::theme::Tokens) { + if response.has_focus() { + switch_control::paint_focus_outline(ui.painter(), response.rect, tokens.text_strong); + } +} /// Side padding: every row starts and ends this far inside the panel pub(crate) const SIDE_PADDING_POINTS: f32 = 12.0; diff --git a/crates/ui-egui/src/property_sheet/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index 6d26f207..e1e5b1b6 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -27,6 +27,8 @@ pub(crate) struct PropertySheet<'u> { pub(super) sections: Vec<(String, f32)>, pub(super) info: Option<&'u str>, pub(super) held: bool, + /// Sub-headers so far in the current folding section: a later one takes air above it + pub(super) sub_headers: usize, } impl<'u> PropertySheet<'u> { @@ -53,6 +55,7 @@ impl<'u> PropertySheet<'u> { sections: Vec::new(), info: None, held: false, + sub_headers: 0, ui, }; let result = body(&mut sheet); diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 8e43a01e..3697880b 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -214,7 +214,8 @@ impl PropertySheet<'_> { pos2(track.end + KNOB_RADIUS, track.center_y + ROW_HIT_HALF_HEIGHT), ); let response = self.ui.interact(hit, id, Sense::click_and_drag()); - response.widget_info(|| WidgetInfo::slider(true, f64::from(*value), &label)); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::slider(enabled, f64::from(*value), &label)); // A press on the track drops what was typed in its value: the track's value is the one wanted if response.is_pointer_button_down_on() { @@ -318,7 +319,8 @@ impl PropertySheet<'_> { let Some(mut draft) = editing else { self.skip_typing_edit(); let response = self.ui.interact(rect, id.with("value"), Sense::click()).on_hover_cursor(egui::CursorIcon::Text); - response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", label)]))); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, crate::i18n::trf("{label} value", &[("label", label)]))); self.ui.painter().text(pos2(right, center_y), Align2::RIGHT_CENTER, shown, semibold(TEXT_SIZE), tokens.text); if response.hovered() { diff --git a/crates/ui-egui/src/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs new file mode 100644 index 00000000..d7934290 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -0,0 +1,475 @@ +//! Rows with their label above a full-width control, as the bake panels lay them out: folding sections, bold sub-headers, checks, and controls that grey out with a reason + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Rect, Response, Sense, Stroke, StrokeKind, UiBuilder, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::choice::ChoicePicture; +use super::number_field::shown_number; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use super::value_text::ValueText; +use super::{CONTROL_HEIGHT, CONTROL_RADIUS, FoldSection, ICON_SIZE, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Height of a label's line above its control, and its text's centre in it +pub(super) const LABEL_LINE: f32 = 18.0; +const LABEL_CENTER: f32 = 9.0; + +/// Air under a control before the next setting; full-width buttons and lists take it above and twice below, so two filled boxes never touch +pub(super) const STACK_ROW_AIR: f32 = 6.0; + +/// A slider's track line under its label, and its centre in it +const TRACK_LINE: f32 = 16.0; +const TRACK_CENTER: f32 = 8.0; + +/// A check's line, its box and the air from the box to its label +const CHECK_LINE: f32 = 20.0; +pub(crate) const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; +const CHECK_TO_LABEL: f32 = 9.0; + +/// The tick's three points across a check's box, as fractions of its side (from the reference's tick) +const TICK_POINTS: [(f32, f32); 3] = [(0.25, 0.52), (0.43, 0.7), (0.75, 0.3)]; +const TICK_WIDTH: f32 = 1.7; + +/// Half the length of a mixed check's dash, and its thickness +const DASH_HALF: f32 = 3.0; +const DASH_WIDTH: f32 = 2.0; + +/// Air above a later section's hairline and from it to the caption +const FOLD_AIR_ABOVE: f32 = 8.0; +const FOLD_RULE_TO_CAPTION: f32 = 10.0; + +/// Air above the first section's caption +const FOLD_FIRST_AIR: f32 = 10.0; + +/// A section caption's line, the air under it, and where its chevron and caption sit +const FOLD_CAPTION_LINE: f32 = 20.0; +const FOLD_CAPTION_AIR: f32 = 10.0; +const FOLD_CHEVRON_CENTER: f32 = 5.0; +const FOLD_CAPTION_LEFT: f32 = 18.0; + +/// The reset glyph's size and its centre's distance from the right edge +const FOLD_RESET_SIZE: f32 = 14.0; +const FOLD_RESET_INSET: f32 = 6.0; +const FOLD_RESET_BOX: f32 = 20.0; + +/// Air above a later sub-header, its line, and the air under it +const SUB_HEADER_AIR: f32 = 6.0; +const SUB_HEADER_LINE: f32 = 18.0; +const SUB_HEADER_GAP: f32 = 4.0; + +/// How far a sub-header's rows, and settings that belong to the one above, sit in from the left +const STACK_INDENT: f32 = 12.0; + +/// Opacity of a greyed setting, on top of egui's disabled fade: 0.4 in all, the locked bake mock's 60 % blend toward the panel +const GREYED_EXTRA_OPACITY: f32 = 0.8; + +/// A full-width button's glyph size and the air between it and its words +const WIDE_BUTTON_ICON_SIZE: f32 = 13.0; +const WIDE_BUTTON_ICON_GAP: f32 = 8.0; + +/// Width of the link between two paired dropdowns, and the air on its sides +const PAIR_LINK_WIDTH: f32 = 26.0; +const PAIR_LINK_AIR: f32 = 4.0; + +/// Values with more places than this drop their trailing zeros +const SHORT_DECIMALS: usize = 2; + +/// Air before a field's text +const FIELD_TEXT_INSET: i8 = 8; + +impl PropertySheet<'_> { + /// A section that folds: chevron and CAPS caption left, its reset glyph right, a hairline above a later one; the click on the caption line folds it + pub(crate) fn fold_section(&mut self, title: &str, default_open: bool) -> FoldSection { + self.close_card(); + if self.empty { + self.space(FOLD_FIRST_AIR); + } else { + self.space(FOLD_AIR_ABOVE); + let y = self.cursor_y(); + self.ui.painter().line_segment([pos2(self.left, y), pos2(self.right, y)], Stroke::new(1.0, self.tokens.separator)); + self.space(FOLD_RULE_TO_CAPTION); + } + + let section = self.id.with(("fold_section", title)); + self.scope = section; + self.band_scope = section; + let line = self.take(FOLD_CAPTION_LINE); + let center_y = line.center().y; + let reset_rect = Rect::from_center_size(pos2(self.right - FOLD_RESET_INSET, center_y), vec2(FOLD_RESET_BOX, FOLD_RESET_BOX)); + let header = Rect::from_min_max(pos2(self.left, line.top()), pos2(reset_rect.left(), line.bottom())); + + let mut open = self.ui.data(|data| data.get_temp::(section)).unwrap_or(default_open); + let fold = self.ui.interact(header, section.with("fold"), Sense::click()); + if fold.clicked() { + open = !open; + self.ui.data_mut(|data| data.insert_temp(section, open)); + } + let enabled = self.ui.is_enabled(); + fold.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, open, title)); + self.ui.ctx().accesskit_node_builder(fold.id, |node| node.set_expanded(open)); + + // Added after the caption's response, so the glyph takes the clicks over it + let reset = self.ui.interact(reset_rect, section.with("reset"), Sense::click()); + let reset_label = crate::i18n::trf("Reset {section}", &[("section", &title)]); + reset.widget_info(|| WidgetInfo::labeled(egui::Role::Button, enabled, &reset_label)); + let reset = self.tip(reset, &reset_label); + + let tokens = self.tokens; + let painter = self.ui.painter(); + let chevron = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; + painter.text(pos2(self.left + FOLD_CHEVRON_CENTER, center_y), Align2::CENTER_CENTER, chevron, FontId::proportional(ICON_SIZE), tokens.text); + painter.text(pos2(self.left + FOLD_CAPTION_LEFT, center_y), Align2::LEFT_CENTER, title.to_uppercase(), semibold(SMALL_TEXT_SIZE), tokens.text); + let reset_color = if reset.hovered() { tokens.text_strong } else { tokens.text_dim }; + painter.text(reset_rect.center(), Align2::CENTER_CENTER, ic::CLOCK_COUNTER_CLOCKWISE, FontId::proportional(FOLD_RESET_SIZE), reset_color); + self.paint_control_focus(&fold); + self.paint_control_focus(&reset); + self.drawn(line.bottom()); + if open { + self.space(FOLD_CAPTION_AIR); + } + self.sub_headers = 0; + FoldSection { open, reset } + } + + /// A bold sub-header; its rows follow one [`STACK_INDENT`] in, inside `body` + pub(crate) fn sub_header(&mut self, title: &str, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + if self.sub_headers > 0 { + self.space(SUB_HEADER_AIR); + } + self.sub_headers += 1; + let line = self.take(SUB_HEADER_LINE); + let text = self.tokens.text_strong; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), text); + self.drawn(line.bottom()); + self.space(SUB_HEADER_GAP); + self.indented(body) + } + + /// `body`'s rows one [`STACK_INDENT`] in from the left + pub(crate) fn indented(&mut self, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let left = self.left; + self.left += STACK_INDENT; + let result = body(self); + self.left = left; + result + } + + /// `body`'s rows, greyed and inert unless `enabled`; hovering them shows `reason` (which also names them for assistive tech). Inside a greyed part they grey no further + pub(crate) fn greyed(&mut self, enabled: bool, reason: Option<&str>, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { + let already_greyed = !self.ui.is_enabled(); + let top = self.cursor_y(); + let builder = UiBuilder::new().max_rect(self.ui.available_rect_before_wrap()).layout(*self.ui.layout()); + let mut child = self.ui.new_child(builder); + if !enabled && !already_greyed { + child.disable(); + child.multiply_opacity(GREYED_EXTRA_OPACITY); + } + + let mut sheet = PropertySheet { + tokens: self.tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: std::mem::take(&mut self.named), + left: self.left, + right: self.right, + used: self.used, + seen: self.seen, + card: self.card.take(), + air_at: self.air_at, + drawn_bottom: self.drawn_bottom, + empty: self.empty, + sections: std::mem::take(&mut self.sections), + info: None, + held: self.held, + sub_headers: self.sub_headers, + ui: &mut child, + }; + let result = body(&mut sheet); + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = + (named, seen, card, air_at, drawn_bottom, empty, sections); + (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + + let bottom = child.min_rect().bottom().max(top); + let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); + self.ui.advance_cursor_after_rect(Rect::from_min_max(pos2(child.min_rect().left(), top), pos2(child.min_rect().right(), bottom))); + if let (false, false, Some(reason)) = (enabled, already_greyed, reason) { + let response = self.ui.interact(region, self.id.with(("greyed", top as i32)), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, true, reason)); + + // At the pointer: the region is tall, so a tip at its edge would land far from what was hovered + let mut tooltip = egui::Tooltip::for_enabled(&response); + tooltip.popup = tooltip.popup.anchor(egui::PopupAnchor::Pointer); + tooltip.show(|ui| ui.label(reason)); + } + result + } + + /// A label on its own line above its control + fn label_line(&mut self, label: &str) -> Rect { + let line = self.take(LABEL_LINE); + let text = self.tokens.text; + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, label, FontId::proportional(TEXT_SIZE), text); + line + } + + /// A full-width control's box under its label, and the air after it + fn control_line(&mut self) -> Rect { + let line = self.take(CONTROL_HEIGHT); + self.drawn(line.bottom()); + let rect = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + self.space(STACK_ROW_AIR); + rect + } + + /// A dropdown under its label; returns the picked option + pub(crate) fn dropdown_above(&mut self, label: &str, current: T, options: &[T], name: impl Fn(T) -> String) -> Option { + self.label_line(label); + let button = self.control_line(); + let response = self.dropdown_button(button, &name(current), None::); + named_choice(self.ui, &response, label, &name(current)); + self.hanging_list(&response, current, options, &name, None::>).0 + } + + /// Two dropdowns under one label with a link between them; while `linked` the second follows the first and shows greyed. Returns which one picked what + pub(crate) fn dropdown_pair_above( + &mut self, + label: &str, + values: [T; 2], + options: &[T], + name: impl Fn(T) -> String, + linked: &mut bool, + link_label: &str, + ) -> Option<(usize, T)> { + self.label_line(label); + let line = self.control_line(); + let half = (line.width() - PAIR_LINK_WIDTH - 2.0 * PAIR_LINK_AIR) / 2.0; + let first = Rect::from_min_size(line.min, vec2(half, CONTROL_HEIGHT)); + let link = Rect::from_min_size(pos2(first.right() + PAIR_LINK_AIR, line.top()), vec2(PAIR_LINK_WIDTH, CONTROL_HEIGHT)); + let second = Rect::from_min_max(pos2(link.right() + PAIR_LINK_AIR, line.top()), line.max); + + let first_response = self.dropdown_button(first, &name(values[0]), None::); + named_choice(self.ui, &first_response, label, &name(values[0])); + let mut picked = self.hanging_list(&first_response, values[0], options, &name, None::>).0.map(|value| (0, value)); + + let link_id = self.next_id(); + let link_response = self.ui.interact(link, link_id, Sense::click()); + let enabled = self.ui.is_enabled(); + link_response.widget_info(|| WidgetInfo::selected(egui::Role::CheckBox, enabled, *linked, link_label)); + let link_response = self.tip(link_response, link_label); + if link_response.clicked() { + *linked = !*linked; + } + let tokens = self.tokens; + + // Held down: the hairline grey, neutral in every accent (tool_active takes the accent's tint) + let fill = if *linked { + tokens.separator + } else if link_response.hovered() { + tokens.row_hover + } else { + tokens.button + }; + let painter = self.ui.painter(); + painter.rect(link, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let glyph = if *linked { ic::LINK_SIMPLE_HORIZONTAL } else { ic::LINK_SIMPLE_HORIZONTAL_BREAK }; + painter.text(link.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&link_response); + + let follows = *linked; + let second_value = if follows { values[0] } else { values[1] }; + let mut second_ui = self.ui.new_child(UiBuilder::new().max_rect(second)); + if follows { + second_ui.disable(); + } + let mut second_sheet = PropertySheet { + tokens, + id: self.id, + scope: self.scope, + band_scope: self.band_scope, + named: Vec::new(), + left: second.left(), + right: second.right(), + used: self.used, + seen: self.seen, + card: None, + air_at: None, + drawn_bottom: self.drawn_bottom, + empty: false, + sections: Vec::new(), + info: None, + held: false, + sub_headers: 0, + ui: &mut second_ui, + }; + let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); + named_choice(second_sheet.ui, &second_response, label, &name(second_value)); + if let Some(value) = second_sheet.hanging_list(&second_response, second_value, options, &name, None::>).0 { + picked = Some((1, value)); + } + picked + } + + /// A slider under its label, its value at the label line's right end; `Some(merge)` when `value` changed, `merge` true for a drag's later steps + pub(crate) fn slider_above(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + let line = self.label_line(label); + let id = self.named_id("slider_above", label); + let shown = shown_number(*value, decimals); + + // Trim trailing zeros only on high-precision values + let shown = if decimals > SHORT_DECIMALS && shown.contains('.') { shown.trim_end_matches('0').trim_end_matches('.').to_owned() } else { shown }; + let width = self.text_width(&shown, semibold(TEXT_SIZE)).max(super::VALUE_MIN_WIDTH); + let value_text = ValueText { label: &label, right: self.right, width, center_y: line.top() + LABEL_CENTER, shown: &shown, suffix: "" }; + let typed = self.value_text_field(id, value_text, *value, &range, decimals); + + let track_line = self.take(TRACK_LINE); + let center_y = track_line.top() + TRACK_CENTER; + let track = Track { start: self.left + KNOB_RADIUS, end: self.right - KNOB_RADIUS, center_y, zero: (*range.start() < 0.0).then_some(0.0), ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + self.drawn(center_y + KNOB_RADIUS); + self.space(STACK_ROW_AIR); + Self::apply_typed(value, typed, dragged) + } + + /// A check with its label after it; returns whether it was clicked (`on` already flipped) + pub(crate) fn check(&mut self, label: &str, on: &mut bool) -> bool { + let clicked = self.check_mixed(label, Some(*on)).clicked(); + if clicked { + *on = !*on; + } + clicked + } + + /// A check that may show mixed (`None`, a dash) for several states at once; the caller flips what it stands for on a click + pub(crate) fn check_mixed(&mut self, label: &str, state: Option) -> Response { + self.check_noted(label, state, None) + } + + /// `check_mixed` with a dim `note` at the row's right end, such as the values a set would give up + pub(crate) fn check_noted(&mut self, label: &str, state: Option, note: Option<&str>) -> Response { + let line = self.take(CHECK_LINE); + let center_y = line.center().y; + let text = self.ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), self.tokens.text); + let hit = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.left + CHECK_SIZE + CHECK_TO_LABEL + text.size().x, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| match state { + Some(on) => WidgetInfo::selected(egui::Role::CheckBox, enabled, on, label), + None => WidgetInfo::labeled(egui::Role::CheckBox, enabled, label), + }); + + let check = Rect::from_min_size(pos2(self.left, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + paint_check(self.ui.painter(), &self.tokens, check, state, response.hovered()); + self.ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, self.tokens.text); + if let Some(note) = note { + self.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(note)); + self.ui.painter().text(pos2(self.right, center_y), Align2::RIGHT_CENTER, note, FontId::proportional(SMALL_TEXT_SIZE), self.tokens.text_dim); + } + self.paint_control_focus(&response); + self.drawn(line.bottom()); + self.space(STACK_ROW_AIR); + response + } + + /// A one-line text field under its label; returns whether `text` changed + pub(crate) fn text_field_above(&mut self, label: &str, text: &mut String) -> bool { + self.label_line(label); + let line = self.take(CONTROL_HEIGHT); + let field = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.named_id("text_field_above", label); + let typing = self.ui.memory(|memory| memory.has_focus(id)); + let tokens = self.tokens; + let outline = Stroke::new(1.0, if typing { tokens.accent } else { tokens.field_border }); + self.ui.painter().rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, outline, StrokeKind::Inside); + let edit = egui::TextEdit::singleline(text) + .id(id) + .font(FontId::proportional(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(FIELD_TEXT_INSET, 0))) + .align(Align2::LEFT_CENTER); + let response = self.ui.put(field.shrink(1.0), edit); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::TextInput, enabled, label)); + self.drawn(field.bottom()); + self.space(STACK_ROW_AIR); + response.changed() + } + + /// A full-width button with air above and twice below; `pressed` shows it held down (a toggle that is on) + pub(crate) fn wide_button(&mut self, glyph: &str, text: &str, pressed: bool) -> Response { + self.space(STACK_ROW_AIR); + let line = self.take(CONTROL_HEIGHT); + let button = Rect::from_min_max(pos2(self.left, line.top()), pos2(self.right, line.bottom())); + let id = self.next_id(); + let response = self.ui.interact(button, id, Sense::click()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::selected(egui::Role::Button, enabled, pressed, text)); + + let tokens = self.tokens; + + // Held down: the hairline grey, as the paired dropdowns' link + let fill = match (pressed, response.hovered()) { + (true, _) => tokens.separator, + (false, true) => tokens.row_hover, + (false, false) => tokens.button, + }; + let painter = self.ui.painter(); + painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + let icon = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(WIDE_BUTTON_ICON_SIZE), tokens.text); + let words = painter.layout_no_wrap(text.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text); + let x = button.center().x - (icon.size().x + WIDE_BUTTON_ICON_GAP + words.size().x) / 2.0; + let center_y = button.center().y; + painter.galley(pos2(x, center_y - icon.size().y / 2.0), icon.clone(), tokens.text); + painter.galley(pos2(x + icon.size().x + WIDE_BUTTON_ICON_GAP, center_y - words.size().y / 2.0), words, tokens.text); + self.paint_control_focus(&response); + self.drawn(button.bottom()); + self.space(2.0 * STACK_ROW_AIR); + response + } + + /// A dim line of its own, such as a map's "No Parameters" + pub(crate) fn dim_line(&mut self, text: &str) { + let line = self.take(LABEL_LINE); + let dim = self.tokens.text_dim; + let id = self.next_id(); + let response = self.ui.interact(line, id, Sense::hover()); + let enabled = self.ui.is_enabled(); + response.widget_info(|| WidgetInfo::labeled(egui::Role::Label, enabled, text)); + self.ui.painter().text(pos2(self.left, line.top() + LABEL_CENTER), Align2::LEFT_CENTER, text, FontId::proportional(TEXT_SIZE), dim); + self.drawn(line.bottom()); + } +} + +/// A check's box in `rect`: on = dim fill and a tick in the panel's colour, mixed (`None`) = a dash, off = the row colour with a field's border +pub(crate) fn paint_check(painter: &egui::Painter, tokens: &crate::theme::Tokens, rect: Rect, state: Option, hovered: bool) { + if state == Some(false) { + let border = if hovered { tokens.text } else { tokens.text_dim }; + painter.rect(rect, CornerRadius::same(CHECK_RADIUS), tokens.row, Stroke::new(1.0, border), StrokeKind::Inside); + return; + } + + let fill = if hovered { tokens.text } else { tokens.text_dim }; + painter.rect_filled(rect, CornerRadius::same(CHECK_RADIUS), fill); + if state.is_none() { + let y = rect.center().y; + painter.line_segment([pos2(rect.center().x - DASH_HALF, y), pos2(rect.center().x + DASH_HALF, y)], Stroke::new(DASH_WIDTH, tokens.panel)); + return; + } + + let points = TICK_POINTS.map(|(x, y)| pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height())); + painter.line(points.to_vec(), Stroke::new(TICK_WIDTH, tokens.panel)); +} + +/// Names a dropdown for assistive tech by its setting (`label`), its value the choice it shows +fn named_choice(ui: &egui::Ui, response: &Response, label: &str, value: &str) { + ui.ctx().accesskit_node_builder(response.id, |node| { + node.set_label(label); + node.set_value(value); + }); +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 5544b8fc..7b6f0442 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -74,7 +74,7 @@ fn result_window_shows(status: &Status, prompt_open: bool) -> bool { /// Whether an update may install and close the app: the project has no unsaved changes and no /// stroke, bake or resize is running. fn safe_to_close(app: &TextureCraftApp) -> bool { - !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() + !app.session.modified && !app.session.stroke_active() && app.bake.is_none() && app.resize.is_none() && app.high_poly_job.is_none() } pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { @@ -263,10 +263,14 @@ mod tests { assert!(!safe_to_close(h.state()), "unsaved changes"); h.state_mut().session.modified = false; - h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 }); + h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0, only: None }); assert!(!safe_to_close(h.state()), "a bake"); h.state_mut().bake = None; + h.state_mut().load_high_polys(["missing-high.obj".to_owned()]); + assert!(!safe_to_close(h.state()), "an accepted high-poly import is still pending"); + h.state_mut().high_poly_job = None; + h.state_mut().resize = Some(crate::ResizeJob { progress: Arc::new(Progress::new()), rx: channel().1 }); assert!(!safe_to_close(h.state()), "a resize"); h.state_mut().resize = None; @@ -275,6 +279,7 @@ mod tests { texturecraft_engine::execute(session, "layer.add.paint", &serde_json::Value::Null).unwrap(); session.modified = false; session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).unwrap(); + assert!(!safe_to_close(h.state()), "a stroke"); h.state_mut().session.cancel_stroke(); assert!(safe_to_close(h.state())); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 92c07e7e..bcddd78f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -65,7 +65,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; let bake_painting = mode == crate::state::Mode::Baking && app.ui.bake_paint_brush.on - && !app.session.bake_meshes.high.is_empty() + && !app.session.doc.bake_meshes.high.is_empty() && app.session.doc.project.texture_sets.get(app.session.ts()).is_some_and(|texture_set| { let settings = &texture_set.bake; match app.ui.bake_paint_brush.target { @@ -1135,7 +1135,9 @@ fn bake_visualization(app: &TextureCraftApp) -> Option, Pick)>) } } -/// Bake mode: add high-definition meshes (or load the cage) with the native file dialog. The -/// meshes load on a later frame, when the dialog answers. +/// Bake mode: add high polys (they load on a worker) or load the cage with the native file dialog, once it answers #[cfg(not(target_arch = "wasm32"))] pub fn import_bake_mesh(app: &mut TextureCraftApp, _ctx: &egui::Context, cage: bool) { use crate::file_dialogs::{Bound, FileDialog}; let dialog = if cage { FileDialog::open() } else { FileDialog::open_many() }; app.ask_file(dialog.filter(tr("Meshes"), &MESH_EXTENSIONS), Bound::Project, move |app, paths| { - for p in paths { - let cmd = if cage { "bake.cage.set" } else { "bake.highPoly.add" }; - app.run(cmd, serde_json::json!({ "path": p.display().to_string() })); + let mut paths = paths.iter().map(|path| path.display().to_string()); + if !cage { + app.load_high_polys(paths); + } else if let Some(path) = paths.next() { + app.run("bake.cage.set", serde_json::json!({ "path": path })); } }); } @@ -507,8 +508,8 @@ mod tests { vec![("high.obj".into(), cage.clone(), Pick::HighPoly(old_project_id)), ("cage.obj".into(), cage, Pick::Cage(old_project_id))], ); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); assert!(!harness.state().session.modified); assert_eq!(harness.state().toasts.iter().filter(|toast| toast.error).count(), 2); @@ -521,8 +522,8 @@ mod tests { vec![("high.obj".into(), mesh.clone(), Pick::HighPoly(project_id)), ("cage.obj".into(), mesh, Pick::Cage(project_id))], ); - assert_eq!(harness.state().session.bake_meshes.high.len(), 1); - assert!(harness.state().session.bake_meshes.cage.is_some()); + assert_eq!(harness.state().session.doc.bake_meshes.high.len(), 1); + assert!(harness.state().session.doc.bake_meshes.cage.is_some()); } #[test] diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 1703abde..02f3ac31 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -130,6 +130,7 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { queue: Vec::new(), total: 1, mesh_id, + only: None, current: Some(RunningBake { set_index: 0, progress: Arc::new(Progress::new()), @@ -175,12 +176,37 @@ fn an_invalid_set_does_not_start_a_partial_bake_or_change_the_view() { let revision = app.session.revision; let history_steps = app.session.history_labels().len(); - app.start_bake(vec![0, invalid_set]); + for only in [None, Some(MAPS[1])] { + if let Some(map) = only { + app.start_bake_of(vec![0, invalid_set], Some(map)); + } else { + app.start_bake(vec![0, invalid_set]); + } - assert!(app.bake.is_none(), "validate every set before queuing any work"); - assert!(!app.session.bake_preview_active()); - assert_eq!(app.session.view, view); - assert_eq!(app.session.revision, revision); - assert_eq!(app.session.history_labels().len(), history_steps); - assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); + assert!(app.bake.is_none(), "validate every set before queuing any work"); + assert!(!app.session.bake_preview_active()); + assert_eq!(app.session.view, view); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.history_labels().len(), history_steps); + assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); + } +} + +#[test] +fn a_rows_quick_bake_bakes_that_map_alone_and_keeps_the_others() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + run_to_the_end(&mut harness); + let before = harness.state().session.doc.baked[&0].maps.clone(); + + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([]); + harness.state_mut().start_bake_of(vec![0], Some(MAPS[1])); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[1]), "the preview shows the one map"); + run_to_the_end(&mut harness); + + let after = &harness.state().session.doc.baked[&0].maps; + assert_eq!(after.keys().collect::>(), before.keys().collect::>(), "the other maps stay"); + for map in MAPS { + assert_eq!(!std::sync::Arc::ptr_eq(&after[&map], &before[&map]), map == MAPS[1], "{map:?}"); + } } diff --git a/crates/ui-egui/tests/it/bake_job_mesh.rs b/crates/ui-egui/tests/it/bake_job_mesh.rs index 60f6f03e..49fe0501 100644 --- a/crates/ui-egui/tests/it/bake_job_mesh.rs +++ b/crates/ui-egui/tests/it/bake_job_mesh.rs @@ -9,35 +9,40 @@ use texturecraft_engine::bake::Progress; use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp}; /// An app with a running bake job (its worker never answers) started on mesh `mesh_id`. -fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc) { +fn with_running_job(mesh_id: impl FnOnce(u64) -> u64, check: impl FnOnce(&Harness<'static, TextureCraftApp>, &Progress)) { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.run_steps(4); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); let progress = Arc::new(Progress::new()); - let (tx, receiver) = std::sync::mpsc::channel(); - let (maps_tx, maps) = std::sync::mpsc::channel(); - let id = mesh_id(h.state().session.mesh_id); - // Leak the sender so the channel stays empty instead of closed. - std::mem::forget(tx); - std::mem::forget(maps_tx); + let (_result_sender, receiver) = std::sync::mpsc::channel(); + let (_map_sender, maps) = std::sync::mpsc::channel(); + let job_mesh_id = mesh_id(harness.state().session.mesh_id); let running = RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 }; - h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id }); - (h, progress) + harness.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: job_mesh_id, only: None }); + + harness.step(); + check(&harness, &progress); } #[test] fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() { - let (mut h, progress) = harness_with_job(|current| current + 1); - h.step(); - assert!(h.state().bake.is_none(), "the job is dropped"); - assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); + with_running_job( + |current| current + 1, + |harness, progress| { + assert!(harness.state().bake.is_none(), "the job is dropped"); + assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop"); + }, + ); } #[test] fn a_job_on_the_current_mesh_keeps_running() { - let (mut h, progress) = harness_with_job(|current| current); - h.step(); - assert!(h.state().bake.is_some(), "the job stays"); - assert!(!progress.cancel.load(Ordering::Relaxed)); + with_running_job( + |current| current, + |harness, progress| { + assert!(harness.state().bake.is_some(), "the job stays"); + assert!(!progress.cancel.load(Ordering::Relaxed)); + }, + ); } diff --git a/crates/ui-egui/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs new file mode 100644 index 00000000..bbf5d13e --- /dev/null +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -0,0 +1,178 @@ +//! The map preview: the selected map's settings show it on the model, small while a slider is dragged + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// How long a preview bake may take on a busy CI machine running every test at once +const PREVIEW_LIMIT: std::time::Duration = std::time::Duration::from_secs(60); + +/// How long the tests let the worker run between frames while they wait +const WAIT_STEP: std::time::Duration = std::time::Duration::from_millis(10); + +/// Bake mode on the sample with Ambient Occlusion's settings in front +fn harness() -> 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::R1024; + + // No earlier bake to start the preview from: its first picture is a preview bake at the chosen size + session.doc.baked.clear(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R256; + harness.run_steps(4); + harness.get(egui_kittest::kittest::by().role(Role::Button).label("Ambient Occlusion")).click(); + harness.state_mut().ui.dock.focus(Panel::MeshMapSettings); + harness.run_steps(3); + harness +} + +/// Run frames until `done` holds, letting the worker run between them; false when the preview limit passes first +fn run_until(harness: &mut Harness<'static, TextureCraftApp>, mut done: impl FnMut(&Harness<'static, TextureCraftApp>) -> bool) -> bool { + let started = std::time::Instant::now(); + while started.elapsed() < PREVIEW_LIMIT { + harness.run_steps(1); + if done(harness) { + return true; + } + + std::thread::sleep(WAIT_STEP); + } + false +} + +/// The size of the picture the preview shows for the first set +fn shown_size(harness: &Harness<'static, TextureCraftApp>) -> Option { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion).then_some(baked.resolution)) +} + +/// The size of the picture the preview shows for the first set, once it is `wanted` +fn wait_for_preview(harness: &mut Harness<'static, TextureCraftApp>, wanted: impl Fn(u32) -> bool) -> Option { + run_until(harness, |harness| shown_size(harness).is_some_and(&wanted)).then(|| shown_size(harness)).flatten() +} + +#[test] +fn the_selected_map_shows_on_the_model_and_common_settings_hide_it_at_once() { + let mut harness = harness(); + + let shown = wait_for_preview(&mut harness, |_| true); + assert!(shown.is_some(), "selecting a map's settings shows it"); + assert_eq!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); + + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(1); + + assert!(!harness.state().session.bake_preview_active(), "no lingering picture"); + assert_ne!(harness.state().session.view, texturecraft_engine::ViewMode::MeshMap(BakedMap::AmbientOcclusion)); +} + +#[test] +fn a_dragged_slider_previews_smaller_than_the_picture_it_settles_on() { + let mut harness = harness(); + let settled = wait_for_preview(&mut harness, |_| true).unwrap(); + let track = harness.get_by_role_and_label(Role::Slider, "Secondary Rays").rect(); + let (from, to) = (track.center(), track.left_center() + egui::vec2(track.width() * 0.1, 0.0)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.hover_at(to); + let dragged = wait_for_preview(&mut harness, |size| size < settled); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + let released = wait_for_preview(&mut harness, |size| size == settled); + + assert!(dragged.is_some(), "while dragging the preview bakes smaller"); + assert!(released.is_some(), "the release refines it to the chosen size"); +} + +#[test] +fn switching_the_preview_off_hides_it() { + let mut harness = harness(); + wait_for_preview(&mut harness, |_| true); + + harness.state_mut().ui.bake_visualization.map_preview = false; + harness.run_steps(1); + + assert!(!harness.state().session.bake_preview_active()); +} + +#[test] +fn pictures_keep_coming_while_the_slider_is_still_moving() { + let mut harness = harness(); + + // Many rays: each preview bake takes several frames, as on a real mesh + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.ao.parameters.rays.rays = 256; + wait_for_preview(&mut harness, |_| true); + let track = harness.get_by_role_and_label(Role::Slider, "Spread Angle").rect(); + let from = track.left_center() + egui::vec2(track.width() * 0.05, 0.0); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + + // Holding the last picture keeps a new one from reusing its address + let mut last = picture(&harness); + let mut pictures = 0; + let started = std::time::Instant::now(); + for step in 0.. { + if pictures > 2 || started.elapsed() > PREVIEW_LIMIT { + break; + } + + // Every frame moves the slider, as a steady drag does + harness.hover_at(from + egui::vec2(track.width() * 0.002 * (step % 200) as f32, 0.0)); + harness.run_steps(1); + let now = picture(&harness); + if now.as_ref().map(std::sync::Arc::as_ptr) != last.as_ref().map(std::sync::Arc::as_ptr) { + pictures += 1; + last = now; + } + } + + assert!(pictures > 2, "new pictures arrive while the slider never stops"); +} + +#[test] +fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() { + let mut harness = harness(); + let first = wait_for_preview(&mut harness, |_| true).unwrap(); + let picture = |harness: &Harness<'static, TextureCraftApp>| { + harness.state().session.bake_preview_baked(0).and_then(|baked| baked.maps.get(&BakedMap::AmbientOcclusion).cloned()) + }; + + harness.state_mut().ui.bake_visualization.map_preview_size = BakeResolution::R128; + let resized = wait_for_preview(&mut harness, |size| size < first); + assert!(resized.is_some(), "a smaller resolution bakes a smaller picture"); + + // A change that doesn't come from the panel: a script, an undo or a synced set + let before = picture(&harness); + harness.state_mut().run("bake.settings", serde_json::json!({ "ts": 0, "patch": { "maps": { "ao": { "parameters": { "rays": { "rays": 8 } } } } } })); + let changed = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); + assert!(changed, "the settings change brings a new picture"); + + // The same file loaded again: same name, new geometry + for (index, bytes) in [b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".as_slice(), b"v 0 0 0\nv 2 0 0\nv 0 2 0\nf 1 2 3\n".as_slice()].into_iter().enumerate() { + let session = &mut harness.state_mut().session; + if index > 0 { + session.remove_high_poly(0).unwrap(); + } + session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); + let before = picture(&harness); + let reloaded = run_until(&mut harness, |harness| is_new(picture(harness), before.as_ref())); + assert!(reloaded, "high poly load {index} brings a new picture"); + } +} + +/// True when the preview holds a picture other than `before`, which the caller keeps alive so its address can't be reused +fn is_new(now: Option>>, before: Option<&std::sync::Arc>>) -> bool { + now.is_some_and(|now| before.is_none_or(|before| !std::sync::Arc::ptr_eq(&now, before))) +} diff --git a/crates/ui-egui/tests/it/bake_map_rows.rs b/crates/ui-egui/tests/it/bake_map_rows.rs new file mode 100644 index 00000000..bdc67b93 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -0,0 +1,133 @@ +//! The Mesh Map Bakers rows: a primary drag down the checkboxes gives each the state the first one took + +use egui::{Event, Modifiers, PointerButton, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::core::BakedMap; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// The rows the drag crosses, from the press to the release +const DRAGGED: [(BakedMap, &str); 3] = [(BakedMap::Normal, "Normal"), (BakedMap::WorldNormal, "World Space Normal"), (BakedMap::Id, "ID")]; + +/// A bake-mode app with Mesh Map Bakers in front and every map checked +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select(BakedMap::ALL); + 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::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn checkbox_center(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::CheckBox, name).rect().center() +} + +fn enabled(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let maps = &harness.state().session.doc.project.texture_sets[0].bake.maps; + BakedMap::ALL.into_iter().filter(|map| maps.is_enabled(*map)).collect() +} + +#[test] +fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { + let mut harness = harness(); + let [from, through, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for position in [through, to] { + harness.hover_at(position); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "the three rows are unchecked, the release does not check the last one again"); +} + +#[test] +fn a_drag_that_jumps_past_a_row_between_two_frames_still_unchecks_it() { + let mut harness = harness(); + let [from, _, to] = DRAGGED.map(|(_, name)| checkbox_center(&harness, name)); + + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.hover_at(to); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|map| DRAGGED.iter().all(|(dragged, _)| dragged != map)).collect(); + assert_eq!(enabled(&harness), expected, "World Space Normal, between Normal and ID, is unchecked too"); +} + +#[test] +fn holding_the_secondary_button_on_a_checkbox_leaves_it_alone() { + let mut harness = harness(); + let at = checkbox_center(&harness, DRAGGED[1].1); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(3); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + assert_eq!(enabled(&harness), BakedMap::ALL); +} + +#[test] +fn a_click_on_one_checkbox_still_toggles_only_that_row() { + let mut harness = harness(); + let (map, name) = DRAGGED[1]; + let at = checkbox_center(&harness, name); + + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); + + let expected: Vec = BakedMap::ALL.into_iter().filter(|other| *other != map).collect(); + assert_eq!(enabled(&harness), expected); +} + +#[test] +fn keyboard_opens_an_unselected_maps_actions_without_selecting_it() { + let mut harness = harness(); + let row = "Height"; + harness.get_by_role_and_label(Role::Button, row).focus(); + harness.run_steps(2); + + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + + assert!(harness.query_by_label("Check Height for More Texture Sets...").is_some()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.get_by_role_and_label(Role::Button, row).is_focused()); + harness.key_press(egui::Key::Menu); + harness.run_steps(3); + harness.get_by_label("Check Height for More Texture Sets...").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert!(harness.get_by_role_and_label(Role::Button, "Close").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.get_by_role_and_label(Role::Button, row).is_focused()); + assert_eq!(harness.get_by_role_and_label(Role::Button, row).accesskit_node().toggled(), Some(egui::accesskit::Toggled::False)); +} diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index b2603842..cb0bd007 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -1,6 +1,6 @@ use egui::Role; use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; @@ -45,9 +45,14 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { harness.run_steps(3); } -fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let label_row = harness.get_by_label(label).rect().center().y; - harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap() +/// Type `text` as the value of the slider labelled `label`: a click on its value turns it into a field with the value selected +fn type_slider_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + harness.get_by_role_and_label(Role::Label, &format!("{label} value")).click(); + harness.run_steps(2); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.event(egui::Event::Text(text.into())); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); } #[test] @@ -99,8 +104,9 @@ fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { let mut expected = before.clone(); for texture_set in &mut expected.texture_sets { - texture_set.bake.common.apply_diffusion = false; + texture_set.bake.common.apply_diffusion = true; } + assert_eq!(harness.state().session.doc.project, expected); harness.get_all_by_value("64").next().unwrap().click(); @@ -109,12 +115,14 @@ fn common_settings_edits_update_all_sets_and_keep_their_map_selection() { for texture_set in &mut expected.texture_sets { texture_set.bake.common.resolution = BakeResolution::R256; } + assert_eq!(harness.state().session.doc.project, expected); click_checkbox(&mut harness, "Use Low Poly Mesh as High Poly Mesh"); for texture_set in &mut expected.texture_sets { texture_set.bake.high_poly.use_low_as_high = true; } + assert_eq!(harness.state().session.doc.project, expected); } @@ -129,20 +137,14 @@ fn secondary_rays_edit_from_another_set_updates_all_sets() { select_map(&mut harness, "Ambient Occlusion"); let history_steps = harness.state().session.history_labels().len(); - number_field(&harness, "Secondary Rays").focus(); - harness.run_steps(2); - harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); - harness.run_steps(1); - number_field(&harness, "Secondary Rays").type_text("128"); - harness.run_steps(1); - harness.key_press(egui::Key::Enter); - harness.run_steps(3); + type_slider_value(&mut harness, "Secondary Rays", "128"); let session = &harness.state().session; assert_eq!(session.ts(), 1); for texture_set in &session.doc.project.texture_sets { assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 128); } + assert_eq!(session.history_labels().len(), history_steps + 1); } @@ -333,15 +335,19 @@ fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() { harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); - harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click(); + harness.get_by_role_and_label(Role::Button, "Reset Common Settings").click(); harness.run_steps(3); let mut expected = before.clone(); expected.texture_sets[1].bake.common = Default::default(); expected.texture_sets[1].bake.common.is_enabled = false; + + // The section holds the High-Poly Parameters too, so its reset covers them + expected.texture_sets[1].bake.high_poly = Default::default(); let session = &mut harness.state_mut().session; assert_eq!(session.doc.project, expected); session.undo().unwrap(); + assert_eq!(session.doc.project, before); } @@ -385,18 +391,20 @@ fn height_controls_follow_manual_normalization_and_the_row_checkbox_enables_heig assert!(harness.query_by_label("Normalization").is_none()); select_map(&mut harness, "Height"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "selecting is not enabling"); - assert!(harness.query_by_label("Scaling Divisor").is_none()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click(&mut harness, "Normalization"); click(&mut harness, "Manual"); - harness.get_by_label("Scaling Divisor"); + + assert!(!harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::Manual); click_checkbox(&mut harness, "Height"); assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); click(&mut harness, "Restore Defaults"); + assert!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled, "Restore Defaults keeps the map enabled"); assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.maps.height.parameters.normalization, HeightNormalization::RelativeToLowMesh); - assert!(harness.query_by_label("Scaling Divisor").is_none()); + assert!(harness.get_by_label("Scaling Divisor").accesskit_node().is_disabled()); click_checkbox(&mut harness, "Height"); assert!(!harness.state().session.doc.project.texture_sets[0].bake.maps.height.is_enabled); } @@ -417,7 +425,9 @@ fn clicking_a_row_shows_that_maps_settings_without_changing_what_bakes() { assert!(harness.query_by_label("Attenuation").is_none()); assert_eq!(enabled_maps(&harness), before); - click(&mut harness, &format!("{} Common Settings", egui_phosphor::regular::GEAR)); + harness.get_by_role_and_label(Role::Button, "Common Settings").click(); + harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::CommonSettings)); assert_eq!(enabled_maps(&harness), before); } @@ -437,10 +447,9 @@ fn the_breadcrumb_switches_the_shown_map() { harness.get_by_label("Sampling Radius"); assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 1, "only the list row before the menu opens"); - let dropdowns: Vec<_> = harness.get_all_by_label(egui_phosphor::regular::CARET_RIGHT).collect(); - let [_texture_set_dropdown, map_dropdown] = dropdowns.as_slice() else { panic!("the breadcrumb has a texture set and a map dropdown") }; - map_dropdown.click(); + harness.get_by_label("Switch Mesh Map").click(); harness.run_steps(3); + assert_eq!(harness.get_all_by_role_and_label(Role::Button, "Position").count(), 2, "the map menu lists Position"); // The menu draws its items after the list rows @@ -452,30 +461,46 @@ fn the_breadcrumb_switches_the_shown_map() { } #[test] -fn curvature_controls_follow_the_method_and_notes_visibility_rules() { +fn a_long_texture_set_name_leaves_the_map_switcher_and_restore_defaults_in_the_breadcrumb() { + let mut harness = harness(Some(BakedMap::Curvature)); + harness.state_mut().session.doc.project.texture_sets[0].name = "W".repeat(200); + harness.run_steps(3); + + let switcher = harness.get_by_label("Switch Mesh Map").rect(); + let restore = harness.get_by_role_and_label(Role::Button, "Restore Defaults").rect(); + assert!(switcher.right() <= restore.left(), "the map switcher stays left of Restore Defaults"); +} + +#[test] +fn curvature_controls_follow_the_method_and_grey_out_by_their_switches() { let mut harness = harness(Some(BakedMap::Curvature)); let curvature = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].bake.maps.curvature.parameters; assert_eq!(curvature(&harness).method, CurvatureMethod::Mesh); assert!(harness.query_by_label("Details").is_none()); harness.get_by_label("Sampling Radius"); - assert!(harness.query_by_label("Value Bounds Min").is_none()); - assert!(harness.query_by_label("Value Bounds Max").is_none()); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(harness.get_by_label(bound).accesskit_node().is_disabled(), "{bound} is greyed while tonemapping is automatic"); + } + + click(&mut harness, "Auto Tonemapping (per UV Tile)"); + for bound in ["Value Bounds Min", "Value Bounds Max"] { + assert!(!harness.get_by_label(bound).accesskit_node().is_disabled()); + } - click(&mut harness, "Auto Tonemapping"); - harness.get_by_label("Value Bounds Min"); - harness.get_by_label("Value Bounds Max"); assert!(!curvature(&harness).mesh.auto_tonemapping); click(&mut harness, "Method"); click(&mut harness, "Generate from Normal Map"); + assert_eq!(curvature(&harness).method, CurvatureMethod::NormalMap); assert!(harness.query_by_label("Sampling Radius").is_none()); harness.get_by_label("Details"); - harness.get_by_label("Seams Intensity"); + assert!(!harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); click(&mut harness, "Enable Seams"); - assert!(harness.query_by_label("Seams Intensity").is_none()); + + assert!(harness.get_by_label("Seams Intensity").accesskit_node().is_disabled()); } #[test] @@ -490,42 +515,67 @@ fn cage_and_skew_controls_require_a_high_poly_and_grey_out_with_a_reason() { } harness.get_by_label("The cage applies once a high poly mesh is loaded."); harness.get_by_label("Skew Correction applies once a high poly mesh is loaded."); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "nothing selected to remove"); 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); + assert!(!harness.get_by_label("Max Frontal Distance").accesskit_node().is_disabled()); assert!(harness.query_by_label("The cage applies once a high poly mesh is loaded.").is_none()); - harness.get_by_label("Skew Correction"); + harness.get_by_role_and_label(Role::Button, "Reset Skew Correction"); harness.state_mut().session.doc.project.texture_sets[0].bake.cage.average_normals = false; harness.run_steps(3); + assert!(harness.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); harness.get_by_label("Skew Correction needs Average Normals turned on in the cage settings."); harness.state_mut().session.doc.project.texture_sets[0].bake.high_poly.use_low_as_high = true; harness.run_steps(3); harness.get_by_label("Skew Correction is not available while the low poly mesh is used as the high poly mesh."); harness.get_by_label("The cage is not used while the low poly mesh is used as the high poly mesh."); - assert!(harness.get_by_label("Paint Cage").accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); + assert!(harness.get(by().label_contains("Paint Cage")).accesskit_node().is_disabled(), "the low poly as its own high poly has no cage to paint"); let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; (settings.cage.average_normals, settings.high_poly.use_low_as_high) = (true, false); harness.run_steps(3); + assert!(!harness.get_by_label("Edge Protection").accesskit_node().is_disabled()); + click(&mut harness, "Cage Type"); + click(&mut harness, "Automatic (Experimental)"); + + assert_eq!(harness.state().session.doc.project.texture_sets[0].bake.cage.kind, CageType::Automatic); + for distance_based_only in ["Max Frontal Distance", "Average Normals"] { + assert!(harness.query_by_label(distance_based_only).is_none(), "the automatic cage has no {distance_based_only}"); + } + + assert!(harness.query(by().label_contains("Paint Cage")).is_none(), "the automatic cage is not painted"); + assert!( + harness.get_by_role_and_label(Role::CheckBox, "Matching Error").accesskit_node().is_disabled(), + "greyed with the automatic cage, as in the reference" + ); + harness.get_by_label("Skew Correction needs a distance-based cage: the automatic cage is fitted to the high poly as it is."); + 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.get_by_label("Edge Protection").accesskit_node().is_disabled(), "the section shows greyed"); harness.get_by_label("Skew Correction needs a distance-based cage: a custom cage file sets the ray directions itself."); + harness.get_by_label("Load Cage"); +} - for button_size in [20.0, 28.0] { - harness.ctx.all_styles_mut(|style| style.spacing.interact_size = egui::Vec2::splat(button_size)); - harness.run_steps(3); - for label in ["Remove", "Load Cage"] { - assert_eq!(harness.get_by_label(label).rect().size(), egui::Vec2::splat(button_size)); - } +#[test] +fn output_sizes_run_from_32_to_8192_as_in_the_reference() { + let mut harness = harness(None); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_all_by_value("64").next().unwrap().click(); + harness.run_steps(3); + for offered in ["32", "8192"] { + harness.get_by_label(offered); } + + assert!(harness.query_by_label("16").is_none()); } #[test] @@ -535,7 +585,8 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { let session = &mut harness.state_mut().session; 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 mesh = session.mesh.clone(); - session.bake_meshes.cage = Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), bytes: Default::default(), mesh, base_color: Vec::new() }); + session.doc.bake_meshes.cage = + Some(texturecraft_engine::BakeMesh { name: "Cage.obj".into(), folder: None, bytes: Default::default(), mesh, base_color: Vec::new() }); let settings = &mut session.doc.project.texture_sets[0].bake; (settings.cage.kind, settings.high_poly.use_low_as_high) = (CageType::CustomFile, true); harness.run_steps(3); @@ -543,18 +594,26 @@ fn a_loaded_cage_can_be_removed_while_the_cage_does_not_apply() { assert!(harness.get_by_label("Load Cage").accesskit_node().is_disabled(), "the cage does not apply"); assert!(!harness.get_by_label("Remove Cage").accesskit_node().is_disabled()); click(&mut harness, "Remove Cage"); - assert!(harness.state().session.bake_meshes.cage.is_none()); + + assert!(harness.state().session.doc.bake_meshes.cage.is_none()); } #[test] fn the_view_menu_picks_the_neutral_or_the_painted_material_in_bake_mode() { let mut harness = harness(None); + + // Mesh Map Settings in front would show its map's preview instead of the material + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(2); + assert!(harness.state().ui.bake_visualization.neutral_shown, "bake mode starts on the neutral material"); harness.get_by_value("Neutral Material").click(); harness.run_steps(3); + assert!(harness.query_by_label("UV checker").is_none(), "bake mode lists lighting and mesh maps only"); harness.get_by_label("Material").click(); harness.run_steps(3); + assert!(!harness.state().ui.bake_visualization.neutral_shown); harness.get_by_value("Material"); } @@ -582,14 +641,14 @@ fn the_high_poly_scene_is_a_list_with_add_and_remove() { harness.state_mut().ui.dock.focus(Panel::CommonSettings); harness.run_steps(3); harness.get_by_label("Add High-Poly Meshes"); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled(), "− waits for a selection"); + harness.get_by_label("Gunhigh.obj"); - harness.get_by_label("Gunhigh.obj").click(); - harness.run_steps(3); + // Each file's row has its own × harness.get_by_label("Remove").click(); harness.run_steps(3); - assert!(harness.state().session.bake_meshes.high.is_empty()); - assert!(harness.get_by_label("Remove").accesskit_node().is_disabled()); + + assert!(harness.state().session.doc.bake_meshes.high.is_empty()); + assert!(harness.query_by_label("Remove").is_none()); } #[test] diff --git a/crates/ui-egui/tests/it/bake_presets.rs b/crates/ui-egui/tests/it/bake_presets.rs index 5adef4ea..705c2347 100644 --- a/crates/ui-egui/tests/it/bake_presets.rs +++ b/crates/ui-egui/tests/it/bake_presets.rs @@ -56,6 +56,9 @@ fn a_saved_preset_loads_back_into_the_active_set_as_one_undo_step() { assert!(harness.state().ui.bake_preset_name.is_empty(), "the name field is cleared"); harness.state_mut().session.doc.project.texture_sets[0].bake.common.antialiasing = BakeAntialiasing::None; + + // Linked sets receive the preset's common settings + harness.state_mut().run("bake.sync", json!({ "group": "common", "ts": [0] })); let steps = harness.state().session.history_labels().len(); open_menu(&mut harness); click(&mut harness, "Final"); @@ -64,6 +67,7 @@ fn a_saved_preset_loads_back_into_the_active_set_as_one_undo_step() { assert_eq!(antialiasing(&harness, 1), BakeAntialiasing::None, "only the active set loads it"); assert_eq!(harness.state().session.history_labels().len(), steps + 1); harness.state_mut().session.undo().unwrap(); + assert_eq!(antialiasing(&harness, 0), BakeAntialiasing::None); } diff --git a/crates/ui-egui/tests/it/bake_reset_menus.rs b/crates/ui-egui/tests/it/bake_reset_menus.rs new file mode 100644 index 00000000..4c5c579c --- /dev/null +++ b/crates/ui-egui/tests/it/bake_reset_menus.rs @@ -0,0 +1,84 @@ +//! The Cage and Skew Correction ⟲ menus: reset the parameters, clear the paint strokes, or both + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{BakePaintTarget, BakeSettings}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// Bake mode with a high poly, Common Settings in front, a painted stroke on `target` and its section's settings changed +fn harness(target: BakePaintTarget) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.add_high_poly_bytes("High.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec()).unwrap(); + 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::CommonSettings); + + let command = match target { + BakePaintTarget::Cage => "bake.cage.paint", + BakePaintTarget::Skew => "bake.skew.paint", + }; + harness.state_mut().run(command, json!({ "points": [[0.5, 0.5]] })); + let settings = &mut harness.state_mut().session.doc.project.texture_sets[0].bake; + (settings.cage.max_frontal, settings.skew.edge_distance) = (CHANGED_CAGE_DISTANCE, CHANGED_EDGE_DISTANCE); + harness.run_steps(3); + harness +} + +/// Values other than the defaults (0.01 and 0.15), inside their sliders' ranges +const CHANGED_CAGE_DISTANCE: f32 = 0.03; +const CHANGED_EDGE_DISTANCE: f32 = 0.5; + +/// Open `section`'s ⟲ menu and pick `item` +fn pick(harness: &mut Harness<'static, TextureCraftApp>, section: &str, item: &str) { + // The Baking Visualization panel has its own Cage section in the 3D view, right of Common Settings + let label = format!("Reset {section}"); + let buttons = harness.get_all_by_role_and_label(Role::Button, &label); + buttons.min_by(|first, second| first.rect().left().total_cmp(&second.rect().left())).unwrap().click(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); +} + +/// Whether the first set still has its `target` strokes, and whether its section's parameters are the defaults +fn state(harness: &Harness<'static, TextureCraftApp>, target: BakePaintTarget) -> (bool, bool) { + let session = &harness.state().session; + let settings = &session.doc.project.texture_sets[0].bake; + let defaults = BakeSettings::default(); + let painted = session.doc.bake_paint.contains_key(&(0, target)); + let reset = match target { + BakePaintTarget::Cage => settings.cage == defaults.cage, + BakePaintTarget::Skew => settings.skew == defaults.skew, + }; + (painted, reset) +} + +#[test] +fn each_cage_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Cage Parameters", (true, true)), ("Clear All Cage Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Cage); + assert_eq!(state(&harness, BakePaintTarget::Cage), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Cage", item); + + assert_eq!(state(&harness, BakePaintTarget::Cage), expected, "{item}: (strokes kept, parameters reset)"); + } +} + +#[test] +fn each_skew_reset_item_resets_the_parameters_clears_the_strokes_or_both() { + let items = [("Reset Skew Correction Parameters", (true, true)), ("Clear All Skew Paint Strokes", (false, false)), ("Reset and Clear All", (false, true))]; + for (item, expected) in items { + let mut harness = harness(BakePaintTarget::Skew); + assert_eq!(state(&harness, BakePaintTarget::Skew), (true, false), "painted, parameters changed"); + + pick(&mut harness, "Skew Correction", item); + + assert_eq!(state(&harness, BakePaintTarget::Skew), expected, "{item}: (strokes kept, parameters reset)"); + } +} diff --git a/crates/ui-egui/tests/it/bake_sync.rs b/crates/ui-egui/tests/it/bake_sync.rs new file mode 100644 index 00000000..7c497cc6 --- /dev/null +++ b/crates/ui-egui/tests/it/bake_sync.rs @@ -0,0 +1,158 @@ +//! Sharing bake settings between texture sets from the Mesh Map Bakers panel + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::{BakeResolution, BakeSyncGroup, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A bake-mode app on the two-set sample with Mesh Map Bakers in front +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for set in &mut session.doc.project.texture_sets { + set.bake = Default::default(); + set.bake.common.resolution = BakeResolution::R64; + } + 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::MeshMapBakers); + harness.run_steps(3); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).click(); + harness.run_steps(3); +} + +fn second_name(harness: &Harness<'_, TextureCraftApp>) -> String { + harness.state().session.doc.project.texture_sets[1].name.clone() +} + +#[test] +fn the_common_settings_sync_dialog_takes_a_set_out_of_the_group() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + harness.get_by_label("Common Settings Sync"); + harness.get_by_role_and_label(Role::CheckBox, "Deselect All"); + + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Select All"); + click(&mut harness, "OK"); + + let project = &harness.state().session.doc.project; + assert!(harness.query_by_label("Common Settings Sync").is_none()); + assert!(!project.texture_sets[1].bake.sync.common); + assert_eq!(project.bake_synced_sets(0, BakeSyncGroup::Common), [0]); + assert_eq!(project.bake_synced_sets(1, BakeSyncGroup::Map(BakedMap::Normal)), [0, 1], "map sync stays"); +} + +#[test] +fn cancel_leaves_the_group_as_it_was() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "Cancel"); + + assert!(harness.state().session.doc.project.texture_sets[1].bake.sync.common); +} + +#[test] +fn common_settings_edits_reach_only_the_sets_sharing_them() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[1].bake.sync.common = false; + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness.get_by_role_and_label(Role::CheckBox, "Apply Diffusion").click(); + harness.run_steps(3); + + let sets = &harness.state().session.doc.project.texture_sets; + assert_ne!(sets[0].bake.common.apply_diffusion, sets[1].bake.common.apply_diffusion); +} + +#[test] +fn the_list_menu_applies_the_checked_maps_to_all_sets() { + let mut harness = harness(); + harness.state_mut().session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal, BakedMap::Height]); + harness.run_steps(3); + click(&mut harness, "Mesh Map Bakers Menu"); + click(&mut harness, "Apply Checked to All Texture Sets"); + let enabled: Vec = harness.state().session.doc.project.texture_sets[1].bake.maps.enabled().collect(); + assert_eq!(enabled, [BakedMap::Normal, BakedMap::Height]); +} + +#[test] +fn a_rows_menu_checks_the_map_for_sets_picked_in_the_dialog() { + let mut harness = harness(); + for set in &mut harness.state_mut().session.doc.project.texture_sets { + set.bake.maps.select([]); + } + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Height").click_secondary(); + harness.run_steps(3); + click(&mut harness, "Check Height for More Texture Sets..."); + harness.get_by_label("Check Height for More Texture Sets"); + + let first = harness.state().session.doc.project.texture_sets[0].name.clone(); + assert!(harness.query_by_role_and_label(Role::CheckBox, &first).is_none(), "the active set is the source, not a target"); + let second = second_name(&harness); + harness.get_by_role_and_label(Role::CheckBox, &second).click(); + harness.run_steps(3); + click(&mut harness, "OK"); + + let sets = &harness.state().session.doc.project.texture_sets; + assert!(!sets[0].bake.maps.height.is_enabled && sets[1].bake.maps.height.is_enabled); +} + +#[test] +fn replacing_the_project_discards_the_open_sync_picker() { + let mut harness = harness(); + click(&mut harness, "Synchronize Common Settings"); + harness.get_by_label("Common Settings Sync"); + + harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); + harness.run_steps(3); + + assert!(harness.query_by_label("Common Settings Sync").is_none()); +} + +#[test] +fn keyboard_opens_the_sync_picker_and_returns_to_its_button() { + let mut harness = harness(); + let opener = "Synchronize Common Settings"; + harness.get_by_role_and_label(Role::Button, opener).focus(); + harness.run_steps(2); + + let node = harness.get_by_role_and_label(Role::Button, opener); + assert!(node.is_focused()); + let center = node.rect().center(); + assert!( + harness + .output() + .shapes + .iter() + .any(|clipped| { matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.stroke.width > 1.0 && shape.rect.center().distance(center) < 1.0) }), + "the focused sync control has a visible outline" + ); + + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert!(harness.get_by_role_and_label(Role::Button, "Close").is_focused()); + harness.key_press(egui::Key::Tab); + harness.run_steps(2); + + assert!(!harness.get_by_role_and_label(Role::Button, "Close").is_focused()); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.query_by_label("Common Settings Sync").is_none()); + assert!(harness.get_by_role_and_label(Role::Button, opener).is_focused()); +} diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs new file mode 100644 index 00000000..c8d3c246 --- /dev/null +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -0,0 +1,132 @@ +//! Bake mode: high poly files load on a worker thread, and the list names them while they do + +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +/// A triangle the importer accepts as a high poly +const TRIANGLE_OBJ: &str = "o Part_high\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; +/// Longest the test waits for the worker +const LOAD_TIMEOUT: Duration = Duration::from_secs(60); +/// Frames (5 ms apart) a stroke stays open while a high poly loads +const STROKE_FRAMES: usize = 200; + +/// A bake-mode app with Common Settings in front +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(4); + harness.state_mut().ui.dock.focus(Panel::CommonSettings); + harness.run_steps(3); + harness +} + +fn high_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.bake_meshes.high.iter().map(|high| high.name.clone()).collect() +} + +fn run_until_loaded(harness: &mut Harness<'_, TextureCraftApp>) { + let started = Instant::now(); + while harness.state().high_poly_job.is_some() { + assert!(started.elapsed() < LOAD_TIMEOUT, "the high polys never finished loading"); + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } +} + +#[test] +fn picked_high_polys_load_in_the_background_and_each_is_an_undo_step() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-loading-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let paths: Vec = ["first.obj", "second.obj"].map(|name| folder.join(name).display().to_string()).into(); + for path in &paths { + std::fs::write(path, TRIANGLE_OBJ).unwrap(); + } + let missing = folder.join("missing.obj").display().to_string(); + + let mut harness = harness(); + let steps = harness.state().session.history_labels().len(); + harness.state_mut().load_high_polys([paths[0].clone(), missing, paths[1].clone()]); + assert!(high_names(&harness).is_empty(), "the call returns before a file is read"); + assert_eq!(harness.state().high_poly_job.as_ref().unwrap().file_names().collect::>(), ["first.obj", "missing.obj", "second.obj"]); + harness.run_steps(1); + harness.get_by_label("Loading second.obj..."); + + run_until_loaded(&mut harness); + harness.run_steps(2); + + assert_eq!(high_names(&harness), ["first.obj", "second.obj"], "the unreadable file is skipped and the rest load in order"); + assert_eq!(harness.state().session.history_labels().len(), steps + 2); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("missing.obj")), "the unreadable file is reported"); + assert!(harness.query_by_label("Loading second.obj...").is_none()); + assert_eq!(harness.state().session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2); + + harness.state_mut().run("edit.undo", serde_json::Value::Null); + + assert_eq!(high_names(&harness), ["first.obj"]); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn high_polys_still_loading_when_another_project_opens_are_not_added_to_it() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-moved-on-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + harness.state_mut().load_high_polys([path.clone(), path]); + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + run_until_loaded(&mut harness); + + assert!(high_names(&harness).is_empty()); + assert!(harness.state().toasts.iter().any(|toast| toast.text.contains("not added"))); + let _ = std::fs::remove_dir_all(folder); +} + +#[test] +fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let file = |name: &str| texturecraft_engine::formats::MeshFile { name: name.into(), bytes: TRIANGLE_OBJ.as_bytes().to_vec(), warnings: Vec::new() }; + let load = texturecraft_engine::HighPolyLoad::prepare(&session.doc.bake_meshes, file("part.obj")).unwrap(); + + session.add_high_poly_bytes("part.obj", TRIANGLE_OBJ.as_bytes().to_vec()).unwrap(); + + assert_eq!(session.apply_high_poly_load(load), "2_part.obj", "the name is made unique against the list of now"); + assert_eq!(session.doc.bake_meshes.merged_high().unwrap().mesh.triangle_count(), 2, "both meshes bake"); +} + +#[test] +fn a_high_poly_read_during_a_paint_stroke_is_added_after_it_and_survives_its_cancel() { + let folder = std::env::temp_dir().join(format!("texturecraft-high-poly-stroke-{}", std::process::id())); + std::fs::create_dir_all(&folder).unwrap(); + let path = folder.join("part.obj").display().to_string(); + std::fs::write(&path, TRIANGLE_OBJ).unwrap(); + + let mut harness = harness(); + + // Bake mode finishes strokes at once: the files go on loading after a switch back to painting + harness.state_mut().ui.mode = Mode::Painting; + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::json!({})).unwrap(); + harness.state_mut().session.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::splat(0.5), 1.0).unwrap(); + harness.state_mut().load_high_polys([path]); + + // Time for the worker to read one triangle + for _ in 0..STROKE_FRAMES { + std::thread::sleep(Duration::from_millis(5)); + harness.run_steps(1); + } + + assert!(harness.state().session.stroke_active()); + assert!(high_names(&harness).is_empty(), "nothing is added while the stroke runs"); + + harness.state_mut().session.cancel_stroke(); + run_until_loaded(&mut harness); + assert_eq!(high_names(&harness), ["part.obj"]); + let _ = std::fs::remove_dir_all(folder); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 191ceaee..28e18ae3 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -4,8 +4,12 @@ mod alpha_parameters; mod anchor_point; mod bake_job_mesh; +mod bake_live_preview; +mod bake_map_rows; mod bake_mode; mod bake_presets; +mod bake_reset_menus; +mod bake_sync; mod brush_drag; mod brush_section_reset; mod camera_views; @@ -42,6 +46,7 @@ mod frame_selection; mod generator_panel; mod generator_picker; mod help_menu_664; +mod high_poly_loading; mod history_panel; mod import_resources; mod inactive_set_hint; diff --git a/crates/ui-egui/tests/it/skew_paint.rs b/crates/ui-egui/tests/it/skew_paint.rs index dd3b5d02..a6ce38d6 100644 --- a/crates/ui-egui/tests/it/skew_paint.rs +++ b/crates/ui-egui/tests/it/skew_paint.rs @@ -2,7 +2,7 @@ //! brush controls are in Common Settings. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{Mode, ViewLayout}; @@ -26,7 +26,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { #[test] fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { let mut h = harness(); - h.get_by_label("Skew Correction"); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction"); assert!(h.state().session.doc.bake_paint.is_empty() && !h.state().ui.bake_paint_brush.on); // Off: a drag in the view paints nothing @@ -34,13 +34,15 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_map() { h.hover_at(STROKE_END); h.drop_at(STROKE_END); h.run_steps(3); + 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.get(by().label_contains("Paint Skew Correction")).scroll_to_me(); h.run_steps(3); - h.get_by_label("Paint Skew Correction").click(); + h.get(by().label_contains("Paint Skew Correction")).click(); h.run_steps(3); + assert!(h.state().ui.bake_paint_brush.on); h.get_by_label("Radius"); h.drag_at(STROKE_START); @@ -53,11 +55,12 @@ fn the_bake_panel_has_the_bake_paint_brush_and_dragging_paints_the_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()); - // Removing it from the panel clears the map - h.get_by_label("Remove Skew Correction").scroll_to_me(); + // The section's reset menu clears the map + h.get_by_role_and_label(egui::accesskit::Role::Button, "Reset Skew Correction").click(); h.run_steps(3); - h.get_by_label("Remove Skew Correction").click(); + h.get_by_role_and_label(egui::accesskit::Role::Button, "Clear All Skew Paint Strokes").click(); h.run_steps(3); + assert!(h.state().session.doc.bake_paint.is_empty()); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 52ec1457..d9f3e53e 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -30,6 +30,7 @@ fn lowest_list<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { harness.run_steps(6); + // Material orbs render off the UI thread: wait for their full pictures let start = std::time::Instant::now(); while !texturecraft_ui_egui::orb_previews::OrbPreviews::settled(&harness.ctx) && start.elapsed() < std::time::Duration::from_secs(20) { @@ -40,16 +41,18 @@ fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { let img = harness.render().unwrap_or_else(|e| panic!("{name}: {e}")); let path = dir.join(format!("{name}.png")); img.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let tree = [egui::Role::Button, egui::Role::SpinButton, egui::Role::CheckBox] + + let control_roles = [egui::Role::Button, egui::Role::CheckBox, egui::Role::ComboBox, egui::Role::Slider, egui::Role::SpinButton, egui::Role::TextInput]; + let control_tree = control_roles .into_iter() - .flat_map(|role| harness.get_all_by_role(role)) - .filter_map(|button| { - let node = button.accesskit_node(); - node.label().map(|label| format!("{label}: disabled={}, checked={:?}", node.is_disabled(), node.toggled())) + .flat_map(|role| harness.query_all_by_role(role).map(move |control| (role, control))) + .filter_map(|(role, control)| { + let node = control.accesskit_node(); + node.label().map(|label| format!("{role:?} {label}: disabled={}, checked={:?}", node.is_disabled(), node.toggled())) }) .collect::>() .join("\n"); - std::fs::write(dir.join(format!("{name}.txt")), tree).unwrap(); + std::fs::write(dir.join(format!("{name}.txt")), control_tree).unwrap(); eprintln!("wrote {}", path.display()); } @@ -424,7 +427,11 @@ fn window_snapshots() { 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(); + let output_width = harness + .get_all_by_role_and_label(egui::Role::ComboBox, "Output Size") + .find(|choice| !choice.accesskit_node().is_disabled()) + .expect("the linked output size has an enabled width control"); + output_width.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); @@ -441,7 +448,7 @@ fn window_snapshots() { save(&mut harness, &output_dir, "bake-curvature-mesh"); select_map(&mut harness, "Height"); save(&mut harness, &output_dir, "bake-height-manual"); - harness.state_mut().session.bake_meshes.high.clear(); + harness.state_mut().session.doc.bake_meshes.high.clear(); harness.state_mut().ui.mode = Mode::Painting; save(&mut harness, &output_dir, "painting-restored"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..08d25499 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -135,9 +135,20 @@ alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). The procedural, library and imported alphas alike and are returned by `tool.brush` with the other values. The alpha's rotation is the brush `angle`. -Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each -set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the -changed fields; Restore Defaults resets the whole parameter section across all sets. +Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that +group's settings: Common Settings, and each map's settings, are shared by any set of texture sets +(at first every set shares them). Each set keeps its own enabled mesh-map checkboxes and Include in +Bake flag. An edit reaches the sets sharing its group with only the fields it changed, so values +that differ elsewhere stay; Restore Defaults resets the whole parameter section across those sets. + +`bake.sync {group: "common" | , ts: [indices] | "all"}` makes exactly these sets share the +group from now on; sets joining take the settings the group shares. `bake.copy {what: "settings" | +"checked" | "check", map?, from?, ts}` copies once: every setting with which maps are checked (or +one map's settings), which maps are checked, or checks one map; settings also reach the sets sharing a group with a target, while +checkboxes stay per set. Each is one undo step. `bake.settings` with `model` keeps each set's sync +membership. A `patch` containing `sync` is rejected. Use `bake.sync` to change membership. +For `bake.copy`, `from` takes a texture set index and `map` takes a mesh map ID. Omit either field +or pass `null` to use its default. `bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum @@ -145,7 +156,8 @@ values returned in the command's `model` result; omitted fields retain each set' `null` clears optional fields such as `common.resolution_height`. All targeted sets are validated before the edit is applied as one undo step. `model` still replaces the complete settings; when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts` -still targets the active set for scripts that need individual control. +still targets the active set. Settings passed to `bake.run` follow the same sync rules, while only +the requested texture sets bake. The settings and baked maps share one undo step. Bake presets are saved settings in the UI state (Mesh Map Bakers > Presets). Loading one is `bake.settings {ts: , model: , preserveEnabled: true, preset: true}`; Apply to All