diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b8299438..d3ae712e 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1175,39 +1175,43 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } - fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] { - match s { - Source::Uniform(v) => *v, + /// The value `source` gives this texel through `projection`, read as a channel of `kind` + fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + match source { + Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { - let (c, proj, _) = self.projected(proj); - let t = procedural(pattern, proj, &c); - mix3(*low, *high, t) + let (coords, projection, _) = self.projected(projection); + let amount = procedural(pattern, projection, &coords); + mix3(*low, *high, amount) } Source::Image { name, normal_format } => { - let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; - let (c, proj, _) = self.projected(proj); - let mut acc = [0.0f32; 4]; - for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) { - let s = img.sample(uv.x, uv.y); - for k in 0..4 { - acc[k] += s[k] * w; + let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; + + let (coords, projection, _) = self.projected(projection); + let mut sum = [0.0f32; 4]; + for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + *total += value * weight; } } + + let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], - ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], - ChannelKind::Scalar => [acc[0]; 3], - ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], + ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 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()); + // An anchor not evaluated yet (above this layer, hidden) reads the channel default + let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); + let value = anchored.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 } + if gray { [lum(value); 3] } else { value } } } } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index e937b6f5..85a62200 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -2,12 +2,12 @@ //! (a decal fill with a planar projection), as a fill layer with a decal projection. use serde_json::{Value, json}; -use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source}; +use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source}; use texturecraft_geom::glam::{Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p}; use crate::tool_cmds::viewport_of; -use crate::{Result, Session, cmd}; +use crate::{Result, Session, StackTarget, cmd}; pub fn specs() -> Vec { vec![ @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -42,43 +42,51 @@ fn vec3(p: &Value, key: &str) -> Option { } } -/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view -/// center by default) or `position` + `normal`. None when `optional` and neither is given. -fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { - if let Some(pos) = vec3(p, "position") { - let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; - return Ok(Some((pos, n))); +/// Resolve a viewport hit or explicit world position, using `texture_set` for explicit positions. +/// Returns None when placement is optional and no position or viewport point is given. +fn placement(session: &Session, command: &str, params: &Value, texture_set: usize, optional: bool) -> Result> { + if let Some(position) = vec3(params, "position") { + let normal = vec3(params, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(command, "`position` needs a non-zero `normal`"))?; + return Ok(Some((position, normal, texture_set))); } - let vp = viewport_of(s, p); - let at = match (f32p(p, "x"), f32p(p, "y")) { + + let viewport = viewport_of(session, params); + let point = match (f32p(params, "x"), f32p(params, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), _ if optional => return Ok(None), - _ => vp * 0.5, + _ => viewport * 0.5, }; - let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; - if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) { - return Err(bad(cmd, "that surface belongs to another texture set")); - } - Ok(Some((hit.pos, hit.nrm))) + let hit = session.pick(point, viewport).ok_or_else(|| bad(command, "nothing under that point: place the decal on the mesh"))?; + let hit_set = session.texture_set_of_material(hit.material).ok_or_else(|| bad(command, "that surface has no texture set"))?; + Ok(Some((hit.pos, hit.nrm, hit_set))) } +/// A new decal's height, relative to the mesh diagonal +const DEFAULT_HEIGHT: f32 = 0.25; + +/// The smallest decal side or depth, relative to the mesh diagonal +const MIN_SIZE: f32 = 1e-4; + +/// The largest decal side or depth, relative to the mesh diagonal +const MAX_SIZE: f32 = 10.0; + /// The mesh's diagonal (decal sizes are relative to it). fn mesh_size(s: &Session) -> f32 { let (lo, hi) = s.mesh.bounds(); (hi - lo).length().max(1e-3) } -/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`). -fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { - let v = p.get("size")?; - let size = match v.as_array() { - Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32], +/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits +fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = p.get("size")?; + let size = match value.as_array() { + Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { - let h = v.as_f64()? as f32; - [h * aspect, h] + let height = value.as_f64()? as f32; + [height * aspect, height] } }; - size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) + size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE))) } /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on @@ -96,11 +104,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { fn add(s: &mut Session, p: &Value) -> Result { let cmd = "layer.add.decal"; let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; - let aspect = img.width as f32 / img.height.max(1) as f32; - let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; - let diag = mesh_size(s); - let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]); + let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; + let aspect = resource.width as f32 / resource.height.max(1) as f32; + let (center, normal, ts) = placement(s, cmd, p, s.ts(), false)?.ok_or_else(|| bad(cmd, "no placement"))?; + + // None: the image masks a new fill layer + let target = match strp(p, "channel") { + Some("mask") => None, + _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + }; + let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + if let Some(channel) = target + && !set_channels.contains(&channel) + { + return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + } + + let mesh_diagonal = mesh_size(s); + let default_height = mesh_diagonal * DEFAULT_HEIGHT; + let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); let decal = Decal { center: center.to_array(), normal: normal.to_array(), @@ -108,68 +130,139 @@ fn add(s: &mut Session, p: &Value) -> Result { size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)), + // By default it reaches half its larger side into the surface + depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), }; - let ts = s.ts(); - let base = - strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string()); + + // A decal dropped on another texture set goes there and selects it, as a dropped material does + if ts != s.ts() { + crate::set_cmds::select_set(s, ts); + } + + let base = strp(p, "name") + .map(str::to_string) + .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); let name = s.doc.project.next_layer_name(ts, &base); - let id = s.edit("Add decal", |s| { + let (id, mask_effect) = s.edit("Add decal", |s| { let id = s.doc.project.alloc_id(); + let Some(channel) = target else { + let effect_id = s.doc.project.alloc_id(); + let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + layer.mask = Some(mask); + crate::layer_cmds::insert_selected(s, layer)?; + s.target = StackTarget::Effect(effect_id); + return Ok((id, Some(effect_id))); + }; + let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor])) + fill.sources.insert(channel, Source::image(image.clone())); + crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + Ok((id, None)) })?; - Ok(json!({ "layer": id.0, "decal": decal })) + Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`. -fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result { +/// The decal of fill layer `id`, or of mask fill effect `effect` when given +fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { + if let Some(effect) = effect { + return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), + _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), + }; + } + match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d), + LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), } } -fn set(s: &mut Session, p: &Value) -> Result { - let cmd = "layer.decal.set"; - let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?; - let mut d = decal_of(s, cmd, id)?; - let diag = mesh_size(s); - if let Some((center, normal)) = placement(s, cmd, p, true)? { - (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); - } - if p.get("up").is_some() { - d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); - } - if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { - d.size = size; - } - if let Some(r) = f32p(p, "rotation") { - d.rotation = r.rem_euclid(360.0); - } - if let Some(o) = p.get("offset").and_then(Value::as_array) { - let v: Vec = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; - d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)]; - } - if let Some(v) = f32p(p, "depth") { - d.depth = v.clamp(diag * 1e-4, diag * 10.0); - } - let image = strp(p, "image").map(str::to_string); - if let Some(name) = &image - && !s.doc.resources.contains_key(name) +fn set(session: &mut Session, params: &Value) -> Result { + let command = "layer.decal.set"; + let effect = u64p(params, "effect").map(LayerId); + let layer_id = match effect { + Some(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(command, format!("no effect {}", effect.0)))?, + None => session.doc.project.content_layer(layer_param(session, command, params)?).map(|layer| layer.id).ok_or_else(|| bad(command, "no layer"))?, + }; + if let (Some(effect), Some(layer)) = (effect, u64p(params, "layer")) + && layer != layer_id.0 { - return Err(bad(cmd, format!("no image resource `{name}`"))); + return Err(bad(command, format!("effect {} is not in layer {layer}", effect.0))); } - s.edit("Edit decal", |s| { - if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind { - f.projection = Projection::Decal(d); - if let Some(name) = image { - f.sources.insert(Channel::BaseColor, Source::image(name)); + + let mut decal = decal_of(session, command, layer_id, effect)?; + let texture_set = + session.doc.project.locate(layer_id).map(|(texture_set, _, _)| texture_set).ok_or_else(|| bad(command, "the decal has no texture set"))?; + let mesh_diagonal = mesh_size(session); + if let Some((center, normal, hit_set)) = placement(session, command, params, texture_set, true)? { + // Selecting another set must not let this decal leave its layer's stack + if hit_set != texture_set { + return Err(bad(command, "that surface belongs to another texture set")); + } + + (decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); + } + if params.get("up").is_some() { + decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array(); + } + if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) { + decal.size = size; + } + if let Some(rotation) = f32p(params, "rotation") { + decal.rotation = rotation.rem_euclid(360.0); + } + if let Some(offset) = params.get("offset").and_then(Value::as_array) { + let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); + let [right, up] = values.as_slice() else { return Err(bad(command, "`offset` must be [right, up]")) }; + + decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; + } + if let Some(depth) = f32p(params, "depth") { + decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + } + + let image = strp(params, "image").map(str::to_string); + if let Some(name) = &image + && !session.doc.resources.contains_key(name) + { + return Err(bad(command, format!("no image resource `{name}`"))); + } + + session.edit("Edit decal", |session| { + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection }) = session.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *projection = Projection::Decal(decal); + if let Some(image) = image { + *source = Source::image(image); + } + } + } else if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer_id)?.kind { + fill.projection = Projection::Decal(decal); + + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} } } Ok(()) })?; - Ok(json!({ "layer": id.0, "decal": d })) + Ok(json!({ "layer": layer_id.0, "decal": decal })) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..3f394e23 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -75,12 +75,20 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let ts = u64p(p, "ts") + .map(|index| index as usize) + .filter(|index| *index < s.set_count()) + .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + select_set(s, ts); + Ok(json!({ "ts": ts })) +} + +/// Make texture set `ts` the active one, on its content stack +pub(crate) fn select_set(s: &mut Session, ts: usize) { s.cancel_stroke(); s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); - Ok(json!({ "ts": ts })) } fn resolution(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index 814ea08b..f729476e 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -34,6 +34,9 @@ fn red(v: [f32; 3]) -> bool { v[0] > 0.85 && v[1] < 0.15 } +/// Distance between the view points searched for a texture set +const SEARCH_STEP: f32 = 10.0; + fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { let mut out = Vec::new(); image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); @@ -345,6 +348,129 @@ fn decal_drags_merge_into_one_undo_step() { assert_eq!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["layers"], start); } +/// A decal dropped on another texture set lands there and selects it, in one undo step +#[test] +fn a_decal_on_another_texture_set_selects_that_set() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.update(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let selected = s.ts(); + let (columns, rows) = ((s.viewport.x / SEARCH_STEP) as u32, (s.viewport.y / SEARCH_STEP) as u32); + let other_set_pixel = (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&pixel| s.texture_set_at(pixel, s.viewport).is_some_and(|ts| ts != selected)) + .expect("the material ball shows both of its texture sets"); + let other = s.texture_set_at(other_set_pixel, s.viewport).unwrap(); + let steps = s.history_labels().len(); + + let drop = json!({"image": name, "x": other_set_pixel.x, "y": other_set_pixel.y, "viewport": [s.viewport.x, s.viewport.y]}); + let layer = id(execute(&mut s, "layer.add.decal", &drop).unwrap(), "layer"); + + assert_eq!(s.ts(), other, "the set under the point is selected"); + assert_eq!(s.doc.project.locate(layer).map(|(ts, _, _)| ts), Some(other), "the decal is in that set"); + assert_eq!(s.selected_layer(), Some(layer)); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.locate(layer).is_none(), "one undo takes the decal away"); + + let background = json!({"image": name, "x": 2, "y": 2, "viewport": [s.viewport.x, s.viewport.y]}); + assert!(s.texture_set_at(Vec2::new(2.0, 2.0), s.viewport).is_none()); + assert!(execute(&mut s, "layer.add.decal", &background).is_err(), "the background still takes nothing"); +} + +/// A decal's image goes in the channel asked for, or masks a new fill layer +#[test] +fn a_decal_image_fills_a_chosen_channel_or_a_mask() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); + + let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); + assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); + + let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); + let masked = id(added.clone(), "layer"); + let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); + assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); + + let effect = &added["maskEffect"]; + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); + assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); + let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); + assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); +} + +#[test] +fn editing_a_decal_checks_its_own_texture_set_after_selection_changes() { + for channel in ["baseColor", "mask"] { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + session.viewport = Vec2::new(400.0, 400.0); + session.update(); + let image = session.import_resource_bytes("logo.png", png(8, 8, |_, _| [255; 4])).unwrap(); + let (columns, rows) = ((session.viewport.x / SEARCH_STEP) as u32, (session.viewport.y / SEARCH_STEP) as u32); + let point_on = |texture_set| { + (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&point| session.texture_set_at(point, session.viewport) == Some(texture_set)) + .expect("both material-ball sets are visible") + }; + let original_point = point_on(0); + let other_point = point_on(1); + let added = + execute(&mut session, "layer.add.decal", &json!({"image": image, "channel": channel, "x": original_point.x, "y": original_point.y})).unwrap(); + let layer = added["layer"].clone(); + let effect = added["maskEffect"].clone(); + execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let before = serde_json::to_value(&session.doc.project).unwrap(); + let history = session.history_labels(); + + let rejected = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": other_point.x, "y": other_point.y})); + + assert!(rejected.is_err(), "{channel}: selecting another set must not allow moving the decal onto that set"); + assert_eq!(serde_json::to_value(&session.doc.project).unwrap(), before); + assert_eq!(session.history_labels(), history); + + let replaced = execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "x": original_point.x, "y": original_point.y})); + + assert!(replaced.is_ok(), "{channel}: the decal's own set remains a valid placement: {replaced:?}"); + let decal = replaced.unwrap()["decal"].clone(); + + execute(&mut session, "layer.decal.set", &json!({"layer": layer, "effect": effect, "position": decal["center"], "normal": decal["normal"]})).unwrap(); + + assert_eq!(session.ts(), 1, "editing an explicit decal does not change selection"); + } +} + +/// A decal's new image stays in the channel the decal was placed in, read as gray there +#[test] +fn a_channel_decal_reads_its_image_as_gray_and_keeps_its_channel() { + let mut s = session(); + let white = s.import_resource_bytes("white.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let green = s.import_resource_bytes("green.png", png(8, 8, |_, _| [0, 255, 0, 255])).unwrap(); + let place = json!({"image": white, "channel": "roughness", "x": 200, "y": 200, "size": 0.5}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "image": green})).unwrap(); + + assert_eq!(s.doc.project.layer(layer).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + let roughness = at(&mut s, Channel::Roughness, 200.0, 200.0)[0]; + assert!((roughness - texturecraft_engine::core::lum([0.0, 1.0, 0.0])).abs() < 0.02, "green reads as its gray, not its red: {roughness}"); +} + /// The Geometry mask tool: a click toggles the selected layer on the part under it. #[test] fn geometry_mask_tool_toggles_the_clicked_part() { diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs new file mode 100644 index 00000000..2071ceb6 --- /dev/null +++ b/crates/ui-egui/src/decal_drop.rs @@ -0,0 +1,130 @@ +//! A shelf image dropped on the 3D view waits for a menu pick at the drop point: a mask, or a channel of the texture set under it + +use egui::{Id, Pos2, Ui, Vec2}; +use serde_json::json; +use texturecraft_engine::geom::OrbitCamera; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// What the menu offers besides the texture set's channels: a new fill layer masked by the image +const MASK_CHOICE: &str = "mask"; + +/// The most of the window's height the channel list takes before it scrolls +const MENU_MAX_HEIGHT_SHARE: f32 = 0.6; + +/// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked +#[derive(Clone)] +pub struct DecalDrop { + /// The image resource + pub image: String, + /// The texture set under the drop point + pub texture_set: usize, + /// The drop point in view pixels + pub view_position: Vec2, + /// The 3D view's size in pixels + pub view_size: Vec2, + /// The camera used to pick the drop point + pub camera: OrbitCamera, + /// The drop point on screen, where the menu opens + pub screen_position: Pos2, +} + +impl DecalDrop { + /// Where the waiting drop and its menu's state are kept + fn menu_id() -> Id { + Id::unique("decal_drop_menu") + } + + /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits + pub fn open(self, ui: &Ui) { + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), (self, frame))); + } + + /// Keep input out of both views while the menu waits and for the rest of its closing frame + pub fn blocks_input(ctx: &egui::Context) -> bool { + Self::current(ctx).is_some() || ctx.data(|data| data.get_temp::(Self::menu_id().with("closed_frame"))) == Some(ctx.cumulative_frame_nr()) + } + + /// The waiting drop; one whose menu went undrawn for a frame (the 3D view was hidden) is dropped instead of blocking the views + fn current(ctx: &egui::Context) -> Option { + let frame = ctx.cumulative_frame_nr(); + let (drop, menu_frame) = ctx.data(|data| data.get_temp::<(DecalDrop, u64)>(Self::menu_id()))?; + if frame > menu_frame + 1 { + ctx.data_mut(|data| data.remove::<(DecalDrop, u64)>(Self::menu_id())); + return None; + } + + Some(drop) + } + + /// Close the menu and consume the rest of this frame's input + fn close(ctx: &egui::Context) { + let id = Self::menu_id(); + let frame = ctx.cumulative_frame_nr(); + + // The 2D view reads input after this menu closes in the 3D view + ctx.data_mut(|data| { + data.remove::<(DecalDrop, u64)>(id); + data.insert_temp(id.with("closed_frame"), frame); + }); + } + + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { + let id = Self::menu_id(); + let Some(drop) = Self::current(ui.ctx()) else { return }; + + // Saved view pixels must not be picked through a different camera + if drop.camera != app.session.camera { + Self::close(ui.ctx()); + return; + } + + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(id, (drop.clone(), frame))); + + let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); + let mut picked = None; + let shown = egui::Popup::new(id, ui.ctx().clone(), egui::PopupAnchor::Position(drop.screen_position), response.layer_id) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + if ui.button(tr("Mask")).clicked() { + picked = Some(MASK_CHOICE); + } + ui.separator(); + + // Many channels scroll instead of running off the window + let max_height = ui.ctx().content_rect().height() * MENU_MAX_HEIGHT_SHARE; + egui::ScrollArea::vertical().max_height(max_height).show(ui, |ui| { + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } + } + }); + }); + + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + Self::close(ui.ctx()); + } + + let Some(channel) = picked else { return }; + + app.run( + "layer.add.decal", + json!({ + "image": drop.image, + "channel": channel, + "x": drop.view_position.x, + "y": drop.view_position.y, + "viewport": [drop.view_size.x, drop.view_size.y], + }), + ); + } +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 429142fd..aabb2571 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -476,6 +476,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "أرجواني / أخضر"), ("Main shader", "المظلل الرئيسي"), ("Marble veins", "عروق الرخام"), + ("Mask", "قناع"), ("Mask Editor: Edge wear", "محرر الأقنعة: تآكل الحواف"), ("Mask value (gray)", "قيمة القناع (رمادي)"), ("Mask with height", "قناع بالارتفاع"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 6a746439..12858d1e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -503,6 +503,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / Grün"), ("Main shader", "Haupt-Shader"), ("Marble veins", "Marmoradern"), + ("Mask", "Maske"), ("Mask Editor: Edge wear", "Masken-Editor: Kantenabnutzung"), ("Mask value (gray)", "Maskenwert (Grau)"), ("Mask with height", "Mit Höhe maskieren"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 1bf38dfc..92120ff4 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -494,6 +494,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Sombreador principal"), ("Marble veins", "Vetas de mármol"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscaras: desgaste de bordes"), ("Mask value (gray)", "Valor de máscara (gris)"), ("Mask with height", "Enmascarar con la altura"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 22300273..e7fa9b1d 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -509,6 +509,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / vert"), ("Main shader", "Shader principal"), ("Marble veins", "Veines de marbre"), + ("Mask", "Masque"), ("Mask Editor: Edge wear", "Éditeur de masque : usure des arêtes"), ("Mask value (gray)", "Valeur du masque (gris)"), ("Mask with height", "Masquer avec la hauteur"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 07eb5f57..8bec1934 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -500,6 +500,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principale"), ("Marble veins", "Venature marmo"), + ("Mask", "Maschera"), ("Mask Editor: Edge wear", "Editor maschera: Usura bordi"), ("Mask value (gray)", "Valore maschera (grigio)"), ("Mask with height", "Maschera con altezza"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index f2dff9bf..90c28cab 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -488,6 +488,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "マゼンタ / グリーン"), ("Main shader", "メインシェーダー"), ("Marble veins", "大理石の筋"), + ("Mask", "マスク"), ("Mask Editor: Edge wear", "マスクエディター: エッジの摩耗"), ("Mask value (gray)", "マスク値 (グレー)"), ("Mask with height", "ハイトでマスク"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 00b97ac4..fd96c46d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -482,6 +482,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "마젠타 / 녹색"), ("Main shader", "메인 셰이더"), ("Marble veins", "대리석 무늬"), + ("Mask", "마스크"), ("Mask Editor: Edge wear", "마스크 에디터: 모서리 마모"), ("Mask value (gray)", "마스크 값 (회색)"), ("Mask with height", "높이로 마스크"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index c532abc7..923b7fee 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -491,6 +491,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principal"), ("Marble veins", "Veios de mármore"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscara: Desgaste de bordas"), ("Mask value (gray)", "Valor da máscara (cinza)"), ("Mask with height", "Mascarar com altura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 6c970fd9..47619f9e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -446,6 +446,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "洋红 / 绿色"), ("Main shader", "主着色器"), ("Marble veins", "大理石纹"), + ("Mask", "遮罩"), ("Mask Editor: Edge wear", "遮罩编辑器:边缘磨损"), ("Mask value (gray)", "遮罩值(灰度)"), ("Mask with height", "用高度遮罩"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 05f90809..dc315a84 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -12,6 +12,7 @@ pub mod bake_mode; mod bake_scene; mod color_selection_editor; pub mod control; +mod decal_drop; pub mod dock; pub mod docking; pub mod export_templates; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 05103100..9a36df2a 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -2,7 +2,7 @@ //! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. //! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas //! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there. +//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; @@ -20,6 +20,7 @@ use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; @@ -89,6 +90,11 @@ impl Asset { pub fn is_material(&self) -> bool { matches!(self, Asset::Material(_) | Asset::Library(_)) } + + /// Assets a 3D view drop puts on the texture set under the pointer + pub fn goes_onto_set(&self) -> bool { + self.is_material() || matches!(self, Asset::Texture(_)) + } } /// The drag-and-drop payload of a shelf tile. @@ -144,17 +150,17 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (decals where they drop, on that set) View3d, } -/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to -pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { +/// The texture set under the pointer while a shelf material or image is dragged over the 3D view `response`: the set a drop there goes to +pub fn drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { if app.ui.mode != crate::state::Mode::Painting { return None; } - response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + response.dnd_hover_payload::().filter(|drag| drag.asset.goes_onto_set())?; set_under_pointer(app, ui, response) } @@ -164,12 +170,16 @@ fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) } -/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material or image goes to the texture set under the pointer, highlighted by the view itself ([`drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; } + if zone == DropZone::View3d { + DecalDrop::show_menu(app, ui, response); + } + let tokens = Tokens::get(ui.ctx()); let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, @@ -177,7 +187,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } @@ -186,11 +196,20 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); - } // The background takes nothing + (Asset::Texture(name), Some(position)) => { + let Some(texture_set) = set_under_pointer(app, ui, response) else { return }; + + let drop = DecalDrop { + image: name.clone(), + texture_set, + view_position: position - response.rect.min, + view_size: response.rect.size(), + camera: app.session.camera, + screen_position: position, + }; + drop.open(ui); + } (asset, _) if onto_set(asset) => { let Some(ts) = set_under_pointer(app, ui, response) else { return }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f3087537..5eb9846a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -13,6 +13,7 @@ use texturecraft_engine::{Session, Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; @@ -238,9 +239,9 @@ fn shade(app: &TextureCraftApp) -> Shade { } } -/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +/// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { - let set = crate::shelf::material_drop_set(app, ui, response)?; + let set = crate::shelf::drop_set(app, ui, response)?; let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) @@ -570,11 +571,12 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // Decal placement: a click moves the decal being placed there + // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt + && !DecalDrop::blocks_input(ui.ctx()) && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -609,6 +611,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && placing.is_none() && !picking_id_color && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()) && decal_input(app, ui, &response, rect); // Painting @@ -622,7 +625,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && placing.is_none() && !picking_id_color && touch.is_none() - && !decal_drag; + && !decal_drag + && !DecalDrop::blocks_input(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); @@ -683,7 +687,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); - // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + // Shelf drops: a material goes above the selection of the set under the pointer, an image opens the decal menu there, an alpha goes on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began @@ -771,16 +775,18 @@ impl DecalGrab { } } -/// A decal handle being dragged (kept in egui's memory between frames). +/// A decal handle being dragged (kept in egui's memory between frames) #[derive(Clone, Copy, Debug)] struct DecalDrag { layer: texturecraft_engine::core::LayerId, + /// The mask fill effect holding the decal, when it was placed as a mask + effect: Option, grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then. + /// Where the drag started, the decal's center on screen and the decal then from: Pos2, center: Pos2, start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it. + /// The drag made its undo step: later updates merge into it stepped: bool, } @@ -791,34 +797,56 @@ fn decal_drag_id() -> egui::Id { /// Screen distance from the top edge to the rotation handle (points). const DECAL_KNOB: f32 = 24.0; -/// The selected decal layer (its content, not its mask) as the 3D view shows it. +/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it struct DecalFrame { layer: texturecraft_engine::core::LayerId, + /// The selected mask fill effect holding the decal, when it was placed as a mask + effect: Option, decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left. + /// Top left, top right, bottom right, bottom left corners: [Pos2; 4], center: Pos2, - /// The middle of the top edge and the rotation handle above it. + /// The middle of the top edge and the rotation handle above it top: Pos2, knob: Pos2, } impl DecalFrame { fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - use texturecraft_engine::core::{Fill, LayerKind, Projection}; - if app.ui.mode != crate::state::Mode::Painting || app.session.target != texturecraft_engine::StackTarget::Content { + use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; + + if app.ui.mode != crate::state::Mode::Painting { return None; } - let p = &app.session.doc.project; - let layer = app.session.selected_layer().and_then(|id| p.content_layer(id))?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - let [a, b, c, d] = decal_corners(decal)?.map(|q| project(app, rect, q)); - let corners = [a?, b?, c?, d?]; + + let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; + let (layer, effect, decal) = match app.session.target { + StackTarget::Content => { + let layer = layers.content_layer(selected)?; + let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; + + (layer.id, None, decal) + } + StackTarget::Effect(effect) => { + // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; + let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), decal) + } + StackTarget::Mask => return None, + }; + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); + let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; let center = project(app, rect, decal_axes(decal)?.0)?; let top = corners[0].lerp(corners[1], 0.5); let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer: layer.id, decal: *decal, corners, center, top, knob }) + Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) } /// The handle under screen point `p`. @@ -839,51 +867,56 @@ impl DecalFrame { } } -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates -/// live). Returns whether a decal drag owns the pointer. +/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { let ctx = ui.ctx(); let frame = DecalFrame::of(app, rect); - let mut drag = ctx.data(|d| d.get_temp::(decal_drag_id())).filter(|d| frame.as_ref().is_some_and(|f| f.layer == d.layer)); + let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); + let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); if resp.drag_started_by(PointerButton::Primary) - && let (Some(f), Some(from)) = (&frame, ctx.input(|i| i.pointer.press_origin())) - && let Some(grab) = f.grab(from) + && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = frame.grab(from) { - drag = Some(DecalDrag { layer: f.layer, grab, from, center: f.center, start: f.decal, stepped: false }); + drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); } - let Some(mut d) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|m| m.remove::(decal_drag_id())); - if let (Some(f), Some(h)) = (&frame, resp.hover_pos()) - && let Some(g) = f.grab(h) + + let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { + ctx.data_mut(|data| data.remove::(decal_drag_id())); + if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) + && let Some(grab) = frame.grab(hover) { - ctx.set_cursor_icon(g.cursor(false)); + ctx.set_cursor_icon(grab.cursor(false)); } return false; }; - ctx.set_cursor_icon(d.grab.cursor(true)); - if let Some(p) = resp.interact_pointer_pos().filter(|_| ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match d.grab { + + ctx.set_cursor_icon(drag.grab.cursor(true)); + if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { + let mut params = match drag.grab { DecalGrab::Move => { - let q = d.center + (p - d.from) - rect.left_top(); - let vp = app.session.viewport; - json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}) + let target = drag.center + (pointer - drag.from) - rect.left_top(); + let viewport = app.session.viewport; + json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) } DecalGrab::Scale => { - let k = (p - d.center).length() / (d.from - d.center).length().max(1.0); - json!({"size": [d.start.size[0] * k, d.start.size[1] * k]}) + let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); + json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) } DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up. - let angle = |v: egui::Vec2| (-v.y).atan2(v.x).to_degrees(); - json!({"rotation": d.start.rotation + angle(p - d.center) - angle(d.from - d.center)}) + // Screen y points down: counter-clockwise angles turn the decal's right toward its up + let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); + json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) } }; - params["layer"] = json!(d.layer.0); - params["merge"] = json!(d.stepped); - // Off the mesh while moving: the decal waits where it is. - d.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); + params["layer"] = json!(drag.layer.0); + if let Some(effect) = drag.effect { + params["effect"] = json!(effect.0); + } + params["merge"] = json!(drag.stepped); + // Off the mesh while moving: the decal waits where it is + drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); } - ctx.data_mut(|m| m.insert_temp(decal_drag_id(), d)); + ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); true } @@ -1400,7 +1433,13 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !picking_id_color; + let painting = app.ui.mode == crate::state::Mode::Painting + && app.properties_popup.is_none() + && !alt + && !adjusting + && !v_held + && !picking_id_color + && !DecalDrop::blocks_input(ui.ctx()); let mut fill_box = None; if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); @@ -1584,6 +1623,139 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + /// A selected mask decal on the ball, with another texture set available for selection tests + fn decal_frame_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = + Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = harness.state_mut().session.import_resource_bytes("decal.png", png).unwrap(); + harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); + harness.run_steps(2); + assert_eq!(harness.state().session.ts(), 0); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness + } + + /// Move a primary-button drag through enough frames to reach the viewport's decal handles + fn drag_decal_handle(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from.lerp(to, step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + } + + #[test] + fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { + use texturecraft_engine::{StackTarget, execute}; + + for texture_set in [0, 1] { + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + execute(session, "textureSet.select", &json!({"ts": texture_set})).unwrap(); + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + let selected = execute(session, "layer.select", &json!({"layer": other, "target": effect.0})); + + assert!(selected.is_err()); + assert_eq!(session.ts(), texture_set); + assert_eq!(session.selected_layer().unwrap().0, other.as_u64().unwrap()); + assert_eq!(session.target, StackTarget::Effect(effect), "the failed selection leaves the previous effect target"); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); + + drag_decal_handle(&mut harness, original.corners[1], original.center + (original.corners[1] - original.center) * 1.5); + drag_decal_handle(&mut harness, original.knob, original.knob + vec2(40.0, 0.0)); + + let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; + assert!( + matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Decal(decal), .. } if *decal == original.decal) + ); + } + } + + #[test] + fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + + // The source effect remains a valid inherited target when selection changes to its instance + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert_eq!(session.ts(), 1); + assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); + let inherited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); + + drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); + + let edited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); + } + + #[test] + fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + execute(session, "mask.add.black", &json!({"layer": instance})).unwrap(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); + } + + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn decal_frame_selection_snapshots() { + use texturecraft_engine::execute; + + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let mut harness = decal_frame_app(true); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); + + let session = &mut harness.state_mut().session; + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none()); + harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); + } + #[test] fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index 5b35cc06..db784edf 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -1,14 +1,21 @@ -//! A shelf material dropped on the 3D view goes to the texture set under the pointer +//! A shelf material or image dropped on the 3D view goes to the texture set under the pointer; an image first asks what it becomes use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; +use texturecraft_ui_egui::state::ViewLayout; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; +/// How far from the drop point the drop menu's items can be +const MENU_REACH: f32 = 60.0; + /// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -33,7 +40,12 @@ fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos /// Drop a built-in shelf material at `position`, as a drag from the shelf ends there fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + drop_asset(harness, Asset::Material("iron_rusted"), position); +} + +/// Drop shelf `asset` at `position`, as a drag from the shelf ends there +fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() }); harness.hover_at(position); harness.run_steps(2); @@ -70,3 +82,231 @@ fn a_material_dropped_on_the_background_changes_nothing() { assert_eq!(stack_sizes(&harness), stacks); assert_eq!(harness.state().session.history_labels().len(), history); } + +/// Import a small white image and return its resource name +fn import_white_image(harness: &mut Harness<'_, TextureCraftApp>) -> String { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); + harness.run_steps(2); + name +} + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let name = import_white_image(&mut harness); + + let position = point_over(&harness, position_over); + drop_asset(&mut harness, Asset::Texture(name), position); + // The menu's first frame only measures it + harness.run_steps(2); + (harness, position) +} + +#[test] +fn an_image_dropped_on_another_set_asks_for_a_channel_then_goes_to_that_set() { + let (mut harness, position) = drop_image(Some(1)); + let before = stack_sizes(&harness); + + // The menu item nearest the drop point (Properties may show the same name) + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + + let app = harness.state(); + assert_eq!(app.session.ts(), 1, "the set under the drop point is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1]); + let layer = app.session.selected_layer().and_then(|id| app.session.doc.project.layer(id).ok()).unwrap(); + assert_eq!(layer.channels.keys().copied().collect::>(), [Channel::Roughness], "the image fills the picked channel"); +} + +/// Whether the drop menu is open at `position` (its Mask item near there) +fn menu_open(harness: &Harness<'_, TextureCraftApp>, position: Pos2) -> bool { + harness.query_all_by_label("Mask").any(|node| node.rect().center().distance(position) < MENU_REACH) +} + +/// Press and release the primary button at `position` +fn click(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.hover_at(position); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +#[test] +fn dismissing_an_image_drop_in_the_2d_view_does_not_paint() { + let (mut harness, position) = drop_image(Some(1)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let view_3d = harness.state().viewport_rect; + let uv_center = egui::pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + let history = harness.state().session.history_labels(); + assert!(menu_open(&harness, position)); + + click(&mut harness, uv_center); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels(), history, "dismissing the menu must not fill the UV view"); + + click(&mut harness, uv_center); + + assert_eq!(harness.state().session.history_labels().len(), history.len() + 1, "the next click paints normally"); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill")); +} + +#[test] +fn a_pending_image_drop_does_not_drag_the_selected_decal() { + let mut harness = sample_app(); + let image = import_white_image(&mut harness); + let rect = harness.state().viewport_rect; + let center = rect.center(); + let local = center - rect.min; + harness.state_mut().run("layer.add.decal", serde_json::json!({"image": image, "x": local.x, "y": local.y})).unwrap(); + harness.run_steps(2); + let drop_position = point_over(&harness, Some(1)); + drop_asset(&mut harness, Asset::Texture(image), drop_position); + harness.run_steps(2); + assert!(menu_open(&harness, drop_position)); + let layer = harness.state().session.selected_layer().unwrap(); + let before = harness.state().session.doc.project.layer(layer).unwrap().kind.clone(); + let history = harness.state().session.history_labels(); + + harness.hover_at(center); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: center, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + let moved = center + egui::vec2(30.0, 0.0); + harness.hover_at(moved); + harness.run_steps(2); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().kind, before, "a pending drop owns the decal-drag input"); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { + let (mut harness, position) = drop_image(Some(1)); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + assert!(menu_open(&harness, position)); + + // A click elsewhere on the mesh closes the menu and fills nothing there (a polygon fill click records a step in this harness) + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let elsewhere = point_over(&harness, Some(0)); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!menu_open(&harness, position)); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); + + let (harness, position) = drop_image(None); + assert!(!menu_open(&harness, position), "the background opens no menu"); +} + +#[test] +fn hiding_the_3d_view_lets_go_of_a_waiting_image_drop() { + let (mut harness, position) = drop_image(Some(1)); + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let history = harness.state().session.history_labels().len(); + assert!(menu_open(&harness, position)); + + // Only the 3D view shows the menu, so a 2D-only layout would otherwise leave the views blocked + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + click(&mut harness, egui::pos2(700.0, 420.0)); + + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the hidden menu no longer blocks UV painting"); + assert_eq!(harness.state().session.undo_label(), Some("Polygon fill")); + + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(3); + + assert!(!menu_open(&harness, position), "the drop lapsed while its menu was hidden"); +} + +#[test] +fn changing_the_camera_cancels_a_drop_with_stale_view_coordinates() { + let (mut harness, position) = drop_image(Some(1)); + let history = harness.state().session.history_labels(); + let stacks = stack_sizes(&harness); + assert!(menu_open(&harness, position)); + + harness.state_mut().session.camera.distance *= 2.0; + harness.run_steps(3); + + let app = harness.state(); + let local = position - app.viewport_rect.min; + assert_ne!(app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport), Some(1), "the saved pixel no longer hits the dropped-on set"); + assert!(!menu_open(&harness, position), "a stale drop must not offer placement on a different surface"); + assert_eq!(harness.state().session.history_labels(), history); + assert_eq!(stack_sizes(&harness), stacks); +} + +#[test] +fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { + let (mut harness, position) = drop_image(Some(1)); + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + let decal_layer = harness.state().session.selected_layer().unwrap(); + harness.state_mut().placing_decal = Some(decal_layer); + + let image = import_white_image(&mut harness); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); + + // A point on the same set, away from the menu + let rect = harness.state().viewport_rect; + let elsewhere = (1..(rect.width() / SEARCH_STEP) as usize) + .map(|step| Pos2::new(rect.max.x - step as f32 * SEARCH_STEP, position.y)) + .find(|point| { + let app = harness.state(); + let local = *point - rect.min; + point.distance(position) > MENU_REACH * 2.0 && app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport) == Some(1) + }) + .unwrap(); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); +} + +#[test] +#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] +fn image_drop_menu_snapshots() { + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(6); + let image = import_white_image(&mut harness); + let position = point_over(&harness, Some(1)); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(6); + + assert!(menu_open(&harness, position)); + harness.render().unwrap().save(directory.join("image-drop-menu.png")).unwrap(); + + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Mask").min_by(|left, right| distance(left).total_cmp(&distance(right))).unwrap().click(); + harness.run_steps(6); + + assert_eq!(harness.state().session.ts(), 1); + assert!(matches!(harness.state().session.target, texturecraft_engine::StackTarget::Effect(_))); + harness.render().unwrap().save(directory.join("image-drop-mask.png")).unwrap(); +}