diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 54d8b9995d..5c4fdf9a18 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -48,6 +48,7 @@ mod steps_layer; mod steps_layer_style; mod steps_lookup; mod steps_make; +mod steps_perspective_warp; mod steps_type_path; mod steps_other; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 13e97309db..900a9220d1 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -1068,6 +1068,14 @@ pub(super) const EVENTS: &[Event] = &[ ev!("", "autoCutout", "Select Subject", "select.subject", &[F("sampleAllLayers", "sampleAllLayers", Kind::Bool)]), Event { code: "ClrR", name: "colorRange", label: "Color Range", ids: &["select.colorRange"], from: color_range_from, to: color_range_to }, // Edit. + Event { + code: "", + name: "perspectiveWarpTransform", + label: "Perspective Warp", + ids: &[crate::distort_cmds::PERSPECTIVE], + from: super::steps_perspective_warp::from, + to: super::steps_perspective_warp::to, + }, Event { code: "Grdn", name: "gradientClassEvent", diff --git a/crates/engine/src/cmd/atn_cmds/steps_perspective_warp.rs b/crates/engine/src/cmd/atn_cmds/steps_perspective_warp.rs new file mode 100644 index 0000000000..87f789ef91 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_perspective_warp.rs @@ -0,0 +1,171 @@ +//! Recorded Perspective Warp layout and warp planes (#10710). + +use std::collections::BTreeSet; + +use photocraft_algo::perspective::{Plane, linked_corners}; +use photocraft_algo::transform::{WARP_REACH, convex_quad}; +use photocraft_io::smart_map::{MAX_PERSPECTIVE_WARP_PLANES as MAX_PLANES, perspective_warp_geometry, perspective_warp_indexed_geometry}; + +use super::convert::normalise; +use super::descriptors::{desc, enm, get_obj, get_ref, layer_ref, layer_target, px, ref_class}; +use super::events::pixel_target; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, ReferenceItem, Value, json}; +use crate::distort_cmds::PERSPECTIVE; + +const EVENT: &str = "perspectiveWarpTransform"; +const SOURCE: &str = "__atnPerspectiveWarp"; +const RECT: &str = "__atnPerspectiveWarpRect"; +const MAX_DESCRIPTOR_BYTES: usize = 256 * 1024; + +/// Allows exactly the measured keys, once each. The preserved descriptor retains their order. +fn exact_keys(d: &Descriptor, keys: &[&str]) -> bool { + d.name.0.len() <= 1024 && d.items.len() == keys.len() && keys.iter().all(|key| d.items.iter().filter(|(id, _)| id.is(key)).count() == 1) +} + +fn coordinate(value: f64) -> bool { + value.abs() <= f64::from(WARP_REACH) +} + +fn rect_valid([left, top, right, bottom]: [f64; 4]) -> bool { + [left, top, right, bottom].into_iter().all(coordinate) && left < right && top < bottom +} + +fn reference_rect(d: &Descriptor) -> Option<[f64; 4]> { + let r = get_obj(d, "referenceRect")?; + if !r.class_id.is("Rctn") || !exact_keys(r, &["Top ", "Left", "Btom", "Rght"]) { + return None; + } + let number = |key| match r.get(key)? { + D::UnitFloat { unit: [b'#', b'P', b'x', b'l'], value } => Some(*value), + _ => None, + }; + let r = [number("Left")?, number("Top ")?, number("Rght")?, number("Btom")?]; + rect_valid(r).then_some(r) +} + +fn objects<'a>(d: &'a Descriptor, key: &str, class: &str, keys: &[&str], max: usize) -> Option<&'a [D]> { + let D::List(items) = d.get(key)? else { return None }; + (!items.is_empty() && items.len() <= max && items.iter().all(|item| matches!(item, D::Descriptor(d) if d.class_id.is(class) && exact_keys(d, keys)))) + .then_some(items) +} + +/// Each recorded index must link exactly the corners the native command would link. Edges +/// shared by two faces must have opposite winding, since the native map has one neighbour per edge. +fn same_topology(planes: &[Plane], indices: &[[usize; 4]], vertices: usize) -> Option<()> { + let at = |plane: usize, corner: usize| indices.get(plane)?.get(corner); + let mut linked = BTreeSet::new(); + for group in linked_corners(planes) { + let &(plane, corner) = group.first()?; + let index = at(plane, corner)?; + if !linked.insert(*index) || !group.iter().all(|&(p, c)| at(p, c) == Some(index)) { + return None; + } + } + let mut edges = BTreeSet::new(); + let distinct = indices.iter().all(|&[a, b, c, d]| [(a, b), (b, c), (c, d), (d, a)].into_iter().all(|edge| edges.insert(edge))); + (linked.len() == vertices && distinct).then_some(()) +} + +/// Decodes the recorded target and its document-space planes, retaining the reference rectangle +/// for export. Unmodelled references and geometry stay as kept steps. +fn parameters(d: &Descriptor) -> Option { + if !(d.class_id.is(EVENT) || d.class_id.is("null")) || !exact_keys(d, &["null", "Md ", "referenceRect", "vertices", "warpedVertices", "quads"]) { + return None; + } + if !matches!(d.get("Md ")?, D::Enumerated { type_id, value } if type_id.is("perspectiveWarpMode") && value.is("warp")) { + return None; + } + let target = get_ref(d, "null")?; + if target.len() != 1 || ref_class(target).as_deref() != Some("Lyr") { + return None; + } + match target.first()? { + ReferenceItem::Enumerated { type_id, value, .. } if type_id.is("Ordn") && value.is("Trgt") => {} + ReferenceItem::Name { name, .. } if name.0.len() <= 1024 && String::from_utf16(&name.0).is_ok() && !name.to_string_lossy().is_empty() => {} + ReferenceItem::Property { key, .. } if key.is("Bckg") => {} + _ => return None, + } + let mut p = layer_target(target)?; + let rect = reference_rect(d)?; + let src = objects(d, "vertices", "Pnt ", &["Hrzn", "Vrtc"], 4 * MAX_PLANES)?; + objects(d, "warpedVertices", "Pnt ", &["Hrzn", "Vrtc"], 4 * MAX_PLANES)?; + objects(d, "quads", "perspectiveWarpQuad", &["indices"], MAX_PLANES)?; + let (planes, indices) = perspective_warp_indexed_geometry(d)?; + if !planes.iter().all(|p| p.src.iter().chain(&p.dst).flatten().copied().all(coordinate) && convex_quad(&p.src) && convex_quad(&p.dst)) { + return None; + } + same_topology(&planes, &indices, src.len())?; + p.insert("planes".into(), json!(planes)); + p.insert("target".into(), json!("pixels")); + p.insert(RECT.into(), json!(rect)); + Some(Value::Object(p)) +} + +/// Keep the exact recorded descriptor after decoding its executable settings. +pub(super) fn from(d: &Descriptor) -> Mapped { + let mapped = || { + let mut p = parameters(d)?; + let bytes = d.to_bytes(); + if bytes.len() > MAX_DESCRIPTOR_BYTES { + return None; + } + p[SOURCE] = json!(crate::paint::tile::b64_encode(&bytes)); + Some(p) + }; + mapped().map_or(Mapped::Unsupported { harmless: false }, |p| step(PERSPECTIVE, p)) +} + +/// Emits the measured field order when the caller supplies the original reference rectangle. +fn canonical(p: &Value) -> Option { + let [left, top, right, bottom] = serde_json::from_value(p.get(RECT)?.clone()).ok()?; + if !rect_valid([left, top, right, bottom]) { + return None; + } + let planes = p.get("planes")?.as_array().filter(|planes| (1..=MAX_PLANES).contains(&planes.len()))?; + let planes: Vec = serde_json::from_value(Value::Array(planes.clone())).ok()?; + let rect = desc("Rctn").with("Top ", px(top)).with("Left", px(left)).with("Btom", px(bottom)).with("Rght", px(right)); + let (src, dst, quads) = perspective_warp_geometry(&planes); + Some( + desc(EVENT) + .with("null", layer_ref(p)?) + .with("Md ", enm("perspectiveWarpMode", "warp")) + .with("referenceRect", D::Descriptor(rect)) + .with("vertices", src) + .with("warpedVertices", dst) + .with("quads", quads), + ) +} + +/// Reuses source bytes only while they still describe the same target, rectangle and planes. +/// A changed recorded mesh cannot silently replace its indexed topology. +pub(super) fn to(_: &str, p: &Value) -> Option { + if !pixel_target(p) || !p.as_object()?.keys().all(|k| ["layer", "planes", "target", "interpolation", RECT, SOURCE].contains(&k.as_str())) { + return None; + } + if p.get("interpolation").is_some_and(|v| v.as_str() != Some("bicubic")) { + return None; + } + let descriptor = if let Some(source) = p.get(SOURCE) { + let text = source.as_str().filter(|v| v.len() <= MAX_DESCRIPTOR_BYTES * 2)?; + let bytes = crate::paint::tile::b64_decode(text)?; + if bytes.len() > MAX_DESCRIPTOR_BYTES { + return None; + } + Descriptor::from_bytes(&bytes).ok()? + } else { + canonical(p)? + }; + let mut expected = parameters(&descriptor)?; + let mut actual = p.clone(); + let m = actual.as_object_mut()?; + m.remove(SOURCE); + m.remove("interpolation"); + if m.get("layer").is_some_and(Value::is_null) { + m.remove("layer"); + } + m.insert("target".into(), json!("pixels")); + normalise(&mut actual); + normalise(&mut expected); + (actual == expected).then_some(descriptor) +} diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index b7c3764346..65708cd5dc 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -658,6 +658,11 @@ fn settings_at_the_value_the_event_plays_still_export() { /// Each mapped command retains its parameters through its corresponding ATN descriptor. fn every_mapped_command_exports_and_imports_back() { let cases: Vec<(&str, Value)> = vec![ + ( + "edit.perspectiveWarp", + json!({"planes":[{"src":[[4,4],[16,4],[16,20],[4,20]],"dst":[[5,5],[17,4],[18,20],[4,19]]}], + "target":"pixels","__atnPerspectiveWarpRect":[0,0,32,24]}), + ), ( "paint.gradient", json!({"from":[1,1],"to":[6,2],"style":"linear","method":"classic","smoothness":100, @@ -1080,6 +1085,9 @@ fn every_mapped_command_exports_and_imports_back() { // Executable values match; independent public tests verify the source carrier. back.as_object_mut().unwrap().remove("__atnClassicGradient"); } + if *id == "edit.perspectiveWarp" { + back.as_object_mut().unwrap().remove("__atnPerspectiveWarp"); + } normalise(&mut back); if *id == "actions.play" || *id == "actions.conditional" { back["set"] = json!("S"); diff --git a/crates/engine/tests/it/atn_perspective_warp.rs b/crates/engine/tests/it/atn_perspective_warp.rs new file mode 100644 index 0000000000..2967285842 --- /dev/null +++ b/crates/engine/tests/it/atn_perspective_warp.rs @@ -0,0 +1,202 @@ +//! The measured Perspective Warp descriptor shape through ATN conversion and action playback. + +use photocraft_doc::{LayerContent, LayerId}; +use photocraft_engine::{Session, actions_cmds::Action, atn_cmds}; +use photocraft_geom::Rect; +use photocraft_psd::{ + atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}, + descriptor::{Class, Descriptor, Id, ReferenceItem, UnicodeString, Value as D}, +}; +use serde_json::{Value, json}; + +const EVENT: &str = "perspectiveWarpTransform"; +const COMMAND: &str = "edit.perspectiveWarp"; + +fn px(value: f64) -> D { + D::UnitFloat { unit: *b"#Pxl", value } +} + +fn points(points: &[[f64; 2]]) -> D { + D::List(points.iter().map(|&[x, y]| D::Descriptor(Descriptor::new("Pnt ").with("Hrzn", px(x)).with("Vrtc", px(y)))).collect()) +} + +fn quad(indices: [i32; 4]) -> D { + D::Descriptor(Descriptor::new("perspectiveWarpQuad").with("indices", D::List(indices.into_iter().map(D::Integer).collect()))) +} + +/// Two planes sharing a seam. Vertices appear out of corner order to distinguish exact export. +fn fixture(name: Option<&str>) -> Descriptor { + let class = Class { class_id: Id::new("Lyr "), name: UnicodeString::new_nul("") }; + let target = match name { + Some(name) => ReferenceItem::Name { class, name: UnicodeString::new_nul(name) }, + None => ReferenceItem::Enumerated { class, type_id: Id::new("Ordn"), value: Id::new("Trgt") }, + }; + let rect = Descriptor::new("Rctn").with("Top ", px(0.0)).with("Left", px(0.0)).with("Btom", px(24.0)).with("Rght", px(32.0)); + Descriptor::new(EVENT) + .with("null", D::Reference(vec![target])) + .with("Md ", D::Enumerated { type_id: Id::new("perspectiveWarpMode"), value: Id::new("warp") }) + .with("referenceRect", D::Descriptor(rect)) + .with("vertices", points(&[[16.0, 20.0], [4.0, 4.0], [28.0, 4.0], [4.0, 20.0], [16.0, 4.0], [28.0, 20.0]])) + .with("warpedVertices", points(&[[17.0, 20.0], [5.5, 5.0], [27.0, 6.0], [4.0, 19.0], [18.0, 4.0], [26.0, 17.0]])) + .with("quads", D::List(vec![quad([1, 4, 0, 3]), quad([4, 2, 5, 0])])) +} + +fn imported(d: Descriptor, with_dialog: bool, enabled: bool) -> atn_cmds::Imported { + let item = + AtnItem { event: AtnEvent::name(EVENT), dictionary: b"Perspective Warp".to_vec(), descriptor: Some(d), with_dialog, enabled, ..Default::default() }; + let file = AtnFile { + name: UnicodeString::new_nul("Set"), + actions: vec![AtnAction { name: UnicodeString::new_nul("Warp"), items: vec![item], ..Default::default() }], + ..Default::default() + }; + atn_cmds::import(&atn::write(&file).unwrap()).unwrap() +} + +fn saved(action: &Action) -> AtnItem { + let (bytes, skipped) = atn_cmds::export("Set", &[action], &[], false).unwrap(); + assert!(skipped.is_empty()); + atn::parse(&bytes).unwrap().actions[0].items[0].clone() +} + +fn planes() -> Value { + json!([ + {"src":[[4,4],[16,4],[16,20],[4,20]],"dst":[[5.5,5],[18,4],[17,20],[4,19]]}, + {"src":[[16,4],[28,4],[28,20],[16,20]],"dst":[[18,4],[27,6],[26,17],[17,20]]} + ]) +} + +fn value_mut<'a>(d: &'a mut Descriptor, key: &str) -> &'a mut D { + &mut d.items.iter_mut().find(|(id, _)| id.is(key)).unwrap().1 +} + +/// Exact export preserves the original indexed mesh, target, rectangle and step flags. +#[test] +fn descriptor_round_trip_preserves_shared_indices_and_flags() { + for name in [None, Some("Façade")] { + let d = fixture(name); + let loaded = imported(d.clone(), true, false); + assert!(loaded.unsupported.is_empty()); + let action = &loaded.actions[0]; + assert_eq!(action.steps[0].0, COMMAND); + let params = &action.steps[0].1; + assert_eq!(params["planes"], planes()); + assert_eq!(params["layer"].as_str(), name); + assert_eq!(params["target"], "pixels"); + assert_eq!(params["__atnPerspectiveWarpRect"], json!([0, 0, 32, 24])); + let item = saved(action); + assert_eq!(item.event.id(), EVENT); + assert_eq!(item.descriptor.unwrap().to_bytes(), d.to_bytes()); + assert!(item.with_dialog); + assert!(!item.enabled); + } +} + +/// Unsupported targets, units, modes and geometry retain the original bytes as kept steps. +#[test] +fn unsupported_recordings_are_kept_without_partial_mapping() { + let d = fixture(None); + let mut layout = d.clone(); + *value_mut(&mut layout, "Md ") = D::Enumerated { type_id: Id::new("perspectiveWarpMode"), value: Id::new("layout") }; + let mut wrong_target = d.clone(); + *value_mut(&mut wrong_target, "null") = D::Reference(vec![ReferenceItem::Class(Class { class_id: Id::new("Chnl"), name: UnicodeString::new_nul("") })]); + let mut bad_index = d.clone(); + *value_mut(&mut bad_index, "quads") = D::List(vec![quad([1, 4, 99, 3])]); + let mut wrong_units = d.clone(); + let D::Descriptor(rect) = value_mut(&mut wrong_units, "referenceRect") else { panic!("reference rectangle") }; + *value_mut(rect, "Rght") = D::UnitFloat { unit: *b"#Prc", value: 32.0 }; + let mut incompatible_topology = d.clone(); + for key in ["vertices", "warpedVertices"] { + let D::List(points) = value_mut(&mut incompatible_topology, key) else { panic!("vertex list") }; + points.push(points[4].clone()); + } + *value_mut(&mut incompatible_topology, "quads") = D::List(vec![quad([1, 4, 0, 3]), quad([6, 2, 5, 0])]); + let mut duplicate = d.clone(); + duplicate.items.push((Id::new("quads"), d.get("quads").unwrap().clone())); + for descriptor in [layout, wrong_target, bad_index, wrong_units, incompatible_topology, duplicate] { + let loaded = imported(descriptor.clone(), false, true); + assert_eq!(loaded.unsupported.len(), 1, "{descriptor:?}"); + assert_eq!(loaded.actions[0].steps[0].0, "actions.photoshopStep"); + assert_eq!(saved(&loaded.actions[0]).descriptor.unwrap().to_bytes(), descriptor.to_bytes()); + } +} + +/// Native export needs a reference rectangle. A stale recorded topology must not be substituted. +#[test] +fn native_export_requires_known_rectangle_and_rejects_stale_source() { + let mut action = Action::new("Warp", vec![(COMMAND.into(), json!({"planes": planes()}))]); + assert!(atn_cmds::export("Set", &[&action], &[], false).is_err()); + action.steps[0].1["__atnPerspectiveWarpRect"] = json!([0, 0, 32, 24]); + let d = saved(&action).descriptor.unwrap(); + let keys: Vec<_> = d.items.iter().map(|(id, _)| id.as_bytes()).collect(); + assert_eq!(keys, [b"null".as_slice(), b"Md ", b"referenceRect", b"vertices", b"warpedVertices", b"quads"]); + let mut recorded = imported(d, false, true).actions.remove(0); + recorded.steps[0].1["planes"][0]["dst"][0][0] = json!(6); + assert!(atn_cmds::export("Set", &[&recorded], &[], false).is_err()); + action.steps[0].1["interpolation"] = json!("nearest"); + assert!(atn_cmds::export("Set", &[&action], &[], false).is_err()); +} + +fn session(depth: u8) -> (Session, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width":32,"height":24,"depth":depth})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("Fixture", |doc, _| { + let layer = doc.layer_mut(id).unwrap(); + layer.name = "Facade".into(); + let surf = layer.surface_mut().unwrap(); + let fmt = surf.format(); + surf.fill_rect(Rect::new(4, 4, 16, 20), &photocraft_raster::from_rgba(&fmt, [0.9, 0.2, 0.1, 1.0])); + surf.fill_rect(Rect::new(16, 4, 28, 20), &photocraft_raster::from_rgba(&fmt, [0.1, 0.2, 0.9, 1.0])); + Ok(()) + }) + .unwrap(); + (s, id) +} + +/// A named raster is warped, while the active decoy stays unchanged. +#[test] +fn action_playback_matches_the_native_raster_warp() { + for depth in [8, 16, 32] { + let (mut actual, id) = session(depth); + let (mut direct, did) = session(depth); + let before = actual.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); + for s in [&mut actual, &mut direct] { + s.execute("layer.new.layer", json!({})).unwrap(); + } + let decoy = actual.active().unwrap().active_layer.unwrap(); + let decoy_before = actual.active().unwrap().doc.layer(decoy).unwrap().clone(); + actual.actions.list.extend(imported(fixture(Some("Facade")), false, true).actions); + actual.execute("actions.play", json!({"action":0})).unwrap(); + direct.execute(COMMAND, json!({"planes":planes(),"layer":"Facade","target":"pixels"})).unwrap(); + let result = actual.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); + assert_ne!(*result, before); + assert_eq!(result, direct.active().unwrap().doc.layer(did).unwrap().surface().unwrap()); + assert_eq!(actual.active().unwrap().doc.layer(decoy), Some(&decoy_before)); + actual.execute("edit.undo", json!({})).unwrap(); + assert_eq!(actual.active().unwrap().doc.layer(id).unwrap().surface(), Some(&before)); + } +} + +/// The same active-layer recording adds a native Smart Filter and keeps PSD export available. +#[test] +fn active_smart_object_playback_matches_the_native_filter() { + let (mut actual, _) = session(8); + let (mut direct, _) = session(8); + for s in [&mut actual, &mut direct] { + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + } + actual.actions.list.extend(imported(fixture(None), false, true).actions); + actual.execute("actions.play", json!({"action":0})).unwrap(); + direct.execute("layer.smartObjects.perspectiveWarp", json!({"planes":planes()})).unwrap(); + let [actual, direct] = [&actual, &direct].map(|s| { + let st = s.active().unwrap(); + let LayerContent::Smart(sm) = &st.doc.layer(st.active_layer.unwrap()).unwrap().content else { panic!("smart object") }; + sm + }); + assert_eq!(actual.cache, direct.cache); + assert_eq!(actual.smart_filters.len(), 1); + assert_eq!(actual.smart_filters[0].command, COMMAND); + assert_eq!(actual.smart_filters[0].params["planes"], planes()); + assert!(photocraft_io::smart_map::item_for_filter(&actual.smart_filters[0]).is_ok()); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c65e58ddca..30f47794ec 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -13,6 +13,7 @@ mod atn_dialog_filters; mod atn_direct_adjustments; mod atn_layer_style; mod atn_newer_events; +mod atn_perspective_warp; mod atn_reference_forms; mod atn_review_regressions; mod atn_ripple_amount; diff --git a/crates/io/src/perspective_warp_map.rs b/crates/io/src/perspective_warp_map.rs index 654de23b32..cb5815bb81 100644 --- a/crates/io/src/perspective_warp_map.rs +++ b/crates/io/src/perspective_warp_map.rs @@ -38,7 +38,7 @@ const FILTER_ID: i32 = 1023; const NAME: &str = "Perspective Warp..."; pub(super) const TEMPLATE_KEY: &str = "__perspectiveWarpPsd"; /// Far more planes than anyone lays out by hand; bounds the corner linking (quadratic). -const MAX_QUADS: usize = 256; +pub const MAX_QUADS: usize = 256; const MAX_VERTICES: usize = 4 * MAX_QUADS; const MAX_TEMPLATE_BYTES: usize = 1 << 20; @@ -74,29 +74,29 @@ fn quads(f: &Descriptor) -> Option> { .map(|q| { let Value::Descriptor(q) = q else { return None }; let Some(Value::List(ix)) = q.get("indices") else { return None }; - let ix: Vec = ix - .iter() - .map(|i| match i { - Value::Integer(i) => usize::try_from(*i).ok(), - _ => None, - }) - .collect::>()?; - ix.try_into().ok() + let [Value::Integer(a), Value::Integer(b), Value::Integer(c), Value::Integer(d)] = ix.as_slice() else { return None }; + Some([usize::try_from(*a).ok()?, usize::try_from(*b).ok()?, usize::try_from(*c).ok()?, usize::try_from(*d).ok()?]) }) .collect() } -/// The planes a `perspectiveWarpTransform` descriptor describes; `None` when it is inconsistent. -fn planes_of(f: &Descriptor) -> Option> { +/// Reads the document-space planes and original corner indices from Perspective Warp geometry. +/// Callers validate the enclosing descriptor and target according to the file format. +pub fn indexed_geometry(f: &Descriptor) -> Option<(Vec, Vec<[usize; 4]>)> { let (src, dst) = (points(f, "vertices")?, points(f, "warpedVertices")?); if src.len() != dst.len() { return None; } let corners = |list: &[[f64; 2]], q: &[usize; 4]| -> Option<[[f64; 2]; 4]> { Some([*list.get(q[0])?, *list.get(q[1])?, *list.get(q[2])?, *list.get(q[3])?]) }; - let planes: Vec = quads(f)?.iter().map(|q| Some(Plane { src: corners(&src, q)?, dst: corners(&dst, q)? })).collect::>()?; + let indices = quads(f)?; + let planes: Vec = indices.iter().map(|q| Some(Plane { src: corners(&src, q)?, dst: corners(&dst, q)? })).collect::>()?; PerspectiveMap::new(&planes)?; - Some(planes) + Some((planes, indices)) +} + +fn planes_of(f: &Descriptor) -> Option> { + indexed_geometry(f).map(|(planes, _)| planes) } /// `layer.smartObjects.perspectiveWarp` params for a Perspective Warp item. @@ -137,7 +137,8 @@ fn template(params: &J) -> Result, String> { /// The planes to write: as rendered, so a `straighten` is baked in. fn export_planes(params: &J) -> Result, String> { let object = params.as_object().ok_or("Perspective Warp parameters must be an object")?; - if let Some(k) = object.keys().find(|k| !super::is_meta(k) && !["planes", "straighten", "interpolation"].contains(&k.as_str())) { + let supported = |k: &str| super::is_meta(k) || ["planes", "straighten", "interpolation"].contains(&k) || (k == "target" && params["target"] == "pixels"); + if let Some(k) = object.keys().find(|k| !supported(k)) { return Err(format!("Perspective Warp setting `{k}` has no PSD equivalent")); } let mut planes: Vec = @@ -161,7 +162,7 @@ fn pnt(p: [f64; 2]) -> Value { /// `vertices`, `warpedVertices` and `quads` for `planes`; a corner shared by several planes (same /// layout and warped position) is written once. -fn geometry(planes: &[Plane]) -> (Value, Value, Value) { +pub fn geometry(planes: &[Plane]) -> (Value, Value, Value) { let mut corners: Vec<([f64; 2], [f64; 2])> = Vec::new(); let mut quads = Vec::with_capacity(planes.len()); for p in planes { diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs index cacce2b7cb..3b19606c94 100644 --- a/crates/io/src/smart_map.rs +++ b/crates/io/src/smart_map.rs @@ -51,6 +51,9 @@ mod hue_sat; mod perspective_warp; pub use displace::{embed_map as displace_embed_map, embedded_map as displace_embedded_map, without_map as displace_without_map}; +pub use perspective_warp::{ + MAX_QUADS as MAX_PERSPECTIVE_WARP_PLANES, geometry as perspective_warp_geometry, indexed_geometry as perspective_warp_indexed_geometry, +}; mod export; mod import; diff --git a/docs/atn.md b/docs/atn.md index 0e72430eeb..7a3e892562 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -90,6 +90,7 @@ row; the action still adds only one Undo entry. | `Btch` | batch | Batch (supported folder and naming forms) | `file.automate.batch` | | (string ID only) | shapeBlur | Shape Blur (custom shape by installed ID) | `filter.blur.shapeBlur` | | (string ID only) | cafWorkspace | Content-Aware Fill | `edit.contentAwareFill` | +| (string ID only) | perspectiveWarpTransform | Perspective Warp (indexed layout and warp planes) | `edit.perspectiveWarp` | | `Cntc` | contract | Contract | `select.modify.contract` | | `CnvM` | convertMode | Convert Mode | `image.mode.rgb`, `image.mode.grayscale`, `image.mode.cmyk`, `image.mode.lab`, `image.mode.multichannel`, `image.mode.bits8`, `image.mode.bits16`, `image.mode.bits32`, `image.mode.bitmap` | | (string ID only) | convertToProfile | Convert to Profile | `edit.convertToProfile` | @@ -295,6 +296,24 @@ The separate `CropPhotos0001` helper remains a complete kept Photoshop step. Playback stops at that enabled helper before subsequent duplicate/crop steps can run. This covers the parent event, not complete recordings with generated helpers. +### Perspective Warp recordings + +`perspectiveWarpTransform` maps Layout and Warp to one `edit.perspectiveWarp` +step. It warps a raster layer in place or adds a Perspective Warp Smart Filter to +a Smart Object. The active layer, a named layer or the Background can be the +recorded target. + +The recorded fields are `null` (layer target), `Md ` (`perspectiveWarpMode`: +`warp`), `referenceRect` (pixel rectangle), `vertices`, `warpedVertices` (document +pixel points), and `quads` (four indices per plane). Unchanged steps save the +original descriptor, including its reference rectangle, vertex order and shared +indices. Playback uses the recorded document-pixel coordinates. A native export +requires an explicit reference rectangle and representable planes. + +Unsupported targets, modes, units, degenerate quads and meshes with different +corner sharing stay kept steps. Export refuses a changed recorded mesh if the +stored descriptor no longer describes it. + ### Content-Aware Fill recordings `cafWorkspace` maps Rectangular / Default color adaptation / None rotation with New Layer or @@ -944,7 +963,6 @@ the recorded steps back from the saved Actions panel. Ranges come from the dialo | New Group with a colour | `Usng` (`Clr ` label), `layerSectionStart`, `layerSectionEnd`, top-level `Nm ` | | | Shear (`Shr `) | `ShrP` list of `Pnt ` (`Hrzn`, `Vrtc` doubles), `UndA` (`WrpA` wrap around, `RptE` repeat edge pixels), `ShrS` long, `ShrE` long | The dialog writes whole numbers: `Hrzn` -64..63 (dragging past the grid clamps), `Vrtc` 1..128 with the first point at 1 and the last at 128; dragging a point out of the grid deletes it. `ShrS` is 0 and `ShrE` the last point's index (count - 1). Script runs take any value unclamped and crashed on far-off `ShrE`/`ShrS` or a first `Vrtc` below 1. | | Gradient tool, default mode | two steps: Make (`null` = class `contentLayer`, `Usng` = `Type` gradient layer object) then Set (`null` = `contentLayer` target, `T ` = the same object plus `Algn` false) | The object: `Dthr`, `gradientsInterpolationMethod`, `Angl` angle, `Type`, `Scl ` percent, `Ofst` (`Hrzn`, `Vrtc` percent), `Grad`. The new tool makes a gradient fill layer; Make holds the first click, Set the finished drag. | -| Perspective Warp (`perspectiveWarpTransform`) | `null` = layer target, `Md ` (`perspectiveWarpMode`: `warp`), `referenceRect` rectangle in pixels, `vertices` list of points in pixels (the layout quad), `warpedVertices` (the same points after warping), `quads` list of `indices` (4 vertex indexes each) | Layout and warp are one step. | | Print (`print`) then Print One Copy (`printOneCopy`) | `print`: `null` = reference `printOutput` property of the target document; `printOutput` (`PstS`, `Inte`, `printSixteenBit`, `printerName` text, `printProofSetup`), `printViewProofSetup`, `printOutputOptions` (caption, marks, `Bckg` colour, `BrdT`, `Bld `, `Rslt`, `vectorData`, `PgPs`, `Left`, `Top `, `Scl `, crop rectangle), `osSpecificPrintInfo` raw data, `Cptn` text. `printOneCopy` has no keys. | Pressing Print in the dialog records both steps. | | Create Droplet (`CrtD`) | `In ` alias: the droplet file; `Fldr` bool (include subfolders); `Usng` reference to the action; then the Batch keys below (destination, file naming, error log) when set | The same settings as Batch, with the droplet file instead of a source folder. | | Sky Replacement (`skyReplacement`) | `shiftEdge` double, `borderSmoothness` long (fade edge, default 50), `Brgh` long, `temperature` long, `harmonizationOpacity` long (35), `foregroundLightingOpacity` long, `lightingMode` blend mode (`Mltp`), `edgeLightingOpacity` long (70), `skyReplacementOutput` (`skyReplacementOutputToNewSheets` new layers, …), `Idnt` text (the sky preset's id), `Nm ` text (its name), `File` alias (the sky image) | Scale and Flip are **not** in the step: with 150 % and Flip on, the returned keys were the same. `foregroundLightingOpacity` is computed from the sky (44 and 29 for two skies). Without a chosen sky the dialog returns no keys. |