diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 9d58ce3f..623d0751 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -57,7 +57,10 @@ impl Session { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) } - _ => Err(EngineError::Other("the selected effect is not a paint effect".into())), + // A filter (or another effect) is selected, e.g. just added from the shelf: paint + // what lies beneath it, so the new paint goes through it. + Some((owner, _)) => self.paint_target_below(owner, e), + None => Err(EngineError::Other("the selected effect is not a paint effect".into())), }, StackTarget::Mask => { let eid = self.doc.project.alloc_id(); @@ -72,6 +75,36 @@ impl Session { } } + /// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the + /// nearest paint effect below it in the same stack, else the paint layer's own pixels (for + /// content) or a new paint effect inserted just below it (for a mask). + fn paint_target_below(&mut self, owner: LayerId, effect: LayerId) -> Result { + let eid = self.doc.project.alloc_id(); + let layer = self.doc.project.layer_mut(owner)?; + let below = |effects: &[Effect], at: usize| effects.get(..at).and_then(|b| b.iter().rev().find(|x| matches!(x.kind, EffectKind::Paint))).map(|x| x.id); + if let Some(at) = layer.content_effects.iter().position(|x| x.id == effect) { + if let Some(id) = below(&layer.content_effects, at) { + return Ok(PaintTarget::Layer(id)); + } + return if matches!(layer.kind, LayerKind::Paint) { + Ok(PaintTarget::Layer(owner)) + } else { + Err(EngineError::Other(format!( + "\"{}\" is a {} layer: paint on a paint layer or on its mask (a filter changes what lies below it)", + layer.name, + layer.kind.name() + ))) + }; + } + let mask = layer.mask.as_mut().ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + let at = mask.effects.iter().position(|x| x.id == effect).ok_or_else(|| EngineError::Other("the selected effect is not a paint effect".into()))?; + if let Some(id) = below(&mask.effects, at) { + return Ok(PaintTarget::Mask(id)); + } + mask.effects.insert(at, Effect::new(eid, EffectKind::Paint)); + Ok(PaintTarget::Mask(eid)) + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; diff --git a/crates/engine/tests/filters.rs b/crates/engine/tests/filters.rs new file mode 100644 index 00000000..12e4e3cd --- /dev/null +++ b/crates/engine/tests/filters.rs @@ -0,0 +1,111 @@ +//! Painting while a filter is selected (it is selected right after the shelf adds it): the +//! stroke paints what lies beneath the filter, so the new paint goes through it. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +const RES: f32 = 256.0; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Base color of the composite under a viewport point. +fn color_at(s: &mut Session, x: f32, y: f32) -> [f32; 3] { + s.update(); + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + s.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * RES) as u32, (hit.uv.y * RES) as u32) +} + +fn brush(s: &mut Session, color: [f32; 3]) { + execute(s, "tool.paint", &Value::Null).unwrap(); + execute(s, "tool.material", &json!({"channel": "baseColor", "color": color})).unwrap(); + execute(s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); +} + +fn dab(s: &mut Session) -> Result { + execute(s, "tool.stroke", &json!({"points": [[200, 200]]})).map_err(|e| e.to_string()) +} + +fn add_filter(s: &mut Session, filter: &str, target: &str) -> LayerId { + execute(s, "effect.add.filter", &json!({"filter": filter, "target": target})).unwrap(); + let StackTarget::Effect(e) = s.target else { panic!("adding a filter selects it: {:?}", s.target) }; + e +} + +fn kinds(effects: &[texturecraft_engine::core::Effect]) -> Vec<&'static str> { + effects.iter().map(|e| if matches!(e.kind, EffectKind::Paint) { "paint" } else { "other" }).collect() +} + +#[test] +fn a_selected_content_filter_paints_its_paint_layer_through_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).expect("painting with the filter selected works"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85 && v[2] > 0.85, "red paint shows inverted (cyan): {v:?}"); + assert!(s.doc.pixels.layers.keys().any(|(id, _)| *id == layer), "the paint landed in the layer's own pixels"); + // One undo step removes the stroke and leaves the filter. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0)); + assert_eq!(s.doc.project.layer(layer).unwrap().content_effects.len(), 1); +} + +#[test] +fn a_selected_content_filter_paints_the_paint_effect_below_it() { + let mut s = session(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap(); + let StackTarget::Effect(paint) = s.target else { panic!("{:?}", s.target) }; + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + dab(&mut s).unwrap(); + assert!(s.doc.pixels.layers.iter().any(|((id, _), img)| *id == paint && img.allocated_count() > 0), "painted into the paint effect"); + assert!(!s.doc.pixels.layers.iter().any(|((id, _), img)| *id == layer && img.allocated_count() > 0), "not into the layer below it"); + let v = color_at(&mut s, 200.0, 200.0); + assert!(v[0] < 0.15 && v[1] > 0.85, "through the filter: {v:?}"); +} + +#[test] +fn a_selected_filter_on_a_fill_layer_explains_why_it_cannot_paint() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.4, 0.8]})).unwrap(); + add_filter(&mut s, "invert", "content"); + brush(&mut s, [1.0, 0.0, 0.0]); + let e = dab(&mut s).unwrap_err(); + assert!(e.contains("fill layer"), "{e}"); +} + +#[test] +fn a_selected_mask_filter_paints_a_mask_paint_effect_below_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let layer = s.selected_layer().unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + add_filter(&mut s, "invert", "mask"); + let mask = |s: &Session| s.doc.project.layer(layer).unwrap().mask.clone().unwrap().effects; + assert_eq!(kinds(&mask(&s)), ["other"]); + // Black mask, inverted: the red fill shows everywhere. + assert!(color_at(&mut s, 200.0, 200.0)[0] > 0.85); + brush(&mut s, [1.0, 1.0, 1.0]); + s.tool.mask_value = 1.0; + dab(&mut s).expect("painting the mask with its filter selected works"); + assert_eq!(kinds(&mask(&s)), ["paint", "other"], "a paint effect was inserted below the filter"); + // White paint goes through the invert: the fill disappears where it was painted only. + let painted = color_at(&mut s, 200.0, 200.0); + let elsewhere = color_at(&mut s, 120.0, 200.0); + assert!(painted[0] < 0.6 && elsewhere[0] > 0.85, "painted {painted:?}, elsewhere {elsewhere:?}"); + // The next stroke reuses that paint effect. + dab(&mut s).unwrap(); + assert_eq!(kinds(&mask(&s)), ["paint", "other"]); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 2b4d1eb9..7a109191 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1,6 +1,7 @@ //! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), ("2D view only", "عرض ثنائي الأبعاد فقط"), ("32 bits (float)", "32 بت (فاصلة عائمة)"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 22d868a9..71f53573 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1,6 +1,7 @@ //! German UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), ("2D view only", "Nur 2D-Ansicht"), ("32 bits (float)", "32 Bit (Float)"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 076fe369..651dec7d 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1,6 +1,7 @@ //! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), ("2D view only", "Solo vista 2D"), ("32 bits (float)", "32 bits (float)"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 3d970991..a071191f 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,6 +1,10 @@ //! French UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", + ), ("0 turns autosave off. Copies go to {folder}", "0 désactive la sauvegarde automatique. Les copies vont dans {folder}"), ("2D view only", "Vue 2D seule"), ("32 bits (float)", "32 bits (flottant)"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 3fb774b3..34c358d4 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1,6 +1,7 @@ //! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), ("2D view only", "Solo vista 2D"), ("32 bits (float)", "32 bit (float)"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index ef2d2d12..d940d74c 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1,6 +1,10 @@ //! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", + ), ("0 turns autosave off. Copies go to {folder}", "0で自動保存をオフにします。コピーの保存先: {folder}"), ("2D view only", "2Dビューのみ"), ("32 bits (float)", "32ビット (浮動小数点)"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index a021ae91..dce21b04 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1,6 +1,10 @@ //! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ( + "\"{layer}\" has no paint yet: the filter changes what you paint on it.", + "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", + ), ("0 turns autosave off. Copies go to {folder}", "0으로 설정하면 자동 저장이 꺼집니다. 사본 저장 위치: {folder}"), ("2D view only", "2D 뷰만"), ("32 bits (float)", "32비트 (float)"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index de48dd90..c9f71744 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1,6 +1,7 @@ //! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), ("2D view only", "Apenas vista 2D"), ("32 bits (float)", "32 bits (float)"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 13ad0ce8..7c56fcb8 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1,6 +1,7 @@ //! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), ("2D view only", "仅 2D 视图"), ("32 bits (float)", "32 位(浮点)"), diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index e6366b9f..f7d23952 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -16,7 +16,7 @@ use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; -use crate::i18n::tr; +use crate::i18n::{tr, trf}; use crate::theme::Tokens; use crate::widgets::{dnd_release, icon_button}; @@ -78,7 +78,17 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { let (cmd, params) = match asset { Asset::Material(id) => ("material.apply", json!({"material": id})), Asset::SmartMask(id) => ("mask.smart.apply", json!({"name": id})), - Asset::Filter(id) => ("effect.add.filter", json!({"filter": id, "target": if crate::dock::targets_content(app) { "content" } else { "mask" }})), + Asset::Filter(id) => { + let content = crate::dock::targets_content(app); + if app.run("effect.add.filter", json!({"filter": id, "target": if content { "content" } else { "mask" }})).is_some() + && content + && let Some(name) = unpainted_paint_layer(app) + { + // Otherwise the filter seems to do nothing: it has nothing to change yet. + app.toast(trf("\"{layer}\" has no paint yet: the filter changes what you paint on it.", &[("layer", &name)]), false); + } + return; + } Asset::Alpha(id) => ("tool.brush", json!({"alpha": {"library": id}})), Asset::Library(path) => ("material.load", json!({"path": path})), Asset::Texture(name) => ("layer.add.image", json!({"name": name})), @@ -86,6 +96,20 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { app.run(cmd, params); } +/// The selected layer's name when it is a paint layer with nothing painted (in itself or in its +/// content paint effects). +fn unpainted_paint_layer(app: &TextureCraftApp) -> Option { + use texturecraft_engine::core::{EffectKind, LayerKind}; + let s = &app.session; + let layer = s.selected_layer().and_then(|id| s.doc.project.content_layer(id))?; + if !matches!(layer.kind, LayerKind::Paint) { + return None; + } + let ids: Vec<_> = std::iter::once(layer.id).chain(layer.content_effects.iter().filter(|e| matches!(e.kind, EffectKind::Paint)).map(|e| e.id)).collect(); + let painted = s.doc.pixels.layers.iter().any(|((id, _), img)| ids.contains(id) && img.allocated_count() > 0); + (!painted).then(|| layer.name.clone()) +} + /// What a view accepts from the shelf. #[derive(Clone, Copy, PartialEq, Eq)] pub enum DropZone {