diff --git a/crates/bake/src/cage/fitted_cage.rs b/crates/bake/src/cage/fitted_cage.rs index 088dae2f..54bbde47 100644 --- a/crates/bake/src/cage/fitted_cage.rs +++ b/crates/bake/src/cage/fitted_cage.rs @@ -2,7 +2,7 @@ use super::name_keys::NameKeys; use crate::map::interpolate; use crate::{BakeRequest, HighPoly, MeshExtent}; use rayon::prelude::*; -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; use texturecraft_geom::Mesh; use texturecraft_geom::glam::Vec3; @@ -26,6 +26,7 @@ impl FittedCage { 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 mut reach: Vec> = vec![None; welded_count]; @@ -71,6 +72,23 @@ impl FittedCage { } } +/// `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(welded_indices: &[u32], vertex_keys: &[u32]) -> Vec { + if vertex_keys.is_empty() { + return welded_indices.to_vec(); + } + + 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() +} + /// 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 @@ -153,7 +171,15 @@ fn spread_to_neighbours(reach: &mut [Option<(f32, f32)>], triangles: impl Iterat #[cfg(test)] mod tests { - use super::spread_to_neighbours; + use super::{spread_to_neighbours, welded_within_groups}; + + #[test] + fn coincident_vertices_of_different_name_groups_are_not_welded() { + // Vertices 0 and 1 share a position, as do 2 and 3; 1 and 2 are in group 7, the others in group 5 + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 7, 7, 5]), [0, 1, 2, 3]); + assert_eq!(welded_within_groups(&[0, 0, 1, 1], &[5, 5, 7, 7]), [0, 0, 1, 1], "same group: still welded"); + assert_eq!(welded_within_groups(&[0, 0, 1], &[]), [0, 0, 1], "without name matching nothing changes"); + } #[test] fn unfitted_vertices_take_the_largest_distances_of_their_nearest_fitted_neighbours() { diff --git a/crates/bake/src/test/fitted_cage.rs b/crates/bake/src/test/fitted_cage.rs index 3aa96e6b..903c5c99 100644 --- a/crates/bake/src/test/fitted_cage.rs +++ b/crates/bake/src/test/fitted_cage.rs @@ -148,3 +148,39 @@ fn a_part_no_high_poly_part_matches_keeps_the_distance_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] { + mesh.materials.truncate(1); + for submesh in &mut mesh.submeshes { + submesh.material = 0; + } + } + let mut bake_settings = automatic(&[BakedMap::Normal]); + bake_settings.high_poly.match_mode = texturecraft_core::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}"); + } +} diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 6bcf92e4..b8e66cd4 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -489,6 +489,12 @@ impl Project { } } + /// 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)) } diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 6bb70d19..3e544857 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -117,15 +117,30 @@ pub(super) fn parse_mesh(file_name: &str, bytes: Vec) -> Result { } 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)) + } + + 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.doc.bake_meshes.high.is_empty()) { + 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 @@ -158,7 +173,7 @@ impl Session { mesh: self.bake_mesh(texture_set)?, bvh: self.bvh.clone(), material: set.material, - settings: set.bake.clone(), + settings, high, cage, skew, @@ -730,14 +745,19 @@ fn updated_settings(session: &Session, params: &Value, command: &str) -> Result< fn set_settings(session: &mut Session, params: &Value, command: &str) -> Result> { 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)?; + let next = with_sync_partners(&session.doc.project, targets, command, boolp(params, "preset") == Some(true))?; 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 -fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, BakeSettings)>, command: &str) -> Result> { +/// `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 settings come out invalid (`from_preset`: preset limits apply) +fn with_sync_partners( + project: &texturecraft_core::Project, + targets: Vec<(usize, BakeSettings)>, + command: &str, + from_preset: bool, +) -> Result> { 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 }; @@ -755,6 +775,10 @@ fn with_sync_partners(project: &texturecraft_core::Project, targets: Vec<(usize, } } } + // A field valid beside the target's other values can be invalid beside a partner's: min above the partner's max + for (partner, settings) in &next { + validate_model_settings(settings, command, from_preset, project.texture_sets.get(*partner).map(|set| &set.bake))?; + } next.extend(targets); Ok(next.into_iter().collect()) } @@ -861,3 +885,23 @@ 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(64, 64).unwrap(); + session.doc.project.texture_sets[0].bake.maps.select([BakedMap::Normal]); + let colours = Arc::new(vec![None]); + let _ = session.doc.bake_meshes.low_base_color.set(Ok(colours.clone())); + + 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/sync_command.rs b/crates/engine/src/bake/sync_command.rs index e244e507..88018b6f 100644 --- a/crates/engine/src/bake/sync_command.rs +++ b/crates/engine/src/bake/sync_command.rs @@ -51,10 +51,7 @@ fn sync(session: &mut Session, params: &Value) -> Result { let members = sets_param(session, COMMAND, params)?; let sets = &session.doc.project.texture_sets; - // Additions take the settings of a set that already shares them; with none left, of the active set when it joins, else of the first - let staying = members.iter().copied().find(|index| sets.get(*index).is_some_and(|set| set.bake.sync.shares(group))); - let active = session.ts(); - let source = staying.or_else(|| members.contains(&active).then_some(active)).or_else(|| members.first().copied()); + 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 @@ -265,4 +262,16 @@ mod tests { 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); + } } diff --git a/crates/ui-egui/src/bake_mode/breadcrumb.rs b/crates/ui-egui/src/bake_mode/breadcrumb.rs index 2ece6800..ac3cda17 100644 --- a/crates/ui-egui/src/bake_mode/breadcrumb.rs +++ b/crates/ui-egui/src/bake_mode/breadcrumb.rs @@ -26,7 +26,7 @@ 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; returns whether ⟲ was clicked +/// › 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(); @@ -39,13 +39,17 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, selected: BakedMap, r 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 = set_names.get(active_set).map_or("", String::as_str); - let set_galley = painter.layout_no_wrap(set_name.to_owned(), FontId::proportional(NAME_SIZE), tokens.text); + 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, tr(baked_map_label(selected)), semibold(NAME_SIZE), tokens.text_strong); + painter.text(pos2(x, center_y), Align2::LEFT_CENTER, map_name, semibold(NAME_SIZE), tokens.text_strong); egui::Popup::menu(&set_caret).show(|ui| { for (set_index, name) in set_names.iter().enumerate() { diff --git a/crates/ui-egui/src/bake_mode/live_preview.rs b/crates/ui-egui/src/bake_mode/live_preview.rs index 4c358962..af8f4732 100644 --- a/crates/ui-egui/src/bake_mode/live_preview.rs +++ b/crates/ui-egui/src/bake_mode/live_preview.rs @@ -231,7 +231,7 @@ fn input(app: &TextureCraftApp, target: LivePreviewTarget, size: BakeResolution) 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_task(target.set) { + let mut task = match app.session.bake_task_only(target.set, target.map) { Ok(task) => task, Err(error) => { // Once, not on every change while it stays unbakeable @@ -245,7 +245,6 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context, target: LivePreviewTarg }; app.live_preview.cannot_bake = false; - task.settings.maps.select([target.map]); let own = task.settings.common.resolution; let size = if own.pixels() < size.pixels() { own } else { size }; task.settings.common.resolution = size; diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index 433cbb98..0cba2eeb 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -3,13 +3,13 @@ use std::sync::{Arc, Weak}; use egui::{ColorImage, TextureHandle, TextureOptions}; use texturecraft_engine::Session; -use texturecraft_engine::core::BakedMap; +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 and the working size it was drawn from -type Thumbnail = (Weak>, (u32, u32), TextureHandle); +/// 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)] @@ -27,9 +27,10 @@ impl MapThumbnails { return None; }; - if let Some((drawn_from, working_size, texture)) = self.textures.get(&key) + 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()); } @@ -38,7 +39,7 @@ impl MapThumbnails { 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, texture.clone())); + self.textures.insert(key, (Arc::downgrade(data), cache.size, cache.composite.block_scales.clone(), texture.clone())); Some(texture) } } @@ -63,6 +64,15 @@ mod tests { 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.iter().next().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 4fbe3505..72d3b1b9 100644 --- a/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs +++ b/crates/ui-egui/src/bake_mode/mesh_map_bakers.rs @@ -1,4 +1,4 @@ -use egui::{Align, CornerRadius, FontId, Layout, Rect, Sense, Stroke, Ui, UiBuilder, pos2, 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::ViewMode; @@ -17,6 +17,9 @@ use crate::theme::{Tokens, semibold}; const PRESETS_MENU_MIN_WIDTH: f32 = 220.0; const PRESET_NAME_FIELD_WIDTH: f32 = 130.0; +/// Spacing of the points tested along a checkbox drag's path between two frames, well under a row's height +const CROSS_STEP: f32 = 4.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; @@ -80,9 +83,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe 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(app, ui, map, settings, map == selected, &mut check_drag)).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); } @@ -90,11 +95,16 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe // Kept through the frame of the release, so the click that ends a drag does not toggle its last checkbox back 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) = check_drag.filter(|_| is_held) { + if let (Some(value), true) = (check_drag, is_held) { data.insert_temp(check_drag_id, value); + if let Some(pointer) = pointer { + data.insert_temp(drag_from_id, pointer); + } } else { data.remove_temp::(check_drag_id); + data.remove_temp::(drag_from_id); } }); } @@ -223,8 +233,16 @@ fn copy_items(app: &mut TextureCraftApp, ui: &mut Ui, what: &'static str, map: O } } -/// One baker row (`check_drag`: the state a pressed check gives those the pointer then crosses); 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) -> 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)); @@ -243,7 +261,7 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak 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); + 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() { @@ -311,12 +329,24 @@ fn row(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, settings: &mut Bak response.clicked() } -/// Start a checkbox drag at a press on `checkbox`; returns whether a drag is in this row's checkbox column now (the whole row height counts) -fn drag_check(ui: &Ui, checkbox: &egui::Response, row: Rect, is_enabled: bool, check_drag: &mut Option) -> bool { - if check_drag.is_none() && checkbox.is_pointer_button_down_on() { +/// 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); } - check_drag.is_some() && ui.rect_contains_pointer(Rect::from_x_y_ranges(checkbox.rect.x_range(), row.y_range())) + 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 { + let steps = (from.distance(to) / CROSS_STEP).ceil().max(1.0) as u32; + (0..=steps).any(|step| rect.contains(from.lerp(to, step as f32 / steps as f32))) } /// The baked map's thumbnail in `rect`; before it is baked, an empty square crossed by a diagonal diff --git a/crates/ui-egui/src/bake_mode/set_picker.rs b/crates/ui-egui/src/bake_mode/set_picker.rs index fc27b9e9..51ce9eef 100644 --- a/crates/ui-egui/src/bake_mode/set_picker.rs +++ b/crates/ui-egui/src/bake_mode/set_picker.rs @@ -4,7 +4,7 @@ use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKi use egui_phosphor::regular as icon; use serde_json::{Value, json}; use texturecraft_engine::bake::settings_patch; -use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap}; +use texturecraft_engine::core::{BakeSettings, BakeSyncGroup, BakedMap, Project}; use super::common_settings::antialiasing_label; use super::set_picker_purpose::SetPickerPurpose; @@ -66,7 +66,7 @@ impl SetPicker { pub(super) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let Some(mut picker) = ctx.data(|data| data.get_temp::(Self::id())) else { return }; - let rows = picker.rows(app); + let rows = picker.rows(&app.session.doc.project, app.session.ts()); let active = app.session.ts(); let tokens = Tokens::get(ctx); let frame = egui::Frame::new() @@ -98,14 +98,8 @@ impl SetPicker { } /// The listed sets - fn rows(&self, app: &TextureCraftApp) -> Vec { - let project = &app.session.doc.project; - let active = app.session.ts(); - let source = match self.purpose { - // New additions take on the settings already shared, or the active set's when none are - SetPickerPurpose::Sync(group) => project.texture_sets.iter().find(|set| set.bake.sync.shares(group)).or(project.texture_sets.get(active)), - SetPickerPurpose::Copy { .. } => None, - }; + 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() @@ -113,8 +107,19 @@ impl SetPicker { // 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, source) { - (SetPickerPurpose::Sync(group), Some(source)) if !set.bake.sync.shares(group) => differing_values(&set.bake, &source.bake, group), + let note = match self.purpose { + // What the set would take on OK when ticked: the source `bake.sync` picks from the ticked sets with this one among them + 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 } @@ -261,7 +266,7 @@ fn leaf_count(patch: &Value) -> usize { mod tests { use texturecraft_engine::core::{BakeAntialiasing, BakeResolution, BakeSettings, BakeSyncGroup, BakedMap}; - use super::differing_values; + use super::{SetPicker, SetPickerPurpose, differing_values}; #[test] fn a_set_shows_its_own_size_and_antialiasing_and_counts_the_rest() { @@ -287,4 +292,25 @@ mod tests { 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] }; + 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/high_poly_job.rs b/crates/ui-egui/src/high_poly_job.rs index 37ac21df..09716f9a 100644 --- a/crates/ui-egui/src/high_poly_job.rs +++ b/crates/ui-egui/src/high_poly_job.rs @@ -50,7 +50,7 @@ impl TextureCraftApp { }); } - /// Add a loaded high poly to the session and start on the next file; drop them all once another project is open + /// 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 #[cfg(not(target_arch = "wasm32"))] pub(crate) fn poll_high_poly_job(&mut self, context: &egui::Context) { let Some(job) = &self.high_poly_job else { return }; @@ -61,6 +61,11 @@ impl TextureCraftApp { } context.request_repaint_after(POLL_INTERVAL); + // A stroke's cancel or undo restores the document from its start, which would drop a high poly added during it + if self.session.stroke_active() { + return; + } + let loaded = match job.answer.try_recv() { Ok(loaded) => loaded, Err(TryRecvError::Empty) => return, diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c1dcf34e..a0c23f0c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -814,12 +814,12 @@ impl TextureCraftApp { let only = job.only; self.session.bake_preview_set_current(set_index); - match self.session.bake_task(set_index) { - Ok(mut task) => { - if let Some(map) = only { - task.settings.maps.select([map]); - } - + 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(); let maps_total = task.maps().len(); diff --git a/crates/ui-egui/src/property_sheet/file_list.rs b/crates/ui-egui/src/property_sheet/file_list.rs index 69a34386..8563df58 100644 --- a/crates/ui-egui/src/property_sheet/file_list.rs +++ b/crates/ui-egui/src/property_sheet/file_list.rs @@ -99,14 +99,8 @@ impl PropertySheet<'_> { 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 = shortened_folder(&painter, folder, words_right - rect.left() - NAME_LEFT); - painter.text( - pos2(rect.left() + NAME_LEFT, rect.top() + FOLDER_CENTER), - Align2::LEFT_CENTER, - shown, - FontId::proportional(SMALL_TEXT_SIZE), - tokens.text_dim, - ); + 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())); @@ -135,6 +129,11 @@ impl PropertySheet<'_> { } } +/// `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; @@ -150,3 +149,25 @@ fn shortened_folder(painter: &egui::Painter, folder: &str, room: f32) -> String } 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/tests/it/bake_live_preview.rs b/crates/ui-egui/tests/it/bake_live_preview.rs index 848543c9..89c6e301 100644 --- a/crates/ui-egui/tests/it/bake_live_preview.rs +++ b/crates/ui-egui/tests/it/bake_live_preview.rs @@ -151,7 +151,7 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() // 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| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + 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 @@ -162,7 +162,12 @@ fn a_new_resolution_or_a_settings_change_from_anywhere_bakes_the_preview_again() } session.add_high_poly_bytes("High.obj", bytes.to_vec()).unwrap(); let before = picture(&harness); - let reloaded = run_until(&mut harness, |harness| picture(harness).as_ref().map(std::sync::Arc::as_ptr) != before.as_ref().map(std::sync::Arc::as_ptr)); + 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 index ce17536c..8a03a411 100644 --- a/crates/ui-egui/tests/it/bake_map_rows.rs +++ b/crates/ui-egui/tests/it/bake_map_rows.rs @@ -1,4 +1,4 @@ -//! The Mesh Map Bakers rows: a drag down the checkboxes gives each the state the first one took +//! 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; @@ -52,6 +52,39 @@ fn a_drag_down_the_checkboxes_unchecks_every_row_it_crosses() { 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(); diff --git a/crates/ui-egui/tests/it/bake_mode.rs b/crates/ui-egui/tests/it/bake_mode.rs index 2339512d..51a543ed 100644 --- a/crates/ui-egui/tests/it/bake_mode.rs +++ b/crates/ui-egui/tests/it/bake_mode.rs @@ -450,6 +450,17 @@ fn the_breadcrumb_switches_the_shown_map() { assert_eq!(enabled_maps(&harness), [BakedMap::Curvature]); } +#[test] +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)); diff --git a/crates/ui-egui/tests/it/high_poly_loading.rs b/crates/ui-egui/tests/it/high_poly_loading.rs index 4808c98c..c332cb95 100644 --- a/crates/ui-egui/tests/it/high_poly_loading.rs +++ b/crates/ui-egui/tests/it/high_poly_loading.rs @@ -12,6 +12,8 @@ use texturecraft_ui_egui::state::Mode; 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> { @@ -95,3 +97,30 @@ fn a_high_poly_that_finishes_after_the_list_changed_joins_the_list_as_it_is() { 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); +}