From ae8fd0cc30b5c6e962e19496542f2d4a6c34f8f3 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:00:51 +0100 Subject: [PATCH 1/9] Decode XML entities in COLLADA attribute values and text Found while testing crates/formats/src/mesh_import/dae.rs:55 Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/mesh_import/dae.rs | 33 +++++++++++++++---- crates/formats/src/mesh_import/scene_tests.rs | 18 ++++++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/crates/formats/src/mesh_import/dae.rs b/crates/formats/src/mesh_import/dae.rs index d23ea61b..8cacf4c5 100644 --- a/crates/formats/src/mesh_import/dae.rs +++ b/crates/formats/src/mesh_import/dae.rs @@ -6,7 +6,9 @@ use std::collections::HashMap; use std::rc::Rc; -use quick_xml::events::{BytesStart, Event}; +use quick_xml::XmlVersion; +use quick_xml::escape::resolve_predefined_entity; +use quick_xml::events::{BytesRef, BytesStart, Event}; use texturecraft_geom::glam::{Mat3, Mat4, Vec2, Vec3, Vec4}; use super::{Corner, PolygonSink, RawCamera, RawMesh, check_vertices}; @@ -52,7 +54,9 @@ impl El { fn element(e: &BytesStart) -> El { let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned(); - let attrs = e.attributes().with_checks(false).flatten().map(|a| (text(a.key.local_name().as_ref()), text(&a.value))).collect(); + // Values come back still escaped; decode them, keeping the raw text if they are malformed. + let value = |a: &quick_xml::events::attributes::Attribute| a.normalized_value(XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned()); + let attrs = e.attributes().with_checks(false).flatten().map(|a| (text(a.key.local_name().as_ref()), value(&a))).collect(); El { name: text(e.local_name().as_ref()), attrs, ..El::default() } } @@ -61,8 +65,11 @@ fn parse_xml(bytes: &[u8]) -> Result { let mut reader = quick_xml::Reader::from_reader(bytes); let mut stack = vec![El::default()]; let mut count = 0usize; + // Text and entity references arrive as separate events but form one run of text. + let mut in_text = false; loop { let event = reader.read_event().map_err(|e| malformed(KIND, e))?; + let glue = std::mem::replace(&mut in_text, matches!(event, Event::Text(_) | Event::GeneralRef(_))); if matches!(event, Event::Start(_) | Event::Empty(_)) { count += 1; if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH { @@ -82,8 +89,9 @@ fn parse_xml(bytes: &[u8]) -> Result { parent.children.push(el); } } - Event::Text(t) => push_text(&mut stack, &t), - Event::CData(t) => push_text(&mut stack, &t), + Event::Text(t) => push_text(&mut stack, &String::from_utf8_lossy(&t), glue), + Event::GeneralRef(r) => push_text(&mut stack, &entity(&r), glue), + Event::CData(t) => push_text(&mut stack, &String::from_utf8_lossy(&t), false), Event::Eof => break, _ => {} } @@ -94,9 +102,22 @@ fn parse_xml(bytes: &[u8]) -> Result { } } -fn push_text(stack: &mut [El], t: &[u8]) { +/// The text an entity or character reference stands for (unknown ones stay as written). +fn entity(r: &BytesRef) -> String { + let name = String::from_utf8_lossy(r); + match r.resolve_char_ref() { + Ok(Some(c)) => c.to_string(), + _ => resolve_predefined_entity(&name).map_or_else(|| format!("&{name};"), str::to_string), + } +} + +/// Appends a text piece; `glue` joins it to the previous piece of the same run of text. +fn push_text(stack: &mut [El], t: &str, glue: bool) { if let Some(el) = stack.last_mut() { - el.text.push_str(&String::from_utf8_lossy(t)); + if glue && el.text.ends_with(' ') { + el.text.pop(); + } + el.text.push_str(t); // Whitespace keeps numbers split across text events apart. el.text.push(' '); } diff --git a/crates/formats/src/mesh_import/scene_tests.rs b/crates/formats/src/mesh_import/scene_tests.rs index 5c5f4b5a..2f0a8cdb 100644 --- a/crates/formats/src/mesh_import/scene_tests.rs +++ b/crates/formats/src/mesh_import/scene_tests.rs @@ -727,6 +727,24 @@ fn dae_polylist_z_up_units_and_node_transforms() { assert!(!cam.ortho && near(cam.fov, 30.0) && near(cam.yaw, 0.0) && near(cam.pitch, 0.0), "{cam:?}"); } +#[test] +fn dae_attribute_and_text_entities_are_decoded() { + let dae = DAE + .replace(r#""#, r#""#) + .replace(r#"name="Red""#, r#"name="R&D""#) + .replace(r#"30", "30"); + let r = import_mesh_bytes("scene.dae", dae.as_bytes()).unwrap(); + let m = &r.mesh; + let parts: Vec<&str> = m.submeshes.iter().map(|s| s.name.as_str()).collect(); + assert!(parts.contains(&"Tom & Jerry <\"'AB"), "{parts:?}"); + assert_eq!(m.materials, vec!["R&D".to_string(), "Blue".to_string()]); + assert_eq!(m.triangle_count(), 2 + 1 + 2); + let [cam] = r.cameras.as_slice() else { panic!("{:?}", r.cameras) }; + assert!((cam.fov - 30.0).abs() < 1e-3, "{cam:?}"); +} + #[test] fn glb_export_round_trips_with_textures() { let mesh = texturecraft_geom::primitives::material_ball(); From 732f6bae284f88cbc7c89e21146581b69bfac9eb Mon Sep 17 00:00:00 2001 From: Rafael Mendes Date: Tue, 10 Nov 2026 17:52:26 -0300 Subject: [PATCH 2/9] Anchor points in masks, generator micro detail, effect rename Anchor point effects can now sit in a mask, where they record the mask value at their place for fills and generators above. Generators take an anchor's height as micro detail (microAnchor, microAmount). Effects can be renamed from the Layers panel, and the anchor picker lists anchors under their own heading. Closes #389 --- crates/compose/src/eval.rs | 141 +++++++++++++++++++--- crates/core/src/layer.rs | 39 +++++- crates/core/src/lib.rs | 4 +- crates/engine/src/effect_clipboard.rs | 6 +- crates/engine/src/inspect.rs | 3 + crates/engine/src/mask_cmds.rs | 67 +++++++++- crates/engine/tests/it/content_effects.rs | 66 ++++++++++ crates/ui-egui/src/dock.rs | 140 +++++++++++++++++---- crates/ui-egui/src/i18n/ar.rs | 15 +++ crates/ui-egui/src/i18n/de.rs | 18 +++ crates/ui-egui/src/i18n/es.rs | 18 +++ crates/ui-egui/src/i18n/fr.rs | 18 +++ crates/ui-egui/src/i18n/it.rs | 18 +++ crates/ui-egui/src/i18n/ja.rs | 18 +++ crates/ui-egui/src/i18n/ko.rs | 18 +++ crates/ui-egui/src/i18n/pt_br.rs | 18 +++ crates/ui-egui/src/i18n/zh_hans.rs | 15 +++ docs/features.md | 4 +- 18 files changed, 571 insertions(+), 55 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3a9404d3..06523f90 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -9,8 +9,8 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator, - GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, - blend3, lum, mix3, per_unit, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, MicroDetail, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, + blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; @@ -202,6 +202,8 @@ enum Content<'a> { } struct EffectPlan<'a> { + /// The effect id (an anchor point records under it). + id: LayerId, kind: &'a EffectKind, blend: BlendMode, opacity: f32, @@ -852,6 +854,7 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y _ => None, }; EffectPlan { + id: effect.id, kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, @@ -945,19 +948,22 @@ fn plan_node<'a>( // `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)); + // 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))); // A paint layer with nothing painted (and not being painted) or added by its content // effects contributes nothing. if let Content::Paint { preview: false } = content && chans.iter().all(|c| c.data.is_none() && c.effects.is_empty()) + && !mask_anchor { return None; } - if chans.is_empty() { + if chans.is_empty() && !mask_anchor { return None; } - let mask = layer_mask(inp.project, id).and_then(|m| mask_plan(inp, id, m, tx, ty, fields)); let anchors = if fx { anchor_cuts(&layer.content_effects) } else { Vec::new() }; - let has_anchor = !anchors.is_empty() || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); + let has_anchor = !anchors.is_empty() || mask_anchor || matches!(&content, Content::Group(nodes) if nodes.iter().any(|n| n.has_anchor)); // The geometry mask is the layer's own (an instance in another set has other parts). let parts = own.geometry_mask.as_ref().map(|names| inp.mesh.submeshes.iter().map(|s| names.contains(&s.name)).collect()); Some(Node { id, content, chans, mask, anchors, has_anchor, height_mask: layer.height_mask, parts }) @@ -1200,16 +1206,20 @@ impl<'a, 'b> Texel<'a, 'b> { ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], } } - Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default. - let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); - let v = v.unwrap_or_else(|| channel.default_value()); - let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(v); 3] } else { v } - } + Source::Anchor { anchor, channel } => self.anchor_value(*anchor, *channel, kind), } } + /// The value anchor point `anchor` recorded for `channel`, read as `kind` (colors read as gray + /// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the + /// channel default. + fn anchor_value(&self, anchor: LayerId, channel: Channel, kind: ChannelKind) -> [f32; 3] { + let v = self.anchors.iter().rev().find(|(id, _)| *id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); + let v = v.unwrap_or_else(|| channel.default_value()); + let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); + if gray { [lum(v); 3] } else { v } + } + fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); let signal = match (generator.kind, &generator.detail) { @@ -1222,6 +1232,10 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; + let signal = match generator.micro { + Some(micro) => signal + self.micro_detail(generator.kind, micro), + None => signal, + }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -1243,6 +1257,21 @@ impl<'a, 'b> Texel<'a, 'b> { if generator.invert { 1.0 - value } else { value } } + /// How a generator's micro detail moves its signal at this texel: the anchor's height (0 where + /// the anchor is not evaluated yet) as an edge where raised and a cavity where recessed. + fn micro_detail(&self, kind: GeneratorKind, micro: MicroDetail) -> f32 { + let height = self.anchor_value(micro.anchor, Channel::Height, ChannelKind::Signed)[0]; + let amount = if micro.amount.is_finite() { micro.amount.clamp(0.0, 1.0) } else { 0.0 }; + let response = height.clamp(-1.0, 1.0) * amount; + match kind { + GeneratorKind::Curvature | GeneratorKind::EdgeWear => response, + // Dirt gathers in dents; dents are occluded. + GeneratorKind::Dirt => -response, + GeneratorKind::AmbientOcclusion => response, + GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction => 0.0, + } + } + /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let combine = |edges: f32, cavities: f32| match detail.mode { @@ -1286,8 +1315,17 @@ impl<'a, 'b> Texel<'a, 'b> { value = filtered; skip = filtered_index + 1; } + // Anchors under the precomputed filter: evaluate the stack up to the last of them (only + // to record them; like a cut content stack, filters below them read as point filters). + 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()) + } - for effect in plan.effects.iter().skip(skip) { + /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them. + fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 { + for effect in plan.effects.iter().take(to).skip(from) { let opacity = effect.opacity.clamp(0.0, 1.0); match effect.kind { EffectKind::Paint | EffectKind::Path(_) => { @@ -1341,8 +1379,10 @@ impl<'a, 'b> Texel<'a, 'b> { let result = if pass { 1.0 } else { 0.0 }; value += (result - value) * opacity; } + // Every channel of a mask anchor reads the mask's gray. + EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH])), // Content-only effects - EffectKind::Material(_) | EffectKind::Anchor => {} + EffectKind::Material(_) => {} } } value.clamp(0.0, 1.0) @@ -2929,6 +2969,79 @@ soft {soft:?}" assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } + /// A white fill layer on top whose mask reads `anchor` (any channel: a mask anchor is gray). + fn anchor_reader(f: &mut Fixture, anchor: LayerId) -> LayerId { + let top = fill_layer(&mut f.project, [1.0; 3], 0.5); + let mut mask = Mask::new(MaskBackground::Black); + let source = Source::Anchor { anchor, channel: Channel::Roughness }; + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); + f.project.layer_mut(top).unwrap().mask = Some(mask); + top + } + + #[test] + fn mask_anchors_record_the_mask_value_at_their_place() { + let mut f = fixture(); + let low = fill_layer(&mut f.project, [0.0; 3], 0.5); + let (gray, anchor, full) = (f.project.alloc_id(), f.project.alloc_id(), f.project.alloc_id()); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(gray, EffectKind::Fill { source: Source::Uniform([0.4; 3]), projection: Projection::default() })); + mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); + mask.effects.push(Effect::new(full, EffectKind::Fill { source: Source::Uniform([1.0; 3]), projection: Projection::default() })); + f.project.layer_mut(low).unwrap().mask = Some(mask.clone()); + anchor_reader(&mut f, anchor); + // The low layer shows fully (black), the top one at the 0.4 the anchor recorded. + assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.4; 3])); + + // Under a blur precomputed over the region the anchor still records its own place. + mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); + f.project.layer_mut(low).unwrap().mask = Some(mask.clone()); + let v = run(&f, None).value(Channel::BaseColor, 5, 5); + assert!(close(v, [0.4; 3]), "{v:?}"); + + // A paint layer with nothing painted draws nothing (the base stays 0.5) but still records + // the anchors of its mask (0.5 + 0.5 × 0.4; unrecorded, the top would read 0 and stay 0.5). + f.project.layer_mut(low).unwrap().kind = LayerKind::Paint; + let v = run(&f, None).value(Channel::BaseColor, 5, 5); + assert!(close(v, [0.7; 3]), "{v:?}"); + } + + #[test] + fn generator_micro_detail_follows_the_anchor_height() { + let mut f = fixture(); + let low = f.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + f.project.insert_layer(0, Layer::new(low, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut f, low, EffectKind::Anchor); + let top = fill_layer(&mut f.project, [1.0; 3], 0.5); + let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::Curvature) }; + let with = |f: &mut Fixture, generator: &Generator| { + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(LayerId(900), EffectKind::Generator(generator.clone()))); + f.project.layer_mut(top).unwrap().mask = Some(mask); + run(f, None).value(Channel::BaseColor, 5, 5)[0] + }; + // No curvature map: flat mid gray, so the mask is 0.5 and the base color 0.75. + let flat = with(&mut f, &generator); + assert!((flat - 0.75).abs() < 0.02, "{flat}"); + // Raised height reads as an edge. + generator.micro = Some(MicroDetail { anchor, amount: 1.0 }); + assert!(with(&mut f, &generator) > flat + 0.2); + // Recessed height reads as a cavity; dirt gathers there. + if let LayerKind::Fill(fill) = &mut f.project.layer_mut(low).unwrap().kind { + fill.sources.insert(Channel::Height, Source::Uniform([-0.5; 3])); + } + assert!(with(&mut f, &generator) < flat - 0.2); + let dirt = + Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, micro: Some(MicroDetail { anchor, amount: 1.0 }), ..Generator::new(GeneratorKind::Dirt) }; + let plain = Generator { micro: None, ..dirt.clone() }; + assert!(with(&mut f, &dirt) > with(&mut f, &plain) + 0.2); + // A hostile amount does nothing. + generator.micro = Some(MicroDetail { anchor, amount: f32::NAN }); + assert!((with(&mut f, &generator) - flat).abs() < 0.02); + } + #[test] fn decal_fills_cover_only_their_frame_and_image_alpha() { let mut f = fixture(); diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 37ce47e8..dce87379 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -549,6 +549,23 @@ pub struct Generator { /// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed). #[serde(default, skip_serializing_if = "Option::is_none")] pub detail: Option, + /// Painted height read from an anchor point below, added as micro detail (None: baked maps only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub micro: Option, +} + +/// A generator's micro detail: the height an anchor point records, so the generated mask +/// follows painted bumps and dents (raised height reads as an edge, recessed as a cavity). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct MicroDetail { + /// The anchor point effect id. + pub anchor: LayerId, + /// How strongly the height moves the signal (0..1). + pub amount: f32, +} + +impl MicroDetail { + pub const DEFAULT_AMOUNT: f32 = 0.5; } impl Generator { @@ -565,7 +582,7 @@ impl Generator { GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail, micro: None } } } @@ -965,8 +982,10 @@ pub enum EffectKind { /// Content only: a material fill (one source per channel; channels without a source are /// left as they are). Material(Fill), - /// Content only: records the composited stack right after its layer (that layer and - /// everything below) so masks and fills above can read it ([`Source::Anchor`]). + /// Records the stack at its place so masks, fills and generators above can read it + /// ([`Source::Anchor`]). In a content stack it records the composited stack right after its + /// layer (that layer and everything below); in a mask, the mask value at that point (every + /// channel reads that gray). Anchor, } @@ -1012,9 +1031,9 @@ impl EffectKind { /// both (`None`). pub fn content_only(&self) -> Option { match self { - EffectKind::Material(_) | EffectKind::Anchor => Some(true), + EffectKind::Material(_) => Some(true), EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => Some(false), - EffectKind::Paint | EffectKind::Path(_) | EffectKind::Levels(_) | EffectKind::Filter(_) => None, + EffectKind::Paint | EffectKind::Path(_) | EffectKind::Levels(_) | EffectKind::Filter(_) | EffectKind::Anchor => None, } } @@ -1028,6 +1047,7 @@ impl EffectKind { match self { EffectKind::Fill { source, .. } => source.anchor().is_some(), EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()), + EffectKind::Generator(g) => g.micro.is_some(), _ => false, } } @@ -1141,7 +1161,7 @@ mod tests { #[test] fn effect_targets_and_anchor_reads() { - assert_eq!(EffectKind::Anchor.content_only(), Some(true)); + 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 l = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); @@ -1152,6 +1172,13 @@ mod tests { ..Mask::new(MaskBackground::Black) }); assert!(l.reads_anchor()); + + // A generator with micro detail reads its anchor too. + let mut g = 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 }); + g.mask = Some(Mask { effects: vec![Effect::new(LayerId(4), EffectKind::Generator(generator))], ..Mask::new(MaskBackground::Black) }); + assert!(g.reads_anchor()); } #[test] diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 75ea2405..74c9af5a 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -25,8 +25,8 @@ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, - LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, - hsl_adjust, per_unit, + LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, PathShape, Procedural, ProceduralKind, Projection, Source, + gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index 36aa5f3a..4790caa7 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -2,7 +2,7 @@ //! clipboard: it holds a layer or an effect. use serde_json::{Value, json}; -use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source}; +use texturecraft_core::{Channel, EffectKind, Generator, LayerId, Mask, MaskBackground, Source}; use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp}; use crate::layer_ops::{empty_texel, fit}; @@ -92,6 +92,10 @@ fn paste(s: &mut Session, p: &Value) -> Result { if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind { anchor_source(s, CMD, owner, *anchor, *channel)?; } + // So does a generator reading one as micro detail. + if let EffectKind::Generator(Generator { micro: Some(micro), .. }) = &effect.kind { + anchor_source(s, CMD, owner, micro.anchor, Channel::Height)?; + } let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?; let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?; let new = s.edit("Paste effect", |s| { diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 2db27946..f18d68fe 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -76,6 +76,9 @@ fn generator_json(generator: &Generator) -> Value { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); } + if let Some(micro) = &generator.micro { + out["micro"] = json!({ "anchor": micro.anchor.0, "amount": micro.amount }); + } out } diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index b8aad872..e793fbac 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, - Procedural, ProceduralKind, Project, Source, + MicroDetail, Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear), microAnchor?: anchor effect id below (its height as micro detail: edges where raised, cavities where recessed; null removes it), microAmount?: 0..1 (0.5)}", has_layer, add_generator ), @@ -85,16 +85,16 @@ pub fn specs() -> Vec { "Add anchor point", ["Layers", "Effects"], None, - "{layer?, name?} (records the stack up to this layer for fills and masks above: effect.add.fill {anchor})", + "{layer?, target?: content|mask (content), name?} (on the content it records the stack up to this layer, in a mask the mask value at that point; fills, masks and generators above read it: effect.add.fill {anchor}, effect.add.generator {microAnchor})", has_layer, - |s, p| push_effect(s, p, EffectKind::Anchor, BlendMode::Normal) + add_anchor ), cmd!( "effect.set", "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, microAnchor?: id|null, microAmount?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -375,6 +375,45 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S Ok(weights) } +/// An anchor point on the layer content (the default, as before anchors went on masks) or, with +/// `target: "mask"`, in its mask. +fn add_anchor(s: &mut Session, p: &Value) -> Result { + let mut params = p.clone(); + if p.get("target").is_none() + && let Some(o) = params.as_object_mut() + { + o.insert("target".into(), json!("content")); + } + push_effect(s, ¶ms, EffectKind::Anchor, BlendMode::Normal) +} + +/// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer +/// `reader` (None: leave it as it is; `Some(None)`: remove it). +fn micro_param(s: &Session, cmd: &str, reader: LayerId, params: &Value, current: Option) -> Result>> { + let amount = match params.get("microAmount") { + Some(value) => Some(value.as_f64().filter(|v| v.is_finite()).ok_or_else(|| bad(cmd, "`microAmount` must be a number 0..1"))?.clamp(0.0, 1.0) as f32), + None => None, + }; + let anchor = match params.get("microAnchor") { + None => current.map(|m| m.anchor), + Some(Value::Null) => return Ok(Some(None)), + Some(value) => Some(LayerId(value.as_u64().ok_or_else(|| bad(cmd, "`microAnchor` must be an anchor effect id or null"))?)), + }; + let Some(anchor) = anchor else { + return match amount { + Some(_) => Err(bad(cmd, "give `microAnchor` before `microAmount`: the generator has no micro detail")), + None => Ok(None), + }; + }; + if params.get("microAnchor").is_none() && amount.is_none() { + return Ok(None); + } + // The same rule as fills: an anchor below, in the same texture set. + anchor_source(s, cmd, reader, anchor, Channel::Height)?; + let amount = amount.or(current.map(|m| m.amount)).unwrap_or(MicroDetail::DEFAULT_AMOUNT); + Ok(Some(Some(MicroDetail { anchor, amount }))) +} + fn add_generator(session: &mut Session, params: &Value) -> Result { let kind = match strp(params, "generator") { Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?, @@ -382,6 +421,10 @@ fn add_generator(session: &mut Session, params: &Value) -> Result { }; let mut generator = Generator::new(kind); generator_from("effect.add.generator", params, &mut generator)?; + let reader = layer_param(session, "effect.add.generator", params)?; + if let Some(micro) = micro_param(session, "effect.add.generator", reader, params, None)? { + generator.micro = micro; + } let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal); push_effect(session, params, EffectKind::Generator(generator), blend) } @@ -471,6 +514,13 @@ fn set(session: &mut Session, params: &Value) -> Result { } _ => None, }; + let micro = match session.doc.project.effect(effect) { + Some((owner, Effect { kind: EffectKind::Generator(generator), .. })) => micro_param(session, CMD, owner, params, generator.micro)?, + _ if params.get("microAnchor").is_some() || params.get("microAmount").is_some() => { + return Err(bad(CMD, "`microAnchor` and `microAmount` edit generator effects only")); + } + _ => None, + }; // Naming the filter the effect already is edits its parameters like a plain effect.set let swapped = match strp(params, "filter") { @@ -505,7 +555,12 @@ fn set(session: &mut Session, params: &Value) -> Result { } match &mut edited.kind { - EffectKind::Generator(generator) => generator_from(CMD, params, generator)?, + EffectKind::Generator(generator) => { + generator_from(CMD, params, generator)?; + if let Some(micro) = micro { + generator.micro = micro; + } + } EffectKind::Levels(levels) => levels_from(params, levels), // The swapped filter was built with the parameters already EffectKind::Filter(_) if swaps_filter => {} diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index b5eedd1e..d10524fb 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -96,6 +96,72 @@ fn anchor_points_feed_masks_above() { assert!(inspect.to_string().contains(&format!("\"anchor\":{anchor}")), "{inspect}"); } +#[test] +fn anchor_points_in_masks_record_the_mask_for_layers_above() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 0.0]})).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"value": 0.4})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({"target": "mask", "name": "Wear"})).unwrap(), "effect"); + let layer = s.doc.project.layer(LayerId(low)).unwrap(); + assert!(layer.mask.as_ref().unwrap().effects.iter().any(|e| e.id.0 == anchor), "in the mask"); + assert!(layer.content_effects.is_empty(), "not on the content"); + // Without a target it still goes on the content, as before. + let content = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == content)); + + // Folders take anchors in their masks only. + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + assert!(execute(&mut s, "effect.add.anchor", &json!({"layer": folder})).is_err(), "folder content"); + execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap(); + + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); + // The low layer shows at 0.4 (black over the 0.5 default), the top one at the anchor's 0.4. + let low_shown = 0.5 * 0.6; + let expected = low_shown + (1.0 - low_shown) * 0.4; + assert!(close(center(&mut s, Channel::BaseColor), [expected; 3]), "{:?}", center(&mut s, Channel::BaseColor)); +} + +#[test] +fn generators_read_an_anchor_height_as_micro_detail() { + let mut s = session(); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 0.5})).unwrap(), "layer"); + let anchor = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap(), "layer"); + + // The anchor must be below; `microAmount` needs an anchor; ids must be numbers. + assert!(execute(&mut s, "effect.add.generator", &json!({"layer": low, "microAnchor": anchor})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAmount": 0.5})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": "x"})).is_err()); + assert!(execute(&mut s, "effect.add.generator", &json!({"microAnchor": low})).is_err(), "not an anchor point"); + + let generator = id(execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "noise": 0.0})).unwrap(), "effect"); + let plain = center(&mut s, Channel::BaseColor); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let raised = center(&mut s, Channel::BaseColor); + assert!(raised[0] > plain[0] + 0.1, "{plain:?} -> {raised:?}"); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + assert!(inspect.to_string().contains(&format!("\"micro\":{{\"amount\":1.0,\"anchor\":{anchor}}}")), "{inspect}"); + + // The amount alone keeps the anchor; null removes the micro detail. + execute(&mut s, "effect.set", &json!({"effect": generator, "microAmount": 0.0})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), plain)); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": null})).unwrap(); + assert!(s.doc.project.effect(LayerId(generator)).map(|(_, e)| matches!(&e.kind, EffectKind::Generator(g) if g.micro.is_none())).unwrap()); + assert!(execute(&mut s, "effect.set", &json!({"effect": anchor, "microAmount": 0.5})).is_err(), "generators only"); + + // A copied generator with micro detail needs the anchor below its new layer. + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": top, "target": generator})).unwrap(); + execute(&mut s, "effect.copy", &json!({"effect": generator})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": low})).unwrap(); + assert!(execute(&mut s, "effect.paste", &json!({"target": "mask"})).is_err()); + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); +} + #[test] fn painting_into_a_content_paint_effect() { let mut s = session(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 0bb90ccd..9a144532 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,7 +6,7 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, - LinkParam, MaterialLink, ProceduralKind, Projection, Source, + LinkParam, MaterialLink, MicroDetail, ProceduralKind, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; use texturecraft_engine::paint::{BrushAlpha, alphas}; @@ -221,7 +221,7 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { 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 to the content + // 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})), @@ -229,11 +229,10 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { (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!({})), + (tr("Add anchor point"), "effect.add.anchor", json!({"target": target})), ]; for (label, command, params) in items { - let enabled = command != "effect.add.anchor" || !layer.is_group(); - if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + if !ui.button(label).clicked() { continue; } @@ -555,9 +554,17 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); + let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == eid.0); + if renaming { + let name_rect = Rect::from_min_max(pos2(x0 + 36.0, rect.top() + 2.0), pos2(rect.right() - 4.0, rect.bottom() - 2.0)); + effect_rename_editor(app, ui, name_rect, e); + } else { + p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); + } if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); + } else if resp.double_clicked() && !renaming { + app.ui.rename = Some((eid.0, e.name.clone())); } else if resp.clicked() { app.run("layer.select", json!({"layer": layer.id.0, "target": eid.0})); } @@ -584,6 +591,10 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef app.run("effect.move", json!({"effect": src.0, "index": index})); } resp.context_menu(|ui| { + if ui.button(tr("Rename effect")).clicked() { + app.ui.rename = Some((eid.0, e.name.clone())); + ui.close(); + } let keymap = app.ui.keymap.clone(); // The row is selected before the paste runs, so a copied effect is all it needs. let paste = texturecraft_engine::effect_clipboard::clipboard_effect(&app.session).is_some(); @@ -609,6 +620,27 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef }); } +/// The name editor of effect row `e` in `rect`: Enter or a click elsewhere renames, Escape cancels. +fn effect_rename_editor(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, e: &Effect) { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::left_to_right(egui::Align::Center))); + let Some((_, buf)) = app.ui.rename.as_mut() else { return }; + // Escape reaches us instead of just unfocusing the field, so it can cancel. + let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; + let r = child.add(egui::TextEdit::singleline(buf).desired_width(rect.width()).font(egui::FontId::proportional(11.5)).event_filter(filter)); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + app.ui.rename = None; + } else if r.lost_focus() { + let name = buf.trim().to_string(); + app.ui.rename = None; + if !name.is_empty() && name != e.name { + app.run("effect.set", json!({"effect": e.id.0, "name": name})); + } + } else if !r.has_focus() { + // Only until the field has focus (see the layer rename editor). + r.request_focus(); + } +} + /// The Geometry mask tool: what a click does, and the selected layer's parts. fn geometry_tool_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); @@ -1681,10 +1713,38 @@ fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(LayerId, String .map(|(id, _)| id) .take_while(|id| *id != reader) .filter_map(|id| p.layers.get(&id)) - .flat_map(|l| l.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Anchor)).map(move |e| (e.id, format!("{} / {}", l.name, e.name)))) + .flat_map(|l| { + let mask = l.mask.iter().flat_map(|m| m.effects.iter()).filter(|e| matches!(e.kind, EffectKind::Anchor)); + let mask = mask.map(|e| (e.id, trf("{layer} / mask / {name}", &[("layer", &l.name), ("name", &e.name)]))); + let content = l.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Anchor)).map(|e| (e.id, format!("{} / {}", l.name, e.name))); + content.chain(mask).collect::>() + }) .collect() } +/// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). +fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { + let p = &app.session.doc.project; + p.effect(anchor).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.mask.iter().flat_map(|m| m.effects.iter()).any(|e| e.id == anchor)) +} + +/// The anchor points of `anchors` as menu entries under their own heading (a note when there +/// are none); returns the one clicked. +fn anchor_entries(ui: &mut Ui, anchors: &[(LayerId, String)], current: Option) -> Option { + ui.separator(); + ui.label(caption(tr("Anchor points"))); + if anchors.is_empty() { + ui.label(RichText::new(tr("No anchor point below this layer")).color(Tokens::get(ui.ctx()).text_dim)); + } + let mut picked = None; + for (anchor, label) in anchors { + if ui.selectable_label(current == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { + picked = Some(*anchor); + } + } + picked +} + fn anchor_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> String { let name = app.session.doc.project.effect(anchor).map(|(_, e)| e.name.clone()).unwrap_or_else(|| tr("missing").into()); trf("Anchor: {name} ({channel})", &[("name", &name), ("channel", &tr(channel.label()))]) @@ -1895,14 +1955,9 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu if let Some(name) = image_menu(app, ui) { app.run("layer.fill.set", set(json!({"image": name}))); } - if !anchors.is_empty() { - ui.separator(); - } - for (a, label) in anchors { - if ui.button(trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("layer.fill.set", set(json!({"anchor": a.0}))); - ui.close(); - } + if let Some(a) = anchor_entries(ui, anchors, fill.source(c).anchor()) { + app.run("layer.fill.set", set(json!({"anchor": a.0}))); + ui.close(); } }) .response @@ -2006,7 +2061,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ui.separator(); match &effect.kind { - EffectKind::Generator(generator) => generator_properties(app, ui, id, generator), + EffectKind::Generator(generator) => generator_properties(app, ui, id, generator, layer.id), EffectKind::Levels(levels) => { ui.label(caption(tr("Levels"))); levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high)); @@ -2037,10 +2092,8 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { app.run("effect.set", json!({"effect": id, "value": 1.0})); } - for (anchor, label) in &anchors { - if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() { - app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); - } + if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { + app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); } }); match source { @@ -2050,6 +2103,9 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } + Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { + ui.label(RichText::new(tr("A mask anchor reads as its mask's gray.")).color(tk.text_dim)); + } Source::Anchor { channel, .. } => { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); combo(ui, tr("Channel"), tr(channel.label()), |ui| { @@ -2074,10 +2130,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } EffectKind::Anchor => { ui.label(caption(tr("Anchor point"))); - ui.label( - RichText::new(tr("Records the stack up to this layer. Fill effects in masks (and fill layers) above can read it as a source.")) - .color(tk.text_dim), - ); + let text = if anchor_in_mask(app, eid) { + 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(tk.text_dim)); } EffectKind::Paint => { let hint = if layer.content_effects.iter().any(|content| content.id == eid) { @@ -2120,7 +2178,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } /// The settings of generator effect `id`. -fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { +fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator, reader: LayerId) { let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Generator"))); egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| { @@ -2150,11 +2208,43 @@ fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generat if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { curvature_detail_properties(app, ui, id, generator.detail.as_ref()); } + if !matches!(generator.kind, GeneratorKind::ThinAreas | GeneratorKind::Position | GeneratorKind::Direction) { + micro_detail_properties(app, ui, id, generator.micro, reader); + } if !app.session.doc.baked.contains_key(&app.session.ts()) { ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning)); } } +/// The micro detail of generator effect `id` on layer `reader`: an anchor point below whose height +/// moves the generated mask, and how much. +fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micro: Option, reader: LayerId) { + let tk = Tokens::get(ui.ctx()); + ui.label(caption(tr("Micro detail"))) + .on_hover_text(tr("Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.")); + let anchors = anchors_below(app, reader); + let current = match micro { + Some(m) => anchors.iter().find(|(a, _)| *a == m.anchor).map_or_else(|| tr("missing").to_string(), |(_, label)| label.clone()), + None => tr("None").to_string(), + }; + combo(ui, tr("Anchor point"), current, |ui| { + if ui.selectable_label(micro.is_none(), tr("None")).clicked() { + app.run("effect.set", json!({"effect": id, "microAnchor": null})); + } + if let Some(anchor) = anchor_entries(ui, &anchors, micro.map(|m| m.anchor)) { + app.run("effect.set", json!({"effect": id, "microAnchor": anchor.0})); + } + }); + if let Some(m) = micro { + let mut amount = m.amount; + if let Some(merge) = slider_edit(ui, tr("Amount"), &mut amount, 0.0..=1.0, 2) { + app.run("effect.set", json!({"effect": id, "microAmount": amount, "merge": merge})); + } + } else if anchors.is_empty() { + ui.label(RichText::new(tr("Add an anchor point to a layer below to use its height as micro detail.")).color(tk.text_dim)); + } +} + /// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes). fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 2d07340b..b69bd0f8 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1094,4 +1094,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), + ("A mask anchor reads as its mask's gray.", "تُقرأ نقطة الارتكاز في القناع كرمادي ذلك القناع."), + ("Add an anchor point to a layer below to use its height as micro detail.", "أضف نقطة ارتكاز إلى طبقة أدناه لاستخدام ارتفاعها كتفاصيل دقيقة."), + ("Anchor points", "نقاط الارتكاز"), + ("Micro detail", "تفاصيل دقيقة"), + ("No anchor point below this layer", "لا توجد نقطة ارتكاز أسفل هذه الطبقة"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "الارتفاع المرسوم من نقطة ارتكاز أدناه: تُقرأ المناطق البارزة كحواف والمنخفضة كتجاويف.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "تسجّل قيمة القناع عند هذه النقطة. يمكن لتأثيرات التعبئة والمولّدات في الأقنعة أعلاه قراءتها.", + ), + ("Rename effect", "إعادة تسمية التأثير"), + ("{layer} / mask / {name}", "{layer} / القناع / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 03cbb436..d561140b 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1143,4 +1143,22 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", ), + ("A mask anchor reads as its mask's gray.", "Ein Masken-Anker liest sich als das Grau seiner Maske."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Füge einer Ebene darunter einen Ankerpunkt hinzu, um ihre Höhe als Mikrodetail zu nutzen.", + ), + ("Anchor points", "Ankerpunkte"), + ("Micro detail", "Mikrodetail"), + ("No anchor point below this layer", "Kein Ankerpunkt unter dieser Ebene"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Gemalte Höhe eines Ankerpunkts darunter: Erhöhungen wirken als Kanten, Vertiefungen als Hohlräume.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Zeichnet den Maskenwert an dieser Stelle auf. Füll-Effekte und Generatoren in Masken darüber können ihn lesen.", + ), + ("Rename effect", "Effekt umbenennen"), + ("{layer} / mask / {name}", "{layer} / Maske / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index e115665a..b06592fc 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1131,4 +1131,22 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", ), + ("A mask anchor reads as its mask's gray.", "Un ancla de máscara se lee como el gris de su máscara."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Añade un punto de anclaje a una capa inferior para usar su altura como microdetalle.", + ), + ("Anchor points", "Puntos de anclaje"), + ("Micro detail", "Microdetalle"), + ("No anchor point below this layer", "Ningún punto de anclaje bajo esta capa"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altura pintada de un punto de anclaje inferior: las zonas elevadas se leen como bordes y las hundidas como cavidades.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Registra el valor de la máscara en este punto. Los efectos de relleno y los generadores de las máscaras superiores pueden leerlo.", + ), + ("Rename effect", "Renombrar efecto"), + ("{layer} / mask / {name}", "{layer} / máscara / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 51fcdc51..28b43ac8 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1155,4 +1155,22 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", ), + ("A mask anchor reads as its mask's gray.", "Une ancre de masque se lit comme le gris de son masque."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Ajoutez un point d'ancrage à un calque inférieur pour utiliser sa hauteur comme micro-détail.", + ), + ("Anchor points", "Points d'ancrage"), + ("Micro detail", "Micro-détail"), + ("No anchor point below this layer", "Aucun point d'ancrage sous ce calque"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Hauteur peinte d'un point d'ancrage inférieur : les zones en relief se lisent comme des arêtes, les creux comme des cavités.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Enregistre la valeur du masque à cet endroit. Les effets de remplissage et les générateurs des masques au-dessus peuvent la lire.", + ), + ("Rename effect", "Renommer l'effet"), + ("{layer} / mask / {name}", "{layer} / masque / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index ad142192..13122894 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1140,4 +1140,22 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", ), + ("A mask anchor reads as its mask's gray.", "Un'ancora di maschera si legge come il grigio della sua maschera."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Aggiungi un punto di ancoraggio a un livello sottostante per usarne l'altezza come microdettaglio.", + ), + ("Anchor points", "Punti di ancoraggio"), + ("Micro detail", "Microdettaglio"), + ("No anchor point below this layer", "Nessun punto di ancoraggio sotto questo livello"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altezza dipinta da un punto di ancoraggio sottostante: le zone in rilievo si leggono come bordi, quelle incavate come cavità.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Registra il valore della maschera in questo punto. Gli effetti di riempimento e i generatori nelle maschere sopra possono leggerlo.", + ), + ("Rename effect", "Rinomina effetto"), + ("{layer} / mask / {name}", "{layer} / maschera / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 6fe4bdd0..5cbec53f 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1122,4 +1122,22 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), + ("A mask anchor reads as its mask's gray.", "マスクのアンカーはマスクのグレーとして読み取られます。"), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "下のレイヤーにアンカーポイントを追加すると、その高さをマイクロディテールとして使えます。", + ), + ("Anchor points", "アンカーポイント"), + ("Micro detail", "マイクロディテール"), + ("No anchor point below this layer", "このレイヤーの下にアンカーポイントがありません"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "下のアンカーポイントのペイントされた高さ:盛り上がった部分はエッジ、くぼんだ部分はキャビティとして読み取られます。", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "この位置のマスク値を記録します。上のマスクの塗りつぶしエフェクトとジェネレーターが読み取れます。", + ), + ("Rename effect", "エフェクト名を変更"), + ("{layer} / mask / {name}", "{layer} / マスク / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index d34e0f2a..44c911ab 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1107,4 +1107,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), + ("A mask anchor reads as its mask's gray.", "마스크의 앵커는 마스크의 회색 값으로 읽힙니다."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "아래 레이어에 앵커 포인트를 추가하면 그 높이를 마이크로 디테일로 사용할 수 있습니다.", + ), + ("Anchor points", "앵커 포인트"), + ("Micro detail", "마이크로 디테일"), + ("No anchor point below this layer", "이 레이어 아래에 앵커 포인트가 없습니다"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "아래 앵커 포인트의 페인트된 높이: 솟은 부분은 가장자리로, 들어간 부분은 캐비티로 읽힙니다.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "이 지점의 마스크 값을 기록합니다. 위쪽 마스크의 채우기 효과와 생성기가 읽을 수 있습니다.", + ), + ("Rename effect", "효과 이름 바꾸기"), + ("{layer} / mask / {name}", "{layer} / 마스크 / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0ce4f36b..4f0b91fd 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1125,4 +1125,22 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), + ("A mask anchor reads as its mask's gray.", "Uma âncora de máscara é lida como o cinza da máscara."), + ( + "Add an anchor point to a layer below to use its height as micro detail.", + "Adicione um ponto de ancoragem a uma camada abaixo para usar a altura dela como microdetalhe.", + ), + ("Anchor points", "Pontos de ancoragem"), + ("Micro detail", "Microdetalhe"), + ("No anchor point below this layer", "Nenhum ponto de ancoragem abaixo desta camada"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "Altura pintada de um ponto de ancoragem abaixo: áreas elevadas são lidas como bordas, áreas rebaixadas como cavidades.", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "Grava o valor da máscara neste ponto. Efeitos de preenchimento e geradores em máscaras acima podem lê-lo.", + ), + ("Rename effect", "Renomear efeito"), + ("{layer} / mask / {name}", "{layer} / máscara / {name}"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index d2b8845e..6be575dd 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1053,4 +1053,19 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), + ("A mask anchor reads as its mask's gray.", "蒙版中的锚点读取为该蒙版的灰度。"), + ("Add an anchor point to a layer below to use its height as micro detail.", "在下方图层添加锚点,即可将其高度用作微细节。"), + ("Anchor points", "锚点"), + ("Micro detail", "微细节"), + ("No anchor point below this layer", "此图层下方没有锚点"), + ( + "Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.", + "下方锚点绘制的高度:凸起处读取为边缘,凹陷处读取为凹腔。", + ), + ( + "Records the mask value at this point. Fill effects and generators in masks above can read it.", + "记录此处的蒙版值。上方蒙版中的填充效果和生成器可以读取它。", + ), + ("Rename effect", "重命名效果"), + ("{layer} / mask / {name}", "{layer} / 蒙版 / {name}"), ]; diff --git a/docs/features.md b/docs/features.md index a51352da..709cffa0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -42,7 +42,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA blur, directional and slope blur, sharpen, high pass, bevel, glow, warp, directional warp, mosaic and four material finishes), fills and paint. **Levels** shows a histogram of what it reads (the mask below it, or a content channel you pick) with its input range marked. - **Anchor points** record the stack at a layer so masks and fills higher up can react to it. + **Anchor points** record the stack at a layer (or, inside a mask, the mask value at that point) + so masks, fills and generators higher up can react to it; a generator can take an anchor's + painted height as **micro detail**. Double-click an effect to rename it. - **Masks** with a white or black background and a stack of effects: painted strokes, fills, **mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction gradients, all with world-space noise), filters, ID color selection and compare. Alt+click a From 26d82b429cd5dcc225dc7d224af5ffa482a65a6c Mon Sep 17 00:00:00 2001 From: Rafael Mendes Date: Tue, 10 Nov 2026 18:32:29 -0300 Subject: [PATCH 3/9] effect.add.anchor without params goes on the content Null params left the target unset, so the anchor landed in the mask. --- crates/engine/src/mask_cmds.rs | 11 ++++------- crates/engine/tests/it/content_effects.rs | 4 +++- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index e793fbac..363a9b93 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -378,13 +378,10 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S /// An anchor point on the layer content (the default, as before anchors went on masks) or, with /// `target: "mask"`, in its mask. fn add_anchor(s: &mut Session, p: &Value) -> Result { - let mut params = p.clone(); - if p.get("target").is_none() - && let Some(o) = params.as_object_mut() - { - o.insert("target".into(), json!("content")); - } - push_effect(s, ¶ms, EffectKind::Anchor, BlendMode::Normal) + // Params may be null or an object without a target: both default to the content. + let mut params = p.as_object().cloned().unwrap_or_default(); + params.entry("target").or_insert_with(|| json!("content")); + push_effect(s, &Value::Object(params), EffectKind::Anchor, BlendMode::Normal) } /// A generator's micro detail from `microAnchor` / `microAmount` for a generator on layer diff --git a/crates/engine/tests/it/content_effects.rs b/crates/engine/tests/it/content_effects.rs index d10524fb..093597bf 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -106,9 +106,11 @@ fn anchor_points_in_masks_record_the_mask_for_layers_above() { let layer = s.doc.project.layer(LayerId(low)).unwrap(); assert!(layer.mask.as_ref().unwrap().effects.iter().any(|e| e.id.0 == anchor), "in the mask"); assert!(layer.content_effects.is_empty(), "not on the content"); - // Without a target it still goes on the content, as before. + // Without a target (or with no params at all) it still goes on the content, as before. let content = id(execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap(), "effect"); assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == content)); + let bare = id(execute(&mut s, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + assert!(s.doc.project.layer(LayerId(low)).unwrap().content_effects.iter().any(|e| e.id.0 == bare)); // Folders take anchors in their masks only. let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); From 1687736cf04d34911c201c426c5314b9ed0cae23 Mon Sep 17 00:00:00 2001 From: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Date: Sat, 7 Nov 2026 16:35:39 +0100 Subject: [PATCH 4/9] Reject signs and extra digits in hex colour strings Found while testing crates/engine/src/commands.rs:203 (same pattern, plus no length check, at crates/engine/src/link_cmds.rs:98) Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 Co-Authored-By: Claude Haiku 5.5 Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/commands.rs | 10 +++++++++- crates/engine/src/link_cmds.rs | 23 +++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index a03a58a9..adeb0959 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -219,7 +219,7 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()), Value::String(s) => { let s = s.trim_start_matches('#'); - if s.len() != 6 { + if s.len() != 6 || !s.bytes().all(|b| b.is_ascii_hexdigit()) { return None; } let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| texturecraft_texel::srgb_to_linear(v as f32 / 255.0)); @@ -275,4 +275,12 @@ mod tests { let overflow_scalar = json!({ "color": 1e40 }); assert!(color_param("test.cmd", &overflow_scalar, "color").is_err()); } + + #[test] + fn hex_color_rejects_signs_and_non_hex() { + assert_eq!(color_of(&json!("#+f+f+f")), None); + assert_eq!(color_of(&json!("#-00000")), None); + assert_eq!(color_of(&json!("#GGGGGG")), None); + assert!(color_of(&json!("#ff8000")).is_some()); + } } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 3a77ae50..603cd0fa 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -97,6 +97,9 @@ pub fn typed(param: &LinkParam, v: &Value) -> Option { ("bool", x) => json!(num(x)? != 0.0), ("color", Value::String(hex)) => { let h = hex.trim_start_matches('#'); + if h.len() != 6 || !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } let c = |i: usize| Some(f64::from(u8::from_str_radix(h.get(i..i + 2)?, 16).ok()?) / 255.0); // Hex colors are sRGB; values are linear. let lin = |x: f64| if x <= 0.04045 { x / 12.92 } else { ((x + 0.055) / 1.055).powf(2.4) }; @@ -551,3 +554,23 @@ esac let _ = std::fs::remove_dir_all(dir); } } + +#[cfg(test)] +mod tests { + use super::typed; + use serde_json::json; + use texturecraft_core::layer::LinkParam; + + fn color_param() -> LinkParam { + let c = json!({"t": "color", "v": [0.0, 0.0, 0.0, 1.0]}); + serde_json::from_value(json!({"id": "c", "label": "C", "value": c, "default": c})).unwrap() + } + + #[test] + fn hex_color_rejects_signs_and_extra_digits() { + let p = color_param(); + assert_eq!(typed(&p, &json!("#aabbccdd")), None); + assert_eq!(typed(&p, &json!("#+f+f+f")), None); + assert!(typed(&p, &json!("#ff8000")).is_some()); + } +} From 2de0338ce2591de5a395587cb39ffe375c505f3b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Mon, 16 Nov 2026 19:50:43 -0500 Subject: [PATCH 5/9] Detailed parity checked --- ROADMAP.md | 279 ++++++++++++++++++++++++++++++++++++++-------- docs/ui-parity.md | 122 ++++++++++++++++++++ 2 files changed, 352 insertions(+), 49 deletions(-) create mode 100644 docs/ui-parity.md diff --git a/ROADMAP.md b/ROADMAP.md index 1a70d26d..ac0340c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,62 +1,243 @@ # TextureCraft roadmap -TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing workflow, with better -performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and -builds for Windows, macOS, Linux, FreeBSD and the web. +Stage: alpha (readiness assessment) · next: beta, ~75% readiness plus scoped compatibility and integration gates; remaining effort unestimated -## Honest parity estimate (2026-11-04) +> Last reviewed: 2026-11-16 · Last updated: 2026-11-16 · Change: major (UI/functionality audit, possible format/package reworks, unfinished `.mcmat` integration and incoming ArtCraft UI/shared-library work) · Target: reference app 12.2.0 -Weighted by how much of a professional's daily work each area carries. "Done" counts what works -end to end today (engine + UI + automation + tests), not what is planned. +TextureCraft is a clean-room implementation of the professional texture-painting workflow. This +assessment covers **main at [62b2b13](https://github.com/storytold/texturecraft/commit/62b2b13fdd32740b6e118cd00c5e0d0c12b30815), +version 0.6.1**, compared with the installed reference app on 2026-11-16. It follows the +[PhotoCraft roadmap format](https://github.com/storytold/photocraft/blob/main/ROADMAP.md). +Detail: [UI gaps and functional task audit](docs/ui-parity.md), [features](docs/features.md), [menu checklist](docs/parity.md), +[architecture](docs/architecture.md), [automation](docs/control-protocol.md), +[localization](docs/localization-parity.md), [releasing](docs/releasing.md). -| Area | Weight | Done | What works | Main gaps | +**Format direction:** `.tcraft` remains the native editable project format. Read-only opening/import +of `.spp` is a future compatibility goal: leave the source untouched and save converted work as +`.tcraft`. Supported versions, recoverable layers/resources and handling of unsupported content +still need investigation; no `.spp` reader is implemented. Writing `.spp`, round-tripping edits +back into it and compatibility with other proprietary asset/preset formats are outside this goal. +Pipeline exchange uses USD, glTF/GLB, MaterialX and texture maps. + +The current `.tcraft` schema/container and output-package contracts may be reworked; their +present implementations are not a frozen design. MaterialCraft `.mcmat` import remains a goal +whose next format is unfinished upstream. ArtCraft UI refactoring and further shared-library +adoption also add integration and regression work. These dependencies are part of the remaining +roadmap, even where a current task already passes. + +## Headline numbers + +| | Value | Kind | +|---|---|---| +| Feature breadth | ~80% (75–85%) | Estimated across feature families; no exhaustive target inventory | +| Ready for real work | ~60% (50–70%) | Estimated readiness of the assessed revision; no completion credit for incoming reworks/integrations | +| Mainstream practitioner | ~60% (50–70%) | Estimated for regular asset texturing, baking, masking and pipeline delivery | +| Essentials user | ~75% (65–85%) | Estimated for a simple mesh, layered materials/paint and texture export | +| Desktop menu catalog | 59/59 live | Observed through the running app; this is TextureCraft's own catalog | +| Engine commands | 178 registered | Observed through the running app; registration does not prove every parameter path | +| Functional review | 20 scoped check groups | UI, mixed-surface and command cases [recorded separately](docs/ui-parity.md#functional-task-audit); not an exhaustive coverage score | +| Remaining to beta | Unestimated | Requires acceptance tasks, performance budgets and a decision on required format/package/UI migrations | +| Remaining to full scoped parity | Unestimated | Includes possible `.tcraft`/output reworks, upstream `.mcmat`, ArtCraft UI/shared-library adoption, `.spp` feasibility and workflow/fidelity work | + +The former ~94% figure mostly counted implementation paths. This review also asks whether an +artist gets equivalent controls, predictable output, responsive interaction and dependable +delivery. The change is a measurement rebaseline and an expanded import goal, not a measured +loss of functionality. Percentages are rounded judgments; ranges express uncertainty, not +statistical confidence intervals. The old “~6 h + baking TBD” remainder is withdrawn: this +review provides no calibrated engineering or agent-hour forecast. + +The percentages describe behavior at `62b2b13`, not how much of a settled delivery plan is +finished. Potential rework can revisit working code and require repeating the checks below. +Its scope and cost are not yet measured, so remaining effort cannot be calculated as +100 minus the readiness score. Incoming upstream work is not counted as landed functionality. + +### Readiness by audience + +| Audience | Ready % | Hours to ~95% | Work that dominates | +|---|---|---|---| +| Full scoped target | ~60% | Unestimated | Workflow depth, format/output-package decisions, `.mcmat`, ArtCraft UI/shared libraries, bake/display fidelity, color management, read-only `.spp` and platform validation | +| Mainstream practitioner | ~60% | Unestimated | Reliable masks/painting, MaterialCraft exchange once its contract is ready, project/package compatibility, larger projects and destination-app checks | +| Essentials user | ~75% | Unestimated | Discoverable controls, predictable startup/GPU selection and save/reopen reliability retained through format/UI migrations | + +Why alpha. Mouse/keyboard tasks verified 3D/2D painting, undo/redo, material drag and drop, mask +and generator editing, UV rectangle fill, UI baking, native saving and texture export. Separate +command checks covered high-to-low transfer, UDIM sizes/packing and scene/material exports. +The interface is recognizably close in its painting, bake and export workspaces, but still lacks +mask-thumbnail effect menus, effect renaming, several fill controls and a MaterialX export option. +Generator depth is limited, bake equivalence is open, +and hardware/performance coverage is incomplete. There were **96 open issues** on the review date; +these include requests and older reports, not 96 reproduced defects. The published +[v0.6.1 release](https://github.com/storytold/texturecraft/releases/tag/v0.6.1) already exists; +“first release v0.1.0” is no longer an upcoming milestone. + +Native/output contracts and the future MaterialCraft, ArtCraft UI and shared-library integrations +also remain unsettled. Passing a legacy reader or a standalone export check does not complete +those future workflows. + +A proposed beta gate is ~75% readiness plus repeatable artist tasks on representative assets: +high/low baking and smart masks, precise 3D/2D painting, a multi-set UDIM project, save/reopen +without lost work, and exports checked in destination tools. Startup failures and data-loss +blockers on the supported test matrix must be resolved. This audit does not establish that gate. +Beta scope must identify which reworks/integrations it requires and which remain later goals. +Every adopted project/package version needs a compatibility policy and regression checks; +MaterialCraft exchange must be validated against a named producer/consumer version pair before +it is advertised as ready. + +## By dimension + +All percentages below are estimates. The weights sum to 100; their additive result is 59.1%, +rounded to ~60%. Hardware, performance and stability scores include confidence discounts for +incomplete validation; they are not measured success rates or speed comparisons. + +| Dimension | % ready | Weight | Hours to full | Evidence / remaining work | |---|---:|---:|---|---| -| Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | -| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | -| Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | -| Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, material picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure in the 3D and 2D views (Windows Ink, and touch pens in the browser), procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt, and pen pressure on Linux, macOS and desktop browsers (not exposed by the windowing layer) | -| Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 24 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | -| Baking | 10 | 90% | All ten mesh-map bakers; low-poly and high-to-low baking with CPU/GPU tracing; mesh-name matching, backface filtering, custom and distance-based cages, frontal/rear distances and average normals; undoable 2D cage/skew painting saved per texture set; rectangular output, antialiasing, dilation/diffusion, ID sources, ray filters, AO attenuation/ground plane, curvature controls and map normalization; per-texture-set selection, progress/cancel and mesh-map import | Residual Painter map differences; reference validation for Height, Bent Normal and Opacity and across additional assets; 3D cage-editing overlay | -| Viewport and display | 12 | 95% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, the baked normal map under the painted normal, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes of the mesh's own polygons, brush cursor, axis gizmos, subsurface scattering blur, **depth of field**, saved cameras and cameras from glTF, FBX, COLLADA and USD files, displacement (also in shadows and the path tracers), **path-traced Rendering mode** (F10, on the GPU or the CPU) with environment importance sampling and an edge-aware **denoiser**; picks a discrete GPU on multi-GPU machines (`--gpu`, `WGPU_ADAPTER_NAME`, `WGPU_POWER_PREF`), and display textures are made on demand so a mesh with many materials imports on a small GPU | Hardware ray tracing | -| Shader | 6 | 100% | Metallic/roughness and specular/glossiness PBR, **clear coat, sheen, anisotropy and subsurface scattering** (viewport and path tracer), height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | — | -| Export | 8 | 92% | 10 presets (incl. Godot 4 and **OpenPBR** with every shading lobe) plus **user output templates** (per-channel packing, converted maps, JSON import/export), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, **colour space** of the colour maps (sRGB, Linear Rec.709, ACEScg, ACES2065-1; data maps never converted; the chosen space is recorded in the file as an ICC profile in PNG, JPEG, TIFF and WebP and as chromaticities in EXR), `$udim` tiles, **MaterialX** (`file.exportTextures` with `materialX`: a `.mtlx` OpenPBR material per set, `` aware), OBJ with MTL and maps, textured GLB (with clearcoat/sheen) and USD (with clear coat) mesh export, zip download in the browser | Sheen and anisotropy in USD (UsdPreviewSurface has no inputs for them; GLB and OpenPBR maps carry them) | -| UI and UX | 8 | 97% | Painter-style layout with **dockable, tabbed, floating panels**, menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history/log panels, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave, viewport texture resolution, system title bar), **own title bar** with the app icon and window buttons (Windows, GNOME; integrated with the macOS traffic lights), saved UI layouts, a **History** panel that jumps to any step (back or forward), a **start window** (new, open, recent projects), **shortcut editor** with conflict detection, tooltips with shortcuts, a compact color picker (saturation/value square, hue strip, copyable RGB); all menu items live ([docs/parity.md](docs/parity.md)); **10 UI languages** with CJK and Arabic fonts ([docs/localization-parity.md](docs/localization-parity.md)); closed panels reopen where they were; frame-budgeted compositing and uploads keep 8K sets responsive | Native-speaker review of the translations | -| Platforms | 4 | 76% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish | -| **Total** | **100** | **≈ 94%** | Weighted workflow-completion estimate | | +| Features (depth) | ~65% | 30 | TBD | Core editing tasks and high/low/UDIM outputs exercised; generators, properties, mask anchors and specialized workflows need depth | +| UI/UX fidelity | ~65% | 20 | TBD | Current editing/bake/export UI checked; [gaps](docs/ui-parity.md), ArtCraft UI adoption and revalidation after refactoring remain | +| File formats / interchange | ~60% | 10 | TBD | Current native save and basic exports exercised; possible `.tcraft`/output-package reworks, unfinished upstream `.mcmat`, `.spp` and consumer validation remain | +| Hardware (GPU, pen, displays) | ~50% | 8 | TBD | One Windows GPU exercised; pen tilt, pressure across platforms and display coverage remain incomplete | +| Localization | ~35% | 4 | TBD | Ten picker languages in source; optional shared catalogs/fonts and native-language review need current measurement | +| Performance | ~40% | 10 | TBD | Dirty-tile/budgeted architecture and benchmark code exist; no matched performance budgets or large-project results from this review | +| Stability | ~55% | 10 | TBD | Small save/reopen and undo/redo passed; recovery, large projects and long sessions need coverage, including after format/library migrations | +| Platforms | ~65% | 3 | TBD | Desktop/web build and packaging paths exist; this review ran Windows only | +| Automation / ecosystem | ~75% | 5 | TBD | 178 commands and CLI/control/MCP architecture; shared-library adoption, command/UI compatibility and the future MaterialCraft contract need integration checks | -Baking’s 90% estimates workflow completion: all ten map types and exposed settings have implementation -paths, with the remaining work listed above. Pixel-level equivalence with Painter remains unverified. +## Features -Beyond the reference app: every command is available to agents through MCP, the CLI and the app's -control channel (MCP workspace tools cover every file action: projects, meshes, high polys and -the cage, resources, smart materials, textures and mesh export), and the whole engine runs headless. +These are approximate depth/readiness estimates, not percentages of matching pixels or completed +menu entries. Feature rows overlap and are not an additional additive score. -## Remaining effort +| Area | % ready | Hours | What works / main gaps | +|---|---:|---|---| +| Projects and files | ~80% | TBD | Current `.tcraft` new/save/reopen passed with layers, effects and baked maps retained. Schema/container rework remains possible; versioning/migration policy and renewed persistence/recovery tests are needed if adopted. Large cases, Alembic HDF5 and animation remain open | +| Texture sets and UDIM | ~80% | TBD | Two tiles exported at independent 128/256 px sizes with expected packed-channel values; 21 channel kinds in source. Many-set/many-tile production coverage remains untested | +| Layers, masks and effects | ~75% | TBD | UI fill/black-mask creation, generator editing/duplication and native persistence passed. Mask-thumbnail context actions, UI effect renaming and mask-stack anchors remain missing | +| Painting and precise 2D work | ~70% | TBD | Mouse painting in both views, keyboard undo/redo, view shortcuts, brush gesture and UV-island rectangle fill passed. Nine tool kinds exist; brush feel, pressure/tilt, other tool task suites and complete trim sheets need validation | +| Generators and smart masks | ~45% | TBD | Seven generator kinds and 24 smart-mask presets; Position/global-balance editing worked in the UI. Shared adjustments, resolution and input slots exist; richer generators, micro-detail workflows and saving user smart masks remain incomplete | +| Materials and asset library | ~60% | TBD | 72 procedural materials and 21 smart materials; shelf search/drop worked. Legacy MaterialCraft paths exist, but the planned `.mcmat` contract is unfinished upstream. Library variety, previews and cross-app integration remain work | +| MaterialCraft `.mcmat` integration | Incomplete; upstream-dependent | TBD after contract | Current reader accepts legacy v1/v2. The proposed MaterialX-based v3 still needs upstream completion, shared-library support, TextureCraft mapping/UI and tests with real producer outputs; this is not a completed material exchange workflow | +| Baking | ~60% | TBD | All ten maps completed through the UI on CPU at 256 px and through commands on GPU at 128 px. Separate high/low normal/height transfer produced varying maps; cross-app pixel equivalence, larger assets and resolution-stable wear remain unproven | +| Viewport, shading and rendering | ~70% | TBD | PBR/IBL, extra shading lobes, 3D/2D views, displacement and CPU/GPU path-tracing paths. Matching material/display behavior, larger scenes and hardware ray tracing remain open | +| Color management | ~35% | TBD | Linear/sRGB handling, fixed export spaces and profile metadata; display model has Linear/ACES-filmic tone mapping. Configurable OCIO project/display workflows are absent | +| Texture and scene export | ~75% | TBD | Current PNG/UDIM/USD/GLB/MaterialX checks passed within scope. Output-package layout/content may be reworked; package contracts and consumers need separate validation. MaterialX UI output, complex materials and larger UDIM assets remain incomplete | +| Read-only `.spp` compatibility | 0% | TBD after feasibility study | Planned; no reader, version matrix or import-fidelity corpus. `.tcraft` remains the save format | +| Workspace, panels and preferences | ~65% | TBD | Current views/layouts checked; narrow labels truncate. Incoming ArtCraft UI refactoring/shared components can change these surfaces; task, shortcut, accessibility and layout/preferences persistence checks must be repeated | +| Automation | ~80% | TBD | Command inspection and scripted editing/export work; UI, CLI and MCP surfaces share engine commands. This review exercised the control channel and CLI, not every MCP/tool path | -Estimated in wall-clock hours of Claude Opus 5.5 agent work, with three or four agents working in -parallel on separate crates: +Source checks matter here: [generator kinds](crates/core/src/layer.rs) number seven even though +their shared controls have grown; [polygon fill](crates/engine/src/fill_mode.rs) already includes +triangle, polygon, UV-island and mesh modes. Current [MaterialCraft import](crates/formats/src/mcmat.rs) +accepts v2 and recognizes the newer source archive layout. That is legacy compatibility, not +completion of the next `.mcmat` integration. The [upstream v3 proposal](https://github.com/storytold/materialcraft/issues/190) +describes MaterialX plus resources in equivalent folder/ZIP deliveries and excludes native source. +Its proposed exposed controls differ from re-cooking an embedded authoring graph. The final +supported subset, version policy and authoring/re-cook workflow must be agreed and tested; +the legacy promise must not be carried forward automatically. -| Milestone | Scope | Estimate | -|---|---|---:| -| M1 Layer stack depth | Done | 0 h | -| M2 Tools | Pen tilt, and pen pressure on Linux, macOS and desktop browsers, once the windowing layer reports them | 0.5 h | -| M3 Assets | Done | 0 h | -| M4 Baking | Validate outputs across reference assets, refine remaining map differences and add 3D cage editing | TBD | -| M5 Viewport | Hardware ray tracing: wgpu's ray queries are experimental and need an `unsafe` opt-in, which the workspace forbids (owner decision) | 1.5 h | -| M6 Shader | Done | 0 h | -| M7 Formats | Done | 0 h | -| M8 UX | Native review of translations | 1 h | -| M9 Release | The twelve signing secrets and the Default runner group (org admin); first signed release run on every platform (v0.1.0); web deployment; Flathub submission | 3 h | -| **Total** | | **≈ 6 h + baking TBD** | +The [UI gap inventory](docs/ui-parity.md#missing-controls-and-workflows) records reproduction +routes and acceptance checks: mask context/rename/save/export actions; independent U/V tiling, +filtering/wrap, physical-size and warp/per-tile projections; mask anchors; MaterialX UI output; +and configurable color-management settings. Generator depth and narrow-layout readability are +tracked as partial areas. Direct hardness/angle controls and polygon/UV rectangle fill already +exist; older reports must not turn them into fresh missing-feature claims. -## Current focus +### Evidence from this review -1. Release v0.1.0 (M9): CI (fmt, clippy, the full test suite, layering and wasm on Linux and - Windows) is green on `main`, and the `release` environment and branch ruleset exist. Left: an - org admin syncs the twelve signing secrets and checks the Default runner group - ([docs/releasing.md](docs/releasing.md)), then the first release run on every platform. -2. Hardware ray tracing in Rendering mode (M5) waits on an owner decision: wgpu exposes ray - queries only as an experimental feature behind an `unsafe` opt-in, and the workspace forbids - `unsafe` (craftrules allows it only in an isolated, tested helper crate). -3. Pen tilt, and pen pressure on Linux, macOS and desktop browsers (M2), once the windowing - layer reports them; Alembic files in the HDF5 container and Alembic animation. +| Check | Result and limit | +|---|---| +| Baseline/build | Fetched `origin/main`; HEAD matched `62b2b13`. `cargo build -p texturecraft -p texturecraft-cli --profile verify` passed; binary reported 0.6.1 and that revision | +| Reference UI/functionality | On an original UV cube, pointer painting, paint/fill/black-mask creation and an empty generator slot worked; seven-map self-bake at 1024 px completed. Inspected fill/projection/scale menus, mask menu and export dialog. The “Read only” title did not prevent these edits; reference save/export and output equivalence remain unchecked | +| TextureCraft UI tasks | Mouse/keyboard new project, 3D/2D strokes, Ctrl+Z/Y, F1/F2/F3, brush gesture, shelf search/drop, black mask, Position generator/global balance and effect duplication worked. UV rectangle fill wrote 88 tiles per channel and undo removed it | +| Persistence | Native UI save of the deeper four-layer case followed by command reopen preserved layers, effects, 21 painted tiles per channel and ten baked maps. Earlier command save/reopen also passed. UI-only open-dialog completion was not established | +| Bake | GPU command check: ten maps at 128 px / 16 rays. UI check: ten maps at 256 px, logged CPU. Separate CPU high/low check: normal and height varied on a two-triangle low plane / 1,152-triangle analytic high surface. No matched reference quality or timing comparison | +| UI texture export | Settings/template/list tabs inspected and Export clicked; eight 1024 px PNGs decoded successfully, and base color was inspected visually. All eight matched command export byte for byte from the same project/options. Creating/editing templates was not exercised | +| UDIM and channel packing | Two tiles exported at 128 and 256 px. Both ORM maps sampled RGB (255,153,51), matching AO 1, roughness 0.6 and metallic 0.2; this is a small command-only case | +| Interchange | Five 256 px OpenPBR PNGs plus parsed MaterialX XML; textured GLB and USDA reopened through TextureCraft's CLI with the original 12 triangles, 24 vertices and material. No external renderer/material equivalence checked | +| Layout | Whole-window PNGs inspected at 1920 × 1032 and 1280 × 800. Narrow layout retained both views and toolbar scroll controls, with severe layer-label truncation; no full narrow-window task suite or pixel-by-pixel UI score | +| Rework/upstream scope | Possible `.tcraft`/output-package reworks and incoming ArtCraft UI/shared-library work are planning inputs, not completed changes. The `.mcmat` v3 proposal and current legacy reader were reviewed; no future contract or current MaterialCraft producer/consumer pair was validated | +| Not run | Full Rust tests, clippy, wasm, other operating systems, pen/display hardware matrix, large UDIM projects, long sessions, matched performance benchmarks and reference image-difference corpus | + +## Languages + +The [picker](crates/ui-egui/src/i18n.rs) contains ten languages. Shared catalogs are optional at +build time; missing entries fall back to English, and builds without catalogs offer English only. +The older [coverage table](docs/localization-parity.md) predates catalog migration, so its “100%” +rows are not a current measurement. This audit ran an English build without external catalogs. + +| Language | Code | UI strings | Status | +|---|---|---|---| +| English | `en` | Source language | Exercised in this audit | +| Simplified Chinese | `zh-Hans` | Not remeasured | Catalog/font dependent; native review pending | +| Spanish | `es` | Not remeasured | Catalog dependent; native review pending | +| Hindi | `hi` | No picker entry | Not offered | +| Arabic | `ar` | Not remeasured | Catalog/font dependent; shaping/layout needs current review | +| French | `fr` | Not remeasured | Catalog dependent; native review pending | +| Portuguese (Brazil) | `pt-BR` | Not remeasured | Catalog dependent; native review pending | +| Indonesian | `id` | No picker entry | Not offered | +| Japanese | `ja` | Not remeasured | Catalog/font dependent; native review pending | +| German | `de` | Not remeasured | Catalog dependent; native review pending | +| Korean | `ko` | Not remeasured | Catalog/font dependent; native review pending | +| Vietnamese | `vi` | No picker entry | Not offered | + +Also in the picker: Italian (`it`), with catalog coverage and native review not remeasured. +Engine error details remain English; UI-key coverage alone would not establish full localization. + +## Upcoming + +These are acceptance-oriented work areas, not claims that their linked reports were reproduced +here. Open pull requests are not credited until merged into the assessed main revision. + +| Rank | Milestone | Estimate | +|---|---|---| +| 1 | Reliable startup and project safety across the supported GPU/platform matrix; reproduce startup/GPU reports and exercise recovery/large saves ([#541](https://github.com/storytold/texturecraft/issues/541), [#489](https://github.com/storytold/texturecraft/issues/489)) | TBD after reproduction | +| 2 | Define `.tcraft` and output-package direction, scope any reworks, and establish versioning, migration and producer/consumer acceptance cases | Unestimated; design scope open | +| 3 | Plan/adopt the incoming ArtCraft UI refactor and shared-library changes; preserve command reachability and repeat UI/persistence/platform checks after adoption | TBD after upstream contracts and consumer scope | +| 4 | Bring in the completed MaterialCraft `.mcmat` contract: agree the supported MaterialX/resources/controls subset, implement the consumer through shared APIs and validate folder/archive outputs from named versions | Upstream-dependent; format unfinished | +| 5 | Bake fidelity and dependable smart-material wear: matched assets/settings at multiple resolutions, all ten maps, high/low pairs and documented differences ([#536](https://github.com/storytold/texturecraft/issues/536), [#538](https://github.com/storytold/texturecraft/issues/538)) | TBD after map corpus | +| 6 | Generator, anchor and property depth; finish the artist-facing control inventory while preserving existing shared controls ([#374](https://github.com/storytold/texturecraft/issues/374), [#389](https://github.com/storytold/texturecraft/issues/389), [#433](https://github.com/storytold/texturecraft/issues/433)) | TBD after control audit | +| 7 | Brush/pen precision, feedback and discoverability; complete 3D/2D/trim-sheet tasks and set responsiveness budgets ([#545](https://github.com/storytold/texturecraft/issues/545), [#485](https://github.com/storytold/texturecraft/issues/485), [#306](https://github.com/storytold/texturecraft/issues/306)) | TBD after task tests | +| 8 | Color-managed pipeline and destination checks for USD, glTF/GLB, MaterialX and texture maps, including UDIM, complex materials and the adopted output packages | TBD after consumer matrix | +| 9 | Read-only `.spp` discovery: clean-room feasibility, recoverable data and unsupported-content reporting; convert into the adopted native format without changing the source | Unestimated; feasibility unknown | +| 10 | Release/platform regression checks, web polish, current translation coverage and native review; expand the original asset library | TBD after validation | + +### Dependencies and possible rework + +These tracks add discovery, migration, integration and repeated validation work. A possible +rework is not an approved replacement design, and an upstream proposal/merge is not proof of +TextureCraft adoption. + +| Track | Current state | Completion / revalidation gate | +|---|---|---| +| Native `.tcraft` | Current save/load works in the audit; schema/container may change | Decide the native contract and compatibility policy. For any adopted rework, check existing projects and conversion explicitly: layers, masks, effects, resources, painted tiles, UDIM layouts and baked data; retain bounded reads, atomic saves and recovery behavior | +| Output packages | Current individual exports work within the recorded scope; future package format/content/layout is not settled | Define affected artifacts, manifests, naming, resource references and versioning. Test package relocation, folder/archive delivery where applicable, color/normal/displacement metadata and real consumers; repeat install/update checks if distribution artifacts change | +| MaterialCraft `.mcmat` | Legacy v1/v2 support exists; [v3](https://github.com/storytold/materialcraft/issues/190) is unfinished upstream | Agree the published contract and supported MaterialX subset, folder/ZIP equivalence, resources and exposed inputs. Adopt it through shared libraries and test actual MaterialCraft output in TextureCraft, including unsupported versions/features. Do not assume native-source recovery or the legacy re-cook behavior | +| ArtCraft UI refactor | Incoming suite/UI work; shared palette/theme proposals such as [craft-libs #102](https://github.com/storytold/craft-libs/pull/102) and [#397](https://github.com/storytold/craft-libs/pull/397) are examples, not the whole refactor or an adoption claim | Scope TextureCraft's adapters/components and design changes. Keep document behavior command-driven; repeat the [UI task audit](docs/ui-parity.md), input/accessibility checks, screenshots and layout/preferences persistence tests against the adopted design | +| Shared libraries | Several shared crates are already pinned in [Cargo.toml](Cargo.toml); [format migration work](https://github.com/storytold/craft-libs/issues/778) continues | Use reviewed public APIs and keep app-specific mapping/policy local. Each adoption needs consumer integration plus compatibility, security-limit, layering, wasm and regression checks; a library change alone does not complete the app's work | + +### Current focus + +Keep the current functional baseline while establishing project-safety and bake-fidelity checks. +Scope `.tcraft`/output-package changes and coordinate ArtCraft UI/shared-library adoption alongside +that work, so feature work budgets include possible migration and revalidation. Bring `.mcmat` +forward against the finished upstream contract rather than treating the legacy reader as completion. +Run `.spp` feasibility separately. Hardware ray tracing is a later enhancement; beta depends on +the scoped acceptance/integration gates above. [Release validation](docs/releasing.md) continues +for existing releases; there is no outstanding “first release” gate. + +## Progress log + +| Date | Entry | +|---|---| +| 2026-11-16 | Added possible native/output-package reworks, unfinished MaterialCraft `.mcmat` integration and incoming ArtCraft UI/shared-library work as explicit roadmap tracks. Current audit scores stay tied to the tested revision; migration scope and effort remain unestimated | +| 2026-11-16 | Deeper UI/functionality audit added in [docs/ui-parity.md](docs/ui-parity.md): twenty check groups, specific missing controls, reference editing/self-bake, UI export/save, analytic high/low transfer and UDIM packing. Overall percentages remain provisional estimates | +| 2026-11-16 | Approximate live review against main `62b2b13` and reference 12.2.0. Basic edit/save/reopen, GPU bake and interchange smoke checks passed. Rebaselined reporting to ~80% breadth / ~60% readiness and recorded validation limits | +| 2026-11-16 | Scoped reference-project compatibility to future read-only `.spp`; retained `.tcraft` for editing/saving and open pipeline exports. No importer or other implementation change in this review | +| 2026-11-12 | v0.6.1 published; supersedes the former first-release v0.1.0 focus | +| 2026-11-04 | Previous roadmap reported ~94% weighted implementation/workflow completion; retained here as historical context, not a comparable readiness measurement | + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-16 | major | Added dependency/rework scope and adoption gates; distinguished legacy `.mcmat` support from the unfinished MaterialX-based proposal; expanded upcoming work without crediting unlanded integrations | +| 2026-11-16 | major | Expanded live UI tasks and output validation; added a separate UI gap inventory with acceptance checks; distinguished UI, mixed and command evidence and CPU/GPU bake paths | +| 2026-11-16 | major | Adopted headline/audience/dimension/feature/language/upcoming tables; added main-revision evidence and uncertainty, read-only `.spp` scope, current release status and acceptance gates; removed the unsupported six-hour remainder | diff --git a/docs/ui-parity.md b/docs/ui-parity.md new file mode 100644 index 00000000..a43f2e7c --- /dev/null +++ b/docs/ui-parity.md @@ -0,0 +1,122 @@ +# UI parity and missing work + +Reviewed 2026-11-16 against **main `62b2b13`, TextureCraft 0.6.1**, and reference app 12.2.0. +The [roadmap](../ROADMAP.md) carries the overall readiness estimate. This document records +specific UI gaps, their evidence, and the functional tasks actually exercised. + +## Scope and method + +The desktop apps were operated with mouse and keyboard input. TextureCraft's read-only +`session.inspect` and `ui.inspect` results confirmed document changes; whole-window screenshots +were inspected after the actions. Export-directory text was entered through the UI's accessibility +control. This is distinct from setting UI state or issuing an editing command directly. + +The main UI case used the built-in cube at 1024 px, the default English interface, and a +1920 × 1032 client area. A 1280 × 800 layout was also inspected. The reference used an original +UV cube; its title showed “Read only”, but painting, layer/mask creation and baking worked. +These were qualitative workflow comparisons, not matched-camera, matched-brush or image-difference +tests. No reference artwork, presets or screenshots are bundled here. + +**Evidence labels:** *UI* means exercised or inspected in the running interface; *source* means +confirmed in the assessed revision; *commands* means exercised through CLI/control commands. +Source-only findings are not presented as reproduced UI errors. Passing a small task does not +establish complete parity for its feature family. + +## Missing controls and workflows + +P1 affects frequent editing or delivery tasks. P2 is important depth or usability work. IDs are +stable review references, not a complete inventory of the reference interface. + +| ID | Priority | Missing capability | Evidence and current workaround | Acceptance check | +|---|---|---|---|---| +| UI-01 | P1 | Effect menu on the mask thumbnail | **UI + source.** Right-clicking the thumbnail did not open its own menu. The reference exposes mask operations and effect creation there. TextureCraft's layer-name context menu does add effects to the selected mask; adding a generator through that route worked | Right-click a mask thumbnail, add a generator/filter, and verify the effect belongs to that mask without changing the target first | +| UI-02 | P1 | Rename effects and anchors in the UI | **UI + source.** An effect row's context menu offers copy/cut/paste/duplicate/remove, with no Rename action; its row has no rename editor. `effect.set {name}` exists. Layers themselves already support UI renaming | Rename two anchors/effects independently from the stack; source pickers show the new names; undo and save/reopen preserve them | +| UI-03 | P1 | Independent U/V tiling and a link/unlink control | **UI + source.** The fill panel has one Scale / tiling value. `projection_transform` reads the first UV scale component and submits a scalar; the model stores two components. The reference exposes two linked values | Set U = 2 and V = 5, switch projections/selections, and reopen the project without silently coupling the values | +| UI-04 | P1 | Fill sampling/filtering and UV wrap controls | **UI + source.** The reference fill panel exposes filtering and wrapping. TextureCraft's fill editor exposes projection, transforms and channel sources without those controls. No per-fill UI workaround was established | Set filtering and wrapping per fill, inspect the difference at a UV border, and retain the settings across save/reopen | +| UI-05 | P2 | Physical-size fill scaling | **UI + source.** The reference Scale menu offers tiling or physical size. TextureCraft exposes dimensionless scale only | Give a pattern a physical size and show that it keeps that size on meshes with different dimensions | +| UI-06 | P2 | Warp and per-UV-tile fill projection choices | **UI + source.** Both choices were visible in the reference projection menu. TextureCraft's ordinary fill picker has UV, tri-planar, planar, spherical and cylindrical choices; decals have a separate editor. A warp filter is a different operation | Exercise the two projection workflows on a multi-tile asset, with explicit controls, persistence and command inspection | +| UI-07 | P1 | Anchors inside mask stacks | **Source, with reference menu inspected.** `EffectKind::Anchor` is content-only. Content anchors exist; this finding concerns capturing an intermediate grayscale mask result | Add an anchor after a mask effect, consume it in a higher layer, and verify the dependency through undo/reopen | +| UI-08 | P2 | Save a reusable user smart mask | **UI + source.** The reference mask menu has a smart-mask creation action. TextureCraft offers built-in smart masks and Create smart material, but no equivalent action for saving just the edited mask | Save a multi-effect mask, apply it to another layer/project, and retain its parameters and resource dependencies | +| UI-09 | P2 | Export/copy a mask bitmap from its context menu | **UI.** The reference exposes file and clipboard mask export; these actions are absent from TextureCraft's inspected menu. Previewing a mask is available, and is not a full-resolution bitmap-export check | Export the evaluated grayscale mask at its texture/tile resolution with explicit bit depth and orientation; test the file and clipboard paths | +| UI-10 | P1 | MaterialX output from the texture-export dialog | **UI + source + commands.** The dialog has no MaterialX option and `export_params` does not forward `materialX`. Command export with the OpenPBR preset successfully wrote `.mtlx` and maps | Enable MaterialX in the UI, preview the manifest and texture outputs, export, and validate the same result as the command route | +| UI-11 | P1 | Configurable project/display color-management workflow | **Source.** `DisplaySettings` provides fixed Linear/ACES-filmic tone mapping; export has fixed color spaces and metadata. There is no OCIO configuration/display/view model to expose in project or display settings | Select a configuration, working space and display/view transform; retain them; distinguish color channels from data maps through painting, preview and export | + +The relevant implementations are [layer rows, menus and fill/brush editors](../crates/ui-egui/src/dock.rs), +[generator properties](../crates/ui-egui/src/generator_panel.rs), +[export settings and parameters](../crates/ui-egui/src/windows.rs), +[layer/effect/projection types](../crates/core/src/layer.rs), +[display settings](../crates/core/src/project.rs), and +[smart-mask commands](../crates/engine/src/smart_masks.rs). + +## Partial areas + +| ID | Area | Observed limit | Next check | +|---|---|---|---| +| UI-12 | Generator depth and property coverage | **UI + source.** The picker contains seven kinds. Switching to Position, changing Global balance and duplicating the effect worked. Shared global adjustments, resolution and input slots already exist; that does not establish the richer generator/control inventory in [#374](https://github.com/storytold/texturecraft/issues/374) | Audit each generator's inputs, micro-detail behavior and controls against the reference; do not count seven shared implementations as equivalent to its whole catalog | +| UI-13 | Narrow workspace readability | **UI.** At 1280 × 800 the app rendered, both views stayed visible and the toolbar exposed scroll arrows. Layer names/types became heavily truncated, the layer toolbar wrapped, and Properties needed scrolling. This was not an input-failure or docking-persistence test | Repeat the editing tasks at smaller sizes, widen/rearrange panels, check full-name tooltips and keyboard access, and retain the layout after restart | + +Broader properties/filter work remains tracked in +[#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking +against current code; an open issue is not proof that every control it lists is still missing. + +## Functional task audit + +These twenty check groups include UI, mixed-surface and command-only cases. They are an evidence +list, not a feature-completion denominator. + +| Check | Surface | Result | Observable evidence / limit | +|---|---|---|---| +| F01 New project | UI | Pass | Ctrl+N, built-in Cube, 1024 px, Create produced a new project with one empty paint layer. The native mesh-file selection path was not completed in this deeper pass | +| F02 Paint in 3D | UI | Pass | A mouse drag produced a visible stroke in 3D and its UV representation; inspection showed a Paint stroke undo step and painted tiles | +| F03 Paint in 2D | UI | Pass | A separate UV-view drag increased painted tiles from 7 to 21 per active channel and changed the visible image | +| F04 Undo and redo | UI | Pass | Ctrl+Z restored 7 tiles and history depth 2; Ctrl+Y restored 21 tiles and depth 3 | +| F05 View switching | UI | Pass | F2 selected Only3D, F3 Only2D and F1 Split; the screenshots changed accordingly | +| F06 Brush gesture | UI | Pass | Ctrl+right-drag changed size from 8 to about 12.94 and hardness from 50 to about 38. This also demonstrates that diagonal movement changes both parameters; pen precision was not tested | +| F07 Shelf search and material application | UI | Pass | Searching for car and dragging Car Paint onto the mesh added a red fill layer and an Add Car Paint history step | +| F08 Fill layer and black mask | UI | Pass | Layer toolbar added a fill; the layer-name context menu added a black mask and selected the mask target | +| F09 Generator editing | UI | Pass | Layer context menu added a generator to that mask. Selecting Position and dragging Global balance changed the mask/viewport; inspection recorded balance about 0.279 | +| F10 Duplicate an effect | UI | Pass | Ctrl+D produced a separate Generator copy with the same parameters and a Duplicate effect history step | +| F11 UV rectangle fill | UI | Pass | Tool 4, UV-island mode and a rectangle across two UV islands wrote 88 tiles per painted channel on a new paint layer. Undo removed that fill. Topology was visible in the tool | +| F12 Bake from the UI | UI | Pass | F8, 256 px, low mesh used as high mesh, Check All and Bake completed all ten map types. The UI log reported CPU execution; this is separate from the GPU command check | +| F13 Texture-export flow | UI + accessibility text entry | Pass | Inspected Settings, Output templates and List of exports, then clicked Export. Eight 1024 px PNGs decoded successfully; all eight were byte-identical to command exports from the same saved project/options. The base-color output was inspected visually. Template creation/editing was not exercised | +| F14 Save and reopen | Mixed | Pass within scope | Ctrl+S and the native Save As dialog saved four layers, two generator effects, 21 painted tiles per channel and ten 256 px baked maps. Reopening through `file.open` matched inspected layers, texture sets and mesh. This was not a complete keyboard-only open-dialog test | +| F15 Smaller window | Scripted resize + UI inspection | Partial | 1280 × 800 rendered with working layout structure; the readability limits are UI-13. No full task suite at that size | +| F16 Reference workflow | Reference UI | Pass within scope | Pointer painting, paint/fill-layer creation, a black mask and an empty generator slot worked. A seven-map self-bake at 1024 px completed with map thumbnails and completion entries. Reference save/export and output equivalence were not tested | +| F17 GPU bake | Commands, earlier pass | Pass | All ten maps at 128 px / 16 rays completed; result identified the GTX 1080 GPU tracer. This does not prove that the UI bake used that path | +| F18 High-to-low transfer | CLI | Pass within scope | A two-triangle plane received normal and height from a separate 1,152-triangle analytic surface at 128 px on the CPU. Both maps varied; this was not a reference comparison or absolute-height calibration | +| F19 UDIM sizes and packed channels | CLI | Pass | Tiles 1001/1002 exported at 128/256 px respectively. Both packed ORM maps sampled RGB (255,153,51), matching AO 1, roughness 0.6 and metallic 0.2 | +| F20 Scene/material interchange | Commands, earlier pass | Pass within scope | Textured GLB and USDA reopened in TextureCraft with the original geometry/material; OpenPBR MaterialX XML parsed and referenced exported maps. External consumers/renderers remain unchecked | + +F18 used an original surface over x,z ∈ [-1,1], with height +`y = 0.06 + 0.1 * exp(-6 * (x*x + z*z))`, a 24 × 24 quad grid, matching UVs and frontal/rear +distance settings of 0.3. Normal and height were exported as 16-bit PNG. Interior samples read +through an 8-bit display decoder ranged 103–152 in normal R/G and 176–255 in height. These ranges +establish nonconstant transfer only; they are not full-precision error bounds. F19 used the +built-in `udim_plane`, a uniform fill and a tile-1002 resolution override. + +## Avoid stale missing-feature claims + +- Polygon fill already has triangle, polygon, connected-mesh and UV-island modes, a rectangle + selection workflow and topology display. F11 exercised the UV rectangle route; a full trim-sheet + authoring task is still unverified. +- The 2D paint cursor was visible, and direct 2D painting worked. This does not reproduce the older + cursor/painting reports on this setup. +- Brush size/hardness and flow/angle gestures have a visible hint. Hardness is present under + Flow and opacity; Angle has its own section. Their absence must not be inferred from the initial + scrolled position. The broader precision/shortcut concerns in + [#545](https://github.com/storytold/texturecraft/issues/545) still need an input-device task test. +- The shelf displayed four columns at the larger size, with type controls and search. Do not + treat every older shelf-layout request as a currently missing implementation. +- A missing mask-thumbnail menu does not mean mask effects are unavailable: the layer-name menu + worked. A missing MaterialX UI option does not mean the exporter is absent. + +## Still unverified + +Pen pressure/tilt and other input hardware; brush-feel matching; projection/stencil, clone, +smudge, path and symmetry task suites; a complete trim-sheet task; creating and editing output +templates; docking/floating/restart persistence; history-panel navigation; many-set/many-tile +projects; long sessions and recovery; matched performance budgets; and destination-app image +fidelity. The new `.spp` reader is a future goal, not a tested capability. + +No implementation fixes were made in this assessment. The build from the earlier pass was +reused; the full Rust tests, clippy, wasm and other operating-system builds were not rerun. From 1e9194d9a6d4c42798fa664791a48a9ab65b05c8 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 21:59:54 -0500 Subject: [PATCH 6/9] ci: let Dependabot maintain GitHub Actions dependencies (#448) --- .github/dependabot.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..daeab9e7 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: + + # Maintain GitHub Actions workflows + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + time: "06:00" + timezone: "America/New_York" + groups: + actions: + patterns: + - "*" + commit-message: + prefix: "ci(deps)" From f10d92b997c445f6e52e2ee18ba3dc6d3fb9e8b5 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 17 Nov 2026 03:56:18 +0000 Subject: [PATCH 7/9] Auto: Respect curvature modes and filter inherited anchor choices Combine micro height with edge and cavity responses before mode selection. Build inherited-effect Fill and micro-detail anchor choices from the effect owner. Add focused regressions for both behaviors. --- crates/compose/src/eval.rs | 70 ++++++++++++++++++++++----- crates/ui-egui/src/dock.rs | 35 +++++++++++++- crates/ui-egui/src/generator_panel.rs | 4 +- 3 files changed, 93 insertions(+), 16 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 7741d057..e38aac84 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1450,12 +1450,13 @@ impl<'a, 'b> Texel<'a, 'b> { fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 { let coords = self.coords(); + let micro = generator.micro.map_or(0.0, |micro| self.micro_detail(generator.kind, micro)); let signal = match (generator.kind, &generator.detail) { (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => { // Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes }; let curvature = self.generator_input(generator, BakedMap::Curvature); - self.curvature_detail(detail, sizes, curvature) + self.curvature_detail(detail, sizes, curvature, micro) } (GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0, (GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5), @@ -1465,10 +1466,8 @@ impl<'a, 'b> Texel<'a, 'b> { (GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, (GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5, }; - let signal = match generator.micro { - Some(micro) => signal + self.micro_detail(generator.kind, micro), - None => signal, - }; + let signal = + if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) && generator.detail.is_some() { signal } else { signal + micro }; let signal = if generator.noise_amount > 0.0 { let noise = world_noise(coords.pos, generator.noise_scale, generator.seed); if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) { @@ -1520,15 +1519,19 @@ impl<'a, 'b> Texel<'a, 'b> { } /// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given. - fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option) -> f32 { - let combine = |edges: f32, cavities: f32| match detail.mode { - CurvatureMode::Edges => edges, - CurvatureMode::Cavities => cavities, - CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), - CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option, micro: f32) -> f32 { + let combine = |edges: f32, cavities: f32| { + let edges = 1.0 - (1.0 - edges) * (1.0 - micro.max(0.0)); + let cavities = 1.0 - (1.0 - cavities) * (1.0 + micro.min(0.0)); + match detail.mode { + CurvatureMode::Edges => edges, + CurvatureMode::Cavities => cavities, + CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities), + CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities), + } }; - // Without curvature to read the texel is flat: no edges or cavities + // Without baked curvature, only painted micro height supplies edges or cavities let Some(curvature) = curvature else { return combine(0.0, 0.0) }; let working_size = (self.res, self.inp.gbuf.height); @@ -3586,6 +3589,49 @@ soft {soft:?}" assert!((with(&mut fixture, &generator) - flat).abs() < 0.02); } + #[test] + fn curvature_modes_classify_raised_and_recessed_micro_height() { + let mut fixture = fixture(); + fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() }; + let lower = fixture.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + fixture.project.insert_layer(0, Layer::new(lower, "Bumps", LayerKind::Fill(fill), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); + let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); + + for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { + for (height, mode, responds) in [ + (0.5, CurvatureMode::Edges, true), + (-0.5, CurvatureMode::Edges, false), + (0.5, CurvatureMode::Cavities, false), + (-0.5, CurvatureMode::Cavities, true), + (0.5, CurvatureMode::Both, true), + (-0.5, CurvatureMode::Both, true), + ] { + if let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind { + fill.sources.insert(Channel::Height, Source::Uniform([height; 3])); + } + let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] }; + let generator = Generator { + level: 0.5, + softness: 0.5, + noise_amount: 0.0, + detail: Some(detail), + micro: Some(MicroDetail { anchor, amount: 1.0 }), + ..Generator::new(kind) + }; + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))); + fixture.project.layer_mut(top).unwrap().mask = Some(mask); + + let value = run(&fixture, None).value(Channel::BaseColor, 5, 5)[0]; + let expected = if responds { 0.75 } else { 0.5 }; + assert!((value - expected).abs() < 0.02, "{kind:?} {mode:?} height {height}: {value}"); + } + } + } + #[test] fn decal_fills_cover_only_their_frame_and_image_alpha() { let mut f = fixture(); diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index f0cc3254..ab5e52d5 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2197,6 +2197,12 @@ pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(Laye .collect() } +/// Anchor choices for an effect, validated against its owner even when shown through an instance +pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { + let owner = app.session.doc.project.effect(effect).map_or(layer, |(owner, _)| owner); + anchors_below(app, owner) +} + /// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { let project = &app.session.doc.project; @@ -2245,7 +2251,7 @@ mod mask_anchor_label_tests { use texturecraft_engine::core::{Channel, LayerId}; use texturecraft_engine::execute; - use super::{anchor_label, anchors_below}; + use super::{anchor_label, anchors_below, effect_anchors_below}; use crate::TextureCraftApp; #[test] @@ -2267,6 +2273,31 @@ mod mask_anchor_label_tests { assert!(labels.iter().any(|(id, label)| *id == LayerId(anchor) && !label.contains("(Off)"))); assert!(!anchor_label(harness.state(), LayerId(anchor), Channel::Height).contains("(Off)")); } + + #[test] + fn inherited_effect_pickers_list_anchors_below_the_owner() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let valid = execute(&mut session, "effect.add.anchor", &json!({"layer": lower})).unwrap()["effect"].as_u64().unwrap(); + let source = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": source})).unwrap()["effect"].as_u64().unwrap(); + let generator = execute(&mut session, "effect.add.generator", &json!({"layer": source})).unwrap()["effect"].as_u64().unwrap(); + let middle = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let invalid = execute(&mut session, "effect.add.anchor", &json!({"layer": middle})).unwrap()["effect"].as_u64().unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source})).unwrap()["layer"].as_u64().unwrap(); + + assert!(execute(&mut session, "effect.set", &json!({"effect": fill, "anchor": invalid})).is_err()); + assert!(execute(&mut session, "effect.set", &json!({"effect": generator, "microAnchor": invalid})).is_err()); + + let harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + assert!(anchors_below(harness.state(), LayerId(instance)).iter().any(|(id, _)| *id == LayerId(invalid))); + for effect in [fill, generator] { + let choices = effect_anchors_below(harness.state(), LayerId(instance), LayerId(effect)); + assert!(choices.iter().any(|(id, _)| *id == LayerId(valid))); + assert!(!choices.iter().any(|(id, _)| *id == LayerId(invalid))); + } + } } /// Space above a fill's Material caption, setting it apart from the projection @@ -2571,7 +2602,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Levels(levels) => crate::levels_properties::levels_properties(app, ui, layer, effect_id, levels), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); - let anchors = anchors_below(app, layer.id); + let anchors = effect_anchors_below(app, layer.id, effect_id); let current = match source { Source::Anchor { anchor, channel } => anchor_label(app, *anchor, *channel), Source::Uniform(_) => tr("Uniform value").to_string(), diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index 74221c3b..d5246c68 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -8,7 +8,7 @@ use texturecraft_engine::core::{ }; use crate::TextureCraftApp; -use crate::dock::{anchor_entries, anchor_label, anchors_below, image_drop, image_menu, mesh_map_color}; +use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_below, image_drop, image_menu, mesh_map_color}; use crate::i18n::{baked_map_label, tr, trf}; use crate::theme::{Tokens, caption}; use crate::widgets::{combo, section, slider_edit}; @@ -79,7 +79,7 @@ fn micro_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, micr let tokens = Tokens::get(ui.ctx()); ui.label(caption(tr("Micro detail"))) .on_hover_text(tr("Painted height from an anchor point below: raised areas read as edges, recessed ones as cavities.")); - let anchors = anchors_below(app, layer); + let anchors = effect_anchors_below(app, layer, LayerId(id)); let current = match micro { Some(detail) => anchors.iter().find(|(anchor, _)| *anchor == detail.anchor).map_or_else(|| tr("missing").to_string(), |(_, label)| label.clone()), None => tr("None").to_string(), From 9d7077601b6170700a74c67f12ec06d3824a3175 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 16 Nov 2026 23:26:09 -0500 Subject: [PATCH 8/9] Use shared aligned stored ZIP entries for USDZ export Co-authored-by: bflatastic --- Cargo.lock | 11 ++++++ Cargo.toml | 2 ++ crates/formats/Cargo.toml | 1 + crates/formats/src/mesh_export/usd.rs | 49 +++++++++++++++++++++++---- 4 files changed, 56 insertions(+), 7 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 54f6ef82..a939100a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -957,6 +957,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=6128eabbfb98e5fe486fa7ee4413724e2a4ca908#6128eabbfb98e5fe486fa7ee4413724e2a4ca908" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip", +] + [[package]] name = "craft-zip" version = "0.1.0" @@ -4473,6 +4483,7 @@ dependencies = [ "craft-mesh", "craft-tcraft", "craft-usd", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6128eabbfb98e5fe486fa7ee4413724e2a4ca908)", "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "exr", "flate2", diff --git a/Cargo.toml b/Cargo.toml index 88936e5f..11a6b539 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,8 @@ craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0 craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] } craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" } craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } +# Isolated aligned writer; existing archive readers retain their pin and behavior. +craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "6128eabbfb98e5fe486fa7ee4413724e2a4ca908" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index f7053917..a70198cf 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -17,6 +17,7 @@ craft-mesh = { workspace = true } craft-mcmat = { workspace = true } craft-tcraft = { workspace = true } craft-zip = { workspace = true } +craft-zip-usdz = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 2f57f7aa..9c737f16 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -6,7 +6,6 @@ //! UsdUVTexture shaders. Meters, Y up. use std::fmt::Write as _; -use std::io::Write as _; use texturecraft_core::{Channel, NormalFormat}; use texturecraft_geom::Mesh; @@ -344,14 +343,12 @@ pub(crate) fn material_maps(mesh: &Mesh, stem: &str, textures: &[Vec)]) -> Result> { - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); - let err = |e: zip::result::ZipError| FormatError::Invalid(format!("usdz package: {e}")); + let mut zip = craft_zip_usdz::Writer::new(); + let err = |e| FormatError::Invalid(format!("usdz package: {e}")); for (name, bytes) in std::iter::once((layer_name, layer)).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) { - zip.start_file(name, opts).map_err(err)?; - zip.write_all(bytes)?; + zip.add_stored_aligned(name, bytes, 64).map_err(err)?; } - Ok(zip.finish().map_err(err)?.into_inner()) + zip.finish().map_err(err) } /// Text of a value as usda writes it. @@ -439,3 +436,41 @@ pub(crate) fn usda(layer: &UsdLayer) -> String { usda_prim(&mut s, &layer.root, 0); s } + +#[cfg(test)] +mod aligned_package_tests { + use super::*; + use std::io::{Cursor, Read, Write}; + + #[test] + fn shared_usdz_keeps_layer_first_and_exact_archive_bytes() { + let files = vec![("textures/color.png".to_owned(), vec![0, 1, 255]), ("empty".to_owned(), Vec::new())]; + let bytes = usdz("scene.usdc", b"PXR-USDC", &files).unwrap(); + let mut previous = zip::ZipWriter::new(Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).with_alignment(64); + for (name, data) in std::iter::once(("scene.usdc", b"PXR-USDC".as_slice())).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))) { + previous.start_file(name, opts).unwrap(); + previous.write_all(data).unwrap(); + } + assert_eq!(bytes, previous.finish().unwrap().into_inner()); + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).unwrap(); + assert_eq!(archive.len(), 3); + for (i, (name, data)) in + std::iter::once(("scene.usdc", b"PXR-USDC".as_slice())).chain(files.iter().map(|(n, b)| (n.as_str(), b.as_slice()))).enumerate() + { + let mut entry = archive.by_index(i).unwrap(); + assert_eq!(entry.name().unwrap(), name); + assert_eq!(entry.compression(), zip::CompressionMethod::Stored); + assert_eq!(entry.data_start().unwrap() % 64, 0); + let mut actual = Vec::new(); + entry.read_to_end(&mut actual).unwrap(); + assert_eq!(actual, data); + } + } + + #[test] + fn shared_usdz_rejects_duplicate_layer_name() { + let err = usdz("scene.usdc", b"PXR-USDC", &[("scene.usdc".to_owned(), Vec::new())]).unwrap_err(); + assert!(matches!(err, FormatError::Invalid(ref why) if why.starts_with("usdz package:"))); + } +} From 0d2f52f6113068c9d3a32a0ccb3563cfc274e03c Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 17 Nov 2026 04:33:18 +0000 Subject: [PATCH 9/9] Auto: Filter inherited anchor choices to recorded texture sets Intersect owner-valid anchors with those recorded below the displayed instance. Add a cross-set picker regression that failed before the fix and passes afterward. --- crates/ui-egui/src/dock.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index ab5e52d5..5e29d054 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -2197,10 +2197,16 @@ pub(crate) fn anchors_below(app: &TextureCraftApp, reader: LayerId) -> Vec<(Laye .collect() } -/// Anchor choices for an effect, validated against its owner even when shown through an instance +/// Anchor choices for an effect, valid for its owner and recorded below the displayed instance pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect: LayerId) -> Vec<(LayerId, String)> { let owner = app.session.doc.project.effect(effect).map_or(layer, |(owner, _)| owner); - anchors_below(app, owner) + let owner_anchors = anchors_below(app, owner); + if owner == layer { + return owner_anchors; + } + + let displayed_anchors = anchors_below(app, layer); + owner_anchors.into_iter().filter(|(id, _)| displayed_anchors.iter().any(|(displayed, _)| id == displayed)).collect() } /// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). @@ -2298,6 +2304,26 @@ mod mask_anchor_label_tests { assert!(!choices.iter().any(|(id, _)| *id == LayerId(invalid))); } } + + #[test] + fn inherited_effect_pickers_hide_unrecorded_source_set_anchors() { + let mesh = texturecraft_engine::geom::primitives::material_ball(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:material_ball", None, 256).unwrap(); + let lower = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower})).unwrap()["effect"].as_u64().unwrap(); + let source = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": source})).unwrap(); + let fill = execute(&mut session, "effect.add.fill", &json!({"layer": source, "anchor": anchor})).unwrap()["effect"].as_u64().unwrap(); + let generator = execute(&mut session, "effect.add.generator", &json!({"layer": source, "microAnchor": anchor})).unwrap()["effect"].as_u64().unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source, "ts": 1})).unwrap()["layer"].as_u64().unwrap(); + + let harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + assert!(anchors_below(harness.state(), LayerId(instance)).is_empty()); + for effect in [fill, generator] { + let choices = effect_anchors_below(harness.state(), LayerId(instance), LayerId(effect)); + assert!(choices.is_empty(), "source-set anchor {anchor} is not recorded for the instance"); + } + } } /// Space above a fill's Material caption, setting it apart from the projection