From 433ae07387cc43eef57fff7a408e1dc7caa2c59f Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:32:12 +0000 Subject: [PATCH] Add color selection editor and ID map picking Properties gets tolerance, a Colors list (swatch, R/G/B, re-pick, remove) and a Pick color mode: the pointer becomes an eyedropper, both views show the ID mesh map and the next click adds the ID color under it. effect.set takes colors; effect.colorSelection.pick samples the texel the mask evaluates and skips hidden texture sets. --- crates/engine/src/color_selection_cmds.rs | 150 +++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/mask_cmds.rs | 5 +- crates/engine/tests/color_selection.rs | 197 ++++++++++++++++++ crates/ui-egui/src/color_selection_editor.rs | 102 +++++++++ crates/ui-egui/src/dock.rs | 1 + crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/id_color_pick.rs | 87 ++++++++ crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/viewport.rs | 41 +++- .../ui-egui/tests/color_selection_editor.rs | 125 +++++++++++ 20 files changed, 738 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/color_selection_cmds.rs create mode 100644 crates/engine/tests/color_selection.rs create mode 100644 crates/ui-egui/src/color_selection_editor.rs create mode 100644 crates/ui-egui/src/id_color_pick.rs create mode 100644 crates/ui-egui/tests/color_selection_editor.rs diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs new file mode 100644 index 00000000..2b0dc210 --- /dev/null +++ b/crates/engine/src/color_selection_cmds.rs @@ -0,0 +1,150 @@ +//! Color selection effects: the ID colors they select, picked from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_core::{BakedMap, EffectKind, LayerId}; +use texturecraft_geom::glam::Vec2; +use texturecraft_geom::surface_at; + +use crate::commands::{CommandSpec, bad, f32p, has_layer, u64p}; +use crate::mask_cmds::effect_id; +use crate::tool_cmds::viewport_of; +use crate::{Result, Session, cmd}; + +/// Most colors one color selection holds; an ID map rarely has more distinct parts +const MAX_SELECTED_COLORS: usize = 256; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.colorSelection.pick", + "Pick ID color", + [], + None, + "{effect?: a color selection (default: the selected effect), x?, y?: viewport pixels, viewport?: [w,h] | uv?: [u,v] texture set atlas UV (the 2D view), index?: replace this color instead of adding one} → {color: [r,g,b] as the ID map stores it, index} — samples the ID mesh map under the point", + has_layer, + pick + )] +} + +/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection +pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> { + if let Some(list) = params.get("colors") { + *colors = colors_param(list)?; + } + if let Some(value) = f32p(params, "tolerance") { + *tolerance = value.clamp(0.0, 1.0); + } + Ok(()) +} + +/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1 +fn colors_param(list: &Value) -> Result> { + const CMD: &str = "effect.set"; + let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?; + if items.is_empty() || items.len() > MAX_SELECTED_COLORS { + return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors"))); + } + + items + .iter() + .map(|item| match finite_numbers(item).as_deref() { + Some([red, green, blue]) => Ok([*red, *green, *blue].map(|value| (value as f32).clamp(0.0, 1.0))), + _ => Err(bad(CMD, "each color must be [r, g, b] with finite numbers")), + }) + .collect() +} + +/// Samples the ID map under a viewport point or at a UV and adds the color to a color selection +fn pick(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "effect.colorSelection.pick"; + let effect = effect_id(session, params, CMD)?; + let (owner, color_count) = match session.doc.project.effect(effect) { + Some((owner, found)) => match &found.kind { + EffectKind::ColorSelection { colors, .. } => (owner, colors.len()), + other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))), + }, + None => return Err(bad(CMD, format!("no effect {}", effect.0))), + }; + + let index = match u64p(params, "index") { + Some(index) => Some(usize::try_from(index).ok().filter(|index| *index < color_count).ok_or_else(|| bad(CMD, format!("no color {index} to replace")))?), + None if color_count >= MAX_SELECTED_COLORS => return Err(bad(CMD, format!("a color selection holds at most {MAX_SELECTED_COLORS} colors"))), + None => None, + }; + + let color = id_color_at(session, params, owner)?; + session.edit("Pick ID color", |session| { + let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; + if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind { + match index.and_then(|index| colors.get_mut(index)) { + Some(slot) => *slot = color, + None => colors.push(color), + } + } + Ok(()) + })?; + Ok(json!({ "color": color, "index": index.unwrap_or(color_count) })) +} + +/// The ID map color of the texel a color selection on `owner` reads at the picked point +fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> { + const CMD: &str = "effect.colorSelection.pick"; + let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?; + let set = session.doc.project.texture_set(set_index)?; + let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id)); + let Some(baked) = baked else { + return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + }; + + let uv = match params.get("uv") { + Some(uv) => uv_param(uv)?, + None => { + let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { + return Err(bad(CMD, "give `x` and `y` (viewport pixels) or `uv`")); + }; + + let (uv, material) = visible_surface(session, Vec2::new(x, y), viewport_of(session, params)) + .ok_or_else(|| bad(CMD, "nothing under that point: pick on the mesh"))?; + if material != set.material { + return Err(bad(CMD, "that surface belongs to another texture set")); + } + uv + } + }; + + // The same texel the mask evaluates, so a picked color always selects where it was picked + let size = set.size(); + let texel = [uv.x * size.0 as f32, uv.y * size.1 as f32]; + if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { + return Err(bad(CMD, "that point is outside the texture set's UV space")); + } + baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there")) +} + +/// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray +fn visible_surface(session: &Session, screen: Vec2, viewport: Vec2) -> Option<(Vec2, usize)> { + let viewport = viewport.max(Vec2::ONE); + let device = Vec2::new(screen.x / viewport.x * 2.0 - 1.0, 1.0 - screen.y / viewport.y * 2.0); + let ray = session.camera.ray(device, viewport.x / viewport.y); + let sets = &session.doc.project.texture_sets; + let visible = |triangle: u32| { + let material = session.mesh.material_of(triangle as usize).unwrap_or(0); + sets.iter().find(|set| set.material == material).is_none_or(|set| set.visible) + }; + + let hit = session.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, &visible)?; + let surface = surface_at(&session.mesh, hit.tri, hit.u, hit.v)?; + Some((surface.uv, session.mesh.material_of(hit.tri as usize).unwrap_or(0))) +} + +/// A `[u, v]` param of finite numbers +fn uv_param(uv: &Value) -> Result { + match finite_numbers(uv).as_deref() { + Some([u, v]) => Ok(Vec2::new(*u as f32, *v as f32)), + _ => Err(bad("effect.colorSelection.pick", "`uv` must be [u, v] with finite numbers")), + } +} + +/// The numbers of a list param, or None when any entry is not a finite number +fn finite_numbers(list: &Value) -> Option> { + list.as_array()?.iter().map(|value| value.as_f64().filter(|number| number.is_finite())).collect() +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..154c5284 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -56,6 +56,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::color_selection_cmds::specs()); v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8c2a03d1..7c5ccec3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod bake; pub mod brush_preset_cmds; pub mod camera_cmds; +pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 27c18bca..b8aad872 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -519,7 +519,8 @@ fn set(session: &mut Session, params: &Value) -> Result { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } } - EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => { + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, + EffectKind::Compare { tolerance, .. } => { if let Some(value) = f32p(params, "tolerance") { *tolerance = value.clamp(0.0, 1.0); } diff --git a/crates/engine/tests/color_selection.rs b/crates/engine/tests/color_selection.rs new file mode 100644 index 00000000..2074176e --- /dev/null +++ b/crates/engine/tests/color_selection.rs @@ -0,0 +1,197 @@ +//! Color selection effects: editing their ID colors and picking them from the ID mesh map + +use serde_json::{Value, json}; +use texturecraft_engine::core::{EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const TOP_LEFT_ID: [u8; 3] = [200, 30, 10]; +const TOP_RIGHT_ID: [u8; 3] = [10, 200, 30]; +const BOTTOM_ID: [u8; 3] = [30, 10, 200]; +const NO_PART: [f32; 3] = [0.0, 0.0, 0.0]; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// An 8×8 ID map: two parts on the top half, one on the bottom half +fn id_map_png() -> Vec { + let image = image::RgbaImage::from_fn(8, 8, |x, y| { + let [red, green, blue] = match (x < 4, y < 4) { + (true, true) => TOP_LEFT_ID, + (false, true) => TOP_RIGHT_ID, + _ => BOTTOM_ID, + }; + image::Rgba([red, green, blue, 255]) + }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +fn stored(id: [u8; 3]) -> [f32; 3] { + id.map(|channel| channel as f32 / 255.0) +} + +fn assert_close(actual: [f32; 3], expected: [f32; 3]) { + assert!(actual.iter().zip(expected).all(|(channel, wanted)| (channel - wanted).abs() < 1e-3), "{actual:?} vs {expected:?}"); +} + +/// A fill layer masked by a color selection that selects no part yet: (layer, effect) +fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) { + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } + + let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap()); + execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + (layer, effect) +} + +fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> { + match &session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +#[test] +fn a_color_picked_on_the_mesh_is_selected_where_it_was_picked() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + let center = Vec2::new(200.0, 200.0); + let hit = session.pick(center, session.viewport).unwrap(); + let (width, height) = session.caches[0].size; + let texel = ((hit.uv.x * width as f32) as u32, (hit.uv.y * height as f32) as u32); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![0.0], "nothing selected before the pick"); + + let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": center.x, "y": center.y})).unwrap(); + + assert_eq!(picked["index"], json!(1)); + assert_eq!(colors(&session, effect).len(), 2); + assert_eq!(session.mask_at(layer, &[texel]).unwrap(), vec![1.0]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART], "one undo step"); +} + +#[test] +fn a_uv_pick_adds_the_color_there_or_replaces_one() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + + execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); + assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID)); + + let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); + assert_eq!(replaced["index"], json!(0)); + let picked = colors(&session, effect); + assert_eq!(picked.len(), 2); + assert_close(picked[0], stored(BOTTOM_ID)); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect)[0], NO_PART, "one undo step"); +} + +#[test] +fn the_colors_param_replaces_the_list_in_one_undo_step() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let edited = [stored(TOP_LEFT_ID), stored(TOP_RIGHT_ID)]; + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); + assert_eq!(colors(&session, effect), edited.to_vec()); + let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; + assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2)); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn bad_colors_are_refused_and_change_nothing() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; + + for colors_param in &refused { + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); + } + assert_eq!(colors(&session, effect), vec![NO_PART]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1e300, 0.5, 0.5]]})).unwrap(); + assert_eq!(colors(&session, effect), vec![[1.0, 0.5, 0.5]], "out-of-range values clamp to 0..1"); +} + +#[test] +fn picking_explains_what_is_missing() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, false); + let pick = |session: &mut Session, params: Value| execute(session, "effect.colorSelection.pick", ¶ms).unwrap_err().to_string(); + + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5]})).contains("no ID map")); + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + assert!(pick(&mut session, json!({"effect": effect.0, "x": 1, "y": 1})).contains("nothing under that point")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [1.5, 0.5]})).contains("outside")); + assert!(pick(&mut session, json!({"effect": effect.0, "uv": [0.5, 0.5], "index": 7})).contains("no color 7")); + assert!(pick(&mut session, json!({"effect": effect.0})).contains("`x` and `y`")); + + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": layer.0})).unwrap()["effect"].as_u64().unwrap(); + assert!(pick(&mut session, json!({"effect": fill, "uv": [0.5, 0.5]})).contains("not a color selection")); + assert_eq!(colors(&session, effect), vec![NO_PART]); +} + +#[test] +fn hostile_params_never_crash_the_color_selection_commands() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, true); + let hostile = [ + json!({"effect": effect.0, "x": f32::MAX, "y": -1e30, "viewport": [0, 0]}), + json!({"effect": effect.0, "uv": [f64::MAX, -1e300], "index": u64::MAX}), + json!({"effect": effect.0, "uv": [0.5], "colors": [[f64::MAX, -f64::MAX, 0.0]]}), + json!({"effect": effect.0, "uv": "x", "colors": {"r": 1}}), + json!({"effect": u64::MAX, "uv": [0.5, 0.5]}), + ]; + + for params in &hostile { + let _ = execute(&mut session, "effect.colorSelection.pick", params); + let _ = execute(&mut session, "effect.set", params); + session.update(); + } +} + +#[test] +fn a_hidden_texture_set_does_not_block_a_pick_behind_it() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.update(); + let set_named = |name: &str| session.doc.project.texture_sets.iter().position(|set| set.name == name).unwrap(); + let (base, ball) = (set_named("Base"), set_named("Ball")); + execute(&mut session, "textureSet.select", &json!({"ts": base})).unwrap(); + let (_, effect) = masked_layer(&mut session, true); + let pick_at = |session: &mut Session, y: f32| execute(session, "effect.colorSelection.pick", &json!({"effect": effect.0, "x": 200, "y": y})); + let ball_in_front = |session: &Session, y: f32| { + session.pick(Vec2::new(200.0, y), session.viewport).is_some_and(|hit| session.texture_set_of_material(hit.material) == Some(ball)) + }; + + // Down the middle until a pixel where the hidden ball covers the base: the pick reads the base + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": false})).unwrap(); + let mut covered = None; + for y in (200..400).map(|y| y as f32) { + if ball_in_front(&session, y) && pick_at(&mut session, y).is_ok() { + covered = Some(y); + break; + } + } + let y = covered.expect("a pixel where the ball covers the base"); + assert_eq!(colors(&session, effect).len(), 2); + + execute(&mut session, "textureSet.visible", &json!({"ts": ball, "visible": true})).unwrap(); + assert!(pick_at(&mut session, y).unwrap_err().to_string().contains("another texture set"), "a shown ball still blocks it"); +} diff --git a/crates/ui-egui/src/color_selection_editor.rs b/crates/ui-egui/src/color_selection_editor.rs new file mode 100644 index 00000000..870e3360 --- /dev/null +++ b/crates/ui-egui/src/color_selection_editor.rs @@ -0,0 +1,102 @@ +//! Properties of a color selection effect: tolerance and the ID colors it selects + +use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{BakedMap, LayerId}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::id_color_pick::IdColorPick; +use crate::theme::Tokens; +use crate::widgets::{icon_button, slider_edit}; + +/// Width of one R, G or B readout, so the columns line up from row to row (fits "G: 255") +const READOUT_WIDTH: f32 = 50.0; + +/// Height of a color row's swatch and readouts, as tall as the app's other swatches +const ROW_HEIGHT: f32 = 18.0; + +const SWATCH_WIDTH: f32 = 36.0; + +const ROW_BUTTON_SIZE: f32 = 20.0; + +/// Tolerance, a Colors list with a pick mode, and one row per ID color (swatch, re-pick, R/G/B, remove) +pub fn color_selection_properties(app: &mut TextureCraftApp, ui: &mut Ui, effect: LayerId, colors: &[[f32; 3]], tolerance: f32) { + let tokens = Tokens::get(ui.ctx()); + let mut edited_tolerance = tolerance; + if let Some(merge) = slider_edit(ui, tr("Tolerance"), &mut edited_tolerance, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": effect.0, "tolerance": edited_tolerance, "merge": merge})); + } + + let set_index = app.session.doc.project.locate(effect_owner(app, effect)).map_or(app.session.ts(), |(set_index, _, _)| set_index); + let has_id_map = app.session.baked(set_index).is_some_and(|baked| baked.maps.contains_key(&BakedMap::Id)); + if !has_id_map { + ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake an ID map (F8) to pick colors from the mesh."))).color(tokens.warning)); + } + + let picking = app.picking_id_color.filter(|pick| pick.effect == effect); + ui.group(|ui| { + ui.horizontal(|ui| { + ui.label(tr("Colors")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let adding = picking.is_some_and(|pick| pick.index.is_none()); + let button = egui::Button::new(format!("{} {}", ic::EYEDROPPER, tr("Pick color"))).selected(adding); + if ui.add_enabled(has_id_map, button).clicked() { + toggle_pick(app, effect, None, adding); + } + }); + }); + + for (index, color) in colors.iter().enumerate() { + ui.horizontal(|ui| { + id_swatch(ui, *color); + let repicking = picking.is_some_and(|pick| pick.index == Some(index)); + let repick = ui.add_enabled_ui(has_id_map, |ui| icon_button(ui, ic::EYEDROPPER, tr("Pick color"), repicking, ROW_BUTTON_SIZE)).inner; + if repick.clicked() { + toggle_pick(app, effect, Some(index), repicking); + } + + for (channel, value) in ["R", "G", "B"].iter().zip(display_bytes(*color)) { + ui.allocate_ui_with_layout(vec2(READOUT_WIDTH, ROW_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(READOUT_WIDTH); + ui.label(format!("{channel}: {value}")); + }); + } + + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let remove = ui.add_enabled_ui(colors.len() > 1, |ui| icon_button(ui, ic::MINUS, tr("Remove"), false, ROW_BUTTON_SIZE)).inner; + if remove.clicked() { + let remaining: Vec<[f32; 3]> = colors.iter().enumerate().filter(|(kept, _)| *kept != index).map(|(_, kept)| *kept).collect(); + app.run("effect.set", json!({"effect": effect.0, "colors": remaining})); + } + }); + }); + } + }); +} + +/// The layer whose mask holds `effect` +fn effect_owner(app: &TextureCraftApp, effect: LayerId) -> LayerId { + app.session.doc.project.effect(effect).map_or(effect, |(owner, _)| owner) +} + +fn toggle_pick(app: &mut TextureCraftApp, effect: LayerId, index: Option, running: bool) { + if running { + IdColorPick::end(app); + } else { + IdColorPick::start(app, effect, index); + } +} + +/// An ID color as the ID map view draws it: the stored value, unconverted, in 0–255 +fn display_bytes(color: [f32; 3]) -> [u8; 3] { + color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8) +} + +fn id_swatch(ui: &mut Ui, color: [f32; 3]) { + let tokens = Tokens::get(ui.ctx()); + let [red, green, blue] = display_bytes(color); + let (rect, _) = ui.allocate_exact_size(vec2(SWATCH_WIDTH, ROW_HEIGHT), Sense::hover()); + ui.painter().rect(rect, f32::from(tokens.radius), Color32::from_rgb(red, green, blue), Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b7602e9e..0bb90ccd 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2112,6 +2112,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: tool_properties(app, ui); } EffectKind::Filter(filter) => filter_properties(app, ui, id, filter), + EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_editor::color_selection_properties(app, ui, eid, colors, *tolerance), other => { ui.label(RichText::new(tr(other.name())).color(tk.text_dim)); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index e651a035..1c4d8686 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "المحور"), ("Back to painting", "العودة إلى الرسم"), ("Backface culling", "استبعاد الوجوه الخلفية"), + ("Bake an ID map (F8) to pick colors from the mesh.", "اخبز خريطة المعرّفات ID (F8) لالتقاط الألوان من الشبكة."), ("Bake Mesh Maps", "خبز خرائط المجسم"), ("Bake mesh maps", "خبز خرائط المجسم"), ( @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "مدمج: {mesh}"), ("Cage: {name}", "القفص (Cage): {name}"), ("Camera", "الكاميرا"), + ("Colors", "الألوان"), ("Go to camera 1", "الانتقال إلى الكاميرا 1"), ("Go to camera 2", "الانتقال إلى الكاميرا 2"), ("Go to camera 3", "الانتقال إلى الكاميرا 3"), @@ -553,6 +555,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "تراكب (Overlay)"), ("Overlay opacity", "عتامة التراكب"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - خشونة ومعدنية (TextureCraft)"), + ("Pick color", "التقاط لون"), ("PNG image", "صورة PNG"), ("Padding", "الحشو (Padding)"), ("Paint", "رسم"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 52bf1393..25420ed6 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Achse"), ("Back to painting", "Zurück zum Malen"), ("Backface culling", "Rückseiten-Culling"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Backe eine ID-Map (F8), um Farben vom Mesh aufzunehmen."), ("Bake Mesh Maps", "Mesh-Maps backen"), ("Bake mesh maps", "Mesh-Maps backen"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "Mesh-Maps backen (F8) für Generatoren auf Basis von Krümmung, AO und Dicke."), @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integriert: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Kamera"), + ("Colors", "Farben"), ("Go to camera 1", "Zu Kamera 1 wechseln"), ("Go to camera 2", "Zu Kamera 2 wechseln"), ("Go to camera 3", "Zu Kamera 3 wechseln"), @@ -586,6 +588,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Ineinanderkopieren"), ("Overlay opacity", "Überlagerungsdeckkraft"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallisch/Rauheit (TextureCraft)"), + ("Pick color", "Farbe aufnehmen"), ("PNG image", "PNG-Bild"), ("Padding", "Padding"), ("Paint", "Malen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 8065a348..afc6b6fd 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -86,6 +86,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eje"), ("Back to painting", "Volver a pintar"), ("Backface culling", "Descarte de caras traseras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Hornea un mapa de ID (F8) para tomar colores de la malla."), ("Bake Mesh Maps", "Hornear mapas de malla"), ("Bake mesh maps", "Hornear mapas de malla"), ( @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrada: {mesh}"), ("Cage: {name}", "Jaula: {name}"), ("Camera", "Cámara"), + ("Colors", "Colores"), ("Go to camera 1", "Ir a la cámara 1"), ("Go to camera 2", "Ir a la cámara 2"), ("Go to camera 3", "Ir a la cámara 3"), @@ -577,6 +579,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Superponer"), ("Overlay opacity", "Opacidad de superposición"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidad (TextureCraft)"), + ("Pick color", "Tomar color"), ("PNG image", "Imagen PNG"), ("Padding", "Margen"), ("Paint", "Pintar"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index b8c882f0..93566ae8 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -92,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Axe"), ("Back to painting", "Retour à la peinture"), ("Backface culling", "Élimination des faces arrière"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Précalculez une carte d'ID (F8) pour prélever des couleurs sur le maillage."), ("Bake Mesh Maps", "Précalculer les cartes de maillage"), ("Bake mesh maps", "Précalculer les cartes de maillage"), ( @@ -127,6 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Intégré : {mesh}"), ("Cage: {name}", "Cage : {name}"), ("Camera", "Caméra"), + ("Colors", "Couleurs"), ("Go to camera 1", "Aller à la caméra 1"), ("Go to camera 2", "Aller à la caméra 2"), ("Go to camera 3", "Aller à la caméra 3"), @@ -592,6 +594,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Incrustation"), ("Overlay opacity", "Opacité de superposition"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Métallique Rugosité (TextureCraft)"), + ("Pick color", "Prélever une couleur"), ("PNG image", "Image PNG"), ("Padding", "Marge"), ("Paint", "Peinture"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index c6cfdaf5..10666776 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Asse"), ("Back to painting", "Torna alla pittura"), ("Backface culling", "Culling facce posteriori"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Esegui il bake di una mappa ID (F8) per prelevare i colori dalla mesh."), ("Bake Mesh Maps", "Bake mappe mesh"), ("Bake mesh maps", "Bake mappe mesh"), ( @@ -124,6 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Integrata: {mesh}"), ("Cage: {name}", "Gabbia: {name}"), ("Camera", "Camera"), + ("Colors", "Colori"), ("Go to camera 1", "Vai alla camera 1"), ("Go to camera 2", "Vai alla camera 2"), ("Go to camera 3", "Vai alla camera 3"), @@ -583,6 +585,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sovrapponi"), ("Overlay opacity", "Opacità sovrapposizione"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metallico Rugosità (TextureCraft)"), + ("Pick color", "Preleva colore"), ("PNG image", "Immagine PNG"), ("Padding", "Padding"), ("Paint", "Pittura"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index bcecd8df..eaa05975 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -92,6 +92,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "軸"), ("Back to painting", "ペイントに戻る"), ("Backface culling", "背面カリング"), + ("Bake an ID map (F8) to pick colors from the mesh.", "メッシュから色を拾うには ID マップをベイクしてください (F8)。"), ("Bake Mesh Maps", "メッシュマップのベイク"), ("Bake mesh maps", "メッシュマップをベイク"), ( @@ -127,6 +128,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "組み込み: {mesh}"), ("Cage: {name}", "ケージ: {name}"), ("Camera", "カメラ"), + ("Colors", "カラー"), ("Go to camera 1", "カメラ 1 に移動"), ("Go to camera 2", "カメラ 2 に移動"), ("Go to camera 3", "カメラ 3 に移動"), @@ -571,6 +573,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "オーバーレイ"), ("Overlay opacity", "オーバーレイの不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - メタリック/ラフネス (TextureCraft)"), + ("Pick color", "色を拾う"), ("PNG image", "PNG画像"), ("Padding", "パディング"), ("Paint", "ペイント"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 6a310a1a..846cf8a8 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "축"), ("Back to painting", "페인팅으로 돌아가기"), ("Backface culling", "후면 컬링"), + ("Bake an ID map (F8) to pick colors from the mesh.", "메시에서 색을 고르려면 ID 맵을 베이크하세요 (F8)."), ("Bake Mesh Maps", "메시 맵 베이크"), ("Bake mesh maps", "메시 맵 베이크"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "곡률, AO, 두께 기반 제너레이터를 사용하려면 메시 맵을 베이크하세요 (F8)."), @@ -121,6 +122,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "기본 제공: {mesh}"), ("Cage: {name}", "케이지: {name}"), ("Camera", "카메라"), + ("Colors", "색상"), ("Go to camera 1", "카메라 1 보기"), ("Go to camera 2", "카메라 2 보기"), ("Go to camera 3", "카메라 3 보기"), @@ -562,6 +564,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "오버레이"), ("Overlay opacity", "오버레이 불투명도"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 메탈릭 러프니스 (TextureCraft)"), + ("Pick color", "색 고르기"), ("PNG image", "PNG 이미지"), ("Padding", "패딩"), ("Paint", "페인트"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index ddee5e62..5d48697b 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -89,6 +89,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "Eixo"), ("Back to painting", "Voltar à pintura"), ("Backface culling", "Descarte de faces traseiras"), + ("Bake an ID map (F8) to pick colors from the mesh.", "Faça o bake de um mapa de ID (F8) para coletar cores da malha."), ("Bake Mesh Maps", "Bake de mapas de malha"), ("Bake mesh maps", "Fazer bake dos mapas de malha"), ( @@ -124,6 +125,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "Embutida: {mesh}"), ("Cage: {name}", "Cage: {name}"), ("Camera", "Câmera"), + ("Colors", "Cores"), ("Go to camera 1", "Ir para a câmera 1"), ("Go to camera 2", "Ir para a câmera 2"), ("Go to camera 3", "Ir para a câmera 3"), @@ -574,6 +576,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "Sobrepor"), ("Overlay opacity", "Opacidade da sobreposição"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - Metálico Rugosidade (TextureCraft)"), + ("Pick color", "Coletar cor"), ("PNG image", "Imagem PNG"), ("Padding", "Margem"), ("Paint", "Pintura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index fc76f759..79696ec5 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Axis", "轴"), ("Back to painting", "返回绘画"), ("Backface culling", "背面剔除"), + ("Bake an ID map (F8) to pick colors from the mesh.", "烘焙 ID 贴图(F8)以从网格上拾取颜色。"), ("Bake Mesh Maps", "烘焙网格贴图"), ("Bake mesh maps", "烘焙网格贴图"), ("Bake mesh maps (F8) for curvature, AO and thickness based generators.", "烘焙网格贴图(F8)以用于基于曲率、AO 和厚度的生成器。"), @@ -112,6 +113,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Built-in: {mesh}", "内置:{mesh}"), ("Cage: {name}", "笼体:{name}"), ("Camera", "相机"), + ("Colors", "颜色"), ("Go to camera 1", "转到相机 1"), ("Go to camera 2", "转到相机 2"), ("Go to camera 3", "转到相机 3"), @@ -526,6 +528,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Overlay", "叠加"), ("Overlay opacity", "叠加层不透明度"), ("PBR - Metallic Roughness (TextureCraft)", "PBR - 金属度/粗糙度(TextureCraft)"), + ("Pick color", "拾取颜色"), ("PNG image", "PNG 图像"), ("Padding", "扩边"), ("Paint", "绘画"), diff --git a/crates/ui-egui/src/id_color_pick.rs b/crates/ui-egui/src/id_color_pick.rs new file mode 100644 index 00000000..ea74a71a --- /dev/null +++ b/crates/ui-egui/src/id_color_pick.rs @@ -0,0 +1,87 @@ +//! Pick mode of a color selection: the next click in the 3D or 2D view adds the ID color under it + +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode}; + +use crate::TextureCraftApp; +use crate::state::Mode; + +/// Height in points of the eyedropper drawn as the pointer while picking +const EYEDROPPER_SIZE: f32 = 20.0; + +/// A color selection waiting for a click, and the view to return to once it comes +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct IdColorPick { + pub effect: LayerId, + /// The color the click replaces; None adds one + pub index: Option, + previous_view: ViewMode, +} + +impl IdColorPick { + /// Waits for a click that picks into `effect`, showing the ID map meanwhile + pub fn start(app: &mut TextureCraftApp, effect: LayerId, index: Option) { + let previous_view = match app.picking_id_color.take() { + Some(running) => running.previous_view, + None => app.session.view, + }; + + app.picking_id_color = Some(IdColorPick { effect, index, previous_view }); + app.run("viewport.view", json!({"mode": format!("map:{}", BakedMap::Id.id())})); + } + + /// Leaves pick mode, returning to the earlier view unless the user chose another meanwhile + pub fn end(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color.take() else { return }; + if app.session.view == ViewMode::MeshMap(BakedMap::Id) { + app.run("viewport.view", view_params(pick.previous_view)); + } + } + + /// Picks at `point` (`x`/`y`/`viewport` or `uv` params) and leaves pick mode + pub fn pick_at(app: &mut TextureCraftApp, point: Value) { + let Some(pick) = app.picking_id_color else { return }; + let mut params = json!({"effect": pick.effect.0, "index": pick.index}); + if let (Some(target), Some(source)) = (params.as_object_mut(), point.as_object()) { + target.extend(source.clone()); + } + + app.run("effect.colorSelection.pick", params); + IdColorPick::end(app); + } + + /// An eyedropper in place of the pointer while it is over `rect`, its tip on the hotspot + pub fn draw_cursor(ui: &egui::Ui, rect: egui::Rect) { + let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|pointer| rect.contains(*pointer)) else { return }; + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + + // The glyph's tip is its bottom-left corner; a dark outline keeps it readable on any ID color + let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("id_color_pick_cursor"))); + let font = egui::FontId::proportional(EYEDROPPER_SIZE); + let glyph = egui_phosphor::regular::EYEDROPPER; + for offset in [egui::vec2(-1.0, 0.0), egui::vec2(1.0, 0.0), egui::vec2(0.0, -1.0), egui::vec2(0.0, 1.0)] { + painter.text(pointer + offset, egui::Align2::LEFT_BOTTOM, glyph, font.clone(), egui::Color32::from_black_alpha(220)); + } + painter.text(pointer, egui::Align2::LEFT_BOTTOM, glyph, font, egui::Color32::WHITE); + } + + /// Ends pick mode once its effect is no longer selected or painting mode is left + pub fn end_when_stale(app: &mut TextureCraftApp) { + let Some(pick) = app.picking_id_color else { return }; + if app.session.target != StackTarget::Effect(pick.effect) || app.ui.mode != Mode::Painting { + IdColorPick::end(app); + } + } +} + +/// The `viewport.view` params that show `view` +fn view_params(view: ViewMode) -> Value { + match view { + ViewMode::Material => json!({"mode": "material"}), + ViewMode::Channel(channel) => json!({"mode": channel.id()}), + ViewMode::MeshMap(map) => json!({"mode": format!("map:{}", map.id())}), + ViewMode::UvChecker => json!({"mode": "uvChecker"}), + ViewMode::Mask(layer) => json!({"mode": "mask", "layer": layer.0}), + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 00bc0524..bd0f0651 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -8,6 +8,7 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] pub mod bake_mode; +mod color_selection_editor; pub mod control; pub mod dock; pub mod docking; @@ -16,6 +17,7 @@ mod filter_slot; pub mod fonts; pub mod gpu; pub mod i18n; +pub mod id_color_pick; pub mod keymap; mod mask_preview_image; mod material_preview_image; @@ -119,6 +121,8 @@ pub struct TextureCraftApp { pub placing_decal: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + /// The color selection the next click in the 3D or 2D view picks an ID color for + pub picking_id_color: Option, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -173,6 +177,7 @@ impl TextureCraftApp { last_paint_point: None, placing_decal: None, properties_popup: None, + picking_id_color: None, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 517377b1..8151ca55 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -59,6 +59,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { _ => None, }; let mut sync = PendingSync(Some(aux_view)); + crate::id_color_pick::IdColorPick::end_when_stale(app); let full = ui.available_rect_before_wrap(); path_keys(app, ui); @@ -560,8 +561,29 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); let popup = app.properties_popup.is_some(); + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let (pixel, viewport) = (local(position), app.session.viewport); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})); + } + } + // The selected decal's frame and handles: drag to move, scale or turn it - let decal_drag = !alt && !s_held && !v_held && !focus_pick && !popup && placing.is_none() && touch.is_none() && decal_input(app, ui, &response, rect); + let decal_drag = !alt + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && !picking_id_color + && touch.is_none() + && decal_input(app, ui, &response, rect); // Painting let painting = app.ui.mode == crate::state::Mode::Painting @@ -572,6 +594,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !v_held && !focus_pick && placing.is_none() + && !picking_id_color && touch.is_none() && !decal_drag; let path_tool = app.session.tool.tool == Tool::Path; @@ -642,6 +665,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && app.picking_id_color.is_none() && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { @@ -1281,8 +1305,21 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); + // A pending ID color pick takes the next click instead of the brush + let picking_id_color = app.picking_id_color.is_some(); + if picking_id_color { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + if !alt + && response.clicked_by(PointerButton::Primary) + && let Some(position) = response.interact_pointer_pos() + { + let uv = to_uv(position); + crate::id_color_pick::IdColorPick::pick_at(app, json!({"uv": [uv.x, uv.y]})); + } + } + // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !picking_id_color; let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); diff --git a/crates/ui-egui/tests/color_selection_editor.rs b/crates/ui-egui/tests/color_selection_editor.rs new file mode 100644 index 00000000..35404f7a --- /dev/null +++ b/crates/ui-egui/tests/color_selection_editor.rs @@ -0,0 +1,125 @@ +//! The color selection editor in Properties: one row per ID color, remove, and the pick mode + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{BakedMap, EffectKind, LayerId}; +use texturecraft_engine::{StackTarget, ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +const FIRST: [f32; 3] = [200.0 / 255.0, 0.0, 0.0]; +const SECOND: [f32; 3] = [10.0 / 255.0, 1.0, 0.0]; +const THIRD: [f32; 3] = [30.0 / 255.0, 0.0, 1.0]; +const ID_PART: [u8; 3] = [90, 160, 220]; + +/// An ID map of one color, as a PNG +fn id_map_png() -> Vec { + let [red, green, blue] = ID_PART; + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([red, green, blue, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// The app with a selected color selection of three colors on a fill layer's mask +fn app_with_color_selection(with_id_map: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + if with_id_map { + let image = session.import_resource_bytes("id.png", id_map_png()).unwrap(); + execute(&mut session, "textureSet.meshMap.set", &json!({"map": "id", "image": image})).unwrap(); + } else { + // The sample bakes an ID map with the others + execute(&mut session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + } + + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); + let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [FIRST, SECOND, THIRD]})).unwrap(); + session.target = StackTarget::Effect(effect); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +fn colors(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Vec<[f32; 3]> { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::ColorSelection { colors, .. } => colors.clone(), + other => panic!("not a color selection: {other:?}"), + } +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.event(Event::PointerMoved(position)); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// Whether the last frame drew the eyedropper glyph with its tip at `pointer` +fn eyedropper_at(harness: &Harness<'_, TextureCraftApp>, pointer: Pos2) -> bool { + harness.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) => text.galley.text() == egui_phosphor::regular::EYEDROPPER && (text.pos.x - pointer.x).abs() < 1.0, + _ => false, + }) +} + +fn pick_color_label() -> String { + format!("{} Pick color", egui_phosphor::regular::EYEDROPPER) +} + +#[test] +fn each_color_gets_a_row_and_remove_sends_the_list_without_it() { + let (mut harness, effect) = app_with_color_selection(false); + for readout in ["R: 200", "R: 10", "R: 30"] { + assert!(harness.query_by_label(readout).is_some(), "{readout} row"); + } + + let second_row = harness.get_by_label("R: 10").rect().center().y; + let remove = harness + .query_all_by_label("Remove") + .find(|button| (button.rect().center().y - second_row).abs() < 8.0) + .expect("the second row's remove button") + .rect() + .center(); + click_at(&mut harness, remove); + + assert_eq!(colors(&harness, effect), vec![FIRST, THIRD]); +} + +#[test] +fn pick_mode_shows_the_id_map_and_a_click_on_the_mesh_adds_its_color() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_some_and(|pick| pick.effect == effect && pick.index.is_none())); + assert_eq!(harness.state().session.view, ViewMode::MeshMap(BakedMap::Id)); + + let center = harness.state().viewport_rect.center(); + harness.event(Event::PointerMoved(center)); + harness.run_steps(2); + assert!(eyedropper_at(&harness, center), "the pointer is an eyedropper"); + + click_at(&mut harness, center); + + let picked = colors(&harness, effect); + assert_eq!(picked.len(), 4, "the click adds a row"); + assert_eq!(picked[3], ID_PART.map(|channel| channel as f32 / 255.0)); + assert!(harness.state().picking_id_color.is_none(), "one click ends pick mode"); + assert_eq!(harness.state().session.view, ViewMode::Material, "the earlier view comes back"); +} + +#[test] +fn without_an_id_map_picking_is_off_and_a_warning_says_why() { + let (mut harness, _) = app_with_color_selection(false); + let warning = format!("{} Bake an ID map (F8) to pick colors from the mesh.", egui_phosphor::regular::WARNING); + assert!(harness.query_by_label(&warning).is_some()); + + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + assert!(harness.state().picking_id_color.is_none()); +}