From f49ff387f13d2824873a538201be7180bfdbcecb Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:29:49 +0000 Subject: [PATCH] Effects, masks and folders: engine evaluation and the remaining tests --- crates/compose/src/below.rs | 21 +- crates/compose/src/effect_histogram.rs | 95 +++ crates/compose/src/eval.rs | 686 ++++++++++++++---- crates/compose/src/lib.rs | 9 +- crates/compose/src/mask_gray.rs | 41 ++ crates/compose/src/solo.rs | 9 +- crates/compose/src/store.rs | 9 + crates/compose/src/thumb.rs | 2 +- crates/compose/tests/cache_and_instances.rs | 66 +- crates/core/src/color_selection.rs | 132 ++++ crates/core/src/compare_source.rs | 60 ++ crates/core/src/contents_offset.rs | 116 +++ crates/core/src/layer.rs | 272 ++++++- crates/core/src/lib.rs | 8 + crates/core/src/project.rs | 89 ++- crates/core/src/selection_background.rs | 58 ++ crates/engine/src/add_mask_cmds.rs | 65 ++ crates/engine/src/color_selection_cmds.rs | 78 +- crates/engine/src/effect_blending_cmds.rs | 203 ++++++ crates/engine/src/fill_material_cmds.rs | 5 + crates/engine/src/fill_reset_cmds.rs | 1 + crates/engine/src/id_mask_view.rs | 43 ++ crates/engine/src/inspect.rs | 47 +- crates/engine/src/layer_cmds.rs | 138 +++- crates/engine/src/layer_cmds/fill_target.rs | 9 - crates/engine/src/layer_selection.rs | 2 +- crates/engine/src/lib.rs | 5 + crates/engine/src/mask_owner.rs | 8 + crates/engine/src/material_lib.rs | 3 +- crates/engine/src/materials.rs | 1 + crates/engine/src/painting.rs | 29 +- crates/engine/src/path_tool.rs | 60 +- crates/engine/src/resource_cmds.rs | 3 +- crates/engine/src/session.rs | 63 +- crates/engine/src/tool_cmds.rs | 47 +- crates/engine/src/warp_cmds.rs | 1 + crates/engine/tests/it/add_mask_items.rs | 109 +++ crates/engine/tests/it/color_selection.rs | 108 ++- crates/engine/tests/it/compare_mask.rs | 130 ++++ crates/engine/tests/it/effect_blending.rs | 142 ++++ crates/engine/tests/it/fill_projections.rs | 2 +- crates/engine/tests/it/main.rs | 7 + crates/engine/tests/it/mask_paint_image.rs | 119 +++ crates/engine/tests/it/painter_gaps.rs | 19 +- crates/engine/tests/it/resources_used.rs | 74 ++ crates/paint/src/commit.rs | 153 ++-- crates/ui-egui/src/dock.rs | 361 +++++---- crates/ui-egui/src/exact_entry_open.rs | 5 + crates/ui-egui/src/fill_material_panel.rs | 24 +- crates/ui-egui/src/fill_pictures.rs | 1 + crates/ui-egui/src/filter_slot.rs | 16 +- crates/ui-egui/src/gpu.rs | 77 +- crates/ui-egui/src/lib.rs | 13 + crates/ui-egui/src/move_on_model.rs | 26 + crates/ui-egui/src/orb_environment.rs | 9 +- .../ui-egui/src/property_sheet/action_row.rs | 62 ++ .../src/property_sheet/action_row_response.rs | 9 + .../src/property_sheet/factor_slider.rs | 25 + crates/ui-egui/src/property_sheet/mod.rs | 16 + .../ui-egui/src/property_sheet/name_field.rs | 48 ++ crates/ui-egui/src/property_sheet/row.rs | 9 + crates/ui-egui/src/property_sheet/slider.rs | 5 + crates/ui-egui/src/property_sheet/slot.rs | 1 + .../ui-egui/src/property_sheet/source_card.rs | 67 ++ .../src/property_sheet/switch_control.rs | 6 + crates/ui-egui/src/property_sheet/tests.rs | 141 +++- crates/ui-egui/src/round_gizmo.rs | 46 ++ crates/ui-egui/src/slot_thumbnail.rs | 12 + crates/ui-egui/src/source_slot.rs | 9 + crates/ui-egui/src/theme.rs | 63 +- crates/ui-egui/src/thumbs.rs | 51 +- crates/ui-egui/src/viewport.rs | 42 +- crates/ui-egui/tests/it/anchor_point.rs | 103 +++ crates/ui-egui/tests/it/compare_mask_rows.rs | 85 +++ crates/ui-egui/tests/it/effect_rows.rs | 71 +- crates/ui-egui/tests/it/effect_sliders.rs | 26 +- crates/ui-egui/tests/it/empty_start.rs | 2 + crates/ui-egui/tests/it/fill_channel_image.rs | 20 +- crates/ui-egui/tests/it/filter_picker.rs | 2 +- .../ui-egui/tests/it/instance_properties.rs | 65 ++ crates/ui-egui/tests/it/layers_panel.rs | 8 +- crates/ui-egui/tests/it/levels_editor.rs | 126 +++- crates/ui-egui/tests/it/main.rs | 15 +- .../ui-egui/tests/it/mask_paint_grayscale.rs | 82 +++ crates/ui-egui/tests/it/popup_press_close.rs | 13 + crates/ui-egui/tests/it/source_picker.rs | 14 + .../ui-egui/tests/it/tile_generator_panel.rs | 35 +- crates/ui-egui/tests/ui_snapshots.rs | 550 ++++++++++++++ docs/control-protocol.md | 5 +- 89 files changed, 4928 insertions(+), 785 deletions(-) create mode 100644 crates/compose/src/effect_histogram.rs create mode 100644 crates/compose/src/mask_gray.rs create mode 100644 crates/core/src/color_selection.rs create mode 100644 crates/core/src/compare_source.rs create mode 100644 crates/core/src/contents_offset.rs create mode 100644 crates/core/src/selection_background.rs create mode 100644 crates/engine/src/add_mask_cmds.rs create mode 100644 crates/engine/src/effect_blending_cmds.rs create mode 100644 crates/engine/src/id_mask_view.rs delete mode 100644 crates/engine/src/layer_cmds/fill_target.rs create mode 100644 crates/engine/src/mask_owner.rs create mode 100644 crates/engine/tests/it/add_mask_items.rs create mode 100644 crates/engine/tests/it/compare_mask.rs create mode 100644 crates/engine/tests/it/effect_blending.rs create mode 100644 crates/engine/tests/it/mask_paint_image.rs create mode 100644 crates/engine/tests/it/resources_used.rs create mode 100644 crates/ui-egui/src/exact_entry_open.rs create mode 100644 crates/ui-egui/src/property_sheet/action_row.rs create mode 100644 crates/ui-egui/src/property_sheet/action_row_response.rs create mode 100644 crates/ui-egui/src/property_sheet/factor_slider.rs create mode 100644 crates/ui-egui/src/property_sheet/name_field.rs create mode 100644 crates/ui-egui/src/property_sheet/source_card.rs create mode 100644 crates/ui-egui/tests/it/anchor_point.rs create mode 100644 crates/ui-egui/tests/it/compare_mask_rows.rs create mode 100644 crates/ui-egui/tests/it/instance_properties.rs create mode 100644 crates/ui-egui/tests/it/mask_paint_grayscale.rs diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 4a2187ed..993c4e9a 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -142,18 +142,21 @@ impl StackKey { let mut referenced_images = BTreeSet::new(); if !images.is_empty() { - let mut record_image_reference = |source: &Source| { - referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name)); + let mut record_image_name = |name: &str| { + if let Some((name, _)) = images.get_key_value(name) { + referenced_images.insert(name); + } }; for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { if let LayerKind::Fill(fill) = &layer.kind { - fill.sources.values().for_each(&mut record_image_reference); + fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name); } for effect in layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects) { match &effect.kind { - EffectKind::Fill { source, .. } => record_image_reference(source), - EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference), - EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference), + EffectKind::Fill { source, .. } => source.images().into_iter().for_each(&mut record_image_name), + EffectKind::Material(fill) => fill.sources.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::Generator(generator) => generator.inputs.values().flat_map(Source::images).for_each(&mut record_image_name), + EffectKind::ColorSelection(selection) => selection.id_map.iter().for_each(|name| record_image_name(name)), _ => {} } } @@ -182,9 +185,11 @@ impl StackKey { if self.set != other.set || self.roots != other.roots || self.layers != other.layers || self.baked != other.baked || self.images != other.images { return None; } + if self.pixels.len() != other.pixels.len() { return None; } + let size = self.set.size(); let mut changed = BTreeSet::new(); for ((left_id, left_channel, left_image), (right_id, right_channel, right_image)) in self.pixels.iter().zip(&other.pixels) { @@ -363,8 +368,8 @@ impl BelowCache { let project = inp.project; let set = project.texture_set(inp.ts).ok()?; - // Anchor readers depend on the stack below them - if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_anchor)) { + // Anchor readers and compare masks reading layers depend on the stack below them + if project.render_tree(&set.stack).iter().any(|id| project.layers.get(id).is_some_and(Layer::reads_stack)) { return None; } diff --git a/crates/compose/src/effect_histogram.rs b/crates/compose/src/effect_histogram.rs new file mode 100644 index 00000000..83f948d6 --- /dev/null +++ b/crates/compose/src/effect_histogram.rs @@ -0,0 +1,95 @@ +//! The distribution of the values entering an effect, as the levels editor draws it + +use texturecraft_core::lum; + +/// Bucket counts over 0..1 of the values entering an effect, pooled and per part of a colour +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EffectHistogram { + /// Every value, a colour's three components pooled + pub all: Vec, + /// Red, green and blue on their own; empty for a one-value channel or a mask + pub components: Vec>, + /// Each colour's luminance; a one-value channel's or a mask's values (the same as `all`) + pub luminance: Vec, +} + +impl EffectHistogram { + /// `bins` empty buckets (at least one), with per-component buckets when it counts colours + pub fn new(bins: usize, color: bool) -> EffectHistogram { + let bins = bins.max(1); + EffectHistogram { all: vec![0; bins], components: if color { vec![vec![0; bins]; 3] } else { Vec::new() }, luminance: vec![0; bins] } + } + + /// Counts one value of a one-value channel or a mask + pub fn add_value(&mut self, value: f32) { + bump(&mut self.all, value); + bump(&mut self.luminance, value); + } + + /// Counts one colour: each component pooled and on its own, and its luminance + pub fn add_color(&mut self, color: [f32; 3]) { + for (index, component) in color.into_iter().enumerate() { + bump(&mut self.all, component); + if let Some(counts) = self.components.get_mut(index) { + bump(counts, component); + } + } + bump(&mut self.luminance, lum(color)); + } + + /// Both histograms' counts together (they have the same buckets) + pub fn merged(mut self, other: &EffectHistogram) -> EffectHistogram { + add_counts(&mut self.all, &other.all); + for (counts, more) in self.components.iter_mut().zip(&other.components) { + add_counts(counts, more); + } + add_counts(&mut self.luminance, &other.luminance); + self + } +} + +/// One more count in the bucket of `value` (clamped to 0..1) +fn bump(counts: &mut [u32], value: f32) { + let bins = counts.len(); + let index = ((value.clamp(0.0, 1.0) * bins as f32) as usize).min(bins.saturating_sub(1)); + if let Some(count) = counts.get_mut(index) { + *count = count.saturating_add(1); + } +} + +fn add_counts(counts: &mut [u32], more: &[u32]) { + for (count, extra) in counts.iter_mut().zip(more) { + *count = count.saturating_add(*extra); + } +} + +#[cfg(test)] +mod tests { + use super::EffectHistogram; + + #[test] + fn a_colour_counts_each_component_pooled_and_alone_and_its_luminance() { + let mut histogram = EffectHistogram::new(4, true); + + histogram.add_color([1.0, 0.0, 0.3]); + let merged = histogram.clone().merged(&histogram); + + assert_eq!(histogram.all, vec![1, 1, 0, 1]); + assert_eq!(histogram.components, vec![vec![0, 0, 0, 1], vec![1, 0, 0, 0], vec![0, 1, 0, 0]]); + assert_eq!(histogram.luminance, vec![0, 1, 0, 0], "luminance 0.33 lands in the second bucket"); + assert_eq!(merged.all, vec![2, 2, 0, 2]); + assert_eq!(merged.components.first(), Some(&vec![0, 0, 0, 2])); + } + + #[test] + fn a_value_has_no_components() { + let mut histogram = EffectHistogram::new(2, false); + + histogram.add_value(f32::NAN); + histogram.add_value(0.9); + + assert_eq!(histogram.all, vec![1, 1]); + assert_eq!(histogram.luminance, histogram.all); + assert!(histogram.components.is_empty()); + } +} diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index eaf04ca2..52305968 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -22,10 +22,12 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; +use crate::effect_histogram::EffectHistogram; use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_place::FillPlace; use crate::held_fields::HeldFields; +use crate::mask_gray::MaskGray; use crate::pattern::{Coords, image_samples, mesh_frame, pattern_pixels, procedural_in, world_noise}; use crate::pattern_context::PatternContext; use crate::projector_cover::{framed_cover, projector_cover, projector_covers_all}; @@ -104,8 +106,8 @@ pub struct StrokePreview { pub erase: bool, /// Values painted per channel (layer targets). pub values: BTreeMap, - /// Gray value painted into a mask. - pub mask_value: f32, + /// Gray painted into a mask + pub mask_gray: MaskGray, /// Projection tool: base color (and alpha) come from a screen-pinned image. pub stencil: Option, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). @@ -244,7 +246,8 @@ enum Content<'a> { struct EffectPlan<'a> { /// The effect id (an anchor point records under it). id: LayerId, - kind: &'a EffectKind, + /// The effect, a fill's with the Scale and Rotation of the folders around its layer laid on + kind: Cow<'a, EffectKind>, blend: BlendMode, opacity: f32, data: Option>, @@ -262,6 +265,8 @@ struct EffectPlan<'a> { struct MaskPlan<'a> { background: f32, effects: Vec>, + /// The layer's own content in the channels its compare effects read (planned only when one reads the stack) + layer: Option<(Content<'a>, Vec>)>, /// A neighbourhood filter (blur, sharpen) precomputed over the region: continue the stack /// after effect `.0` starting from the field's value. start: Option<(usize, &'a Field)>, @@ -322,14 +327,13 @@ 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. @@ -606,18 +610,33 @@ fn stroke_at(preview: Option<&[u16]>, o: usize) -> f32 { preview.and_then(|t| t.get(o)).map(|v| from_u16(*v)).unwrap_or(0.0) } -/// The full stack of tile (tx, ty) when `layer` reads anchor points (empty otherwise): evaluated -/// up to the layer, it records the anchors below it. -fn anchor_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { - match inp.project.texture_set(inp.ts) { - Ok(set) if reads_anchor(inp.project, id) => plan(inp, &set.stack, channels, tx, ty, 0, fields), - _ => Vec::new(), +/// The full stack of tile (tx, ty) in `channels` and the channels the layer's mask compares, when the layer reads the stack below it (else empty) +fn anchor_plan<'a>(inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, ty: u32, fields: Option<&'a Fields>) -> Vec> { + let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; + if !reads_stack(inp.project, id) { + return Vec::new(); } + + let compare_effects = layer_mask(inp.project, id).into_iter().flat_map(|mask| mask.effects.iter()); + let planned = compared_channels(compare_effects, channels.to_vec()); + plan(inp, &set.stack, &planned, tx, ty, 0, fields) } -/// Whether layer `id` (its own mask, or the content it draws) reads an anchor point. -pub(crate) fn reads_anchor(p: &Project, id: LayerId) -> bool { - p.layers.get(&id).is_some_and(Layer::reads_anchor) || p.content_layer(id).is_some_and(Layer::reads_anchor) +/// `channels` with every channel the Compare effects among `effects` compare added once +fn compared_channels<'e>(effects: impl IntoIterator, mut channels: Vec) -> Vec { + for effect in effects { + if let EffectKind::Compare { channel, .. } = effect.kind + && !channels.contains(&channel) + { + channels.push(channel); + } + } + channels +} + +/// Whether layer `id` (its own mask, or the content it draws) reads the stack below it: an anchor point, or a compare mask's layer sides +pub(crate) fn reads_stack(p: &Project, id: LayerId) -> bool { + p.layers.get(&id).is_some_and(Layer::reads_stack) || p.content_layer(id).is_some_and(Layer::reads_stack) } /// The mask layer `id` draws with: its own, or an instance source's. @@ -727,6 +746,11 @@ fn filter_region( (region_x, region_y, width, height): (u32, u32, u32, u32), start: Option<(usize, &Field)>, ) -> Option { + let channel = match job { + Job::Mask(_) => None, + Job::Content(channel) => Some(channel), + }; + let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index); let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0); let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height)); @@ -756,7 +780,10 @@ fn filter_region( let mut generator_sizes = None; match job { Job::Mask(layer_mask) => { - let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() }; + // The layer's own filtered content, for a compare of it (this mask's field is not built yet) + let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, Some(below), inputs.project.contents_around(id)) else { + return Vec::new(); + }; generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone()); mask_stack.effects.truncate(index); @@ -1054,27 +1081,44 @@ fn fields_of(inp: &EvaluationInputs, channels: &[Channel], list: &[LayerId], til for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; + let mask = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()); - if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) - && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) - { - out.insert(FieldKey::Mask(id), filtered); + // A mask comparing the layer's own content reads it filtered, so its field comes after the content's + let compares_content = mask.is_some_and(|mask| mask.effects.iter().any(|effect| effect.visible && compares_this_layer(&effect.kind))); + if !compares_content { + insert_mask_field(inp, channels, &mut out, id, mask, tiles); } - if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { - continue; - } - - for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { - if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { - out.insert(FieldKey::Content(id, *channel), filtered); + if !layer.is_group() && neighbourhood(&layer.content_effects, working_width).is_some() { + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); + } } } + + if compares_content { + insert_mask_field(inp, channels, &mut out, id, mask, tiles); + } } out } +/// Layer `id`'s filtered `mask` field put into `fields` (nothing without a mask or a field) +fn insert_mask_field(inp: &Inputs, channels: &[Channel], fields: &mut Fields, id: LayerId, mask: Option<&Mask>, tiles: &[(u32, u32)]) { + if let Some(mask) = mask + && let Some(filtered) = field(inp, channels, fields, id, Job::Mask(mask), tiles) + { + fields.insert(FieldKey::Mask(id), filtered); + } +} + +/// Whether a mask effect compares the layer's own content +fn compares_this_layer(kind: &EffectKind) -> bool { + matches!(kind, EffectKind::Compare { left, right, .. } if *left == CompareSource::ThisLayer || *right == CompareSource::ThisLayer) +} + /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -1100,10 +1144,9 @@ 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). @@ -1113,6 +1156,14 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { +fn effect_plans<'a>( + inp: &Inputs<'a>, + effects: &'a [Effect], + tile_x: u32, + tile_y: u32, + channel: Option, + around: ContentsOffset, +) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -1133,9 +1184,9 @@ fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u }; EffectPlan { id: effect.id, - kind: &effect.kind, - blend: effect.blend, - opacity: effect.opacity, + kind: offset_effect(&effect.kind, around), + blend: blend.mode, + opacity: blend.opacity, data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), curvature_sizes, @@ -1147,6 +1198,26 @@ fn effect_plans<'a>(inp: &EvaluationInputs<'a>, effects: &'a [Effect], tile_x: u .collect() } +/// `kind` with the folders' Scale and Rotation `around` laid on its projection (borrowed where that changes nothing) +fn offset_effect(kind: &EffectKind, around: ContentsOffset) -> Cow<'_, EffectKind> { + match kind { + EffectKind::Fill { source, projection, sampling } if !around.is_none() => { + Cow::Owned(EffectKind::Fill { source: source.clone(), projection: around.apply(projection), sampling: *sampling }) + } + EffectKind::Material(fill) if !around.is_none() => Cow::Owned(EffectKind::Material(offset_fill(fill, around).into_owned())), + _ => Cow::Borrowed(kind), + } +} + +/// `fill` with the folders' Scale and Rotation `around` laid on its projection (borrowed where that changes nothing) +fn offset_fill(fill: &Fill, around: ContentsOffset) -> Cow<'_, Fill> { + if around.is_none() { + return Cow::Borrowed(fill); + } + + Cow::Owned(Fill { projection: around.apply(&fill.projection), ..fill.clone() }) +} + /// Whether the live stroke paints `target` in this composite (a stroke on a layer instanced in a /// set of another size does not show there). fn previews(inp: &Inputs, target: PaintTarget) -> bool { @@ -1172,33 +1243,59 @@ fn tile_of<'a>(inp: &Inputs, img: Option<&'a TileImage>, tx: u32, ty: u32, chann } fn mask_plan<'a>(inp: &EvaluationInputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>) -> Option> { +/// The plan of layer `id`'s `mask` for tile (tx, ty), its fills under the Scale and Rotation `around` of the folders holding the layer +fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32, fields: Option<&'a Fields>, around: ContentsOffset) -> Option> { if !mask.enabled { return None; } let background = if mask.background == MaskBackground::White { 1.0 } else { 0.0 }; - let mut effects = effect_plans(inp, &mask.effects, tx, ty, None); + let mut effects = effect_plans(inp, &mask.effects, tx, ty, None, around); let filtered = fields.and_then(|fields| fields.get(&FieldKey::Mask(id))); for effect in &mut effects { effect.filtered_mask = filtered.and_then(|field| field.anchor_stages.iter().find(|(id, _)| *id == effect.id).map(|(_, field)| field)); } let start = filtered.and_then(|field| neighbourhood(&mask.effects, inp.gbuf.width).map(|(index, _, _)| (index, field))); - Some(MaskPlan { background, effects, start }) + let compared = compared_channels(mask.effects.iter().filter(|effect| effect.visible && effect.kind.reads_stack()), Vec::new()); + + // A folder's own content is its children: its compare sides read the stack below it + let layer = if compared.is_empty() { + None + } else { + inp.project.content_layer(id).and_then(|l| plan_content(inp, id, l, &compared, tx, ty, 0, fields, false, around)) + }; + Some(MaskPlan { background, effects, layer, start }) } -fn plan<'a>(inp: &EvaluationInputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { +/// The plans of sibling layers `list` (under the Scale and Rotation of the folders holding them) +fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { + let around = list.first().map_or(ContentsOffset::NONE, |id| inp.project.contents_around(*id)); + plan_in(inp, list, channels, tx, ty, depth, fields, around) +} + +/// [`plan`] of sibling layers held by folders whose Scale and Rotation make `around` +#[allow(clippy::too_many_arguments)] +fn plan_in<'a>( + inp: &Inputs<'a>, + list: &[LayerId], + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + around: ContentsOffset, +) -> Vec> { 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() + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, around)).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), its fills under the Scale and Rotation `around` of the folders holding it; a folder's children are planned when `kids` #[allow(clippy::too_many_arguments)] fn plan_node<'a>( - inp: &EvaluationInputs<'a>, + inp: &Inputs<'a>, id: LayerId, channels: &[Channel], tx: u32, @@ -1206,6 +1303,7 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, + around: ContentsOffset, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; @@ -1215,38 +1313,11 @@ fn plan_node<'a>( return None; } - let paint = matches!(layer.kind, LayerKind::Paint); - let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); - let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; - let chans = channels - .iter() - .filter_map(|c| { - let b = layer.blend(*c)?; - if b.mode == BlendMode::Disable || b.opacity <= 0.0 { - return None; - } - - let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; - let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c)) } else { Vec::new() }; - let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); - Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) - }) - .collect::>(); - let content = match &layer.kind { - LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, - LayerKind::Fill(f) => { - let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); - Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } - } - LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), - - // `content_layer` already followed instance links - LayerKind::Instance { .. } => return None, - }; - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); + let (content, chans) = plan_content(inp, id, layer, channels, tx, ty, depth, fields, kids, around)?; + let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields, around)); // Anchors in the mask record even where the layer draws nothing - let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(e.kind, EffectKind::Anchor))); + let mask_anchor = mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| matches!(*e.kind, EffectKind::Anchor))); // An empty paint layer still matters if its mask records an anchor if let Content::Paint { preview: false } = content @@ -1260,6 +1331,7 @@ fn plan_node<'a>( return None; } + let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); @@ -1268,6 +1340,54 @@ fn plan_node<'a>( Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) } +/// The content of `layer` (layer `id`'s own, or its instance source's; None for an unfollowed instance) and its plan per drawn channel of `channels`, its fills under the Scale and Rotation `around` of the folders holding `id`; a folder's children are planned when `kids` +#[allow(clippy::too_many_arguments)] +fn plan_content<'a>( + inp: &Inputs<'a>, + id: LayerId, + layer: &'a Layer, + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + kids: bool, + around: ContentsOffset, +) -> Option<(Content<'a>, Vec>)> { + let paint = matches!(layer.kind, LayerKind::Paint); + let fx = !layer.is_group() && layer.content_effects.iter().any(|e| e.visible); + let fx_start = if fx { neighbourhood(&layer.content_effects, inp.gbuf.width).map(|n| n.0) } else { None }; + let chans = channels + .iter() + .filter_map(|c| { + let b = layer.blend(*c)?; + if b.mode == BlendMode::Disable || b.opacity <= 0.0 { + return None; + } + + let data = if paint { tile_of(inp, inp.pixels.layer(layer.id, *c), tx, ty, Some(*c)) } else { None }; + let effects = if fx { effect_plans(inp, &layer.content_effects, tx, ty, Some(*c), around) } else { Vec::new() }; + let start = fx_start.zip(fields.and_then(|f| f.get(&FieldKey::Content(id, *c)))); + Some(ChanPlan { ch: c.index(), kind: c.kind(), comps: c.components(), blend: b.mode, opacity: b.opacity.clamp(0.0, 1.0), data, effects, start }) + }) + .collect::>(); + let content = match &layer.kind { + LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, + LayerKind::Fill(f) => { + let (depth, covers_all) = fill_coverage(inp, &f.projection, f.sampling); + Content::Fill { fill: Box::new(Cow::Borrowed(f)), depth, covers_all } + Content::Fill { fill: Box::new(offset_fill(f, around)), depth, covers_all } + } + LayerKind::Group { children, contents, .. } => { + Content::Group(if kids { plan_in(inp, children, channels, tx, ty, depth + 1, fields, around.then(*contents)) } else { Vec::new() }) + } + + // `content_layer` already followed instance links + LayerKind::Instance { .. } => return None, + }; + Some((content, chans)) +} + /// The visible anchor points of a content stack with where they cut it: after their index among /// the visible effects, or None for anchors with only anchors above them (they record the /// layer's full result). @@ -1294,7 +1414,7 @@ fn plan_levels<'a>(inp: &EvaluationInputs<'a>, levels: &[Level], channels: &[Cha .enumerate() .map(|(d, l)| LevelPlan { below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, inp.project.contents_around(l.at)), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1354,6 +1474,8 @@ struct Texel<'a, 'b> { stop: Option, /// Stack values recorded by the anchor points evaluated so far; true marks a mask anchor (gray, not channel values). anchors: Vec<(LayerId, Acc, bool)>, + /// The stack below the layer whose mask compares its channels (recorded by `eval` there, or where it stops) + below: Option, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip @@ -1588,6 +1710,15 @@ impl<'a, 'b> Texel<'a, 'b> { self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales) } + /// This texel's ID color: from image resource `image` (nearest, as stored), or from the ID mesh map without one + fn id_color(&self, image: Option<&str>) -> Option<[f32; 3]> { + let Some(name) = image else { return self.baked_color(BakedMap::Id) }; + let image = self.inp.images.get(name)?; + let [red, green, blue, _] = + image.sample_nearest((self.x as f32 + 0.5) / self.res.max(1) as f32, (self.y as f32 + 0.5) / self.inp.gbuf.height.max(1) as f32); + Some([red, green, blue]) + } + /// Where `proj` samples this texel: its coordinates, or for a projection from a frame on the surface (placed planar, warp) its place in the frame, and how much backface culling and the shape crop let through fn projected(&mut self, proj: &Projection) -> (Coords, f32) { let c = self.coords(); @@ -1890,7 +2021,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Replay the prefix to record anchors skipped by the precomputed filter - if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(e.kind, EffectKind::Anchor)) { + if let Some(last) = plan.effects.iter().take(skip).rposition(|e| matches!(*e.kind, EffectKind::Anchor)) { self.mask_effects(plan, plan.background, 0, last + 1); } self.mask_effects(plan, value, skip, plan.effects.len()) @@ -1908,7 +2039,7 @@ impl<'a, 'b> Texel<'a, 'b> { } let opacity = effect.opacity.clamp(0.0, 1.0); - match effect.kind { + match &*effect.kind { EffectKind::Paint | EffectKind::Path(_) => { let (mut painted, mut coverage) = match effect.data.as_deref() { Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), @@ -1923,7 +2054,10 @@ impl<'a, 'b> Texel<'a, 'b> { coverage *= 1.0 - stroke; } else { // Clone and smudge show the values they carry instead of the mask gray - let deposited = preview.carried_mask.as_ref().map_or(preview.mask_value, |carried| from_u16(carried.get(self.x, self.y)[0])); + let deposited = preview.carried_mask.as_ref().map_or_else( + || preview.mask_gray.at(self.x, self.y, (self.inp.gbuf.width, self.inp.gbuf.height)), + |carried| from_u16(carried.get(self.x, self.y)[0]), + ); painted = deposited * stroke + painted * (1.0 - stroke); coverage = stroke + coverage * (1.0 - stroke); } @@ -1953,20 +2087,15 @@ impl<'a, 'b> Texel<'a, 'b> { let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]); value += (filtered - value) * opacity; } - EffectKind::ColorSelection { colors, tolerance } => { - let id = self.baked_color(BakedMap::Id); - let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance); - let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 }; - value += (blend1(effect.blend, value, selected) - value) * opacity; + EffectKind::ColorSelection(selection) => { + let (selected, cover) = selection.value(self.id_color(selection.id_map.as_deref())); + value += (blend1(effect.blend, value, selected) - value) * opacity * cover; } - EffectKind::Compare { op, value: compared, tolerance } => { - let pass = match op { - CompareOp::LesserThan => value < *compared, - CompareOp::GreaterThan => value > *compared, - CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance, - }; - let result = if pass { 1.0 } else { 0.0 }; - value += (result - value) * opacity; + EffectKind::Compare { op, value: constant, tolerance, left, right, channel, hardness } => { + let left = self.compare_side(*left, *channel, plan, value, *constant); + let right = self.compare_side(*right, *channel, plan, value, *constant); + let compared = op.mask(left, right, *tolerance, *hardness); + value += (blend1(effect.blend, value, compared) - value) * opacity; } // Every channel of a mask anchor reads the mask's gray @@ -1979,13 +2108,42 @@ impl<'a, 'b> Texel<'a, 'b> { value.clamp(0.0, 1.0) } + /// What one side of a compare effect in mask `plan` reads at this texel (0..1): `mask` is the mask so far + fn compare_side(&mut self, side: CompareSource, channel: Channel, plan: &MaskPlan, mask: f32, constant: f32) -> f32 { + let stack_below = self.below; + let below = || stack_below.and_then(|acc| acc.get(channel.index()).copied()).unwrap_or_else(|| channel.default_value()); + let read = match side { + CompareSource::ThisMask => return mask, + CompareSource::Constant => return constant, + CompareSource::LayersBelow => below(), + CompareSource::ThisLayer => { + let own = plan.layer.as_ref().and_then(|(content, chans)| { + let chan_plan = chans.iter().find(|chan_plan| chan_plan.ch == channel.index())?; + self.content(content, chan_plan) + }); + + // Where the layer is empty (or thin) it shows the stack below it + let below = below(); + own.map_or(below, |(value, coverage)| mix3(below, value, coverage)) + } + }; + match channel.kind() { + ChannelKind::Color | ChannelKind::NormalMap => lum(read), + ChannelKind::Scalar => read[0], + ChannelKind::Signed => read[0] * 0.5 + 0.5, + } + } + /// Composite `nodes` over `acc`, recording anchors; true when it reached the `stop` layer (`acc` then holds the stack below it) fn eval(&mut self, nodes: &[Node], acc: &mut Acc) -> bool { for node in nodes { if self.stop == Some(node.id) { + self.below = Some(*acc); return true; } - + if node.mask.as_ref().is_some_and(|mask| mask.layer.is_some()) { + self.below = Some(*acc); + } let mask = self.tape_mask(node); match &node.content { // Masked-out groups still run when they record anchors or hold the stop layer @@ -2229,7 +2387,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// Apply one content effect to a channel's straight value and coverage fn content_effect(&mut self, effect: &EffectPlan, chan_plan: &ChanPlan, value: [f32; 3], coverage: f32) -> ([f32; 3], f32) { let opacity = effect.opacity.clamp(0.0, 1.0); - match effect.kind { + match &*effect.kind { EffectKind::Paint | EffectKind::Path(_) => { let (painted, painted_coverage) = self.painted(effect.data.as_deref(), chan_plan, effect.preview); over(chan_plan, effect.blend, value, coverage, painted, painted_coverage * opacity) @@ -2243,6 +2401,10 @@ impl<'a, 'b> Texel<'a, 'b> { None => (value, coverage), }, EffectKind::Levels(levels) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), + EffectKind::Levels(levels) => match Channel::ALL.get(chan_plan.ch) { + Some(&channel) if levels.remaps(channel) => (mix3(value, per_unit(chan_plan.kind, value, |x| levels.apply(x)), opacity), coverage), + _ => (value, coverage), + }, // 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) => { @@ -2255,7 +2417,7 @@ impl<'a, 'b> Texel<'a, 'b> { // Neighbourhood filters come precomputed through `ChanPlan::start` EffectKind::Filter(filter) => (filter.point(chan_plan.kind, value).map_or(value, |out| mix3(value, out, opacity)), coverage), // Anchors are recorded by `eval`; mask-only effects leave content as it is - EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => { + EffectKind::Anchor | EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => { (value, coverage) } } @@ -2957,7 +3119,7 @@ fn mask_tile<'a>( (tile_x, tile_y): (u32, u32), offsets: impl Iterator + 'a, ) -> impl Iterator + 'a { - let plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields)); + let plan = mask_plan(inputs, id, mask, tile_x, tile_y, Some(fields), inputs.project.contents_around(id)); let anchor_stack = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(fields)); offsets.map(move |offset| { let Some(plan) = plan.as_ref() else { return (offset, 0.0) }; @@ -2986,15 +3148,88 @@ fn histogram_tiles(width: u32, height: u32) -> Vec<(u32, u32)> { all.into_iter().step_by(stride).collect() } -/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask -/// below it, or (a content effect) the layer's `channel` below it where the layer has content, -/// color components pooled and signed values mapped to 0..1. Over the texels the mesh covers -/// (in an even sample of tiles on large sets); None for an unknown effect. -pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option> { +/// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's mask below it, or (a content effect) the layer's `channel` below it where the layer has content, signed values mapped to 0..1, a color's components pooled, on their own and as luminance. Over the texels the mesh covers (in an even sample of tiles on large sets); None for an unknown effect +pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: usize) -> Option { let (owner, _) = inp.project.effect(effect)?; let bins = bins.max(1); - // Evaluate the layer forced visible, its mask enabled, cut just below the effect. - let mut cut = inp.project.clone(); + let (cut, in_mask) = cut_below(inp.project, owner, effect)?; + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let channels = cut.texture_set(inp.ts).map(|set| set.channel_list()).unwrap_or_default(); + let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); + let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); + let color = !in_mask && channel.kind() == ChannelKind::Color; + + let histogram = tiles + .par_iter() + .map(|&(tx, ty)| { + let mut own = None; + let fields = histogram_tile_fields(shared.as_ref(), &mut own, &cut_inp, &channels, (tx, ty)); + let mut histogram = EffectHistogram::new(bins, color); + + // The mask is planned on its own: a layer with nothing drawn plans no node + let mask = if in_mask { + layer_mask(&cut, owner).and_then(|mask| mask_plan(&cut_inp, owner, mask, tx, ty, Some(fields), cut.contents_around(owner))) + } else { + None + }; + let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; + let content = nodes + .first() + .and_then(|node| node.chans.iter().find(|chan_plan| Channel::ALL.get(chan_plan.ch) == Some(&channel)).map(|chan_plan| (node, chan_plan))); + if mask.is_none() && content.is_none() { + return histogram; + } + + let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); + for (x, y, offset) in tile_texels(inp.gbuf, tx, ty) { + let mut texel = Texel::new(&cut_inp, x, y, offset, 0.0); + if !full.is_empty() { + texel.anchors_below(&full, owner); + } + if let Some(mask) = &mask { + histogram.add_value(texel.mask(mask)); + } else if let Some((node, chan_plan)) = content + && let Some((value, _)) = texel.content(&node.content, chan_plan) + { + // As levels reads them (`per_unit`); normal maps pass through levels unchanged + match chan_plan.kind { + ChannelKind::Color => histogram.add_color(value), + ChannelKind::Scalar => histogram.add_value(value[0]), + ChannelKind::Signed => histogram.add_value(value[0] * 0.5 + 0.5), + ChannelKind::NormalMap => {} + } + } + } + histogram + }) + .reduce(|| EffectHistogram::new(bins, color), |left, right| left.merged(&right)); + Some(histogram) +} + +/// The neighbourhood fields every sampled tile of a histogram shares; None with only local neighbourhood filters below, where each tile builds its own +fn shared_histogram_fields(inp: &Inputs, channels: &[Channel], tiles: &[(u32, u32)]) -> Option { + // A field covers the bounding box of the tiles it is built for, the whole set for a scattered sample + let probe = neighbourhood_fields(inp, channels, tiles.get(..1).unwrap_or_default()); + if probe.is_empty() { + return Some(probe); + } + + // A stage reading the whole set builds it for every tile: once for the whole sample instead + let whole_set = probe.values().any(|field| field.w >= inp.gbuf.width && field.h >= inp.gbuf.height); + whole_set.then(|| neighbourhood_fields(inp, channels, tiles)) +} + +/// The fields histogram tile `tile` reads: the `shared` ones, else its own built into `own` +fn histogram_tile_fields<'f>(shared: Option<&'f Fields>, own: &'f mut Option, inp: &Inputs, channels: &[Channel], tile: (u32, u32)) -> &'f Fields { + match shared { + Some(fields) => fields, + None => own.insert(neighbourhood_fields(inp, channels, &[tile])), + } +} + +/// The project with layer `owner` forced visible, its mask enabled, cut just below its effect `effect`, and whether the effect is in the mask +fn cut_below(project: &Project, owner: LayerId, effect: LayerId) -> Option<(Project, bool)> { + let mut cut = project.clone(); let l = cut.layers.get_mut(&owner)?; l.visible = true; let in_mask = match l.mask.as_mut().and_then(|m| m.effects.iter().position(|e| e.id == effect).map(|k| (m, k))) { @@ -3009,66 +3244,72 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u false } }; + Some((cut, in_mask)) +} + +/// Histograms (`bins` buckets over 0..1) of what compare mask `effect` reads on its left and right, over [`effect_histogram`]'s texels (None for another effect) +pub fn compare_histograms(inp: &Inputs, effect: LayerId, bins: usize) -> Option<[Vec; 2]> { + let (owner, found) = inp.project.effect(effect)?; + let EffectKind::Compare { left, right, channel, value: constant, .. } = found.kind else { return None }; + let bins = bins.max(1); + let (cut, in_mask) = cut_below(inp.project, owner, effect)?; + let set = cut.texture_set(inp.ts).ok()?; + if !in_mask { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let projectors = ProjectorDepthCache::default(); - let cut_inp = EvaluationInputs::new(&cut_inp, &projectors); - let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default(); + let mut channels = set.channel_list(); + if !channels.contains(&channel) { + channels.push(channel); + } + let reads_stack = found.kind.reads_stack(); let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height); - // A field covers the bounding box of the tiles it is built for, which for a scattered sample - // is the whole set: with a neighbourhood filter below, each tile gets its own. let probe = evaluation_fields(&cut_inp, &channels, tiles.get(..1).unwrap_or_default()); - let shared = probe.is_empty().then_some(probe); - let bin = |v: f32| ((v.clamp(0.0, 1.0) * bins as f32) as usize).min(bins - 1); - let hist = tiles + let shared = shared_histogram_fields(&cut_inp, &channels, &tiles); + let empty = || [EffectHistogram::new(bins, false), EffectHistogram::new(bins, false)]; + + let [left_counts, right_counts] = tiles .par_iter() .map(|&(tx, ty)| { - let own; - let fields = match &shared { - Some(f) => f, - None => { own = evaluation_fields(&cut_inp, &channels, &[(tx, ty)]); - &own - } + let mut own = None; + let fields = histogram_tile_fields(shared.as_ref(), &mut own, &cut_inp, &channels, (tx, ty)); + let mut sides = empty(); + + // The mask under the compare, and (sides reading layers) the layer's content and the stack below it + let Some(mut mask) = layer_mask(&cut, owner).and_then(|mask| mask_plan(&cut_inp, owner, mask, tx, ty, Some(fields), cut.contents_around(owner))) + else { + return sides; }; - let mut h = vec![0u32; bins]; - // The mask is planned on its own: a layer with nothing drawn plans no node. - let mask = if in_mask { layer_mask(&cut, owner).and_then(|m| mask_plan(&cut_inp, owner, m, tx, ty, Some(fields))) } else { None }; - let nodes = if in_mask { Vec::new() } else { plan(&cut_inp, &[owner], &channels, tx, ty, 0, Some(fields)) }; - let content = nodes.first().and_then(|n| n.chans.iter().find(|c| Channel::ALL.get(c.ch) == Some(&channel)).map(|c| (n, c))); - if mask.is_none() && content.is_none() { - return h; + + // Every channel, so the content also serves the compares under this one + if reads_stack { + mask.layer = cut + .content_layer(owner) + .and_then(|layer| plan_content(&cut_inp, owner, layer, &channels, tx, ty, 0, Some(fields), false, cut.contents_around(owner))); } - let full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(&cut_inp, x, y, o, 0.0); + + // The stack below, for this compare's sides and for the anchors and compares under it + let mut full = anchor_plan(&cut_inp, owner, &channels, tx, ty, Some(fields)); + if reads_stack && full.is_empty() { + full = plan(&cut_inp, &set.stack, &channels, tx, ty, 0, Some(fields)); + } + + for (x, y, offset) in tile_texels(inp.gbuf, tx, ty) { + let mut texel = Texel::new(&cut_inp, x, y, offset, 0.0); if !full.is_empty() { - tex.anchors_below(&full, owner); + texel.anchors_below(&full, owner); } - if let Some(m) = &mask { - if let Some(b) = h.get_mut(bin(tex.mask(m))) { - *b += 1; - } - } else if let Some((n, c)) = content - && let Some((v, _)) = tex.content(&n.content, c) - { - // As levels reads them (`per_unit`); normal maps pass through levels unchanged. - let (vals, signed) = match c.kind { - ChannelKind::Color => (&v[..], false), - ChannelKind::Scalar => (&v[..1], false), - ChannelKind::Signed => (&v[..1], true), - ChannelKind::NormalMap => (&v[..0], false), - }; - for x in vals { - if let Some(b) = h.get_mut(bin(if signed { x * 0.5 + 0.5 } else { *x })) { - *b += 1; - } - } + let so_far = texel.mask(&mask); + for (side, histogram) in [left, right].into_iter().zip(sides.iter_mut()) { + histogram.add_value(texel.compare_side(side, channel, &mask, so_far, constant)); } } - h + sides }) - .reduce(|| vec![0u32; bins], |a, b| a.iter().zip(&b).map(|(x, y)| x.saturating_add(*y)).collect()); - Some(hist) + .reduce(empty, |[left, right], [more_left, more_right]| [left.merged(&more_left), right.merged(&more_right)]); + Some([left_counts.all, right_counts.all]) } /// One flattened tile of one channel: (channel, tile, premultiplied value + coverage data). @@ -3419,7 +3660,7 @@ mod tests { opacity: 1.0, erase: false, values: [(Channel::BaseColor, [0.0, 0.0, 1.0])].into_iter().collect(), - mask_value: 1.0, + mask_gray: MaskGray::Value(1.0), stencil: None, carried: BTreeMap::new(), carried_mask: None, @@ -3939,7 +4180,12 @@ soft {soft:?}" fn groups_pass_through_with_opacity() { let mut f = fixture(); let gid = f.project.alloc_id(); - let g = Layer::new(gid, "G", LayerKind::Group { children: vec![], collapsed: false }, &[Channel::BaseColor]); + let g = Layer::new( + gid, + "G", + LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, + &[Channel::BaseColor], + ); f.project.insert_layer(0, g, None, false).unwrap(); f.project.layer_mut(gid).unwrap().channels.insert(Channel::BaseColor, ChannelBlend { mode: BlendMode::Passthrough, opacity: 0.5 }); let cid = f.project.alloc_id(); @@ -4149,6 +4395,89 @@ soft {soft:?}" assert_eq!(Filter::Invert.baked_light([0.0; 3], 1.0), None); } + #[test] + fn a_compares_histogram_reads_the_compares_under_it_against_the_stack() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.8); + let top = fill_layer(&mut f.project, [1.0; 3], 0.2); + let compare = |left, right| EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left, + right, + channel: Channel::Roughness, + hardness: 1.0, + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), compare(CompareSource::LayersBelow, CompareSource::Constant))); + let reader = Effect::new(f.project.alloc_id(), compare(CompareSource::ThisMask, CompareSource::Constant)); + let reader_id = reader.id; + mask.effects.push(reader); + f.project.layer_mut(top).unwrap().mask = Some(mask); + let images = ImageStore::default(); + + let [mask_so_far, _] = compare_histograms(&inputs(&f, &images, None), reader_id, 4).unwrap(); + + // The roughness below (0.8) passes the first compare everywhere: the mask so far is white + let white = *mask_so_far.last().unwrap(); + + assert!(white > 0 && mask_so_far.iter().sum::() == white, "{mask_so_far:?}"); + } + + #[test] + fn a_filtered_mask_compares_the_layers_filtered_content() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.5); + let top = fill_layer(&mut f.project, [1.0; 3], 0.9); + content_fx(&mut f, top, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 })); + let compare = EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.7, + tolerance: 0.0, + left: CompareSource::ThisLayer, + right: CompareSource::Constant, + channel: Channel::Roughness, + hardness: 1.0, + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), compare)); + f.project.layer_mut(top).unwrap().mask = Some(mask); + + let color = run(&f, None).value(Channel::BaseColor, 30, 30); + + // Uniform roughness 0.9 has no edges: black after the edge detection, it fails the compare and the layer below shows + assert!(close(color, [0.5; 3]), "{color:?}"); + } + + #[test] + fn a_compare_mask_blends_onto_the_mask_with_its_blend_mode() { + let mut f = fixture(); + fill_layer(&mut f.project, [0.5; 3], 0.8); + let top = fill_layer(&mut f.project, [1.0; 3], 0.2); + + // The roughness below (0.8) passes everywhere, but a white compare multiplied onto a black mask stays black + let mut compare = Effect::new( + f.project.alloc_id(), + EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left: CompareSource::LayersBelow, + right: CompareSource::Constant, + channel: Channel::Roughness, + hardness: 1.0, + }, + ); + compare.blend = BlendMode::Multiply; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(compare); + f.project.layer_mut(top).unwrap().mask = Some(mask); + + let color = run(&f, None).value(Channel::BaseColor, 30, 30); + assert!(close(color, [0.5; 3]), "the layer under shows: {color:?}"); + } + #[test] fn geometry_masks_show_layers_on_chosen_parts_only() { let mut f = fixture(); @@ -4385,6 +4714,71 @@ soft {soft:?}" } } + #[test] + fn fills_inside_folders_take_the_folders_scale_and_rotation_on_top_of_their_own() { + // Nested folders (x2 turned 30, then x1.5 turned -10) around a procedural fill with a procedural mask fill + let build = |outer: ContentsOffset, inner: ContentsOffset, projection: Projection| { + let mut f = fixture(); + let folder = |f: &mut Fixture, contents: ContentsOffset| { + let id = f.project.alloc_id(); + Layer::new(id, "G", LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, &[Channel::BaseColor]) + }; + let outer = folder(&mut f, outer); + let outer = f.project.insert_layer(0, outer, None, false).unwrap(); + let inner = folder(&mut f, inner); + let inner = f.project.insert_layer(0, inner, Some(outer), true).unwrap(); + let pattern = |seed| Source::Procedural { + pattern: Procedural { seed, ..Procedural::new(ProceduralKind::Perlin) }, + low: [0.0; 3], + high: [1.0; 3], + ramp: Vec::new(), + }; + let mut fill = Fill { projection: projection.clone(), ..Fill::default() }; + fill.sources.insert(Channel::BaseColor, pattern(3)); + let id = f.project.alloc_id(); + let mut layer = Layer::new(id, "C", LayerKind::Fill(fill), &[Channel::BaseColor]); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: pattern(9), projection, sampling: Default::default() })); + layer.mask = Some(mask); + f.project.insert_layer(0, layer, Some(inner), true).unwrap(); + run(&f, None) + }; + let own = Projection::Uv { scale: [2.0, 1.0], rotation: 15.0, offset: [0.1, 0.0] }; + let (outer, inner) = (ContentsOffset::new(2.0, 30.0), ContentsOffset::new(1.5, -10.0)); + let none = ContentsOffset::NONE; + let offset = build(outer, inner, own.clone()); + let written = build(none, none, Projection::Uv { scale: [6.0, 3.0], rotation: 35.0, offset: [0.1, 0.0] }); + assert_eq!(offset, written, "the folders' offset renders as if it were written into the fills"); + assert_ne!(offset, build(none, none, own), "without the offset every fill keeps its own"); + } + + #[test] + fn folder_mask_anchor_points_record_even_where_the_folder_is_masked_out() { + let mut fixture = fixture(); + let group_id = fixture.project.alloc_id(); + let folder = Layer::new( + group_id, + "G", + LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, + &[Channel::BaseColor, Channel::Roughness], + ); + fixture.project.insert_layer(0, folder, None, false).unwrap(); + let child = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Uniform([0.0; 3])); + fixture.project.insert_layer(0, Layer::new(child, "C", LayerKind::Fill(fill), &[Channel::BaseColor]), Some(group_id), true).unwrap(); + let (gray, anchor, last) = (fixture.project.alloc_id(), fixture.project.alloc_id(), fixture.project.alloc_id()); + let uniform = |value: f32| EffectKind::Fill { source: Source::Uniform([value; 3]), projection: Projection::default(), sampling: Default::default() }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects = vec![Effect::new(gray, uniform(0.4)), Effect::new(anchor, EffectKind::Anchor), Effect::new(last, uniform(0.0))]; + fixture.project.layer_mut(group_id).unwrap().mask = Some(mask); + anchor_reader(&mut fixture, anchor); + + // The folder's mask ends at 0 (its black child hides), the reader above shows at 0.4 over the 0.5 base + let color = run(&fixture, None).value(Channel::BaseColor, 5, 5); + assert!(close(color, [0.7; 3]), "{color:?}"); + } + /// A fixture under a decal fill of image "decal" framed on the plane's middle, its projection changed by `change` fn decal_fixture(change: impl FnOnce(&mut Fill)) -> Fixture { let mut fixture = fixture(); diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index ccf2d252..c40ce2f7 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -13,6 +13,7 @@ pub mod below; mod curvature_size_level; pub mod curvature_sizes; pub mod display; +mod effect_histogram; pub mod eval; mod fabric; pub mod fill_copies; @@ -22,6 +23,7 @@ pub mod frame_placement; mod fur_lock; mod held_fields; mod image_identity; +mod mask_gray; pub mod mip_level; mod organic; pub mod pattern; @@ -41,13 +43,14 @@ pub mod warp; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; +pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, - stack_reads_neighbours, + BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, + covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; +pub use mask_gray::MaskGray; pub use pattern_context::PatternContext; -pub use projector_depth_cache::ProjectorDepthCache; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/mask_gray.rs b/crates/compose/src/mask_gray.rs new file mode 100644 index 00000000..3cadf807 --- /dev/null +++ b/crates/compose/src/mask_gray.rs @@ -0,0 +1,41 @@ +//! The gray a mask stroke paints + +use std::sync::Arc; + +use texturecraft_core::lum; + +use crate::ImageRes; + +/// The gray a mask stroke paints: one value, or the gray of an image laid once over the texture by its UVs +#[derive(Clone, Debug, PartialEq)] +pub enum MaskGray { + Value(f32), + /// Image resource `name`, read as its gray like a mask fill reads an image + Image { + name: String, + image: Arc, + }, +} + +impl MaskGray { + /// The gray painted at texel (`x`, `y`) of a `width` × `height` texture (the image read at the texel's centre) + pub fn at(&self, x: u32, y: u32, (width, height): (u32, u32)) -> f32 { + match self { + MaskGray::Value(value) => value.clamp(0.0, 1.0), + MaskGray::Image { image, .. } => { + let u = (x as f32 + 0.5) / width.max(1) as f32; + let v = (y as f32 + 0.5) / height.max(1) as f32; + let [r, g, b, _] = image.sample(u, v); + lum([r, g, b]).clamp(0.0, 1.0) + } + } + } + + /// The image resource painted, None for one value + pub fn image_name(&self) -> Option<&str> { + match self { + MaskGray::Value(_) => None, + MaskGray::Image { name, .. } => Some(name), + } + } +} diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs index c9d17f5a..11427c3a 100644 --- a/crates/compose/src/solo.rs +++ b/crates/compose/src/solo.rs @@ -114,7 +114,8 @@ mod tests { fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() { let mut p = project(); let outside = add(&mut p, 0, LayerKind::Paint, None, false); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false); let view = solo_project(&p, inner, false).unwrap(); @@ -131,7 +132,8 @@ mod tests { #[test] fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() { let mut p = project(); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let other = add(&mut p, 0, LayerKind::Paint, None, false); for id in [folder, inner, other] { @@ -163,7 +165,8 @@ mod tests { #[test] fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() { let mut p = project(); - let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let folder = + add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false, contents: Default::default(), randomized: Vec::new() }, None, false); let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false); let view = solo_project(&p, instance, false).unwrap(); diff --git a/crates/compose/src/store.rs b/crates/compose/src/store.rs index e7b78d3b..07229ab5 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -128,6 +128,15 @@ impl ImageRes { bilinear(&self.rgba, self.width, self.height, u, v, (true, true)) } + /// The texel under (`u`, `v`) as stored, wrapping (an ID map's colors must not blend) + pub fn sample_nearest(&self, u: f32, v: f32) -> [f32; 4] { + if !u.is_finite() || !v.is_finite() { + return [0.0; 4]; + } + + self.nearest(u, v, (true, true)) + } + /// The texel under (`u`, `v`), on the axes that do not `repeat` the edge texel past the edge fn nearest(&self, u: f32, v: f32, repeat: (bool, bool)) -> [f32; 4] { self.texel((u * self.width as f32).floor() as i64, (v * self.height as f32).floor() as i64, repeat) diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index b4c59a15..afa677d6 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -60,7 +60,7 @@ fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option LayerId { mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position)))); mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 }))); add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask)); - let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); + let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, None); for b in f.project.layer_mut(group).unwrap().channels.values_mut() { b.mode = BlendMode::Passthrough; } @@ -226,7 +228,7 @@ fn mask_with_height_follows_the_layer_height() { } fn group(f: &mut Fixture, folder: Option, mode: BlendMode, opacity: f32, mask: Option) -> LayerId { - let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false }, mask); + let id = put(f, 0, folder, LayerKind::Group { children: vec![], collapsed: false, contents: Default::default(), randomized: Vec::new() }, mask); blend(f, id, mode, opacity); id } @@ -338,7 +340,7 @@ fn stroke(target: LayerId) -> StrokePreview { opacity: 0.9, erase: false, values: [(Channel::BaseColor, [1.0, 0.1, 0.1]), (Channel::Roughness, [0.2; 3])].into_iter().collect(), - mask_value: 1.0, + mask_gray: MaskGray::Value(1.0), stencil: None, carried: BTreeMap::new(), carried_mask: None, @@ -904,16 +906,66 @@ fn generator_input_image_changes_invalidate_stack_key() { let original = key(&images); images.insert("unrelated".into(), image(0.5)); - assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged"); let old_image = Arc::downgrade(&images["used"]); images.insert("used".into(), image(0.9)); - assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels"); assert!(key(&images) != original, "replacing a generator input must invalidate the cache"); images.remove("used"); - assert!(key(&images) != original, "removing a generator input must invalidate the cache"); } + +#[test] +fn compare_masks_reading_layers_fall_back_to_full_evaluation() { + let mut f = fixture(); + let n = nested_stack(&mut f); + let compare = effect( + &mut f, + EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.5, + tolerance: 0.0, + left: CompareSource::LayersBelow, + right: CompareSource::ThisLayer, + channel: Channel::Roughness, + hardness: 1.0, + }, + ); + + // A mask above the hot layer compares the stack below it + f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(compare); + + for hot in [n.deep, n.top] { + assert!(check_cached(&f, 0, hot).is_empty(), "compare masks read the stack: nothing cached"); + } +} + +/// The key of set 0's whole stack over `images` +fn stack_key(fixture: &Fixture, images: &texturecraft_compose::ImageStore) -> texturecraft_compose::StackKey { + let roots = &fixture.project.texture_sets[0].stack; + texturecraft_compose::StackKey::new(&fixture.project, &fixture.pixels, &Default::default(), images, 0, roots).unwrap() +} + +/// A flat image resource of `value` +fn flat_image(value: f32) -> std::sync::Arc { + std::sync::Arc::new(texturecraft_compose::ImageRes::new(RES, RES, vec![[value; 4]; (RES * RES) as usize], false)) +} + +#[test] + let mut fixture = fixture(); + heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + selection.id_map = Some("id".into()); + let selection = effect(&mut fixture, EffectKind::ColorSelection(selection)); + let layer = fixture.project.layer_mut(bottom_layer).unwrap(); + layer.mask = Some(Mask::new(MaskBackground::White)); + layer.mask.as_mut().unwrap().effects.push(selection); + let mut images = texturecraft_compose::ImageStore::default(); + images.insert("id".into(), flat_image(0.1)); + + let original = stack_key(&fixture, &images); + +} diff --git a/crates/core/src/color_selection.rs b/crates/core/src/color_selection.rs new file mode 100644 index 00000000..df2390a4 --- /dev/null +++ b/crates/core/src/color_selection.rs @@ -0,0 +1,132 @@ +//! A mask effect that selects the parts of an ID map whose colors are in its list + +use serde::{Deserialize, Serialize}; + +use crate::SelectionBackground; + +/// Selects ID-map colors within a tolerance: the selected parts get the output value, the rest the background +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ColorSelection { + /// The selected ID colors, as the ID map stores them + pub colors: Vec<[f32; 3]>, + /// How far each component may be from a selected color and still count as it + pub tolerance: f32, + /// The value selected parts get + #[serde(default = "full", skip_serializing_if = "is_full")] + pub output: f32, + /// 1 is a hard edge (what selections saved before hardness did); lower ramps over 1 − hardness past the tolerance + #[serde(default = "full", skip_serializing_if = "is_full")] + pub hardness: f32, + #[serde(default, skip_serializing_if = "SelectionBackground::is_default")] + pub background: SelectionBackground, + /// The image resource read as the ID map; none reads the texture set's ID mesh map + #[serde(default, skip_serializing_if = "Option::is_none")] + pub id_map: Option, +} + +fn full() -> f32 { + 1.0 +} + +/// Whether an output or hardness is what selections saved before it existed had (not saved then, so they save as they were) +fn is_full(value: &f32) -> bool { + *value == full() +} + +impl ColorSelection { + /// A selection of `colors` with the defaults of a new one + pub fn new(colors: Vec<[f32; 3]>, tolerance: f32) -> ColorSelection { + ColorSelection { colors, tolerance, output: 1.0, hardness: 1.0, background: SelectionBackground::Black, id_map: None } + } + + /// How much ID color `id` is selected, 0..1 (none: no ID map there) + pub fn amount(&self, id: Option<[f32; 3]>) -> f32 { + let Some(id) = id else { return 0.0 }; + let distance = self + .colors + .iter() + // A NaN component matches nothing (f32::max would drop it), as the old strict comparison did + .map(|picked| { + picked + .iter() + .zip(id) + .map(|(picked, component)| (picked - component).abs()) + .fold(0.0f32, |far, gap| if gap.is_nan() || gap > far { gap } else { far }) + }) + .fold(f32::INFINITY, f32::min); + if !distance.is_finite() { + return 0.0; + } + + let past = distance - self.tolerance; + if past <= 0.0 { + return 1.0; + } + + // A NaN tolerance or hardness (only a hand-edited file holds one) selects nothing, as a NaN component does + let width = 1.0 - self.hardness.clamp(0.0, 1.0); + let ramp = if width <= 0.0 { 0.0 } else { (1.0 - past / width).clamp(0.0, 1.0) }; + if ramp.is_nan() { 0.0 } else { ramp } + } + + /// The gray this selection gives ID color `id` and how much of it covers the mask below (a transparent background covers only the selection) + pub fn value(&self, id: Option<[f32; 3]>) -> (f32, f32) { + let amount = self.amount(id); + match self.background.value() { + Some(background) => (background + (self.output - background) * amount, 1.0), + None => (self.output, amount), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::EffectKind; + + #[test] + fn a_selection_saved_before_loads_hard_on_black_from_the_mesh_map() { + let saved = r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#; + let EffectKind::ColorSelection(selection) = serde_json::from_str::(saved).unwrap() else { panic!("not a color selection") }; + assert_eq!(selection, ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1)); + assert_eq!(serde_json::to_string(&EffectKind::ColorSelection(selection)).unwrap(), saved, "it saves as it was saved"); + } + + #[test] + fn the_hard_edge_selects_as_before_and_softness_ramps_past_the_tolerance() { + let mut selection = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + assert_eq!(selection.value(Some([0.95, 0.05, 0.0])), (1.0, 1.0)); + assert_eq!(selection.value(Some([0.8, 0.0, 0.0])), (0.0, 1.0)); + assert_eq!(selection.value(None), (0.0, 1.0)); + assert_eq!(selection.value(Some([f32::NAN, 0.0, 0.0])), (0.0, 1.0)); + selection.hardness = 0.8; + let (ramped, _) = selection.value(Some([0.8, 0.0, 0.0])); + assert!((ramped - 0.5).abs() < 1e-5, "{ramped}"); + selection.colors.clear(); + assert_eq!(selection.value(Some([1.0, 0.0, 0.0])), (0.0, 1.0)); + } + + #[test] + fn a_nan_tolerance_or_hardness_selects_nothing() { + let mut nan_tolerance = ColorSelection::new(vec![[1.0, 0.0, 0.0]], f32::NAN); + nan_tolerance.hardness = 0.5; + let mut nan_hardness = ColorSelection::new(vec![[1.0, 0.0, 0.0]], 0.1); + nan_hardness.hardness = f32::NAN; + + for selection in [nan_tolerance, nan_hardness] { + assert_eq!(selection.amount(Some([0.8, 0.0, 0.0])), 0.0); + } + } + + #[test] + fn the_output_and_background_set_both_sides_and_transparent_covers_only_the_selection() { + let mut selection = ColorSelection::new(vec![[0.0, 0.0, 1.0]], 0.1); + selection.output = 0.25; + selection.background = SelectionBackground::White; + assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0)); + assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (1.0, 1.0)); + selection.background = SelectionBackground::Transparent; + assert_eq!(selection.value(Some([0.0, 0.0, 1.0])), (0.25, 1.0)); + assert_eq!(selection.value(Some([1.0, 1.0, 1.0])), (0.25, 0.0)); + } +} diff --git a/crates/core/src/compare_source.rs b/crates/core/src/compare_source.rs new file mode 100644 index 00000000..794e7c6f --- /dev/null +++ b/crates/core/src/compare_source.rs @@ -0,0 +1,60 @@ +//! What one side of a compare mask reads + +use serde::{Deserialize, Serialize}; + +/// One side of a compare mask's comparison +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum CompareSource { + /// The compared channel of the stack below the layer + LayersBelow, + /// The compared channel of the layer's own content, laid over the stack below by its coverage + ThisLayer, + /// The mask so far (the effects under the compare) + ThisMask, + /// The compare's constant + Constant, +} + +impl CompareSource { + /// Menu order + pub const ALL: [CompareSource; 4] = [CompareSource::LayersBelow, CompareSource::ThisLayer, CompareSource::ThisMask, CompareSource::Constant]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + CompareSource::LayersBelow => "layersBelow", + CompareSource::ThisLayer => "thisLayer", + CompareSource::ThisMask => "thisMask", + CompareSource::Constant => "constant", + } + } + + pub fn from_id(id: &str) -> Option { + CompareSource::ALL.into_iter().find(|source| source.id() == id) + } + + /// Reads a material channel of the stack (the layer or the layers below) + pub fn reads_stack(self) -> bool { + matches!(self, CompareSource::LayersBelow | CompareSource::ThisLayer) + } + + /// The left side of compare masks saved before sources existed + pub(crate) fn saved_left() -> CompareSource { + CompareSource::ThisMask + } + + /// The right side of compare masks saved before sources existed + pub(crate) fn saved_right() -> CompareSource { + CompareSource::Constant + } + + /// Whether a left side reads what saved compare masks did (not saved then) + pub(crate) fn is_saved_left(&self) -> bool { + *self == CompareSource::saved_left() + } + + /// Whether a right side reads what saved compare masks did (not saved then) + pub(crate) fn is_saved_right(&self) -> bool { + *self == CompareSource::saved_right() + } +} diff --git a/crates/core/src/contents_offset.rs b/crates/core/src/contents_offset.rs new file mode 100644 index 00000000..033071b0 --- /dev/null +++ b/crates/core/src/contents_offset.rs @@ -0,0 +1,116 @@ +//! A folder's Scale and Rotation for the fills inside it + +use serde::{Deserialize, Serialize}; + +use crate::layer::Projection; + +/// Scale and Rotation a folder lays on every fill inside it, on top of each fill's own: the tiling is multiplied by `scale` and `rotation` (degrees) is added to the fill's angle; the fills themselves never change, so dropping the offset gives each its own back +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct ContentsOffset { + pub scale: f32, + pub rotation: f32, +} + +impl Default for ContentsOffset { + /// Nothing changed, as in every folder saved before folders had an offset + fn default() -> Self { + ContentsOffset::NONE + } +} + +impl ContentsOffset { + /// The offset that changes nothing + pub const NONE: ContentsOffset = ContentsOffset { scale: 1.0, rotation: 0.0 }; + + /// The smallest and largest Scale a folder takes + pub const SCALE_RANGE: (f32, f32) = (0.01, 100.0); + + /// The Rotation a folder takes, in degrees: a half turn each way + pub const ROTATION_RANGE: (f32, f32) = (-180.0, 180.0); + + /// Whether the offset changes nothing + pub fn is_none(&self) -> bool { + *self == ContentsOffset::NONE + } + + /// An offset with `scale` kept in [`ContentsOffset::SCALE_RANGE`] and `rotation` wrapped into [`ContentsOffset::ROTATION_RANGE`] (non-finite values change nothing) + pub fn new(scale: f32, rotation: f32) -> ContentsOffset { + let (low, high) = ContentsOffset::SCALE_RANGE; + let scale = if scale.is_finite() { scale.clamp(low, high) } else { 1.0 }; + let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE; + let rotation = if rotation.is_finite() { (rotation - turn_start).rem_euclid(turn_end - turn_start) + turn_start } else { 0.0 }; + ContentsOffset { scale, rotation } + } + + /// The offset of a folder inside one with offset `self` (`inner` is the inner folder's own): scales multiply, rotations add, and the result stays in range however deep folders nest + pub fn then(self, inner: ContentsOffset) -> ContentsOffset { + ContentsOffset::new(self.scale * inner.scale, self.rotation + inner.rotation) + } + + /// `projection` with this offset laid on its tiling and rotation (a projection stretched once over each UV tile has neither) + pub fn apply(self, projection: &Projection) -> Projection { + // A loaded offset never went through `new` + let offset = ContentsOffset::new(self.scale, self.rotation); + let mut out = projection.clone(); + match &mut out { + Projection::Uv { scale, rotation, .. } => { + *scale = scale.map(|s| s * offset.scale); + *rotation += offset.rotation; + } + Projection::UvTile => {} + Projection::Triplanar { uv, .. } + | Projection::Planar { uv, .. } + | Projection::Spherical { uv, .. } + | Projection::Cylindrical { uv, .. } + | Projection::Warp { uv, .. } => { + uv.tiling = uv.tiling.map(|t| t * offset.scale); + uv.rotation += offset.rotation; + } + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::layer::UvTransform; + + #[test] + fn an_offset_multiplies_the_tiling_and_adds_to_the_angle_of_every_projection() { + let offset = ContentsOffset::new(1.5, 30.0); + let uv = offset.apply(&Projection::Uv { scale: [2.0, 4.0], rotation: 10.0, offset: [0.25, 0.0] }); + assert_eq!(uv, Projection::Uv { scale: [3.0, 6.0], rotation: 40.0, offset: [0.25, 0.0] }); + let spherical = Projection::Spherical { + scale: 1.0, + uv: UvTransform { tiling: [2.0, 1.0], rotation: -5.0, offset: [0.0; 2] }, + offset: [0.0; 3], + projector: Default::default(), + }; + let Projection::Spherical { scale, uv, .. } = offset.apply(&spherical) else { panic!("expected a spherical projection") }; + assert_eq!((scale, uv.tiling, uv.rotation), (1.0, [3.0, 1.5], 25.0)); + assert_eq!(offset.apply(&Projection::UvTile), Projection::UvTile); + assert_eq!(ContentsOffset::NONE.apply(&spherical), spherical); + } + + #[test] + fn nested_offsets_combine_and_hostile_values_are_kept_in_range() { + let both = ContentsOffset::new(2.0, 170.0).then(ContentsOffset::new(1.5, 20.0)); + assert_eq!((both.scale, both.rotation), (3.0, -170.0)); + assert_eq!(ContentsOffset::new(f32::NAN, f32::INFINITY), ContentsOffset::NONE); + assert_eq!(ContentsOffset::new(1e9, 190.0), ContentsOffset { scale: 100.0, rotation: -170.0 }); + assert_eq!(ContentsOffset::new(-3.0, -180.0), ContentsOffset { scale: 0.01, rotation: -180.0 }); + assert!(ContentsOffset::default().is_none()); + } + + #[test] + fn deep_nesting_and_loaded_offsets_keep_the_scale_in_range() { + let deep = (0..17).fold(ContentsOffset::NONE, |around, _| around.then(ContentsOffset::new(100.0, 0.0))); + assert_eq!(deep.scale, ContentsOffset::SCALE_RANGE.1); + + let loaded: ContentsOffset = serde_json::from_str(r#"{"scale":0,"rotation":0}"#).unwrap(); + let tiled = loaded.apply(&Projection::Uv { scale: [2.0, 2.0], rotation: 0.0, offset: [0.0; 2] }); + assert_eq!(tiled, Projection::Uv { scale: [0.02, 0.02], rotation: 0.0, offset: [0.0; 2] }, "a loaded Scale of 0 is kept at the smallest"); + } +} diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 7d380e4c..56520585 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -129,7 +129,16 @@ pub enum LayerKind { /// A procedural or uniform material applied everywhere (shaped by the mask). Fill(Fill), /// A folder of layers, bottom → top. - Group { children: Vec, collapsed: bool }, + Group { + children: Vec, + collapsed: bool, + /// Scale and Rotation laid on every fill inside (none in folders saved before folders had one) + #[serde(default, skip_serializing_if = "ContentsOffset::is_none")] + contents: ContentsOffset, + /// The seeds inside that its Randomize seeds changed, until its Contents reset puts them back (none in folders saved before) + #[serde(default, skip_serializing_if = "Vec::is_empty")] + randomized: Vec, + }, /// A linked instance of `source` (possibly in another texture set): renders the source's /// content, content effects and channel blending, and its mask unless the instance has its /// own. Edits to the source show in every instance. @@ -137,6 +146,11 @@ pub enum LayerKind { } impl LayerKind { + /// A new folder: empty, open, with no Scale or Rotation laid on its contents + pub fn folder() -> LayerKind { + LayerKind::Group { children: Vec::new(), collapsed: false, contents: ContentsOffset::NONE, randomized: Vec::new() } + } + pub fn name(&self) -> &'static str { match self { LayerKind::Paint => "paint", @@ -697,6 +711,11 @@ impl Source { _ => None, } } + + /// Whether this source reads anchor point `anchor` (any anchor point when None) + pub fn reads_anchor(&self, anchor: Option) -> bool { + self.anchor().is_some_and(|found| anchor.is_none_or(|wanted| wanted == found)) + } } /// A fill layer's material: one source per channel, plus how it is projected. @@ -834,19 +853,51 @@ pub struct Levels { pub gamma: f32, pub out_low: f32, pub out_high: f32, + /// The one channel a content levels remaps; none remaps every channel (as levels saved before the choice did) and a mask's one value + #[serde(default, skip_serializing_if = "Option::is_none")] + pub affects: Option, + /// Values past the input handles stop at the output ends; off, the remap's line carries on past them (older saves load clamped) + #[serde(default = "saved_levels_clamp", skip_serializing_if = "is_true")] + pub clamp: bool, +} + +/// What levels saved before [`Levels::clamp`] existed did +fn saved_levels_clamp() -> bool { + true } impl Default for Levels { fn default() -> Self { - Levels { in_low: 0.0, in_high: 1.0, gamma: 1.0, out_low: 0.0, out_high: 1.0 } + Levels { in_low: 0.0, in_high: 1.0, gamma: 1.0, out_low: 0.0, out_high: 1.0, affects: None, clamp: false } } } impl Levels { + /// The gamma a levels effect takes, typed or dragged + pub const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + + /// Narrowest input range the remap divides by, so handles on one value never divide by zero + const MIN_INPUT_RANGE: f32 = 1e-5; + + /// Smallest gamma the remap raises by, so a zero gamma read from a file never divides by zero + const MIN_GAMMA: f32 = 1e-3; + pub fn apply(&self, x: f32) -> f32 { - let t = ((x - self.in_low) / (self.in_high - self.in_low).max(1e-5)).clamp(0.0, 1.0); - let t = t.powf(1.0 / self.gamma.max(1e-3)); - self.out_low + (self.out_high - self.out_low) * t + let between = (x - self.in_low) / (self.in_high - self.in_low).max(Self::MIN_INPUT_RANGE); + + // Past the input handles an unclamped remap carries on in a straight line (gamma only bends the part between them) + let between = if self.clamp || (0.0..=1.0).contains(&between) { between.clamp(0.0, 1.0).powf(1.0 / self.gamma.max(Self::MIN_GAMMA)) } else { between }; + self.out_low + (self.out_high - self.out_low) * between + } + + /// Whether these levels remap `channel` of a layer's content + pub fn remaps(&self, channel: Channel) -> bool { + self.affects.is_none_or(|affects| affects == channel) + } + + /// The handles back at their defaults, keeping the channel and the clamp + pub fn reset(&self) -> Levels { + Levels { affects: self.affects, clamp: self.clamp, ..Levels::default() } } } @@ -1125,6 +1176,10 @@ pub enum Filter { }, } +fn is_true(on: &bool) -> bool { + *on +} + /// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1. fn shift_unit(x: f32, amount: f32) -> f32 { let a = amount.clamp(-1.0, 1.0); @@ -1378,15 +1433,24 @@ pub enum EffectKind { Levels(Levels), Filter(Filter), /// Select ID-map colors within a tolerance. - ColorSelection { - colors: Vec<[f32; 3]>, - tolerance: f32, - }, - /// Compare the mask with a constant. + ColorSelection(crate::ColorSelection), + /// Compare one channel (or the mask so far, or a constant) on two sides: 1 where the comparison holds, softened by `hardness` Compare { op: CompareOp, + /// The constant a [`CompareSource::Constant`] side reads value: f32, + /// How far apart two values may be and still count as equal ([`CompareOp::WithinTolerance`]) tolerance: f32, + #[serde(default = "CompareSource::saved_left", skip_serializing_if = "CompareSource::is_saved_left")] + left: CompareSource, + #[serde(default = "CompareSource::saved_right", skip_serializing_if = "CompareSource::is_saved_right")] + right: CompareSource, + /// The channel a layer side reads + #[serde(default = "saved_compare_channel", skip_serializing_if = "is_saved_compare_channel")] + channel: Channel, + /// 1 is a hard step (what compare masks saved before hardness did); lower ramps over 1 − hardness + #[serde(default = "saved_compare_hardness", skip_serializing_if = "is_saved_compare_hardness")] + hardness: f32, }, /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). @@ -1421,6 +1485,66 @@ pub enum CompareOp { GreaterThan, } +impl CompareOp { + /// Menu order + pub const ALL: [CompareOp; 3] = [CompareOp::LesserThan, CompareOp::WithinTolerance, CompareOp::GreaterThan]; + + /// Command id + pub fn id(self) -> &'static str { + match self { + CompareOp::LesserThan => "lesser", + CompareOp::WithinTolerance => "within", + CompareOp::GreaterThan => "greater", + } + } + + pub fn from_id(id: &str) -> Option { + match id { + // mask.add.compare took "less" as well as "lesser" before the ids were the op names + "less" => Some(CompareOp::LesserThan), + _ => CompareOp::ALL.into_iter().find(|op| op.id() == id), + } + } + + /// The mask value of `left` compared with `right`: a hard 0/1 at hardness 1, else a ramp over 1 − hardness past the edge + pub fn mask(self, left: f32, right: f32, tolerance: f32, hardness: f32) -> f32 { + // How far past the edge of the passing range `left` is (positive passes) + let past = match self { + CompareOp::LesserThan => right - left, + CompareOp::GreaterThan => left - right, + CompareOp::WithinTolerance => tolerance - (left - right).abs(), + }; + let width = (1.0 - hardness).clamp(0.0, 1.0); + let pass = if self == CompareOp::WithinTolerance { past >= 0.0 } else { past > 0.0 }; + if width.is_nan() || width <= 0.0 || past.is_nan() { + return if pass { 1.0 } else { 0.0 }; + } + + let ramp = if self == CompareOp::WithinTolerance { 1.0 + past / width } else { past / width }; + ramp.clamp(0.0, 1.0) + } +} + +/// The channel of compare masks saved before the channel choice (their sides read no channel) +fn saved_compare_channel() -> Channel { + Channel::Height +} + +/// The hardness of compare masks saved before hardness existed (a hard step) +fn saved_compare_hardness() -> f32 { + 1.0 +} + +/// Whether a compare mask reads the channel saved ones did (not saved then) +fn is_saved_compare_channel(channel: &Channel) -> bool { + *channel == saved_compare_channel() +} + +/// Whether a compare mask is the hard step saved ones were (not saved then) +fn is_saved_compare_hardness(hardness: &f32) -> bool { + *hardness == saved_compare_hardness() +} + impl EffectKind { pub fn name(&self) -> &'static str { match self { @@ -1437,6 +1561,11 @@ impl EffectKind { } } + /// Whether the effect has a blend mode and opacity of its own (levels and anchor points do not) + pub fn blends(&self) -> bool { + !matches!(self, EffectKind::Levels(_) | EffectKind::Anchor) + } + /// Whether the effect belongs in a layer's content stack (`true`), its mask (`false`), or /// both (`None`). pub fn content_only(&self) -> Option { @@ -1452,12 +1581,15 @@ impl EffectKind { matches!(self, EffectKind::Paint | EffectKind::Path(_)) } - /// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point. - fn reads_anchor(&self) -> bool { + /// Whether a source of this effect reads anchor point `anchor` (any anchor point when None) + pub fn reads(&self, anchor: Option) -> bool { match self { - EffectKind::Fill { source, .. } => source.anchor().is_some(), - EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()), - EffectKind::Generator(generator) => generator.micro.is_some() || generator.inputs.values().any(|source| source.anchor().is_some()), + EffectKind::Fill { source, .. } => source.reads_anchor(anchor), + EffectKind::Material(fill) => fill.sources.values().any(|source| source.reads_anchor(anchor)), + EffectKind::Generator(generator) => { + generator.micro.is_some_and(|micro| anchor.is_none_or(|wanted| wanted == micro.anchor)) + || generator.inputs.values().any(|source| source.reads_anchor(anchor)) + } _ => false, } } @@ -1485,7 +1617,7 @@ impl EffectKind { anchors } - /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input) + /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input, a colour selection's ID map) pub fn images_read(&self) -> impl Iterator { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], @@ -1493,7 +1625,16 @@ impl EffectKind { EffectKind::Generator(generator) => generator.inputs.values().collect(), _ => Vec::new(), }; - sources.into_iter().flat_map(Source::images) + let id_map = match self { + EffectKind::ColorSelection(selection) => selection.id_map.as_deref(), + _ => None, + }; + sources.into_iter().flat_map(Source::images).chain(id_map) + } + + /// Reads a channel of the layer or of the stack below it (a compare mask's layer sides) + pub fn reads_stack(&self) -> bool { + matches!(self, EffectKind::Compare { left, right, .. } if left.reads_stack() || right.reads_stack()) } } @@ -1501,10 +1642,14 @@ impl Layer { /// Whether any source of the layer (fill, mask or content effects) reads an anchor point. pub fn reads_anchor(&self) -> bool { let fill = match &self.kind { - LayerKind::Fill(f) => f.sources.values().any(|s| s.anchor().is_some()), + LayerKind::Fill(fill) => fill.sources.values().any(|source| source.reads_anchor(None)), _ => false, }; - fill || self.mask.iter().flat_map(|m| m.effects.iter()).chain(self.content_effects.iter()).any(|e| e.kind.reads_anchor()) + } + + /// Whether the layer's result depends on the stack below it: it reads an anchor point, or its mask compares channels of the stack + pub fn reads_stack(&self) -> bool { + self.reads_anchor() || self.mask.iter().flat_map(|mask| mask.effects.iter()).any(|effect| effect.visible && effect.kind.reads_stack()) } } @@ -1516,12 +1661,20 @@ pub struct Effect { pub kind: EffectKind, pub blend: BlendMode, pub opacity: f32, + /// A content effect's channels that blend apart from `blend` and `opacity` (none in projects saved before they existed) + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub channel_blends: BTreeMap, } impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { // Generators and fills that build a mask usually add on top of the background - Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 } + } + + /// How the effect blends on `channel` of its layer's content, or on its mask (`None`) + pub fn blend_of(&self, channel: Option) -> ChannelBlend { + let shared = ChannelBlend { mode: self.blend, opacity: self.opacity }; + channel.and_then(|channel| self.channel_blends.get(&channel).copied()).unwrap_or(shared) } } @@ -1559,6 +1712,12 @@ mod tests { assert_eq!(effect.images_read().collect::>(), vec!["material.png"]); } + #[test] + let mut selection = crate::ColorSelection::new(Vec::new(), 0.0); + selection.id_map = Some("id.png".into()); + + } + #[test] fn generator_offset_shifts_the_mask_value() { let mut g = Generator::new(GeneratorKind::Position); @@ -1648,7 +1807,7 @@ mod tests { #[test] fn levels_map_range_and_gamma() { - let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 }; + let l = Levels { in_low: 0.2, in_high: 0.6, clamp: true, ..Levels::default() }; assert!((l.apply(0.4) - 0.5).abs() < 1e-6); assert_eq!(l.apply(0.0), 0.0); assert_eq!(l.apply(1.0), 1.0); @@ -1661,6 +1820,18 @@ mod tests { assert!(d.apply(0.7).is_finite()); } + #[test] + fn unclamped_levels_carry_on_past_the_input_handles() { + let clamped = Levels { in_low: 0.2, in_high: 0.6, clamp: true, ..Levels::default() }; + let open = Levels { clamp: false, ..clamped }; + assert_eq!(clamped.apply(0.0), 0.0); + assert!((open.apply(0.0) + 0.5).abs() < 1e-6, "0.2 below the black handle is half a range below black"); + assert!((open.apply(0.8) - 1.5).abs() < 1e-6); + assert!((open.apply(0.4) - clamped.apply(0.4)).abs() < 1e-6, "between the handles both remap alike"); + let bent = Levels { gamma: 2.0, ..open }; + assert!((bent.apply(0.0) + 0.5).abs() < 1e-6, "gamma bends only the part between the handles"); + } + #[test] fn fills_and_effects_in_the_shape_older_projects_saved_save_unchanged() { let fills = [ @@ -1679,6 +1850,9 @@ mod tests { 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#"{"Levels":{"in_low":0.2,"in_high":0.6,"gamma":1.0,"out_low":0.0,"out_high":1.0}}"#, + r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#, + r#"{"ColorSelection":{"colors":[[1.0,0.0,0.0]],"tolerance":0.1}}"#, r#"{"Material":{"sources":{},"projection":{"Spherical":{"scale":2.0}}}}"#, ]; for saved in effects { @@ -1688,6 +1862,23 @@ mod tests { } } + #[test] + fn levels_saved_before_the_channel_and_clamp_load_as_they_rendered() { + let saved = serde_json::json!({"in_low": 0.2, "in_high": 0.6, "gamma": 1.0, "out_low": 0.0, "out_high": 1.0}); + let loaded: Levels = serde_json::from_value(saved.clone()).unwrap(); + assert!(loaded.clamp, "they stopped at the output ends"); + assert_eq!(loaded.affects, None, "they remapped every channel"); + assert!(Channel::ALL.iter().all(|&channel| loaded.remaps(channel))); + let saved_again = serde_json::to_value(loaded).unwrap(); + assert!(saved_again.get("affects").is_none(), "no channel is saved, as before: {saved_again}"); + assert!(saved_again.get("clamp").is_none(), "a clamped level is saved as before: {saved_again}"); + assert_eq!(serde_json::from_value::(saved_again).unwrap(), loaded); + let unclamped = serde_json::to_value(Levels { clamp: false, ..loaded }).unwrap(); + assert_eq!(serde_json::from_value::(unclamped).unwrap(), Levels { clamp: false, ..loaded }, "an unclamped level keeps its choice"); + let base = Levels { affects: Some(Channel::BaseColor), ..loaded }; + assert!(base.remaps(Channel::BaseColor) && !base.remaps(Channel::Roughness)); + } + #[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); @@ -1711,13 +1902,17 @@ mod tests { let cl = Filter::ContrastLuminosity { contrast: 1.0, luminosity: 0.0 }; assert!(close(cl.point(c, [0.25, 0.5, 0.75]).unwrap(), [0.0, 0.5, 1.0])); assert!(close(Filter::ContrastLuminosity { contrast: 0.0, luminosity: 0.2 }.point(ChannelKind::Scalar, [0.5; 3]).unwrap(), [0.7; 3])); + let gm = Filter::GradientMap { colors: vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]] }; assert!(close(gm.point(c, [0.0; 3]).unwrap(), [1.0, 0.0, 0.0])); assert!(close(gm.point(c, [1.0; 3]).unwrap(), [0.0, 0.0, 1.0])); assert_eq!(Filter::GradientMap { colors: vec![] }.point(c, [0.3; 3]), None, "an empty gradient changes nothing"); + assert!(close(Filter::Posterize { levels: 2.0 }.point(c, [0.2, 0.6, 0.9]).unwrap(), [0.0, 1.0, 1.0])); assert!(close(Filter::Clamp { min: 0.8, max: 0.3 }.point(c, [0.1, 0.5, 0.9]).unwrap(), [0.3, 0.5, 0.8]), "swapped bounds never panic"); + let scan = |position, contrast| Filter::HistogramScan { position, contrast }.point(c, [0.2, 0.5, 0.9]).unwrap(); + assert!(close(scan(0.5, 0.0), [0.2, 0.5, 0.9]), "a full-width ramp at the middle keeps the values"); 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"); @@ -1737,6 +1932,7 @@ mod tests { 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])); assert_eq!(Filter::Invert.point(ChannelKind::NormalMap, [0.5, 0.5, 1.0]), Some([0.5, 0.5, 1.0])); + for f in [Filter::Blur { radius: 1.0 }, Filter::Warp { intensity: 1.0, scale: 1.0, seed: 0 }, Filter::DirectionalBlur { radius: 1.0, angle: 0.0 }] { assert!(f.is_neighbourhood() && f.point(c, [0.5; 3]).is_none()); } @@ -1772,29 +1968,53 @@ mod tests { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false)); assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); - let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); - let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default(), sampling: Default::default() })], ..Mask::new(MaskBackground::Black) }); - assert!(fill_layer.reads_anchor()); + let reader = fill_layer.mask.as_ref().map(|mask| &mask.effects[0].kind); + assert!(reader.is_some_and(|reader| reader.reads(Some(LayerId(9))) && reader.reads(None) && !reader.reads(Some(LayerId(8))))); // A generator with micro detail reads its anchor too let mut generator_layer = Layer::new(LayerId(3), "g", LayerKind::Paint, &[Channel::BaseColor]); let mut generator = Generator::new(GeneratorKind::Dirt); generator.micro = Some(MicroDetail { anchor: LayerId(9), amount: 0.5 }); - assert_eq!(EffectKind::Generator(generator.clone()).anchors_read(), [(LayerId(9), Channel::Height)]); + assert!(EffectKind::Generator(generator.clone()).reads(Some(LayerId(9))) && !EffectKind::Generator(generator.clone()).reads(Some(LayerId(8)))); generator_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); - assert!(generator_layer.reads_anchor()); } + #[test] + fn compare_masks_saved_before_sources_compare_the_mask_with_the_constant_hard() { + let saved = r#"{"Compare":{"op":"GreaterThan","value":0.5,"tolerance":0.1}}"#; + let kind: EffectKind = serde_json::from_str(saved).unwrap(); + let EffectKind::Compare { left, right, channel, hardness, .. } = kind else { panic!("{kind:?}") }; + assert_eq!((left, right, channel, hardness), (CompareSource::ThisMask, CompareSource::Constant, Channel::Height, 1.0)); + assert_eq!(serde_json::to_string(&kind).unwrap(), saved, "an unedited compare saves only its op, value and tolerance"); + let round_trip: EffectKind = serde_json::from_str(&serde_json::to_string(&kind).unwrap()).unwrap(); + assert_eq!(round_trip, kind); + } + + #[test] + fn a_hard_compare_is_the_old_step_and_a_soft_one_ramps() { + // Hardness 1 keeps the strict comparisons compare masks always made + for (left, right) in [(0.4, 0.5), (0.5, 0.5), (0.6, 0.5), (f32::NAN, 0.5)] { + let step = |pass: bool| if pass { 1.0 } else { 0.0 }; + assert_eq!(CompareOp::GreaterThan.mask(left, right, 0.1, 1.0), step(left > right)); + assert_eq!(CompareOp::LesserThan.mask(left, right, 0.1, 1.0), step(left < right)); + assert_eq!(CompareOp::WithinTolerance.mask(left, right, 0.05, 1.0), step((left - right).abs() <= 0.05)); + } + assert!((CompareOp::GreaterThan.mask(0.55, 0.5, 0.1, 0.9) - 0.5).abs() < 1e-5, "halfway up a 0.1 ramp"); + assert_eq!(CompareOp::GreaterThan.mask(0.45, 0.5, 0.1, 0.0), 0.0, "below the edge stays 0 however soft"); + assert_eq!(CompareOp::GreaterThan.mask(0.6, 0.5, 0.1, f32::NAN), 1.0, "a NaN hardness compares hard"); + assert!((CompareOp::WithinTolerance.mask(0.65, 0.5, 0.1, 0.9) - 0.5).abs() < 1e-5, "0.05 past the tolerance"); + } + #[test] fn height_mask_keeps_the_ends_and_follows_height() { let off = HeightMask::default(); diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 1c877b7b..c1fc86f6 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -12,6 +12,9 @@ pub mod bake; pub mod blend; mod block_scales; pub mod channel; +pub mod color_selection; +pub mod compare_source; +pub mod contents_offset; pub mod cook_resolution; pub mod depth_culling; mod env_alignment; @@ -22,6 +25,7 @@ pub mod projector; pub mod randomized_seed; mod saved_decal; mod saved_projection; +pub mod selection_background; mod shadow_mode; pub mod shape_crop; pub mod symmetry_kind; @@ -39,6 +43,9 @@ pub use bake::{ }; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use color_selection::ColorSelection; +pub use compare_source::CompareSource; +pub use contents_offset::ContentsOffset; pub use cook_resolution::CookResolution; pub use depth_culling::DepthCulling; pub use fill_symmetry::FillSymmetry; @@ -54,6 +61,7 @@ pub use project::{ }; pub use projector::Projector; pub use randomized_seed::RandomizedSeed; +pub use selection_background::SelectionBackground; 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 df5aa54a..794a5915 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -641,6 +641,21 @@ impl Project { self.layers.values().find_map(|l| l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).find(|e| e.id == id).map(|e| (l.id, e))) } + /// What reads anchor point `anchor`, bottom to top in its texture set: (layer, the effect reading it, or None for the layer's own fill) + pub fn anchor_readers(&self, anchor: LayerId) -> Vec<(LayerId, Option)> { + let Some((ts, _, _)) = self.effect(anchor).and_then(|(owner, _)| self.locate(owner)) else { return Vec::new() }; + let mut out = Vec::new(); + for layer in self.walk(ts).into_iter().filter_map(|(id, _)| self.layers.get(&id)) { + if let LayerKind::Fill(fill) = &layer.kind + && fill.sources.values().any(|s| s.anchor() == Some(anchor)) + { + out.push((layer.id, None)); + } + let effects = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()); + } + out + } + pub fn effect_mut(&mut self, id: LayerId) -> Option<&mut Effect> { self.layers.values_mut().find_map(|l| { let in_mask = l.mask.as_mut().and_then(|m| m.effects.iter_mut().find(|e| e.id == id)); @@ -712,6 +727,27 @@ impl Project { self.layers.values().filter_map(|l| Some((l.id, l.instance_source()?))).find(|(id, s)| self.render_tree(&[*s]).contains(id)).map(|(id, _)| id) } + /// The Scale and Rotation folder `id` lays on the fills inside it (none for any other layer) + pub fn contents_offset(&self, id: LayerId) -> ContentsOffset { + match self.layers.get(&id).map(|l| &l.kind) { + Some(LayerKind::Group { contents, .. }) => *contents, + _ => ContentsOffset::NONE, + } + } + + /// The Scale and Rotation the folders holding layer `id` lay on its fills, combined from the outermost in + pub fn contents_around(&self, id: LayerId) -> ContentsOffset { + let mut folders = Vec::new(); + let mut at = id; + while folders.len() <= MAX_DEPTH + && let Some((_, Some(parent), _)) = self.locate(at) + { + folders.push(parent); + at = parent; + } + folders.iter().rev().fold(ContentsOffset::NONE, |around, folder| around.then(self.contents_offset(*folder))) + } + /// The layer whose content `id` draws: itself, or an instance's source. pub fn content_layer(&self, id: LayerId) -> Option<&Layer> { let mut l = self.layers.get(&id)?; @@ -762,25 +798,19 @@ mod tests { let b = paint(&mut p, "b"); let b = p.insert_layer(0, b, None, false).unwrap(); let gid = p.alloc_id(); - let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET); + let g = Layer::new(gid, "g", LayerKind::folder(), &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(); } @@ -844,10 +874,15 @@ mod tests { p.insert_layer(0, top, Some(id), false).unwrap(); let json = serde_json::to_string(&p).unwrap(); let back: Project = serde_json::from_str(&json).unwrap(); - assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); + // The mask fill of the layer above reads it + let top = back.layers.values().find(|l| l.name == "y").unwrap(); + let reader = top.mask.as_ref().unwrap().effects[0].id; + assert_eq!(back.anchor_readers(anchor), vec![(top.id, Some(reader))]); + assert!(back.anchor_readers(LayerId(999)).is_empty()); + // Projects saved before content effects existed load with empty stacks let mut v: serde_json::Value = serde_json::from_str(&json).unwrap(); for l in v["layers"].as_object_mut().unwrap().values_mut() { @@ -866,23 +901,49 @@ 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(); + p.insert_layer(1, Layer::new(gid, "g", LayerKind::folder(), &[]), 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()); } + #[test] + fn folder_offsets_load_as_none_from_old_saves_save_only_when_set_and_combine_inward() { + let mut p = project(); + let folder = |p: &mut Project, contents: ContentsOffset| { + Layer::new(p.alloc_id(), "g", LayerKind::Group { children: vec![], collapsed: false, contents, randomized: Vec::new() }, &[]) + }; + let outer = folder(&mut p, ContentsOffset::new(2.0, 30.0)); + let outer = p.insert_layer(0, outer, None, false).unwrap(); + let inner = folder(&mut p, ContentsOffset::new(1.5, -10.0)); + let inner = p.insert_layer(0, inner, Some(outer), true).unwrap(); + let a = paint(&mut p, "a"); + let a = p.insert_layer(0, a, Some(inner), true).unwrap(); + let top = paint(&mut p, "top"); + let top = p.insert_layer(0, top, None, false).unwrap(); + assert_eq!(p.contents_around(a), ContentsOffset { scale: 3.0, rotation: 20.0 }); + assert_eq!(p.contents_around(inner), ContentsOffset::new(2.0, 30.0)); + assert_eq!( + (p.contents_around(outer), p.contents_around(top), p.contents_offset(a)), + (ContentsOffset::NONE, ContentsOffset::NONE, ContentsOffset::NONE) + ); + + // A folder saved before folders had an offset has none, and one without an offset saves as before + let old: LayerKind = serde_json::from_str(r#"{"Group":{"children":[],"collapsed":true}}"#).unwrap(); + assert_eq!(old, LayerKind::Group { children: vec![], collapsed: true, contents: ContentsOffset::NONE, randomized: Vec::new() }); + assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"Group":{"children":[],"collapsed":true}}"#); + let saved = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&saved).unwrap().contents_around(a), p.contents_around(a)); + } + #[test] fn tile_grids_map_mesh_uvs_to_atlas_blocks() { assert_eq!(TileGrid::of(&[]), None); diff --git a/crates/core/src/selection_background.rs b/crates/core/src/selection_background.rs new file mode 100644 index 00000000..1661ecf2 --- /dev/null +++ b/crates/core/src/selection_background.rs @@ -0,0 +1,58 @@ +//! What a color selection gives the parts it does not select + +use serde::{Deserialize, Serialize}; + +/// The value a color selection gives outside its colors; transparent leaves the mask below as it is +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SelectionBackground { + Transparent, + /// What color selections did before the choice existed + #[default] + Black, + White, + Gray, +} + +impl SelectionBackground { + /// Menu order + pub const ALL: [SelectionBackground; 4] = + [SelectionBackground::Transparent, SelectionBackground::Black, SelectionBackground::White, SelectionBackground::Gray]; + + /// Whether it is what selections saved before the choice had (not saved then) + pub fn is_default(&self) -> bool { + *self == SelectionBackground::default() + } + + /// Command id + pub fn id(self) -> &'static str { + match self { + SelectionBackground::Transparent => "transparent", + SelectionBackground::Black => "black", + SelectionBackground::White => "white", + SelectionBackground::Gray => "gray", + } + } + + pub fn from_id(id: &str) -> Option { + SelectionBackground::ALL.into_iter().find(|background| background.id() == id) + } + + pub fn label(self) -> &'static str { + match self { + SelectionBackground::Transparent => "Transparent", + SelectionBackground::Black => "Black", + SelectionBackground::White => "White", + SelectionBackground::Gray => "Gray", + } + } + + /// The gray it gives, none for transparent + pub fn value(self) -> Option { + match self { + SelectionBackground::Transparent => None, + SelectionBackground::Black => Some(0.0), + SelectionBackground::White => Some(1.0), + SelectionBackground::Gray => Some(0.5), + } + } +} diff --git a/crates/engine/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs new file mode 100644 index 00000000..ee2e8404 --- /dev/null +++ b/crates/engine/src/add_mask_cmds.rs @@ -0,0 +1,65 @@ +//! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection + +use serde_json::Value; +use texturecraft_core::{BlendMode, EffectKind, Sampling, Source}; +use texturecraft_paint::alphas; + +use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect}; +use crate::{Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![ + cmd!( + "mask.add.bitmap", + "Add bitmap mask", + ["Layers", "Mask"], + None, + "{layer?, image: image resource name | alpha: library alpha id or name (its picture becomes the image resource alpha_.png), projection? (see effect.add.fill)} → {effect} — a mask fill reading the image's gray, in the layer's mask (a new black one if it has none); selected", + has_layer, + add_bitmap + ), + cmd!( + "mask.add.heightCombination", + "Add mask with height combination", + ["Layers", "Mask"], + None, + "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected", + has_layer, + |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(())) + ), + cmd!( + "effect.add.colorSelection", + "Add color selection", + ["Layers", "Effects"], + None, + "{layer?, color?: a first ID color as [r,g,b] linear or \"#rrggbb\" sRGB (default: none), tolerance?} → {effect} — in the layer's mask (a new black one if it has none; colour selections go on masks only); selected", + has_layer, + |s, p| push_effect_as(s, &mask_target(p), color_selection("effect.add.colorSelection", p)?, BlendMode::Normal, "Add color selection") + ), + ] +} + +/// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource +fn add_bitmap(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "mask.add.bitmap"; + let (name, library) = match (strp(p, "image"), strp(p, "alpha")) { + (Some(_), Some(_)) => return Err(bad(CMD, "give `image` or `alpha`, not both")), + (Some(image), None) => { + if !s.images.contains_key(image) { + return Err(bad(CMD, format!("no image resource `{image}` (import it first)"))); + } + + (image.to_owned(), None) + } + (None, Some(alpha)) => { + let alpha = alphas::find(alpha).ok_or_else(|| bad(CMD, format!("unknown alpha `{alpha}`")))?; + (crate::fill_alpha::resource_name(alpha), Some(alpha)) + } + (None, None) => return Err(bad(CMD, "`image` or `alpha` is required")), + }; + let projection = crate::layer_cmds::projection_from(p, CMD, None, || crate::warp_cmds::fitted_frame(&s.mesh))?; + let kind = EffectKind::Fill { source: Source::Image { name, normal_format: Default::default() }, projection, sampling: Sampling::default() }; + let add_library = |s: &mut Session| library.map_or(Ok(()), |alpha| s.add_library_alpha(alpha).map(|_| ())); + push_own_mask_effect(s, p, kind, "Add bitmap mask", add_library) +} diff --git a/crates/engine/src/color_selection_cmds.rs b/crates/engine/src/color_selection_cmds.rs index 2b9f9eaf..7e7e53be 100644 --- a/crates/engine/src/color_selection_cmds.rs +++ b/crates/engine/src/color_selection_cmds.rs @@ -1,11 +1,11 @@ //! Color selection effects: the ID colors they select, picked from the ID mesh map use serde_json::{Value, json}; -use texturecraft_core::{BakedMap, EffectKind, LayerId}; +use texturecraft_core::{BakedMap, ColorSelection, EffectKind, LayerId, SelectionBackground}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::surface_at; -use crate::commands::{CommandSpec, bad, f32p, has_layer}; +use crate::commands::{CommandSpec, bad, f32p, has_layer, strp}; use crate::mask_cmds::effect_id; use crate::tool_cmds::viewport_of; use crate::{Result, Session, cmd}; @@ -25,23 +25,45 @@ pub fn specs() -> Vec { )] } -/// Applies `effect.set`'s `colors` and `tolerance` params to a color selection -pub(crate) fn apply_params(params: &Value, colors: &mut Vec<[f32; 3]>, tolerance: &mut f32) -> Result<()> { +/// Applies `effect.set`'s color selection params; `id_map` is the checked `idMap` ([`id_map_param`]) +pub(crate) fn apply_params(params: &Value, selection: &mut ColorSelection, id_map: Option>) -> Result<()> { + const CMD: &str = "effect.set"; if let Some(list) = params.get("colors") { - *colors = colors_param(list)?; + selection.colors = colors_param(list)?; } - if let Some(value) = f32p(params, "tolerance") { - *tolerance = value.clamp(0.0, 1.0); + for (key, value) in [("tolerance", &mut selection.tolerance), ("output", &mut selection.output), ("hardness", &mut selection.hardness)] { + if let Some(given) = f32p(params, key) { + *value = given.clamp(0.0, 1.0); + } + } + if let Some(id) = strp(params, "background") { + selection.background = + SelectionBackground::from_id(id).ok_or_else(|| bad(CMD, format!("unknown background \"{id}\": transparent, black, white or gray")))?; + } + if let Some(id_map) = id_map { + selection.id_map = id_map; } Ok(()) } -/// A non-empty `[[r, g, b], ...]` list of finite values, clamped to 0..1 +/// `effect.set`'s `idMap`: absent, null (the ID mesh map) or the name of an image resource +pub(crate) fn id_map_param(session: &Session, params: &Value) -> Result>> { + const CMD: &str = "effect.set"; + match params.get("idMap") { + None => Ok(None), + Some(Value::Null) => Ok(Some(None)), + Some(Value::String(name)) if session.images.contains_key(name) => Ok(Some(Some(name.clone()))), + Some(Value::String(name)) => Err(bad(CMD, format!("no image resource \"{name}\": import it first"))), + Some(_) => Err(bad(CMD, "`idMap` must be an image resource name or null")), + } +} + +/// A `[[r, g, b], ...]` list (empty selects nothing) of finite values, clamped to 0..1 fn colors_param(list: &Value) -> Result> { const CMD: &str = "effect.set"; let items = list.as_array().ok_or_else(|| bad(CMD, "`colors` must be a list of [r, g, b]"))?; - if items.is_empty() || items.len() > MAX_SELECTED_COLORS { - return Err(bad(CMD, format!("`colors` needs 1 to {MAX_SELECTED_COLORS} colors"))); + if items.len() > MAX_SELECTED_COLORS { + return Err(bad(CMD, format!("`colors` holds at most {MAX_SELECTED_COLORS} colors"))); } items @@ -57,9 +79,9 @@ fn colors_param(list: &Value) -> Result> { fn pick(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.colorSelection.pick"; let effect = effect_id(session, params, CMD)?; - let (owner, color_count) = match session.doc.project.effect(effect) { + let (owner, color_count, id_map) = match session.doc.project.effect(effect) { Some((owner, found)) => match &found.kind { - EffectKind::ColorSelection { colors, .. } => (owner, colors.len()), + EffectKind::ColorSelection(selection) => (owner, selection.colors.len(), selection.id_map.clone()), other => return Err(bad(CMD, format!("{} is not a color selection", other.name()))), }, None => return Err(bad(CMD, format!("no effect {}", effect.0))), @@ -76,13 +98,13 @@ fn pick(session: &mut Session, params: &Value) -> Result { None => None, }; - let color = id_color_at(session, params, owner)?; + let color = id_color_at(session, params, owner, id_map.as_deref())?; session.edit("Pick ID color", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; - if let EffectKind::ColorSelection { colors, .. } = &mut edited.kind { - match index.and_then(|index| colors.get_mut(index)) { + if let EffectKind::ColorSelection(selection) = &mut edited.kind { + match index.and_then(|index| selection.colors.get_mut(index)) { Some(slot) => *slot = color, - None => colors.push(color), + None => selection.colors.push(color), } } Ok(()) @@ -90,15 +112,19 @@ fn pick(session: &mut Session, params: &Value) -> Result { Ok(json!({ "color": color, "index": index.unwrap_or(color_count) })) } -/// The ID map color of the texel a color selection on `owner` reads at the picked point -fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32; 3]> { +/// The ID map color of the texel a color selection on `owner` reading `id_map` (none: the ID mesh map) reads at the picked point +fn id_color_at(session: &Session, params: &Value, owner: LayerId, id_map: Option<&str>) -> Result<[f32; 3]> { const CMD: &str = "effect.colorSelection.pick"; let (set_index, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the effect's layer is not in a texture set"))?; let set = session.doc.project.texture_set(set_index)?; let baked = session.baked(set_index).filter(|baked| baked.maps.contains_key(&BakedMap::Id)); - let Some(baked) = baked else { - return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + let image = match id_map { + Some(name) => Some(session.images.get(name).ok_or_else(|| bad(CMD, format!("the ID map image \"{name}\" is gone: choose another")))?), + None => None, }; + if image.is_none() && baked.is_none() { + return Err(bad(CMD, format!("texture set \"{}\" has no ID map: bake one, or set one with textureSet.meshMap.set", set.name))); + } let uv = match params.get("uv") { Some(uv) => uv_param(uv)?, @@ -122,7 +148,17 @@ fn id_color_at(session: &Session, params: &Value, owner: LayerId) -> Result<[f32 if !texel.iter().zip([size.0, size.1]).all(|(position, extent)| (0.0..extent as f32).contains(position)) { return Err(bad(CMD, "that point is outside the texture set's UV space")); } - baked.sample_working(BakedMap::Id, texel[0] as u32, texel[1] as u32, size, &set.block_scales()).ok_or_else(|| bad(CMD, "no ID color there")) + let (x, y) = (texel[0] as u32, texel[1] as u32); + let color = match (image, baked) { + (Some(image), _) => { + // The texel's centre, as the mask reads it + let [red, green, blue, _] = image.sample_nearest((x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32); + Some([red, green, blue]) + } + (None, Some(baked)) => baked.sample_working(BakedMap::Id, x, y, size, &set.block_scales()), + (None, None) => None, + }; + color.ok_or_else(|| bad(CMD, "no ID color there")) } /// The UV and mesh material under viewport pixel `screen`; hidden texture sets don't stop the ray diff --git a/crates/engine/src/effect_blending_cmds.rs b/crates/engine/src/effect_blending_cmds.rs new file mode 100644 index 00000000..2d46fde0 --- /dev/null +++ b/crates/engine/src/effect_blending_cmds.rs @@ -0,0 +1,203 @@ +//! An effect's blending per channel: the Blending options of an effect row (one channel's blending on every channel, copy and paste) + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_core::{BlendMode, Channel, ChannelBlend, Effect, LayerId, Project}; + +use crate::commands::{CommandSpec, bad, channel_param, has_layer}; +use crate::mask_cmds::effect_id; +use crate::session::StackTarget; +use crate::{Result, Session, cmd}; + +/// The undo step of every Blending options command +const UNDO_LABEL: &str = "Blending options"; + +/// What a copy of channel blending holds: the blending shared by the channels, and the channels that blend apart +pub type CopiedBlending = (ChannelBlend, BTreeMap); + +pub fn specs() -> Vec { + vec![ + cmd!( + "effect.blending.modeToEveryChannel", + "Use this blend mode on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose blend mode every channel takes (default baseColor)}", + content_effect_selected, + mode_to_every_channel + ), + cmd!( + "effect.blending.opacityToEveryChannel", + "Use this opacity on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose opacity every channel takes (default baseColor)}", + content_effect_selected, + opacity_to_every_channel + ), + cmd!( + "effect.blending.bothToEveryChannel", + "Use both on every channel", + [], + None, + "{effect?: the selected content effect, channel?: the channel whose blend mode and opacity every channel takes (default baseColor)}", + content_effect_selected, + both_to_every_channel + ), + cmd!( + "effect.blending.copy", + "Copy channel blending", + [], + None, + "{effect?: the selected effect} — every channel's blend mode and opacity", + blending_effect_selected, + copy + ), + cmd!( + "effect.blending.paste", + "Paste channel blending", + [], + None, + "{effect?: the selected effect} — the copied blend modes and opacities (a mask effect takes the shared ones)", + can_paste, + paste + ), + ] +} + +/// Sets `effect`'s blend `mode` and `opacity` where given: on `channel` alone, or on every channel (`None`, a mask effect's only one); channels left blending like the others stop blending apart +pub fn set_blending(effect: &mut Effect, channel: Option, mode: Option, opacity: Option) { + let edit = |blend: &mut ChannelBlend| { + if let Some(mode) = mode { + blend.mode = mode; + } + if let Some(opacity) = opacity { + blend.opacity = opacity.clamp(0.0, 1.0); + } + }; + match channel { + Some(channel) => { + let mut blend = effect.blend_of(Some(channel)); + edit(&mut blend); + effect.channel_blends.insert(channel, blend); + } + None => { + let mut shared = effect.blend_of(None); + edit(&mut shared); + effect.blend = shared.mode; + effect.opacity = shared.opacity; + effect.channel_blends.values_mut().for_each(edit); + } + } + let shared = effect.blend_of(None); + effect.channel_blends.retain(|_, blend| *blend != shared); +} + +/// Whether effect `id` is in a layer's mask (it then blends one channel) +pub fn on_mask(project: &Project, id: LayerId) -> bool { + project.layers.values().any(|layer| layer.mask.as_ref().is_some_and(|mask| mask.effects.iter().any(|effect| effect.id == id))) +} + +/// Whether the selected effect has blending (and with `content_only`, is a content effect); with no effect selected, a command names its effect +fn selected_blending_effect(s: &Session, content_only: bool) -> std::result::Result<(), String> { + let StackTarget::Effect(id) = s.target else { return has_layer(s) }; + let Some((_, effect)) = s.doc.project.effect(id) else { return has_layer(s) }; + blending_refusal(&s.doc.project, id, effect, content_only) +} + +/// Why effect `id` (`effect`) can't take a Blending options command: it has no blending or, with `content_only`, it is a mask effect +fn blending_refusal(project: &Project, id: LayerId, effect: &Effect, content_only: bool) -> std::result::Result<(), String> { + if !effect.kind.blends() { + return Err(format!("{} has no blending", effect.kind.name().to_ascii_lowercase())); + } + + if content_only && on_mask(project, id) { + return Err("a mask effect blends one channel".into()); + } + + Ok(()) +} + +fn content_effect_selected(s: &Session) -> std::result::Result<(), String> { + selected_blending_effect(s, true) +} + +fn blending_effect_selected(s: &Session) -> std::result::Result<(), String> { + selected_blending_effect(s, false) +} + +fn can_paste(s: &Session) -> std::result::Result<(), String> { + if s.blending_clipboard.is_none() { + return Err("no channel blending is copied".into()); + } + + blending_effect_selected(s) +} + +/// Effect `effect` (or the selected one) of command `cmd`, checked to have blending and, with `content_only`, to be a content effect +fn blending_effect(s: &Session, p: &Value, cmd: &str, content_only: bool) -> Result { + let id = effect_id(s, p, cmd)?; + let (_, effect) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + blending_refusal(&s.doc.project, id, effect, content_only).map_err(|refusal| bad(cmd, refusal))?; + Ok(id) +} + +/// Every channel of the content effect in `p` takes what `copied` picks (a blend mode, an opacity or both) from the `channel` in `p` +fn to_every_channel(s: &mut Session, p: &Value, cmd: &str, copied: fn(ChannelBlend) -> (Option, Option)) -> Result { + let id = blending_effect(s, p, cmd, true)?; + let channel = channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor); + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + let mut changed = current.clone(); + let (mode, opacity) = copied(changed.blend_of(Some(channel))); + set_blending(&mut changed, None, mode, opacity); + replace_blending(s, id, cmd, changed) +} + +/// Effect `id` replaced by `changed`, in one undo step; no step when nothing changes +fn replace_blending(s: &mut Session, id: LayerId, cmd: &str, changed: Effect) -> Result { + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + if *current == changed { + return Ok(Value::Null); + } + + s.edit(UNDO_LABEL, |s| { + let effect = s.doc.project.effect_mut(id).ok_or_else(|| bad(cmd, format!("no effect {}", id.0)))?; + *effect = changed; + Ok(()) + })?; + Ok(Value::Null) +} + +fn mode_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.modeToEveryChannel", |source| (Some(source.mode), None)) +} + +fn opacity_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.opacityToEveryChannel", |source| (None, Some(source.opacity))) +} + +fn both_to_every_channel(s: &mut Session, p: &Value) -> Result { + to_every_channel(s, p, "effect.blending.bothToEveryChannel", |source| (Some(source.mode), Some(source.opacity))) +} + +fn copy(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.blending.copy"; + let id = blending_effect(s, p, CMD, false)?; + let (_, effect) = s.doc.project.effect(id).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?; + s.blending_clipboard = Some((effect.blend_of(None), effect.channel_blends.clone())); + Ok(json!({ "copied": id.0 })) +} + +fn paste(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "effect.blending.paste"; + let (shared, channels) = s.blending_clipboard.clone().ok_or_else(|| bad(CMD, "no channel blending is copied"))?; + let id = blending_effect(s, p, CMD, false)?; + let mask = on_mask(&s.doc.project, id); + let (_, current) = s.doc.project.effect(id).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?; + let mut changed = current.clone(); + changed.blend = shared.mode; + changed.opacity = shared.opacity; + changed.channel_blends = if mask { BTreeMap::new() } else { channels }; + replace_blending(s, id, CMD, changed) +} diff --git a/crates/engine/src/fill_material_cmds.rs b/crates/engine/src/fill_material_cmds.rs index 77d538b1..c4141934 100644 --- a/crates/engine/src/fill_material_cmds.rs +++ b/crates/engine/src/fill_material_cmds.rs @@ -46,6 +46,7 @@ fn set_material(s: &mut Session, p: &Value) -> Result { // 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)), FillTarget::Layer(_) => edited.sources.clear(), + FillTarget::Layer(_) | FillTarget::Mask(_) => edited.sources.clear(), } Ok(()) })?; @@ -101,6 +102,7 @@ fn holds(s: &Session, target: FillTarget, set: usize, material: Option<&SmartMat Some(EffectKind::Material(fill)) => (fill, None), _ => return Err(bad(CMD, "not a content fill effect")), }, + FillTarget::Mask(_) => return Err(bad(CMD, "a mask fill has one grayscale source and no channels or material")), }; if fill.material.as_deref() != material.map(|found| found.id) { return Ok(false); @@ -125,6 +127,9 @@ fn target_set(s: &Session, target: FillTarget) -> Result { let owner = match target { FillTarget::Layer(id) => id, FillTarget::Effect(id) => s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))?, + FillTarget::Effect(id) | FillTarget::Mask(id) => { + s.doc.project.effect(id).map(|(owner, _)| owner).ok_or_else(|| bad(CMD, format!("no effect {}", id.0)))? + } }; s.doc.project.locate(owner).map(|(set, ..)| set).ok_or_else(|| bad(CMD, format!("layer {} is in no texture set", owner.0))) } diff --git a/crates/engine/src/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index 6d50a4c4..5c1d4c6d 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -14,6 +14,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", + "{layer? | effect?: content or mask fill effect id} — the Fill section back to a new fill's in one undo step: the same projection kind with its defaults (tiling 1, no offset or rotation, a planar or warp frame stays where it is placed, a warp's corners unpulled), the default filtering, wrap and scale mode (symmetry, sources and material stay)", has_layer, reset_projection )] diff --git a/crates/engine/src/id_mask_view.rs b/crates/engine/src/id_mask_view.rs new file mode 100644 index 00000000..d7d58e85 --- /dev/null +++ b/crates/engine/src/id_mask_view.rs @@ -0,0 +1,43 @@ +//! The view a color selection picks from while its ID Mask is an image chosen by hand: that image laid on its texture set as the mask reads it + +use std::sync::Arc; + +use texturecraft_compose::ImageRes; +use texturecraft_core::{EffectKind, LayerId}; + +use crate::Session; + +impl Session { + /// The texture set of color selection `effect` and the image it reads as its ID mask (None for another effect, the ID mesh map or a missing image) + pub fn id_mask_image(&self, effect: LayerId) -> Option<(usize, &Arc)> { + let (owner, found) = self.doc.project.effect(effect)?; + let EffectKind::ColorSelection(selection) = &found.kind else { return None }; + let image = self.images.get(selection.id_map.as_deref()?)?; + let (texture_set, _, _) = self.doc.project.locate(owner)?; + Some((texture_set, image)) + } + + /// RGBA8 of [`Session::id_mask_image`] on its texture set at `size²`, the stored values unconverted like the ID mesh map's view + pub fn id_mask_view_rgba(&self, effect: LayerId, size: u32) -> Option> { + let (texture_set, image) = self.id_mask_image(effect)?; + let (width, height) = self.doc.project.texture_sets.get(texture_set)?.size(); + let size = size.max(1); + + // Each view pixel shows the color its texture set texel reads, sampled at that texel's centre as the mask and a pick do + let texel_centre = |pixel: u32, extent: u32| { + let extent = extent.max(1); + let texel = ((pixel as f32 + 0.5) / size as f32 * extent as f32).floor().min((extent - 1) as f32); + (texel + 0.5) / extent as f32 + }; + let mut rgba = Vec::with_capacity(size as usize * size as usize * 4); + for y in 0..size { + let v = texel_centre(y, height); + for x in 0..size { + let color = image.sample_nearest(texel_centre(x, width), v); + rgba.extend(color[..3].iter().map(|value| (value.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); + rgba.push(u8::MAX); + } + } + Some(rgba) + } +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3f16e843..87ccb68e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -69,15 +69,39 @@ fn placement_json(projection: &Projection, sampling: &Sampling, out: &mut Value) /// A mask or content (`content`) effect fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity }); + if !effect.channel_blends.is_empty() { + let channels = + effect.channel_blends.iter().map(|(channel, blend)| (channel.id().to_string(), json!({ "blend": blend.mode.label(), "opacity": blend.opacity }))); + out["channelBlends"] = Value::Object(channels.collect()); + } let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count()); let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::(); match &effect.kind { EffectKind::Generator(generator) => out["generator"] = generator_json(generator), - EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]), - EffectKind::ColorSelection { colors, tolerance } => { - out["colors"] = json!(colors); - out["tolerance"] = json!(tolerance); + EffectKind::Levels(levels) => { + out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]); + out["affects"] = levels.affects.map_or(json!("all"), |channel| json!(channel.id())); + out["clamp"] = json!(levels.clamp); + } + EffectKind::ColorSelection(selection) => { + out["colors"] = json!(selection.colors); + out["tolerance"] = json!(selection.tolerance); + out["output"] = json!(selection.output); + out["hardness"] = json!(selection.hardness); + out["background"] = json!(selection.background.id()); + out["idMap"] = json!(selection.id_map); + } + EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { + out["compare"] = json!({ + "left": left.id(), + "op": op.id(), + "right": right.id(), + "compareChannel": channel.id(), + "value": value, + "tolerance": tolerance, + "hardness": hardness, + }); } EffectKind::Path(paths) => { out["paths"] = json!( @@ -100,7 +124,15 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { _ => {} } } - _ => {} + EffectKind::Anchor => { + let readers = session + .doc + .project + .anchor_readers(effect.id) + .into_iter() + .map(|(layer, reader)| json!({ "layer": layer.0, "effect": reader.map(|reader| reader.0) })); + out["references"] = Value::Array(readers.collect()); + } } out } @@ -167,6 +199,11 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value { if !l.content_effects.is_empty() { v["contentEffects"] = json!(l.content_effects.iter().map(|e| effect_json(s, e, true)).collect::>()); } + if let LayerKind::Group { contents, .. } = &l.kind + && !contents.is_none() + { + v["contents"] = json!({ "scale": contents.scale, "rotation": contents.rotation }); + } if depth < texturecraft_core::project::MAX_DEPTH { let kids: Vec = l.children().iter().rev().filter_map(|c| s.doc.project.layers.get(c)).map(|c| layer_json(s, c, depth + 1)).collect(); if l.is_group() { diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index b8b2ae93..dbdac206 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -7,6 +7,7 @@ use texturecraft_core::{ Procedural, ProceduralKind, Project, Projection, Projector, Sampling, ScaleMode, ShapeCrop, Source, SymmetryKind, UvTransform, UvWrap, }; use texturecraft_paint::alphas; +use texturecraft_paint::alphas::{self, LibraryAlpha}; use crate::commands::{ CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p, @@ -35,6 +36,9 @@ const MAX_CORNER_REACH: f32 = 100.0; /// The largest Projection Depth, in lengths of the frame's longer side pub(crate) const MAX_PROJECTION_DEPTH: f32 = 100.0; +/// The `layer.fill.set` keys a one-source grayscale fill (a mask fill or a filter's image input) has no use for +const GRAY_REFUSED_KEYS: [&str; 4] = ["channel", "enabled", "solo", "normalFormat"]; + pub fn specs() -> Vec { vec![ cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint), @@ -128,6 +132,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", + "{layer? | effect?: content or mask fill effect id, projection?: uvTile (Fill (Match per UV Tile))|uv|triplanar|planar|spherical|cylindrical|warp (default: the current one; a new warp's frame sits around the mesh, seen from the front), tiling?: number | [u, v] (UV transformations, every projection; uv: same as scale), rotation?: degrees (UV transformations), uvOffset?: [u, v] (UV transformations of a 3D projection), scale?: number | [u, v] (uv: the tiling; 3D projections but warp: one number), offset?: [u, v] (uv) | [x, y, z] (3D projections but warp; a warp is placed by its frame with layer.decal.set, and refuses either), projectorRotation?: [x, y, z] degrees, projectorScale?: number | [x, y, z] (3D projection settings; a negative axis mirrors it), shapeCrop?: cropped|extendsOutside (3D projections), backfaceCulling?: bool, backfaceAngle?: degrees, backfaceHardness?: 0..1 (planar, cylindrical), depthCulling?: bool, depthCullingHardness?: 0..1 (planar, warp; surfaces hidden from the projector behind others get none of it; new planar and warp projections start with it on at 0.75), sharpness?: 1..64 (triplanar), warpCorners?: [[x, y] × 4] (warp: top left, top right, bottom right, bottom left, across and up in frame sizes from its centre; unpulled = ±0.5), projectionDepth?: lengths of the frame's longer side it reaches in front of and behind it when cropped (warp), angle?: 1..360 degrees one repeat spans (cylindrical), axis?: 0|1|2 (planar, cylindrical), filtering?: bilinearHq|bilinearSharp|nearest (how images are read), wrap?: repeat|repeatHorizontally|repeatVertically|none (past the 0..1 tile; not tri-planar), symmetry?: bool (copies of a 3D projection; UV projections have none), symmetryType?: mirror|radial, symmetryAxis?: 0|1|2 or x|y|z (the mirror plane's normal or the turning axis), flipCopy?: [u, v] (turn the copies' images over), axisPosition?: number | [x, y, z] (where the plane or axis passes, -1..1 mesh radii from the mesh's centre), symmetryCount?: 2..64 (radial copies, the original included), angleSpan?: 1..360 degrees (radial copies spread over it; 360 spaces them evenly)} — what is not given keeps its value", has_layer, fill_projection ), @@ -191,11 +196,8 @@ fn add_group(s: &mut Session, p: &Value) -> Result { let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Folder")); let id = s.edit("Add folder", |s| { let id = s.doc.project.alloc_id(); - let mut l = Layer::new(id, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels_of(s)); - for b in l.channels.values_mut() { - b.mode = BlendMode::Passthrough; - } - insert_selected(s, l) + let channels = channels_of(s); + insert_selected(s, new_folder(id, name, &channels)) })?; Ok(json!({ "layer": id.0 })) } @@ -258,23 +260,28 @@ fn duplicate(s: &mut Session, p: &Value) -> Result { fn group(s: &mut Session, p: &Value) -> Result { let ids = batch_param(s, "layer.group", p, true)?; - let g = s.edit("Group layers", |s| { + let folder = s.edit("Group layers", |s| { // The folder takes the top layer's place and parent; the others follow it in, in stack order let id = ids.first().copied().ok_or_else(|| bad("layer.group", "no layer to group"))?; let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; - let gid = s.doc.project.alloc_id(); + let folder = s.doc.project.alloc_id(); let name = s.doc.project.next_layer_name(ts, "Folder"); let channels = s.doc.project.texture_set(ts)?.channel_list(); - let mut gl = Layer::new(gid, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); - for b in gl.channels.values_mut() { - b.mode = BlendMode::Passthrough; - } - s.doc.project.insert_layer(ts, gl, Some(id), false)?; - move_stacked(&mut s.doc.project, &ids, Some(gid), true)?; - s.select_one(ts, gid); - Ok(gid) + s.doc.project.insert_layer(ts, new_folder(folder, name, &channels), Some(id), false)?; + move_stacked(&mut s.doc.project, &ids, Some(folder), true)?; + s.select_one(ts, folder); + Ok(folder) })?; - Ok(json!({ "layer": g.0 })) + Ok(json!({ "layer": folder.0 })) +} + +/// An empty folder `id` whose channels pass the blending of its contents through +fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { + let mut folder = Layer::new(id, name, LayerKind::folder(), channels); + for blend in folder.channels.values_mut() { + blend.mode = BlendMode::Passthrough; + } + folder } fn select(s: &mut Session, p: &Value) -> Result { @@ -518,11 +525,14 @@ pub(crate) fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result match s.doc.project.effect(effect).map(|(_, found)| &found.kind) { Some(EffectKind::Material(_)) => Ok(FillTarget::Effect(effect)), _ => Err(bad(cmd, format!("{} is not a content fill effect", effect.0))), + Some(EffectKind::Fill { .. }) => Ok(FillTarget::Mask(effect)), + _ => Err(bad(cmd, format!("{} is not a fill effect", effect.0))), }, None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)), } } +/// The material of the fill at `target`; a mask fill has none pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { match target { FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind { @@ -533,17 +543,35 @@ pub(crate) fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> Some(EffectKind::Material(f)) => Ok(f), _ => Err(EngineError::Other("not a content fill effect".into())), }, + FillTarget::Mask(_) => Err(EngineError::Other("a mask fill has one grayscale source and no channels or material".into())), } } /// How the fill at `target` is projected and sampled: every fill has both pub(crate) fn placement_mut(s: &mut Session, target: FillTarget) -> Result<(&mut Projection, &mut Sampling)> { + if let FillTarget::Mask(effect) = target { + return match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { + Some(EffectKind::Fill { projection, sampling, .. }) => Ok((projection, sampling)), + _ => Err(EngineError::Other("not a mask fill effect".into())), + }; + } let fill = fill_mut(s, target)?; Ok((&mut fill.projection, &mut fill.sampling)) } +/// The grayscale source of the mask fill effect `effect` +fn mask_source_mut(s: &mut Session, effect: LayerId) -> Result<&mut Source> { + match s.doc.project.effect_mut(effect).map(|found| &mut found.kind) { + Some(EffectKind::Fill { source, .. }) => Ok(source), + _ => Err(EngineError::Other("not a mask fill effect".into())), + } +} + fn fill_set(session: &mut Session, params: &Value) -> Result { let target = fill_target(session, params, FILL_SET)?; + if let FillTarget::Mask(effect) = target { + return mask_fill_set(session, params, effect); + } let channel = channel_param(FILL_SET, params, "channel")?.ok_or_else(|| bad(FILL_SET, "`channel` is required"))?; @@ -600,6 +628,7 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { let source = with_ramp(channel, current, source, colors)?; match target { + FillTarget::Mask(_) => return Err(bad(FILL_SET, "a mask fill has no channels")), // A fill effect's channel is on while it has a source FillTarget::Effect(_) if enabled == Some(false) => { fill.sources.remove(&channel); @@ -634,6 +663,81 @@ fn fill_set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// `layer.fill.set` on mask fill effect `effect`: its one grayscale source (no `channel`, `enabled`, `solo` or `normalFormat`) +fn mask_fill_set(s: &mut Session, p: &Value, effect: LayerId) -> Result { + refuse_gray_keys(p, "a mask fill")?; + + let current = mask_source_mut(s, effect)?.clone(); + let (source, library_alpha) = gray_source(s, p, effect, current.clone())?; + + // Setting what the fill already reads adds no undo step + if source == current && library_alpha_present(s, library_alpha) { + return Ok(Value::Null); + } + + s.edit("Set fill", |s| { + if let Some(alpha) = library_alpha { + s.add_library_alpha(alpha)?; + } + *mask_source_mut(s, effect)? = source; + Ok(()) + })?; + Ok(Value::Null) +} + +/// Refuses the [`GRAY_REFUSED_KEYS`] for `subject`, a fill with one grayscale source +fn refuse_gray_keys(p: &Value, subject: &str) -> Result<()> { + if GRAY_REFUSED_KEYS.iter().any(|key| p.get(key).is_some()) { + let keys = GRAY_REFUSED_KEYS.map(|key| format!("`{key}`")).join(", "); + return Err(bad(FILL_SET, format!("{subject} has one grayscale source: leave out {keys}"))); + } + + Ok(()) +} + +/// Whether the project already holds `library_alpha`'s image (true when there is none to add) +fn library_alpha_present(s: &Session, library_alpha: Option<&LibraryAlpha>) -> bool { + library_alpha.is_none_or(|alpha| s.doc.resources.contains_key(&crate::fill_alpha::resource_name(alpha))) +} + +/// The grayscale source `p` asks for in place of `current` (read by a mask or filter effect `effect`), and the library alpha it needs added +fn gray_source(s: &Session, p: &Value, effect: LayerId, current: Source) -> Result<(Source, Option<&'static LibraryAlpha>)> { + let low = color_param(FILL_SET, p, "low")?; + let high = color_param(FILL_SET, p, "high")?; + let color = color_param(FILL_SET, p, "color")?; + let value = color_param(FILL_SET, p, "value")?; + if let Some(kind) = strp(p, "procedural") { + let kind = ProceduralKind::parse(kind).ok_or_else(|| bad(FILL_SET, format!("unknown procedural `{kind}`")))?; + Ok((procedural_from(p, kind, Some(¤t), [low, high])?, None)) + } else if let Some(gray) = color.or(value) { + Ok((Source::Uniform(gray.map(|component| component.clamp(0.0, 1.0))), None)) + } else if let Some(name) = strp(p, "image") { + Ok((Source::image(name.to_string()), None)) + } else if let Some(name) = strp(p, "alpha") { + let alpha = alphas::find(name).ok_or_else(|| bad(FILL_SET, format!("unknown alpha `{name}`")))?; + Ok((Source::image(crate::fill_alpha::resource_name(alpha)), Some(alpha))) + } else if let Some(anchor) = u64p(p, "anchor") { + let reader = s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(FILL_SET, "the effect is not in a layer"))?; + + // A gray reads one channel of the anchor's stack: the one it read, else Height + let kept = match current { + Source::Anchor { channel, .. } => channel, + _ => Channel::Height, + }; + let channel = channel_param(FILL_SET, p, "anchorChannel")?.unwrap_or(kept); + Ok((crate::mask_cmds::anchor_source(s, FILL_SET, reader, LayerId(anchor), channel)?, None)) + } else if crate::procedural_params::has_pattern_settings(p) { + // Pattern settings alone edit the current pattern + let Source::Procedural { pattern, .. } = ¤t else { + return Err(bad(FILL_SET, "the source has no pattern: give `procedural` with its settings")); + }; + + Ok((procedural_from(p, pattern.kind, Some(¤t), [None, None])?, None)) + } else { + Err(bad(FILL_SET, "give `value`, `procedural`, `image`, `alpha` or `anchor`")) + } +} + /// The procedural source `params` ask for with `low`/`high` already parsed: a pattern of the same kind as `current` keeps what `params` do not give; another kind starts from its defaults fn procedural_from(params: &Value, kind: ProceduralKind, current: Option<&Source>, [low, high]: [Option<[f32; 3]>; 2]) -> Result { let (mut pattern, current_low, current_high) = match current { @@ -680,7 +784,7 @@ fn fill_source_from( if let Some(anchor) = u64p(params, "anchor") { let reader = match target { FillTarget::Layer(id) => Some(id), - FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), + FillTarget::Effect(effect) | FillTarget::Mask(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), }; let reader = reader.ok_or_else(|| bad(FILL_SET, "the fill is not in a layer"))?; let anchor_channel = channel_param(FILL_SET, params, "anchorChannel")?.unwrap_or(channel); diff --git a/crates/engine/src/layer_cmds/fill_target.rs b/crates/engine/src/layer_cmds/fill_target.rs deleted file mode 100644 index a92e52ec..00000000 --- a/crates/engine/src/layer_cmds/fill_target.rs +++ /dev/null @@ -1,9 +0,0 @@ -use texturecraft_core::LayerId; - -/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's -/// (`effect`). -#[derive(Clone, Copy)] -pub(crate) enum FillTarget { - Layer(LayerId), - Effect(LayerId), -} diff --git a/crates/engine/src/layer_selection.rs b/crates/engine/src/layer_selection.rs index e4012afc..e766fe0e 100644 --- a/crates/engine/src/layer_selection.rs +++ b/crates/engine/src/layer_selection.rs @@ -105,7 +105,7 @@ fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: us for id in list.iter().rev() { let Some(layer) = project.layers.get(id) else { continue }; rows.push(*id); - if let LayerKind::Group { children, collapsed } = &layer.kind + if let LayerKind::Group { children, collapsed, .. } = &layer.kind && !(expanded_only && *collapsed) { push_rows(project, children, expanded_only, depth + 1, rows); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a8173320..53c87e71 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -8,6 +8,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod add_mask_cmds; pub mod bake; pub mod bake_preview; pub mod brush_preset_cmds; @@ -15,6 +16,7 @@ pub mod camera_cmds; pub mod color_selection_cmds; pub mod commands; pub mod decal_cmds; +pub mod effect_blending_cmds; pub mod effect_clipboard; pub mod file_cmds; pub mod fill_alpha; @@ -23,7 +25,9 @@ pub mod fill_material_cmds; pub mod fill_mode; pub mod fill_reset_cmds; pub mod filter_lib; +pub mod folder_cmds; mod frame_target; +pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; @@ -36,6 +40,7 @@ mod log_level; mod mask_bitmap; pub mod mask_cmds; pub mod mask_export; +mod mask_owner; mod mask_preview_pixel; pub mod material_lib; mod material_preview_pixel; diff --git a/crates/engine/src/mask_owner.rs b/crates/engine/src/mask_owner.rs new file mode 100644 index 00000000..433eea33 --- /dev/null +++ b/crates/engine/src/mask_owner.rs @@ -0,0 +1,8 @@ +//! Whose mask a new mask effect goes in + +/// Whose mask a mask effect goes in: an instance without a mask of its own shares its source's, unless the effect starts the instance's own +#[derive(Clone, Copy, PartialEq)] +pub(crate) enum MaskOwner { + Shared, + Own, +} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 8a1c2f77..e3638c2f 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -36,7 +36,7 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and their patterns, mask fills and generator inputs) +/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; @@ -54,6 +54,7 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, 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)); + out.extend(crate::path_tool::path_images(&effect.kind)); } for child in layer.children() { diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 6640df26..64d8d752 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -842,6 +842,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { } else { let folder_id = s.doc.project.alloc_id(); let mut folder = Layer::new(folder_id, material.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels); + let mut folder = Layer::new(folder_id, material.label, LayerKind::folder(), &channels); for blend in folder.channels.values_mut() { *blend = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 }; } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 42909bd9..e6e253da 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use texturecraft_compose::PaintTarget; +use texturecraft_compose::{MaskGray, PaintTarget}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, Source}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ @@ -189,6 +189,15 @@ impl Session { Some(Pickup::from_snapshot(PickupMode::Clone { offset: [0; 2] }, snapshot, self.caches.get(ts)?.gbuf.clone(), values.keys().copied())) } + /// What mask strokes paint: the tool's image while it is loaded, else its gray + pub(crate) fn mask_gray(&self) -> MaskGray { + let image = self.tool.mask_image.as_ref().and_then(|name| Some((name, self.images.get(name)?))); + match image { + Some((name, image)) => MaskGray::Image { name: name.clone(), image: image.clone() }, + None => MaskGray::Value(self.tool.mask_value), + } + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; @@ -332,6 +341,7 @@ impl Session { camera: self.camera, viewport, values, + mask_gray: self.mask_gray(), erase, stencil, before, @@ -525,16 +535,17 @@ impl Session { let Some(st) = self.stroke.as_mut() else { return }; let recent = std::mem::take(&mut st.canvas.recent); let (ts, target) = (st.ts, st.target); - let Some(t) = target else { + let Some(paint_target) = target else { self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); return; }; + let gbuf = self.caches.get(ts).map(|c| c.gbuf.clone()); - let (pixels, mask_value) = (&self.doc.pixels, self.tool.mask_value); + let pixels = &self.doc.pixels; let mut staging = std::mem::take(&mut st.staging); - with_commit_source(st, gbuf.as_deref(), &self.mesh, &recent, |src| match t { + with_commit_source(st, gbuf.as_deref(), &self.mesh, &recent, |src| match paint_target { PaintTarget::Layer(id) => staging.stage_layer(pixels, id, &st.values, &src), - PaintTarget::Mask(eid) => staging.stage_mask(pixels, eid, mask_value, &src), + PaintTarget::Mask(effect) => staging.stage_mask(pixels, effect, &st.mask_gray, &src), }); st.staging = staging; self.mark_painted(ts, target, recent); @@ -556,7 +567,6 @@ impl Session { let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); - let mask_value = self.tool.mask_value; match st.target { Some(PaintTarget::Layer(id)) => { let pixels = &mut self.doc.pixels; @@ -564,7 +574,7 @@ impl Session { } Some(PaintTarget::Mask(eid)) => { let pixels = &mut self.doc.pixels; - with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_mask(pixels, eid, size, mask_value, src, &mut staging)); + with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| commit_mask(pixels, eid, size, &st.mask_gray, src, &mut staging)); } None => { with_commit_source(&st, gbuf.as_deref(), &mesh, &st.canvas.dirty, |src| self.commit_quick_mask(st.ts, size, src)); @@ -658,7 +668,10 @@ impl Session { let values = self.stroke_values(target); match target { PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()), - PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()), + PaintTarget::Mask(effect) => { + let mask_gray = self.mask_gray(); + commit_mask(&mut self.doc.pixels, effect, size, &mask_gray, source, &mut Staging::default()) + } } Ok(()) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5398501f..19157759 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -156,14 +156,20 @@ impl PathState { #[derive(Clone)] pub(crate) struct PathCache { pub(crate) eid: LayerId, - // Alpha image resources are not part of this cache key - // Replacing an alpha takes effect when a cached path changes + // A change to the mask images `below` paints with drops the cache (Session::invalidate_changed) key: (u64, Option<(u32, u32)>), below: Vec, mask: Option, layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, } +impl PathCache { + /// The image resources the cached paths painted their mask with + pub(crate) fn images(&self) -> impl Iterator + '_ { + self.below.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image) + } +} + /// What a stored path is painted with ([`PathShape::paint`]). #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] struct PathPaint { @@ -171,6 +177,8 @@ struct PathPaint { values: BTreeMap, enabled: BTreeSet, mask_value: f32, + #[serde(default, skip_serializing_if = "Option::is_none")] + mask_image: Option, camera: OrbitCamera, } @@ -337,6 +345,7 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; + s.tool.mask_image = paint.mask_image; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); @@ -369,6 +378,12 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } +/// The image resources a path sublayer's paths paint their mask with (none for any other effect) +pub(crate) fn path_images(kind: &EffectKind) -> Vec { + let EffectKind::Path(shapes) = kind else { return Vec::new() }; + shapes.iter().filter_map(|shape| read_paint(shape).ok()?.mask_image).collect() +} + /// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); @@ -459,7 +474,14 @@ impl Session { /// The Path tool's curve with the current brush and material, as painted from `camera`. fn path_shape(&self, camera: OrbitCamera, viewport: Vec2) -> PathShape { let (t, path) = (&self.tool, &self.tool.path); - let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera }; + let paint = PathPaint { + brush: t.brush.clone(), + values: t.values.clone(), + enabled: t.enabled.clone(), + mask_value: t.mask_value, + mask_image: t.mask_image.clone(), + camera, + }; PathShape { points: path.points.iter().map(|p| p.to_array()).collect(), corners: path.corner_flags(), @@ -1008,6 +1030,7 @@ impl Session { self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; + self.tool.mask_image = paint.mask_image; self.camera = camera; self.tool.path = state_of(shape); self.paint_path(viewport) @@ -1213,6 +1236,37 @@ mod tests { assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles"); } + #[test] + fn removing_a_cached_paths_mask_image_repaints_it_with_the_mask_value() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + let layer = execute(&mut s, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let white = texturecraft_formats::gray16_png(1, 1, [1.0].into_iter()).unwrap(); + let image = s.import_resource_bytes("brush.png", white).unwrap(); + execute(&mut s, "tool.material", &json!({"maskImage": image, "maskValue": 0.5})).unwrap(); + let mut eid = 0; + for v in [0.3, 0.7] { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + eid = r["committed"]["effect"].as_u64().unwrap(); + } + let eid = LayerId(eid); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap(); + assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached"); + + execute(&mut s, "resource.remove", &json!({"name": image})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap(); + let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid)); + let edited = mask(&s); + s.path_cache = None; + s.render_paths(eid, 0).unwrap(); + + assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does"); + } + #[test] fn failed_edit_releases_cached_path_tiles() { let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 12, 6), "builtin:test", None, 128).unwrap(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index e1f352c7..dd59c1d8 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -256,7 +256,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment. +/// Drop resources no layer, mask effect, the brush alpha, the projection stencil, the mask brush or the environment uses (one undo step) fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); for set in &s.doc.project.texture_sets { @@ -266,6 +266,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { } used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); used.extend(s.tool.brush.alpha_image.clone()); + used.extend(s.tool.mask_image.clone()); used.extend(s.doc.project.display.environment_resource().map(str::to_string)); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 2668cb1f..1a51a38a 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -236,6 +236,9 @@ pub struct ToolState { pub material: Option, /// Gray painted into masks. pub mask_value: f32, + /// Image resource whose gray is painted into masks in place of `mask_value` + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mask_image: Option, pub fill_mode: FillMode, /// How a polygon fill box decides which polygons it selects #[serde(default)] @@ -310,6 +313,7 @@ impl Default for ToolState { enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), material: None, mask_value: 1.0, + mask_image: None, fill_mode: FillMode::Triangle, fill_hit_test: Default::default(), fill_visible_only: default_fill_visible_only(), @@ -351,6 +355,8 @@ pub(crate) struct ActiveStroke { pub camera: OrbitCamera, pub viewport: Vec2, pub values: BTreeMap, + /// What a mask stroke paints, resolved once so staging, preview and commit read one image + pub mask_gray: texturecraft_compose::MaskGray, pub erase: bool, /// Projection tool: the stencil captured with the stroke's camera. pub stencil: Option, @@ -449,6 +455,8 @@ pub struct Session { pub(crate) stroke: Option, /// Layer clipboard: a document snapshot and the copied layer (or effect). pub clipboard: Option<(Document, LayerId)>, + /// Channel blending copied from an effect (see [`crate::effect_blending_cmds`]) + pub blending_clipboard: Option, /// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`). pub images: texturecraft_compose::ImageStore, /// Temporary texel mask limiting paint strokes (not saved, not in the history). @@ -533,6 +541,7 @@ impl Session { viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, + blending_clipboard: None, images: Default::default(), quick_mask: Default::default(), painting_paths: false, @@ -743,6 +752,15 @@ impl Session { self.path_cache = None; } + // Cached path pixels were painted with the mask images their paths name + let resource_changed = |name: &str| match (previous_document.resources.get(name), self.doc.resources.get(name)) { + (Some(previous), Some(current)) => !Arc::ptr_eq(previous, current), + (previous, current) => previous.is_some() != current.is_some(), + }; + if self.path_cache.as_ref().is_some_and(|cache| cache.images().any(|name| resource_changed(&name))) { + self.path_cache = None; + } + // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); @@ -754,27 +772,23 @@ impl Session { return; } - let added_resource_names: BTreeSet<_> = self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).collect(); - let uses_added_resource = |texture_set_index: usize| { - use texturecraft_core::{EffectKind, Fill, Source}; + let added_resource_names: BTreeSet<&str> = + self.doc.resources.keys().filter(|name| !previous_document.resources.contains_key(*name)).map(String::as_str).collect(); + let is_added = |name: &str| added_resource_names.contains(name); + use texturecraft_core::{EffectKind, Fill}; - let uses_source = |source: &Source| source.images().into_iter().any(|name| added_resource_names.iter().any(|added| added.as_str() == name)); - let uses_fill = - |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); - let project = &self.doc.project; - !added_resource_names.is_empty() - && project.texture_sets.get(texture_set_index).is_some_and(|set| { - project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { - matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) - || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind { - EffectKind::Fill { source, .. } => uses_source(source), - EffectKind::Material(fill) => uses_fill(fill), - EffectKind::Generator(generator) => generator.inputs.values().any(uses_source), - _ => false, - }) + let uses_link = |fill: &Fill| fill.link.as_ref().is_some_and(|link| is_added(&link.package)); + let uses_fill = |fill: &Fill| fill.sources.values().any(|source| source.images().into_iter().any(is_added)) || uses_link(fill); + let project = &self.doc.project; + !added_resource_names.is_empty() + && project.texture_sets.get(texture_set_index).is_some_and(|set| { + project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)).any(|layer| { + matches!(&layer.kind, LayerKind::Fill(fill) if uses_fill(fill)) + || layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| { + }) + }) }) - }) - }; + }; let (empty_baked_maps, empty_images) = (BakedMaps::default(), Default::default()); let stack_key = |document: &Document, texture_set_index: usize| { let stack = document.project.texture_sets.get(texture_set_index).map(|set| set.stack.as_slice()).unwrap_or_default(); @@ -1012,7 +1026,7 @@ impl Session { opacity: stroke.stroke.settings.opacity, erase: stroke.erase, values: stroke.values.clone(), - mask_value: self.tool.mask_value, + mask_gray: stroke.mask_gray.clone(), stencil: stroke.stencil.clone(), carried_mask: stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()).cloned(), carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(), @@ -1223,12 +1237,19 @@ impl Session { /// Histogram (`bins` buckets over 0..1) of the values entering effect `effect`: its layer's /// mask, or for a content effect the layer's `channel` (None for an unknown effect). - pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option> { + pub fn effect_histogram(&self, effect: LayerId, channel: Channel, bins: usize) -> Option { let (owner, _) = self.doc.project.effect(effect)?; let (ts, _, _) = self.doc.project.locate(owner)?; self.with_inputs(ts, |inp| texturecraft_compose::effect_histogram(inp, effect, channel, bins)) } + /// Histograms (`bins` buckets over 0..1) of what the two sides of compare mask `effect` read, left then right (None for an unknown effect or one that is no compare mask) + pub fn compare_histograms(&self, effect: LayerId, bins: usize) -> Option<[Vec; 2]> { + let (owner, _) = self.doc.project.effect(effect)?; + let (ts, _, _) = self.doc.project.locate(owner)?; + self.with_inputs(ts, |inp| texturecraft_compose::compare_histograms(inp, effect, bins)) + } + pub fn baked(&self, ts: usize) -> Option<&BakedMaps> { self.doc.baked.get(&ts) } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 9ca84090..a9142fa4 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Tool material", [], None, - "{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)", + "{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1, maskImage?: image resource | null (paint its gray into masks; null = maskValue)} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)", always, material ), @@ -315,6 +315,22 @@ fn material(s: &mut Session, p: &Value) -> Result { let channel = channel_param("tool.material", p, "channel")?; let color = color_param("tool.material", p, "color")?; let value = color_param("tool.material", p, "value")?; + + // Every param is checked before the tool changes, so a refused call changes nothing + let mask_image = match p.get("maskImage") { + Some(Value::Null) => Some(None), + Some(name) => { + let name = name.as_str().ok_or_else(|| bad("tool.material", "maskImage must be an image resource name or null"))?; + + // The brush reads the decoded image: a resource that is not one (an environment, a linked package) is refused + if !s.images.contains_key(name) { + return Err(bad("tool.material", format!("no image resource '{name}'"))); + } + + Some(Some(name.to_owned())) + } + None => None, + }; if let Some(id) = strp(p, "material") { let values = crate::materials::brush_values(id).ok_or_else(|| { bad("tool.material", format!("`{id}` is not a simple material (a brush paints plain values; add smart materials with material.apply)")) @@ -332,35 +348,40 @@ fn material(s: &mut Session, p: &Value) -> Result { } s.tool.material = Some(crate::materials::find(id).map_or_else(|| id.to_string(), |m| m.id.to_string())); } - if let Some(v) = f32p(p, "maskValue") { - s.tool.mask_value = v.clamp(0.0, 1.0); + if let Some(mask_value) = f32p(p, "maskValue") { + s.tool.mask_value = mask_value.clamp(0.0, 1.0); } - if let Some(c) = channel { - if let Some(v) = color.or(value) { - let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; - s.tool.values.insert(c, v); - s.tool.enabled.insert(c); + if let Some(mask_image) = mask_image { + s.tool.mask_image = mask_image; + } + if let Some(channel) = channel { + if let Some(picked) = color.or(value) { + let picked = + if channel == Channel::Height { picked.map(|component| component.clamp(-1.0, 1.0)) } else { picked.map(|component| component.clamp(0.0, 1.0)) }; + s.tool.values.insert(channel, picked); + s.tool.enabled.insert(channel); s.tool.material = None; } match boolp(p, "enabled") { Some(true) => { - s.tool.enabled.insert(c); + s.tool.enabled.insert(channel); } Some(false) => { - s.tool.enabled.remove(&c); + s.tool.enabled.remove(&channel); } None => {} } if boolp(p, "solo") == Some(true) { - s.tool.enabled = std::iter::once(c).collect(); + s.tool.enabled = std::iter::once(channel).collect(); } } s.revision = s.revision.wrapping_add(1); Ok(json!({ "material": s.tool.material, - "values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>(), - "enabled": s.tool.enabled.iter().map(|c| c.id()).collect::>(), + "values": s.tool.values.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::>(), + "enabled": s.tool.enabled.iter().map(|channel| channel.id()).collect::>(), "maskValue": s.tool.mask_value, + "maskImage": s.tool.mask_image, })) } diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index 6a3e18b0..11b4ceaa 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -18,6 +18,7 @@ pub fn specs() -> Vec { [], None, "{layer? | effect?: content fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", + "{layer? | effect?: content or mask fill effect id} — a warp projection's frame back around the mesh, seen from the front, with its corners unpulled (Projection Depth and the other settings stay)", has_layer, reset_frame )] diff --git a/crates/engine/tests/it/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs new file mode 100644 index 00000000..ec0e6e53 --- /dev/null +++ b/crates/engine/tests/it/add_mask_items.rs @@ -0,0 +1,109 @@ +//! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; +use texturecraft_engine::fill_alpha::resource_name; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::paint::alphas; +use texturecraft_engine::{Session, StackTarget, execute}; + +fn fill() -> (Session, LayerId) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + (s, layer) +} + +/// A 2 × 2 mid-gray picture +fn gray_png() -> Vec { + let image = image::RgbaImage::from_pixel(2, 2, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// The effect `command` added and selected, and its kind +fn added(s: &mut Session, command: &str, params: Value) -> (LayerId, EffectKind) { + let steps = s.history_labels().len(); + let effect = LayerId(execute(s, command, ¶ms).unwrap()["effect"].as_u64().unwrap()); + assert_eq!(s.history_labels().len(), steps + 1, "{command} is one undo step"); + assert_eq!(s.target, StackTarget::Effect(effect), "{command} selects the effect it adds"); + let kind = s.doc.project.effect(effect).unwrap().1.kind.clone(); + (effect, kind) +} + +#[test] +fn a_bitmap_mask_is_a_black_mask_with_a_fill_reading_the_picked_alpha() { + let (mut s, layer) = fill(); + let name = resource_name(alphas::find("scratches").unwrap()); + let (_, kind) = added(&mut s, "mask.add.bitmap", json!({"layer": layer.0, "alpha": "scratches"})); + assert!(matches!(kind, EffectKind::Fill { source: Source::Image { name: ref read, .. }, .. } if *read == name), "{kind:?}"); + let mask = s.doc.project.layer(layer).unwrap().mask.clone().unwrap(); + assert_eq!(mask.background, MaskBackground::Black); + assert!(s.doc.resources.contains_key(&name)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.layer(layer).unwrap().mask.is_none(), "one undo takes the mask back"); + assert!(!s.doc.resources.contains_key(&name), "and the alpha's picture with it"); + + // Without a picture there is nothing to add + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0})).is_err()); + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": "missing.png"})).is_err()); + let image = s.import_resource_bytes("gray.png", gray_png()).unwrap(); + assert!(execute(&mut s, "mask.add.bitmap", &json!({"layer": layer.0, "image": image, "alpha": "scratches"})).is_err(), "one picture, not two"); + assert!(s.doc.project.layer(layer).unwrap().mask.is_none()); +} + +#[test] +fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_below() { + let (mut s, layer) = fill(); + let (_, kind) = added(&mut s, "mask.add.heightCombination", json!({"layer": layer.0})); + match kind { + EffectKind::Compare { left, right, channel, hardness, .. } => { + assert_eq!((left, right, channel, hardness), (CompareSource::ThisLayer, CompareSource::LayersBelow, Channel::Height, 0.9)); + } + other => panic!("not a compare mask: {other:?}"), + } + assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination")); +} + +#[test] +fn color_selections_go_in_the_mask_and_are_selected() { + let (mut s, layer) = fill(); + let (first, kind) = added(&mut s, "mask.add.colorSelection", json!({"layer": layer.0})); + assert!(matches!(kind, EffectKind::ColorSelection(_))); + assert_eq!(s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().background, MaskBackground::Black, "as colour selection masks were"); + + // Add effect's item adds another to the same mask, whatever target it is given + let (second, kind) = added(&mut s, "effect.add.colorSelection", json!({"layer": layer.0, "target": "content"})); + assert!(matches!(kind, EffectKind::ColorSelection(_))); + let mask: Vec = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(mask, vec![first, second]); + assert!(s.doc.project.layer(layer).unwrap().content_effects.is_empty()); +} + +/// An instance with no mask of its own: the Add mask items start one on the instance and leave the source's mask (or its lack of one) alone +#[test] +fn add_mask_on_an_instance_starts_its_own_mask() { + for source_mask in [None, Some("mask.add.white")] { + for (command, params) in [ + ("mask.add.heightCombination", json!({})), + ("mask.add.colorSelection", json!({"color": [1.0, 0.0, 0.0]})), + ("mask.add.bitmap", json!({"alpha": "scratches"})), + ] { + let (mut s, source) = fill(); + if let Some(add) = source_mask { + execute(&mut s, add, &json!({"layer": source.0})).unwrap(); + } + let before = s.doc.project.layer(source).unwrap().mask.clone(); + let instance = LayerId(execute(&mut s, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().unwrap()); + + let mut params = params; + params["layer"] = json!(instance.0); + let (effect, _) = added(&mut s, command, params); + + assert_eq!(s.doc.project.layer(source).unwrap().mask, before, "{command} left the source's mask as it was"); + let own = s.doc.project.layer(instance).unwrap().mask.as_ref().map(|mask| mask.effects.iter().map(|effect| effect.id).collect::>()); + assert_eq!(own, Some(vec![effect]), "{command} started the instance's own mask"); + } + } +} diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs index bdb984b5..97039c9e 100644 --- a/crates/engine/tests/it/color_selection.rs +++ b/crates/engine/tests/it/color_selection.rs @@ -51,14 +51,14 @@ fn masked_layer(session: &mut Session, with_id_map: bool) -> (LayerId, LayerId) } let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap()["layer"].as_u64().unwrap()); - execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); - let effect = session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects[0].id; + let added = execute(session, "mask.add.colorSelection", &json!({"color": NO_PART, "tolerance": 0.05})).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); (layer, effect) } fn colors(session: &Session, effect: LayerId) -> Vec<[f32; 3]> { match &session.doc.project.effect(effect).unwrap().1.kind { - EffectKind::ColorSelection { colors, .. } => colors.clone(), + EffectKind::ColorSelection(selection) => selection.colors.clone(), other => panic!("not a color selection: {other:?}"), } } @@ -88,7 +88,8 @@ fn a_uv_pick_adds_the_color_there_or_replaces_one() { let (_, effect) = masked_layer(&mut session, true); execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.25, 0.25]})).unwrap(); - assert_close(colors(&session, effect)[1], stored(TOP_LEFT_ID)); + let [_, picked] = colors(&session, effect)[..] else { panic!("the pick adds one color to the first") }; + assert_close(picked, stored(TOP_LEFT_ID)); let replaced = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [0.75, 0.75], "index": 0})).unwrap(); assert_eq!(replaced["index"], json!(0)); @@ -108,7 +109,7 @@ fn the_colors_param_replaces_the_list_in_one_undo_step() { execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": edited, "tolerance": 0.2})).unwrap(); assert_eq!(colors(&session, effect), edited.to_vec()); let Some((_, found)) = session.doc.project.effect(effect) else { panic!("effect gone") }; - assert!(matches!(found.kind, EffectKind::ColorSelection { tolerance, .. } if tolerance == 0.2)); + assert!(matches!(&found.kind, EffectKind::ColorSelection(selection) if selection.tolerance == 0.2)); execute(&mut session, "edit.undo", &Value::Null).unwrap(); assert_eq!(colors(&session, effect), vec![NO_PART]); @@ -118,7 +119,7 @@ fn the_colors_param_replaces_the_list_in_one_undo_step() { fn bad_colors_are_refused_and_change_nothing() { let mut session = session(); let (_, effect) = masked_layer(&mut session, false); - let refused = [json!([]), json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; + let refused = [json!([[0.5, 0.5]]), json!([[0.5, "x", 0.5]]), json!([[0.5, null, 0.5]]), json!("red")]; for colors_param in &refused { assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors_param})).is_err(), "{colors_param}"); @@ -307,3 +308,98 @@ fn benchmark_color_selection_edits() { } } } + +#[test] +fn a_new_color_selection_selects_nothing_until_a_color_is_picked() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap(); + let added = execute(&mut session, "mask.add.colorSelection", &Value::Null).unwrap(); + let effect = LayerId(added["effect"].as_u64().unwrap()); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new()); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [[1.0, 0.0, 0.0]]})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": []})).unwrap(); + assert_eq!(colors(&session, effect), Vec::<[f32; 3]>::new(), "the last color can be removed"); +} + +#[test] +fn an_image_resource_can_be_the_id_map_without_a_mesh_map() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, false); + let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + let pick = json!({"effect": effect.0, "uv": [0.75, 0.25]}); + assert!(execute(&mut session, "effect.colorSelection.pick", &pick).is_err(), "no ID map yet"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": "missing.png"})).is_err()); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); + execute(&mut session, "effect.colorSelection.pick", &pick).unwrap(); + let [_, picked] = colors(&session, effect)[..] else { panic!("the pick adds one color to the first") }; + assert_close(picked, stored(TOP_RIGHT_ID)); + let (width, height) = session.caches[0].size; + let top_right = ((width as f32 * 0.75) as u32, (height as f32 * 0.25) as u32); + let bottom = ((width as f32 * 0.25) as u32, (height as f32 * 0.75) as u32); + assert_eq!(session.mask_at(layer, &[top_right, bottom]).unwrap(), vec![1.0, 0.0]); + assert_eq!(execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string().matches(&format!("\"idMap\":\"{image}\"")).count(), 1); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": null})).unwrap(); + assert_eq!(session.mask_at(layer, &[top_right]).unwrap(), vec![0.0], "back on the missing mesh map"); +} + +#[test] +fn output_hardness_and_background_shape_the_mask_in_one_undo_step_each() { + let mut session = session(); + let (layer, effect) = masked_layer(&mut session, true); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": [stored(TOP_LEFT_ID)]})).unwrap(); + let (width, height) = session.caches[0].size; + let texels = [((width as f32 * 0.25) as u32, (height as f32 * 0.25) as u32), ((width as f32 * 0.25) as u32, (height as f32 * 0.75) as u32)]; + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0], "selected part, background"); + + execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 0.5, "background": "white"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "gray"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 0.5]); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![0.5, 1.0], "one undo step"); + + // A transparent background leaves the mask below it: the black mask background here + execute(&mut session, "effect.set", &json!({"effect": effect.0, "output": 1.0, "background": "transparent"})).unwrap(); + assert_eq!(session.mask_at(layer, &texels).unwrap(), vec![1.0, 0.0]); + + // The bottom part is far from the picked color: a soft edge reaches it only when wide enough + execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "black", "tolerance": 0.0, "hardness": 0.0})).unwrap(); + let soft = session.mask_at(layer, &texels).unwrap(); + assert_eq!(soft[0], 1.0); + let far = (200.0f32 - 10.0) / 255.0; + assert!((soft[1] - (1.0 - far)).abs() < 1e-2, "{soft:?}"); + assert!(execute(&mut session, "effect.set", &json!({"effect": effect.0, "background": "purple"})).is_err()); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for key in ["\"output\":1.0", "\"hardness\":0.0", "\"background\":\"black\""] { + assert!(inspected.contains(key), "{key} in {inspected}"); + } +} + +#[test] +fn the_id_mask_view_shows_the_chosen_image_where_the_mask_reads_it() { + let mut session = session(); + let (_, effect) = masked_layer(&mut session, false); + assert!(session.id_mask_view_rgba(effect, 16).is_none(), "the ID mesh map is no image"); + + let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); + assert_eq!(session.id_mask_image(effect).map(|(texture_set, _)| texture_set), Some(0)); + let rgba = session.id_mask_view_rgba(effect, 16).unwrap(); + assert_eq!(rgba.len(), 16 * 16 * 4); + let pixel = |x: usize, y: usize| -> [u8; 3] { + let start = (y * 16 + x) * 4; + [rgba[start], rgba[start + 1], rgba[start + 2]] + }; + assert_eq!(pixel(1, 1), TOP_LEFT_ID); + assert_eq!(pixel(14, 1), TOP_RIGHT_ID); + assert_eq!(pixel(8, 14), BOTTOM_ID); + + // Each view pixel shows the color a pick at the same UV adds + let picked = execute(&mut session, "effect.colorSelection.pick", &json!({"effect": effect.0, "uv": [14.5 / 16.0, 1.5 / 16.0]})).unwrap(); + let picked: Vec = serde_json::from_value(picked["color"].clone()).unwrap(); + assert_close([picked[0], picked[1], picked[2]], stored(pixel(14, 1))); +} diff --git a/crates/engine/tests/it/compare_mask.rs b/crates/engine/tests/it/compare_mask.rs new file mode 100644 index 00000000..fd00fa03 --- /dev/null +++ b/crates/engine/tests/it/compare_mask.rs @@ -0,0 +1,130 @@ +//! Compare masks: one channel of the layer, the layers below, the mask so far or a constant on each side + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const SIZE: u32 = 256; +const BELOW_COLOR: [f32; 3] = [0.0, 0.0, 1.0]; +const LAYER_COLOR: [f32; 3] = [1.0, 0.0, 0.0]; + +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, SIZE).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + session +} + +/// The texel under the viewport centre +fn center_texel(session: &mut Session) -> (u32, u32) { + session.update(); + let hit = session.pick(Vec2::new(200.0, 200.0), session.viewport).unwrap(); + ((hit.uv.x * SIZE as f32) as u32, (hit.uv.y * SIZE as f32) as u32) +} + +fn base_color(session: &mut Session) -> [f32; 3] { + let (x, y) = center_texel(session); + session.caches[0].composite.value(Channel::BaseColor, x, y) +} + +fn mask(session: &mut Session, layer: LayerId) -> f32 { + let texel = center_texel(session); + session.mask_at(layer, &[texel]).unwrap()[0] +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +fn close(actual: f32, expected: f32) -> bool { + (actual - expected).abs() < 2e-3 +} + +/// A blue fill of `below` roughness, a red fill of `own` roughness over it with a default compare mask on roughness: (below, layer, compare) +fn two_layers(session: &mut Session, below: f32, own: f32) -> (LayerId, LayerId, LayerId) { + let bottom = id(execute(session, "layer.add.fill", &json!({"color": BELOW_COLOR, "roughness": below})).unwrap(), "layer"); + let top = id(execute(session, "layer.add.fill", &json!({"color": LAYER_COLOR, "roughness": own})).unwrap(), "layer"); + let compare = id(execute(session, "effect.add.compare", &json!({"layer": top, "compareChannel": "roughness"})).unwrap(), "effect"); + (LayerId(bottom), LayerId(top), LayerId(compare)) +} + +#[test] +fn this_layer_is_compared_with_the_layers_below() { + let mut session = session(); + let (bottom, top, compare) = two_layers(&mut session, 0.2, 0.6); + assert!(close(mask(&mut session, top), 1.0), "0.6 > 0.2 holds: {}", mask(&mut session, top)); + assert_eq!(base_color(&mut session), LAYER_COLOR, "the layer shows where its mask compares true"); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser"})).unwrap(); + assert!(close(mask(&mut session, top), 0.0)); + assert_eq!(base_color(&mut session), BELOW_COLOR, "the layer is hidden where the comparison fails"); + + // Changing the layers below changes the mask above them (no stale cached stack) + execute(&mut session, "layer.fill.set", &json!({"layer": bottom.0, "channel": "roughness", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9 holds: {}", mask(&mut session, top)); + assert_eq!(base_color(&mut session), LAYER_COLOR); +} + +#[test] +fn hardness_ramps_the_mask_past_the_edge() { + let mut session = session(); + + // 0.6 is 0.03 past 0.57: a third of the default hardness 0.9's 0.1 ramp + let (_, top, compare) = two_layers(&mut session, 0.57, 0.6); + assert!(close(mask(&mut session, top), 0.3), "{}", mask(&mut session, top)); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a hard step: {}", mask(&mut session, top)); + + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "within", "tolerance": 0.02, "hardness": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 0.9), "0.01 past the tolerance of 0.1's ramp: {}", mask(&mut session, top)); +} + +#[test] +fn a_constant_side_and_the_mask_so_far() { + let mut session = session(); + let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "right": "constant", "value": 0.7, "hardness": 1.0})).unwrap(); + assert!(close(mask(&mut session, top), 0.0), "0.6 > 0.7 fails"); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "thisMask", "value": 0.5})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "a white mask (1) > 0.5 holds"); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + for part in ["\"left\":\"thisMask\"", "\"op\":\"greater\"", "\"right\":\"constant\"", "\"compareChannel\":\"roughness\"", "\"hardness\":1.0"] { + assert!(inspected.contains(part), "inspect shows {part}"); + } +} + +#[test] +fn compare_parameters_are_one_undo_step_and_refuse_unknown_values() { + let mut session = session(); + let (_, top, compare) = two_layers(&mut session, 0.2, 0.6); + execute(&mut session, "effect.set", &json!({"effect": compare.0, "op": "lesser", "right": "constant", "value": 0.9})).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "0.6 < 0.9"); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert!(close(mask(&mut session, top), 1.0), "back to 0.6 > layers below 0.2"); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"op\":\"greater\"") && inspected.contains("\"right\":\"layersBelow\""), "one undo step restores both"); + + assert!(execute(&mut session, "effect.set", &json!({"effect": compare.0, "left": "elsewhere"})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": compare.0, "compareChannel": "nope"})).is_err()); + assert!(execute(&mut session, "effect.add.compare", &json!({"layer": top.0, "target": "content"})).is_err(), "compare masks go on masks"); +} + +#[test] +fn the_histogram_counts_what_each_side_reads() { + let mut session = session(); + let (_, _, compare) = two_layers(&mut session, 0.25, 0.65); + let histogram = execute(&mut session, "effect.histogram", &json!({"effect": compare.0, "bins": 10})).unwrap(); + let busiest = |side: &str| { + let counts: Vec = histogram["compare"][side].as_array().unwrap().iter().map(|count| count.as_u64().unwrap()).collect(); + assert!(counts.iter().sum::() > 0, "{side} counts texels"); + counts.iter().enumerate().max_by_key(|(_, count)| **count).map(|(bucket, _)| bucket).unwrap() + }; + assert_eq!(busiest("left"), 6, "this layer's roughness 0.65"); + assert_eq!(busiest("right"), 2, "the layers below's roughness 0.25"); +} diff --git a/crates/engine/tests/it/effect_blending.rs b/crates/engine/tests/it/effect_blending.rs new file mode 100644 index 00000000..f90bd380 --- /dev/null +++ b/crates/engine/tests/it/effect_blending.rs @@ -0,0 +1,142 @@ +//! A content effect's blending per channel and the Blending options commands, through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const SIZE: u32 = 128; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, SIZE).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Composited value of `channel` under the viewport center +fn center(s: &mut Session, channel: Channel) -> [f32; 3] { + s.update(); + let hit = s.pick(Vec2::new(200.0, 200.0), s.viewport).unwrap(); + s.caches[0].composite.value(channel, (hit.uv.x * SIZE as f32) as u32, (hit.uv.y * SIZE as f32) as u32) +} + +fn assert_close(actual: [f32; 3], expected: [f32; 3], what: &str) { + assert!((0..3).all(|i| (actual[i] - expected[i]).abs() < 4e-3), "{what}: {actual:?}, expected {expected:?}"); +} + +fn id(value: Value, key: &str) -> u64 { + value[key].as_u64().unwrap() +} + +/// A red fill layer of roughness 0.2 under a content fill effect of grey 0.5 and roughness 0.8: (layer, effect) +fn layer_with_content_fill(s: &mut Session) -> (u64, u64) { + let layer = id(execute(s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0], "roughness": 0.2})).unwrap(), "layer"); + let effect = id(execute(s, "effect.add.fill", &json!({"target": "content", "color": [0.5, 0.5, 0.5], "roughness": 0.8})).unwrap(), "effect"); + (layer, effect) +} + +/// What inspect shows of content effect `effect`'s per-channel blending, in `layer`'s row +fn channel_blends(s: &mut Session, layer: u64, effect: u64) -> Value { + let inspect = execute(s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap().clone(); + let shown = row["contentEffects"].as_array().unwrap().iter().find(|shown| shown["id"] == effect).unwrap().clone(); + shown["channelBlends"].clone() +} + +/// Setting one channel's blend mode or opacity leaves the others' as they are, and inspect shows it +#[test] +fn a_content_effect_blends_each_channel_on_its_own() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + assert_close(center(&mut s, Channel::BaseColor), [0.5; 3], "normal at 100%"); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "normal at 100%"); + + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "baseColor", "opacity": 0.5})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color at half opacity"); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "roughness keeps its full opacity"); + + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.16; 3], "roughness multiplies"); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color stays normal"); + let blends = channel_blends(&mut s, layer, effect); + assert_eq!(blends["baseColor"]["opacity"], json!(0.5), "{blends}"); + assert_eq!(blends["roughness"]["blend"], json!("Multiply"), "{blends}"); + + // Without a channel the edit reaches every channel, and channels left alike stop blending apart + execute(&mut s, "effect.set", &json!({"effect": effect, "opacity": 1.0, "blend": "Normal"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.8; 3], "every channel back to normal at 100%"); + assert_close(center(&mut s, Channel::BaseColor), [0.5; 3], "every channel back to normal at 100%"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "no channel blends apart any more"); + + // Saved per channel, loaded as saved; an effect saved before has none + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); + let effect = s.doc.project.effect(LayerId(effect)).unwrap().1; + assert_eq!(effect.blend_of(Some(Channel::BaseColor)), effect.blend_of(None), "unset channels share the effect's blending"); +} + +/// The three "on every channel" items take the chosen channel's blend mode, opacity or both, each in one undo step +#[test] +fn one_channels_blending_goes_to_every_channel_in_one_undo_step() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "baseColor", "opacity": 0.5})).unwrap(); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply"})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + + execute(&mut s, "effect.blending.opacityToEveryChannel", &json!({"channel": "baseColor"})).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.18; 3], "roughness multiplies at half opacity"); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.25, 0.25], "base color unchanged"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_close(center(&mut s, Channel::Roughness), [0.16; 3], "one undo puts the opacity back"); + + execute(&mut s, "effect.blending.modeToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.75, 0.0, 0.0], "base color multiplies at its own half opacity"); + + execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0], "base color multiplies at full opacity"); + assert!(channel_blends(&mut s, layer, effect).is_null(), "every channel blends alike"); + + // Nothing left to change: no empty undo step + let steps = s.history_labels().len(); + execute(&mut s, "effect.blending.bothToEveryChannel", &json!({"channel": "roughness"})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "every channel already blends alike"); +} + +/// Copy and paste carry every channel's blending to another effect; masks, levels and anchors take what applies to them +#[test] +fn channel_blending_copies_and_pastes_between_effects() { + let mut s = session(); + let (layer, effect) = layer_with_content_fill(&mut s); + execute(&mut s, "effect.set", &json!({"effect": effect, "channel": "roughness", "blend": "Multiply", "opacity": 0.5})).unwrap(); + assert!(execute(&mut s, "effect.blending.paste", &json!({"effect": effect})).is_err(), "nothing copied yet"); + execute(&mut s, "effect.blending.copy", &json!({"effect": effect})).unwrap(); + + let other = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer, "target": "content", "roughness": 0.8})).unwrap(), "effect"); + execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); + let pasted = s.doc.project.effect(LayerId(other)).unwrap().1; + assert_eq!(pasted.blend_of(Some(Channel::Roughness)), s.doc.project.effect(LayerId(effect)).unwrap().1.blend_of(Some(Channel::Roughness))); + assert_eq!(pasted.blend_of(Some(Channel::BaseColor)), pasted.blend_of(None)); + let steps = s.history_labels().len(); + execute(&mut s, "effect.blending.paste", &json!({"effect": other})).unwrap(); + assert_eq!(s.history_labels().len(), steps, "pasting the blending it already has adds no undo step"); + + // A mask effect has one channel: it takes the shared blending and refuses a channel of its own + execute(&mut s, "mask.add.white", &json!({"layer": layer})).unwrap(); + let masked = id(execute(&mut s, "effect.add.fill", &json!({"layer": layer})).unwrap(), "effect"); + execute(&mut s, "effect.blending.paste", &json!({"effect": masked})).unwrap(); + assert!(s.doc.project.effect(LayerId(masked)).unwrap().1.channel_blends.is_empty()); + assert!(execute(&mut s, "effect.set", &json!({"effect": masked, "channel": "roughness", "opacity": 0.5})).is_err()); + assert!(execute(&mut s, "effect.blending.modeToEveryChannel", &json!({"effect": masked})).is_err()); + + // Levels and anchor points have no blending + let levels = id(execute(&mut s, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap(), "effect"); + assert!(execute(&mut s, "effect.blending.copy", &json!({"effect": levels})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer, "target": levels})).unwrap(); + assert!((texturecraft_engine::commands::find("effect.blending.paste").unwrap().enabled)(&s).is_err(), "greyed for levels"); +} diff --git a/crates/engine/tests/it/fill_projections.rs b/crates/engine/tests/it/fill_projections.rs index 23711592..3c7e6267 100644 --- a/crates/engine/tests/it/fill_projections.rs +++ b/crates/engine/tests/it/fill_projections.rs @@ -515,7 +515,7 @@ fn an_axis_planar_reading_a_pattern_is_not_placed() { let added = execute(&mut s, "effect.add.fill", &json!({"layer": layer.0, "target": "mask", "projection": "planar"})).unwrap(); let effect = added["effect"].as_u64().unwrap(); execute(&mut s, "effect.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); - + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "procedural": "Checker"})).unwrap(); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "effect": effect})).is_err(), "a mask fill's pattern keeps its axis too"); } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index bae8985c..f45226e8 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -1,6 +1,7 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone session.rs target remains available. +mod add_mask_items; mod bake; mod bake_checks; mod bake_resolution; @@ -9,7 +10,9 @@ mod bake_tiles; mod brush_material; mod closed_session; mod color_selection; +mod compare_mask; mod content_effects; +mod effect_blending; mod export_colour_space; mod export_file_types; mod export_maps; @@ -21,6 +24,7 @@ mod fill_whole_material; mod filter_support; mod filter_swap; mod filters; +mod folder_contents; mod frame_selection; mod generator_inputs; mod gradient_map; @@ -29,6 +33,8 @@ mod instances; mod layer_multi_select; mod mask_clone_smudge; mod mask_export; +mod mask_fill_source; +mod mask_paint_image; mod materialcraft_link; mod materialx; mod materialx_import; @@ -40,6 +46,7 @@ mod pbr_import; mod perf; mod polygon_fill; mod project_recovery; +mod resources_used; mod sample; mod solo; mod swatches; diff --git a/crates/engine/tests/it/mask_paint_image.rs b/crates/engine/tests/it/mask_paint_image.rs new file mode 100644 index 00000000..61f16f29 --- /dev/null +++ b/crates/engine/tests/it/mask_paint_image.rs @@ -0,0 +1,119 @@ +//! Painting a mask with an image: the tool's Grayscale slot set to an image paints its gray per texel + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const RESOLUTION: u32 = 256; + +/// An 8 × 8 picture: black on its left half, white on its right half +fn halves_png() -> Vec { + let image = image::RgbaImage::from_fn(8, 8, |x, _| if x < 4 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) }); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A paint layer under a black mask, the mask selected for painting, a big brush +fn masked_layer() -> (Session, LayerId) { + let mut session = Session::new_project("Mask image", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 40.0, "spacing": 5.0, "hardness": 100})).unwrap(); + (session, layer) +} + +/// The mask at texture coordinates (`u`, `v`) +fn mask_at(session: &Session, layer: LayerId, u: f32, v: f32) -> f32 { + let texel = ((u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32); + session.mask_at(layer, &[texel]).unwrap()[0] +} + +#[test] +fn a_mask_stroke_paints_the_tools_image_gray_and_null_goes_back_to_the_value() { + let (mut session, layer) = masked_layer(); + let image = session.import_resource_bytes("halves.png", halves_png()).unwrap(); + let set = execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap(); + assert_eq!(set["maskImage"], json!(image)); + assert!(execute(&mut session, "tool.material", &json!({"maskImage": "missing.png"})).is_err(), "an unknown image is refused"); + assert!(execute(&mut session, "tool.material", &json!({"maskImage": 3})).is_err()); + + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5)); + assert!(left < 0.05 && right > 0.95, "the image's halves: left {left}, right {right}"); + + // Back to one value: the next stroke paints white on the left too + let set = execute(&mut session, "tool.material", &json!({"maskImage": null})).unwrap(); + assert_eq!(set["maskImage"], Value::Null); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + assert!(mask_at(&session, layer, 0.25, 0.5) > 0.95); +} + +#[test] +fn a_refused_mask_image_leaves_the_mask_value_as_it_was() { + let (mut session, _) = masked_layer(); + execute(&mut session, "tool.material", &json!({"maskValue": 0.25})).unwrap(); + + let refused = execute(&mut session, "tool.material", &json!({"maskValue": 0.75, "maskImage": "missing.png"})); + + assert!(refused.is_err()); + assert_eq!(execute(&mut session, "tool.material", &Value::Null).unwrap()["maskValue"], json!(0.25)); +} + +#[test] +fn a_resource_that_is_no_image_is_refused_as_the_mask_image() { + let (mut session, _) = masked_layer(); + session.doc.resources.insert("notes.png".to_string(), std::sync::Arc::new(b"not a picture".to_vec())); + session.sync_images(); + + let refused = execute(&mut session, "tool.material", &json!({"maskImage": "notes.png"})); + + assert!(refused.is_err(), "the brush could not read it"); + assert_eq!(execute(&mut session, "tool.material", &Value::Null).unwrap()["maskImage"], Value::Null); +} + +#[test] +fn a_mask_image_that_is_gone_paints_the_value() { + let (mut session, layer) = masked_layer(); + let image = session.import_resource_bytes("halves.png", halves_png()).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": image, "maskValue": 0.5})).unwrap(); + session.images.remove(&image); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.1, 0.5], [0.9, 0.5]]})).unwrap(); + let painted = mask_at(&session, layer, 0.25, 0.5); + assert!((painted - 0.5).abs() < 0.02, "painted {painted}"); +} + +/// A one-colour picture, `level` 0 for black or 255 for white +fn plain_png(level: u8) -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba([level, level, level, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +#[test] +fn a_mask_stroke_paints_the_image_it_began_with_when_the_resource_is_replaced_mid_stroke() { + let mut session = Session::new_project("Mask image", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + let layer = LayerId(execute(&mut session, "layer.add.paint", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.white", &json!({"layer": layer.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 40.0, "spacing": 5.0, "hardness": 100})).unwrap(); + let image = session.import_resource_bytes("brush.png", plain_png(0)).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": image})).unwrap(); + + session.begin_stroke_uv(Vec2::new(0.1, 0.5), 1.0).unwrap(); + session.continue_stroke_uv(Vec2::new(0.4, 0.5), 1.0); + execute(&mut session, "resource.remove", &json!({"name": image})).unwrap(); + let replaced = session.import_resource_bytes("brush.png", plain_png(255)).unwrap(); + session.continue_stroke_uv(Vec2::new(0.9, 0.5), 1.0); + session.end_stroke().unwrap(); + + assert_eq!(replaced, image, "the white picture took the black one's name"); + let (left, right) = (mask_at(&session, layer, 0.25, 0.5), mask_at(&session, layer, 0.75, 0.5)); + assert!(left < 0.05 && right < 0.05, "the whole stroke is black: left {left}, right {right}"); +} diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 6c4be47f..c22a0d42 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -80,33 +80,44 @@ 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})), diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs new file mode 100644 index 00000000..9d57d1d6 --- /dev/null +++ b/crates/engine/tests/it/resources_used.rs @@ -0,0 +1,74 @@ + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const RESOLUTION: u32 = 128; + +fn session() -> Session { + Session::new_project("Resources", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, RESOLUTION).unwrap() +} + +/// A 4 × 4 white picture +fn white_png() -> Vec { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A red fill layer whose mask selects white on `id_map` +fn selecting_layer(session: &mut Session, id_map: &str) -> LayerId { + let layer = LayerId(execute(session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap()["layer"].as_u64().unwrap()); + let selection = execute(session, "mask.add.colorSelection", &Value::Null).unwrap()["effect"].as_u64().unwrap(); + execute(session, "effect.set", &json!({"effect": selection, "idMap": id_map, "colors": [[1.0, 1.0, 1.0]], "tolerance": 0.05})).unwrap(); + layer +} + +#[test] + let mut session = session(); + + // A path on the mask is painted with one image, then the brush moves on to another + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": path})).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "tool.material", &json!({"maskImage": brush})).unwrap(); + + let reply = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(reply["removed"], json!([unused]), "only the image nothing reads goes"); +} + +#[test] + let mut session = session(); + let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); + let bytes = session.smart_material_bytes(layer, "Parts").unwrap(); + + let mut other = self::session(); + other.add_smart_material_bytes(&bytes).unwrap(); + + assert!(other.doc.resources.contains_key(&id_map), "the ID map comes along"); +} + +#[test] +fn importing_the_id_map_a_selection_reads_again_redraws_its_mask() { + let mut session = session(); + let id_map = session.import_resource_bytes("id.png", white_png()).unwrap(); + selecting_layer(&mut session, &id_map); + assert!(red_in_the_view(&mut session), "white is selected"); + execute(&mut session, "resource.remove", &json!({"name": id_map})).unwrap(); + assert!(!red_in_the_view(&mut session), "no ID map, nothing selected"); + + let imported = session.import_resource_bytes("id.png", white_png()).unwrap(); + + assert_eq!(imported, id_map); + assert!(red_in_the_view(&mut session), "the image is read again"); +} + +/// Whether the composite the views show is the masked layer's red in the middle of the texture +fn red_in_the_view(session: &mut Session) -> bool { + session.update(); + let [red, green, _] = session.caches[0].composite.value(Channel::BaseColor, RESOLUTION / 2, RESOLUTION / 2); + red > 0.85 && green < 0.15 +} diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index 8351ca8f..e7df85cf 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -7,7 +7,7 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::Arc; use rayon::prelude::*; -use texturecraft_compose::PixelStore; +use texturecraft_compose::{MaskGray, PixelStore}; use texturecraft_core::{Channel, ChannelKind, LayerId}; use texturecraft_texel::{TILE, TILE_AREA, TileData, TileImage, from_u16, from_u16_signed, to_u16, to_u16_signed}; @@ -19,14 +19,13 @@ pub(crate) fn enc(kind: ChannelKind, v: f32) -> u16 { if kind == ChannelKind::Signed { to_u16_signed(v) } else { to_u16(v) } } -/// What one image receives: its channel kind, the painted value (unused when erasing or for -/// coverage images), whether a stencil's color replaces it (base color) and the values a clone -/// or smudge stroke carries for it. +/// What one image receives: its channel kind, the painted value (unused when erasing or for coverage images), whether a stencil's color replaces it (base color) and the values a clone or smudge stroke carries for it, and the image whose gray a mask stroke paints in place of `value` struct Blend<'a> { kind: ChannelKind, value: &'a [f32], stencil_color: bool, carried: Option<&'a TileImage>, + gray: Option<&'a MaskGray>, } /// Blend `alpha × opacity` into one image of `n` value components plus coverage. With a @@ -70,42 +69,47 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option) { - let n = comps.saturating_sub(1); - let opacity = src.opacity.clamp(0.0, 1.0); +/// Blend the stroke's alpha tile `stroke_alpha` into tile `(tx, ty)` of an image (`dst`, `components` per texel) +fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty): (u32, u32), blend: &Blend, source: &CommitSource, carried: Option<&[u16]>) { + // The last component is the coverage, the ones before it the value + let value_count = components.saturating_sub(1); + let opacity = source.opacity.clamp(0.0, 1.0); for i in 0..TILE_AREA { - let mut m = from_u16(a.get(i).copied().unwrap_or(0)) * opacity; - if m <= 0.0 { + let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; + if weight <= 0.0 { continue; } - let mut color = None; - if let Some(f) = src.per_texel { - let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); - match f(x, y) { - Some((c, af)) => { - m *= af; - color = Some(c); + + let mut stencil = None; + let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); + if let Some(per_texel) = source.per_texel { + match per_texel(x, y) { + Some((color, alpha_factor)) => { + weight *= alpha_factor; + stencil = Some(color); } None => continue, } - if m <= 0.0 { + if weight <= 0.0 { continue; } } - let Some(px) = dst.get_mut(i * comps..(i + 1) * comps) else { continue }; - let cov = from_u16(px[n]); - for k in 0..n { - let p = dec(b.kind, px[k]); - let target = match (carried, color) { - (Some(t), _) => dec(b.kind, t.get(i * n + k).copied().unwrap_or(0)), - (None, Some(c)) if b.stencil_color => c.get(k).copied().unwrap_or(0.0), - _ => b.value.get(k).copied().unwrap_or(0.0), + + let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; + let gray = blend.gray.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); + let coverage = from_u16(*coverage_slot); + for (component, slot) in values.iter_mut().enumerate() { + let previous = dec(blend.kind, *slot); + let target = match (carried, stencil) { + (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(i * value_count + component).copied().unwrap_or(0)), + (None, _) if let Some(gray) = gray => gray, + (None, Some(color)) if blend.stencil_color => color.get(component).copied().unwrap_or(0.0), + _ => blend.value.get(component).copied().unwrap_or(0.0), }; - let v = if src.erase { p * (1.0 - m) } else { target * m + p * (1.0 - m) }; - px[k] = enc(b.kind, v); + let blended = if source.erase { previous * (1.0 - weight) } else { target * weight + previous * (1.0 - weight) }; + *slot = enc(blend.kind, blended); } - px[n] = to_u16(if src.erase { cov * (1.0 - m) } else { m + cov * (1.0 - m) }); + *coverage_slot = to_u16(if source.erase { coverage * (1.0 - weight) } else { weight + coverage * (1.0 - weight) }); } } @@ -134,13 +138,15 @@ fn fill_from(dst: &mut Vec, from: Option<&[u16]>, empty: &[u16]) { #[derive(Clone, Debug, PartialEq)] struct BlendKey { value: Vec, + image: Option, opacity: f32, erase: bool, } impl BlendKey { fn new(b: &Blend, src: &CommitSource) -> BlendKey { - BlendKey { value: b.value.to_vec(), opacity: src.opacity, erase: src.erase } + let image = b.gray.and_then(MaskGray::image_name).map(str::to_owned); + BlendKey { value: b.value.to_vec(), image, opacity: src.opacity, erase: src.erase } } } @@ -240,11 +246,10 @@ impl Staging { } } - /// Prepare tiles `src.tiles` of the mask paint effect a [`commit_mask`] of `effect` with - /// the same arguments will write. - pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, value: f32, src: &CommitSource) { - let value = [value.clamp(0.0, 1.0)]; - let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }; + /// Prepare tiles `src.tiles` of the mask paint effect a [`commit_mask`] of `effect` with the same arguments will write + pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, gray: &MaskGray, src: &CommitSource) { + let value = mask_value(gray); + let b = Blend { carried: src.carried_mask, ..mask_blend(gray, &value) }; self.images.entry(None).or_default().stage(pixels.masks.get(&effect), 2, &b, src); } @@ -273,9 +278,24 @@ fn layer_blend<'a>(c: Channel, values: &'a BTreeMap, src: &Co value: value.get(..c.components()).unwrap_or(value), stencil_color: c == Channel::BaseColor, carried: src.carried.and_then(|m| m.get(&c)), + gray: None, } } +/// The one value a mask stroke painting `gray` blends (0 under an image, which gives its own per texel) +fn mask_value(gray: &MaskGray) -> [f32; 1] { + match gray { + MaskGray::Value(value) => [value.clamp(0.0, 1.0)], + MaskGray::Image { .. } => [0.0], + } +} + +/// How a mask stroke painting `gray` blends (`value` from [`mask_value`]) +fn mask_blend<'a>(gray: &'a MaskGray, value: &'a [f32; 1]) -> Blend<'a> { + let gray = matches!(gray, MaskGray::Image { .. }).then_some(gray); + Blend { kind: ChannelKind::Scalar, value, stencil_color: false, carried: None, gray } +} + /// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint. pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<([f32; 3], f32)> + Sync); @@ -309,16 +329,16 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v images.into_par_iter().for_each(|(c, img, staged)| over(img, &layer_blend(c, values, &src), &src, staged)); } -/// Commit a stroke into the paint effect `effect` of a mask, painting gray `value`. -pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), value: f32, src: CommitSource, staging: &mut Staging) { +/// Commit a stroke into the paint effect `effect` of a mask, painting `gray` +pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), gray: &MaskGray, src: CommitSource, staging: &mut Staging) { let img = pixels.mask_mut(effect, size); - let value = [value.clamp(0.0, 1.0)]; - over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }, &src, staging.take(None)); + let value = mask_value(gray); + over(img, &Blend { carried: src.carried_mask, ..mask_blend(gray, &value) }, &src, staging.take(None)); } -/// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask. +/// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask pub fn commit_coverage(img: &mut TileImage, src: CommitSource) { - over(img, &Blend { kind: ChannelKind::Scalar, value: &[], stencil_color: false, carried: None }, &src, None); + over(img, &Blend { kind: ChannelKind::Scalar, value: &[], stencil_color: false, carried: None, gray: None }, &src, None); } #[cfg(test)] @@ -371,9 +391,9 @@ mod tests { fn mask_commit_and_untouched_tiles_stay_shared() { let mut px = PixelStore::default(); let (a, tiles) = alpha(1.0); - commit_mask(&mut px, LayerId(9), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); let before = px.clone(); - commit_mask(&mut px, LayerId(9), (64, 64), 0.0, src(&a, &tiles, 1.0, true), &mut Staging::default()); + commit_mask(&mut px, LayerId(9), (64, 64), &MaskGray::Value(0.0), src(&a, &tiles, 1.0, true), &mut Staging::default()); assert_eq!(from_u16(before.masks[&LayerId(9)].get(5, 5)[1]), 1.0); assert_eq!(px.masks[&LayerId(9)].get(5, 5)[1], 0); } @@ -406,7 +426,7 @@ mod tests { let source = CommitSource { carried: Some(&carried), ..src(&alpha, &tiles, 1.0, false) }; let mut pixels = PixelStore::default(); - commit_mask(&mut pixels, LayerId(1), (64, 64), 1.0, source, &mut Staging::default()); + commit_mask(&mut pixels, LayerId(1), (64, 64), &MaskGray::Value(1.0), source, &mut Staging::default()); assert_eq!(pixels.masks[&LayerId(1)].get(5, 5)[0], u16::MAX); } @@ -417,7 +437,7 @@ mod tests { let (a, tiles) = alpha(0.7); let mut base = PixelStore::default(); commit_layer(&mut base, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); - commit_mask(&mut base, LayerId(2), (64, 64), 0.5, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut base, LayerId(2), (64, 64), &MaskGray::Value(0.5), src(&a, &tiles, 1.0, false), &mut Staging::default()); let carried: BTreeMap = vals.keys().map(|c| (*c, a.clone())).collect(); // Staged when the stroke started, then again after the alpha changed (pre-blended // tiles re-blend), and staged once more with its last alpha change left out (that @@ -428,20 +448,20 @@ mod tests { let mut staging = Staging::default(); let c = carry.then_some(&carried); staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); a.set(7, 9, &[to_u16(0.3)]); staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); a.set(8, 9, &[to_u16(0.9)]); if stage_last { staging.stage_layer(&staged, LayerId(1), &vals, &source(&a, &tiles, c, erase)); - staging.stage_mask(&staged, LayerId(2), 1.0, &source(&a, &tiles, c, erase)); + staging.stage_mask(&staged, LayerId(2), &MaskGray::Value(1.0), &source(&a, &tiles, c, erase)); } let mut plain = base.clone(); commit_layer(&mut plain, LayerId(1), (64, 64), &vals, source(&a, &tiles, c, erase), &mut Staging::default()); - commit_mask(&mut plain, LayerId(2), (64, 64), 1.0, source(&a, &tiles, c, erase), &mut Staging::default()); + commit_mask(&mut plain, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut Staging::default()); commit_layer(&mut staged, LayerId(1), (64, 64), &vals, source(&a, &tiles, c, erase), &mut staging); - commit_mask(&mut staged, LayerId(2), (64, 64), 1.0, source(&a, &tiles, c, erase), &mut staging); + commit_mask(&mut staged, LayerId(2), (64, 64), &MaskGray::Value(1.0), source(&a, &tiles, c, erase), &mut staging); assert_eq!((&staged.layers, &staged.masks), (&plain.layers, &plain.masks), "erase {erase}, carried {carry}, staged last {stage_last}"); } // Tiles staged before the layer changed or with another value are stale: the commit @@ -449,13 +469,40 @@ mod tests { let mut px = base.clone(); let mut staging = Staging::default(); staging.stage_layer(&px, LayerId(1), &vals, &src(&a, &tiles, 1.0, false)); - staging.stage_mask(&px, LayerId(2), 0.25, &src(&a, &tiles, 1.0, false)); + staging.stage_mask(&px, LayerId(2), &MaskGray::Value(0.25), &src(&a, &tiles, 1.0, false)); commit_layer(&mut px, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); let mut expected = px.clone(); commit_layer(&mut expected, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut Staging::default()); - commit_mask(&mut expected, LayerId(2), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut Staging::default()); + commit_mask(&mut expected, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); commit_layer(&mut px, LayerId(1), (64, 64), &vals, src(&a, &tiles, 1.0, false), &mut staging); - commit_mask(&mut px, LayerId(2), (64, 64), 1.0, src(&a, &tiles, 1.0, false), &mut staging); + commit_mask(&mut px, LayerId(2), (64, 64), &MaskGray::Value(1.0), src(&a, &tiles, 1.0, false), &mut staging); assert_eq!((&px.layers, &px.masks), (&expected.layers, &expected.masks)); } + + #[test] + fn a_mask_stroke_paints_an_images_gray_per_texel_staged_or_not() { + use std::sync::Arc; + use texturecraft_compose::ImageRes; + + // A 2 × 1 image: black on the left half of the texture, white on the right + let image = |name: &str, left: f32| MaskGray::Image { name: name.into(), image: Arc::new(ImageRes::new(2, 1, vec![[left; 4], [1.0; 4]], false)) }; + let mut a = TileImage::new(64, 64, 1); + for (x, y) in [(16, 5), (48, 5)] { + a.set(x, y, &[to_u16(1.0)]); + } + let tiles: BTreeSet<(u32, u32)> = [(0, 0)].into_iter().collect(); + let gray_at = |px: &PixelStore, x| from_u16(px.masks[&LayerId(4)].get(x, 5)[0]); + + let mut plain = PixelStore::default(); + commit_mask(&mut plain, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut Staging::default()); + assert!(gray_at(&plain, 16) < 0.05 && gray_at(&plain, 48) > 0.95, "left {} right {}", gray_at(&plain, 16), gray_at(&plain, 48)); + + // Staged with another image first: the commit blends the image it is given + let mut staged = PixelStore::default(); + let mut staging = Staging::default(); + staging.stage_mask(&staged, LayerId(4), &image("other", 0.5), &src(&a, &tiles, 1.0, false)); + staging.stage_mask(&staged, LayerId(4), &image("scratches", 0.0), &src(&a, &tiles, 1.0, false)); + commit_mask(&mut staged, LayerId(4), (64, 64), &image("scratches", 0.0), src(&a, &tiles, 1.0, false), &mut staging); + assert_eq!(staged.masks, plain.masks); + } } diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index b564144f..15e59218 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -25,8 +25,6 @@ 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, 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"; const FILTER_SWATCH_WIDTH: f32 = 36.0; const FILTER_HINT_SIZE: f32 = 10.5; /// The most colors `effect.set {colors}` takes for a gradient map @@ -138,75 +136,12 @@ 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(); - for (label, id) in - [(tr("Add white mask"), "mask.add.white"), (tr("Add black mask"), "mask.add.black"), (tr("Add mask with color selection"), "mask.add.colorSelection")] - { - if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { - if let Some(layer) = row { - app.run("layer.select", json!({ "layer": layer })); - } - app.run(id, Value::Null); - ui.close(); - } - } -} - pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); - // Wrap in a narrow column so rows stay within the panel - let project_open = app.session.project_open; - ui.add_enabled_ui(project_open, |ui| { - ui.horizontal_wrapped(|ui| { - // Keep menu buttons as compact as the adjacent icon buttons - ui.spacing_mut().button_padding.x = 4.0; - ui.spacing_mut().item_spacing.x = TOOLBAR_SPACING; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - - // The channel box takes what the six buttons leave, so the toolbar stays on one row in a narrow column - let buttons = 2.0 * (MENU_BUTTON_WIDTH + TOOLBAR_SPACING) + 4.0 * (TOOLBAR_ICON_SIZE + TOOLBAR_SPACING); - let channel_width = (ui.available_width() - buttons).clamp(CHANNEL_BOX_MIN_WIDTH, CHANNEL_BOX_WIDTH); - ui.allocate_ui(vec2(channel_width, ICON_BUTTON_SIZE), |ui| { - egui::ComboBox::from_id_salt("layer_channel").width(channel_width).truncate().selected_text(tr(app.ui.layer_channel.label())).show_ui( - ui, - |ui| { - for channel in channels { - ui.selectable_value(&mut app.ui.layer_channel, channel, tr(channel.label())); - } - }, - ); - }); - ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| { - let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); - match &selected { - Some(layer) => effect_menu(app, ui, layer), - None => { - ui.label(RichText::new(tr("Select a layer")).color(tokens.text_dim)); - } - } - }) - .response - .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); - if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.paint", Value::Null); - } - if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.fill", Value::Null); - } - if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.add.group", Value::Null); - } - if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, TOOLBAR_ICON_SIZE).clicked() { - app.run("layer.remove", Value::Null); - } - }) - }); - // The empty state has no layers: the toolbar stays, greyed + let project_open = app.session.project_open; + ui.add_enabled_ui(project_open, |ui| crate::layer_toolbar::show(app, ui)); if !project_open { return; } @@ -301,45 +236,6 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool { } } -/// "Add effect" items for `layer`: content when it is the selected target, else the mask -fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app); - let target = if content { "content" } else { "mask" }; - ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") })); - - // Generators and compare masks always go to the mask; anchor points go where the others do - let items = [ - (tr("Add generator"), "effect.add.generator", json!({})), - (tr("Add paint"), "effect.add.paint", json!({"target": target})), - (tr("Add fill"), "effect.add.fill", json!({"target": target})), - (tr("Add levels"), "effect.add.levels", json!({"target": target})), - (tr("Add compare mask"), "effect.add.compare", json!({})), - (tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})), - (tr("Add anchor point"), "effect.add.anchor", json!({"target": target})), - ]; - for (label, command, params) in items { - if !ui.button(label).clicked() { - continue; - } - - if app.session.selected_layer() != Some(layer.id) { - app.run("layer.select", json!({"layer": layer.id.0})); - } - - let added = app.run(command, with(¶ms, json!({"layer": layer.id.0}))); - - // The neutral filter is a placeholder: its slot opens the picker to choose the real one - if command == "effect.add.filter" - && let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64()) - { - app.ui.dock.focus(crate::docking::Panel::Properties); - crate::filter_slot::open_picker_when_shown(ui.ctx(), effect); - } - - ui.close(); - } -} - /// Layer rows alternate between two shades so neighbours read as separate items. fn row_shade(tokens: &Tokens, index: usize) -> Color32 { if index.is_multiple_of(2) { tokens.row } else { tokens.row.lerp_to_gamma(tokens.row_hover, ALTERNATE_LAYER_SHADE) } @@ -361,14 +257,6 @@ pub fn layer_eye_colors(tokens: &Tokens, visible: bool) -> (Color32, Option Option<[(&'static str, &'static str); 3]> { if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; @@ -1932,6 +1854,15 @@ pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static s 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(false)) } + StackTarget::Effect(effect) => mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true)), + _ => None, + } +} + +/// Effect `effect`'s source, projection and sampling when it is a mask fill the Properties panel lays out like a fill (a decal's placed fill keeps its own rows) +fn mask_fill_of(project: &texturecraft_engine::core::Project, effect: LayerId) -> Option<(&Source, &Projection, Sampling)> { + match &project.effect(effect)?.1.kind { + EffectKind::Fill { source, projection, sampling } if projection.placed().is_none() => Some((source, projection, *sampling)), _ => None, } } @@ -1959,19 +1890,38 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { match (&selected, app.session.target) { // Polygon fill shows its own settings and says what it fills into, wherever it can fill _ if tool == Tool::PolygonFill && tool_usable => legacy_body(ui, |ui| polygon_fill_properties(app, ui)), - (Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Effect(effect)) if mask_fill_of(&app.session.doc.project, effect).is_some() => mask_fill_properties(app, ui, layer, effect), + (Some(layer), StackTarget::Effect(effect)) => { + effect_properties(app, ui, layer, effect); + let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_))); + if painted && grayscale_tab_open(app) { + crate::mask_paint_panel::grayscale_sheet(app, ui); + } + } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer), (Some(layer), StackTarget::Content) if layer.is_group() => legacy_body(ui, |ui| { - ui.label(RichText::new(tr("A folder blends its children (pass-through). Set per-channel opacity in the layer rows.")).color(tokens.text_dim)); - }), (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => legacy_body(ui, |ui| instance_properties(app, ui, layer)), (Some(layer), StackTarget::Mask) => legacy_body(ui, |ui| { - height_mask_section(app, ui, layer); - if tool_usable { - ui.separator(); - tool_properties(app, ui); + (Some(layer), StackTarget::Content) if layer.is_group() => crate::folder_properties::folder_properties(app, ui, layer.id), + (Some(layer), StackTarget::Content) if layer.instance_source().is_some() => crate::instance_properties::instance_properties(app, ui, layer), + (Some(layer), StackTarget::Mask) => { + legacy_body(ui, |ui| { + // Add mask > Height combination took its place; a layer saved with it on can still turn it off here + let height_shown = app.session.doc.project.content_layer(layer.id).is_some_and(|content| content.height_mask.enabled); + if height_shown { + height_mask_section(app, ui, layer); + } + if tool_usable { + if height_shown { + ui.separator(); + } + tool_properties(app, ui); + } + }); + if tool_usable && grayscale_tab_open(app) { + crate::mask_paint_panel::grayscale_sheet(app, ui); } - }), + } (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); }), @@ -1979,25 +1929,9 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// An instance draws its source: point there for edits. -fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { - let tk = Tokens::get(ui.ctx()); - let Some(src) = layer.instance_source() else { return }; - let p = &app.session.doc.project; - let name = p.layers.get(&src).map_or_else(|| tr("a missing layer").to_string(), |l| format!("\"{}\"", l.name)); - let set = p.locate(src).and_then(|(ts, _, _)| p.texture_sets.get(ts)).map(|t| t.name.clone()).unwrap_or_default(); - ui.label(caption(tr("Instance"))); - ui.label( - RichText::new(format!( - "{} {}", - ic::LINK, - trf("Draws {name} of texture set \"{set}\". Edits to the source show in every instance.", &[("name", &name), ("set", &set)]) - )) - .color(tk.text_dim), - ); - if ui.button(tr("Select source")).clicked() { - app.run("layer.select", json!({"layer": src.0})); - } +/// Whether the tool panel's third tab is open while a mask is painted: its Grayscale tab, drawn under the tool's rows +fn grayscale_tab_open(app: &TextureCraftApp) -> bool { + app.ui.props_tab == PropsTab::Material && !targets_content(app) } /// Mask with height: the layer's height shapes its mask transitions. @@ -2052,6 +1986,8 @@ const BRUSH_PREVIEW_GAP: f32 = 4.0; fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + let content = targets_content(app); + // Brush preview: a stroke and a sphere with the tool's material let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); let painter = ui.painter(); @@ -2070,14 +2006,28 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { 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); + // A mask stroke shows the gray it lays down and no material + let gray = match (content, &app.session.tool.mask_image) { + (false, None) => (app.session.tool.mask_value.clamp(0.0, 1.0) * 255.0).round() as u8, + _ => u8::MAX, + }; + let stroke_color = Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA)); + painter.add(egui::Shape::line(points, Stroke::new(stroke_width, stroke_color))); + if content { + 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); ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; + + // Painting a mask, the material tab becomes the Grayscale tab + let material = if content { (ic::SPHERE, tr("Material")) } else { (ic::SQUARE_HALF, tr("Grayscale")) }; for (tab, icon, tip) in - [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, ic::SPHERE, tr("Material"))] + [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, material.0, material.1)] { if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { app.ui.props_tab = tab; @@ -2107,7 +2057,9 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { match app.ui.props_tab { PropsTab::Brush => brush_section(app, ui), PropsTab::Alpha => alpha_section(app, ui), - PropsTab::Material => material_section(app, ui), + PropsTab::Material if content => material_section(app, ui), + // A mask's Grayscale tab is a property sheet, drawn by the caller past this panel's margins + PropsTab::Material => {} } } @@ -2669,7 +2621,7 @@ fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec Value { merged } -/// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). +/// Anchor points (content and mask ones) below layer `reader` in its texture set: (effect id, its name, or "layer / name" where two share a name; marked off in a mask turned off) 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 + + // (id, layer name, anchor name, in a mask, the mask off) + let anchors: Vec<(LayerId, &str, &str, bool, bool)> = project .walk(texture_set) .into_iter() .map(|(id, _)| id) .take_while(|id| *id != reader) .filter_map(|id| project.layers.get(&id)) .flat_map(|layer| { - let mask = layer.mask.iter().flat_map(|mask| { - mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(move |effect| { - let label = trf("{layer} / mask / {name}", &[("layer", &layer.name), ("name", &effect.name)]); - (effect.id, if mask.enabled { label } else { format!("{label} ({})", tr("Off")) }) - }) - }); - let content = layer - .content_effects - .iter() - .filter(|effect| matches!(effect.kind, EffectKind::Anchor)) - .map(|effect| (effect.id, format!("{} / {}", layer.name, effect.name))); - content.chain(mask).collect::>() + let content = layer.content_effects.iter().map(|effect| (effect, false, false)); + let mask = layer.mask.iter().flat_map(|mask| mask.effects.iter().map(move |effect| (effect, true, !mask.enabled))); + content + .chain(mask) + .filter(|(effect, _, _)| matches!(effect.kind, EffectKind::Anchor)) + .map(move |(effect, in_mask, off)| (effect.id, layer.name.as_str(), effect.name.as_str(), in_mask, off)) + }) + .collect(); + let shared = |name: &str| anchors.iter().filter(|anchor| anchor.2 == name).count() > 1; + anchors + .iter() + .map(|&(id, layer, name, in_mask, off)| { + let label = match (shared(name), in_mask) { + (false, _) => name.to_owned(), + (true, false) => format!("{layer} / {name}"), + (true, true) => trf("{layer} / mask / {name}", &[("layer", &layer), ("name", &name)]), + }; + (id, if off { format!("{label} ({})", tr("Off")) } else { label }) }) .collect() } @@ -2883,6 +2835,18 @@ pub(crate) fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Chan if mask_anchor_enabled(app, anchor) == Some(false) { format!("{label} ({})", tr("Off")) } else { label } } +/// A mask fill effect: its Fill, Symmetry and Grayscale sections as one sheet (its blending is on its row) +fn mask_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId) { + let Some((source, projection, sampling)) = + mask_fill_of(&app.session.doc.project, effect_id).map(|(source, projection, sampling)| (source.clone(), projection.clone(), sampling)) + else { + return; + }; + PropertySheet::show(ui, ("mask_fill_sheet", effect_id.0), |sheet| { + crate::mask_fill_panel::mask_fill_sheet(app, sheet, effect_id, source, projection, sampling, layer.id); + }); +} + /// Slider range of a fill's scale or tiling const FILL_SCALE_RANGE: std::ops::RangeInclusive = 0.01..=20.0; @@ -3104,31 +3068,30 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe match &effect.kind { EffectKind::Generator(generator) => legacy_body(ui, |ui| crate::generator_panel::generator_properties(app, ui, layer.id, id, generator)), EffectKind::Levels(levels) => legacy_body(ui, |ui| crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels)), + EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, projection, .. } => legacy_body(ui, |ui| { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); let name = match source { Source::Anchor { anchor, channel, .. } => { - let project = &app.session.doc.project; let owner = project.effect(*anchor).and_then(|(owner, _)| project.layers.get(&owner)); let read = if anchor_in_mask(app, *anchor) { "Mask" } else { channel.label() }; format!("{} · {}", owner.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()), tr(read)) - } + let current = match source { + Source::Anchor { anchor, channel, .. } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), Source::Image { name, .. } => name.clone(), + Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), }; - // Main's Grayscale slot on the new picker: patterns, images and a uniform value, or the anchor points below let (rect, source_response) = ui.allocate_exact_size(vec2(ui.available_width(), crate::filter_slot::SLOT_HEIGHT), Sense::click()); source_response.widget_info(|| egui::WidgetInfo { current_text_value: Some(name.clone()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, tr("Grayscale")) - }); let (ctx, popup) = (ui.ctx().clone(), ui.make_persistent_id(("fill_source_picker", id))); if source_response.clicked() { crate::resource_picker::toggle(&ctx, popup); - } let highlighted = source_response.hovered() || egui::Popup::is_id_open(&ctx, popup); crate::filter_slot::paint(ui, rect, (highlighted, source_response.has_focus()), None, (tr("Grayscale"), &name)); let current = crate::fill_material_panel::source_choice(source); @@ -3137,7 +3100,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe let mut tabs = crate::fill_material_panel::source_tabs(thumbs, &ctx, &images, &anchors, Color32::from_gray(204)); tabs.iter_mut().for_each(|tab| tab.groups.retain(|group| group.header != Some(tr("Alphas")))); tabs - }); let anchor_channel = if let Source::Anchor { channel, .. } = source { *channel } else { Channel::Height }; let params = match picked.filter(|choice| *choice != current) { Some(SourceChoice::Procedural(kind)) => Some(json!({"effect": id, "procedural": kind.label()})), @@ -3145,14 +3107,20 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe Some(SourceChoice::Uniform) => Some(json!({"effect": id, "uniform": 1.0})), Some(SourceChoice::Anchor(anchor)) => Some(json!({"effect": id, "anchor": anchor.0, "anchorChannel": anchor_channel.id()})), Some(SourceChoice::Import) => { - crate::menus::invoke(app, &ctx, "resource.import"); None + let source_response = combo(ui, tr("Source"), current, |ui| { + if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { + app.run("effect.set", json!({"effect": id, "value": 1.0})); } Some(SourceChoice::Alpha(_)) | None => None, - }; if let Some(params) = params { - app.run("effect.set", params); - } + if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); + } + if let Some(name) = image_menu(app, ui) { + app.run("effect.set", json!({"effect": id, "image": name})); + } + }); // The source selector accepts image drops from the Assets panel if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { @@ -3200,19 +3168,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe }); } EffectKind::Anchor => legacy_body(ui, |ui| { - ui.label(caption(tr("Anchor point"))); - let text = if anchor_in_mask(app, effect_id) { - tr("Records the mask value at this point. Fill effects and generators in masks above can read it.") - } else { - tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.") - }; - ui.label(RichText::new(text).color(tokens.text_dim)); - }), + EffectKind::Anchor => crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), EffectKind::Paint => legacy_body(ui, |ui| { let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { tr("Paint on the mesh to edit the layer content.") } else { - tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.") + tr("Paint on the mesh to edit this mask.") }; ui.label(RichText::new(hint).color(tokens.text_dim)); if app.session.tool_usable(app.session.tool.tool) { @@ -3247,6 +3208,18 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Filter(filter) => legacy_body(ui, |ui| filter_properties(app, ui, id, filter)), EffectKind::ColorSelection { colors, tolerance } => { legacy_body(ui, |ui| crate::color_selection_editor::color_selection_properties(app, ui, effect_id, colors, *tolerance)) + EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), + EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { + let settings = crate::compare_settings::CompareSettings { + op: *op, + constant: *value, + tolerance: *tolerance, + left: *left, + right: *right, + channel: *channel, + hardness: *hardness, + }; + crate::compare_properties::compare_properties(app, ui, layer, effect_id, settings); } other => legacy_body(ui, |ui| { ui.label(RichText::new(tr(other.name())).color(tokens.text_dim)); diff --git a/crates/ui-egui/src/exact_entry_open.rs b/crates/ui-egui/src/exact_entry_open.rs new file mode 100644 index 00000000..67abc1b5 --- /dev/null +++ b/crates/ui-egui/src/exact_entry_open.rs @@ -0,0 +1,5 @@ +//! 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_material_panel.rs b/crates/ui-egui/src/fill_material_panel.rs index c58c9807..4d4db43e 100644 --- a/crates/ui-egui/src/fill_material_panel.rs +++ b/crates/ui-egui/src/fill_material_panel.rs @@ -179,6 +179,7 @@ pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String { } /// One source's card (a channel's): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now +/// One source's card (a channel's, a mask fill's grayscale or a filter's image input): its slot (the row opens the source picker), then the source's own settings; `in_card`: only its slot row, inside the card open now pub(crate) fn source_card( app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, @@ -260,11 +261,23 @@ pub(crate) fn source_card( } } } + Source::Anchor { anchor, channel, .. } if slot_of == SourceSlot::Grayscale && !crate::dock::anchor_in_mask(app, anchor) => { + anchor_channel_row(app, sheet, base, reader, channel); + } Source::Image { .. } | Source::Anchor { .. } => {} } sheet.close_card(); } +/// The channel a mask fill reads from a content anchor point as gray (a mask anchor point reads its mask's one gray) +fn anchor_channel_row(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, base: &Value, reader: LayerId, channel: Channel) { + let project = &app.session.doc.project; + let channels = project.locate(reader).and_then(|(set, _, _)| project.texture_set(set).ok()).map(|set| set.channel_list()).unwrap_or_default(); + if let (Some(picked), _) = sheet.dropdown(tr("Channel"), channel, &channels, |option| tr(option.label()).to_string(), None) { + app.run("effect.set", with(base, json!({"anchorChannel": picked.id()}))); + } +} + /// Runs the fill command `choice` asks for on the slot (Import opens the import dialog) fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSlot, choice: SourceChoice, set: &impl Fn(Value) -> Value) { match choice { @@ -290,6 +303,7 @@ fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSl /// The picker's choice `source` is: a library alpha's image is its alpha pub(crate) fn source_choice(source: &Source) -> SourceChoice { +fn source_choice(source: &Source) -> SourceChoice { match source { Source::Uniform(_) => SourceChoice::Uniform, Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind), @@ -306,6 +320,7 @@ pub(crate) fn source_tabs( anchors: &[(LayerId, String)], uniform: Color32, ) -> Vec> { +fn source_tabs(thumbs: &mut Thumbs, ctx: &egui::Context, images: &ImageStore, anchors: &[(LayerId, String)], uniform: Color32) -> Vec> { let procedurals = ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect(); let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned())); @@ -419,8 +434,15 @@ fn procedural_rows( let mut edited = pattern.clone(); let mut edit = scale_and_contrast(sheet, &mut edited); - if sheet.fold(tr("Attributes"), None, false) { + + // A grayscale's card (a mask fill's, a filter input's) shows its Balance and Seed with Scale and Contrast; a material channel's keeps them in Attributes + if gray { edit = edit.or(balance_and_seed(sheet, &mut edited)); + } + if sheet.fold(tr("Attributes"), None, false) { + if !gray { + edit = edit.or(balance_and_seed(sheet, &mut edited)); + } if sheet.toggle(tr("Invert"), &mut edited.invert) { edit = edit.or(Some(("invert", json!(edited.invert), false))); } diff --git a/crates/ui-egui/src/fill_pictures.rs b/crates/ui-egui/src/fill_pictures.rs index 43b0a9d5..5a9fa0d7 100644 --- a/crates/ui-egui/src/fill_pictures.rs +++ b/crates/ui-egui/src/fill_pictures.rs @@ -370,6 +370,7 @@ 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/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index c41b7021..1fa4929f 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -60,9 +60,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: match groups.last_mut() { Some(group) if group.header == Some(tr(def.group)) => group.items.push(item), _ => groups.push(PickerGroup { header: Some(tr(def.group)), items: vec![item] }), - } - } vec![PickerTab { icon: ic::FUNNEL, name: tr("Filter"), groups }] + let mut items: Vec> = filter_effects() + .iter() + .filter(|def| def.mask || !on_mask) + .map(|def| ResourcePickerItem { + id: def.id, + label: tr(def.label).to_owned(), + caption: None, + picture: TilePicture::Texture(thumbs.filter(&ctx, def.id)), + }) + .collect(); + + // One kind of resource: one grid in name order, no group captions + items.sort_by_cached_key(|item| item.label.to_lowercase()); + vec![PickerTab { icon: ic::FUNNEL, name: tr("Filters"), groups: vec![PickerGroup { header: None, items }] }] }; let picked = resource_picker::show(&response, popup, &mut app.thumbs, current.as_ref(), current.is_some(), tabs); if let Some(id) = picked.filter(|id| Some(*id) != current) { diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 60e5a7b4..dce44a17 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -9,7 +9,7 @@ use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor use rayon::prelude::*; use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, kinds_for, tile_bytes}; -use texturecraft_engine::core::{BakedMap, Channel}; +use texturecraft_engine::core::{BakedMap, Channel, LayerId}; use texturecraft_engine::geom::Mesh; use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; @@ -19,11 +19,13 @@ use crate::bake_scene::{BakeSceneLink, CageUpload}; #[derive(Clone, Copy, Debug, PartialEq)] pub enum AuxView { MeshMap(BakedMap), - Mask(texturecraft_engine::core::LayerId), + Mask(LayerId), /// The quick mask being edited, over the base color. QuickMask, /// The project image of the view picker's "Other..." (`Session::view_image`) Image, + /// The image a color selection reads as its ID mask on its texture set, the ID mesh map on the others (its pick mode) + IdMask(LayerId), } /// A texture set's texels across and down, and its mesh material. @@ -286,29 +288,10 @@ impl GpuLink { } match aux_map { - Some(AuxView::MeshMap(map)) => { - for texture_set in 0..session.caches.len() { - // Streamed bake maps replace document maps while the bake is visible - let preview = session.bake_preview_baked(texture_set); - let baked = preview.or_else(|| session.doc.baked.get(&texture_set)); - let have = baked.and_then(|baked| baked.maps.get(&map)); - let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); - let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), revision); - if self.aux.get(&texture_set) == Some(&key) { - continue; - } - - let Some(cache) = session.caches.get(texture_set) else { continue }; - - let resolution = texturecraft_render::aux_size(cache.size); - let rgba = if preview.is_some() && have.is_none() { - texturecraft_render::mesh_maps::neutral_rgba(map, resolution) - } else { - texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) - }; - out.aux.push((texture_set, resolution, rgba)); - self.aux.insert(texture_set, key); - } + Some(AuxView::MeshMap(map)) => self.sync_mesh_maps(session, map, None, &mut out), + Some(AuxView::IdMask(effect)) => { + let shown = self.sync_id_mask(session, effect, &mut out); + self.sync_mesh_maps(session, BakedMap::Id, shown, &mut out); } Some(AuxView::Mask(id)) => { if let Some((texture_set, _, _)) = session.doc.project.locate(id) { @@ -382,6 +365,50 @@ impl GpuLink { self.bake_scene.sync(session, bake, &mut out); out } + + /// Queues mesh map `map` for every texture set but `skip` whose aux texture shows something else + fn sync_mesh_maps(&mut self, session: &Session, map: BakedMap, skip: Option, out: &mut SceneSync) { + for texture_set in 0..session.caches.len() { + if skip == Some(texture_set) { + continue; + } + + // Streamed bake maps replace document maps while the bake is visible + let preview = session.bake_preview_baked(texture_set); + let baked = preview.or_else(|| session.doc.baked.get(&texture_set)); + let have = baked.and_then(|baked| baked.maps.get(&map)); + let revision = have.map(|data| Arc::as_ptr(data) as u64).unwrap_or(0); + let key = (format!("{map:?}{}", if preview.is_some() { "~" } else { "" }), revision); + if self.aux.get(&texture_set) == Some(&key) { + continue; + } + + let Some(cache) = session.caches.get(texture_set) else { continue }; + let resolution = texturecraft_render::aux_size(cache.size); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(map, resolution) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) + }; + out.aux.push((texture_set, resolution, rgba)); + self.aux.insert(texture_set, key); + } + } + + /// Queues the image color selection `effect` reads as its ID mask on its texture set; the texture set it shows on, None when it reads the ID mesh map + fn sync_id_mask(&mut self, session: &Session, effect: LayerId, out: &mut SceneSync) -> Option { + let (texture_set, image) = session.id_mask_image(effect)?; + let cache = session.caches.get(texture_set)?; + let resolution = texturecraft_render::aux_size(cache.size); + let key = (format!("idMask{}:{resolution}", effect.0), Arc::as_ptr(image) as u64); + if self.aux.get(&texture_set) != Some(&key) + && let Some(rgba) = session.id_mask_view_rgba(effect, resolution) + { + out.aux.push((texture_set, resolution, rgba)); + self.aux.insert(texture_set, key); + } + Some(texture_set) + } } fn record_recreated_uploads(recreated: &mut BTreeMap>, reset: &[usize], sync: &SceneSync) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2206f55e..db514466 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod anchor_properties; mod angle_dial; mod ask; mod bake_job; @@ -18,6 +19,8 @@ mod bake_scene; mod color_management; mod color_picker; mod color_selection_editor; +mod compare_properties; +mod compare_settings; pub mod control; mod decal_drop; mod display_settings; @@ -25,6 +28,7 @@ pub mod dock; pub mod docking; mod drawn_icon; mod environment_picker; +mod exact_entry_open; mod export_panel; pub mod export_templates; mod export_window; @@ -35,27 +39,35 @@ mod fill_panel; mod fill_pictures; mod fill_symmetry_panel; mod filter_slot; +mod folder_properties; pub mod fonts; mod frame_gizmo; mod generator_panel; pub mod gpu; mod gray_slider; mod grid_tile; +mod histogram_cache; pub mod i18n; pub mod id_color_pick; #[cfg(not(target_arch = "wasm32"))] mod import_resources; mod inactive_set_hint; +mod instance_properties; pub mod keymap; pub mod layer_panel; +mod layer_toolbar; mod layout_dialog; +mod levels_display; mod levels_editor; mod levels_handle; mod levels_properties; mod line_snap; mod list_action; pub mod log_panel; +mod mask_fill_panel; +mod mask_paint_panel; mod mask_preview_image; +mod mask_source_choice; mod material_orb; mod material_preview_image; pub mod menus; @@ -101,6 +113,7 @@ pub mod properties_popup; mod property_sheet; mod query_field; mod rail_popup; +mod reference; pub mod render_mode; mod resolution_band; mod resource_panel; diff --git a/crates/ui-egui/src/move_on_model.rs b/crates/ui-egui/src/move_on_model.rs index 37a15b5c..b42bdbfb 100644 --- a/crates/ui-egui/src/move_on_model.rs +++ b/crates/ui-egui/src/move_on_model.rs @@ -350,6 +350,32 @@ mod tests { assert_eq!(projection(&harness, layer), slid, "no mode is left on"); } + /// A mask fill's warp frame moves with the hold as a fill layer's does: the frame slides, not only the image inside it + #[test] + fn holding_a_mask_fills_pad_slides_its_frame() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let (mut harness, layer) = fill_app("triplanar"); + harness.state_mut().run("mask.add.black", json!({"layer": layer.0})).unwrap(); + let effect = harness.state_mut().run("effect.add.fill", json!({"layer": layer.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + harness.state_mut().run("layer.fill.projection", json!({"effect": effect, "projection": "warp"})).unwrap(); + harness.state_mut().run("layer.select", json!({"layer": layer.0, "target": effect})).unwrap(); + harness.run_steps(4); + let mask_projection = |harness: &Harness| match &harness.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind { + EffectKind::Fill { projection, .. } => projection.clone(), + other => panic!("a mask fill: {other:?}"), + }; + let Projection::Warp { frame: before, uv: uv_before, .. } = mask_projection(&harness) else { panic!("a warp") }; + + let mut pointer = press_the_button(&mut harness); + assert_eq!(harness.state().moving_on_model, Some(MoveOnModel { layer, effect: Some(LayerId(effect)) }), "a press starts the hold"); + pointer.drags(&mut harness, vec2(-60.0, 0.0), 10, Modifiers::NONE); + let_go(&mut harness, &mut pointer); + + let Projection::Warp { frame: after, uv: uv_after, .. } = mask_projection(&harness) else { panic!("still a warp") }; + assert_ne!(after.offset, before.offset, "the frame slid"); + assert_eq!(uv_after, uv_before, "not only the image inside it"); + } + /// Losing the focus mid-hold (Alt+Tab) ends it as letting go does: one undo step, the pointer shown, and moves after it (egui still has the button down) leave the projection alone #[test] fn losing_the_window_focus_mid_hold_ends_it_as_letting_go_does() { diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index e0bd4da4..0e05486f 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -33,14 +33,11 @@ impl OrbEnvironment { fn from_hdr(bytes: &[u8]) -> Option { let decoded = image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; - - let rgb = decoded.into_rgb32f(); - let (pixels, _) = rgb.as_raw().as_chunks::<3>(); let rgba: Vec<[f32; 4]> = pixels.iter().map(|&[red, green, blue]| [red, green, blue, 1.0]).collect(); let env = EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false)?; - drop(rgb); - - Some(OrbEnvironment::of(&env)) + let rgb = decoded.to_rgb32f(); + let rgba: Vec<[f32; 4]> = rgb.pixels().map(|pixel| [pixel[0], pixel[1], pixel[2], 1.0]).collect(); + EnvImage::from_rgba(rgb.width(), rgb.height(), &rgba, false).map(|env| OrbEnvironment::of(&env)) } /// The built-in procedural studio, should the bundled one ever fail to decode diff --git a/crates/ui-egui/src/property_sheet/action_row.rs b/crates/ui-egui/src/property_sheet/action_row.rs new file mode 100644 index 00000000..8eaf51cd --- /dev/null +++ b/crates/ui-egui/src/property_sheet/action_row.rs @@ -0,0 +1,62 @@ +//! A row of section actions: buttons as wide as their words from the left, an on/off with its label at the right end + +use egui::{Align2, CornerRadius, FontId, Rect, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; + +use super::switch_control::PILL_SIZE; +use super::{ActionRowResponse, CONTROL_HEIGHT, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, TEXT_SIZE}; + +/// Air on each side of a button's word +const BUTTON_WORD_AIR: f32 = 9.0; + +/// Air between two buttons +const BUTTON_GAP: f32 = 6.0; + +/// Air between the toggle's label and its pill +const TOGGLE_LABEL_AIR: f32 = 9.0; + +/// From the right edge to the toggle's centre (the pill ends on the edge), and to its label's end +const TOGGLE_CENTER_INSET: f32 = PILL_SIZE.x / 2.0; +const TOGGLE_LABEL_INSET: f32 = PILL_SIZE.x + TOGGLE_LABEL_AIR; + +impl PropertySheet<'_> { + /// `buttons` (word, enabled) from the left edge, then `toggle_label` and its toggle at the right end + pub(crate) fn action_row(&mut self, buttons: &[(&str, bool)], toggle_label: &str, on: &mut bool) -> ActionRowResponse { + let row = self.take(ROW_HEIGHT); + let center_y = row.center().y; + self.drawn(center_y + CONTROL_HEIGHT / 2.0); + let font = FontId::proportional(TEXT_SIZE); + let tokens = self.tokens; + + let mut clicked = None; + let mut x = self.left; + for (index, (word, enabled)) in buttons.iter().enumerate() { + let width = self.text_width(word, font.clone()) + 2.0 * BUTTON_WORD_AIR; + let button = Rect::from_min_size(pos2(x, center_y - CONTROL_HEIGHT / 2.0), vec2(width, CONTROL_HEIGHT)); + let id = self.next_id(); + let response = self.ui.interact(button, id, if *enabled { Sense::click() } else { Sense::hover() }); + response.widget_info(|| WidgetInfo::labeled(Role::Button, *enabled, *word)); + if *enabled && response.clicked() { + clicked = Some(index); + } + + let fill = if *enabled && response.hovered() { tokens.row_hover } else { tokens.button }; + let painter = self.ui.painter(); + painter.rect(button, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + painter.text(button.center(), Align2::CENTER_CENTER, *word, font.clone(), if *enabled { tokens.text } else { tokens.text_dim }); + x = button.right() + BUTTON_GAP; + } + + let label_end = self.right - TOGGLE_LABEL_INSET; + let pill = pos2(self.right - TOGGLE_CENTER_INSET, center_y); + let hit = Rect::from_min_max(pos2(label_end - self.text_width(toggle_label, font.clone()), row.top()), pos2(self.right, row.bottom())); + let id = self.next_id(); + let response = self.ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + } + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, *on, toggle_label)); + self.ui.painter().text(pos2(label_end, center_y), Align2::RIGHT_CENTER, toggle_label, font, tokens.text); + self.pill(pill, *on, true); + ActionRowResponse { clicked, toggled: response.clicked() } + } +} diff --git a/crates/ui-egui/src/property_sheet/action_row_response.rs b/crates/ui-egui/src/property_sheet/action_row_response.rs new file mode 100644 index 00000000..fe7a383b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/action_row_response.rs @@ -0,0 +1,9 @@ +//! What happened on an action row this frame + +/// What an action row's user did this frame +pub(crate) struct ActionRowResponse { + /// The button clicked + pub(crate) clicked: Option, + /// Whether the toggle flipped + pub(crate) toggled: bool, +} diff --git a/crates/ui-egui/src/property_sheet/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs new file mode 100644 index 00000000..eddf9f72 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -0,0 +1,25 @@ +//! A factor slider: ×1 in the middle, halving to the left and doubling to the right + +use std::ops::RangeInclusive; + +use super::PropertySheet; +use super::slider::{KNOB_RADIUS, kept_in}; +use super::track::Track; + +impl PropertySheet<'_> { + /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed + pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> 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(0.0), ramp: false }; + let track_range = -doublings..=doublings; + let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); + if dragged.is_some() { + *factor = along.exp2(); + } + let shown = format!("×{:.2}", *factor); + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + Self::apply_typed(factor, entered, dragged) + } +} diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index 65806206..fe8a47dd 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -1,16 +1,24 @@ //! The Properties panel's rows, groups and controls, shared by every panel so they line up +mod action_row; +mod action_row_response; mod axis_rows; mod band_response; mod button_icon; mod choice; mod color_bar; mod color_picker_rows; +mod compare_row; +mod compare_row_response; mod eye_toggle; +mod factor_slider; mod group; mod hold_pad; +mod id_color_row; +mod id_color_row_response; mod info_icon; mod material_rows; +mod name_field; mod number_field; mod open_card; mod preview_block; @@ -18,6 +26,7 @@ mod preview_edit; mod preview_lower; mod preview_size; mod ramp_edit; +mod reference_row; mod row; mod row_lead; mod section_tabs; @@ -25,6 +34,7 @@ mod sheet_measure; mod slider; mod slot; mod slot_response; +mod source_card; mod stack_slider; mod switch_control; mod tooltip; @@ -35,8 +45,11 @@ mod value_text_draft; #[cfg(test)] mod tests; +pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; +pub(crate) use compare_row_response::CompareRowResponse; +pub(crate) use id_color_row_response::IdColorRowResponse; pub(crate) use number_field::NumberField; pub(crate) use preview_lower::PreviewLower; pub(crate) use preview_size::PreviewSize; @@ -111,6 +124,9 @@ 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 a hovered row's face +const ROW_RADIUS: u8 = 6; + /// Corner radius of dropdowns, fields and buttons const CONTROL_RADIUS: u8 = 4; diff --git a/crates/ui-egui/src/property_sheet/name_field.rs b/crates/ui-egui/src/property_sheet/name_field.rs new file mode 100644 index 00000000..6435fc3b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/name_field.rs @@ -0,0 +1,48 @@ +//! A name typed in place: a field in the controls column, outlined in the accent while it is typed in + +use egui::{CornerRadius, Stroke, StrokeKind}; + +use super::{CONTROL_RADIUS, PropertySheet, TEXT_SIZE}; +use crate::theme::semibold; + +/// Air before the field's text +const TEXT_INSET: i8 = 8; + +impl PropertySheet<'_> { + /// A field holding `name`; returns the new name once typing ends (Enter or a click elsewhere) with a changed, non-blank name. Escape keeps the old one + pub(crate) fn name_field(&mut self, label: &str, name: &str) -> Option { + let (control, _) = self.row(label); + let typing_id = self.next_id().with("typed"); + let typing = self.ui.memory(|memory| memory.has_focus(typing_id)); + + // The draft is read even when the focus already left (Shift+Tab, a field built earlier this frame took it): it commits below; it lasts one frame without the focus. Escape drops it, read from the frame's raw input as an app shortcut may already have taken the key + let escaped = + self.ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + if escaped { + self.ui.data_mut(|data| data.remove::(typing_id)); + } + let mut text = self.ui.data(|data| data.get_temp::(typing_id)).unwrap_or_else(|| name.to_owned()); + + let tokens = self.tokens; + let outline = Stroke::new(1.0, if typing { tokens.accent } else { tokens.field_border }); + self.ui.painter().rect(control, CornerRadius::same(CONTROL_RADIUS), tokens.field, outline, StrokeKind::Inside); + let edit = egui::TextEdit::singleline(&mut text) + .id(typing_id) + .font(semibold(TEXT_SIZE)) + .text_color(tokens.text) + .frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(TEXT_INSET, 0))) + .align(egui::Align2::LEFT_CENTER); + let response = self.ui.put(control.shrink(1.0), edit); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, label)); + self.drawn(control.bottom()); + + if response.has_focus() { + self.ui.data_mut(|data| data.insert_temp(typing_id, text)); + return None; + } + + self.ui.data_mut(|data| data.remove::(typing_id)); + let typed = text.trim(); + (response.lost_focus() && !escaped && !typed.is_empty() && typed != name).then(|| typed.to_owned()) + } +} diff --git a/crates/ui-egui/src/property_sheet/row.rs b/crates/ui-egui/src/property_sheet/row.rs index bd1f5cc4..be6936e2 100644 --- a/crates/ui-egui/src/property_sheet/row.rs +++ b/crates/ui-egui/src/property_sheet/row.rs @@ -195,6 +195,7 @@ impl PropertySheet<'_> { self.seen.label_width = self.seen.label_width.max(width); } + let text = self.tokens.text; if width <= self.column() - self.left - LABEL_MIN_AIR && !stack { self.paint_info(center_y); self.ui.painter().text(pos2(self.left + shift, center_y), Align2::LEFT_CENTER, label, font, text_color); @@ -215,6 +216,14 @@ impl PropertySheet<'_> { self.left } + /// A dim caption line above its control (Offset, Size…) + pub(crate) fn caption(&mut self, text: &str) { + let rect = self.take(CAPTION_LINE); + let dim = self.tokens.text_dim; + self.ui.painter().text(pos2(self.left, rect.top() + CAPTION_LINE / 2.0), Align2::LEFT_CENTER, text, FontId::proportional(SMALL_TEXT_SIZE), dim); + self.drawn(rect.bottom()); + } + /// A caret pointing down (open) or right (folded), centred on `center` pub(super) fn caret(&self, center: egui::Pos2, open: bool, color: egui::Color32) { let glyph = if open { ic::CARET_DOWN } else { ic::CARET_RIGHT }; diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 08f7eb58..14b8d740 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -75,6 +75,11 @@ impl PropertySheet<'_> { self.angle_shown(lead, degrees, range, false) } + /// An angle added to others: a signed track over `range` with its zero tick, the dial, and the value with its sign ("+30°") + pub(crate) fn relative_angle(&mut self, label: &str, degrees: &mut f32, range: RangeInclusive) -> Option { + self.angle_shown(RowLead::label(label), degrees, range, true) + } + /// [`Self::angle_led`], the value shown with its sign when `plus` fn angle_shown(&mut self, lead: RowLead<'_>, degrees: &mut f32, range: RangeInclusive, plus: bool) -> Option { let (control, center_y) = self.row_with(lead); diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 6717eb3c..468e42a1 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -276,6 +276,7 @@ impl PropertySheet<'_> { if dice_response.clicked() { *seed = next_seed(*seed); + *seed = texturecraft_engine::folder_cmds::next_seed(*seed); changed = true; } changed diff --git a/crates/ui-egui/src/property_sheet/source_card.rs b/crates/ui-egui/src/property_sheet/source_card.rs new file mode 100644 index 00000000..fc152f25 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/source_card.rs @@ -0,0 +1,67 @@ +//! A card for the layer something draws: its thumbnail, its name over a link and its texture set, and an arrow; a click goes to it + +use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::group::CARD_RADIUS; +use super::slot::THUMB_SIZE; +use super::{GROUP_GAP, PropertySheet, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::theme::semibold; + +/// Height of the card: 11 px of air above and below the thumbnail, as a slot card has +const CARD_HEIGHT: f32 = 48.0; + +/// Air between the section caption and the card, as above a slot card +const CARD_TOP_AIR: f32 = 6.0; + +/// From the left edge to the name, to the link glyph's centre and to the texture set +const NAME_LEFT: f32 = 36.0; +const LINK_CENTER: f32 = 41.0; +const SET_LEFT: f32 = 51.0; + +/// From the card's centre line up to the name's and down to the texture set's +const NAME_RISE: f32 = 7.0; +const SET_DROP: f32 = 9.0; + +/// Size of the link glyph and of the arrow +const LINK_SIZE: f32 = 12.0; +const ARROW_SIZE: f32 = 14.0; + +/// From the right edge to the arrow's centre +const ARROW_INSET: f32 = 7.0; + +impl PropertySheet<'_> { + /// The card of `name` in texture set `set`, right under its section caption; a `missing` one is dim, shows a broken link and takes no click. Returns true when it was clicked + pub(crate) fn source_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, set: &str, missing: bool) -> bool { + self.close_card(); + self.space(CARD_TOP_AIR); + let rect = self.take(CARD_HEIGHT); + let center_y = rect.center().y; + let face = self.bled_row(rect); + let id = self.next_id(); + let mut response = self.ui.interact(face, id, if missing { Sense::hover() } else { Sense::click() }); + if !missing { + response = response.on_hover_cursor(egui::CursorIcon::PointingHand); + } + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !missing, format!("{name} {set}"))); + let hovered = !missing && response.hovered(); + + let tokens = self.tokens; + let painter = self.ui.painter().clone(); + painter.rect_filled(face, CornerRadius::same(CARD_RADIUS), if hovered { tokens.button } else { tokens.row }); + thumbnail(&painter, Rect::from_min_size(pos2(self.left, center_y - THUMB_SIZE / 2.0), vec2(THUMB_SIZE, THUMB_SIZE))); + let (name_font, name_color) = if missing { (FontId::proportional(TEXT_SIZE), tokens.text_dim) } else { (semibold(TEXT_SIZE), tokens.text) }; + painter.text(pos2(self.left + NAME_LEFT, center_y - NAME_RISE), Align2::LEFT_CENTER, name, name_font, name_color); + let link = if missing { ic::LINK_BREAK } else { ic::LINK }; + painter.text(pos2(self.left + LINK_CENTER, center_y + SET_DROP), Align2::CENTER_CENTER, link, FontId::proportional(LINK_SIZE), tokens.text_dim); + painter.text(pos2(self.left + SET_LEFT, center_y + SET_DROP), Align2::LEFT_CENTER, set, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim); + if !missing { + let arrow_color = if hovered { tokens.text } else { tokens.text_dim }; + painter.text(pos2(self.right - ARROW_INSET, center_y), Align2::CENTER_CENTER, ic::ARROW_RIGHT, FontId::proportional(ARROW_SIZE), arrow_color); + } + self.drawn(rect.bottom()); + self.space(GROUP_GAP); + self.air_at = Some(self.cursor_y()); + response.clicked() + } +} diff --git a/crates/ui-egui/src/property_sheet/switch_control.rs b/crates/ui-egui/src/property_sheet/switch_control.rs index 1792d9e5..98b278e1 100644 --- a/crates/ui-egui/src/property_sheet/switch_control.rs +++ b/crates/ui-egui/src/property_sheet/switch_control.rs @@ -105,6 +105,12 @@ impl PropertySheet<'_> { self.dropdown_built(label, selected, || 0..options.len(), name, None).0 } + /// A boxed switch across the whole panel; the chosen word takes its colours from `tints` (several colours split the word between them) + pub(crate) fn wide_switch(&mut self, options: &[&str], selected: usize, tints: &[&[Color32]]) -> Option { + let control = self.wide_row(); + self.segments(control, options, selected, |index| tints.get(index).copied().unwrap_or_default(), None) + } + /// 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); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index d47ab16a..67c55f5e 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -7,6 +7,7 @@ use super::number_field::shown_number; use super::slot::next_seed; use super::{NumberField, PropertySheet}; use crate::theme::{Accent, Brightness, Tokens}; +use texturecraft_engine::folder_cmds::next_seed; mod filtering; mod gallery; @@ -99,11 +100,13 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } } - 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); + if sheet.fold("Edges", None, true) { + 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); @@ -115,6 +118,7 @@ fn gallery(ui: &mut egui::Ui, state: &mut Gallery) { } let band = sheet.band("Parameters", true, None, Some("3")); if band.open { + sheet.caption("Offset"); 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"); @@ -159,38 +163,6 @@ fn toggles_switches_and_pills_change_their_state() { 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() { @@ -234,6 +206,40 @@ fn culling_rows(ui: &mut egui::Ui, on: &mut [bool; 2]) { }); } +/// A section caption's switch and an action row's toggle over a dropdown +fn right_end_switches(ui: &mut egui::Ui, mirror: &mut bool) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "right end", |sheet| { + sheet.section_switch("Symmetry", true); + sheet.action_row(&[("Reset", true)], "Mirror", mirror); + sheet.dropdown("Filtering", Filtering::Nearest, &[Filtering::Nearest], Filtering::name, None); + }); + }); +} + +/// A switch at a caption's or a row's right end ends on the right padding, where a dropdown ends (they sat 3 px in) +#[test] +fn right_end_switches_end_where_a_dropdown_ends() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut harness = builder(Brightness::MediumDark).build_ui_state(right_end_switches, false); + harness.run_steps(3); + + let dropdown_right = harness.get_by_label("Nearest").rect().right(); + let pill_rights: Vec = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Rect(rect) if rect.rect.size() == super::switch_control::PILL_SIZE => Some(rect.rect.right()), + _ => None, + }) + .collect(); + + assert_eq!(pill_rights, [dropdown_right; 2], "the pills end at {pill_rights:?}, the dropdown at {dropdown_right}"); +} + /// A culling name too long for the label column moves every culling row's picture and switch, so the switches stay one column #[test] fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { @@ -246,6 +252,39 @@ fn culling_rows_keep_their_switches_in_one_column_when_a_name_is_long() { assert_eq!(short.right(), long.right(), "both switches end at one x: {short:?} vs {long:?}"); } +/// Under a section caption, an instance card (`instance` true) or a slot card; records where its thumbnail was painted +fn card_under_caption(ui: &mut egui::Ui, state: &mut (bool, std::cell::Cell>)) { + let (instance, thumbnail) = state; + let record = |_: &Painter, rect: Rect| thumbnail.set(Some(rect)); + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "card", |sheet| { + sheet.section("Caption", false); + if *instance { + sheet.source_card(&record, "Layer", "Set", false); + } else { + } + }); + }); +} + +/// Where the card under a caption paints its thumbnail +fn thumbnail_under_caption(instance: bool) -> Rect { + let mut harness = builder(Brightness::MediumDark).build_ui_state(card_under_caption, (instance, std::cell::Cell::new(None))); + harness.run_steps(3); + harness.state().1.get().unwrap_or_else(|| panic!("the card (instance: {instance}) paints no thumbnail")) +} + +/// The instance card keeps a card's air under its caption and above its thumbnail, as a slot card does (it sat 6 px higher) +#[test] +fn an_instance_card_sits_under_its_caption_as_a_slot_card_does() { + let slot = thumbnail_under_caption(false); + let instance = thumbnail_under_caption(true); + + assert_eq!(instance.top(), slot.top(), "the thumbnails start at one y: {instance:?} vs {slot:?}"); +} + /// A gray slider in a panel-wide column; records the column's right edge fn gray_row(ui: &mut egui::Ui, state: &mut (f32, f32)) { ui.set_width(PANEL_WIDTH); @@ -764,6 +803,34 @@ fn the_pickers_hex_field_ends_on_the_colour_fields_right_edge() { assert_eq!(hex.right(), field.right(), "the hex field ends at {}, the colour field at {}", hex.right(), field.right()); } +/// A comparison's two sources, its operators beside the first +fn compare_rows(ui: &mut egui::Ui) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "compare", |sheet| { + let names = ["Left source", "Right source", "Other source"]; + let name = |index: usize| names.get(index).copied().unwrap_or_default().to_owned(); + sheet.compare_rows((0, 1), &[0, 1, 2], name, [Color32::RED, Color32::BLUE], (&["Min", "Max"], 0)); + }); + }); +} + +/// A compare source's tagged button shows its value where its open list's options start, a dropdown's value x (it sat 2 px right) +#[test] +fn a_compare_sources_value_starts_where_its_lists_options_do() { + let mut harness = builder(Brightness::MediumDark).build_ui(compare_rows); + harness.run_steps(3); + let button = harness.get_by_role_and_label(egui::Role::ComboBox, "Left source").rect(); + + click_at(&mut harness, button.center()); + harness.run_steps(2); + + let button_word = painted_at(&harness, "Left source").into_iter().find(|at| button.contains(*at)).map(|at| at.x); + let option_word = painted_at(&harness, "Other source").first().map(|at| at.x); + assert!(button_word.is_some() && option_word == button_word, "the option's word at {option_word:?}, the button's at {button_word:?}"); +} + /// 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; diff --git a/crates/ui-egui/src/round_gizmo.rs b/crates/ui-egui/src/round_gizmo.rs index d0497fdf..21541abe 100644 --- a/crates/ui-egui/src/round_gizmo.rs +++ b/crates/ui-egui/src/round_gizmo.rs @@ -431,6 +431,7 @@ pub(crate) mod tests { use super::*; use crate::frame_gizmo::tests::{drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; + use crate::frame_gizmo::tests::{ball_app, drag, drag_frames, fill_app, fill_app_with, panel_xyz, press_and_move, projection}; fn gizmo(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> RoundGizmo { RoundGizmo::of(harness.state(), harness.state().viewport_rect).unwrap() @@ -670,6 +671,26 @@ pub(crate) mod tests { assert!(gizmo(&harness).rings.iter().all(|ring| !ring.is_empty()), "turned aside, every ring shows"); } + /// A paint layer on the ball whose mask holds a fill effect (selected) projecting `kind`: painting there paints the mask + fn mask_fill_app(kind: &str) -> (egui_kittest::Harness<'static, TextureCraftApp>, LayerId) { + let mut harness = ball_app(false); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = harness.state_mut().session.import_resource_bytes("decal.png", png).unwrap(); + harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); + let texturecraft_engine::StackTarget::Effect(effect) = harness.state().session.target else { panic!("the mask fill is selected") }; + harness.state_mut().run("layer.fill.projection", json!({"effect": effect.0, "projection": kind})).unwrap(); + harness.run_steps(2); + (harness, effect) + } + + fn effect_projection(harness: &egui_kittest::Harness<'_, TextureCraftApp>, effect: LayerId) -> Projection { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + texturecraft_engine::core::EffectKind::Fill { projection, .. } => projection.clone(), + other => panic!("a fill effect: {other:?}"), + } + } + /// A point on the model clear of every handle of the shown gizmo pub(crate) fn on_the_model_off_the_handles(harness: &egui_kittest::Harness<'_, TextureCraftApp>) -> Pos2 { let app = harness.state(); @@ -687,6 +708,31 @@ pub(crate) mod tests { .expect("the model shows past the handles") } + /// With every projection, a drag on the model away from the gizmo leaves the projection put (and paints nothing: no tool acts on a selected fill effect); only a drag that starts on a handle moves the projection + #[test] + fn only_a_handle_moves_the_projection_and_any_other_drag_on_the_model_leaves_it() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + for kind in ["planar", "warp", "triplanar", "spherical", "cylindrical"] { + let (mut harness, effect) = mask_fill_app(kind); + let rect = harness.state().viewport_rect; + let before = effect_projection(&harness, effect); + let steps = harness.state().session.history_labels().len(); + + let from = on_the_model_off_the_handles(&harness); + drag(&mut harness, from, from + vec2(30.0, 0.0), Modifiers::NONE); + assert_eq!(effect_projection(&harness, effect), before, "{kind}: a drag off the handles leaves the projection alone"); + assert_eq!(harness.state().session.history_labels().len(), steps, "{kind}: and adds no undo step"); + + let center = match RoundGizmo::of(harness.state(), rect) { + Some(round) => round.center, + None => crate::frame_gizmo::FrameGizmo::of(harness.state(), rect).unwrap_or_else(|| panic!("{kind}: a gizmo shows")).center, + }; + drag(&mut harness, center, center + vec2(0.0, -30.0), Modifiers::NONE); + assert_ne!(effect_projection(&harness, effect), before, "{kind}: the centre square moves it"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "{kind}: one step, no stroke"); + } + } + /// A sphere has one size handle (it only scales evenly); a tri-planar box scales evenly from its corner and along one direction from a face's double arrow #[test] fn a_sphere_scales_from_one_dot_and_a_tri_planar_box_from_its_corner_and_faces() { diff --git a/crates/ui-egui/src/slot_thumbnail.rs b/crates/ui-egui/src/slot_thumbnail.rs index d739e42a..16cebc02 100644 --- a/crates/ui-egui/src/slot_thumbnail.rs +++ b/crates/ui-egui/src/slot_thumbnail.rs @@ -1,6 +1,7 @@ //! The picture a slot card shows of a fill channel's source use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, TextureHandle, TextureId, pos2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Stroke, StrokeKind, TextureHandle, TextureId, pos2}; use egui_phosphor::regular as ic; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::Source; @@ -38,6 +39,12 @@ pub(crate) fn thumbnail(app: &mut TextureCraftApp, ctx: &egui::Context, source: /// The glyph size of a slot without a picture const GLYPH_SIZE: f32 = 14.0; +/// Corner radius of a rounded slot picture and of the empty square +pub(crate) const THUMB_RADIUS: u8 = 3; + +/// How far the empty square's outline sits inside the slot's square +const EMPTY_SLOT_INSET: f32 = 1.0; + /// The whole of a texture, as the part of it a picture shows pub(crate) const FULL_UV: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); @@ -60,3 +67,8 @@ pub(crate) fn paint_thumbnail(painter: &Painter, rect: Rect, thumbnail: &SlotThu } } } + +/// A slot without a picture (no ID map, a missing source): an empty outlined square +pub(crate) fn paint_empty_slot(painter: &Painter, rect: Rect, tokens: &Tokens) { + painter.rect_stroke(rect.shrink(EMPTY_SLOT_INSET), CornerRadius::same(THUMB_RADIUS), Stroke::new(1.0, tokens.text_dim), StrokeKind::Inside); +} diff --git a/crates/ui-egui/src/source_slot.rs b/crates/ui-egui/src/source_slot.rs index b52bf7a3..4f353f73 100644 --- a/crates/ui-egui/src/source_slot.rs +++ b/crates/ui-egui/src/source_slot.rs @@ -9,6 +9,8 @@ use crate::i18n::tr; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum SourceSlot { Channel(Channel), + /// A mask fill's source, read as gray 0..1 + Grayscale, } impl SourceSlot { @@ -16,6 +18,7 @@ impl SourceSlot { pub(crate) fn name(self) -> &'static str { match self { SourceSlot::Channel(channel) => tr(channel.label()), + SourceSlot::Grayscale => tr("Grayscale"), } } @@ -27,9 +30,11 @@ impl SourceSlot { } /// The value Uniform and the slot's × give it + /// The value Uniform and the slot's × give it: a new mask fill's white for a grayscale pub(crate) fn default_value(self) -> [f32; 3] { match self { SourceSlot::Channel(channel) => channel.default_value(), + SourceSlot::Grayscale => [1.0; 3], } } @@ -39,6 +44,7 @@ impl SourceSlot { } /// A procedural's two ends when it is picked: a softer part of the channel's range + /// A procedural's two ends when it is picked: a gray fill spans the whole range, a channel a softer part of it pub(crate) fn procedural_ends(self) -> ([f32; 3], [f32; 3]) { /// Base color stays off pure black and white, which read as unlit or blown out const BASE_COLOR_ENDS: ([f32; 3], [f32; 3]) = ([0.15; 3], [0.85; 3]); @@ -57,9 +63,11 @@ impl SourceSlot { } /// The fill command's fields naming the slot + /// The fill command's fields naming the slot (a grayscale has no channel) pub(crate) fn fields(self) -> Value { match self { SourceSlot::Channel(channel) => json!({"channel": channel.id()}), + SourceSlot::Grayscale => json!({}), } } @@ -67,6 +75,7 @@ impl SourceSlot { pub(crate) fn key(self) -> &'static str { match self { SourceSlot::Channel(channel) => channel.id(), + SourceSlot::Grayscale => "grayscale", } } } diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 33f94c62..05b2eb8f 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -397,45 +397,12 @@ 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() @@ -445,23 +412,6 @@ 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 { @@ -479,7 +429,18 @@ mod tests { #[test] fn every_brightness_and_accent_reads() { - let contrast = contrast_ratio; + // 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) + }; 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/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9014c9a3..b85e073a 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -8,7 +8,7 @@ use std::sync::{Arc, Weak}; use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions}; use texturecraft_engine::compose::{ImageRes, ImageStore}; -use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::core::{BakedMap, ProceduralKind}; use texturecraft_engine::paint::presets::BrushPreset; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::texel::linear_to_srgb; @@ -50,6 +50,8 @@ pub struct Thumbs { saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, + /// Each texture set's ID mesh map preview, with the map it shows (a rebake's new map replaces it) + id_maps: HashMap>, TextureHandle)>, /// (frame, thumbnails rendered in it) budget: (u64, usize), /// Renders the orb thumbnails and the big previews @@ -91,6 +93,30 @@ impl Thumbs { texture } + /// Cached preview of texture set `set_index`'s ID mesh map, its colors as stored (the ID view's); a rebake makes a new one + pub fn id_mesh_map(&mut self, ctx: &egui::Context, set_index: usize, baked: &texturecraft_engine::compose::BakedMaps) -> Option { + let data = baked.maps.get(&BakedMap::Id)?; + + // The weak reference keeps the shown map's allocation, so a new map never takes its address + if let Some((shown, texture)) = self.id_maps.get(&set_index) + && std::ptr::eq(shown.as_ptr(), Arc::as_ptr(data)) + { + return Some(texture.clone()); + } + + let mut image = ColorImage::filled([IMAGE_PX, IMAGE_PX], Color32::TRANSPARENT); + for (index, pixel) in image.pixels.iter_mut().enumerate() { + let uv = [((index % IMAGE_PX) as f32 + 0.5) / IMAGE_PX as f32, ((index / IMAGE_PX) as f32 + 0.5) / IMAGE_PX as f32]; + if let Some(color) = baked.sample_uv(BakedMap::Id, uv) { + let [red, green, blue] = color.map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8); + *pixel = Color32::from_rgb(red, green, blue); + } + } + let texture = ctx.load_texture(format!("mesh_id_{set_index}"), image, TextureOptions::NEAREST); + self.id_maps.insert(set_index, (Arc::downgrade(data), texture.clone())); + Some(texture) + } + /// Cached preview of an image resource (64 px, letterboxed) pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { if let Some((cached_image, texture)) = self.images.get(name) @@ -403,8 +429,11 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) { #[cfg(test)] mod tests { use super::*; + use std::collections::BTreeMap; use std::sync::atomic::{AtomicUsize, Ordering}; + use texturecraft_engine::compose::BakedMaps; + use crate::orb_shape::OrbShape; static NEXT_FILE: AtomicUsize = AtomicUsize::new(0); @@ -612,4 +641,24 @@ mod tests { eprintln!("cached previews after clearing resources: {}", thumbs.images.len()); assert!(thumbs.images.is_empty()); } + + /// A 2 × 2 ID map of one red, in a map of its own + fn id_map() -> BakedMaps { + BakedMaps { resolution: 2, maps: BTreeMap::from([(BakedMap::Id, Arc::new([1.0, 0.0, 0.0].repeat(4)))]) } + } + + #[test] + fn an_id_map_preview_is_kept_while_its_map_lives_and_a_rebaked_map_gets_a_new_one() { + let ctx = egui::Context::default(); + let mut thumbs = Thumbs::default(); + let baked = id_map(); + + let first = thumbs.id_mesh_map(&ctx, 0, &baked).map(|texture| texture.id()); + let shared = thumbs.id_mesh_map(&ctx, 0, &baked.clone()).map(|texture| texture.id()); + let rebaked = thumbs.id_mesh_map(&ctx, 0, &id_map()).map(|texture| texture.id()); + + assert!(first.is_some()); + assert_eq!(shared, first, "the same map keeps its cached preview"); + assert_ne!(rebaked, first, "a new map of the same texture set, even of equal texels, gets a new preview"); + } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 13bf3900..47b7ab56 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -45,6 +45,21 @@ pub fn set_focus_picking(ctx: &egui::Context, on: bool) { ctx.data_mut(|d| d.insert_temp(focus_pick_id(), on)); } +/// What the views' aux texture shows: the quick mask being edited, a mesh map, the image a pending ID pick reads instead of the ID mesh map, or a mask +fn aux_view(app: &TextureCraftApp) -> Option { + match (app.session.view, app.picking_id_color) { + _ if quick_mask_shown(app) => Some(crate::gpu::AuxView::QuickMask), + (ViewMode::MeshMap(BakedMap::Id), Some(pick)) => Some(crate::gpu::AuxView::IdMask(pick.effect)), + (ViewMode::MeshMap(map), _) => Some(crate::gpu::AuxView::MeshMap(map)), + (ViewMode::Mask(id), _) => Some(crate::gpu::AuxView::Mask(id)), + (ViewMode::Image, _) => Some(crate::gpu::AuxView::Image), + _ if app.ui.mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => { + Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)) + } + _ => None, + } +} + /// The viewport dock tab: the paint bar, then the 3D and 2D views in the chosen layout with the mode's overlays pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { let mode = app.ui.mode; @@ -98,14 +113,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { finish_unavailable_tool_gestures(app, pending_2d_endpoint); crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); - let aux_view = match app.session.view { - _ if quick_mask_shown(app) => Some(crate::gpu::AuxView::QuickMask), - ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), - ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), - ViewMode::Image => Some(crate::gpu::AuxView::Image), - _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), - _ => None, - }; + let aux_view = aux_view(app); let mut sync = PendingSync(Some(aux_view)); let full = ui.available_rect_before_wrap(); path_keys(app, ui); @@ -2623,6 +2631,24 @@ mod tests { assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); } + #[test] + fn picking_shows_the_id_mask_its_color_selection_reads() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + use texturecraft_engine::{StackTarget, execute}; + + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!(null)).unwrap(); + let effect = texturecraft_engine::core::LayerId(execute(&mut session, "mask.add.colorSelection", &json!(null)).unwrap()["effect"].as_u64().unwrap()); + session.target = StackTarget::Effect(effect); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(2); + + crate::id_color_pick::IdColorPick::start(harness.state_mut(), effect, None); + assert_eq!(aux_view(harness.state()), Some(crate::gpu::AuxView::IdMask(effect)), "the pick's own ID mask"); + crate::id_color_pick::IdColorPick::end(harness.state_mut()); + assert_eq!(aux_view(harness.state()), None, "the earlier 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() { diff --git a/crates/ui-egui/tests/it/anchor_point.rs b/crates/ui-egui/tests/it/anchor_point.rs new file mode 100644 index 00000000..2e7d7f3a --- /dev/null +++ b/crates/ui-egui/tests/it/anchor_point.rs @@ -0,0 +1,103 @@ +//! The anchor point in Properties: its name typed in place, and the References band listing what reads it (a click selects that) + +use egui::accesskit::Role; +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A fill with an anchor point in its mask, read by the mask fill of a layer above, the anchor point selected: (harness, anchor, reading layer, reading effect) +fn anchor_harness() -> (Harness<'static, TextureCraftApp>, LayerId, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let low = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": low, "name": "Cavity Dirt"})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": low, "target": "mask", "value": 0.4})).unwrap(); + let anchor = LayerId(execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap()["effect"].as_u64().unwrap()); + let top = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": top, "name": "Rust"})).unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": top})).unwrap(); + let reader = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": top, "anchor": anchor.0})).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": low, "target": anchor.0})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, anchor, LayerId(top.as_u64().unwrap()), reader) +} + +fn anchor_name(harness: &Harness<'_, TextureCraftApp>, anchor: LayerId) -> String { + harness.state().session.doc.project.effect(anchor).unwrap().1.name.clone() +} + +/// Clicks the name field, selects its text and types `text` +fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { + harness.get_by_role_and_label(Role::TextInput, "Anchor point name").click(); + harness.run_steps(SETTLE_FRAMES); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness.event(egui::Event::Text(text.into())); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_name_field_renames_on_enter_in_one_undo_step_and_escape_keeps_it() { + let (mut harness, anchor, _, _) = anchor_harness(); + assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "a mask anchor point is named after its layer"); + let steps = harness.state().session.history_labels().len(); + type_name(&mut harness, "Edges"); + assert_eq!(anchor_name(&harness, anchor), "Cavity Dirt mask", "nothing changes while typing"); + harness.key_press(Key::Enter); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step"); + + type_name(&mut harness, "Never applied"); + harness.key_press(Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "Escape keeps the name"); +} + +#[test] +fn a_click_on_a_reference_selects_what_reads_the_anchor_point() { + let (mut harness, _, top, reader) = anchor_harness(); + assert!(harness.state().session.selected_layer() != Some(top)); + harness.get_by_role_and_label(Role::Button, "Rust Mask fill").click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(top)); + assert_eq!(harness.state().session.target, StackTarget::Effect(reader)); +} + +/// A reader's name longer than the band is cut short before its kind, and hovering the row shows it in full +#[test] +fn a_long_reference_name_is_cut_short_and_shows_in_full_on_hover() { + const LONG_NAME: &str = "Rust along every lower edge of the hull plates where rain water collects and runs"; + // Frames past the tooltip delay + const TOOLTIP_FRAMES: usize = 60; + let (mut harness, _, top, _) = anchor_harness(); + harness.state_mut().run("layer.rename", json!({"layer": top.0, "name": LONG_NAME})); + harness.run_steps(REDRAW_FRAMES); + let row = harness.get_by_role_and_label(Role::Button, &format!("{LONG_NAME} Mask fill")).rect(); + let before = harness.query_all_by_label(LONG_NAME).count(); + + harness.hover_at(row.center()); + harness.run_steps(TOOLTIP_FRAMES); + + // The row's own label is its name and kind; the Layers row shows the name too + assert_eq!(harness.query_all_by_label(LONG_NAME).count(), before + 1, "the tooltip carries the full name"); +} + +#[test] +fn a_name_typed_then_left_with_shift_tab_is_kept() { + let (mut harness, anchor, _, _) = anchor_harness(); + let steps = harness.state().session.history_labels().len(); + type_name(&mut harness, "Edges"); + + // The focus moves back to a control drawn before the field: the field never sees itself focused again + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(anchor_name(&harness, anchor), "Edges", "the typed name is kept"); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "in one undo step"); +} diff --git a/crates/ui-egui/tests/it/compare_mask_rows.rs b/crates/ui-egui/tests/it/compare_mask_rows.rs new file mode 100644 index 00000000..daf7af52 --- /dev/null +++ b/crates/ui-egui/tests/it/compare_mask_rows.rs @@ -0,0 +1,85 @@ +//! The compare mask in Properties: channel, the two sources with the operator between them, the constant, tolerance and hardness rows + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{Channel, CompareOp, CompareSource, EffectKind, LayerId}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// A fill over a fill, a compare mask on the top one, selected: (harness, compare effect) +fn compare_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"roughness": 0.2})).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.6})).unwrap()["layer"].clone(); + let effect = LayerId(execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].as_u64().unwrap()); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); + (harness, effect) +} + +/// (left, op, right, channel, constant, tolerance, hardness) of compare mask `effect` +fn compare(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> (CompareSource, CompareOp, CompareSource, Channel, f32, f32, f32) { + match harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Compare { left, op, right, channel, value, tolerance, hardness } => (left, op, right, channel, value, tolerance, hardness), + ref other => panic!("a compare mask, found {other:?}"), + } +} + +fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn has_slider(harness: &Harness<'_, TextureCraftApp>, label: &str) -> bool { + harness.query_by_role_and_label(Role::Slider, label).is_some() +} + +/// Opens the list of the source showing `name` and picks `option` +fn pick_source(harness: &mut Harness<'_, TextureCraftApp>, name: &str, option: &str) { + harness.get_by_role_and_label(Role::ComboBox, name).click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ListBoxOption, option).click(); + harness.run_steps(REDRAW_FRAMES); +} + +#[test] +fn the_rows_show_and_edit_the_comparison_one_undo_step_each() { + let (mut harness, effect) = compare_harness(); + assert!(crate::levels_editor::painted_text(&harness, "COMPARE MASK"), "the section caption"); + assert_eq!(compare(&harness, effect).0, CompareSource::ThisLayer); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Layers below").is_some(), "the right source"); + assert!(has_slider(&harness, "Hardness") && !has_slider(&harness, "Constant") && !has_slider(&harness, "Tolerance")); + + let steps = undo_steps(&harness); + pick_source(&mut harness, "Layers below", "Constant"); + assert_eq!(compare(&harness, effect).2, CompareSource::Constant); + assert_eq!(undo_steps(&harness), steps + 1, "one undo step"); + assert!(has_slider(&harness, "Constant"), "a constant side shows its value"); + + pick_source(&mut harness, "This layer", "This mask"); + assert_eq!(compare(&harness, effect).0, CompareSource::ThisMask); + + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("≈")).click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(compare(&harness, effect).1, CompareOp::WithinTolerance); + assert!(has_slider(&harness, "Tolerance"), "within tolerance shows its tolerance"); + + pick_source(&mut harness, "Height", "Roughness"); + assert_eq!(compare(&harness, effect).3, Channel::Roughness); + assert_eq!(undo_steps(&harness), steps + 4); +} + +#[test] +fn a_source_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outside() { + let (mut harness, effect) = compare_harness(); + crate::assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + harness.get_by_role_and_label(Role::ComboBox, "Layers below").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_role_and_label(Role::ComboBox, "Layers below").rect() + }); + assert_eq!(compare(&harness, effect).2, CompareSource::LayersBelow, "nothing changed"); +} diff --git a/crates/ui-egui/tests/it/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index fdd04351..ba6c7372 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,7 +1,7 @@ -//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right. +//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; @@ -11,6 +11,11 @@ fn id(v: Value, key: &str) -> u64 { v[key].as_u64().unwrap() } +/// The blending the rows show and set: the displayed channel's (base color by default) +fn base_color_blend(effect: &texturecraft_engine::core::Effect) -> texturecraft_engine::core::ChannelBlend { + effect.blend_of(Some(texturecraft_engine::core::Channel::BaseColor)) +} + /// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`. fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) { let start = harness.get_by_label(from).rect().center(); @@ -51,7 +56,7 @@ fn dragging_an_effect_row_reorders_its_stack() { assert_eq!(order(&harness), [a, c, b]); } -/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows. +/// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -62,6 +67,8 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(4); let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); assert_eq!(effect, effect_of(&harness).id.0); + harness.state_mut().ui.layer_material_view = false; + harness.run_steps(2); // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field let row = harness.get_by_label("Effect A").rect(); @@ -73,7 +80,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(2); harness.get_by_label("Multiply").click(); harness.run_steps(3); - assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply); + assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "the row sets the displayed channel's"); + let roughness = effect_of(&harness).blend_of(Some(texturecraft_engine::core::Channel::Roughness)).mode; + assert_eq!(roughness, texturecraft_engine::core::BlendMode::Normal, "the other channels keep theirs"); let history = harness.state().session.history_labels().len(); let opacity_at = egui::pos2(pair_right - 20.0, row.center().y); @@ -83,7 +92,8 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.run_steps(2); harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(3); - assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity); + let opacity = base_color_blend(&effect_of(&harness)).opacity; + assert!(opacity < 0.9, "dragging the field to the left lowers the opacity: {opacity}"); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step"); } @@ -106,14 +116,57 @@ fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() { harness.run_steps(2); harness.hover_at(opacity_at + egui::vec2(8.0, 8.0)); harness.run_steps(2); - assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity"); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0, "the drag started without changing the opacity"); harness.hover_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(2); harness.drop_at(opacity_at - egui::vec2(100.0, 0.0)); harness.run_steps(3); - assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity); + let opacity = base_color_blend(&effect_of(&harness)).opacity; + assert!(opacity < 0.9, "the drag lowered the opacity: {opacity}"); assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step"); harness.state_mut().session.undo().unwrap(); - assert_eq!(effect_of(&harness).opacity, 1.0); - assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); + assert_eq!(base_color_blend(&effect_of(&harness)).opacity, 1.0); + assert_eq!(base_color_blend(&effect_of(&harness)).mode, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change"); +} + +/// An effect row's menu holds Blending options: the channel the Layers panel shows lends its blend mode to every channel (none in the Material view), and Paste waits for a Copy +#[test] +fn an_effect_rows_blending_options_reach_every_channel() { + use texturecraft_engine::core::{BlendMode, Channel}; + + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect"); + execute(&mut session, "effect.set", &json!({"effect": effect, "channel": "baseColor", "blend": "Multiply"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone(); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Normal); + + let open_blending_options = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.get_by_label("Effect A").click_secondary(); + harness.run_steps(3); + harness.get_by_label("Blending options").click(); + harness.run_steps(3); + }; + open_blending_options(&mut harness); + assert!(harness.get_by_label("Use this blend mode on every channel").accesskit_node().is_disabled(), "the Material view shows no channel to lend"); + assert!(harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "nothing is copied yet"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // With Base color shown, the row reads its Multiply and lends it to every channel + harness.state_mut().ui.layer_material_view = false; + harness.run_steps(3); + open_blending_options(&mut harness); + harness.get_by_label("Use this blend mode on every channel").click(); + harness.run_steps(3); + assert_eq!(effect_of(&harness).blend_of(Some(Channel::Roughness)).mode, BlendMode::Multiply); + + open_blending_options(&mut harness); + harness.get_by_label("Copy channel blending").click(); + harness.run_steps(3); + open_blending_options(&mut harness); + assert!(!harness.get_by_label("Paste channel blending").accesskit_node().is_disabled(), "a copy can be pasted"); } diff --git a/crates/ui-egui/tests/it/effect_sliders.rs b/crates/ui-egui/tests/it/effect_sliders.rs index 3a4a2e63..a2b4e0de 100644 --- a/crates/ui-egui/tests/it/effect_sliders.rs +++ b/crates/ui-egui/tests/it/effect_sliders.rs @@ -7,7 +7,7 @@ use serde_json::json; use texturecraft_engine::core::{EffectKind, LayerId}; use texturecraft_ui_egui::TextureCraftApp; -/// The sample session with its first generator effect selected, and that effect's id. +/// The sample session with its first generator effect selected, and that effect's id fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let (layer, effect) = session @@ -80,28 +80,6 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } -/// The combo box in the row of the levels editor's Reset button. -fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = harness.get_by_label("Reset").rect().center().y; - harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() -} - -/// A content levels effect offers a channel for its histogram; picking one keeps it selected. -#[test] -fn content_levels_pick_the_histogram_channel() { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); - texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap(); - texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); - harness.run_steps(4); - assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel"); - channel_picker(&harness).click(); - harness.run_steps(2); - harness.get_by_label("Roughness").click(); - harness.run_steps(3); - assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays"); -} - #[test] fn clicking_a_slider_track_applies_it() { let (mut harness, effect) = selected_generator(); @@ -113,7 +91,7 @@ fn clicking_a_slider_track_applies_it() { assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect)); } -/// The number field in the row of the slider labelled `label`. +/// The number field in the row of the slider labelled `label` fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { let row = harness.get_by_label(label).rect().center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs index eedbb9c2..a52a385b 100644 --- a/crates/ui-egui/tests/it/empty_start.rs +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -107,6 +107,8 @@ fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { // The picker shows "Material" right of the tool shelf and the Assets panel and left of the right column: one per view in the split layout let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && (300.0..1200.0).contains(x)).count(); + // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); assert_eq!(pickers, 2, "each of the two views keeps its view picker"); diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index bd7222b8..6863656e 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -7,6 +7,7 @@ use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; use crate::fill_support::click_node; +use crate::fill_support::{click_label, click_node}; /// 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) { @@ -126,35 +127,32 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - // The mask fill's slot opens the source picker - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").scroll_to_me(); - harness.run_steps(30); - harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); - harness.run_steps(3); // The search field has the focus: it brings the tile into the grid's view + // The mask fill's Grayscale slot opens the source picker; its search finds the image + click_node(&mut harness, egui::Role::ComboBox, "Grayscale"); + harness.run_steps(2); harness.event(egui::Event::Text("mask".into())); harness.run_steps(2); harness.get_by_role_and_label(egui::Role::ListBoxOption, &image_name).click(); + click_node(&mut harness, egui::Role::ListBoxOption, &image_name); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { source: Source::Image { name, .. }, .. } if name == &image_name)); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("UV projection")).unwrap().click(); + click_node(&mut harness, egui::Role::ComboBox, "UV projection"); harness.run_steps(2); - harness.get_by_label("Tri-planar projection").click(); + click_label(&mut harness, "Tri-planar projection"); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); - 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); // The search field has the focus: it brings the tile into the grid's view harness.event(egui::Event::Text("uniform".into())); - harness.run_steps(2); harness.get_by_role_and_label(egui::Role::ListBoxOption, "Uniform value").click(); + // The slot's × puts the mask fill back to a uniform value + click_node(&mut harness, egui::Role::Button, "Clear"); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; diff --git a/crates/ui-egui/tests/it/filter_picker.rs b/crates/ui-egui/tests/it/filter_picker.rs index 36abe572..2efe721f 100644 --- a/crates/ui-egui/tests/it/filter_picker.rs +++ b/crates/ui-egui/tests/it/filter_picker.rs @@ -66,7 +66,7 @@ fn escape_closes_the_picker_without_changes() { assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert))); } -/// Opens the wand's Add effect menu and clicks Add filter +/// Opens the wand's Add effect menu and clicks Filter fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) { harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); harness.run_steps(3); diff --git a/crates/ui-egui/tests/it/instance_properties.rs b/crates/ui-egui/tests/it/instance_properties.rs new file mode 100644 index 00000000..15ece0a7 --- /dev/null +++ b/crates/ui-egui/tests/it/instance_properties.rs @@ -0,0 +1,65 @@ +//! The instance in Properties: INSTANCE OF holds the card of the layer it draws, a click on it selects that layer; a source that is gone shows a missing layer that takes no click + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// No layer has this id +const GONE: LayerId = LayerId(999_999); + +/// A fill named Steel and an instance of it (its source swapped for a layer that is gone when `dangling`), the instance selected: (harness, instance, source) +fn instance_harness(dangling: bool) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let source = LayerId(execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "layer.rename", &json!({"layer": source.0, "name": "Steel"})).unwrap(); + let instance = LayerId(execute(&mut session, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().unwrap()); + if dangling { + session.doc.project.layers.get_mut(&instance).unwrap().kind = LayerKind::Instance { source: GONE }; + } + execute(&mut session, "layer.select", &json!({"layer": instance.0, "target": "content"})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, instance, source) +} + +/// The name of the texture set holding `layer` +fn set_name(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> String { + let project = &harness.state().session.doc.project; + let (set, _, _) = project.locate(layer).unwrap(); + project.texture_set(set).unwrap().name.clone() +} + +#[test] +fn the_source_card_names_the_source_and_its_texture_set_and_a_click_selects_it() { + let (mut harness, instance, source) = instance_harness(false); + assert_eq!(harness.state().session.selected_layer(), Some(instance)); + let card = format!("Steel {}", set_name(&harness, source)); + harness.get_by_role_and_label(Role::Button, &card).click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(source), "the click goes to the source"); +} + +#[test] +fn a_source_that_is_gone_shows_a_missing_layer_that_takes_no_click() { + let (mut harness, instance, _) = instance_harness(true); + let card = format!("Missing layer {}", set_name(&harness, instance)); + let missing = harness.get_by_role_and_label(Role::Button, &card); + assert!(missing.accesskit_node().is_disabled(), "a missing source can't be gone to"); + + // A real press and release on the card + let steps = harness.state().session.history_labels().len(); + let at = missing.rect().center(); + harness.drag_at(at); + harness.run_steps(1); + harness.drop_at(at); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.selected_layer(), Some(instance)); + assert_eq!(harness.state().session.history_labels().len(), steps, "the click ran nothing"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 02416390..036d1f5f 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -267,13 +267,7 @@ fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { let h = narrow_harness(); let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); - // The effect menu button is the wand left of the paint button (effect rows draw wands too) - let wand = h - .query_all_by_label(egui_phosphor::regular::MAGIC_WAND) - .map(|n| n.rect()) - .filter(|r| r.right() < buttons[0].left()) - .max_by(|a, b| a.right().total_cmp(&b.right())) - .expect("the effect menu button"); + let wand = h.get_by_label("Add effect").rect(); let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); for rect in buttons.into_iter().chain([remove]) { assert!((rect.center().y - wand.center().y).abs() < 1.0, "the toolbar wrapped: {rect:?} against {wand:?}"); diff --git a/crates/ui-egui/tests/it/levels_editor.rs b/crates/ui-egui/tests/it/levels_editor.rs index 3fef7357..d117abc8 100644 --- a/crates/ui-egui/tests/it/levels_editor.rs +++ b/crates/ui-egui/tests/it/levels_editor.rs @@ -8,7 +8,9 @@ use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels}; use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; -/// Histogram buckets and Auto's share, as in levels_properties.rs +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, REDRAW_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Histogram buckets (histogram_cache.rs) and Auto's share (levels_properties.rs) const HISTOGRAM_BUCKETS: usize = 64; const AUTO_MIN_SHARE: f64 = 0.001; @@ -20,7 +22,7 @@ const HANDLE_POINTER_CORNERS: usize = 5; /// A clouds mask under a levels effect added by `command` with `params`, selected, and its id fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); for (id, params) in [ ("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})), ("mask.add.black", Value::Null), @@ -38,8 +40,8 @@ fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraft execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay - let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); - harness.run_steps(4); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(STARTUP_FRAMES); (harness, effect) } @@ -161,7 +163,7 @@ fn reset_and_invert_are_one_undo_step_each() { button(&harness, "Invert").click(); harness.run_steps(3); - assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 }); + assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2, ..Levels::default() }); assert_eq!(undo_steps(&harness), steps + 1); button(&harness, "Reset").click(); @@ -174,7 +176,7 @@ fn reset_and_invert_are_one_undo_step_each() { #[test] fn auto_fits_the_input_range_to_the_histogram() { let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5})); - let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap(); + let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap().all; let total: u32 = counts.iter().sum(); let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; @@ -195,6 +197,19 @@ fn auto_fits_the_input_range_to_the_histogram() { assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step"); } +/// How many of the five exact-entry fields are shown +fn open_fields(harness: &Harness<'_, TextureCraftApp>) -> usize { + HANDLE_LABELS.iter().filter(|label| harness.query_by_role_and_label(Role::TextInput, label).is_some()).count() +} + +/// Opens the number fields from `label`'s handle with the keyboard (focus, Enter) +fn open_exact_entry(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_role_and_label(Role::Slider, label).focus(); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); +} + /// Double-clicks `label`'s handle, then types `text` into its number field with the value selected fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { let at = handle(harness, label); @@ -220,18 +235,24 @@ fn a_value_typed_after_double_clicking_a_handle_applies() { assert_eq!(levels(&harness, effect).gamma, 2.5); assert_eq!(undo_steps(&harness), steps + 1); + assert_eq!(open_fields(&harness), 0, "Enter commits and closes the fields"); } #[test] -fn focusing_exact_entry_moves_nothing_in_the_panel() { +fn exact_entry_opens_on_a_double_click_and_closes_with_typing() { let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect()); let before = buttons(&harness); + assert_eq!(open_fields(&harness), 0, "no number fields until a handle asks for them"); type_value(&mut harness, "Output low", ""); - assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the number field has focus"); - assert_eq!(buttons(&harness), before); + assert_eq!(open_fields(&harness), HANDLE_LABELS.len()); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(open_fields(&harness), 0, "Escape closes the fields"); + assert_eq!(buttons(&harness), before, "the buttons go back where they were"); } #[test] @@ -296,7 +317,8 @@ fn the_hovered_handle_is_painted_on_top() { #[test] fn number_fields_are_labelled_and_stay_in_one_row() { - let (harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + open_exact_entry(&mut harness, "Gamma"); let fields = HANDLE_LABELS.map(|label| harness.get_by_role_and_label(Role::TextInput, label).rect()); let row = fields[0].center().y; @@ -405,6 +427,7 @@ fn dragging_near_a_handle_uses_the_larger_target() { fn number_fields_commit_on_focus_loss() { let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.8})); let steps = undo_steps(&harness); + open_exact_entry(&mut harness, "Gamma"); harness.get_by_role_and_label(Role::TextInput, "Input low").focus(); harness.run_steps(2); @@ -427,6 +450,87 @@ fn replacing_effects_releases_old_histograms() { harness.run_steps(3); } - let cached = harness.ctx.data(|data| data.count::<(u64, std::sync::Arc>)>()); + let cached = harness.ctx.data(|data| data.count::<(u64, std::sync::Arc)>()); assert_eq!(cached, 1, "only the current effect's histogram remains cached"); } + +/// Whether `text` was painted this frame (section captions are painted, not widgets) +pub(crate) fn painted_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(painted) if painted.galley.text() == text)) +} + +/// The Affects list: the combo box its row describes as "Affects", not the Layers channel list +pub(crate) fn affects_list<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> Option> { + harness.query_by(|node| node.role() == Role::ComboBox && node.description().as_deref() == Some("Affects")) +} + +/// A fill layer with a content levels, selected +fn content_levels_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap(); + execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap(); + let effect = levels_effect(&session); + open(session, effect) +} + +#[test] +fn a_content_levels_picks_the_channel_it_affects() { + let (mut harness, effect) = content_levels_harness(); + assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor)); + assert!(painted_text(&harness, "LEVELS - BASE COLOR"), "the caption names the channel"); + assert!(harness.query_by_label("Blending").is_none(), "levels have no blending"); + for view in ["Colors", "RGB", "R", "G", "B", "Lum"] { + assert!(harness.query_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some(view)).is_some(), "{view} on the display switch"); + } + + // The display switch only changes the view + let steps = undo_steps(&harness); + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(undo_steps(&harness), steps); + assert!( + harness.get_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("R")).accesskit_node().toggled() + == Some(egui::accesskit::Toggled::True), + "the switch shows red only" + ); + + assert_eq!(affects_list(&harness).and_then(|list| list.accesskit_node().label()).as_deref(), Some("Base color")); + affects_list(&harness).unwrap().click(); + harness.run_steps(SETTLE_FRAMES); + assert!( + harness.query_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Normal")).is_none(), + "levels pass normal maps through" + ); + harness.get_by(|node| node.role() == Role::ListBoxOption && node.label().as_deref() == Some("Roughness")).click(); + harness.run_steps(REDRAW_FRAMES); + assert_eq!(levels(&harness, effect).affects, Some(Channel::Roughness)); + assert_eq!(undo_steps(&harness), steps + 1); + assert!(painted_text(&harness, "LEVELS - ROUGHNESS")); + assert!(harness.query_by(|node| node.role() == Role::RadioButton && node.label().as_deref() == Some("Colors")).is_none(), "one value: no display choice"); +} + +#[test] +fn clamp_is_one_undo_step() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert!(painted_text(&harness, "LEVELS - MASK")); + assert!(affects_list(&harness).is_none() && !painted_text(&harness, "Affects"), "a mask has no channel to pick"); + assert!(!levels(&harness, effect).clamp, "new levels carry on past their handles"); + let steps = undo_steps(&harness); + harness.get_by_role_and_label(Role::CheckBox, "Clamp").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(levels(&harness, effect).clamp); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn the_affects_list_leaves_the_view_its_wheel_and_closes_on_escape_or_a_click_outside() { + let (mut harness, effect) = content_levels_harness(); + crate::assert_list_leaves_the_wheel_and_closes(&mut harness, |harness| { + let list = affects_list(harness).unwrap(); + let button = list.rect(); + list.click(); + harness.run_steps(SETTLE_FRAMES); + button + }); + assert_eq!(levels(&harness, effect).affects, Some(Channel::BaseColor), "nothing changed"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 8b642d36..3e9a0d64 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. mod alpha_parameters; +mod anchor_point; mod bake_job_mesh; mod bake_mode; mod bake_presets; @@ -12,6 +13,7 @@ mod clone_source_view; mod close_unsaved; mod color_picker; mod color_selection_editor; +mod compare_mask_rows; mod curvature_generator; mod display_environment; mod display_post_effects; @@ -32,20 +34,25 @@ mod fill_support; mod fill_symmetry_rows; mod filter_picker; mod filter_support; +mod folder_properties; mod frame_selection; mod generator_panel; mod help_menu_664; mod history_panel; mod import_resources; mod inactive_set_hint; +mod instance_properties; mod layer_blending_options; mod layer_clipboard; mod layer_multi_select; mod layer_rename; +mod layer_toolbar; mod layers_panel; mod levels_editor; mod log_panel_680; mod mask_export; +mod mask_fill_rows; +mod mask_paint_grayscale; mod mask_value_swap; mod named_layouts; mod nav_buttons; @@ -85,7 +92,6 @@ 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; @@ -98,6 +104,7 @@ mod window_menu_684; 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"] @@ -114,6 +121,9 @@ const PROPERTIES_WINDOW: egui::Vec2 = egui::vec2(1600.0, 1400.0); const TEXTURE_RESOLUTION: u32 = 256; const BAKE_RESOLUTION: u32 = 64; +/// One frame at 60 Hz, so timed steps run as on a common display +const FRAME_SECONDS: f32 = 1.0 / 60.0; + /// Frames for the first layout and fonts to settle const STARTUP_FRAMES: usize = 4; @@ -123,6 +133,9 @@ 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; +/// How far in from a slider track's ends a drag's points stay, so they land on the track +const SLIDER_END_INSET: f32 = 5.0; + /// Frames for an input that redraws Properties (another selection, source or operator) to show const REDRAW_FRAMES: usize = 4; diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs new file mode 100644 index 00000000..e2e28236 --- /dev/null +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -0,0 +1,82 @@ +//! A folder's mask selected: the paint tool's third tab is Grayscale, a slot card for the gray a stroke paints (its ramp and invert) or an image picked from the slot's picker + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::PropsTab; + +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// An 8 × 8 gray picture +fn gray_png() -> Vec { + let image = image::RgbaImage::from_pixel(8, 8, image::Rgba([90, 90, 90, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + bytes +} + +/// A folder with a white mask, the mask selected and the tool's Grayscale tab open: (harness, the imported image's name) +fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let image = session.import_resource_bytes("scratches.png", gray_png()).unwrap(); + let folder = LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut session, "mask.add.white", &json!({"layer": folder.0})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "mask"})).unwrap(); + let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.props_tab = PropsTab::Material; + harness.run_steps(STARTUP_FRAMES); + (harness, image) +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_grayscale_slot_paints_one_gray_its_ramp_drags_and_inverts() { + let (mut harness, _) = folder_mask_harness(); + assert!(harness.query_by_label("Mask value (gray)").is_none(), "the old slider is gone"); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Grayscale").is_some(), "the Grayscale slot card"); + + click(&mut harness, Role::Button, "Invert"); + assert_eq!(harness.state().session.tool.mask_value, 0.0, "white inverts to black"); + + // A real drag along the ramp to its right end + let track = harness.get_by_role_and_label(Role::Slider, "Grayscale").rect(); + let at = |t: f32| egui::pos2(track.left() + SLIDER_END_INSET + (track.width() - 2.0 * SLIDER_END_INSET) * t, track.center().y); + harness.drag_at(at(0.1)); + harness.run_steps(DRAG_STEP_FRAMES); + for t in [0.6, 1.0] { + harness.hover_at(at(t)); + harness.run_steps(DRAG_STEP_FRAMES); + } + harness.drop_at(at(1.0)); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().session.tool.mask_value > 0.95, "dragged to {}", harness.state().session.tool.mask_value); +} + +#[test] +fn the_slot_picks_an_image_to_paint_and_clear_goes_back_to_the_gray() { + let (mut harness, image) = folder_mask_harness(); + click(&mut harness, Role::ComboBox, "Grayscale"); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_some(), "Textures starts with Import..."); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Import...").is_none(), "Escape closes the picker"); + assert_eq!(harness.state().session.tool.mask_image, None); + + click(&mut harness, Role::ComboBox, "Grayscale"); + click(&mut harness, Role::ListBoxOption, &image); + assert_eq!(harness.state().session.tool.mask_image.as_deref(), Some(image.as_str())); + assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_none(), "an image has no ramp"); + + click(&mut harness, Role::Button, "Clear"); + assert_eq!(harness.state().session.tool.mask_image, None); + assert!(harness.query_by_role_and_label(Role::Slider, "Grayscale").is_some(), "the ramp is back"); +} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index b56d3c91..b909b013 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -1,6 +1,7 @@ //! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart use eframe::App as _; +use egui::accesskit::Role; use egui::{Event, Modifiers, PointerButton, Pos2, Vec2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -124,6 +125,18 @@ fn an_alt_orbit_keeps_the_tool_colour_popup_open() { assert!(egui::Popup::is_any_open(&harness.ctx), "an Alt+drag orbits the camera and keeps the popup, like the colour picker"); } +#[test] +fn a_stroke_on_the_model_closes_the_add_effect_menu() { + let mut harness = app(&MemoryStorage::default()); + harness.get_by_role_and_label(Role::Button, "Add effect").click(); + harness.run_steps(SETTLE_FRAMES); + assert!(egui::Popup::is_any_open(&harness.ctx), "the menu opens"); + + stroke_on_model(&mut harness, Modifiers::NONE); + + assert!(!egui::Popup::is_any_open(&harness.ctx), "the stroke closes the menu"); +} + #[test] fn a_stroke_on_the_model_closes_the_symmetry_settings() { let mut harness = app(&MemoryStorage::default()); diff --git a/crates/ui-egui/tests/it/source_picker.rs b/crates/ui-egui/tests/it/source_picker.rs index af9cdb4b..f40afea9 100644 --- a/crates/ui-egui/tests/it/source_picker.rs +++ b/crates/ui-egui/tests/it/source_picker.rs @@ -144,6 +144,20 @@ fn the_anchor_points_tab_lists_the_stacks_anchors() { assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); } +#[test] +fn the_anchor_points_tab_lists_mask_anchor_points_by_name() { + let (mut harness, _) = app_with_fill(|session, layer| { + texturecraft_engine::execute(session, "effect.add.anchor", &json!({"layer": layer.0, "target": "mask", "name": "Dirt mask"})).unwrap(); + texturecraft_engine::execute(session, "layer.add.fill", &json!({})).unwrap(); + }); + let reader = harness.state().session.selected_layer().unwrap(); + click_slot(&mut harness, "Roughness"); + click_widget(&mut harness, Role::Tab, "Anchor points"); + let anchor = harness.get_all_by_role(Role::ListBoxOption).find_map(|node| node.accesskit_node().label().filter(|label| label.starts_with("Dirt mask"))); + click_tile(&mut harness, &anchor.expect("the mask anchor point below is offered under its own name")); + assert!(matches!(source(&harness, reader, Channel::Roughness), Source::Anchor { .. })); +} + #[test] fn escape_or_a_click_outside_closes_it_and_the_wheel_still_zooms_the_view() { let (mut harness, layer) = app_with_fill(|_, _| {}); diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs index 7e8dabd5..48b3be42 100644 --- a/crates/ui-egui/tests/it/tile_generator_panel.rs +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -60,6 +60,11 @@ fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { harness.run_steps(3); } +/// The lowest control labelled `label`: the slot's rows show a pattern's Scale, Contrast and ⟲ above the Tile Generator's own +fn lowest<'h>(harness: &'h Harness<'_, TextureCraftApp>, label: &'h str) -> egui_kittest::Node<'h> { + harness.get_all_by_label(label).max_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap() +} + /// Where a slider's track is grabbed, from its label's left end and bottom, and how far it is dragged (points) const TRACK_GRAB_INSET: f32 = 20.0; const TRACK_BELOW_LABEL: f32 = 10.0; @@ -113,18 +118,16 @@ fn the_anchor_points_tab_picks_an_anchor() { harness.get_by_label("Anchor points").click(); harness.run_steps(3); - // An anchor tile is labelled " / ", as the anchors below a layer are listed - let project = &harness.state().session.doc.project; - let owner = project.layers.values().find(|layer| layer.content_effects.iter().any(|effect| effect.name == "Height")).unwrap(); - let label = format!("{} / Height", owner.name); harness.get_by_role_and_label(Role::ListBoxOption, &label).click(); + // An anchor tile is labelled with the anchor's name; its layer is named only where two anchors share a name + harness.get_by_role_and_label(Role::ListBoxOption, "Height").click(); harness.run_steps(3); assert!(source(&harness, effect).anchor().is_some()); } -/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the mask +/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the anchor and no channel #[test] -fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { +fn the_slot_names_the_anchor_in_a_mask_it_reads() { let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); session.active_set = 1; let lower = execute(&mut session, "layer.add.fill", &json!({"name": "Lower"})).unwrap()["layer"].as_u64().unwrap(); @@ -141,7 +144,7 @@ fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { let slot = harness.get_by_role_and_label(Role::ComboBox, "Grayscale"); - assert_eq!(slot.value().as_deref(), Some("Lower · Mask")); + assert_eq!(slot.value().as_deref(), Some("Anchor · Wear")); } #[test] @@ -156,9 +159,9 @@ fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { assert!(tile.amount[0] > TileGenerator::default().amount[0], "the drag adds columns: {:?}", tile.amount); assert_eq!(harness.state().session.history_labels().len(), history + 1, "one drag is one undo step"); - harness.get_by_label("Restore defaults").scroll_to_me(); - harness.run_steps(2); - harness.get_by_label("Restore defaults").click(); + lowest(&harness, "Restore defaults").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + lowest(&harness, "Restore defaults").click(); harness.run_steps(3); assert_eq!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); } @@ -205,10 +208,9 @@ fn typing_tile_contrast_then_clicking_invert_preserves_both_edits() { let (mut harness, effect) = harness(false); execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); harness.run_steps(3); - let contrast = harness.get_by_label("Contrast"); - contrast.scroll_to_me(); + lowest(&harness, "Contrast").scroll_to_me(); harness.run_steps(12); - let row = harness.get_by_label("Contrast").rect().center().y; + let row = lowest(&harness, "Contrast").rect().center().y; let at = harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center(); harness.drag_at(at); @@ -257,13 +259,6 @@ fn tile_generator_snapshots() { } harness.state_mut().ui.prefs.brightness = Brightness::Dark; - // Open, the section also holds a menu labelled "Resolution": its title is the first one - harness.get_by_label("Resolution").click(); - harness.run_steps(6); - harness.render().unwrap().save(directory.join("tile-resolution.png")).unwrap(); - harness.get_all_by_label("Resolution").next().unwrap().click(); - harness.run_steps(6); - for (sections, name) in [(["Pattern", "Size"], "pattern-size"), (["Position", "Rotation"], "position-rotation")] { for section in sections { // A section's title can also be a control's label above it ("Position"): the title is the last one diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 3789cf98..c451ea98 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -798,6 +798,52 @@ 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] @@ -1657,6 +1703,510 @@ fn popup_tabs_snapshots() { } } +/// Screen 07: a mask fill effect's Grayscale section from each kind of source (Uniform, image, procedural, anchor), its picker open with a tile hovered, and its Fill section; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn mask_fill_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 scratches = image::RgbaImage::from_fn(64, 64, |x, y| { + let gray = 90 + ((x * 13 + y * 7) % 90) as u8; + image::Rgba([gray, gray, gray, 255]) + }); + scratches.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let scratches = session.import_resource_bytes("scratches.png", png).unwrap(); + let below = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": below, "name": "Cavity Dirt"})).unwrap()["effect"].clone(); + let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].clone(); + let effect = execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect})).unwrap(); + 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); + save(&mut harness, &output_dir, "mask-fill-fill"); + harness.get_by_role_and_label(egui::Role::Tab, "Grayscale").click(); + harness.run_steps(30); + + let shot = |harness: &mut Harness<'_, TextureCraftApp>, mut source: serde_json::Value, name: &str| { + source["effect"] = effect.clone(); + execute(&mut harness.state_mut().session, "layer.fill.set", &source).unwrap(); + harness.run_steps(3); + settle_thumbnails(harness); + save(harness, &output_dir, name); + }; + shot(&mut harness, json!({"value": 1.0}), "mask-fill-uniform"); + shot(&mut harness, json!({"image": scratches}), "mask-fill-image"); + shot(&mut harness, json!({"procedural": "Clouds", "scale": 4.0, "seed": 12}), "mask-fill-procedural"); + + // The procedural's Resolution list open (Relative factors and Fixed sizes) with a size hovered + let click_in_view = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(3); + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(3); + }; + click_in_view(&mut harness, egui::Role::ComboBox, "Texture set · 256"); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "×2 · 512").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "mask-fill-resolution-list"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The picker opened from the slot in view (Properties still scrolled to the card), a tile hovered + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + settle_thumbnails(&mut harness); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Clouds").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "mask-fill-picker"); + 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!("mask-fill-picker-{name}")); + } + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + shot(&mut harness, json!({"anchor": anchor}), "mask-fill-anchor"); + + // Again once the anchored stack's picture has rendered + settle_thumbnails(&mut harness); + save(&mut harness, &output_dir, "mask-fill-anchor"); + + shot(&mut harness, json!({"value": 1.0}), "mask-fill-uniform-again"); +} + +/// Screen 09: a compare mask at its defaults, within tolerance, its right source's list open with Constant hovered, then Constant picked +#[test] +#[ignore] +fn compare_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 layer = json!(null); + for (low, high) in [(-0.7, 0.1), (-0.2, 0.6)] { + layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let (low, high) = (json!([low, low, low]), json!([high, high, high])); + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": "height", "procedural": "Clouds", "scale": 3.0, "low": low, "high": high})) + .unwrap(); + } + let compare = execute(&mut session, "effect.add.compare", &json!({"layer": layer})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": compare})).unwrap(); + 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(6); + save(&mut harness, &output_dir, "compare-default"); + + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some("≈")).click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "compare-within"); + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some(">")).click(); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ComboBox, "Layers below").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Constant").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "compare-source-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Constant").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "compare-constant"); + 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!("compare-constant-{name}")); + } + } +} + +/// Screen 11: a new anchor point on a fill's content being renamed, then a mask anchor point read by two layers above (a reference hovered) +#[test] +#[ignore] +fn anchor_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 low = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": low, "name": "Cavity Dirt"})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": low, "generator": "dirt"})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": low, "target": "mask"})).unwrap()["effect"].clone(); + for name in ["Fill layer 2", "Rust"] { + let reader = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": reader, "name": name})).unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": reader, "anchor": anchor})).unwrap(); + } + let fresh = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let content = execute(&mut session, "effect.add.anchor", &json!({"layer": fresh})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": fresh, "target": content})).unwrap(); + 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(6); + harness.get_by_role_and_label(egui::Role::TextInput, "Anchor point name").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "anchor-new-renaming"); + + harness.key_press(egui::Key::Escape); + harness.state_mut().session.target = texturecraft_engine::StackTarget::Content; + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": low, "target": anchor})).unwrap(); + harness.run_steps(6); + let row = harness.get_by_role_and_label(egui::Role::Button, "Rust Mask fill").rect().center(); + harness.hover_at(row); + save(&mut harness, &output_dir, "anchor-mask-references"); + 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!("anchor-mask-references-{name}")); + } + } +} + +/// Screen 15: a folder of fills at rest, scaled x1.5 and turned +30 with the reset hovered, and an empty folder +#[test] +#[ignore] +fn folder_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 empty = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + let fill = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.move", &json!({"layer": fill, "above": empty, "inside": false})).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": fill, "channel": "baseColor", "procedural": "Clouds"})).unwrap(); + let folder = execute(&mut session, "layer.group", &json!({"layer": fill})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": folder, "target": "content"})).unwrap(); + 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(6); + save(&mut harness, &output_dir, "folder-rest"); + + execute(&mut harness.state_mut().session, "folder.contents.set", &json!({"layer": folder, "scale": 1.5, "rotation": 30.0})).unwrap(); + harness.run_steps(4); + let reset = harness.get_by_role_and_label(egui::Role::Button, "Contents: Reset to defaults").rect().center(); + harness.hover_at(reset); + save(&mut harness, &output_dir, "folder-offset-reset-hovered"); + 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!("folder-offset-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": empty, "target": "content"})).unwrap(); + harness.run_steps(4); + save(&mut harness, &output_dir, "folder-empty"); +} + +/// Screen 16: an instance of an orange fill named Steel (at rest, its card hovered), then one whose source is gone +#[test] +#[ignore] +fn instance_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 source = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": source, "name": "Steel"})).unwrap(); + execute(&mut session, "layer.fill.set", &json!({"layer": source, "channel": "baseColor", "color": [0.78, 0.29, 0.09]})).unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": instance, "target": "content"})).unwrap(); + 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(6); + save(&mut harness, &output_dir, "instance-rest"); + let set = harness.state().session.doc.project.texture_sets[0].name.clone(); + let card = harness.get_by_role_and_label(egui::Role::Button, &format!("Steel {set}")).rect().center(); + harness.hover_at(card); + save(&mut harness, &output_dir, "instance-hovered"); + 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!("instance-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + + let id = LayerId(instance.as_u64().unwrap()); + harness.state_mut().session.doc.project.layers.get_mut(&id).unwrap().kind = LayerKind::Instance { source: LayerId(999_999) }; + harness.hover_at(egui::pos2(10.0, 10.0)); + save(&mut harness, &output_dir, "instance-missing"); +} + +/// Screen 17: a folder's mask selected with the paint tool's Grayscale tab open: painting white, black, then an image (the slot hovered), then the slot's picker open +#[test] +#[ignore] +fn folder_mask_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 scratches = image::RgbaImage::from_fn(64, 64, |x, y| { + let value = (((x * 7 + y * 13) ^ (x * y)) % 200 + 40) as u8; + image::Rgba([value, value, value, 255]) + }); + let mut bytes = Vec::new(); + scratches.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("scratches.png", bytes).unwrap(); + let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "mask.add.white", &json!({"layer": folder})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap(); + 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.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; + harness.run_steps(6); + save(&mut harness, &output_dir, "foldermask-white"); + 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!("foldermask-{name}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + execute(&mut harness.state_mut().session, "tool.material", &json!({"maskValue": 0.0})).unwrap(); + save(&mut harness, &output_dir, "foldermask-black"); + execute(&mut harness.state_mut().session, "tool.material", &json!({"maskImage": image})).unwrap(); + let slot = harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").rect().center(); + harness.hover_at(slot); + save(&mut harness, &output_dir, "foldermask-image"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "foldermask-picker"); +} + +/// Screen 10: a new color selection without an ID map, then three colors on the ID mesh map (a row hovered, a row picking again, the Background list open) +#[test] +#[ignore] +fn color_selection_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 shoot = |with_id_map: bool| { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + if !with_id_map { + execute(&mut session, "textureSet.meshMap.clear", &json!({"map": "id"})).unwrap(); + } + let layer = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + let added = execute(&mut session, "mask.add.colorSelection", &json!({"layer": layer})).unwrap(); + let effect = texturecraft_engine::core::LayerId(added["effect"].as_u64().unwrap()); + if with_id_map { + let colors = json!([[214.0 / 255.0, 1.0, 0.0], [1.0, 49.0 / 255.0, 0.0], [1.0, 0.0, 247.0 / 255.0]]); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "colors": colors})).unwrap(); + } + execute(&mut session, "layer.select", &json!({"layer": layer, "target": effect.0})).unwrap(); + 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(6); + harness + }; + + let mut harness = shoot(false); + save(&mut harness, &output_dir, "colorsel-new"); + + // Picking with an ID Mask image chosen by hand and nothing baked: the model shows that image + let quarters = image::RgbaImage::from_fn(8, 8, |x, y| match (x < 4, y < 4) { + (true, true) => image::Rgba([214, 255, 0, 255]), + (false, true) => image::Rgba([255, 49, 0, 255]), + (true, false) => image::Rgba([255, 0, 247, 255]), + (false, false) => image::Rgba([20, 90, 255, 255]), + }); + let mut png = Vec::new(); + quarters.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let mut harness = shoot(false); + let effect = match harness.state().session.target { + texturecraft_engine::StackTarget::Effect(effect) => effect, + other => panic!("the color selection is selected, not {other:?}"), + }; + harness.state_mut().session.doc.baked.clear(); + let name = harness.state_mut().session.import_resource_bytes("parts.png", png).unwrap(); + harness.state_mut().run("effect.set", json!({"effect": effect.0, "idMap": name})); + harness.run_steps(4); + harness.get_by_label("Pick color").click(); + harness.run_steps(8); + save(&mut harness, &output_dir, "colorsel-image-pick"); + + let mut harness = shoot(true); + let row = harness.get_by_label("Pick color R 255 G 49 B 0").rect().center(); + harness.hover_at(row); + harness.run_steps(2); + save(&mut harness, &output_dir, "colorsel-hover"); + let first = harness.get_by_label("Pick color R 214 G 255 B 0").rect().center(); + harness.get_by_label("Pick color R 214 G 255 B 0").click(); + harness.run_steps(4); + harness.hover_at(first); + harness.run_steps(2); + save(&mut harness, &output_dir, "colorsel-repick"); + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ComboBox, "Black").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Transparent").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "colorsel-background-list"); + if std::env::var_os("TC_UI_THEMES").is_some() { + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("colorsel-{name}")); + } + } +} + +/// Screen 08: a mask's levels, then a content levels on Base color (Colors, red only with Clamp on, its Affects list open with an option hovered) and on Roughness +#[test] +#[ignore] +fn levels_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 layer = execute(&mut session, "layer.add.fill", &json!({"roughness": 0.5})).unwrap()["layer"].clone(); + for (channel, low, high) in + [("baseColor", json!([0.1, 0.2, 0.45]), json!([0.85, 0.5, 0.2])), ("roughness", json!([0.25, 0.25, 0.25]), json!([0.7, 0.7, 0.7]))] + { + execute(&mut session, "layer.fill.set", &json!({"layer": layer, "channel": channel, "procedural": "Clouds", "scale": 3.0, "low": low, "high": high})) + .unwrap(); + } + execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "mask", "procedural": "clouds"})).unwrap(); + let mask_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "mask"})).unwrap()["effect"].clone(); + let content_levels = execute(&mut session, "effect.add.levels", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].clone(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": mask_levels})).unwrap(); + 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(6); + save(&mut harness, &output_dir, "levels-mask"); + + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": content_levels})).unwrap(); + harness.run_steps(6); + save(&mut harness, &output_dir, "levels-colors"); + let switch = |harness: &mut Harness<'_, TextureCraftApp>, view: &str| { + harness.get_by(|node| node.role() == egui::Role::RadioButton && node.label().as_deref() == Some(view)).click(); + harness.run_steps(3); + }; + switch(&mut harness, "R"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Clamp").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "levels-red-clamp"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Clamp").click(); + switch(&mut harness, "Colors"); + lowest_list(&harness, "Base color").click(); + harness.run_steps(3); + let hovered = harness.get_by_role_and_label(egui::Role::ListBoxOption, "Roughness").rect().center(); + harness.hover_at(hovered); + save(&mut harness, &output_dir, "levels-affects-list"); + harness.get_by_role_and_label(egui::Role::ListBoxOption, "Roughness").click(); + harness.run_steps(6); + save(&mut harness, &output_dir, "levels-roughness"); + harness.get_by_role_and_label(egui::Role::Slider, "Gamma").focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + save(&mut harness, &output_dir, "levels-exact-entry"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + 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!("levels-roughness-{name}")); + } + } +} + +/// Screen 14: the Layers panel's top row (Add fill layer hovered), Add effect on a layer and on its mask, Add mask, and Bitmap's texture picker; the panel's left edge goes to stderr for cropping +#[test] +#[ignore] +fn layer_toolbar_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 dirt = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.rename", &json!({"layer": dirt, "name": "Dirt"})).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"layer": dirt, "generator": "dirt"})).unwrap(); + let fill = execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].clone(); + execute(&mut session, "layer.select", &json!({"layer": fill})).unwrap(); + 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(6); + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.run_steps(3); + eprintln!("toolbar at {:?}", harness.get_by_role_and_label(egui::Role::Button, "Add effect").rect()); + let hover = |harness: &mut Harness<'_, TextureCraftApp>, label: &str| { + let at = harness.get_by_role_and_label(egui::Role::Button, label).rect().center(); + harness.hover_at(at); + }; + let open = |harness: &mut Harness<'_, TextureCraftApp>, menu: &str| { + harness.get_by_role_and_label(egui::Role::Button, menu).click(); + harness.run_steps(3); + }; + hover(&mut harness, "Add fill layer"); + save(&mut harness, &output_dir, "toolbar-rest"); + open(&mut harness, "Add effect"); + hover(&mut harness, "Filter"); + save(&mut harness, &output_dir, "toolbar-effect-content"); + harness.key_press(egui::Key::Escape); + execute(&mut harness.state_mut().session, "mask.add.white", &json!({"layer": fill})).unwrap(); + harness.run_steps(3); + open(&mut harness, "Add effect"); + hover(&mut harness, "Compare mask"); + save(&mut harness, &output_dir, "toolbar-effect-mask"); + harness.key_press(egui::Key::Escape); + execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); + harness.run_steps(3); + open(&mut harness, "Add mask"); + hover(&mut harness, "Height combination"); + save(&mut harness, &output_dir, "toolbar-mask"); + harness.get_by_role_and_label(egui::Role::Button, "Bitmap").click(); + harness.run_steps(3); + save(&mut harness, &output_dir, "toolbar-bitmap"); + if std::env::var_os("TC_UI_THEMES").is_some() { + harness.key_press(egui::Key::Escape); + open(&mut harness, "Add effect"); + hover(&mut harness, "Filter"); + for (brightness, name) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("toolbar-effect-content-{name}")); + } + } +} + #[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 diff --git a/docs/control-protocol.md b/docs/control-protocol.md index bc2cc695..9b88b0f8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -589,16 +589,13 @@ with `material.apply` instead. The fill remembers the material (`Fill.material`, - `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. + the shared one). `effect.set {effect, channel, blend?, opacity?}` sets one channel's blending. - `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