From b5b99d6fd3ba97d69b69ce4304e47eb4019e89f4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:29 +0000 Subject: [PATCH] Fills: Material and colour commands, panels and tests --- apps/texturecraft/src/main.rs | 7 + crates/compose/src/eval.rs | 15 +- crates/compose/tests/cache_and_instances.rs | 2 +- crates/core/src/cook_resolution.rs | 58 ++ crates/core/src/layer.rs | 100 +++- crates/core/src/lib.rs | 8 +- crates/core/src/project.rs | 18 +- crates/core/src/randomized_seed.rs | 14 + crates/engine/src/commands.rs | 2 + crates/engine/src/fill_alpha.rs | 65 +++ crates/engine/src/fill_material_cmds.rs | 154 +++++ crates/engine/src/inspect.rs | 4 + crates/engine/src/layer_cmds.rs | 34 +- crates/engine/src/lib.rs | 3 + crates/engine/src/material_lib.rs | 7 +- crates/engine/src/materials.rs | 46 +- crates/engine/src/painting.rs | 13 +- crates/engine/src/swatch_cmds.rs | 48 ++ crates/engine/tests/it/fill_alpha_source.rs | 66 +++ crates/engine/tests/it/fill_whole_material.rs | 155 +++++ crates/engine/tests/it/filter_support.rs | 44 ++ crates/engine/tests/it/main.rs | 4 + crates/engine/tests/it/materialcraft_link.rs | 84 ++- crates/engine/tests/it/painter_gaps.rs | 20 +- crates/engine/tests/it/swatches.rs | 36 ++ crates/engine/tests/session.rs | 85 +++ crates/paint/src/pickup.rs | 1 + crates/ui-egui/src/dock.rs | 353 +++-------- crates/ui-egui/src/exact_entry_open.rs | 5 - crates/ui-egui/src/fill_panel.rs | 11 + crates/ui-egui/src/fill_pictures.rs | 1 - crates/ui-egui/src/generator_panel.rs | 2 +- crates/ui-egui/src/lib.rs | 41 +- crates/ui-egui/src/menus.rs | 17 +- crates/ui-egui/src/pattern_panel.rs | 29 +- crates/ui-egui/src/projection_preview.rs | 1 + crates/ui-egui/src/properties_popup.rs | 11 +- .../ui-egui/src/property_sheet/button_icon.rs | 10 + crates/ui-egui/src/property_sheet/choice.rs | 14 + crates/ui-egui/src/property_sheet/group.rs | 64 ++ .../src/property_sheet/material_rows.rs | 113 ++++ crates/ui-egui/src/property_sheet/mod.rs | 16 + .../ui-egui/src/property_sheet/ramp_edit.rs | 10 + crates/ui-egui/src/property_sheet/row.rs | 6 + crates/ui-egui/src/property_sheet/slider.rs | 25 + crates/ui-egui/src/property_sheet/slot.rs | 221 +++++++ .../src/property_sheet/slot_response.rs | 15 + .../src/property_sheet/switch_control.rs | 115 +++- crates/ui-egui/src/property_sheet/tests.rs | 533 +++++++++++++++++ .../src/property_sheet/tests/gallery.rs | 37 ++ crates/ui-egui/src/rail_popup.rs | 11 +- crates/ui-egui/src/round_gizmo.rs | 24 + crates/ui-egui/src/shelf.rs | 11 - crates/ui-egui/src/state.rs | 9 + crates/ui-egui/src/symmetry/plane_pick.rs | 25 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/src/toolbar.rs | 69 ++- crates/ui-egui/src/viewport.rs | 76 ++- crates/ui-egui/src/widgets.rs | 12 +- crates/ui-egui/tests/brush_cursor_2d.rs | 14 + .../tests/it/color_selection_editor.rs | 12 +- crates/ui-egui/tests/it/fill_channel_image.rs | 41 +- crates/ui-egui/tests/it/gradient_map_menu.rs | 55 -- crates/ui-egui/tests/it/layers_panel.rs | 40 ++ crates/ui-egui/tests/it/main.rs | 48 +- crates/ui-egui/tests/it/properties_popup.rs | 65 ++- crates/ui-egui/tests/it/properties_scroll.rs | 193 ++++++ crates/ui-egui/tests/it/rename_anchor.rs | 2 +- .../ui-egui/tests/it/tile_generator_panel.rs | 9 +- crates/ui-egui/tests/ui_snapshots.rs | 552 +++++++++++++++--- docs/control-protocol.md | 48 +- 71 files changed, 3525 insertions(+), 597 deletions(-) create mode 100644 crates/core/src/cook_resolution.rs create mode 100644 crates/core/src/randomized_seed.rs create mode 100644 crates/engine/src/fill_alpha.rs create mode 100644 crates/engine/src/fill_material_cmds.rs create mode 100644 crates/engine/src/swatch_cmds.rs create mode 100644 crates/engine/tests/it/fill_alpha_source.rs create mode 100644 crates/engine/tests/it/fill_whole_material.rs create mode 100644 crates/engine/tests/it/filter_support.rs create mode 100644 crates/engine/tests/it/swatches.rs delete mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/property_sheet/material_rows.rs create mode 100644 crates/ui-egui/src/property_sheet/ramp_edit.rs create mode 100644 crates/ui-egui/src/property_sheet/slot_response.rs delete mode 100644 crates/ui-egui/tests/it/gradient_map_menu.rs create mode 100644 crates/ui-egui/tests/it/properties_scroll.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 4af56d84..0ebd5e94 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -196,6 +196,13 @@ fn main() { if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); } + + // Windows: the eyedropper's pointer keeper (screen_pick) is a copy of this program started with its own argument + #[cfg(windows)] + if std::env::args_os().nth(1).is_some_and(|arg| arg == texturecraft_ui_egui::screen_pick::KEEPER_ARG) { + std::process::exit(texturecraft_ui_egui::screen_pick::keep_pointer()); + } + let args = match parse_args() { Ok(Some(a)) => a, Ok(None) => return, diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 5dedc593..1b90a147 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -230,6 +230,7 @@ enum Content<'a> { Paint { preview: bool, }, + /// A fill (with the Scale and Rotation of the folders around it laid on) Fill { fill: Box>, /// Its projector's depth map when it culls by depth @@ -321,13 +322,14 @@ enum Op { Slope { scale: f32, seed: u32 }, } -/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]). +/// The last neighbourhood filter of an effect stack (see [`neighbourhood_filters`]) fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> { neighbourhood_filters(effects, res).last() } /// Below this a coverage weight counts as no coverage at all. const MIN_COVERAGE_WEIGHT: f32 = 1e-6; + /// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at. const FILTER_SIZE_RESOLUTION: f32 = 2048.0; /// The smallest radius a filter runs at, in texels. @@ -1098,9 +1100,10 @@ struct Node<'a> { content: Content<'a>, chans: Vec>, mask: Option>, - /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an anchor with visible effects above it) with its content cut after `k` visible effects + /// Visible anchor points of the layer: recorded after it is applied, or (`Some(k)`, an + /// anchor with visible effects above it) with its content cut after `k` visible effects. anchors: Vec<(LayerId, Option)>, - /// The node or one of its children records an anchor + /// The node or one of its children records an anchor. has_anchor: bool, height_mask: HeightMask, /// Geometry mask: whether the layer shows on each mesh submesh (None: everywhere). @@ -1188,11 +1191,12 @@ fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are planned when `kids` +/// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are +/// planned when `kids`. #[allow(clippy::too_many_arguments)] fn plan_node<'a>( inp: &EvaluationInputs<'a>, @@ -2243,8 +2247,9 @@ impl<'a, 'b> Texel<'a, 'b> { // Baked lighting reads the texel's normal and occlusion, and lights the base color only EffectKind::Filter(filter @ Filter::BakedLighting { .. }) => match Channel::ALL.get(chan_plan.ch) { Some(Channel::BaseColor) => { - let nrm = self.coords().nrm.to_array(); let factor = filter.baked_light(nrm, self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0)).unwrap_or(1.0); + let ao = self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0); + let factor = filter.baked_light(self.coords().nrm.to_array(), ao).unwrap_or(1.0); (mix3(value, value.map(|x| (x * factor).clamp(0.0, 1.0)), opacity), coverage) } _ => (value, coverage), diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 4ec0863e..e8c4270c 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -667,7 +667,7 @@ fn kept_filter_fields_are_not_used_after_an_edit_or_under_a_live_stroke() { // Changing the hot mask must invalidate the retained fields let mask = fixture.project.layer_mut(top).unwrap().mask.as_mut().unwrap(); - mask.effects[1].kind = EffectKind::Filter(Filter::Blur { radius: 6.0 }); + let blur = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Filter(Filter::Blur { .. }))).unwrap(); let (images, baked) = (Default::default(), Default::default()); cache.ahead = Vec::new(); composite_tiles_cached(&inputs(&fixture, 0, &images, &baked), &mut out, &all, Some(&mut cache)); diff --git a/crates/core/src/cook_resolution.rs b/crates/core/src/cook_resolution.rs new file mode 100644 index 00000000..3b4f8942 --- /dev/null +++ b/crates/core/src/cook_resolution.rs @@ -0,0 +1,58 @@ +//! The size a cooked source (a MaterialCraft material's maps) is made at + +use serde::{Deserialize, Serialize}; + +use crate::layer::OutputResolution; +use crate::{MAX_RESOLUTION, MIN_RESOLUTION}; + +/// How big a source is cooked: relative to its texture set (following it when it changes) or a fixed size +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum CookResolution { + /// The texture set's resolution times 2 to this power + Relative(i8), + /// Pixels across + Fixed(u32), +} + +impl CookResolution { + /// The texture set's own resolution (Auto) + pub const TEXTURE_SET: CookResolution = CookResolution::Relative(0); + + /// Powers of two a relative size may scale the texture set's by, as a generator's output resolution does + pub const FACTORS: std::ops::RangeInclusive = OutputResolution::FACTORS; + + /// Pixels across for a texture set `set` pixels across: a power of two the engine can cook, else the texture set's size + pub fn size(self, set: u32) -> u32 { + let size = match self { + CookResolution::Relative(factor) => { + let factor = factor.clamp(*Self::FACTORS.start(), *Self::FACTORS.end()); + if factor >= 0 { set.saturating_mul(1 << factor) } else { set >> factor.unsigned_abs() } + } + CookResolution::Fixed(size) => size, + }; + if Self::cookable(size) { size } else { set } + } + + /// Whether maps may be cooked `size` pixels across + pub fn cookable(size: u32) -> bool { + size.is_power_of_two() && (MIN_RESOLUTION..=MAX_RESOLUTION).contains(&size) + } +} + +#[cfg(test)] +mod tests { + use super::CookResolution; + + #[test] + fn sizes_follow_the_texture_set_and_stay_cookable() { + assert_eq!(CookResolution::TEXTURE_SET.size(2048), 2048); + assert_eq!(CookResolution::Relative(-1).size(2048), 1024); + assert_eq!(CookResolution::Relative(2).size(1024), 4096); + assert_eq!(CookResolution::Relative(3).size(2048), 2048, "16384 is past the largest cook"); + assert_eq!(CookResolution::Relative(i8::MIN).size(1024), 128); + assert_eq!(CookResolution::Fixed(512).size(2048), 512); + assert_eq!(CookResolution::Fixed(300).size(2048), 2048); + assert_eq!(CookResolution::Fixed(u32::MAX).size(2048), 2048); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 34664b03..1f8f731d 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -710,6 +710,9 @@ pub struct Fill { /// Set when the sources are maps cooked from a MaterialCraft material. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option>, + /// The built-in material (shelf id) the sources were set from as one whole material; cleared when a channel's source changes on its own + #[serde(default, skip_serializing_if = "Option::is_none")] + pub material: Option, } /// A MaterialCraft material behind a fill (from a `.mcmat` portable material): its channel @@ -730,6 +733,22 @@ pub struct MaterialLink { pub inputs: Vec, /// Size the maps were cooked at (pixels across). pub size: u32, + /// Size to cook at; `None` cooks at the texture set's resolution + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resolution: Option, + /// The output a channel reads, where it is not the output named like the channel + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub mapping: BTreeMap, + /// The image resource of each output of the last cook, by output id. Empty in projects saved before channels could be mapped: there each channel's source is its own output + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub outputs: BTreeMap, +} + +impl MaterialLink { + /// The output channel `c` reads + pub fn output_of(&self, c: Channel) -> &str { + self.mapping.get(&c).map_or(c.id(), String::as_str) + } } /// An exposed input of a linked material. Values keep MaterialCraft's typed form, @@ -767,6 +786,22 @@ impl Fill { pub fn source(&self, c: Channel) -> Source { self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c)) } + + /// The image resource of each output of the linked material's last cook, by output id (empty without a link). Links saved before channels could be mapped list their channels' own outputs + pub fn link_outputs(&self) -> BTreeMap { + let Some(link) = &self.link else { return BTreeMap::new() }; + if !link.outputs.is_empty() { + return link.outputs.clone(); + } + + self.sources + .iter() + .filter_map(|(c, s)| match s { + Source::Image { name, .. } => Some((link.output_of(*c).to_string(), name.clone())), + _ => None, + }) + .collect() + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -1327,10 +1362,9 @@ impl Filter { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum EffectKind { - /// Painted grayscale (mask) or material (content) pixels keyed by the effect id. + /// Painted grayscale (mask) or material (content) pixels keyed by the effect id Paint, - /// A path sublayer: pixels keyed by the effect id like [`EffectKind::Paint`], but painted - /// only from its stored paths and repainted whenever one is added, edited or removed. + /// A path sublayer: pixels keyed by the effect id like [`EffectKind::Paint`], but painted only from its stored paths and repainted whenever one is added, edited or removed Path(Vec), /// A uniform or procedural grayscale fill. Fill { @@ -1625,6 +1659,33 @@ mod tests { assert!(d.apply(0.7).is_finite()); } + #[test] + fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { + let fills = [ + r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, + r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, + r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, + r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, + ]; + for saved in fills { + let loaded: Fill = serde_json::from_str(saved).unwrap(); + + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); + } + + let effects = [ + r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, + r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, + ]; + for saved in effects { + let loaded: EffectKind = serde_json::from_str(saved).unwrap(); + + assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); + } + } + #[test] fn hsl_adjust_shifts_hue_saturation_and_lightness() { let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4); @@ -1658,12 +1719,17 @@ mod tests { assert!(close(scan(0.4, 1.0), [0.0, 1.0, 1.0]), "full contrast is a step at the position"); assert!(close(scan(0.5, 1.0), [0.0, 1.0, 1.0]), "the position itself goes to white"); assert!(close(scan(0.7, 0.5), [0.0, 0.1, 0.9])); + let range = |range, position| Filter::HistogramRange { range, position }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(range(1.0, 0.3), [0.2, 0.5, 0.9]) && close(range(0.0, 0.3), [0.3; 3])); assert!(close(range(0.5, 0.5), [0.35, 0.5, 0.7])); + let shift = |offset| Filter::HistogramShift { offset }.point(c, [0.0, 0.5, 1.0]).unwrap(); + assert!(close(shift(0.0), [0.0, 0.5, 1.0]), "no offset keeps white white"); assert!(close(shift(0.25), [0.25, 0.75, 0.25]) && close(shift(-0.25), [0.75, 0.25, 0.75])); + let cb = Filter::ColorBalance { shadows: [0.2, 0.0, 0.0], midtones: [0.0; 3], highlights: [0.0, 0.0, 0.2] }; assert!(cb.point(c, [0.05; 3]).unwrap()[0] > 0.2 && cb.point(c, [0.95; 3]).unwrap()[2] > 0.99); assert!(close(Filter::Invert.point(ChannelKind::Signed, [0.5; 3]).unwrap(), [-0.5; 3])); @@ -1721,7 +1787,6 @@ mod tests { generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); - generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); assert!(generator_layer.reads_anchor()); @@ -1767,33 +1832,6 @@ mod tests { } } - #[test] - fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { - let fills = [ - r#"{"sources":{"BaseColor":{"Uniform":[0.5,0.5,0.5]}},"projection":{"Uv":{"scale":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Planar":{"scale":2.0,"axis":2,"offset":[0.0,1.0,0.0]}}}"#, - r#"{"sources":{},"projection":{"Spherical":{"scale":1.0}}}"#, - r#"{"sources":{},"projection":{"Cylindrical":{"scale":1.0,"axis":1}}}"#, - r#"{"sources":{},"projection":{"Decal":{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":1.0}}}"#, - ]; - for saved in fills { - let loaded: Fill = serde_json::from_str(saved).unwrap(); - - assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "a fill saves as it was saved"); - } - - let effects = [ - r#"{"Fill":{"source":{"Uniform":[0.5,0.5,0.5]},"projection":{"Triplanar":{"scale":1.0,"sharpness":0.5,"offset":[0.0,0.0,0.0]}}}}"#, - r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, - ]; - for saved in effects { - let loaded: EffectKind = serde_json::from_str(saved).unwrap(); - - assert_eq!(serde_json::to_string(&loaded).unwrap(), saved, "an effect saves as it was saved"); - } - } - #[test] fn procedural_kinds_parse_labels_and_saved_names() { for kind in ProceduralKind::ALL { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index be8338bc..1c877b7b 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,12 +12,14 @@ pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod cook_resolution; pub mod depth_culling; mod env_alignment; pub mod fill_symmetry; pub mod layer; pub mod project; pub mod projector; +pub mod randomized_seed; mod saved_decal; mod saved_projection; mod shadow_mode; @@ -37,6 +39,7 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use cook_resolution::CookResolution; pub use depth_culling::DepthCulling; pub use fill_symmetry::FillSymmetry; pub use layer::{ @@ -46,10 +49,11 @@ pub use layer::{ TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, UvTransform, UvWrap, gradient, hsl_adjust, per_unit, }; pub use project::{ - AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, - Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, + AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, EnvAlignment, FORMAT_VERSION, MAX_RESOLUTION, MAX_SWATCHES, MIN_RESOLUTION, NormalFormat, + NormalMixing, Project, ShadowMode, TANGENT_BENT_NORMAL_VERSION, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, }; pub use projector::Projector; +pub use randomized_seed::RandomizedSeed; pub use shape_crop::ShapeCrop; pub use symmetry_kind::SymmetryKind; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 7b6c92c2..df5aa54a 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -15,6 +15,9 @@ pub const FORMAT_VERSION: u32 = 3; /// First format whose baked bent normal maps are in tangent space pub const TANGENT_BENT_NORMAL_VERSION: u32 = 3; +/// Most colour swatches a project keeps +pub const MAX_SWATCHES: usize = 64; + /// Maximum group nesting (also bounds recursion over hostile project files) pub const MAX_DEPTH: usize = 16; @@ -439,6 +442,9 @@ pub struct Project { /// Saved and imported cameras (the viewport's default camera is not in the list). #[serde(default)] pub cameras: Vec, + /// The project's colour swatches (linear RGB), in the order they were added; projects without any save none + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub swatches: Vec<[f32; 3]>, } impl Project { @@ -455,6 +461,7 @@ impl Project { next_id: 1, display: DisplaySettings::default(), cameras: Vec::new(), + swatches: Vec::new(), } } @@ -757,17 +764,23 @@ mod tests { let gid = p.alloc_id(); let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET); p.insert_layer(0, g, Some(a), false).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]); + p.move_above(b, Some(gid), true).unwrap(); + assert_eq!(p.texture_sets[0].stack, vec![a, gid]); assert_eq!(p.layer(gid).unwrap().children(), &[b]); assert_eq!(p.locate(b), Some((0, Some(gid), 0))); assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself"); + p.validate().unwrap(); let removed = p.remove_layer(gid).unwrap(); + assert_eq!(removed, vec![gid, b]); assert_eq!(p.texture_sets[0].stack, vec![a]); assert!(p.layer(b).is_err()); + p.validate().unwrap(); } @@ -853,15 +866,18 @@ mod tests { let a = p.insert_layer(0, a, None, false).unwrap(); let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]); let inst = p.insert_layer(1, inst, None, false).unwrap(); + assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a)); assert_eq!(p.sets_drawing(a), vec![0, 1]); assert_eq!(p.sets_drawing(inst), vec![1]); + p.validate().unwrap(); - // A folder holding an instance of itself draws itself. + // A folder holding an instance of itself draws itself let gid = p.alloc_id(); p.insert_layer(1, Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &[]), None, false).unwrap(); let loop_id = p.alloc_id(); p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap(); + assert_eq!(p.instance_cycle(), Some(loop_id)); assert!(p.validate().is_err()); assert!(p.content_layer(LayerId(999)).is_none()); diff --git a/crates/core/src/randomized_seed.rs b/crates/core/src/randomized_seed.rs new file mode 100644 index 00000000..222fe9df --- /dev/null +++ b/crates/core/src/randomized_seed.rs @@ -0,0 +1,14 @@ +//! One seed a folder's Randomize seeds changed, kept on the folder so its Contents reset can put it back + +use serde::{Deserialize, Serialize}; + +use crate::layer::LayerId; + +/// A seed inside a folder that the folder's Randomize seeds changed: the `index`-th seed of layer `layer` (its fill's, then its content and mask effects', in stack order) went from `before` to `after` +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RandomizedSeed { + pub layer: LayerId, + pub index: u32, + pub before: u32, + pub after: u32, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 32451af5..3692499c 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -111,6 +111,7 @@ pub fn command_specs() -> &'static [CommandSpec] { let mut v = Vec::new(); v.extend(crate::view_cmds::edit_specs()); v.extend(crate::layer_cmds::specs()); + v.extend(crate::fill_material_cmds::specs()); v.extend(crate::fill_reset_cmds::specs()); v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); @@ -124,6 +125,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::view_cmds::specs()); v.extend(crate::solo::specs()); v.extend(crate::camera_cmds::specs()); + v.extend(crate::swatch_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); v.extend(crate::meshmap_cmds::specs()); diff --git a/crates/engine/src/fill_alpha.rs b/crates/engine/src/fill_alpha.rs new file mode 100644 index 00000000..3ce4f6af --- /dev/null +++ b/crates/engine/src/fill_alpha.rs @@ -0,0 +1,65 @@ +//! A library alpha as a fill source: the source picker's Alphas put the alpha's picture in the project as an image resource the channel reads + +use std::sync::Arc; + +use texturecraft_paint::alphas::{self, LibraryAlpha}; + +use crate::resource_cmds::decoded; +use crate::{EngineError, Result, Session}; + +/// Resource names of library alphas start with this, so the picker and the slot can tell them from imported images +const PREFIX: &str = "alpha_"; +/// Resource names of library alphas end with this: they are stored as PNG +const EXTENSION: &str = ".png"; +/// Samples per pixel side when the alpha is rendered, for smooth edges +const SUPERSAMPLING: usize = 2; + +/// The resource name a library alpha takes in a project +pub fn resource_name(alpha: &LibraryAlpha) -> String { + texturecraft_formats::sanitize_resource_name(&format!("{PREFIX}{}{EXTENSION}", alpha.id)) +} + +/// The library alpha resource `name` holds, if it is one (library ids are safe resource names already, so a name is matched without building one) +pub fn library_alpha_of(name: &str) -> Option<&'static LibraryAlpha> { + let id = name.strip_prefix(PREFIX)?.strip_suffix(EXTENSION)?; + alphas::library().iter().find(|alpha| alpha.id == id) +} + +impl Session { + /// Puts library alpha `alpha` in the project as an image resource unless it is there already, inside the caller's edit; returns its name + pub(crate) fn add_library_alpha(&mut self, alpha: &LibraryAlpha) -> Result { + let name = resource_name(alpha); + if self.doc.resources.contains_key(&name) { + return Ok(name); + } + + let bytes = png(alpha)?; + let image = texturecraft_formats::decode_image(&bytes).map_err(|error| EngineError::Other(format!("{name}: {error}")))?; + self.doc.resources.insert(name.clone(), Arc::new(bytes)); + self.images.insert(name.clone(), decoded(image)); + Ok(name) + } +} + +/// The alpha's picture as a 16-bit grayscale PNG at the library's base size +fn png(alpha: &LibraryAlpha) -> Result> { + let size = alphas::BASE; + let side = u32::try_from(size).map_err(|_| EngineError::Other("alpha size out of range".into()))?; + texturecraft_formats::mcmat::mesh_map_png(side, 1, &alpha.render(size, SUPERSAMPLING)) + .map_err(|error| EngineError::Other(format!("alpha {}: {error}", alpha.id))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_library_alpha_is_found_by_the_resource_name_it_takes() { + for alpha in alphas::library() { + let name = resource_name(alpha); + assert_eq!(name, format!("{PREFIX}{}{EXTENSION}", alpha.id), "the id is a safe resource name as it is"); + assert_eq!(library_alpha_of(&name).map(|found| &found.id), Some(&alpha.id)); + } + assert!(library_alpha_of("alpha_.png").is_none()); + } +} diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs new file mode 100644 index 00000000..2248e9b3 --- /dev/null +++ b/crates/engine/src/fill_material_cmds.rs @@ -0,0 +1,154 @@ +//! A fill's whole material: set every channel of a fill layer or content fill effect from one built-in material at once + +use std::collections::BTreeMap; + +use serde_json::Value; +use texturecraft_core::{Channel, EffectKind, Fill, LayerKind, Project, Source}; + +use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::layer_cmds::{FillTarget, fill_mut, fill_target}; +use crate::materials::{Builder, MATERIALS, SmartMaterial, build, find}; +use crate::{EngineError, Result, Session, cmd}; + +/// The command [`set_material`] runs as +const CMD: &str = "layer.fill.material"; + +pub fn specs() -> Vec { + vec![cmd!( + "layer.fill.material", + "Set fill material", + [], + None, + "{layer? | effect?: content fill effect id, material: built-in material id (not a smart material) | null (back to the channels' defaults)} — sets every channel the material writes, turns those channels on and the others off; the projection stays", + has_layer, + set_material + )] +} + +/// The built-in materials a fill can hold whole: the plain ones (smart materials are folders of layers) +pub fn whole_materials() -> impl Iterator { + MATERIALS.iter().filter(|material| !material.smart) +} + +fn set_material(s: &mut Session, p: &Value) -> Result { + let target = fill_target(s, p, CMD)?; + let material = material_param(p)?; + let set = target_set(s, target)?; + if holds(s, target, set, material)? { + return Ok(Value::Null); + } + + let Some(found) = material else { + s.edit("Clear fill material", |s| { + let edited = fill_mut(s, target)?; + edited.material = None; + match target { + // A fill effect changes a channel while it has a source: its channels stay on, at their defaults + FillTarget::Effect(_) => edited.sources.iter_mut().for_each(|(channel, source)| *source = Source::uniform_of(*channel)), + } + Ok(()) + })?; + return Ok(Value::Null); + }; + + s.edit(&format!("Set fill material {}", found.label), |s| { + let sources = material_sources(&mut s.doc.project, set, found)?; + let edited = fill_mut(s, target)?; + edited.sources = sources; + edited.material = Some(found.id.to_string()); + let written: Vec = edited.sources.keys().copied().collect(); + if let FillTarget::Layer(id) = target { + let layer = s.doc.project.layer_mut(id)?; + layer.channels.retain(|channel, _| written.contains(channel)); + for channel in written { + layer.channels.entry(channel).or_default(); + } + } + Ok(()) + })?; + Ok(Value::Null) +} + +/// The `material` param: a plain built-in material, or `None` for null +fn material_param(p: &Value) -> Result> { + match p.get("material") { + Some(Value::Null) => Ok(None), + Some(_) => { + let id = strp(p, "material").ok_or_else(|| bad(CMD, "`material` is a material id or null"))?; + let found = find(id).ok_or_else(|| bad(CMD, format!("unknown material `{id}`")))?; + if found.smart { + return Err(bad(CMD, format!("`{}` is a smart material (a folder of layers): add it from the shelf with material.apply", found.id))); + } + + Ok(Some(found)) + } + None => Err(bad(CMD, "`material` is required: a material id or null")), + } +} + +/// Whether the fill at `target` (in texture set `set`) already holds `material` whole (or, for `None`, no material and its channels' defaults), so setting it changes nothing +fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMaterial>) -> Result { + let (fill, layer_channels) = match target { + FillTarget::Layer(id) => { + let layer = s.doc.project.layer(id)?; + let LayerKind::Fill(fill) = &layer.kind else { return Err(bad(CMD, "not a fill layer")) }; + (fill, Some(&layer.channels)) + } + FillTarget::Effect(id) => match s.doc.project.effect(id).map(|(_, found)| &found.kind) { + Some(EffectKind::Material(fill)) => (fill, None), + _ => return Err(bad(CMD, "not a content fill effect")), + }, + }; + if fill.material.as_deref() != material.map(|found| found.id) { + return Ok(false); + } + + // A channel set on its own clears the material; one turned off or back on keeps it, so an effect (whose sources are its channels) compares them whole + Ok(match (material, layer_channels) { + (Some(_), Some(channels)) => channels.len() == fill.sources.len() && fill.sources.keys().all(|channel| channels.contains_key(channel)), + (Some(found), None) => fill.sources == material_sources(&mut s.doc.project.clone(), set, found)?, + (None, Some(_)) => fill.sources.is_empty(), + (None, None) => fill.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), + }) +} + +/// The texture set the fill `target` paints in, whichever set is selected +fn target_set(s: &Session, target: FillTarget) -> Result { + let owner = match target { + FillTarget::Layer(id) => id, + }; + s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) +} + +/// The sources `material` writes in texture set `set`: its fill's channels the set has (the built fill's ids are taken from `project`) +fn material_sources(project: &mut Project, set: usize, material: &SmartMaterial) -> Result> { + let channels = project.texture_set(set)?.channel_list(); + let fill = whole_fill(project, material, &channels)?; + Ok(fill.sources.into_iter().filter(|(channel, _)| channels.contains(channel)).collect()) +} + +/// The one unmasked fill a plain material is made of +fn whole_fill(project: &mut Project, material: &SmartMaterial, channels: &[Channel]) -> Result { + let layers = build(&mut Builder { p: project, channels: channels.to_vec() }, material.id)?; + match <[_; 1]>::try_from(layers) { + Ok([layer]) if layer.mask.is_none() => match layer.kind { + LayerKind::Fill(fill) => Ok(fill), + _ => Err(EngineError::Other(format!("material `{}` is not a fill", material.id))), + }, + _ => Err(EngineError::Other(format!("material `{}` is more than one fill", material.id))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_whole_material_is_one_unmasked_fill() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let channels = s.doc.project.texture_set(s.ts()).map(|set| set.channel_list()).unwrap_or_default(); + for material in whole_materials() { + assert!(whole_fill(&mut s.doc.project, material, &channels).is_ok(), "{}", material.id); + } + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index f1c82a32..3f16e843 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -47,6 +47,9 @@ fn fill_json(fill: &Fill) -> Value { if let Some(link) = &fill.link { out["link"] = json!(link); } + if let Some(material) = &fill.material { + out["material"] = json!(material); + } out } @@ -236,6 +239,7 @@ pub fn session(session: &Session) -> Value { "bakePreview": crate::bake_preview::preview_json(session), "camera": crate::view_cmds::camera_json(session), "display": session.doc.project.display, + "swatches": session.doc.project.swatches, "history": { "undo": session.undo_label(), "redo": session.redo_label(), "depth": session.history_labels().len() }, "memoryBytes": session.memory().total(), "pendingTiles": session.pending_tiles(), diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 86fd4a55..a490b39a 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -512,11 +512,18 @@ fn blending_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Which fill `layer.fill.*` edits: a fill layer's (`layer`), a content fill effect's (`effect`) or a mask fill effect's (`effect`: one grayscale source, no channels or material) +#[derive(Clone, Copy)] +pub(crate) enum FillTarget { + Layer(LayerId), + Effect(LayerId), + Mask(LayerId), +} + pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result { match u64p(p, "effect").map(LayerId) { - Some(e) => match s.doc.project.effect(e) { - Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)), - _ => Err(bad(cmd, format!("{} is not a content fill effect", e.0))), + Some(effect) => match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { + Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), }, None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)), } @@ -544,6 +551,7 @@ pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut fn fill_set(session: &mut Session, params: &Value) -> Result { let target = fill_target(session, params, FILL_SET)?; + let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; // `solo`: this channel on, every other one off @@ -557,10 +565,15 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { } let source = fill_source_from(session, params, (target, channel), normal_format)?; + // A library alpha that became the source joins the project's images + let library_alpha = match &source { + Some(Source::Image { name, .. }) => crate::fill_alpha::library_alpha_of(name).filter(|_| strp(params, "image").is_none()), + _ => None, + }; if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp { return Err(bad( FILL_SET, - "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", + "give `color`, `value`, `procedural`, `image`, `alpha`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", )); } @@ -571,6 +584,9 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { // Changing only the normal format or gradient stops leaves the layer channel on or off let touches_channel = source.is_some() || enabled.is_some(); session.edit("Set fill", |session| { + if let Some(alpha) = library_alpha { + session.add_library_alpha(alpha)?; + } let fill = fill_mut(session, target)?; // `normalFormat` alone: the convention of the channel's image @@ -581,6 +597,11 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { } } + // A channel set on its own (its source or its gradient map): the sources are no longer one whole material + if source.is_some() || colors.is_some() || init_ramp { + fill.material = None; + } + let current = fill.sources.get(&channel); let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors }; let source = with_ramp(channel, current, source, colors)?; @@ -658,6 +679,11 @@ fn fill_source_from( return Ok(Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })); } + if let Some(name) = strp(params, "alpha") { + let alpha = alphas::find(name).ok_or_else(|| bad(FILL_SET, format!("unknown alpha `{name}`")))?; + return Ok(Some(Source::Image { name: crate::fill_alpha::resource_name(alpha), normal_format: normal_format.unwrap_or_default() })); + } + if let Some(anchor) = u64p(params, "anchor") { let reader = match target { FillTarget::Layer(id) => Some(id), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4d25b237..a8173320 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,7 +17,9 @@ pub mod commands; pub mod decal_cmds; pub mod effect_clipboard; pub mod file_cmds; +pub mod fill_alpha; pub mod fill_hit_test; +pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; pub mod filter_lib; @@ -66,6 +68,7 @@ mod session_log; pub mod set_cmds; pub mod smart_masks; mod solo; +pub mod swatch_cmds; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 5931761e..8a1c2f77 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -46,11 +46,16 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, if let LayerKind::Fill(fill) = &layer.kind { out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); - out.extend(fill.link.as_ref().map(|link| link.package.clone())); + if let Some(link) = &fill.link { + out.push(link.package.clone()); + out.extend(link.outputs.values().cloned()); + } } + for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.kind.images_read().map(str::to_string)); } + for child in layer.children() { images_used(project, *child, out, depth + 1); } diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 5b8c1c7d..287c7cc8 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -787,6 +787,7 @@ pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f3 id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None }), + LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, sampling: Default::default(), link: None, material: None }), &channels, ) } @@ -814,35 +815,44 @@ pub fn apply(s: &mut Session, id: &str) -> Result { /// [`apply`] at `place` (one undo step). pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { - let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?; - let label = format!("Add {}", m.label); + let material = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?; + let label = format!("Add {}", material.label); s.edit(&label, |s| { let ts = s.ts(); let mut channels = s.doc.project.texture_set(ts)?.channel_list(); // Lobe channels the material uses join the texture set (other channels it lacks are skipped) - let missing: Vec = Channel::LOBES.into_iter().filter(|c| !channels.contains(c)).collect(); - let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, m.id)?; - for c in missing.into_iter().filter(|c| layers.iter().any(|l| l.channels.contains_key(c))) { - crate::set_cmds::add_channel(s, ts, c)?; - channels.push(c); + let missing: Vec = Channel::LOBES.into_iter().filter(|channel| !channels.contains(channel)).collect(); + let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, material.id)?; + for channel in missing.into_iter().filter(|channel| layers.iter().any(|layer| layer.channels.contains_key(channel))) { + crate::set_cmds::add_channel(s, ts, channel)?; + channels.push(channel); } + let top = if layers.len() == 1 { - let l = layers.into_iter().next().ok_or_else(|| EngineError::Other("empty material".into()))?; - crate::layer_cmds::insert_selected(s, l)? + let mut layer = layers.into_iter().next().ok_or_else(|| EngineError::Other("empty material".into()))?; + + // A plain material's fill remembers it, so its Material side names it + if !material.smart + && let LayerKind::Fill(fill) = &mut layer.kind + { + fill.material = Some(material.id.to_string()); + } + + crate::layer_cmds::insert_selected(s, layer)? } else { - let gid = s.doc.project.alloc_id(); - let mut group = Layer::new(gid, m.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); - for c in group.channels.values_mut() { - *c = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; + let folder_id = s.doc.project.alloc_id(); + for blend in folder.channels.values_mut() { + *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; } - let gid = crate::layer_cmds::insert_selected(s, group)?; - for l in layers { - s.doc.project.insert_layer(ts, l, Some(gid), true)?; + let folder_id = crate::layer_cmds::insert_selected(s, folder)?; + for layer in layers { + s.doc.project.insert_layer(ts, layer, Some(folder_id), true)?; } - s.select_one(ts, gid); - gid + s.select_one(ts, folder_id); + folder_id }; + place.apply(s, top)?; Ok(top) }) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 62010b50..42909bd9 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -665,6 +665,14 @@ impl Session { /// Material picker: copy the material under the cursor into the tool's paint values pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result> { + let picked = self.color_at(screen, viewport)?; + self.tool.values.extend(&picked); + self.tool.material = None; + Ok(picked) + } + + /// The composited value of every channel on the surface under `screen`, changing nothing (an eyedropper's read) + pub fn color_at(&self, screen: Vec2, viewport: Vec2) -> Result> { let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; let texture_set = self.texture_set_of_material(hit.material).unwrap_or(self.ts()); let cache = self.caches.get(texture_set).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; @@ -674,10 +682,7 @@ impl Session { let tile = (x / texturecraft_texel::TILE, y / texturecraft_texel::TILE); let source = self.document_composite(texture_set, &[tile]).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; - let picked: BTreeMap<_, _> = source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect(); - self.tool.values.extend(&picked); - self.tool.material = None; - Ok(picked) + Ok(source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect()) } /// The stroke canvas alpha of the active stroke (for overlays and tests). diff --git a/crates/engine/src/swatch_cmds.rs b/crates/engine/src/swatch_cmds.rs new file mode 100644 index 00000000..2237f7db --- /dev/null +++ b/crates/engine/src/swatch_cmds.rs @@ -0,0 +1,48 @@ +//! The project's colour swatches: the row under the colour picker, saved with the project + +use serde_json::{Value, json}; +use texturecraft_core::MAX_SWATCHES; + +use crate::commands::{CommandSpec, always, bad, color_param, u64p}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!("swatch.list", "Swatches", [], None, "{}", always, |s, _| Ok(list(s))), + cmd!("swatch.add", "Add swatch", [], None, "{color: [r, g, b] (linear 0..1) | \"#rrggbb\"}", always, add), + cmd!("swatch.remove", "Remove swatch", [], None, "{index}", has_swatches, remove), + ] +} + +fn has_swatches(s: &Session) -> std::result::Result<(), String> { + if s.doc.project.swatches.is_empty() { Err("the project has no swatches".into()) } else { Ok(()) } +} + +fn list(s: &Session) -> Value { + json!({ "swatches": s.doc.project.swatches }) +} + +/// Adds `color` (clamped to 0..1) after the project's last swatch +fn add(s: &mut Session, p: &Value) -> Result { + let color = color_param("swatch.add", p, "color")?.ok_or_else(|| bad("swatch.add", "`color` is required: [r, g, b] or \"#rrggbb\""))?; + if s.doc.project.swatches.len() >= MAX_SWATCHES { + return Err(bad("swatch.add", format!("a project keeps at most {MAX_SWATCHES} swatches; remove one first"))); + } + + let color = color.map(|part| part.clamp(0.0, 1.0)); + s.edit("Add swatch", |s| { + s.doc.project.swatches.push(color); + Ok(json!({ "index": s.doc.project.swatches.len() - 1, "color": color })) + }) +} + +fn remove(s: &mut Session, p: &Value) -> Result { + let index = u64p(p, "index") + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < s.doc.project.swatches.len()) + .ok_or_else(|| bad("swatch.remove", "`index` must name a swatch (see swatch.list)"))?; + s.edit("Remove swatch", |s| { + let color = s.doc.project.swatches.remove(index); + Ok(json!({ "removed": color })) + }) +} diff --git a/crates/engine/tests/it/fill_alpha_source.rs b/crates/engine/tests/it/fill_alpha_source.rs new file mode 100644 index 00000000..6c3e7dd3 --- /dev/null +++ b/crates/engine/tests/it/fill_alpha_source.rs @@ -0,0 +1,66 @@ +//! A library alpha as a fill channel's source through `layer.fill.set {alpha}`: its picture becomes one image resource the channel reads + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; +use texturecraft_engine::fill_alpha::{library_alpha_of, resource_name}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{Session, execute}; + +fn fill() -> (Session, LayerId) { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + (session, layer) +} + +fn source(session: &Session, layer: LayerId, channel: Channel) -> Source { + match &session.doc.project.layer(layer).unwrap().kind { + LayerKind::Fill(fill) => fill.source(channel), + other => panic!("not a fill: {other:?}"), + } +} + +#[test] +fn an_alpha_becomes_the_channels_image_once_and_its_set_is_one_undo_step() { + let (mut session, layer) = fill(); + let scratches = alphas::find("scratches").unwrap(); + let name = resource_name(scratches); + let set = |session: &mut Session, channel: &str, alpha: &str| { + execute(session, "layer.fill.set", &json!({"layer": layer.0, "channel": channel, "alpha": alpha})).unwrap(); + }; + set(&mut session, "roughness", "Scratches"); + + assert_eq!(source(&session, layer, Channel::Roughness), Source::image(name.clone())); + assert!(session.doc.resources.contains_key(&name), "the alpha's picture is a project resource, so the project saves it"); + let image = session.images.get(&name).expect("the channel's image is decoded"); + assert_eq!((image.width, image.height), (alphas::BASE as u32, alphas::BASE as u32)); + assert_eq!(library_alpha_of(&name).map(|alpha| alpha.id.as_str()), Some("scratches"), "the slot can name the alpha it came from"); + assert!(library_alpha_of("scratches.png").is_none(), "an imported image is not a library alpha"); + + // One undo takes the source and the resource back together + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(source(&session, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); + assert!(!session.doc.resources.contains_key(&name), "undo takes the resource back with the source"); + + // The same alpha on a second channel reads the same resource + set(&mut session, "roughness", "Scratches"); + let count = session.doc.resources.len(); + set(&mut session, "metallic", "scratches"); + + assert_eq!(source(&session, layer, Channel::Metallic), Source::image(name.clone())); + assert_eq!(session.doc.resources.len(), count); +} + +#[test] +fn an_unknown_alpha_changes_nothing() { + let (mut session, layer) = fill(); + let before = session.doc.resources.len(); + assert!(execute(&mut session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "alpha": "no such alpha"})).is_err()); + + assert_eq!(source(&session, layer, Channel::Roughness), Source::uniform_of(Channel::Roughness)); + assert_eq!(session.doc.resources.len(), before); + + // No undo step either: the next undo takes back the added layer + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(session.doc.project.layer(layer).is_err(), "the refused set added no undo step"); +} diff --git a/crates/engine/tests/it/fill_whole_material.rs b/crates/engine/tests/it/fill_whole_material.rs new file mode 100644 index 00000000..b444a3fb --- /dev/null +++ b/crates/engine/tests/it/fill_whole_material.rs @@ -0,0 +1,155 @@ +//! A fill holding one whole built-in material: set, saved, cleared back to its channels' defaults, on a fill layer or a content fill effect + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind, Source}; +use texturecraft_engine::{Session, execute, geom::primitives}; + +fn session() -> Session { + Session::new_project("Whole material", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +fn layer(v: Value) -> u64 { + v["layer"].as_u64().unwrap() +} + +fn fill(s: &Session, id: u64) -> texturecraft_engine::core::Fill { + match &s.doc.project.layer(LayerId(id)).unwrap().kind { + LayerKind::Fill(fill) => fill.clone(), + _ => panic!("not a fill"), + } +} + +fn channels(s: &Session, id: u64) -> Vec { + s.doc.project.layer(LayerId(id)).unwrap().channels.keys().copied().collect() +} + +#[test] +fn a_fill_takes_one_whole_material_names_it_and_forgets_it_once_a_channel_is_set_alone() { + let mut s = session(); + let id = layer(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap()); + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "opacity", "value": 0.5})).unwrap(); + let projection = fill(&s, id).projection; + let saved: Value = serde_json::to_value(fill(&s, id)).unwrap(); + assert!(saved.get("material").is_none(), "a fill without a whole material saves as before"); + + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "copper_hammered"})).unwrap(); + let copper = fill(&s, id); + assert_eq!(copper.material.as_deref(), Some("copper_hammered")); + assert!(matches!(copper.source(Channel::BaseColor), Source::Procedural { .. }), "the material's base colour"); + assert_eq!(copper.source(Channel::Metallic), Source::Uniform([1.0; 3])); + assert_eq!(channels(&s, id), [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height], "the material's channels on, opacity off"); + assert_eq!(copper.projection, projection, "the fill keeps its projection"); + assert_eq!(execute(&mut s, "project.inspect", &json!({})).unwrap().to_string().matches("\"material\":\"copper_hammered\"").count(), 1); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(fill(&reopened, id).material.as_deref(), Some("copper_hammered"), "saved with the project"); + + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(fill(&s, id).material, None, "one undo step"); + assert_eq!(fill(&s, id).source(Channel::BaseColor), Source::Uniform([1.0, 0.0, 0.0])); + execute(&mut s, "edit.redo", &json!({})).unwrap(); + + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "metallic", "enabled": false})).unwrap(); + assert!(fill(&s, id).material.is_some(), "turning a channel off keeps the material"); + execute(&mut s, "layer.fill.set", &json!({"layer": id, "channel": "roughness", "value": 0.3})).unwrap(); + assert_eq!(fill(&s, id).material, None, "a channel set on its own is no longer the whole material"); + + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "Steel"})).unwrap(); + execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": null})).unwrap(); + let cleared = fill(&s, id); + assert_eq!((cleared.material, cleared.sources.len()), (None, 0), "null: back to the channels' defaults"); + + // A content fill effect takes the material too + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": "gold_polished"})).unwrap(); + let inspect = execute(&mut s, "project.inspect", &json!({})).unwrap().to_string(); + assert!(inspect.contains("\"material\":\"gold_polished\"")); + + // The shelf names a plain material's fill; a smart one is no whole material + let shelf = layer(execute(&mut s, "material.apply", &json!({"material": "brass"})).unwrap()); + assert_eq!(fill(&s, shelf).material.as_deref(), Some("brass")); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "steel_painted_worn"})).is_err(), "smart"); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": "nope"})).is_err()); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id})).is_err(), "material is required"); + assert!(execute(&mut s, "layer.fill.material", &json!({"layer": id, "material": 7})).is_err()); +} + +#[test] +fn a_fill_in_another_texture_set_takes_the_channels_of_its_own_set() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + let other = layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + s.doc.project.texture_sets[1].channels.retain(|(channel, _)| *channel != Channel::Metallic); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + + execute(&mut s, "layer.fill.material", &json!({"layer": other, "material": "copper_hammered"})).unwrap(); + + assert!(!channels(&s, other).contains(&Channel::Metallic), "set 1 has no metallic channel: {:?}", channels(&s, other)); + assert!(channels(&s, other).contains(&Channel::BaseColor)); +} + +/// The fill of content fill effect `effect` +fn effect_fill(s: &Session, effect: u64) -> texturecraft_engine::core::Fill { + match &s.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Material(fill) => fill.clone(), + other => panic!("not a content fill: {other:?}"), + } +} + +#[test] +fn clearing_a_content_fill_effects_material_lays_its_channels_defaults() { + let mut s = crate::filter_support::facing_session(); + execute(&mut s, "layer.add.fill", &json!({"roughness": 0.2})).unwrap(); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": "gold_polished"})).unwrap(); + let material_channels: Vec = effect_fill(&s, effect).sources.keys().copied().collect(); + + execute(&mut s, "layer.fill.material", &json!({"effect": effect, "material": null})).unwrap(); + + let cleared = effect_fill(&s, effect); + assert_eq!(cleared.material, None); + assert_eq!(cleared.sources.keys().copied().collect::>(), material_channels, "the material's channels stay on"); + assert!(cleared.sources.iter().all(|(channel, source)| *source == Source::uniform_of(*channel)), "at their defaults"); + let roughness = crate::filter_support::center(&mut s, Channel::Roughness)[0]; + assert!((roughness - Channel::Roughness.default_value()[0]).abs() < 0.01, "the effect still lays the default roughness: {roughness}"); +} + +#[test] +fn setting_the_material_a_fill_already_holds_adds_no_undo_step() { + let mut s = session(); + let id = layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + let steps = s.history_labels().len(); + + for target in [json!({"layer": id}), json!({"effect": effect})] { + for material in [json!("gold_polished"), Value::Null] { + let mut params = target.clone(); + params["material"] = material; + execute(&mut s, "layer.fill.material", ¶ms).unwrap(); + execute(&mut s, "layer.fill.material", ¶ms).unwrap(); + } + } + + assert_eq!(s.history_labels().len(), steps + 4, "one step per change, none for a repeat"); +} + +#[test] +fn setting_the_material_again_brings_back_a_content_fill_effects_channel_turned_off() { + let mut s = session(); + layer(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()); + let effect = execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap()["effect"].as_u64().unwrap(); + let gold = json!({"effect": effect, "material": "gold_polished"}); + execute(&mut s, "layer.fill.material", &gold).unwrap(); + let whole = effect_fill(&s, effect).sources; + + for off_and_on in [vec![false], vec![false, true]] { + for enabled in off_and_on { + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "roughness", "enabled": enabled})).unwrap(); + } + assert_ne!(effect_fill(&s, effect).sources, whole, "roughness is off or back at its default"); + + execute(&mut s, "layer.fill.material", &gold).unwrap(); + + assert_eq!(effect_fill(&s, effect).sources, whole, "the material's roughness is back"); + } +} diff --git a/crates/engine/tests/it/filter_support.rs b/crates/engine/tests/it/filter_support.rs new file mode 100644 index 00000000..eb585ba3 --- /dev/null +++ b/crates/engine/tests/it/filter_support.rs @@ -0,0 +1,44 @@ +//! What the filter tests share: their sessions, adding, setting and refusing a filter, and reading the composite + +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; + +/// The texture set side the filter tests paint on +pub(crate) const SIZE: u32 = 128; + +/// The viewport's side in pixels when a test reads the texel under its center +const VIEWPORT_SIDE: f32 = 400.0; + +/// A sphere on a `SIZE` texture set, rendered once +pub(crate) fn session() -> Session { + let mut s = sized_session(SIZE); + s.update(); + s +} + +/// A sphere on a texture set of side `size`, not yet rendered +pub(crate) fn sized_session(size: u32) -> Session { + Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, size).unwrap() +} + +/// A session whose camera looks straight at the sphere, so the viewport center reads one texel (see [`center`]) +pub(crate) fn facing_session() -> Session { + let mut s = session(); + s.viewport = Vec2::splat(VIEWPORT_SIDE); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// The UV under the viewport center +pub(crate) fn center_uv(s: &mut Session) -> Vec2 { + s.update(); + s.pick(Vec2::splat(VIEWPORT_SIDE / 2.0), s.viewport).unwrap().uv +} + +/// Composited value of `channel` under the viewport center +pub(crate) fn center(s: &mut Session, channel: Channel) -> [f32; 3] { + let uv = center_uv(s); + s.caches[0].composite.value(channel, (uv.x * SIZE as f32) as u32, (uv.y * SIZE as f32) as u32) +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 11a5b7f0..bae8985c 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,9 +13,12 @@ mod content_effects; mod export_colour_space; mod export_file_types; mod export_maps; +mod fill_alpha_source; mod fill_patterns; mod fill_projections; mod fill_sampling; +mod fill_whole_material; +mod filter_support; mod filter_swap; mod filters; mod frame_selection; @@ -39,6 +42,7 @@ mod polygon_fill; mod project_recovery; mod sample; mod solo; +mod swatches; mod symmetry; mod thumbs; mod tile_generator; diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index ea361a89..d9052f04 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use texturecraft_engine::compose::BakedMaps; -use texturecraft_engine::core::{BakedMap, Channel, LayerId, LayerKind, NormalFormat, Source}; +use texturecraft_engine::core::{BakedMap, Channel, CookResolution, LayerId, LayerKind, NormalFormat, Source}; use texturecraft_engine::formats::mcmat::mesh_map_png; use texturecraft_engine::geom::primitives; use texturecraft_engine::link_cmds::{CookedMap, CookedMaterial, LinkMemoryBudget}; @@ -187,6 +187,88 @@ fn parameters_are_checked_stored_and_recooked_in_one_undo_step() { assert_eq!(link(&session, id).params[0].value, json!({"t": "float", "v": 1.0})); } +/// A channel can read another output of the material; the choice survives re-cooks, undo and saving, and links saved before it existed map their channels too +#[test] +fn channels_read_the_output_they_are_mapped_to() { + let mut s = session(); + let id = install(&mut s); + let map = |s: &mut Session, output: &str| execute(s, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": output})); + assert!(map(&mut s, "curvature").is_err(), "outputs the material lacks are errors"); + assert!(execute(&mut s, "material.link.map", &json!({"layer": id.0, "output": "roughness"})).is_err()); + + // Roughness reads the ambient occlusion output (all white) + map(&mut s, "ambientOcclusion").unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); + assert_eq!(link(&s, id).output_of(Channel::Roughness), "ambientOcclusion"); + let saved = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(link(&saved, id), link(&s, id)); + s.apply_link_cook(id, &cooked(0.75, 0.5), false).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3, "a re-cook keeps the mapping"); + map(&mut s, "roughness").unwrap(); + assert!((roughness(&mut s) - 0.75).abs() < 2e-3); + assert!(link(&s, id).mapping.is_empty(), "a channel's own output is no mapping"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!((roughness(&mut s) - 1.0).abs() < 2e-3); + + // A link saved before mappings (no outputs list) maps from its channels' maps + let mut old = session(); + let id = install(&mut old); + if let LayerKind::Fill(fill) = &mut old.doc.project.layer_mut(id).unwrap().kind { + let link = fill.link.as_mut().unwrap(); + link.outputs.clear(); + let saved = serde_json::to_value(&**link).unwrap(); + assert!(saved.get("outputs").is_none() && saved.get("mapping").is_none() && saved.get("resolution").is_none(), "{saved}"); + } + execute(&mut old, "material.link.map", &json!({"layer": id.0, "channel": "roughness", "output": "ambientOcclusion"})).unwrap(); + assert!((roughness(&mut old) - 1.0).abs() < 2e-3); + assert!(link(&old, id).outputs.contains_key("roughness"), "the unmapped output stays listed"); + let kept = old.doc.resources.len(); + execute(&mut old, "file.removeUnused", &Value::Null).unwrap(); + assert_eq!(old.doc.resources.len(), kept, "outputs no channel reads are kept"); +} + +/// The cook size: relative sizes follow the texture set, a fixed size is stored and cooked at +#[test] +fn materials_cook_at_their_picked_resolution() { + let mut s = session(); + let id = install(&mut s); + let size = |s: &Session| s.link_job(id, &serde_json::Map::new()).unwrap().size; + let pick = |s: &mut Session, mut size: Value| { + size["layer"] = json!(id.0); + size["cook"] = json!(false); + execute(s, "material.link.resolution", &size) + }; + assert_eq!(size(&s), 128); + pick(&mut s, json!({"fixed": 1024})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (Some(CookResolution::Fixed(1024)), 1024)); + pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(size(&s), 512); + let steps = s.history_labels().len(); + pick(&mut s, json!({"relative": 2})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "the size it already has adds no step"); + for bad in [ + json!({"fixed": 300}), + json!({"fixed": 64}), + json!({"fixed": 16384}), + json!({"relative": 4}), + json!({"relative": "x"}), + json!({}), + json!({"relative": 1, "fixed": 256}), + ] { + assert!(pick(&mut s, bad.clone()).is_err(), "{bad}"); + } + pick(&mut s, json!({"relative": 0})).unwrap(); + assert_eq!((link(&s, id).resolution, size(&s)), (None, 128)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&s), 512); + + // A hostile project's size falls back to the texture set's + if let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id).unwrap().kind { + fill.link.as_mut().unwrap().resolution = Some(CookResolution::Fixed(u32::MAX)); + } + assert_eq!(size(&s), 128); +} + #[test] fn duplicates_keep_their_maps_and_mesh_maps_feed_inputs() { let mut session = session(); diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 26fcb753..6c4be47f 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -80,44 +80,33 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { let fid = f["id"].as_str().unwrap(); let eid = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": fid, "target": "content"})).unwrap(), "effect"); let (owner, e) = s.doc.project.effect(eid).unwrap(); - assert_eq!(owner, layer); assert_eq!(e.name, f["label"].as_str().unwrap(), "named after the shelf entry"); assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|x| x.id == eid)); - execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); } - // A gradient map recolors the content; effect.set edits it and inspect shows it + // A gradient map recolors the content; effect.set edits it and inspect shows it. let gm = id(execute(&mut s, "effect.add.filter", &json!({"filter": "gradientMap", "target": "content", "colors": [[0, 0, 1], [0, 0, 1]]})).unwrap(), "effect"); let blue = at(&mut s, Channel::BaseColor, 200.0, 200.0); assert!(blue[2] > 0.95 && blue[0] < 0.05, "{before:?} -> {blue:?}"); - execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": ["#00ff00"]})).unwrap(); - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0)[1] > 0.95); assert!(execute(&mut s, "effect.set", &json!({"effect": gm.0, "colors": []})).is_err()); - let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); - assert!(inspect.contains("GradientMap"), "inspect shows filter parameters"); - execute(&mut s, "effect.remove", &json!({"effect": gm.0})).unwrap(); - // Posterize on the mask; its steps are clamped + // Posterize on the mask; its steps are clamped. let post = id(execute(&mut s, "effect.add.filter", &json!({"filter": "posterize", "levels": 3})).unwrap(), "effect"); execute(&mut s, "effect.set", &json!({"effect": post.0, "levels": 500})).unwrap(); - assert!(s.doc.project.layer(layer).unwrap().mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == post))); assert!(matches!(s.doc.project.effect(post).unwrap().1.kind, EffectKind::Filter(Filter::Posterize { levels }) if levels == 64.0)); - - // Material finishes fill the content's roughness and height + // Material finishes fill the content's roughness and height. let fin = id(execute(&mut s, "effect.add.filter", &json!({"filter": "MatFinish Hammered"})).unwrap(), "effect"); - assert!(s.doc.project.layer(layer).unwrap().content_effects.iter().any(|e| e.id == fin)); assert!(matches!(&s.doc.project.effect(fin).unwrap().1.kind, EffectKind::Material(f) if f.sources.contains_key(&Channel::Height))); assert!(execute(&mut s, "effect.add.filter", &json!({"filter": "nope"})).is_err()); - - // A directional blur, slope blur and warp composite without trouble on a sphere + // A directional blur, slope blur and warp composite without trouble on a sphere. for (fid, extra) in [ ("blurDirectional", json!({"radius": 40, "angle": 45})), ("slopeBlur", json!({"radius": 30})), @@ -133,7 +122,6 @@ fn filter_library_adds_every_filter_and_edits_its_parameters() { p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); execute(&mut s, "effect.add.filter", &p).unwrap(); } - assert!(at(&mut s, Channel::BaseColor, 200.0, 200.0).iter().all(|v| v.is_finite())); } diff --git a/crates/engine/tests/it/swatches.rs b/crates/engine/tests/it/swatches.rs new file mode 100644 index 00000000..6e6b026a --- /dev/null +++ b/crates/engine/tests/it/swatches.rs @@ -0,0 +1,36 @@ +use serde_json::json; +use texturecraft_engine::{Session, execute, geom::primitives}; + +fn session() -> Session { + Session::new_project("Swatches", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +#[test] +fn swatches_are_added_saved_with_the_project_removed_and_undone() { + let mut s = session(); + let plain = s.to_project_bytes().unwrap(); + let saved: serde_json::Value = serde_json::to_value(&s.doc.project).unwrap(); + assert!(saved.get("swatches").is_none(), "a project without swatches saves as before"); + + execute(&mut s, "swatch.add", &json!({"color": [0.8, 0.25, 0.07]})).unwrap(); + let added = execute(&mut s, "swatch.add", &json!({"color": [2.0, -1.0, 0.5]})).unwrap(); + assert_eq!(added["index"], 1); + assert_eq!(s.doc.project.swatches, vec![[0.8, 0.25, 0.07], [1.0, 0.0, 0.5]], "kept in order, clamped to 0..1"); + assert_eq!(execute(&mut s, "project.inspect", &json!({})).unwrap()["swatches"][1], json!([1.0, 0.0, 0.5])); + + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.swatches, s.doc.project.swatches, "saved per project"); + assert!(Session::from_project_bytes(&plain).unwrap().doc.project.swatches.is_empty()); + + execute(&mut s, "swatch.remove", &json!({"index": 0})).unwrap(); + assert_eq!(s.doc.project.swatches, vec![[1.0, 0.0, 0.5]]); + execute(&mut s, "edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc.project.swatches.len(), 2, "a removal is one undo step"); + + assert!(execute(&mut s, "swatch.add", &json!({})).is_err(), "a colour is required"); + assert!(execute(&mut s, "swatch.remove", &json!({"index": 2})).is_err(), "no such swatch"); + while s.doc.project.swatches.len() < texturecraft_core::MAX_SWATCHES { + execute(&mut s, "swatch.add", &json!({"color": "#336699"})).unwrap(); + } + assert!(execute(&mut s, "swatch.add", &json!({"color": "#336699"})).is_err(), "the list is capped"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index f776f46a..36b45d1f 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,5 +1,6 @@ use serde_json::{Value, json}; use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, command_specs, execute}; @@ -183,6 +184,24 @@ fn polygon_fill_and_color_picker() { assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}"); } +#[test] +fn color_at_reads_the_surface_without_changing_the_brush() { + let mut s = session(); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.9})).unwrap(); + execute(&mut s, "tool.polygonFill", &Value::Null).unwrap(); + execute(&mut s, "tool.fillMode", &json!({"mode": "mesh"})).unwrap(); + execute(&mut s, "tool.click", &json!({"x": 200, "y": 200})).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.2})).unwrap(); + let viewport = s.viewport; + + let read = s.color_at(Vec2::new(200.0, 200.0), viewport).unwrap(); + + let surface = read.get(&Channel::Roughness).unwrap(); + assert!((surface[0] - 0.9).abs() < 0.01, "{surface:?}"); + let brush = s.tool.values.get(&Channel::Roughness).unwrap(); + assert!((brush[0] - 0.2).abs() < 0.01, "the brush keeps its own value: {brush:?}"); +} + #[test] fn polygon_fill_boxes_survive_hostile_params() { let hostile = [ @@ -247,6 +266,56 @@ fn panic_hunt() { } } +/// A 4 × 4 gray PNG, the image the hunted decals project +fn gray_png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +#[test] +fn panic_hunt_frames_and_transforms() { + let mut s = session(); + let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); + let planar = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.projection", &json!({"layer": planar, "projection": "planar"})).unwrap(); + let warp = execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "layer.fill.projection", &json!({"layer": warp, "projection": "warp"})).unwrap(); + let decal = execute(&mut s, "layer.add.decal", &json!({"image": image, "channel": "mask", "position": [0, 0, 1], "normal": [0, 0, 1]})).unwrap(); + let mask_effect = decal["maskEffect"].as_u64().unwrap(); + s.update(); + + let hostile_values = + [json!(1e30), json!(-1e30), json!(0), json!(null), json!("x"), json!([]), json!([1e30, -1e30]), json!([0, 0, 0]), json!([-1e30, 1e30, 0, 5])]; + let targets = [json!({"layer": planar}), json!({"layer": warp}), json!({"effect": mask_effect})]; + let keys = ["frameOffset", "frameRotation", "frameScale", "size", "offset", "depth", "rotation", "up"]; + for target in &targets { + for key in keys { + for value in &hostile_values { + let mut params = target.clone(); + params[key] = value.clone(); + hunt_refused_changes_nothing(&mut s, "layer.decal.set", ¶ms); + } + } + } + + for target in &targets { + for command in ["layer.fill.resetFrame", "layer.fill.resetProjection"] { + let _ = execute(&mut s, command, target); + s.update(); + } + } +} + +/// Run `command` with `params` and render; refused, it must leave the project and the undo history as they were +fn hunt_refused_changes_nothing(s: &mut Session, command: &str, params: &Value) { + let (before, steps) = (s.doc.project.clone(), s.history_labels().len()); + if execute(s, command, params).is_err() { + assert!(s.doc.project == before && s.history_labels().len() == steps, "a refused {command} {params} changes nothing"); + } + s.update(); +} + /// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ /// between the two, so every command that takes a colour says which form is which. #[test] @@ -872,3 +941,19 @@ fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() { execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap(); assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped"); } + +#[test] +fn a_new_session_forgets_the_projector_depth_maps_built_before_it() { + use texturecraft_engine::compose::projector_depth::ProjectorDepth; + use texturecraft_engine::core::{Projection, Projector, UvTransform}; + + let mesh = primitives::sphere(1.0, 16, 8); + let projection = + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; + let built = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + + let after = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + assert!(!std::sync::Arc::ptr_eq(&built, &after), "a mesh sharing the old one's fingerprint must not take its map"); +} diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index 6d61b073..b0161e4b 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -371,6 +371,7 @@ mod tests { projection: Default::default(), sampling: Default::default(), link: None, + material: None, }; let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]); layer.mask = Some(Mask::new(MaskBackground::White)); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index dd2a06d3..fe8fd68d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -15,7 +15,6 @@ use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; -use crate::filter_slot::SLOT_HEIGHT; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::past_end::PastEnd; @@ -24,7 +23,7 @@ use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, section_with_reset, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; /// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it const NEW_FILTER: &str = "hsl"; @@ -133,6 +132,12 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { // --------------------------------------------------------------------------------------------- // Layers +/// Gap between the layer toolbar and the layer rows +const LAYER_TOOLBAR_GAP: f32 = 2.0; + +/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target +const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; + /// The add-mask commands, for the selected layer or (`row`) the layer whose mask slot was clicked. fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { let enabled = row.is_some() || app.session.selected_layer().is_some(); @@ -149,12 +154,6 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } } -/// Gap between the layer toolbar and the layer rows -const LAYER_TOOLBAR_GAP: f32 = 2.0; - -/// Least height of the drop space under the layer rows, so a drop to the bottom always has a target -const BOTTOM_DROP_MIN_HEIGHT: f32 = 24.0; - pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); @@ -1923,6 +1922,7 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: /// The tabs over the panel when it shows a fill layer's sections, which they jump between pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 2]> { +pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } @@ -1932,6 +1932,7 @@ pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static s StackTarget::Content => { let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(crate::fill_panel::fill_tabs) + matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) } _ => None, } @@ -2070,6 +2071,8 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let alpha = (brush.flow * brush.opacity * 255.0) as u8; painter.add(egui::Shape::line(points, Stroke::new(stroke_width, Color32::from_white_alpha(alpha.max(PREVIEW_STROKE_MIN_ALPHA))))); let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); + + // The sphere sits in the middle of the preview's right half crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); ui.add_space(BRUSH_PREVIEW_GAP); @@ -2649,6 +2652,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { /// Space between the tool's channel chips and the first channel value const CHIPS_GAP: f32 = 4.0; +/// Room right of the tool's colour swatch, like a linked material's +const TOOL_SWATCH_RIGHT_MARGIN: f32 = LINK_SWATCH_RIGHT_MARGIN; + /// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. /// The Material tab and the Smudge panel both draw these, so they share one set of flags. fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { @@ -2691,7 +2697,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { ChannelKind::Color => { ui.horizontal(|ui| { ui.label(tr(channel.label())); - if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { + if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - TOOL_SWATCH_RIGHT_MARGIN) { app.session.tool.values.insert(channel, value); app.session.tool.material = None; } @@ -2725,133 +2731,66 @@ fn fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let on: Vec = layer.channels.keys().copied().collect(); PropertySheet::show(ui, ("fill_sheet", layer.id.0), |sheet| { crate::fill_panel::placement_sections(app, sheet, fill, &json!({"layer": layer.id.0}), layer.id); - }); - legacy_body(ui, |ui| { - if let Some(link) = &fill.link { - link_properties(app, ui, layer.id, link); - ui.add_space(6.0); - } - fill_editor(app, ui, fill, &json!({"layer": layer.id.0}), &on, layer.id); + crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"layer": layer.id.0}), &on, layer.id); }); } -/// A MaterialCraft material's presets and exposed inputs; edits store the value and re-cook the -/// maps on a worker thread (desktop only: cooking runs MaterialCraft's command line). -fn link_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, link: &MaterialLink) { - let tk = Tokens::get(ui.ctx()); - let base = json!({"layer": layer.0, "cook": false}); - ui.label(caption(tr("MaterialCraft material"))); - ui.horizontal(|ui| { - ui.label(RichText::new(&link.name).strong()); - ui.label(RichText::new(trf("Cooked at {size} px", &[("size", &link.size)])).size(10.0).color(tk.text_dim)); - if app.link_cooks.iter().any(|c| c.layer == layer) { - ui.spinner(); - } - }); - let editable = cfg!(not(target_arch = "wasm32")); - ui.add_enabled_ui(editable, |ui| { - if !link.presets.is_empty() { - combo(ui, tr("Preset"), "", |ui| { - for p in &link.presets { - if ui.selectable_label(false, &p.name).clicked() && app.run("material.link.preset", with(&base, json!({"name": p.name}))).is_some() { - app.cook_link(layer); - } - } - }); - } - let mut group = ""; - for p in &link.params { - if p.group != group && !p.group.is_empty() { - ui.label(RichText::new(p.group.to_uppercase()).size(10.0).strong().color(tk.text_dim)); - } - group = &p.group; - if let Some(v) = link_param_editor(ui, layer, p) - && app.run("material.link.set", with(&base, json!({"id": p.id, "value": v}))).is_some() - { - app.cook_link(layer); - } - } - }); - if !editable { - ui.label(RichText::new(tr("Parameters change in the desktop app, with MaterialCraft installed")).size(10.0).color(tk.text_dim)); +/// Writes the material's package to a temporary file and opens it in MaterialCraft +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn open_link_in_materialcraft(app: &mut TextureCraftApp, layer: LayerId, link: &texturecraft_engine::core::MaterialLink) { + let ext = texturecraft_engine::link_cmds::source_extension(&link.package); + let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); + let opened = app + .session + .link_package(layer) + .and_then(|package| std::fs::write(&path, package.as_slice()).map_err(|err| texturecraft_engine::EngineError::Other(err.to_string()))) + .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); + match opened { + Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), + Err(e) => app.toast(e.to_string(), true), } - #[cfg(not(target_arch = "wasm32"))] - ui.horizontal(|ui| { - if ui.button(tr("Re-cook")).clicked() { - app.cook_link(layer); - } - if ui.button(tr("Open in MaterialCraft")).clicked() { - let ext = texturecraft_engine::link_cmds::source_extension(&link.package); - let path = std::env::temp_dir().join(format!("{}.{ext}", texturecraft_engine::formats::export::sanitize_file_stem(&link.name))); - let opened = app - .session - .link_package(layer) - .and_then(|b| std::fs::write(&path, b.as_slice()).map_err(|e| texturecraft_engine::EngineError::Other(e.to_string()))) - .and_then(|()| texturecraft_engine::link_cmds::open_in_materialcraft(&path)); - match opened { - Ok(()) => app.toast(tr("Opened in MaterialCraft: use File > Send to TextureCraft there to bring your changes back"), false), - Err(e) => app.toast(e.to_string(), true), - } - } - }); } -/// The editor of one linked-material input; returns its new value when an edit completes. -fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option { - let t = p.default.get("t").and_then(Value::as_str).unwrap_or(""); - let v = p.value.get("v").unwrap_or(&Value::Null); - let num = |x: &Value| x.as_f64().unwrap_or(0.0) as f32; - let (lo, hi) = if p.max > p.min { (p.min, p.max) } else { (0.0, 1.0) }; - // A slider edit completes when the drag ends, on a click or a typed value. - let edit = |ui: &mut Ui, label: &str, x: f32, decimals: usize| { - let mut y = x; - let r = slider(ui, label, &mut y, lo.min(x)..=hi.max(x), decimals); - (r.drag_stopped() || (!r.dragged() && y != x)).then_some(y) - }; - match t { - "bool" => { - let mut b = v.as_bool().unwrap_or(num(v) != 0.0); - ui.checkbox(&mut b, &p.label).changed().then(|| json!(b)) - } - "enum" if !p.options.is_empty() => { - let cur = num(v).max(0.0) as usize; - let mut pick = None; - combo(ui, &p.label, p.options.get(cur).map_or("", String::as_str), |ui| { - for (i, o) in p.options.iter().enumerate() { - if ui.selectable_label(i == cur, o).clicked() { - pick = Some(json!(i)); - } - } - }); - pick - } - "float" | "int" | "enum" => edit(ui, &p.label, num(v), if t == "float" { 2 } else { 0 }).map(|y| json!(y)), - "color" => { - let a = v.as_array().map(|a| a.iter().map(num).collect::>()).unwrap_or_default(); - let mut rgb = [0, 1, 2].map(|i| a.get(i).copied().unwrap_or(1.0)); - let mut out = None; - ui.horizontal(|ui| { - ui.label(&p.label); - if color_swatch(ui, &format!("link_{}_{}", layer.0, p.id), &mut rgb, ui.available_width() - 4.0) { - out = Some(json!([rgb[0], rgb[1], rgb[2], a.get(3).copied().unwrap_or(1.0)])); - } - }); - out - } - _ => { - // Vectors: one slider per component. - let mut a: Vec = v.as_array().map(|a| a.iter().map(num).collect()).unwrap_or_default(); - let decimals = if t == "int2" { 0 } else { 2 }; - let mut changed = false; - for (x, axis) in a.iter_mut().zip(["x", "y", "z", "w"]) { - if let Some(y) = edit(ui, &format!("{} {axis}", p.label), *x, decimals) { - *x = y; - changed = true; - } - } - changed.then(|| json!(a)) +/// Room the colour swatch of a linked-material input leaves at the row's right +const LINK_SWATCH_RIGHT_MARGIN: f32 = 4.0; + +/// The editor of a linked-material colour or vector input (the sheet draws the other kinds): the new value and whether it continues a colour drag +pub(crate) fn link_param_editor(ui: &mut Ui, layer: LayerId, param: &LinkParam) -> Option<(Value, bool)> { + let kind = param.default.get("t").and_then(Value::as_str).unwrap_or(""); + let value = param.value.get("v").unwrap_or(&Value::Null); + let number = |item: &Value| item.as_f64().unwrap_or(0.0) as f32; + let (low, high) = if param.max > param.min { (param.min, param.max) } else { (0.0, 1.0) }; + + if kind == "color" { + let components = value.as_array().map(|items| items.iter().map(number).collect::>()).unwrap_or_default(); + let mut rgb = [0, 1, 2].map(|index| components.get(index).copied().unwrap_or(1.0)); + let swatch_id = format!("link_{}_{}", layer.0, param.id); + let changed = ui + .horizontal(|ui| { + ui.label(¶m.label); + color_swatch(ui, &swatch_id, &mut rgb, ui.available_width() - LINK_SWATCH_RIGHT_MARGIN) + }) + .inner; + + // The picker changes the colour every frame of a drag: those frames share one undo step + let merge = press_edit(ui, ui.make_persistent_id((swatch_id.as_str(), "press")), changed)?; + return Some((json!([rgb[0], rgb[1], rgb[2], components.get(3).copied().unwrap_or(1.0)]), merge)); + } + + // Vectors: one slider per component; an edit applies when the drag ends, on a click or a typed value + let mut components: Vec = value.as_array().map(|items| items.iter().map(number).collect()).unwrap_or_default(); + let decimals = if kind == "int2" { 0 } else { 2 }; + let mut changed = false; + for (component, axis) in components.iter_mut().zip(["x", "y", "z", "w"]) { + let current = *component; + let response = slider(ui, &format!("{} {axis}", param.label), component, low.min(current)..=high.max(current), decimals); + if response.drag_stopped() || (!response.dragged() && *component != current) { + changed = true; + } else { + *component = current; } } + changed.then(|| (json!(components), false)) } /// `base` with the fields of `extra` added @@ -2864,8 +2803,7 @@ pub(crate) fn with(base: &Value, extra: Value) -> Value { } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). -pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String)> { - let project = &app.session.doc.project; +pub(crate) fn anchors_below(project: &texturecraft_engine::core::Project, reader: LayerId) -> Vec<(LayerId, String)> { let Some((texture_set, _, _)) = project.locate(reader) else { return Vec::new() }; project .walk(texture_set) @@ -2892,13 +2830,18 @@ pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(Laye /// Anchor choices for an effect, valid for its owner and recorded below the displayed instance pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { - let owner = app.session.doc.project.effect(effect).map_or(layer, |(owner, _)| owner); - let owner_anchors = anchors_below(app, owner); + project_effect_anchors_below(&app.session.doc.project, layer, effect) +} + +/// [`effect_anchors_below`] in `project` +pub(crate) fn project_effect_anchors_below(project: &texturecraft_engine::core::Project, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { + let owner = project.effect(effect).map_or(layer, |(owner, _)| owner); + let owner_anchors = anchors_below(project, owner); if owner == layer { return owner_anchors; } - let displayed_anchors = anchors_below(app, layer); + let displayed_anchors = anchors_below(project, layer); owner_anchors.into_iter().filter(|(id, _)| displayed_anchors.iter().any(|(displayed, _)| id == displayed)).collect() } @@ -3162,121 +3105,6 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// Space a fill channel's color swatch leaves at the group's right edge -const CHANNEL_SWATCH_MARGIN: f32 = 4.0; -/// Width of a pattern's low and high swatches -const PATTERN_RANGE_SWATCH_WIDTH: f32 = 60.0; -/// Size of the gradient map menu icon beside the fill source slot -const FILL_CHANNEL_MENU_ICON_SIZE: f32 = 13.0; -const GRADIENT_MAP_HINT: &str = n_("Colors the procedural or anchor from dark to light through color stops"); - -/// The source slot, source settings and gradient map of one fill channel -fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, channel: Channel, anchors: &[(LayerId, String)], salt: &str) { - let tokens = Tokens::get(ui.ctx()); - let set = |extra: Value| with(base, with(&json!({"channel": channel.id()}), extra)); - let default_source = Source::uniform_of(channel); - let source = fill.sources.get(&channel).unwrap_or(&default_source); - let is_color = channel.kind() == ChannelKind::Color; - let group = ui.group(|ui| { - let slot = crate::fill_source_target::FillSourceTarget::Channel { base: base.clone(), channel }; - if is_color { - ui.allocate_ui_with_layout(vec2(ui.available_width(), SLOT_HEIGHT), egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(FILL_CHANNEL_MENU_ICON_SIZE), |ui| gradient_map_item(app, ui, source, &set)) - .response - .on_hover_text(tr(GRADIENT_MAP_HINT)); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); - }); - }); - } else { - crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); - } - - match source { - Source::Uniform(value) if is_color => { - let mut value = *value; - if color_swatch(ui, &format!("fill_{salt}_{}", channel.id()), &mut value, ui.available_width() - CHANNEL_SWATCH_MARGIN) { - app.run("layer.fill.set", set(json!({"color": value}))); - } - } - Source::Uniform(value) => { - let mut value = value[0]; - let range = if channel.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, range, 2) { - app.run("layer.fill.set", set(json!({"value": value, "merge": merge}))); - } - } - Source::Procedural { pattern, low, high, ramp } => { - let target = crate::pattern_target::PatternTarget { - command: "layer.fill.set", - base: with(base, json!({"channel": channel.id(), "low": low, "high": high})), - salt: format!("{salt}_{}", channel.id()), - }; - crate::pattern_panel::pattern_properties(app, ui, &target, pattern); - if is_color && ramp.is_empty() { - let (mut low, mut high) = (*low, *high); - let mut changed = false; - ui.horizontal(|ui| { - ui.label(tr("Low")); - changed |= color_swatch(ui, &format!("lo_{salt}_{}", channel.id()), &mut low, PATTERN_RANGE_SWATCH_WIDTH); - ui.label(tr("High")); - changed |= color_swatch(ui, &format!("hi_{salt}_{}", channel.id()), &mut high, PATTERN_RANGE_SWATCH_WIDTH); - }); - if changed { - crate::pattern_panel::send(app, &target, pattern, json!({"low": low, "high": high})); - } - } - } - Source::Image { name, normal_format } => { - ui.label(trf("Image: {name}", &[("name", name)])); - if channel.kind() == ChannelKind::NormalMap { - let mut directx = *normal_format == texturecraft_engine::core::NormalFormat::DirectX; - let toggle = ui - .checkbox(&mut directx, tr("DirectX normal map")) - .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")); - if toggle.changed() { - app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); - } - } - } - Source::Anchor { anchor, channel: anchored, .. } => { - ui.label(RichText::new(anchor_label(app, *anchor, *anchored)).color(tokens.text_dim)); - } - } - - if is_color && !source.ramp().is_empty() { - ramp_editor(app, ui, source.ramp(), &format!("ramp_{salt}_{}", channel.id()), &set); - } - }); - - // A shelf image dropped on the channel becomes its source - if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { - app.run("layer.fill.set", set(json!({"image": name}))); - } -} - -/// The Gradient Map item beside a color channel's source slot: turns the color stops of its -/// procedural (starting from its low and high, so the look holds) or anchor on, or off. -fn gradient_map_item(app: &mut TextureCraftApp, ui: &mut Ui, source: &Source, set: &impl Fn(Value) -> Value) { - let can = matches!(source, Source::Procedural { .. } | Source::Anchor { .. }); - let on = !source.ramp().is_empty(); - let hint = tr(GRADIENT_MAP_HINT); - let item = ui.add_enabled_ui(can, |ui| ui.selectable_label(on, tr("Gradient Map"))).inner; - if item.on_hover_text(hint).on_disabled_hover_text(hint).clicked() { - let params = if on { json!({ "colors": [] }) } else { json!({ "gradientMap": true }) }; - app.run("layer.fill.set", set(params)); - ui.close(); - } -} - -/// The color stops of a fill channel's gradient map. -fn ramp_editor(app: &mut TextureCraftApp, ui: &mut Ui, ramp: &[[f32; 3]], salt: &str, set: &impl Fn(Value) -> Value) { - let mut stops = ramp.to_vec(); - if gradient_stops(ui, salt, &mut stops) { - app.run("layer.fill.set", set(json!({ "colors": stops }))); - } -} - /// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when /// they changed. fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool { @@ -3313,11 +3141,23 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); - let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; - let slot = ui.scope(|ui| crate::fill_source_slot::show(app, ui, &target, source, (&anchors, tr("Grayscale")))).response; + let project = &app.session.doc.project; + } + Source::Uniform(_) => tr("Uniform value").to_string(), + Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), + }; - // The slot accepts image drops from the Assets panel - if let Some(name) = image_drop(ui, &slot.interact(Sense::hover())) { + }); + } + }); + crate::menus::invoke(app, &ctx, "resource.import"); + } + }; + app.run("effect.set", params); + } + + // The source selector accepts image drops from the Assets panel + if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { app.run("effect.set", json!({"effect": id, "image": name})); } @@ -3328,10 +3168,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } - Source::Procedural { pattern, .. } => { - let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; - crate::pattern_panel::pattern_properties(app, ui, &target, pattern); - } Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { let note = if mask_anchor_enabled(app, *anchor) == Some(false) { tr("Off") } else { tr("A mask anchor reads as its mask's gray.") }; ui.label(RichText::new(note).color(tokens.text_dim)); @@ -3350,6 +3186,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe Source::Image { .. } => { projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); } + Source::Procedural { pattern, .. } => { + let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; + crate::pattern_panel::pattern_properties(app, ui, &target, pattern); + } } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); @@ -3359,6 +3199,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let enabled: Vec = fill.sources.keys().copied().collect(); PropertySheet::show(ui, ("fill_effect_sheet", id), |sheet| { crate::fill_panel::placement_sections(app, sheet, fill, &json!({"effect": id}), layer.id); + crate::fill_panel::fill_sheet(app, sheet, fill, &json!({"effect": id}), &enabled, layer.id); }); legacy_body(ui, |ui| fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id)); } diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs deleted file mode 100644 index 67abc1b5..00000000 --- a/crates/ui-egui/src/exact_entry_open.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! The Levels editor's mark that its exact-entry fields are shown - -/// Marks the exact-entry fields as shown; they appear on a handle's double-click or Enter and close when typing ends -#[derive(Clone, Copy)] -pub(crate) struct ExactEntryOpen; diff --git a/crates/ui-egui/src/fill_panel.rs b/crates/ui-egui/src/fill_panel.rs index 88aef1be..7f740796 100644 --- a/crates/ui-egui/src/fill_panel.rs +++ b/crates/ui-egui/src/fill_panel.rs @@ -8,6 +8,7 @@ use serde_json::{Value, json}; use texturecraft_engine::compose::frame_placement; use texturecraft_engine::compose::tile_length::{MeshSize, tile_length, tiling_for_length}; use texturecraft_engine::core::{Backface, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; +use texturecraft_engine::core::{Backface, Channel, Fill, Filtering, LayerId, Projection, Projector, ScaleMode, ShapeCrop, UvWrap}; use texturecraft_engine::layer_cmds::{MAX_PLACEMENT, MIN_SCALE}; use texturecraft_engine::paint::FULL_TURN_DEGREES; @@ -78,6 +79,10 @@ const SCALE_FIELD_SPEED: f32 = 0.01; /// The tabs over a fill's Properties, each jumping to its section pub(crate) fn fill_tabs() -> [(&'static str, &'static str); 2] { [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry"))] +/// The tabs over a fill's Properties, each jumping to its section: a mask fill's last section is its Grayscale, a fill layer's its Material +pub(crate) fn fill_tabs(grayscale: bool) -> [(&'static str, &'static str); 3] { + let last = if grayscale { (ic::SQUARE_HALF, tr("Grayscale")) } else { (ic::CIRCLE_HALF, tr("Material")) }; + [(ic::SLIDERS_HORIZONTAL, tr("Fill")), (ic::FLIP_HORIZONTAL, tr("Symmetry")), last] } /// Which fill a `base` addresses, (layer, effect), as the salt of its rows' widget state @@ -107,6 +112,12 @@ fn mesh_size(app: &TextureCraftApp, ctx: &egui::Context) -> MeshSize { size } +/// A fill's whole Properties: the Fill section, the Symmetry section, then the Material section with one slot per channel that is on +pub(crate) fn fill_sheet(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) { + placement_sections(app, sheet, fill, base, reader); + crate::fill_material_panel::material_section(app, sheet, fill, base, on, reader); +} + /// The Fill section (with its reset) and the Symmetry section of the fill at `base`: a fill layer's, a content fill effect's or a mask fill's pub(crate) fn placement_sections(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, reader: LayerId) { // The section reset: projection, placement, sampling and culling back to a new fill's in one undo step diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 5a9fa0d7..43b0a9d5 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,7 +370,6 @@ mod tests { use super::*; - /// A hand-edited span past a full turn spaces the ring's dots as the engine spaces the copies: six copies 60° apart, none on top of another #[test] fn the_ring_spaces_its_copies_as_the_engine_does() { let symmetry = FillSymmetry { on: true, kind: SymmetryKind::Radial, count: 6, span: 720.0, ..FillSymmetry::OFF }; diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 9a6dfae1..962914b1 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -326,7 +326,7 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 }); }); combo(ui, tr("Source"), current.clone(), |ui| { - let anchors = anchors_below(app, layer); + let anchors = anchors_below(&app.session.doc.project, layer); if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() { app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true})); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 283013a9..2206f55e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,22 +16,23 @@ pub mod bake_presets; mod bake_report; mod bake_scene; mod color_management; +mod color_picker; mod color_selection_editor; pub mod control; mod decal_drop; mod display_settings; pub mod dock; pub mod docking; +mod drawn_icon; mod environment_picker; mod export_panel; pub mod export_templates; mod export_window; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_material_panel; mod fill_panel; mod fill_pictures; -mod fill_source_slot; -mod fill_source_target; mod fill_symmetry_panel; mod filter_slot; pub mod fonts; @@ -55,6 +56,7 @@ mod line_snap; mod list_action; pub mod log_panel; mod mask_preview_image; +mod material_orb; mod material_preview_image; pub mod menus; mod mesh_export_options; @@ -67,6 +69,9 @@ mod nav_button; pub mod nav_buttons; mod nav_view; pub mod new_project_advanced; +mod orb_environment; +mod orb_material; +pub mod orb_previews; mod orb_shape; pub mod parity; mod past_end; @@ -75,6 +80,8 @@ mod path_surface_cache; mod pattern_panel; mod pattern_target; pub mod pbr_import; +mod picker_group; +mod picker_tab; mod placement; mod pointer_lock; mod popup_drag; @@ -95,17 +102,15 @@ mod property_sheet; mod query_field; mod rail_popup; pub mod render_mode; +mod resolution_band; mod resource_panel; mod resource_picker; -mod resource_picker_anchor; -mod resource_picker_choice; mod resource_picker_item; -mod resource_picker_tab; -mod resource_picker_tile; mod round_gizmo; mod running_bake; pub mod saved_search; mod screen_color_pick; +pub mod screen_pick; mod section_page; pub mod settings_window; pub mod shader_settings; @@ -117,15 +122,19 @@ pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_view; +mod slot_thumbnail; #[cfg(not(target_arch = "wasm32"))] mod smart_mask_menu; mod soft_box; +mod source_choice; +mod source_slot; pub mod state; mod surface_paint_point; pub mod symmetry; pub mod theme; pub mod thumbs; mod tile_edits; +mod tile_picture; pub mod titlebar; pub mod toolbar; pub mod ui_state_store; @@ -262,6 +271,12 @@ pub struct TextureCraftApp { pub picking_id_color: Option, /// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings) pub picking_symmetry_plane: bool, + /// The colour bar whose eyedropper waits for a click on the model or, outside the app, on the screen + pub picking_color: Option, + /// That eyedropper pick's wait for a click outside the app + pub screen_pick: Option, + /// Whether an eyedropper pick also takes a click outside the app (only with a real window: never in tests) + pub screen_picking: bool, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -367,6 +382,12 @@ impl TextureCraftApp { properties_popup: None, picking_id_color: None, picking_symmetry_plane: false, + picking_color: None, + screen_pick: None, + #[cfg(not(target_arch = "wasm32"))] + screen_picking: raw_window_handle::HasWindowHandle::window_handle(cc).is_ok(), + #[cfg(target_arch = "wasm32")] + screen_picking: false, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, @@ -612,7 +633,8 @@ impl TextureCraftApp { return false; }; - let resized = self.session.doc.project.texture_set(set).is_ok_and(|set| set.resolution != c.size); + // A cook for another size than the layer's picked or texture set resolution is redone + let resized = self.session.link_size(c.layer).is_ok_and(|now| now != c.size); let baked = self.session.baked(set); let stale = resized || c.baked_inputs.iter().any(|input| !input.is_current(baked)); done.push((c.layer, c.values.clone(), stale, result)); @@ -1066,6 +1088,7 @@ impl eframe::App for TextureCraftApp { self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); + screen_pick::sync(self, ctx); move_on_model::end_when_gone(self, ctx); // The Path tool's curve repaints (a preview while placed) as its points, brush or material change @@ -1124,6 +1147,10 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); + // Last, so no widget's pointer replaces it: an armed eyedropper is the pointer over the whole window + if self.picking_color.is_some() { + screen_pick::paint_cursor(&ctx, None, screen_pick::SwatchColor::shown(&ctx)); + } pointer_lock::settle(&ctx); let end_ms = now_ms(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 7ec42c75..3e40db15 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -471,8 +471,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { input.events.extend(aliases); }); - // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke + // Escape closes a dropdown before an eyedropper pick, the colour picker window, Properties, the rail popup, the ID colour pick or the stroke let popup_open = egui::Popup::is_any_open(ctx); + let picker_open = crate::color_picker::open_window(ctx).is_some(); let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); #[cfg(not(target_arch = "wasm32"))] @@ -511,6 +512,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } + // The open list or the picker window closes on this Escape itself + let escape_is_free = !popup_open && !picker_open; if confirming_reset { // Its keys were handled before the shortcuts ran } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -523,15 +526,17 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.picking_color = None; + } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs index 7afe7662..0d570bce 100644 --- a/crates/ui-egui/src/pattern_panel.rs +++ b/crates/ui-egui/src/pattern_panel.rs @@ -31,19 +31,34 @@ pub(crate) fn pattern_properties(app: &mut TextureCraftApp, ui: &mut Ui, target: Some(tile) => tile_parameters(app, ui, target, pattern, tile), None => pattern_parameters(app, ui, target, pattern), } - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Restore defaults")).clicked() { - restore_defaults(app, target, pattern); - } - }); - }); + restore_row(app, ui, target, pattern); }); if let Some(tile) = pattern.tile.as_deref() { section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); } } +/// A Tile Generator under a slot whose rows already show its scale, contrast, seed and resolution: its own parameters and image inputs +pub(crate) fn tile_generator_sections(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let id = |name: &str| format!("pattern_{name}_{}", target.salt); + section(ui, &id("parameters"), tr("Parameters"), true, |ui| { + tile_parameters(app, ui, target, pattern, tile); + restore_row(app, ui, target, pattern); + }); + section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); +} + +/// Restore defaults, on the right +fn restore_row(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + restore_defaults(app, target, pattern); + } + }); + }); +} + /// Sends `pattern` again (its kind, scale, seed, contrast, balance and invert) with `extra` to its fill pub(crate) fn send(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural, extra: Value) { let mut params = target.base.clone(); diff --git a/crates/ui-egui/src/projection_preview.rs b/crates/ui-egui/src/projection_preview.rs index 37992c63..18a8bc60 100644 --- a/crates/ui-egui/src/projection_preview.rs +++ b/crates/ui-egui/src/projection_preview.rs @@ -17,6 +17,7 @@ use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; use rayon::prelude::*; use crate::projector_outline::ProjectorOutline; +use crate::slot_thumbnail::FULL_UV; use crate::theme::Tokens; mod preview_shape; diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 4e4d2f34..4f70d16a 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -49,18 +49,19 @@ pub(crate) fn open_on_right_click(app: &mut TextureCraftApp, ui: &Ui, response: } } -/// Draws the open popup and closes it on a press outside it or when the app leaves Painting +/// Draws the open popup and closes it on a press outside it (but not an eyedropper pick's) or when the app leaves Painting pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let (any_down, pressed_at) = ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()))); - match app.properties_popup { _ if app.ui.mode != Mode::Painting => app.properties_popup = None, Some(PropertiesPopup::Closing) if !any_down => app.properties_popup = None, Some(PropertiesPopup::Open { .. }) => { let shown = ctx.memory(|memory| memory.area_rect(area_id())); - let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))); - // A press in one of the popup's own dropdowns lands outside its area - if outside && !egui::Popup::is_any_open(ctx) { + let in_picker = |at: egui::Pos2| crate::color_picker::open_window(ctx).is_some_and(|picker| picker.contains(at)); + let outside = pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at)) && !in_picker(at)); + + // A press in one of the popup's own dropdowns or its colour picker window lands outside its area; an eyedropper pick's click on the model hands its colour back to the popup + if outside && !egui::Popup::is_any_open(ctx) && app.picking_color.is_none() { app.properties_popup = Some(PropertiesPopup::Closing); } } diff --git a/crates/ui-egui/src/property_sheet/button_icon.rs b/crates/ui-egui/src/property_sheet/button_icon.rs index be97a317..5ed4fb73 100644 --- a/crates/ui-egui/src/property_sheet/button_icon.rs +++ b/crates/ui-egui/src/property_sheet/button_icon.rs @@ -1,10 +1,14 @@ //! What a full-width button shows before its words: an icon font glyph or an icon drawn in code +use crate::drawn_icon::DrawnIcon; + /// A full-width button's icon #[derive(Clone, Copy, Debug)] pub(crate) enum ButtonIcon<'a> { /// A glyph of the icon font Glyph(&'a str), + /// An icon the font has no fitting glyph for + Drawn(DrawnIcon), } impl<'a> From<&'a str> for ButtonIcon<'a> { @@ -12,3 +16,9 @@ impl<'a> From<&'a str> for ButtonIcon<'a> { ButtonIcon::Glyph(glyph) } } + +impl From for ButtonIcon<'_> { + fn from(icon: DrawnIcon) -> Self { + ButtonIcon::Drawn(icon) + } +} diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 15d3d03f..5ce08fe6 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -134,6 +134,20 @@ impl PropertySheet<'_> { response } + /// [`Self::dropdown`] whose list holds its options in groups, each under its caption, built only while the list is open; returns the picked option + pub(crate) fn grouped_dropdown<'g, T: Copy + PartialEq, Groups: IntoIterator)>>( + &mut self, + label: &str, + current: T, + groups: impl FnOnce() -> Groups, + name: impl Fn(T) -> String, + picture: ChoicePicture<'_, T>, + ) -> Option { + let response = self.dropdown_row(RowLead::label(label), current, &name, Some(picture)); + let captioned = || groups().into_iter().map(|(caption, options)| (Some(caption), options)); + self.hanging_groups(&response, current, captioned, &name, Some(picture)).0 + } + /// Paints a dropdown's button in `rect` and returns its response pub(super) fn dropdown_button(&mut self, rect: Rect, value: &str, picture: Option) -> Response { self.dropdown_button_led(rect, value, |painter| match picture { diff --git a/crates/ui-egui/src/property_sheet/group.rs b/crates/ui-egui/src/property_sheet/group.rs index 09ff1a4c..2e93f4af 100644 --- a/crates/ui-egui/src/property_sheet/group.rs +++ b/crates/ui-egui/src/property_sheet/group.rs @@ -3,6 +3,7 @@ use egui_phosphor::regular as ic; use super::row::{EDGE_GLYPH_INSET, RESET_ICON_SIZE}; use super::{BandResponse, GROUP_GAP, PropertySheet, TEXT_SIZE}; +use super::{BandResponse, GROUP_GAP, OpenCard, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; use crate::theme::semibold; /// Draws a band's picture in its rect @@ -33,12 +34,20 @@ const BAND_PICTURE_AIR: f32 = 8.0; /// A band's reset button click square const BAND_RESET_TARGET: f32 = 20.0; +/// How far a title's text reaches below its centre +const TITLE_HALF_LINE: f32 = 7.0; + impl PropertySheet<'_> { /// A top-level group across the whole panel with a caret and a reset (`Some(changed)`) or a value; a click folds it pub(crate) fn band(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>) -> BandResponse { self.band_drawn(title, default_open, reset, value, None) } + /// [`Self::band`] whose value is led by a picture (Resolution: the size against the texture set's) + pub(crate) fn band_pictured(&mut self, title: &str, default_open: bool, value: &str, picture: BandPicture<'_>) -> BandResponse { + self.band_drawn(title, default_open, None, Some(value), Some(picture)) + } + fn band_drawn(&mut self, title: &str, default_open: bool, reset: Option, value: Option<&str>, picture: Option>) -> BandResponse { if self.card.is_none() { self.space(GROUP_GAP); @@ -109,12 +118,67 @@ impl PropertySheet<'_> { BandResponse { open, reset: reset_clicked } } + /// A group's fold state kept under `id`, flipped by a click on `hit` (answering as `title`); returns whether it is open + fn fold_toggle(&mut self, id: egui::Id, hit: Rect, title: &str, default_open: bool) -> bool { + let mut open = self.ui.data(|data| data.get_temp::(id)).unwrap_or(default_open); + let response = self.ui.interact(hit, id, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title)); + if response.clicked() { + open = !open; + self.ui.data_mut(|data| data.insert_temp(id, open)); + } + open + } + + /// A row of `rect`'s height across the open card, out to its bled edges + pub(super) fn bled_row(&self, rect: Rect) -> Rect { + Rect::from_min_max(pos2(self.left - CARD_BLEED, rect.top()), pos2(self.right + CARD_BLEED, rect.bottom())) + } + /// Ends [`Self::hold_card`] and closes the held card pub(crate) fn release_card(&mut self) { self.held = false; self.close_card(); } + /// Starts a card with no name row: a slot card, whose slot is its top row; inside a held card it joins that card + pub(crate) fn open_card(&mut self) { + if self.held && self.card.is_some() { + return; + } + + if self.card.is_none() && self.air_at != Some(self.cursor_y()) && !self.empty { + self.space(GROUP_GAP); + } + self.close_card(); + let face = self.ui.painter().add(Shape::Noop); + self.card = Some(OpenCard { top: self.cursor_y(), face }); + self.drawn_bottom = self.cursor_y(); + } + + /// A folded group inside a card: its bold name, the value it holds (dim) and a caret. Returns whether it is open + pub(crate) fn fold(&mut self, title: &str, value: Option<&str>, default_open: bool) -> bool { + let id = self.named_id("fold", title); + let rect = self.take(ROW_HEIGHT); + let open = self.fold_toggle(id, Rect::from_x_y_ranges(self.left..=self.right, rect.y_range()), title, default_open); + + let tokens = self.tokens; + let center_y = rect.center().y; + self.ui.painter().text(pos2(self.left, center_y), Align2::LEFT_CENTER, title, semibold(TEXT_SIZE), tokens.text); + if let Some(value) = value { + self.ui.painter().text( + pos2(self.right - BAND_VALUE_INSET, center_y), + Align2::RIGHT_CENTER, + value, + FontId::proportional(TEXT_SIZE), + tokens.text_dim, + ); + } + self.caret(pos2(self.right - EDGE_GLYPH_INSET, center_y), open, tokens.text_dim); + self.drawn(center_y + TITLE_HALF_LINE); + open + } + /// Ends the open card (not a held one: [`Self::release_card`] ends that): its face reaches [`CARD_PADDING`] below what its rows painted pub(crate) fn close_card(&mut self) { if self.held { diff --git a/crates/ui-egui/src/property_sheet/material_rows.rs b/crates/ui-egui/src/property_sheet/material_rows.rs new file mode 100644 index 00000000..14fc9b40 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/material_rows.rs @@ -0,0 +1,113 @@ +//! The Material section's own rows: the orb beside the Material | Channels switch and a uniform channel's gray ramp + +use std::ops::RangeInclusive; + +use egui::{Color32, Mesh, Painter, Rect, Sense, Vec2, pos2, vec2}; + +use super::ramp_edit::RampEdit; +use super::slider::KNOB_RADIUS; +use super::track::Track; +use super::{CONTROL_HEIGHT, GLYPH_TARGET, PropertySheet, ROW_HEIGHT}; +use crate::drawn_icon::DrawnIcon; + +/// Side of the material's orb +const ORB_SIZE: f32 = 90.0; + +/// Air between the orb and the switch beside it +const ORB_TO_SWITCH: f32 = 12.0; + +/// Air under the orb +const ORB_AIR: f32 = 14.0; + +/// From the right edge to the end of a ramp's track, where its value and invert glyph sit +const RAMP_END_INSET: f32 = 56.0; + +/// From the right edge to a ramp's value: where the linked Tiling and Offset values end +const RAMP_VALUE_INSET: f32 = super::preview_block::LINK_ROOM; + +/// From the right edge to a ramp's invert glyph's centre +const INVERT_INSET: f32 = 8.0; + +/// Width of a ramp's typed value +const RAMP_VALUE_WIDTH: f32 = 34.0; + +/// Height of a ramp's track +const RAMP_HEIGHT: f32 = 4.0; + +/// Size of the invert glyph +const INVERT_GLYPH_SIZE: f32 = 14.0; + +/// The gaps between the widgets of a card's own body +const CARD_ITEM_SPACING: Vec2 = vec2(8.0, 4.0); + +impl PropertySheet<'_> { + /// The material's orb with the Material | Channels switch beside it (none without `options`); returns the segment clicked when it was not the chosen one + pub(crate) fn orb_switch(&mut self, orb: &dyn Fn(&Painter, Rect), options: &[&str], selected: usize) -> Option { + let rect = self.take(ORB_SIZE); + let square = Rect::from_min_size(pos2(self.left, rect.top()), vec2(ORB_SIZE, ORB_SIZE)); + orb(self.ui.painter(), square); + let switch = Rect::from_min_max( + pos2(square.right() + ORB_TO_SWITCH, square.center().y - CONTROL_HEIGHT / 2.0), + pos2(self.right, square.center().y + CONTROL_HEIGHT / 2.0), + ); + let picked = if options.is_empty() { None } else { self.segments(switch, options, selected, super::switch_control::untinted, None) }; + self.drawn(square.bottom()); + self.space(ORB_AIR); + picked + } + + /// A uniform gray channel: a black-to-white ramp across the card (fills from the middle when `range` is signed), its value and the invert glyph + pub(crate) fn ramp(&mut self, label: &str, value: &mut f32, range: RangeInclusive) -> RampEdit { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + let id = self.next_id(); + let track = + Track { start: self.left + KNOB_RADIUS, end: self.right - RAMP_END_INSET, center_y, zero: (*range.start() < 0.0).then_some(0.0), ramp: true }; + let ramp = Rect::from_min_max(pos2(track.start, center_y - RAMP_HEIGHT / 2.0), pos2(track.end, center_y + RAMP_HEIGHT / 2.0)); + self.ui.painter().add(gray_ramp(ramp)); + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field_at(id, label, self.right - RAMP_VALUE_INSET, RAMP_VALUE_WIDTH, center_y, *value, &range, 2, ""); + + let glyph = Rect::from_center_size(pos2(self.right - INVERT_INSET, center_y), vec2(GLYPH_TARGET, GLYPH_TARGET)); + let invert_id = self.next_id(); + let tip = crate::i18n::tr("Invert"); + let response = self.tip(self.ui.interact(glyph, invert_id, Sense::click()), tip); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); + let tokens = self.tokens; + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + DrawnIcon::Invert.paint(self.ui.painter(), glyph.center(), INVERT_GLYPH_SIZE, color); + self.drawn(center_y + KNOB_RADIUS); + RampEdit { changed: Self::apply_typed(value, typed, dragged), invert: response.clicked() } + } + + /// Controls the sheet has no row for yet, laid out by egui between the panel's edges + pub(crate) fn embed(&mut self, body: impl FnOnce(&mut egui::Ui) -> R) -> R { + let width = self.right - self.left; + let top = self.cursor_y(); + let inner = self.ui.horizontal(|ui| { + ui.add_space(self.left - ui.cursor().left()); + ui.vertical(|ui| { + ui.set_width(width); + ui.spacing_mut().item_spacing = CARD_ITEM_SPACING; + body(ui) + }) + .inner + }); + let bottom = inner.response.rect.bottom().max(top); + self.empty = false; + self.drawn(bottom); + inner.inner + } +} + +/// A horizontal black-to-white ramp filling `rect` +fn gray_ramp(rect: Rect) -> Mesh { + let mut mesh = Mesh::default(); + mesh.colored_vertex(rect.left_top(), Color32::BLACK); + mesh.colored_vertex(rect.right_top(), Color32::WHITE); + mesh.colored_vertex(rect.right_bottom(), Color32::WHITE); + mesh.colored_vertex(rect.left_bottom(), Color32::BLACK); + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + mesh +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index e5c97ea2..c3786b5c 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -4,22 +4,27 @@ mod axis_rows; mod band_response; mod button_icon; mod choice; +mod color_bar; +mod color_picker_rows; mod eye_toggle; mod group; mod hold_pad; mod info_icon; +mod material_rows; mod number_field; mod open_card; mod preview_block; mod preview_edit; mod preview_lower; mod preview_size; +mod ramp_edit; mod row; mod row_lead; mod section_tabs; mod sheet_measure; mod slider; mod slot; +mod slot_response; mod stack_slider; mod switch_control; mod tooltip; @@ -37,6 +42,11 @@ pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; pub(crate) use row_lead::RowLead; pub(crate) use section_tabs::{SectionScope, forget_sections, full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box}; +pub(crate) use section_tabs::{ + SectionScope, TAB_GAP, TAB_ICON_CENTER, TAB_ICON_SIZE, TAB_NAME_LEFT, TAB_PADDING, TAB_ROUNDING, TAB_TEXT_SIZE, TAB_TOP, forget_sections, + full_height_tab_rect, in_scope, room_past_end, section_tabs, shown_tab_box, +}; +pub(crate) use slot_response::SlotResponse; pub(crate) use stack_slider::StackSlider; use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; @@ -93,9 +103,15 @@ const ICON_SIZE: f32 = 12.0; const ROW_PICTURE_SIZE: f32 = 18.0; const ROW_PICTURE_AIR: f32 = 8.0; +/// The click square of a glyph button inside a row +const GLYPH_TARGET: f32 = 18.0; + /// How far above and below a row's centre a slider track or a typed value takes the pointer const ROW_HIT_HALF_HEIGHT: f32 = 10.0; +/// Size of a row's glyph button glyphs (eyedropper, remove, arrow) +const GLYPH_SIZE: f32 = 13.0; + /// Corner radius of dropdowns, fields and buttons const CONTROL_RADIUS: u8 = 4; diff --git a/crates/ui-egui/src/property_sheet/ramp_edit.rs b/crates/ui-egui/src/property_sheet/ramp_edit.rs new file mode 100644 index 00000000..db1e61dd --- /dev/null +++ b/crates/ui-egui/src/property_sheet/ramp_edit.rs @@ -0,0 +1,10 @@ +//! What a uniform channel's ramp row did + +/// What a uniform channel's ramp row did this frame +pub(crate) struct RampEdit { + /// `Some(merge)` when the value changed, `merge` true for a drag's later steps + pub(crate) changed: Option, + + /// The invert glyph was clicked + pub(crate) invert: bool, +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index 28af9dd7..bd1f5cc4 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -56,6 +56,12 @@ const RESET_AT_DEFAULT_OPACITY: f32 = 0.4; const SECTION_RESET_INSET: f32 = RESET_ICON_SIZE / 2.0; impl PropertySheet<'_> { + /// A section caption in capitals, a hairline above a later one; `menu` adds the ≡ button + pub(crate) fn section(&mut self, title: &str, menu: bool) -> Option { + let text = self.tokens.text; + self.section_in(title, menu, text) + } + /// [`Self::section`] with the round section reset at the caption's right end: faint and inert at the defaults (`changed` false); returns whether it was clicked pub(crate) fn section_reset(&mut self, title: &str, changed: bool) -> bool { let text = self.tokens.text; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 9ce3760a..08f7eb58 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -30,6 +30,16 @@ const DIAL_ZERO_DEGREES: f32 = 90.0; const DIAL_AIR: f32 = 6.0; impl PropertySheet<'_> { + /// A bounded number; `Some(merge)` when `value` changed, `merge` true for a drag's later steps + pub(crate) fn slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.slider_with_suffix(label, value, range, decimals, "") + } + + /// [`Self::slider`] with a unit after the value ("°", "%") + pub(crate) fn slider_with_suffix(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { + self.slider_led(RowLead::label(label), value, range, decimals, suffix) + } + /// [`Self::slider_with_suffix`] led by `lead` (a picture row, a child setting) pub(crate) fn slider_led(&mut self, lead: RowLead<'_>, value: &mut f32, range: RangeInclusive, decimals: usize, suffix: &str) -> Option { let (control, center_y) = self.row_with(lead); @@ -40,6 +50,21 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } + /// A signed range: fills from zero and marks it with a tick + pub(crate) fn signed_slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, decimals: usize) -> Option { + self.centered_slider(label, value, range, 0.0, decimals) + } + + /// A range whose middle `centre` leaves things as they are: fills from it and marks it with a tick, like a signed range + pub(crate) fn centered_slider(&mut self, label: &str, value: &mut f32, range: RangeInclusive, centre: f32, decimals: usize) -> Option { + let (control, center_y) = self.row(label); + let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(centre), ramp: false }; + let dragged = self.track(id, label, &track, value, &range); + let typed = self.value_field(id, label, center_y, *value, &range, decimals, ""); + Self::apply_typed(value, typed, dragged) + } + /// An angle in degrees: the track, then a small dial just before the value pub(crate) fn angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { self.angle_led(RowLead::label(label), degrees, range) diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index fe2cef24..5bdfb324 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,6 +1,59 @@ use egui::{CornerRadius, FontId, Sense, Stroke, StrokeKind, pos2}; +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; +use egui_phosphor::regular as ic; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; +use super::switch_control::PILL_SIZE; +use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air between a slot card's top and its slot row +const SLOT_CARD_TOP: f32 = 6.0; + +/// Height of a slot row +const SLOT_HEIGHT: f32 = 36.0; + +/// Size of a slot's thumbnail +pub(super) const THUMB_SIZE: f32 = 26.0; + +/// Air between the thumbnail and the slot's name +const THUMB_TO_NAME: f32 = 10.0; + +/// Size of a slot's source line +const SOURCE_TEXT_SIZE: f32 = 10.0; + +/// The slot's name line above its centre and its source line below it +const NAME_ABOVE_CENTER: f32 = 7.0; +const SOURCE_BELOW_CENTER: f32 = 8.0; + +/// The square a slot's end glyph sits in +const SLOT_GLYPH_BOX: f32 = 18.0; + +/// The extra margin the on/off pill answers clicks in +const TOGGLE_HIT_MARGIN: f32 = 3.0; + +/// The seed's dice glyph size +const DICE_ICON_SIZE: f32 = 14.0; + +/// From the right edge to the slot toggle's centre +const SLOT_TOGGLE_INSET: f32 = 11.0; + +/// From the right edge to the × with a toggle beside it, and without +const CLEAR_INSET_WITH_TOGGLE: f32 = 40.0; +const CLEAR_INSET: f32 = 6.0; + +/// Distance between the × and the ⟲ left of it +const RESET_STEP: f32 = 22.0; + +/// Size of the slot's × and ⟲ glyphs +const SLOT_ICON_SIZE: f32 = 12.0; + +/// From the seed field's right edge to its value's right end +const SEED_VALUE_INSET: f32 = 8.0; + +/// Room the seed's dice button takes at the row's end, and the button's width +const DICE_ROOM: f32 = 34.0; +const DICE_WIDTH: f32 = 28.0; /// Air between a full-width button's icon and its words const BUTTON_ICON_GAP: f32 = 8.0; @@ -9,6 +62,103 @@ const BUTTON_ICON_GAP: f32 = 8.0; const BUTTON_ICON_SIZE: f32 = 14.0; impl PropertySheet<'_> { + /// Opens a slot card with its top row: thumbnail, name over source, then ⟲, × and the toggle on the right; the row opens the source list + pub(crate) fn slot( + &mut self, + thumbnail: &dyn Fn(&Painter, Rect), + name: &str, + source: &str, + on: Option<&mut bool>, + clear: bool, + reset: bool, + ) -> SlotResponse { + self.open_card(); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) + } + + /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own + pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { + self.slot_row(thumbnail, name, source, None, clear, None) + } + + /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list + fn slot_row( + &mut self, + thumbnail: &dyn Fn(&Painter, Rect), + name: &str, + source: &str, + on: Option<&mut bool>, + clear: bool, + reset: Option, + ) -> SlotResponse { + let rect = self.take(SLOT_HEIGHT); + let center_y = rect.top() + SLOT_HEIGHT / 2.0; + let enabled = on.as_deref().copied().unwrap_or(true); + let has_toggle = on.is_some(); + let thumb = Rect::from_min_size(pos2(self.left, center_y - THUMB_SIZE / 2.0), vec2(THUMB_SIZE, THUMB_SIZE)); + let clear_x = self.right - if has_toggle { CLEAR_INSET_WITH_TOGGLE } else { CLEAR_INSET }; + let reset_x = if clear { clear_x - RESET_STEP } else { clear_x }; + + // The whole row across the card picks the source, so its list hangs at the card's width; the glyphs on the right take their clicks first + let row = self.bled_row(rect); + let pick_id = self.next_id(); + let pick = self.ui.interact(row, pick_id, Sense::click()); + pick.widget_info(|| egui::WidgetInfo { current_text_value: Some(source.to_owned()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) }); + let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; + + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + thumbnail(&painter, thumb); + painter.rect_stroke( + thumb, + CornerRadius::ZERO, + Stroke::new(1.0, if result.pick.hovered() { tokens.accent } else { tokens.field_border }), + StrokeKind::Inside, + ); + let text_x = thumb.right() + THUMB_TO_NAME; + let (name_font, name_color) = if enabled { (semibold(TEXT_SIZE), tokens.text) } else { (FontId::proportional(TEXT_SIZE), tokens.text_dim) }; + painter.text(pos2(text_x, center_y - NAME_ABOVE_CENTER), Align2::LEFT_CENTER, name, name_font, name_color); + painter.text(pos2(text_x, center_y + SOURCE_BELOW_CENTER), Align2::LEFT_CENTER, source, FontId::proportional(SOURCE_TEXT_SIZE), tokens.text_dim); + + for (shown, live, x, glyph, tip, slot) in [ + (clear, true, clear_x, ic::X, crate::i18n::n_("Clear"), &mut result.clear), + (reset.is_some(), reset.unwrap_or(false), reset_x, ic::CLOCK_COUNTER_CLOCKWISE, crate::i18n::n_("Restore defaults"), &mut result.reset), + ] { + if !shown { + continue; + } + + let glyph_rect = Rect::from_center_size(pos2(x, center_y), Vec2::splat(SLOT_GLYPH_BOX)); + let id = self.next_id(); + + // At the defaults the ⟲ is faint and inert, as on a band: a click there picks the source like the rest of the row + let response = if live { + self.tip(self.ui.interact(glyph_rect, id, Sense::click()), crate::i18n::tr(tip)) + } else { + self.ui.interact(glyph_rect, id, Sense::hover()) + }; + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(tip))); + *slot = live && response.clicked(); + let color = self.reset_glyph_color(live, response.hovered(), tokens.text); + painter.text(glyph_rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(SLOT_ICON_SIZE), color); + } + + if let Some(on) = on { + let pill = Rect::from_center_size(pos2(self.right - SLOT_TOGGLE_INSET, center_y), PILL_SIZE); + let id = self.next_id(); + let response = self.ui.interact(pill.expand(TOGGLE_HIT_MARGIN), id, Sense::click()); + if response.clicked() { + *on = !*on; + result.toggled = true; + } + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, name)); + self.pill(pill.center(), *on, true); + } + self.drawn(thumb.bottom()); + result + } + /// A full-width button: centred icon and words pub(crate) fn button<'a>(&mut self, icon: impl Into>, text: &str) -> egui::Response { self.button_lit(icon, text, false) @@ -52,6 +202,7 @@ impl PropertySheet<'_> { let galley = painter.layout_no_wrap(glyph.to_owned(), FontId::proportional(BUTTON_ICON_SIZE), color); (galley.size().x, Some(galley)) } + ButtonIcon::Drawn(_) => (BUTTON_ICON_SIZE, None), }; let text_galley = painter.layout_no_wrap(text.to_owned(), font, color); let total = icon_width + BUTTON_ICON_GAP + text_galley.size().x; @@ -59,8 +210,78 @@ impl PropertySheet<'_> { if let Some(galley) = icon_galley { painter.galley(pos2(x, button.center().y - galley.size().y / 2.0), galley, color); } + if let ButtonIcon::Drawn(drawn) = icon { + drawn.paint(painter, pos2(x + icon_width / 2.0, button.center().y), BUTTON_ICON_SIZE, color); + } painter.galley(pos2(x + icon_width + BUTTON_ICON_GAP, button.center().y - text_galley.size().y / 2.0), text_galley, color); self.drawn(button.bottom()); response } + + /// A seed: its field (click to type) and the dice button, which picks a new one. Returns true when the seed changed + pub(crate) fn seed(&mut self, label: &str, seed: &mut u32) -> bool { + let (control, center_y) = self.row(label); + let field = Rect::from_min_max(control.min, pos2(self.right - DICE_ROOM, control.bottom())); + let dice = Rect::from_min_max(pos2(self.right - DICE_WIDTH, control.top()), control.max); + + let id = self.next_id(); + let typing_id = id.with("typed"); + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect(field, CornerRadius::same(CONTROL_RADIUS), tokens.field, Stroke::new(1.0, tokens.field_border), StrokeKind::Inside); + + // The value sits right like every number; the box lights on hover and goes accent while typing + let mut changed = false; + if let Some(mut text) = self.ui.data(|data| data.get_temp::(typing_id)) { + let edit = egui::TextEdit::singleline(&mut text).id(typing_id).font(semibold(TEXT_SIZE)).align(egui::Align2::RIGHT_CENTER); + let response = self.typing_edit(field.left() + SEED_VALUE_INSET, field.right() - SEED_VALUE_INSET, center_y, edit); + painter.rect_stroke(field, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + + if response.lost_focus() { + let untouched = self.end_typing(typing_id, &text); + if let Ok(typed) = text.trim().parse::() + && !untouched + && typed != *seed + && !self.ui.input(|input| input.key_pressed(egui::Key::Escape)) + { + *seed = typed; + changed = true; + } + } else { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + } + } else { + self.skip_typing_edit(); + let response = self.ui.interact(field, id, Sense::click()).on_hover_cursor(egui::CursorIcon::Text); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, crate::i18n::trf("{label} value", &[("label", &label)]))); + painter.text(pos2(field.right() - SEED_VALUE_INSET, center_y), Align2::RIGHT_CENTER, seed.to_string(), semibold(TEXT_SIZE), tokens.text); + + if response.hovered() { + painter.rect_stroke(field, CornerRadius::same(CONTROL_RADIUS), Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + if response.clicked() { + self.start_typing(typing_id, seed.to_string()); + } + } + + // The dice picks the next seed + let dice_id = self.next_id(); + let dice_response = self.tip(self.ui.interact(dice, dice_id, Sense::click()), crate::i18n::tr("Random")); + painter.rect( + dice, + CornerRadius::same(CONTROL_RADIUS), + if dice_response.hovered() { tokens.row_hover } else { tokens.button }, + Stroke::new(1.0, tokens.button_border), + StrokeKind::Inside, + ); + painter.text(dice.center(), Align2::CENTER_CENTER, ic::DICE_FIVE, FontId::proportional(DICE_ICON_SIZE), tokens.text); + dice_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, crate::i18n::tr("Random"))); + + if dice_response.clicked() { + changed = true; + } + changed + } +} + } diff --git a/crates/ui-egui/src/property_sheet/slot_response.rs b/crates/ui-egui/src/property_sheet/slot_response.rs new file mode 100644 index 00000000..7fac7e34 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot_response.rs @@ -0,0 +1,15 @@ +/// What a slot card's top row did this frame +#[derive(Clone, Debug)] +pub(crate) struct SlotResponse { + /// The slot's row: a click opens the source list hanging from it (see [`super::PropertySheet::hanging_list`]) + pub(crate) pick: egui::Response, + + /// The × was clicked: back to a uniform source + pub(crate) clear: bool, + + /// The ⟲ was clicked: restore the slot's defaults + pub(crate) reset: bool, + + /// The slot's toggle was flipped + pub(crate) toggled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 03677ab4..c8210d11 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -32,25 +32,35 @@ const PILL_RADIUS: u8 = 6; const TOGGLE_KNOB_RADIUS: f32 = 4.0; const TOGGLE_KNOB_TRAVEL: f32 = 4.5; +/// Air after a toggle's label, before the column the panel's toggles line up on +const TOGGLE_LABEL_AIR: f32 = 10.0; + +/// From that column to the pill's centre: the pill starts on the column +const TOGGLE_CENTER_OFFSET: f32 = PILL_SIZE.x / 2.0; + /// From one of a pair's toggles to the next, and from its name to its pill's centre const PAIR_PITCH: f32 = 76.0; const PAIR_NAME_TO_PILL: f32 = 32.0; -/// Width of a focused control's outline in points -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +/// Height of a channel pill, and the air between pills +const CHANNEL_PILL_HEIGHT: f32 = 22.0; +const CHANNEL_PILL_GAP: f32 = 4.0; + +/// Corner radius of a channel pill: half its height, so its ends are round +const CHANNEL_PILL_RADIUS: u8 = 11; + +/// Air under the channel strip +const CHANNEL_STRIP_AIR: f32 = 6.0; + +/// The least air around a channel pill's name before the names shrink a point +const PILL_TEXT_AIR: f32 = 10.0; + +/// No tint for any segment: the chosen word keeps the text colour +pub(super) fn untinted(_index: usize) -> &'static [Color32] { + &[] +} impl PropertySheet<'_> { - pub(super) fn paint_control_focus(&self, response: &Response) { - if response.has_focus() { - self.ui.painter().rect_stroke( - response.rect, - CornerRadius::same(CONTROL_RADIUS), - Stroke::new(FOCUS_OUTLINE_WIDTH, self.tokens.text_strong), - StrokeKind::Inside, - ); - } - } - /// Two to four short choices as a boxed switch, or a dropdown when one doesn't fit; returns the picked index pub(crate) fn switch(&mut self, label: &str, options: &[&str], selected: usize) -> Option { self.switch_tinted(label, options, selected, &[]) @@ -81,6 +91,20 @@ impl PropertySheet<'_> { self.dropdown_built(label, selected, || 0..options.len(), name, None).0 } + /// A row's control box, `CONTROL_HEIGHT` tall, from the left padding to the right one + pub(super) fn wide_row(&mut self) -> Rect { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + super::CONTROL_HEIGHT / 2.0); + Rect::from_x_y_ranges(self.left..=self.right, (center_y - super::CONTROL_HEIGHT / 2.0)..=(center_y + super::CONTROL_HEIGHT / 2.0)) + } + + /// A boxed switch across the whole panel (a mode switch at the top of a group), each word led by its picture; returns the picked index + pub(crate) fn picture_switch(&mut self, options: &[&str], selected: usize, picture: SegmentPicture<'_>) -> Option { + let control = self.wide_row(); + self.segments(control, options, selected, untinted, Some(picture)) + } + /// A boxed switch's box and segments in `control`, the chosen word in the colours `tints` gives its index (none: the text colour); returns the segment clicked when it was not the chosen one pub(super) fn segments<'t>( &mut self, @@ -136,6 +160,27 @@ impl PropertySheet<'_> { picked } + /// An on/off beside its label; every toggle in a panel lines up past the longest toggle label + pub(crate) fn toggle(&mut self, label: &str, on: &mut bool) -> bool { + let rect = self.take(ROW_HEIGHT); + let center_y = rect.center().y; + let label_x = self.left + self.lead_shift(); + self.paint_info(center_y); + let font = FontId::proportional(TEXT_SIZE); + let label_end = label_x - self.left + self.text_width(label, font.clone()) + TOGGLE_LABEL_AIR; + self.seen.toggle_label_end = self.seen.toggle_label_end.max(label_end); + + let column = (self.column() - self.left).max(self.used.toggle_label_end).max(label_end); + let pill = Rect::from_center_size(pos2(self.left + column + TOGGLE_CENTER_OFFSET, center_y), PILL_SIZE); + let clicked = self.toggle_hit(Rect::from_min_max(pos2(label_x, rect.top()), pos2(pill.right(), rect.bottom())), label, on); + + let text = self.tokens.text; + self.ui.painter().text(pos2(label_x, center_y), Align2::LEFT_CENTER, label, font, text); + self.pill(pill.center(), *on, true); + self.drawn(center_y + PILL_SIZE.y / 2.0); + clicked + } + /// A culling row on the panel's grid: its name on the label column, its picture where the controls start with the switch after it, a pending i at the row's right end pub(crate) fn picture_toggle(&mut self, picture: RowPicture<'_>, label: &str, on: &mut bool) -> bool { let rect = self.take(ROW_HEIGHT); @@ -209,6 +254,50 @@ impl PropertySheet<'_> { painter.rect(Rect::from_center_size(center, PILL_SIZE), CornerRadius::same(PILL_RADIUS), fill, Stroke::new(1.0, border), StrokeKind::Inside); painter.circle_filled(pos2(knob_x, center.y), TOGGLE_KNOB_RADIUS, knob); } + + /// The channel strip: one pill per channel; returns the clicked index and whether Alt (solo) was held + pub(crate) fn channel_pills(&mut self, names: &[&str], on: &[bool]) -> Option<(usize, bool)> { + let rect = self.take(CHANNEL_PILL_HEIGHT); + let count = names.len().max(1) as f32; + let width = (self.right - self.left - (count - 1.0) * CHANNEL_PILL_GAP) / count; + let size = if names.iter().all(|name| self.text_width(name, semibold(SMALL_TEXT_SIZE)) + PILL_TEXT_AIR <= width) { + SMALL_TEXT_SIZE + } else { + SMALL_TEXT_SIZE - 1.0 + }; + + let tokens = self.tokens; + let mut clicked = None; + for (index, name) in names.iter().enumerate() { + let pill = Rect::from_min_size(pos2(self.left + index as f32 * (width + CHANNEL_PILL_GAP), rect.top()), vec2(width, CHANNEL_PILL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(pill, id, Sense::click()); + if response.clicked() { + clicked = Some((index, self.ui.input(|input| input.modifiers.alt))); + } + + let enabled = on.get(index).copied().unwrap_or(false); + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, enabled, *name)); + let (fill, border, color, font) = if enabled { + (tokens.accent_dim, tokens.accent, tokens.text, semibold(size)) + } else { + (tokens.field, tokens.field_border, tokens.text_dim, FontId::proportional(size)) + }; + let painter = self.ui.painter(); + painter.rect( + pill, + CornerRadius::same(CHANNEL_PILL_RADIUS), + if response.hovered() && !enabled { tokens.row_hover } else { fill }, + Stroke::new(1.0, border), + StrokeKind::Inside, + ); + painter.text(pill.center(), Align2::CENTER_CENTER, *name, font, color); + } + self.drawn(rect.bottom()); + self.space(CHANNEL_STRIP_AIR); + self.air_at = Some(self.cursor_y()); + clicked + } } /// `word` laid out with its letters split as evenly as they go between the colours of `runs` diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 11b20f48..2cc6c702 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -1,6 +1,7 @@ use egui::{Color32, CornerRadius, Painter, Rect}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable as _; +use egui_phosphor::regular as ic; use super::number_field::shown_number; use super::{NumberField, PropertySheet}; @@ -18,6 +19,9 @@ const PANEL_WIDTH: f32 = 300.0; /// The harness window: the panel plus room on its right for popups and tips, tall enough for the whole gallery unscrolled const HARNESS_SIZE: egui::Vec2 = egui::vec2(PANEL_WIDTH + 260.0, 1000.0); +/// The i of the gallery's Depth Culling row +const DEPTH_CULLING_TIP: &str = "Paints only the surface the projector sees first"; + fn swatch(color: Color32) -> impl Fn(&Painter, Rect) { move |painter: &Painter, rect: Rect| { painter.rect_filled(rect, CornerRadius::ZERO, color); @@ -38,6 +42,10 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { egui::Frame::NONE.fill(panel).show(ui, |ui| { ui.set_width(PANEL_WIDTH); PropertySheet::show(ui, "gallery", |sheet| { + sheet.section("Fill", true); + if let Some(scale) = sheet.switch("Scale", &["Tiling", "Physical size"], state.scale) { + state.scale = scale; + } if let Some(picked) = sheet .dropdown( "Filtering", @@ -50,6 +58,24 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { { state.filtering = picked; } + if let Some(merge) = sheet.slider("Hardness", &mut state.hardness, 0.0..=1.0, 2) { + state.hardness_merges.push(merge); + } + sheet.signed_slider("Offset", &mut state.offset, -1.0..=1.0, 2); + sheet.angle("Rotation", &mut state.rotation, 0.0..=360.0); + let names = ["Projection Extends Outside Shape", "Projection Is Cropped To Shape"]; + if let Some(picked) = sheet + .dropdown( + "A label wider than the column's cap", + state.long_choice, + &[0, 1], + |index| names.get(index).copied().unwrap_or_default().to_owned(), + None, + ) + .0 + { + state.long_choice = picked; + } let reset = sheet.band("3D projection settings", true, Some(state.position != [0.0; 3]), None); if reset.reset { @@ -71,6 +97,32 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { state.position_merges.push(merge); } } + + sheet.toggle("Wrap", &mut state.wrap); + sheet.toggle("Shape Crop", &mut state.crop); + sheet.info(DEPTH_CULLING_TIP); + sheet.picture_toggle(&swatch(Color32::from_gray(160)), "Depth Culling", &mut state.depth_culling); + sheet.picture_toggle(&swatch(Color32::from_gray(100)), "Backface Culling", &mut state.backface_culling); + sheet.slot(&swatch(Color32::from_rgb(0xb0, 0x5a, 0x3a)), "Base color", "Uniform color", Some(&mut state.channel_on), false, false); + sheet.slider("Value", &mut state.channel_value, 0.0..=1.0, 2); + + sheet.section("Filter", false); + if let Some((index, _)) = sheet.channel_pills(&["Color", "Metal", "Rough", "Normal", "Height"], &state.channels) + && let Some(on) = state.channels.get_mut(index) + { + *on = !*on; + } + let band = sheet.band("Parameters", true, None, Some("3")); + if band.open { + sheet.signed_slider("Horizontal", &mut state.offset, -1.0..=1.0, 2); + if sheet.fold("Attributes", Some("Default"), false) { + sheet.button(ic::DOT, "No attributes"); + } + sheet.seed("Seed", &mut state.seed); + if sheet.button(ic::DICE_FIVE, "Randomize seeds").clicked() { + state.randomized += 1; + } + } }); }); } @@ -89,6 +141,85 @@ fn gallery_harness(brightness: Brightness, gallery_state: Gallery) -> Harness<'s harness } +#[test] +fn toggles_switches_and_pills_change_their_state() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let at = harness.get_by_label("Shape Crop").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Physical size").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Normal").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert!(harness.state().crop); + assert_eq!(harness.state().scale, 1); + assert_eq!(harness.state().channels, [true, true, true, true, true]); +} + +#[test] +fn keyboard_focus_is_visible_on_switches_toggles_and_channel_pills() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for brightness in [Brightness::MediumDark, Brightness::Light] { + let mut harness = builder(brightness).build_ui(|ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "keyboard", |sheet| { + sheet.switch("Scale", &["Tiling", "Physical size"], 0); + sheet.toggle("Shape Crop", &mut false); + sheet.channel_pills(&["Normal"], &[true]); + }); + }); + harness.run_steps(3); + + for label in ["Tiling", "Physical size", "Shape Crop", "Normal"] { + harness.key_press(egui::Key::Tab); + harness.run_steps(2); + + let node = harness.get_by_label(label); + assert!(node.is_focused(), "{label} receives keyboard focus"); + + let rect = node.rect(); + assert!( + harness.output().shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.stroke.width > 1.0 && shape.rect.center().distance(rect.center()) < 1.0) + }), + "{label} paints a visible focus outline" + ); + } + } +} + +/// A toggle's pill starts on the controls column, where a dropdown's button starts (it sat 3 px in) +#[test] +fn a_toggles_pill_starts_where_a_dropdown_starts() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let dropdown = harness.get_by_label("Bilinear | HQ").rect(); + + // The toggle's hit area ends with its pill + let pill_left = harness.get_by_label("Shape Crop").rect().right() - super::switch_control::PILL_SIZE.x; + assert_eq!(pill_left, dropdown.left(), "the pill starts at {pill_left}, the dropdown at {}", dropdown.left()); +} + +/// A culling row sits on the panel's grid like a plain toggle: its name on the label column, its picture and switch where the controls start, its i at the row's end +#[test] +fn a_culling_row_reads_name_then_picture_and_switch_with_its_i_at_the_end() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let culling = harness.get_by_label("Depth Culling").rect(); + let plain = harness.get_by_label("Wrap").rect(); + let info = harness.get_by_label(DEPTH_CULLING_TIP).rect(); + assert_eq!(culling.left(), plain.left(), "the name starts where a plain toggle's does: {culling:?} vs {plain:?}"); + assert!(info.left() > culling.right(), "the i sits after the switch, at the row's end: {info:?} vs {culling:?}"); + + let was = harness.state().depth_culling; + let at = harness.get_by_label("Depth Culling").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert_ne!(harness.state().depth_culling, was, "a click on the row flips it"); +} + /// Two culling rows, the second named past the label column fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { let panel = Tokens::get(ui.ctx()).panel; @@ -191,6 +322,86 @@ fn click_at(harness: &mut Harness<'_, State>, at: egui::Pos2) { harness.run_steps(1); } +/// Clicks at `at`, then types `text` into the field that opened and presses Enter +fn type_at(harness: &mut Harness<'_, Gallery>, at: egui::Pos2, text: &str) { + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + harness.get_by_role(egui::Role::TextInput).type_text(text); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); +} + +#[test] +fn a_click_on_a_value_or_the_seed_selects_it_so_typing_replaces_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let value = harness.get_by_label("Hardness value").rect(); + type_at(&mut harness, value.center(), "0.4"); + assert_eq!(harness.state().hardness, 0.4, "the slider's value is replaced, not appended to"); + + let seed = harness.get_by_label("Seed value").rect(); + type_at(&mut harness, seed.center(), "77"); + assert_eq!(harness.state().seed, 77, "the seed is replaced, not appended to"); +} + +/// Clicks at `at` to type, then presses Enter without typing +fn open_and_leave_at(harness: &mut Harness<'_, Gallery>, at: egui::Pos2) { + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_some(), "a click at {at:?} opens the value to type"); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_none(), "Enter closes the value at {at:?}"); +} + +/// A value opened to type and left as it opened is not an edit: no undo step, and its hidden digits are not rounded away +#[test] +fn a_value_opened_and_left_untyped_changes_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 0.333, position: [1.2345, 0.0, 0.0], ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + let position = harness.get_by_label("Position X").rect(); + + open_and_leave_at(&mut harness, hardness.center()); + open_and_leave_at(&mut harness, position.center()); + + assert_eq!(harness.state().hardness, 0.333, "the slider keeps its unrounded value"); + assert!(harness.state().hardness_merges.is_empty(), "the slider reports no edit: {:?}", harness.state().hardness_merges); + assert_eq!(harness.state().position[0], 1.2345, "the number field keeps its unrounded value"); + assert!(harness.state().position_merges.is_empty(), "the number field reports no edit: {:?}", harness.state().position_merges); +} + +/// A value opened to type and left untyped while something else changed it (an agent's command) keeps the newer value: no edit, no undo step +#[test] +fn a_value_left_untyped_keeps_a_change_made_while_it_was_open() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 0.333, position: [1.2345, 0.0, 0.0], ..Gallery::default() }); + for (newer_seed, label) in (1..).zip(["Hardness value", "Position X", "Seed value"]) { + let at = harness.get_by_label(label).rect().center(); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_some(), "{label}: the click opens the value to type"); + + // Changed elsewhere while the field is open, then Enter without typing + harness.state_mut().hardness = 0.9; + harness.state_mut().position[0] = 0.5; + harness.state_mut().seed = newer_seed; + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); + assert!(harness.query_by_role(egui::Role::TextInput).is_none(), "{label}: Enter closes the value"); + assert_eq!(harness.state().hardness, 0.9, "{label}: the slider keeps the newer value"); + assert_eq!(harness.state().position[0], 0.5, "{label}: the number field keeps the newer value"); + assert_eq!(harness.state().seed, newer_seed, "{label}: the seed keeps the newer value"); + } + assert!(harness.state().hardness_merges.is_empty(), "the slider reports no edit: {:?}", harness.state().hardness_merges); + assert!(harness.state().position_merges.is_empty(), "the number field reports no edit: {:?}", harness.state().position_merges); +} + /// A reason too long for its caption's row is cut with "…", and hovering it shows it whole #[test] fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { @@ -211,6 +422,87 @@ fn a_cut_unavailable_reason_reads_whole_in_its_tooltip() { assert!(harness.get_all_by_label(REASON).count() > 1, "its tooltip reads it whole"); } +/// A typed value that lands on the current one is no edit: one past the end kept at the end, or the same number written another way +#[test] +fn a_typed_value_equal_to_the_current_one_changes_nothing() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 1.0, ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + type_at(&mut harness, hardness.center(), "5"); + assert_eq!(harness.state().hardness, 1.0, "a value past the end is kept at the end"); + assert!(harness.state().hardness_merges.is_empty(), "kept at the value it had, it reports no edit: {:?}", harness.state().hardness_merges); + + harness.state_mut().hardness = 0.75; + harness.run_steps(1); + type_at(&mut harness, hardness.center(), ".750"); + assert_eq!(harness.state().hardness, 0.75); + assert!(harness.state().hardness_merges.is_empty(), "the same number written another way reports no edit: {:?}", harness.state().hardness_merges); +} + +/// A value just under zero opens to type as it reads, without a minus sign +#[test] +fn a_value_just_under_zero_opens_without_a_minus_sign() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: -0.001, ..Gallery::default() }); + let hardness = harness.get_by_label("Hardness value").rect(); + harness.drag_at(hardness.center()); + harness.drop_at(hardness.center()); + harness.run_steps(2); + assert_eq!(harness.get_by_role(egui::Role::TextInput).value().as_deref(), Some("0.00")); +} + +#[test] +fn a_drag_merges_after_its_first_step_and_a_click_does_not() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let track = harness.get_by_label("Hardness").rect(); + harness.drag_at(track.center()); + harness.run(); + harness.hover_at(track.center() + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(track.center() + egui::vec2(40.0, 0.0)); + harness.run(); + harness.drop_at(track.center() + egui::vec2(40.0, 0.0)); + harness.run(); + let drag_merges = harness.state().hardness_merges.clone(); + + let click = track.left_center() + egui::vec2(20.0, 0.0); + harness.drag_at(click); + harness.drop_at(click); + harness.run(); + + assert!(drag_merges.len() >= 2, "the drag changes the value more than once: {drag_merges:?}"); + assert_eq!(drag_merges.first(), Some(&false), "the drag's first change starts an undo step: {drag_merges:?}"); + assert!(drag_merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {drag_merges:?}"); + let merges = &harness.state().hardness_merges; + assert_eq!(merges.len(), drag_merges.len() + 1, "the click changes the value once: {merges:?}"); + assert_eq!(merges.last(), Some(&false), "the click starts its own undo step: {merges:?}"); +} + +/// A drag whose first frames change nothing (the knob held at its end) still starts its own undo step with its first change +#[test] +fn a_drag_pressed_past_the_tracks_end_starts_an_undo_step_with_its_first_change() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery { hardness: 1.0, ..Gallery::default() }); + let track = harness.get_by_label("Hardness").rect(); + let past_end = track.right_center() - egui::vec2(1.0, 0.0); + harness.drag_at(past_end); + harness.run(); + harness.hover_at(past_end + egui::vec2(20.0, 0.0)); + harness.run(); + harness.hover_at(track.center()); + harness.run(); + harness.hover_at(track.center() - egui::vec2(20.0, 0.0)); + harness.run(); + harness.drop_at(track.center() - egui::vec2(20.0, 0.0)); + harness.run(); + + let merges = &harness.state().hardness_merges; + assert!(merges.len() >= 2, "the drag changes the value more than once: {merges:?}"); + assert_eq!(merges.first(), Some(&false), "the first real change starts an undo step: {merges:?}"); + assert!(merges.iter().skip(1).all(|merge| *merge), "later changes continue it: {merges:?}"); +} + /// A number field held still until egui starts its drag, then moved, starts its own undo step with its first change #[test] fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_change() { @@ -234,6 +526,82 @@ fn a_number_field_held_still_then_dragged_starts_an_undo_step_with_its_first_cha assert!(merges.iter().skip(1).all(|merge| *merge), "later moves continue it: {merges:?}"); } +#[test] +fn the_label_column_fits_the_widest_short_label_and_long_labels_stack() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let hardness = harness.get_by_label("Hardness").rect(); + let filtering = harness.get_by_label("Bilinear | HQ").rect(); + let crop = harness.get_by_label("Projection Extends Outside Shape").rect(); + + let column = filtering.left(); + assert!((hardness.left() - column).abs() < 0.5, "sliders start on the controls column"); + assert!(crop.left() < column, "a label wider than the cap stacks above a full-width control"); +} + +#[test] +fn reset_restores_the_band_and_the_seed_dice_steps_deterministically() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = gallery_harness(Brightness::MediumDark, Gallery::default()); + let at = harness.get_by_label("Random").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Restore defaults").rect().center(); + click_at(&mut harness, at); + let at = harness.get_by_label("Randomize seeds").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert_eq!(harness.state().seed, next_seed(1234)); + assert_eq!(harness.state().position, [0.0; 3]); + assert_eq!(harness.state().randomized, 1); +} + +/// The gallery in every theme, closed and with a list open, for comparing with the mockups +#[test] +#[ignore] +fn property_sheet_gallery_snapshots() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + let mut harness = builder(brightness).with_pixels_per_point(2.0).wgpu().build_ui_state(gallery, Gallery::default()); + harness.run_steps(4); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}.png"))).unwrap(); + + let at = harness.get_by_label("Bilinear | HQ").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + harness.get_by_label("Bilinear | Sharp").hover(); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-list-open.png"))).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // A value: the grey line on hover, then typing on that line in accent; the seed's box lights the same way + let value = harness.get_by_label("Hardness value").rect().center(); + harness.hover_at(value); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-value-hover.png"))).unwrap(); + harness.drag_at(value); + harness.drop_at(value); + harness.run_steps(2); + harness.get_by_role(egui::Role::TextInput).type_text("0.4"); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-value-typing.png"))).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + let seed = harness.get_by_label("Seed value").rect().center(); + harness.hover_at(seed); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-seed-hover.png"))).unwrap(); + harness.drag_at(seed); + harness.drop_at(seed); + harness.run_steps(2); + harness.render().unwrap().save(output_dir.join(format!("sheet-{name}-seed-typing.png"))).unwrap(); + } +} + #[test] fn a_number_field_reads_zero_without_a_minus_sign() { assert_eq!(shown_number(-0.0, 0), "0"); @@ -243,3 +611,168 @@ fn a_number_field_reads_zero_without_a_minus_sign() { assert_eq!(shown_number(-1.25, 2), "-1.25"); assert_eq!(shown_number(2.5, 1), "2.5"); } + +/// Folds keep their own open state when a fold above them comes and goes (the state follows the name, not the row's place) +#[test] +fn a_fold_keeps_its_state_when_rows_above_it_come_and_go() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let folds = |ui: &mut egui::Ui, extra_shown: &mut bool| { + PropertySheet::show(ui, "folds", |sheet| { + if *extra_shown && sheet.fold("Extra", None, true) { + sheet.button(ic::DOT, "Extra rows"); + } + if sheet.fold("Edges", None, true) { + sheet.button(ic::DOT, "Edge rows"); + } + if sheet.fold("Parameters", None, false) { + sheet.button(ic::DOT, "Parameter rows"); + } + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(folds, true); + harness.run_steps(2); + let at = harness.get_by_label("Edges").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_label("Edge rows").is_none(), "Edges stays folded"); + assert!(harness.query_by_label("Parameter rows").is_none(), "Parameters stays folded"); +} + +/// Two colour bars, one under the other, each opening its own picker +fn two_color_bars(ui: &mut egui::Ui) { + PropertySheet::show(ui, "color_bars", |sheet| { + sheet.color_bar("Bar A", [0.2, 0.4, 0.6], None, &[]); + sheet.color_bar("Bar B", [0.6, 0.4, 0.2], None, &[]); + }); +} + +/// The colour space picked in one picker is the one the next picker opens in, even for a bar drawn before it all along +#[test] +fn the_next_picker_opens_in_the_colour_space_last_picked() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui(two_color_bars); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar B").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::ComboBox, "sRGB").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Linear").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, "Linear").is_some(), "Bar B's picker shows Linear"); + + let at = harness.get_by_role_and_label(egui::Role::Button, "Close").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar A").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Bar A").is_some(), "Bar A's picker is open"); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, "Linear").is_some(), "Bar A's picker opens in Linear"); +} + +/// A colour bar's picker stays open when a colour bar above it comes and goes (its state follows its name, not its place) +#[test] +fn a_color_bars_picker_stays_open_when_a_row_above_it_goes_away() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let bars = |ui: &mut egui::Ui, extra_shown: &mut bool| { + PropertySheet::show(ui, "color_bars", |sheet| { + if *extra_shown { + sheet.color_bar("Extra", [0.5; 3], None, &[]); + } + sheet.color_bar("Tint", [0.2, 0.4, 0.6], None, &[]); + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(bars, true); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Tint").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Tint").is_some(), "the picker opened"); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_role_and_label(egui::Role::TitleBar, "Tint").is_some(), "the picker stays open"); +} + +/// A fold under a later section, before that section's first band, keeps its state when a band of the section above comes and goes +#[test] +fn a_fold_before_a_sections_first_band_keeps_its_state_when_the_band_above_goes_away() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let sections = |ui: &mut egui::Ui, band_shown: &mut bool| { + PropertySheet::show(ui, "sections", |sheet| { + sheet.section("First", false); + if *band_shown && sheet.band("Band", true, None, None).open { + sheet.button(ic::DOT, "Band rows"); + } + sheet.section("Second", false); + if sheet.fold("Edges", None, true) { + sheet.button(ic::DOT, "Edge rows"); + } + }); + }; + let mut harness = builder(Brightness::MediumDark).build_ui_state(sections, true); + harness.run_steps(2); + let at = harness.get_by_label("Edges").rect().center(); + click_at(&mut harness, at); + harness.run_steps(2); + assert!(harness.query_by_label("Edge rows").is_none()); + + *harness.state_mut() = false; + harness.run_steps(2); + + assert!(harness.query_by_label("Edge rows").is_none(), "Edges stays folded"); +} + +/// The colour picker's hex field ends where the colour field above it ends (it ended 4 px short) +#[test] +fn the_pickers_hex_field_ends_on_the_colour_fields_right_edge() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui(two_color_bars); + harness.run_steps(2); + let at = harness.get_by_role_and_label(egui::Role::Button, "Bar A").rect().center(); + + click_at(&mut harness, at); + harness.run_steps(2); + + let field = harness.get_by_role_and_label(egui::Role::Slider, "Saturation and value").rect(); + let hex = harness.get_by_role_and_label(egui::Role::TextInput, "Hex color").rect(); + assert_eq!(hex.right(), field.right(), "the hex field ends at {}, the colour field at {}", hex.right(), field.right()); +} + +/// A linked Tiling and Offset block over a ramp +fn ramp_under_tiling(ui: &mut egui::Ui, state: &mut ([f32; 2], [f32; 2], bool, f32)) { + let (tiling, offset, linked, gray) = state; + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "ramp", |sheet| { + let size = super::PreviewSize { label: "Tiling", values: tiling, range: 0.0..=10.0, typed: 0.0..=100.0, decimals: 2, linked }; + let lower = super::PreviewLower::Offset { values: offset, range: 0.0..=1.0, typed: -10.0..=10.0 }; + sheet.preview_block(&swatch(Color32::from_gray(128)), size, lower); + sheet.ramp("Grayscale", gray, 0.0..=1.0); + }); + }); +} + +/// A ramp's value ends on the linked Tiling and Offset values above it (it ended 2 px right of them) +#[test] +fn a_ramps_value_ends_on_the_linked_tiling_value() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(ramp_under_tiling, ([1.0; 2], [0.0; 2], true, 0.5)); + + harness.run_steps(3); + + let tiling = harness.get_by_label("Tiling value").rect(); + let ramp = harness.get_by_label("Grayscale value").rect(); + assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); +} diff --git a/crates/ui-egui/src/property_sheet/tests/gallery.rs b/crates/ui-egui/src/property_sheet/tests/gallery.rs index b1774512..2332a36b 100644 --- a/crates/ui-egui/src/property_sheet/tests/gallery.rs +++ b/crates/ui-egui/src/property_sheet/tests/gallery.rs @@ -3,15 +3,52 @@ use super::Filtering; /// The gallery's controls, with the values they last set +/// Every control of the shared set once, with the values the gallery last set pub(super) struct Gallery { + pub(super) scale: usize, pub(super) filtering: Filtering, + pub(super) hardness: f32, + pub(super) hardness_merges: Vec, + pub(super) offset: f32, + pub(super) rotation: f32, pub(super) position: [f32; 3], pub(super) position_merges: Vec, pub(super) linked: bool, + pub(super) wrap: bool, + pub(super) crop: bool, + pub(super) depth_culling: bool, + pub(super) backface_culling: bool, + pub(super) channel_on: bool, + pub(super) channels: [bool; 5], + pub(super) channel_value: f32, + pub(super) seed: u32, + pub(super) randomized: u32, + pub(super) long_choice: usize, } impl Default for Gallery { fn default() -> Self { Gallery { filtering: Filtering::BilinearHq, position: [0.0, 1.25, -0.5], position_merges: Vec::new(), linked: true } + Gallery { + scale: 0, + filtering: Filtering::BilinearHq, + hardness: 0.75, + hardness_merges: Vec::new(), + offset: -0.25, + rotation: 30.0, + position: [0.0, 1.25, -0.5], + position_merges: Vec::new(), + linked: true, + wrap: true, + crop: false, + depth_culling: true, + backface_culling: false, + channel_on: true, + channels: [true, true, true, false, true], + channel_value: 0.8, + seed: 1234, + randomized: 0, + long_choice: 0, + } } } diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index c54113d0..a590761a 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -161,7 +161,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }; let shown = ctx.memory(|memory| memory.area_rect(area_id())); - if closed_by_input(ctx, shown, strip) { + + // An eyedropper pick's click on the model hands its colour back to the popup + if app.picking_color.is_none() && closed_by_input(ctx, shown, strip) { app.ui.rail_panel = None; let held = ctx.input(|input| input.pointer.any_down()); ctx.data_mut(|data| data.insert_temp(area_id().with("closing"), held)); @@ -212,12 +214,13 @@ fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { (Pos2::new(right, icon.top()), width) } -/// A press outside the popup and the rail, unless in one of the popup's own dropdowns +/// A press outside the popup and the rail, unless in one of the popup's own dropdowns or its colour picker window fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); - // A press on the rail is left to its icons, which switch or close the popup themselves - let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at))); + // A press on the rail is left to its icons, which switch or close the popup themselves; one in the popup's colour picker window stays in the popup + let in_picker = |at: Pos2| crate::color_picker::open_window(ctx).is_some_and(|picker| picker.contains(at)); + let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at)) && !in_picker(at)); outside && !egui::Popup::is_any_open(ctx) } diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index f017b9ba..94a73684 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -426,6 +426,7 @@ pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, gizmo: &RoundG #[cfg(test)] pub(crate) mod tests { use egui::{Modifiers, PointerButton, vec2}; + use egui_kittest::kittest::Queryable; use texturecraft_engine::core::{Fill, LayerId, LayerKind, Projection, Projector}; use super::*; @@ -815,6 +816,29 @@ pub(crate) mod tests { harness.run_steps(2); } + /// A plain left press on the projector's handle while a colour picker is open only closes the picker: no stroke, no slide, and the press after it works again + #[test] + fn a_press_that_closes_the_colour_picker_neither_paints_nor_slides() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + let before = projection(&harness, layer); + let from = gizmo(&harness).center; + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_some(), "the picker is open"); + let steps = harness.state().session.history_labels().len(); + + drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert!(crate::color_picker::open_window(&harness.ctx).is_none(), "the press closed the picker"); + assert_eq!(projection(&harness, layer), before, "and slid nothing"); + assert_eq!(harness.state().session.history_labels().len(), steps, "nor made an undo step"); + + drag(&mut harness, from, from + vec2(40.0, 0.0), Modifiers::NONE); + assert_ne!(projection(&harness, layer), before, "the next press slides again"); + } + /// A tri-planar fill selected while the quick mask is edited with the Paint tool: brushes act and the projector shows fn quick_mask_paint_app() -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { let (mut harness, layer) = fill_app("triplanar"); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 05e687ff..3416a106 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -413,17 +413,6 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { ui.add_space(SECTION_GAP); } -/// The distinct categories of `items`, in order of first appearance. -pub(crate) fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> { - let mut out: Vec<&'static str> = Vec::new(); - for c in items.iter().map(category) { - if !out.contains(&c) { - out.push(c); - } - } - out -} - /// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] fn scan_library(app: &mut TextureCraftApp) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index c5dffbc9..e2a36d40 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -471,6 +471,11 @@ fn default_wireframe_opacity() -> f32 { 40.0 } +/// The Layers panel's channel list starts on Material, so the Material tab's orb shows the whole material +fn default_layer_material_view() -> bool { + true +} + /// Settings that start on, for saved states that predate them fn default_true() -> bool { true @@ -524,6 +529,9 @@ pub struct UiState { pub uv_rotation: f32, /// Channel whose blending the layer rows show. pub layer_channel: Channel, + /// The Layers panel's channel list is on Material: the Material tab's orb shows the whole material, else `layer_channel` alone + #[serde(default = "default_layer_material_view")] + pub layer_material_view: bool, pub shelf_filter: String, /// The asset shelf's picked type: an index into the shelf's types, or past them for every type #[serde(default)] @@ -701,6 +709,7 @@ impl Default for UiState { uv_rotation: 0.0, layer_channel: Channel::BaseColor, blend_clipboard: None, + layer_material_view: true, shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), diff --git a/crates/ui-egui/src/symmetry/plane_pick.rs b/crates/ui-egui/src/symmetry/plane_pick.rs index 4dfcde97..de1bb98a 100644 --- a/crates/ui-egui/src/symmetry/plane_pick.rs +++ b/crates/ui-egui/src/symmetry/plane_pick.rs @@ -83,4 +83,29 @@ mod tests { assert_eq!(offset, [0.5, 0.25, 3.0], "x is picked minus center, y is untouched, z is clamped to the mesh"); } + + /// Escape closes an open colour picker first and leaves Pick point armed; the next Escape cancels Pick point + #[test] + fn escape_closes_an_open_colour_picker_before_it_cancels_pick_point() { + use egui_kittest::kittest::Queryable; + + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, _) = crate::frame_gizmo::tests::fill_app("triplanar"); + harness.state_mut().session.tool.brush.symmetry.x = true; + harness.state_mut().picking_symmetry_plane = true; + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_some(), "the picker is open"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + assert!(crate::color_picker::open_window(&harness.ctx).is_none(), "Escape closed the picker"); + assert!(harness.state().picking_symmetry_plane, "and left Pick point armed"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + assert!(!harness.state().picking_symmetry_plane, "the next Escape cancels Pick point"); + } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 05b2eb8f..33f94c62 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,12 +397,45 @@ pub const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; /// The axes' letters, as the Axis switches and the 3D fields' tags show them pub const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; +/// Cyan, magenta and yellow: the opposites of [`AXIS_COLORS`] at the same brightness (Color Balance's color names) +pub const OPPOSITE_COLORS: [Color32; 3] = [Color32::from_rgb(0x52, 0xb8, 0xc4), Color32::from_rgb(0xc4, 0x6a, 0xc8), Color32::from_rgb(0xd2, 0xb8, 0x52)]; + /// `from` moved `amount` of the way to `to` in gamma space, opaque pub(crate) fn lerp_color(from: Color32, to: Color32, amount: f32) -> Color32 { let mix = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * amount).round().clamp(0.0, 255.0) as u8; Color32::from_rgb(mix(from.r(), to.r()), mix(from.g(), to.g()), mix(from.b(), to.b())) } +/// Least contrast a tinted color name keeps against its background (the WCAG ratio for normal text: the names are regular 12 pt lettering) +const TINT_MIN_CONTRAST: f32 = 4.5; + +/// How finely [`legible_tint`] walks from the tint to the text colour: a tenth of the way at a time keeps as much of the tint as reads +const TINT_STEPS: u8 = 10; + +/// `tint` moved toward `text` just enough to read on `background` (Color Balance's yellow and cyan names on a light card); a tint that already reads stays as it is +pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color32 { + (0..=TINT_STEPS) + .map(|step| tint.lerp_to_gamma(text, f32::from(step) / f32::from(TINT_STEPS))) + .find(|color| contrast_ratio(*color, background) >= TINT_MIN_CONTRAST) + .unwrap_or(text) +} + +/// WCAG's flare term, added to both luminances so black still has a ratio +const WCAG_FLARE: f32 = 0.05; + +/// The WCAG contrast ratio of two opaque colors (1..21) +fn contrast_ratio(a: Color32, b: Color32) -> f32 { + let luminance = |color: Color32| { + let linear = egui::Rgba::from(color); + + // Rec. 709 luminance + 0.2126 * linear.r() + 0.7152 * linear.g() + 0.0722 * linear.b() + }; + let (first, second) = (luminance(a), luminance(b)); + let (high, low) = (first.max(second), first.min(second)); + (high + WCAG_FLARE) / (low + WCAG_FLARE) +} + /// A section caption inside a panel: semibold in the strong colour, as written (no capitals). pub fn caption(text: &str) -> egui::RichText { egui::RichText::new(text).font(semibold(12.5)).strong() @@ -412,6 +445,23 @@ pub fn caption(text: &str) -> egui::RichText { mod tests { use super::*; + #[test] + fn tint_names_reach_normal_text_contrast_and_a_tint_that_already_reads_stays_as_it_is() { + for theme in [Brightness::Light, Brightness::MediumLight, Brightness::MediumDark, Brightness::Dark] { + let tokens = Tokens::for_brightness(theme); + for tint in OPPOSITE_COLORS.into_iter().chain(AXIS_COLORS) { + let shown = legible_tint(tint, tokens.row, tokens.text); + assert!(contrast_ratio(shown, tokens.row) >= TINT_MIN_CONTRAST, "{theme:?} {tint:?} -> {shown:?}"); + if contrast_ratio(tint, tokens.row) >= TINT_MIN_CONTRAST { + assert_eq!(shown, tint, "{theme:?}: a tint that already reads stays as it is"); + } + } + } + + let light = Tokens::for_brightness(Brightness::Light); + assert_ne!(legible_tint(OPPOSITE_COLORS[2], light.row, light.text), OPPOSITE_COLORS[2], "yellow darkens on a light card"); + } + #[test] fn settings_round_trip_and_unknown_values_load_the_defaults() { for b in Brightness::ALL { @@ -429,18 +479,7 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - // Relative luminance (WCAG) and contrast ratio. - let lum = |c: Color32| { - let ch = |v: u8| { - let v = f32::from(v) / 255.0; - if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } - }; - 0.2126 * ch(c.r()) + 0.7152 * ch(c.g()) + 0.0722 * ch(c.b()) - }; - let contrast = |a: Color32, b: Color32| { - let (x, y) = (lum(a), lum(b)); - (x.max(y) + 0.05) / (x.min(y) + 0.05) - }; + let contrast = contrast_ratio; for b in Brightness::ALL { for a in Accent::ALL { let t = Tokens::for_brightness(b).with_accent(a); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index dc2f3453..84fd39e4 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -7,11 +7,12 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::docking::Panel; +use crate::drawn_icon::DrawnIcon; use crate::i18n::{tr, trf}; use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; -use crate::widgets::{bar_slider, icon_button, icon_button_without_tooltip, icon_dropdown_button, icon_dropdown_button_width}; +use crate::widgets::{bar_slider, drawn_icon_button, icon_button, icon_button_without_tooltip, icon_dropdown_button, icon_dropdown_button_width}; const BAR_SPACING: f32 = 10.0; const COMPACT_BAR_SPACING: f32 = 4.0; @@ -260,31 +261,54 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const DEFAULT_LAZY_DISTANCE_PX: f32 = 20.0; const TOOL_ICON_SIZE: f32 = 15.0; + // Slider widths: the longer-named Size and Stroke opacity get more room, Lazy mouse's Distance less + const WIDE_SLIDER_WIDTH: f32 = 110.0; + const SLIDER_WIDTH: f32 = 100.0; + const NARROW_SLIDER_WIDTH: f32 = 90.0; + + /// The sliders show fractions as percentages + const PERCENT: f32 = 100.0; + + /// Size's track, in percent of the largest brush + const SIZE_PERCENT_RANGE: std::ops::RangeInclusive = 0.05..=100.0; + + /// Spacing's track, in percent of the brush's diameter + const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=200.0; + + /// Lazy mouse Distance's track, in pixels + const LAZY_DISTANCE_RANGE_PX: std::ops::RangeInclusive = 1.0..=200.0; + let button_size = ui.spacing().interact_size.y; let tool = app.session.tool.tool; - ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); + if tool == Tool::ColorPicker { + let (icon, response) = ui.allocate_exact_size(vec2(TOOL_ICON_SIZE, TOOL_ICON_SIZE), egui::Sense::hover()); + DrawnIcon::Pipette.paint(ui.painter(), icon.center(), TOOL_ICON_SIZE, tokens.text_strong); + response.on_hover_text(tr(tool.label())); + } else { + ui.label(RichText::new(tool_icon(tool)).size(TOOL_ICON_SIZE).color(tokens.text_strong)).on_hover_text(tr(tool.label())); + } let brush = &mut app.session.tool.brush; match tool { Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path => { - let mut size = brush.size / MAX_BRUSH_SIZE * 100.0; - if bar_slider(ui, tr("Size"), &mut size, 0.05..=100.0, 110.0).changed() { - brush.size = (size / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + let mut size = brush.size / MAX_BRUSH_SIZE * PERCENT; + if bar_slider(ui, tr("Size"), &mut size, SIZE_PERCENT_RANGE, WIDE_SLIDER_WIDTH).changed() { + brush.size = (size / PERCENT * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - let mut flow = brush.flow * 100.0; - if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=100.0, 100.0).changed() { - brush.flow = flow / 100.0; + let mut flow = brush.flow * PERCENT; + if bar_slider(ui, tr("Flow"), &mut flow, 0.0..=PERCENT, SLIDER_WIDTH).changed() { + brush.flow = flow / PERCENT; } - let mut opacity = brush.opacity * 100.0; - if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=100.0, 110.0).changed() { - brush.opacity = opacity / 100.0; + let mut opacity = brush.opacity * PERCENT; + if bar_slider(ui, tr("Stroke opacity"), &mut opacity, 0.0..=PERCENT, WIDE_SLIDER_WIDTH).changed() { + brush.opacity = opacity / PERCENT; } - let mut spacing = brush.spacing * 100.0; - if bar_slider(ui, tr("Spacing"), &mut spacing, 1.0..=200.0, 100.0).changed() { - brush.spacing = spacing / 100.0; + let mut spacing = brush.spacing * PERCENT; + if bar_slider(ui, tr("Spacing"), &mut spacing, SPACING_PERCENT_RANGE, SLIDER_WIDTH).changed() { + brush.spacing = spacing / PERCENT; } ui.separator(); @@ -294,7 +318,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } if lazy_on { let mut distance = brush.lazy; - if bar_slider(ui, tr("Distance"), &mut distance, 1.0..=200.0, 90.0).changed() { + if bar_slider(ui, tr("Distance"), &mut distance, LAZY_DISTANCE_RANGE_PX, NARROW_SLIDER_WIDTH).changed() { brush.lazy = distance; } } @@ -309,9 +333,9 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) if tool == Tool::Smudge { ui.separator(); - let mut strength = app.session.tool.smudge_strength * 100.0; - if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=100.0, 100.0).changed() { - app.session.tool.smudge_strength = (strength / 100.0).clamp(0.0, 1.0); + let mut strength = app.session.tool.smudge_strength * PERCENT; + if bar_slider(ui, tr("Strength"), &mut strength, 0.0..=PERCENT, SLIDER_WIDTH).changed() { + app.session.tool.smudge_strength = (strength / PERCENT).clamp(0.0, 1.0); } } @@ -456,7 +480,12 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (usable, usable && app.session.tool.tool == tool) } }; - let button = ui.add_enabled_ui(usable, |ui| icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE)).inner; + let button = ui + .add_enabled_ui(usable, |ui| match tool { + Tool::ColorPicker => drawn_icon_button(ui, DrawnIcon::Pipette, &hint, selected, SHELF_BUTTON_SIZE), + _ => icon_button(ui, tool_icon(tool), &hint, selected, SHELF_BUTTON_SIZE), + }) + .inner; if button.on_disabled_hover_text(tr(tool.label())).clicked() && app.ui.mode == Mode::Painting { app.run("tool.select", json!({"tool": tool.id()})); } @@ -502,7 +531,7 @@ const RAIL_ICON_SIZE: f32 = 26.0; const RAIL_ICON_GAP: f32 = 4.0; /// Padding inside the rail's card around its icons, as the tool shelf's -const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); +const RAIL_CARD_PADDING: egui::Margin = SHELF_PADDING; /// The icon rail: the rail panels that are not in the dock (Export first), each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index a58be4de..c2e92805 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -874,18 +874,36 @@ 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() || rail_popup; + // A press that closes an open colour picker only closes it: it neither paints nor moves a projection + let picker = crate::color_picker::blocks_view_press(ui.ctx()); + let popup = app.properties_popup.is_some() || rail_popup || picker; - // A pending ID color pick takes the next click instead of the brush let picking = app.picking_id_color.is_some(); + // A pending ID color pick or eyedropper takes the next click instead of the brush + let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); if picking { - crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + // The eyedropper's own pointer is drawn over the whole window (screen_pick) + if app.picking_color.is_none() { + crate::id_color_pick::IdColorPick::draw_cursor(ui, rect); + } + + // The eyedropper's disc shows the colour a click here would pick + if app.picking_color.is_some() + && let Some(hover) = response.hover_pos() + && let Ok(values) = app.session.color_at(local(hover), app.session.viewport) + && let Some(color) = values.get(&texturecraft_engine::core::Channel::BaseColor) + { + crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color); + } 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]})); + match app.picking_color { + Some(bar) => eyedrop(app, ui.ctx(), bar, pixel, viewport), + None => crate::id_color_pick::IdColorPick::pick_at(app, json!({"x": pixel.x, "y": pixel.y, "viewport": [viewport.x, viewport.y]})), + } } } @@ -1025,6 +1043,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && (app.session.tool.tool != Tool::Path || adjusting) && !crate::symmetry::manipulator_hovered(app, ui, rect) && app.picking_id_color.is_none() + && app.picking_color.is_none() && app.moving_on_model.is_none() && !ShownGizmo::hovered(ui, rect, gizmo.as_ref()) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } @@ -2121,11 +2140,13 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !projection_hint && app.properties_popup.is_none() && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) + && !crate::color_picker::blocks_view_press(ui.ctx()) && !alt && !adjusting && !v_held && !picking_id_color && !app.picking_symmetry_plane + && app.picking_color.is_none() && !DecalDrop::blocks_input(ui.ctx()); let mut fill_box = None; if painting && path_tool { @@ -2230,7 +2251,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Match the 3D view's stamp size and hardness - let show_brush_cursor = tool_acts(app) && !alt && !v_held; + let show_brush_cursor = tool_acts(app) && !alt && !v_held && app.picking_color.is_none(); let pointer_in_view = ui.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)); if show_brush_cursor && !path_tool @@ -2422,6 +2443,16 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t painter.add(egui::Shape::mesh(mesh)); } +/// Hands the base colour on the model at `pixel` to the colour bar `bar` and ends its eyedropper pick; a click off the model ends it too +fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: Vec2, viewport: Vec2) { + app.picking_color = None; + let Ok(values) = app.session.color_at(pixel, viewport) else { return }; + + if let Some(color) = values.get(&texturecraft_engine::core::Channel::BaseColor) { + crate::color_picker::ColorPick::deliver(ctx, bar, *color); + } +} + #[cfg(test)] mod tests { use super::*; @@ -2593,6 +2624,41 @@ mod tests { assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } + /// A click in the 2D view while a colour bar's eyedropper waits paints nothing: the pick keeps waiting, as over the 3D view + #[test] + fn a_waiting_eyedropper_keeps_a_2d_view_click_from_painting() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(4); + + // The 2D view fills the window's middle: there the sample's UV islands are (the shelf drop tests click the same point) + let on_the_uvs = pos2(700.0, 420.0); + let steps = harness.state().session.history_labels().len(); + let bar = egui::Id::unique("a colour bar"); + harness.state_mut().picking_color = Some(bar); + + click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.history_labels().len(), steps, "the click painted nothing"); + assert_eq!(harness.state().picking_color, Some(bar), "the eyedropper still waits"); + + harness.state_mut().picking_color = None; + click(&mut harness, on_the_uvs); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill"), "without a pick the same click paints"); + } + + /// Press and release the primary button at `at` + fn click(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + } + #[test] fn stored_surfaces_release_after_a_frame_without_paths() { // Hold the language lock while drawing the harness diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 93bb6b5a..b38010f6 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::drawn_icon::DrawnIcon; use crate::i18n::tr; use crate::theme::Tokens; @@ -191,6 +192,15 @@ pub fn icon_button(ui: &mut Ui, icon: &str, tooltip: &str, selected: bool, size: icon_button_without_tooltip(ui, icon, tooltip, selected, size).on_hover_text(tooltip) } +/// An `icon_button` showing an icon drawn in code +pub(crate) fn drawn_icon_button(ui: &mut Ui, icon: DrawnIcon, tooltip: &str, selected: bool, size: f32) -> Response { + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(tooltip, vec2(size, size), &style) + .selected(selected) + .show(ui, |ui, rect, color| icon.paint(ui.painter(), rect.center(), size * ICON_SCALE, color)) + .on_hover_text(tooltip) +} + /// Icon glyph size as a fraction of the button height const ICON_SCALE: f32 = 0.62; @@ -496,7 +506,7 @@ fn color_picker(ui: &mut Ui, id: egui::Id, c: &mut Color32, width: f32) -> bool } /// Fill `rect` with `rgb(x, y)` (sRGB 0..1 over 0..1 across and down), as a shaded mesh -fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { +pub(crate) fn gradient(painter: &egui::Painter, rect: egui::Rect, rgb: impl Fn(f32, f32) -> [f32; 3]) { /// Cells across and down: fine enough that a hue strip's six ramps read smooth const GRID_CELLS: u32 = 24; diff --git a/crates/ui-egui/tests/brush_cursor_2d.rs b/crates/ui-egui/tests/brush_cursor_2d.rs index d56067e4..7185890e 100644 --- a/crates/ui-egui/tests/brush_cursor_2d.rs +++ b/crates/ui-egui/tests/brush_cursor_2d.rs @@ -160,3 +160,17 @@ fn a_ctrl_right_drag_out_of_the_2d_view_keeps_its_outline_at_the_anchor() { harness.event(Event::ModifiersChanged(egui::Modifiers::NONE)); harness.run_steps(2); } + +#[test] +fn a_waiting_eyedropper_hides_the_2d_brush_outline() { + let mut harness = harness(); + harness.state_mut().picking_color = Some(egui::Id::unique("a colour bar")); + let pointer = egui::pos2(800.0, 480.0); + harness.hover_at(pointer); + harness.run_steps(3); + assert!(rings_at(&harness, pointer).is_empty(), "no brush outline under the eyedropper (its own pointer is drawn instead)"); + + harness.state_mut().picking_color = None; + harness.run_steps(3); + assert_eq!(rings_at(&harness, pointer).len(), 1, "without a pick the outline is back"); +} diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 4278b0b3..97ce9790 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -64,12 +64,14 @@ fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { harness.run_steps(3); } -/// Whether the last frame drew the eyedropper glyph with its tip at `pointer` +/// Whether the pointer at `pointer` is the drawn eyedropper: the system pointer hidden and a picture painted under it 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, - }) + let output = harness.output(); + output.platform_output.cursor_icon == egui::CursorIcon::None + && output.shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) => mesh.texture_id != egui::TextureId::default() && mesh.calc_bounds().expand(1.0).contains(pointer), + _ => false, + }) } fn pick_color_label() -> String { diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index b03a4440..c39610c9 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -1,4 +1,4 @@ -//! A fill channel takes an image resource from its source picker +//! A fill channel takes an image resource from its slot's source picker use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -11,13 +11,14 @@ fn roughness<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Nod harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness") } -/// Opens the source picker of the Roughness channel from its slot -fn open_roughness_source_picker(harness: &mut Harness<'_, TextureCraftApp>) { - // Allow the scroll animation to finish before the click - roughness(harness).scroll_to_me(); - harness.run_steps(30); - roughness(harness).click(); +/// Opens the Roughness slot's source picker on the Material tab and types `search` into its search field, which has the focus +fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>, search: &str) { + click_node(harness, egui::Role::Tab, "Material"); harness.run_steps(3); + click_node(harness, egui::Role::ComboBox, "Roughness"); + harness.run_steps(2); + harness.event(egui::Event::Text(search.into())); + harness.run_steps(2); } #[test] @@ -34,8 +35,8 @@ fn a_fill_channel_takes_an_image_from_its_source_picker() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_picker(&mut harness); - harness.get_by_role_and_label(egui::Role::Button, &name).click(); + open_roughness_source_menu(&mut harness, "rough"); + click_node(&mut harness, egui::Role::ListBoxOption, &name); harness.run_steps(3); let LayerKind::Fill(fill) = &harness.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; @@ -59,7 +60,8 @@ fn the_source_picker_offers_only_images_that_were_decoded() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_picker(&mut harness); + // Both names match the search, so only the decoded one may show + open_roughness_source_menu(&mut harness, "png"); assert!(harness.query_by_label(&name).is_some(), "a decoded image is offered"); assert!(harness.query_by_label("broken.png").is_none(), "an image that did not decode is not"); @@ -131,7 +133,8 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.run_steps(30); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_role_and_label(egui::Role::Button, &image_name).click(); + harness.event(egui::Event::Text("mask".into())); + harness.run_steps(2); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; @@ -148,14 +151,14 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_role_and_label(egui::Role::Button, "Uniform value").click(); + harness.run_steps(2); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { source: Source::Uniform(_), .. })); } -/// An image on a fill's Normal channel offers a DirectX toggle that flips its green. +/// An image on a fill's Normal channel offers OpenGL | DirectX in its Attributes; DirectX flips its green #[test] fn a_normal_image_can_be_marked_directx() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -169,9 +172,17 @@ fn a_normal_image_can_be_marked_directx() { h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); - h.get_by_label("DirectX normal map").scroll_to_me(); + click_node(&mut h, egui::Role::Tab, "Material"); + h.run_steps(3); + + // The normal image's convention sits in the slot's folded Attributes + h.get_by_role_and_label(egui::Role::Button, "Attributes").scroll_to_me(); + + // The scroll animates for about twenty frames h.run_steps(30); - h.get_by_label("DirectX normal map").click(); + click_node(&mut h, egui::Role::Button, "Attributes"); + h.run_steps(3); + click_node(&mut h, egui::Role::RadioButton, "DirectX"); h.run_steps(3); let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; diff --git a/crates/ui-egui/tests/it/gradient_map_menu.rs b/crates/ui-egui/tests/it/gradient_map_menu.rs deleted file mode 100644 index a19e6cb5..00000000 --- a/crates/ui-egui/tests/it/gradient_map_menu.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! The Gradient Map item of a fill's Base color source menu turns color stops on and off. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use serde_json::json; -use texturecraft_engine::core::{Channel, LayerId, LayerKind}; -use texturecraft_ui_egui::TextureCraftApp; - -/// The Base color channel's name in Properties (the rightmost "Base color" label). -fn base_color<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - h.get_all_by_label("Base color").max_by(|a, b| a.rect().right().total_cmp(&b.rect().right())).unwrap() -} - -/// Opens the Base color source menu and clicks its Gradient Map item. -fn click_gradient_map(h: &mut Harness<'_, TextureCraftApp>) { - base_color(h).scroll_to_me(); - - // The scroll animates for about twenty frames - h.run_steps(30); - let row = base_color(h).rect().center().y; - let menu = h.get_all_by_label(egui_phosphor::regular::DOTS_THREE).find(|n| (n.rect().center().y - row).abs() < 6.0).unwrap(); - let at = menu.rect().center(); - menu.click(); - h.run_steps(2); - - // The filter of the same name may show elsewhere (the shelf): the menu's item is the nearest - let item = h.get_all_by_label("Gradient Map").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); - item.click(); - h.run_steps(3); -} - -fn ramp(h: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Vec<[f32; 3]> { - let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; - fill.source(Channel::BaseColor).ramp().to_vec() -} - -#[test] -fn the_base_color_menu_turns_a_procedural_gradient_map_on_and_off() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - let layer = LayerId(out["layer"].as_u64().unwrap()); - let set = json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]}); - texturecraft_engine::execute(&mut session, "layer.fill.set", &set).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - - // The labels below are English; a first run would speak the system's language - h.state_mut().ui.prefs.language = "en".into(); - h.run_steps(4); - - // The stops start at low, halfway and high, so the fill looks the same until they change - click_gradient_map(&mut h); - assert_eq!(ramp(&h, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]); - click_gradient_map(&mut h); - assert!(ramp(&h, layer).is_empty(), "the item turns the stops off again"); -} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index e346617a..90f4c1d8 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -9,6 +9,8 @@ use texturecraft_engine::core::{Channel, LayerId}; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; +use crate::SETTLE_FRAMES; + fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } @@ -413,3 +415,41 @@ fn alt_click_on_the_content_thumbnail_leaves_the_view_alone() { alt_click(&mut h, at); assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); } + +/// Pointer moves of the opacity cell drag, one per frame +const OPACITY_DRAG_MOVES: usize = 4; + +/// How far left each move of the opacity cell drag goes, in points +const OPACITY_DRAG_STEP: f32 = 10.0; + +/// A drag on a row's opacity cell is one undo step, however many frames it spans +#[test] +fn dragging_a_row_opacity_adds_one_undo_step() { + let (mut h, layer) = harness(); + let row = h.get_by_label("Masked fill").rect(); + let cell = h.get_all_by_role(egui::accesskit::Role::SpinButton).map(|node| node.rect()).find(|cell| row.contains(cell.center())).unwrap(); + let opacity = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].blend(Channel::BaseColor).unwrap().opacity; + let (before, steps) = (opacity(&h), h.state().session.history_labels().len()); + + // A leftward drag lowers it from 100 %, a frame per move as a real drag arrives + let from = cell.center(); + h.hover_at(from); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + h.run_steps(1); + let step_left = |step: usize| from - egui::vec2(OPACITY_DRAG_STEP * step as f32, 0.0); + for step in 1..=OPACITY_DRAG_MOVES { + h.hover_at(step_left(step)); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { + pos: step_left(OPACITY_DRAG_MOVES), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(SETTLE_FRAMES); + + assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h)); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index be8a4c26..8b642d36 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -26,13 +26,14 @@ mod export_settings; mod export_template_guards; mod file_dialogs; mod fill_channel_image; +mod fill_material_rows; mod fill_projection_rows; mod fill_support; mod fill_symmetry_rows; mod filter_picker; +mod filter_support; mod frame_selection; mod generator_panel; -mod gradient_map_menu; mod help_menu_664; mod history_panel; mod import_resources; @@ -60,6 +61,7 @@ mod popup_press_close; mod project_config; mod properties_min_width; mod properties_popup; +mod properties_scroll; mod rail; mod reference_order; mod rename_anchor; @@ -78,10 +80,12 @@ mod side_panels; mod skew_paint; mod smudge_channels; mod snapped_lines; +mod source_picker; mod split_divider; mod temp_dir; mod template_invert; mod templates_681; +mod tile_generator_panel; mod tool_availability; mod tool_settings_saved; mod toolbar; @@ -91,11 +95,9 @@ mod view2d_tiles; mod view_mode_picker; mod window_menu_684; -mod filter_support; mod stencil; mod symmetry; mod symmetry_2d; -mod tile_generator_panel; /// eframe's in-memory storage, shared by the tests that save and restore the UI state #[path = "../../src/ui_state_store/memory_storage.rs"] @@ -121,6 +123,40 @@ const SETTLE_FRAMES: usize = 3; /// Frames between the moves of a drag, and between a press and its release const DRAG_STEP_FRAMES: usize = 2; +/// Frames for an input that redraws Properties (another selection, source or operator) to show +const REDRAW_FRAMES: usize = 4; + +/// One wheel notch over the view, in points +const WHEEL_NOTCH: f32 = 60.0; + +/// How far left of a list's button a click lands, clear of the list and its popup +const OUTSIDE_OFFSET: f32 = 400.0; + +/// A Properties list that `open` opens (returning its button's rect) leaves the view its wheel, and closes on Escape and on a click outside +fn assert_list_leaves_the_wheel_and_closes(harness: &mut Harness<'_, TextureCraftApp>, open: impl Fn(&mut Harness<'_, TextureCraftApp>) -> egui::Rect) { + open(harness); + assert!(egui::Popup::is_any_open(&harness.ctx), "the list opens"); + let distance = harness.state().session.camera.distance; + harness.hover_at(harness.state().viewport_rect.center()); + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.run_steps(REDRAW_FRAMES); + assert_ne!(harness.state().session.camera.distance, distance, "the wheel over the view zooms with the list open"); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(!egui::Popup::is_any_open(&harness.ctx), "Escape closes the list"); + + let button = open(harness); + click_at(harness, egui::pos2(button.min.x - OUTSIDE_OFFSET, button.min.y)); + assert!(!egui::Popup::is_any_open(&harness.ctx), "a click outside closes the list"); +} + /// Presses and releases the primary button at `at` without moving, as a pointer click does fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.hover_at(at); @@ -132,6 +168,12 @@ fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { harness.run_steps(SETTLE_FRAMES); } +/// Clicks the middle of the widget with `role` and `label` through the pointer +fn click_widget(harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str) { + let at = harness.get_by_role_and_label(role, label).rect().center(); + click_at(harness, at); +} + /// The close button nearest the right of a docked panel's `title` (its tab or header title), on the same row fn panel_close_button(harness: &Harness<'_, TextureCraftApp>, title: egui::Rect) -> egui::Rect { harness diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 3ff215b7..d6db3fb2 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -29,6 +29,12 @@ const SELECT_FRAMES: usize = 3; /// Pointer moves a drag makes between its press and its release const DRAG_MOVES: usize = 4; +/// Frames for a scroll to a popup row to finish its animation +const SCROLL_FRAMES: usize = 25; + +/// How far left of the popup a click lands on the model +const MODEL_LEFT_OF_POPUP: f32 = 60.0; + fn harness() -> Harness<'static, TextureCraftApp> { harness_sized(WINDOW_SIZE) } @@ -214,11 +220,14 @@ fn its_jump_tabs_scroll_to_a_section_and_light_it_without_moving_the_docked_pane let symmetry = harness.get_all_by_role_and_label(Role::Tab, "Symmetry").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); click(&mut harness, PointerButton::Primary, symmetry); + let material = harness.get_all_by_role_and_label(Role::Tab, "Material").find(|tab| popup.contains_rect(tab.rect())).unwrap().rect().center(); + click(&mut harness, PointerButton::Primary, material); harness.run_steps(JUMP_FRAMES); - assert!(is_open(&harness), "a tab click keeps it open"); assert!(!in_popup(&harness, "UV projection"), "the list jumped down to SYMMETRY"); assert!(tab_lit(&harness, popup, "Symmetry"), "the section in view is lit"); + assert!(!in_popup(&harness, "UV projection"), "the list jumped down to MATERIAL"); + assert!(tab_lit(&harness, popup, "Material"), "the section in view is lit"); assert!(!tab_lit(&harness, popup, "Fill")); assert!(tab_lit(&harness, docked, "Fill"), "the docked panel keeps its own place"); } @@ -235,3 +244,57 @@ fn bake_and_render_modes_never_open_it() { assert_eq!(harness.state().properties_popup, None, "{mode:?}"); } } + +#[test] +fn the_colour_picker_opened_in_the_popup_takes_its_presses_and_the_first_escape() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2]})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + assert!(is_open(&harness)); + + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |rect: egui::Rect| popup.x_range().contains(rect.center().x); + harness.get_all_by_role_and_label(Role::Button, "Base color").find(|node| in_popup(node.rect())).unwrap().scroll_to_me(); + + harness.run_steps(SCROLL_FRAMES); + let button = harness.get_all_by_role_and_label(Role::Button, "Base color").find(|node| in_popup(node.rect())).unwrap().rect(); + click(&mut harness, PointerButton::Primary, button.center()); + let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect(); + + click(&mut harness, PointerButton::Primary, title.center()); + assert!(is_open(&harness), "a press in the picker window stays in the popup"); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "and keeps the picker open"); + + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the first Escape closes the picker"); + assert!(is_open(&harness), "and leaves the popup open"); + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(!is_open(&harness), "the next Escape closes the popup"); +} + +#[test] +fn an_eyedropper_pick_from_the_popup_keeps_the_popup_open_for_its_colour() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2]})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); + let in_popup = |rect: egui::Rect| popup.x_range().contains(rect.center().x); + harness.get_all_by_role_and_label(Role::Button, "Pick color").find(|node| in_popup(node.rect())).unwrap().scroll_to_me(); + + harness.run_steps(SCROLL_FRAMES); + let button = harness.get_all_by_role_and_label(Role::Button, "Pick color").find(|node| in_popup(node.rect())).unwrap().rect(); + click(&mut harness, PointerButton::Primary, button.center()); + assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model"); + + // The model's middle, left of the popup + let model = egui::pos2(popup.left() - MODEL_LEFT_OF_POPUP, center.y); + click(&mut harness, PointerButton::Primary, model); + assert!(harness.state().picking_color.is_none(), "the click on the model picks"); + assert!(is_open(&harness), "and leaves the popup open for the picked colour"); +} diff --git a/crates/ui-egui/tests/it/properties_scroll.rs b/crates/ui-egui/tests/it/properties_scroll.rs new file mode 100644 index 00000000..e3c45785 --- /dev/null +++ b/crates/ui-egui/tests/it/properties_scroll.rs @@ -0,0 +1,193 @@ +//! The docked Properties list keeps its scroll place per layer: selecting another layer and coming back lands where it was; it scrolls +//! until its last section's top reaches the top of the list + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::{Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, REDRAW_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// Short enough that a fill's Properties scrolls +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1000.0); + +/// Tall enough that a fill's three sections fit in the list without scrolling +const TALL_WINDOW: egui::Vec2 = egui::vec2(1600.0, 2400.0); + +/// Short enough that a fill's MATERIAL section alone is taller than the list +const SHORT_WINDOW: egui::Vec2 = egui::vec2(1600.0, 600.0); + +/// Wheel steps, in points, and how many reach the end of any fill's list +const WHEEL_NOTCH: f32 = 120.0; +const WHEEL_NOTCHES_TO_END: usize = 40; + +/// Frames for the wheel's smoothed scroll to settle +const WHEEL_SETTLE_FRAMES: usize = 30; + +/// A row's height and the air under the last one: the most a list scrolled to its rows' end shows below them +const ROW_AND_AIR: f32 = 40.0; + +/// From the tab strip down into the list, where the wheel is turned +const INTO_LIST: f32 = 100.0; + +/// How far a hairline may sit from the list's top: it snaps to whole pixels, the list's top need not (the old jump was 4 px low) +const HAIRLINE_SNAP: f32 = 1.0; + +/// The app with two UV fills ("Fill A", "Fill B") and a folder ("Folder", a short panel), Fill A selected +fn harness() -> Harness<'static, TextureCraftApp> { + harness_sized(WINDOW_SIZE) +} + +/// [`harness`] in a window of `size` +fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.group", &json!({"name": "Folder"})).unwrap(); + for name in ["Fill B", "Fill A"] { + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "layer.rename", &json!({"layer": layer, "name": name})).unwrap(); + execute(&mut session, "layer.fill.projection", &json!({"layer": layer, "projection": "uv"})).unwrap(); + } + + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// Selects the Layers panel row labelled `name` by clicking it +fn select_row(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + let at = harness.get_by_label(name).rect().center(); + click_at(harness, at); + harness.run_steps(REDRAW_FRAMES); +} + +/// Whether the docked jump tab `name` is the lit one, i.e. its section is in view +fn tab_lit(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + harness.get_by_role_and_label(Role::Tab, name).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn coming_back_to_a_layer_lands_where_its_properties_were_scrolled() { + lands_where_each_layer_was_scrolled(harness()); +} + +#[test] +fn a_greyed_polygon_fill_tool_keeps_each_layers_own_place() { + // Polygon fill can't fill a fill layer, so the layer's own sheet shows, and it keeps its own place as with any tool + let mut harness = harness(); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + harness.run_steps(REDRAW_FRAMES); + lands_where_each_layer_was_scrolled(harness); +} + +/// Scrolls Fill A down to MATERIAL, then checks a folder in between keeps it there and Fill B keeps its own place, the top +fn lands_where_each_layer_was_scrolled(mut harness: Harness<'_, TextureCraftApp>) { + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Fill"), "a fill never shown starts at the top"); + + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(REDRAW_FRAMES); + assert!(tab_lit(&harness, "Material"), "the jump scrolled down to MATERIAL"); + + select_row(&mut harness, "Folder"); + assert!(harness.query_by_role_and_label(Role::Tab, "Material").is_none(), "a folder shows no fill tabs"); + + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Material"), "Fill A is back where it was scrolled"); + assert!(!tab_lit(&harness, "Fill")); + + select_row(&mut harness, "Fill B"); + assert!(tab_lit(&harness, "Fill"), "another fill keeps its own place: the top"); +} + +/// Turns the wheel down over the docked list until it can scroll no further +fn wheel_to_end(harness: &mut Harness<'_, TextureCraftApp>) { + let strip = harness.get_by_role_and_label(Role::Tab, "Fill").rect(); + harness.hover_at(strip.center_bottom() + egui::vec2(0.0, INTO_LIST)); + for _ in 0..WHEEL_NOTCHES_TO_END { + harness.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -WHEEL_NOTCH), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: egui::Modifiers::NONE, + }); + harness.step(); + } + harness.run_steps(WHEEL_SETTLE_FRAMES); +} + +/// Top of the docked list's `label` combo box (a fill's first row) +fn combo_top(harness: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { + harness.get_by_role_and_label(Role::ComboBox, label).rect().top() +} + +/// Bottom of a new fill's last row: the Height source card's slider +fn last_row_bottom(harness: &Harness<'_, TextureCraftApp>) -> f32 { + harness.get_by_role_and_label(Role::Slider, "Height").rect().bottom() +} + +#[test] +fn a_list_whose_sections_all_fit_still_scrolls_its_last_section_to_the_top() { + let mut harness = harness_sized(TALL_WINDOW); + select_row(&mut harness, "Fill A"); + let list_top = harness.get_by_role_and_label(Role::Tab, "Fill").rect().bottom(); + assert!(last_row_bottom(&harness) < TALL_WINDOW.y, "every section fits in the list"); + + wheel_to_end(&mut harness); + assert!(tab_lit(&harness, "Material"), "the wheel brought MATERIAL to the top"); + assert!(!tab_lit(&harness, "Fill")); + assert!(combo_top(&harness, "UV projection") < list_top, "FILL scrolled out above the list"); + + select_row(&mut harness, "Folder"); + select_row(&mut harness, "Fill A"); + assert!(tab_lit(&harness, "Material"), "coming back keeps the place past the rows' end"); +} + +#[test] +fn a_last_section_taller_than_the_list_scrolls_to_its_real_end() { + let mut harness = harness_sized(SHORT_WINDOW); + select_row(&mut harness, "Fill A"); + let strip = harness.get_by_role_and_label(Role::Tab, "Fill").rect(); + let bar = harness.get_all_by_role(Role::ScrollBar).map(|bar| bar.rect()).find(|bar| bar.top() >= strip.top() && bar.left() > strip.left()); + let list_bottom = bar.unwrap().bottom(); + assert!(last_row_bottom(&harness) > SHORT_WINDOW.y, "the list's rows run below the window"); + + wheel_to_end(&mut harness); + let last_bottom = last_row_bottom(&harness); + assert!(tab_lit(&harness, "Material")); + assert!(last_bottom <= list_bottom, "the last row came into view"); + assert!(list_bottom - last_bottom < ROW_AND_AIR, "no blank space past a section taller than the list"); +} + +/// A jump tab lands its section's hairline on the list's top (egui's top-aligned scroll stopped one item spacing short, 4 px low) +#[test] +fn a_jump_lands_the_sections_hairline_on_the_lists_top() { + let mut harness = harness(); + select_row(&mut harness, "Fill A"); + + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(WHEEL_SETTLE_FRAMES); + + // The caption's clip is the list's view; its hairline is the last line drawn above it in that view + let shapes = &harness.output().shapes; + let caption = shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "MATERIAL" => Some((clipped.clip_rect, text.pos.y)), + _ => None, + }); + let Some((list, caption_y)) = caption else { panic!("a MATERIAL caption") }; + let hairline = shapes + .iter() + .filter(|clipped| clipped.clip_rect == list) + .filter_map(|clipped| match &clipped.shape { + egui::Shape::LineSegment { points, .. } if points[0].y == points[1].y && points[0].y < caption_y => Some(points[0].y), + _ => None, + }) + .reduce(f32::max); + + assert!(hairline.is_some_and(|y| (y - list.top()).abs() < HAIRLINE_SNAP), "the hairline at {hairline:?}, the list's top at {}", list.top()); +} diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs index f8ee1763..244c7f7b 100644 --- a/crates/ui-egui/tests/it/rename_anchor.rs +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -208,7 +208,7 @@ fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { h.run_steps(3); let label = format!("Low / mask / {}", effect_name(&h, anchor)); - h.get_by_role_and_label(Role::Button, &label).click(); + h.get_by_role_and_label(Role::ListBoxOption, &label).click(); h.run_steps(3); let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the fill reads an anchor: {:?}", reader_source(&h, high)) }; diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 40bfaa04..5613ca7d 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -47,11 +47,16 @@ fn pattern(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Procedura } } -/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile` +/// Frames for a scroll to bring a control into view (it animates) +const SCROLL_FRAMES: usize = 25; + +/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile`, scrolled into view first fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); harness.run_steps(3); - harness.get_by_label(tile).click(); + harness.get_by_role_and_label(Role::ListBoxOption, tile).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, tile).click(); harness.run_steps(3); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 01b2e2e2..3789cf98 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -23,8 +23,20 @@ fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { harness.run_steps(3); } +/// The lowest list showing `label`: Properties' (the Layers panel above it has a channel list showing "Base color" too) +fn lowest_list<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_all_by_role_and_label(egui::Role::ComboBox, label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + 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) { + std::thread::sleep(std::time::Duration::from_millis(10)); + harness.run_steps(1); + } + harness.run_steps(2); 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())); @@ -786,53 +798,6 @@ fn i18n_snapshots() { texturecraft_ui_egui::i18n::set_language("en"); } -/// The merged effect panel selects an image and exposes its projection controls -#[test] -#[ignore] -fn mask_fill_image_snapshot() { - use serde_json::json; - use texturecraft_engine::{ - core::{EffectKind, LayerId, Source}, - execute, - }; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut png_bytes = Vec::new(); - image::RgbaImage::from_fn(16, 16, |x, y| { - let value = if (x / 4 + y / 4) % 2 == 0 { 255 } else { 32 }; - image::Rgba([value, value, value, 255]) - }) - .write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png) - .unwrap(); - let name = session.import_resource_bytes("Mask checker.png", png_bytes).unwrap(); - let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.2, 0.1]})).unwrap()["layer"].as_u64().unwrap(); - execute(&mut session, "mask.add.black", &json!({})).unwrap(); - let effect = execute(&mut session, "effect.add.fill", &json!({"target": "mask", "value": 1.0})).unwrap()["effect"].as_u64().unwrap(); - execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(6); - - // The Grayscale slot opens the source picker; its search finds the image - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); - harness.run_steps(3); - harness.event(egui::Event::Text("checker".into())); - harness.run_steps(3); - save(&mut harness, &output_dir, "mask-fill-image-menu"); - - harness.get_by_role_and_label(egui::Role::ListBoxOption, &name).click(); - harness.run_steps(4); - - let EffectKind::Fill { source, .. } = &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind else { panic!("fill effect") }; - assert_eq!(*source, Source::image(name)); - assert!(harness.query_by_label("UV projection").is_some(), "image projection is editable"); - - save(&mut harness, &output_dir, "mask-fill-image-selected"); -} - /// Every docked panel's header bar (names in capitals, a close × at the right), then the Properties × hovered #[test] #[ignore] @@ -862,35 +827,6 @@ fn panel_header_snapshots() { save(&mut harness, &output_dir, "panel-header-close-hovered"); } -#[test] -#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] -fn tile_generator_gradient_map_snapshot() { - use serde_json::json; - use texturecraft_engine::execute; - - let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; - - std::fs::create_dir_all(&output_dir).unwrap(); - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - execute(&mut session, "layer.add.fill", &json!({})).unwrap(); - execute( - &mut session, - "layer.fill.set", - &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), - ) - .unwrap(); - - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); - harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.dock.focus(Panel::Properties); - harness.run_steps(6); - harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); - harness.run_steps(30); - - assert!(harness.query_by_label_contains("Add color").is_some()); - save(&mut harness, &output_dir, "tile-generator-gradient-map"); -} - /// Edit > Settings: the three pages and a compact window at 150% scale #[test] #[ignore] @@ -1196,6 +1132,428 @@ fn fill_symmetry_snapshots() { save(&mut harness, &output_dir, "symmetry-uv"); } +/// A material link as MaterialCraft leaves it on a fill: three float inputs, a preset and five outputs (the maps stay the fill's own sources) +fn steel_painted_worn() -> texturecraft_engine::core::MaterialLink { + use serde_json::json; + use texturecraft_engine::core::{LinkParam, LinkPreset, MaterialLink}; + let float = |id: &str, label: &str, value: f32| LinkParam { + id: id.into(), + label: label.into(), + group: String::new(), + value: json!({"t": "float", "v": value}), + default: json!({"t": "float", "v": 0.5}), + min: 0.0, + max: 1.0, + options: Vec::new(), + }; + MaterialLink { + name: "Steel Painted Worn".into(), + package: String::new(), + graph: "main".into(), + params: vec![float("wear", "Wear", 0.55), float("hue", "Paint hue", 0.3), float("dirt", "Dirt", 0.2)], + presets: vec![LinkPreset { name: "Fresh paint".into(), values: Default::default() }], + inputs: Vec::new(), + size: 1024, + resolution: None, + mapping: Default::default(), + outputs: ["baseColor", "metallic", "roughness", "normal", "height"].map(|output| (output.to_owned(), format!("steel_{output}.png"))).into(), + } +} + +/// Screen 04: the colour picker window open on a uniform base colour with five swatches, its close, a slider, a swatch and + hovered, a swatch's menu, with its lists open (a hovered option previews nothing), in RGB and resized from its top left corner; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn fill_color_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let orange = [0xE5, 0x8A, 0x4E].map(|c| texturecraft_engine::texel::srgb_to_linear(f32::from(c as u8) / 255.0)); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": orange})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": "height", "enabled": true})).unwrap(); + for swatch in ["#E58A4E", "#BEBEBE", "#3C4046", "#7A7AF5", "#B0623A"] { + execute(&mut session, "swatch.add", &json!({"color": swatch})).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + + // The tab scrolls the panel to its section (the scroll animates for about twenty frames) + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-open"); + let title = harness.get_by_role_and_label(egui::Role::TitleBar, "Base color").rect(); + harness.hover_at(egui::pos2(title.right() + 6.0, title.center().y)); + save(&mut harness, &output_dir, "picker-close-hover"); + harness.get_by_role_and_label(egui::Role::Slider, "S").hover(); + save(&mut harness, &output_dir, "picker-hover"); + harness.get_by_role_and_label(egui::Role::Button, "#7A7AF5").hover(); + save(&mut harness, &output_dir, "picker-swatch-hover"); + harness.get_by_role_and_label(egui::Role::Button, "Add swatch").hover(); + harness.run_steps(30); + save(&mut harness, &output_dir, "picker-add-hover"); + let chip = harness.get_by_role_and_label(egui::Role::Button, "#7A7AF5").rect().center(); + harness.hover_at(chip); + harness.run_steps(1); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: chip, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + } + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Button, "Remove swatch").hover(); + save(&mut harness, &output_dir, "picker-swatch-menu"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ComboBox, "sRGB").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Linear").hover(); + save(&mut harness, &output_dir, "picker-space-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ComboBox, "HSV").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "RGB").hover(); + save(&mut harness, &output_dir, "picker-model-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "RGB").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-rgb"); + + // The window stands at the screen's bottom here, so it grows from its top left corner + let corner = harness.get_by_role_and_label(egui::Role::TitleBar, "Base color").rect().left_top() + egui::vec2(2.0, 2.0); + let by = egui::vec2(-120.0, -90.0); + harness.hover_at(corner); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: corner, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(1); + for step in 1..=4 { + harness.hover_at(corner + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: corner + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(2); + save(&mut harness, &output_dir, "picker-resized"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("picker-resized-{name}")); + } + } +} + +/// Screen 04: a fill's Material section in Channels (a procedural base colour with its Attributes open, a uniform metallic, a normal image, a signed height), its source list open with a hover, the picker on the base colour, the Material side of a plain fill (no material, its material list open with a hover, Copper picked; Copper also in the dark and light themes) and of a linked material; the linked one also in the dark and light themes +#[test] +#[ignore] +fn fill_material_snapshots() { + use serde_json::json; + use texturecraft_engine::core::{LayerId, LayerKind}; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + image::RgbaImage::from_fn(16, 16, |x, y| image::Rgba([110 + (x * 8) as u8, 110 + (y * 8) as u8, 250, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let normal = session.import_resource_bytes("bricks_normal.png", png).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.55, 0.2, 0.08]})).unwrap()["layer"].as_u64().unwrap(); + for settings in [ + json!({"channel": "basecolor", "procedural": "Clouds", "low": [0.3, 0.08, 0.02], "high": [0.7, 0.3, 0.12]}), + json!({"channel": "normal", "enabled": true}), + json!({"channel": "normal", "image": normal}), + json!({"channel": "height", "enabled": true}), + ] { + let mut settings = settings; + settings["layer"] = json!(layer); + execute(&mut session, "layer.fill.set", &settings).unwrap(); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + save(&mut harness, &output_dir, "material-channels"); + + // The orb follows the Layers panel's channel list: its list open, then one channel alone each + harness.get_all_by_role_and_label(egui::Role::ComboBox, "Material").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-ball-list"); + harness.key_press(egui::Key::Escape); + for channel in [texturecraft_engine::core::Channel::BaseColor, texturecraft_engine::core::Channel::Normal, texturecraft_engine::core::Channel::Height] { + harness.state_mut().ui.layer_material_view = false; + harness.state_mut().ui.layer_channel = channel; + save(&mut harness, &output_dir, &format!("material-ball-{}", channel.id())); + } + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-ball-height-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::default(); + } + harness.state_mut().ui.layer_material_view = true; + + // The Base color slot (the lowest "Base color" list: the Layers panel has one too) with its list open + lowest_list(&harness, "Base color").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Perlin noise").hover(); + save(&mut harness, &output_dir, "material-source-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_all_by_role_and_label(egui::Role::Button, "Attributes").next().unwrap().click(); + save(&mut harness, &output_dir, "material-attributes"); + harness.get_all_by_role_and_label(egui::Role::Button, "Attributes").next().unwrap().click(); + harness.run_steps(2); + harness.get_all_by_role_and_label(egui::Role::Button, "Invert").next().unwrap().hover(); + save(&mut harness, &output_dir, "material-invert-hover"); + + // The procedural slot's Resolution: one row in its card, its one list holding the Relative factors and the Fixed sizes + let texture_set = harness.state().session.doc.project.texture_sets[0].resolution; + let resolution = format!("Texture set · {texture_set}"); + harness.get_by_role_and_label(egui::Role::ComboBox, &resolution).click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "1024 × 1024").hover(); + save(&mut harness, &output_dir, "material-procedural-resolution-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + // The same plain fill on the Material side: one whole material, picked from the card's list + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-whole-none"); + harness.get_by_role_and_label(egui::Role::ComboBox, "None").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Copper").hover(); + save(&mut harness, &output_dir, "material-whole-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Copper").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").hover(); + save(&mut harness, &output_dir, "material-whole-copper"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-whole-copper-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-whole-copper-channels"); + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(2); + + // Back to the fill the linked shots below expect (the pick was one undo step) + execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); + + let session = &mut harness.state_mut().session; + if let Some(LayerKind::Fill(fill)) = session.doc.project.layers.get_mut(&LayerId(layer)).map(|layer| &mut layer.kind) { + fill.link = Some(Box::new(steel_painted_worn())); + } + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + save(&mut harness, &output_dir, "material-linked"); + + // The bands sit below the panel's fold: scroll each control into view (the scroll animates for about twenty frames) + let reach = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(25); + }; + + // The band is folded by the time it is reached in this run: unfold it first + if harness.query_by_role_and_label(egui::Role::ComboBox, "normal").is_none() { + reach(&mut harness, egui::Role::Button, "Channels mapping"); + harness.get_by_role_and_label(egui::Role::Button, "Channels mapping").click(); + harness.run_steps(2); + } + reach(&mut harness, egui::Role::ComboBox, "normal"); + harness.get_by_role_and_label(egui::Role::ComboBox, "roughness").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "normal").hover(); + save(&mut harness, &output_dir, "material-mapping-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + reach(&mut harness, egui::Role::Button, "Resolution"); + save(&mut harness, &output_dir, "material-resolution-folded"); + harness.get_by_role_and_label(egui::Role::Button, "Resolution").click(); + harness.run_steps(2); + reach(&mut harness, egui::Role::ComboBox, "Texture set · 256"); + save(&mut harness, &output_dir, "material-resolution"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Texture set · 256").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "×2 · 512").hover(); + save(&mut harness, &output_dir, "material-resolution-relative-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::RadioButton, "Fixed").click(); + harness.run_steps(2); + + // This link has no package, so the re-cook fails with a toast over the panel + harness.state_mut().toasts.clear(); + harness.get_by_role_and_label(egui::Role::ComboBox, "256 × 256").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "1024 × 1024").hover(); + save(&mut harness, &output_dir, "material-resolution-fixed-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Button, "Resolution").click(); + harness.run_steps(2); + save(&mut harness, &output_dir, "material-resolution-fixed-folded"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("material-linked-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.get_by_role_and_label(egui::Role::RadioButton, "Channels").click(); + save(&mut harness, &output_dir, "material-linked-channels"); +} + +/// The armed eyedropper is the pointer over the panels too, its tip on the hovered pixel +#[test] +#[ignore] +fn eyedropper_pointer_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + + // A light and a dark model: the disc's white outline and faint dark ring must read on both + for (name, color) in [("light", [0.92, 0.92, 0.9]), ("dark", [0.01, 0.01, 0.012])] { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": color})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + // Only the app's own pointer shows, not the test's stand-in arrow + harness.set_render_cursor(false); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Base color").click(); + harness.run_steps(3); + harness.get_all_by_role_and_label(egui::Role::Button, "Pick color").next().unwrap().click(); + harness.run_steps(3); + harness.hover_at(egui::pos2(520.0, 430.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, &format!("eyedropper-over-{name}-model")); + if name == "light" { + let over_panel = harness.get_by_role_and_label(egui::Role::Tab, "Material").rect().center(); + harness.hover_at(over_panel); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-over-properties"); + harness.hover_at(egui::pos2(1590.0, 300.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-at-right-edge"); + harness.hover_at(egui::pos2(12.0, 950.0)); + harness.run_steps(2); + save(&mut harness, &output_dir, "eyedropper-at-bottom-left-corner"); + } + } +} + +/// Gives the shelf thumbnails rendered off the UI thread time to arrive +fn settle_thumbnails(h: &mut Harness<'_, TextureCraftApp>) { + for _ in 0..100 { + std::thread::sleep(std::time::Duration::from_millis(20)); + h.run_steps(1); + } +} + +/// The channel source picker opened from each kind of source, searching, on Anchor points, and the filter picker in the same style +#[test] +#[ignore] +fn source_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::execute; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + let rust = image::RgbaImage::from_fn(64, 64, |x, y| image::Rgba([150 + ((x * 7 + y * 3) % 60) as u8, 70 + ((x * y) % 40) as u8, 30, 255])); + rust.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let rust = session.import_resource_bytes("rust_albedo.png", png).unwrap(); + let below = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "effect.add.anchor", &json!({"layer": below, "name": "Edge wear"})).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.45, 0.13, 0.05]})).unwrap()["layer"].clone(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(3); + + let shot = |harness: &mut Harness<'_, TextureCraftApp>, mut source: serde_json::Value, hover: Option<&str>, search: Option<&str>, name: &str| { + source["layer"] = layer.clone(); + source["channel"] = json!("baseColor"); + execute(&mut harness.state_mut().session, "layer.fill.set", &source).unwrap(); + harness.run_steps(3); + lowest_list(harness, "Base color").click(); + harness.run_steps(30); + if let Some(text) = search { + harness.event(egui::Event::Text(text.into())); + harness.run_steps(3); + } + settle_thumbnails(harness); + if let Some(label) = hover { + let at = harness.get_by_role_and_label(egui::Role::ListBoxOption, label).rect().center(); + harness.hover_at(at); + } + save(harness, &output_dir, name); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + }; + shot(&mut harness, json!({"color": [0.45, 0.13, 0.05]}), Some("Grunge"), None, "source-picker-top"); + shot(&mut harness, json!({"image": rust}), Some("Import..."), None, "source-picker-textures"); + shot(&mut harness, json!({"alpha": "scratches"}), Some("Cracks"), None, "source-picker-alphas"); + shot(&mut harness, json!({"alpha": "letter_y"}), None, None, "source-picker-end"); + shot(&mut harness, json!({"color": [0.45, 0.13, 0.05]}), None, Some("scr"), "source-picker-search"); + + // Anchor points on the Roughness slot, scrolled into view first + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness").scroll_to_me(); + harness.run_steps(25); + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Tab, "Anchor points").click(); + harness.run_steps(3); + let anchor = harness.get_all_by_role(egui::Role::ListBoxOption).next().unwrap().rect().center(); + harness.hover_at(anchor); + save(&mut harness, &output_dir, "source-picker-anchors"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The picked procedural's card, then the three themes with the picker open from Uniform + execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "procedural": "Clouds", "scale": 4.0})) + .unwrap(); + save(&mut harness, &output_dir, "source-picker-picked"); + execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "color": [0.45, 0.13, 0.05]})).unwrap(); + harness.run_steps(3); + lowest_list(&harness, "Base color").click(); + settle_thumbnails(&mut harness); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("source-picker-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The filter picker in the same style + let filter = execute(&mut harness.state_mut().session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(); + let filter = texturecraft_engine::core::LayerId(filter["effect"].as_u64().unwrap()); + harness.state_mut().session.target = texturecraft_engine::StackTarget::Effect(filter); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::ComboBox, "Invert").click(); + settle_thumbnails(&mut harness); + let blur = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Blur").rect().center(); + harness.hover_at(blur); + save(&mut harness, &output_dir, "filter-picker-v4"); +} + /// The culling rows' i on a planar fill: each one hovered with its tooltip, in the medium theme, then the Depth culling one in the dark and light themes #[test] #[ignore] @@ -1299,6 +1657,48 @@ fn popup_tabs_snapshots() { } } +#[test] +#[ignore = "writes the material picker (Material mode) to TC_UI_SNAPSHOTS; run with --ignored"] +/// A whole-material fill's card opens the material picker: grouped under its categories, Copper chosen and Brass hovered, then a search +fn material_picker_snapshots() { + use serde_json::json; + use texturecraft_engine::{StackTarget, execute}; + + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.fill.material", &json!({"layer": layer, "material": "copper"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + session.target = StackTarget::Content; + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 2000.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness.get_by_role_and_label(egui::Role::Tab, "Material").click(); + harness.run_steps(4); + if harness.query_by_role_and_label(egui::Role::ComboBox, "Copper").is_none() { + harness.get_by_role_and_label(egui::Role::RadioButton, "Material").click(); + harness.run_steps(4); + } + harness.get_by_role_and_label(egui::Role::ComboBox, "Copper").click(); + harness.run_steps(30); + let brass = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Brass").rect().center(); + harness.hover_at(brass); + harness.run_steps(4); + save(&mut harness, &output_dir, "material-picker-open"); + harness.event(egui::Event::Text("steel".into())); + harness.run_steps(6); + save(&mut harness, &output_dir, "material-picker-search"); + if std::env::var_os("TC_UI_THEMES").is_some() { + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(4); + save(&mut harness, &output_dir, &format!("material-picker-search-{name}")); + } + } +} + /// The Properties panel at its minimum width (the right column dragged as narrow as it goes), on the Fill tab's widest row (3D projection settings) and on a filter #[test] #[ignore] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bd11cb2d..bc2cc695 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -560,6 +560,50 @@ and Height are shaded on a lit neutral material in the 3D view. `viewport.nextCh the shading uses (mesh normal, Height channel slope and Normal channel), unlit; the 2D view shows its tangent-space form. +## Colour swatches + +The project's swatches (`Project.swatches`, linear RGB, stored in the `.tcraft` file; projects without any +save none) are the Swatches row under the colour picker. `swatch.list` lists them, `swatch.add {color}` +(`[r, g, b]` linear or `"#rrggbb"`, clamped to 0..1, at most 64) adds one at the end and +`swatch.remove {index}` removes one; `project.inspect` shows them as `swatches`. Applying a swatch is an +ordinary colour edit (`layer.fill.set {color}`). + +## A fill's whole material + +A fill layer or content fill effect can hold one built-in plain material whole (the Material side of +its Material section). `layer.fill.material {layer? | effect?, material}` sets every channel the +material writes from it, turns those channels on and the others off, and keeps the fill's projection; +`material: null` returns the channels to their defaults (a content fill effect keeps the channels it +changes, at their defaults); setting what the fill already holds adds no undo step. Smart materials (folders of layers) are added +with `material.apply` instead. The fill remembers the material (`Fill.material`, saved only when set; +`project.inspect` shows it as `material`) until a channel's source is set on its own with +`layer.fill.set`. A plain material added from the shelf names its fill the same way. + +## Folders, effect blending and masks + +- `folder.contents.set {layer?, scale?, rotation?}` lays a Scale (multiplying every fill's tiling inside) + and a Rotation (degrees added to every fill's angle) on a folder's contents, never written into the fills; + `folder.contents.reset {layer?}` drops them and puts back the seeds `folder.randomizeSeeds {layer?}` changed. + `folder.randomizeSeeds` gives every pattern, generator and noise filter inside a new seed (seeds that were + equal stay equal) and returns `{seeds}`, how many changed. +- `effect.blending.modeToEveryChannel`, `opacityToEveryChannel` and `bothToEveryChannel {effect?, channel?}` + give every channel of a content effect one channel's blend mode, opacity or both; `effect.blending.copy` + and `effect.blending.paste {effect?}` carry every channel's blending between effects (a mask effect takes + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending and + `effect.set {effect, channels: {roughness: false}}` switches a content effect's channels on or off. +- `mask.add.bitmap {layer?, image | alpha, projection?}` adds a mask fill reading an image's gray; + `effect.set {effect, idMap: image resource | null}` gives a colour selection its own ID map in place of + the baked one; `tool.material {maskImage: image resource | null}` paints an image's gray into masks. +- `effect.add.colorSelection {layer?, color?, tolerance?}` and `mask.add.heightCombination {layer?}` add a + colour selection or a compare mask (this layer's height against the layers below) to a layer's mask, + making the mask first when it has none; both return `{effect}`. +- `effect.filter.restoreDefaults {effect?}` puts a filter's parameters back to its defaults (name, + channels and blending stay) and returns `{changed}`. +- `layer.fill.resetProjection {layer? | effect?}` puts the Fill section back to a new fill's (same + projection kind; a placed frame, the symmetry and the sources stay); `layer.fill.resetFrame` puts a + warp's frame back around the mesh with its corners unpulled. Each is one undo step, or none when + nothing changes. + ## MaterialCraft materials A v3 `.mcmat` holds a published SBS graph and its source assets. TextureCraft uses the shared `craft-mcmat` reader and cooks the archive through `materialcraft-cli`. The resulting fill stores its channel textures and the original archive in the project. Linked cooks use the Settings percentage of available RAM. A cook that exceeds the estimated budget reports the required and configured byte counts without replacing the current fill. Its exposed values, presets and mesh-map inputs appear in `project.inspect`. Republish older MCMAT files from their original authoring project. Procedural imports and re-cooks require the desktop CLI. Saved projects retain their baked maps for use in the browser. @@ -573,7 +617,9 @@ operation returns a busy error and can be retried. | `material.load` | `{path, above?, inside?, index?}`: `.tcmat`, `.mcmat` or `.mcraft` (cooked first) | | `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` | | `material.link.preset` | `{layer?, name, cook?: true}` | -| `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) | +| `material.link.map` | `{layer?, channel, output}`: the channel reads another output of the material | +| `material.link.resolution` | `{layer?, relative: -3..3 \| fixed: 128..8192, cook?: true}`: the size the material cooks at | +| `material.link.cook` | `{layer?}`: re-cook at its picked resolution (default: the texture set's) with its baked mesh maps (after a bake or a resize) | | `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from