mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
feat(engine): reset a smart object's transform
Layer > Smart Objects > Reset Transform (#11662): the placement goes back to 100 % of the current contents' own box, with rotation, skew, Distort and Perspective cleared and the object left centred where it sits, in one history step. Photoshop resets the transform and not the warp, so the smart object's Warp (kept in source space) and its smart filter stack stay as they are. The map is applied through the Free Transform path, so a linked layer or vector mask and the Smart Filter mask follow the placement back and the object re-renders losslessly from its source. transform_by_map is the projective sibling of transform_by: the step from a Distorted placement to an axis-aligned one is not affine. The exact reset map is pinned onto the placement afterwards, because new * old^-1 * old only lands on it to float noise and would otherwise keep a nearly affine perspective in the document.
This commit is contained in:
1 parent
c101cbfb7e
commit
e24efcf762
4 files changed
+152
-6
No files matched your search
@@ -193,7 +193,7 @@ pub(crate) use filters::{add_smart_filter, add_smart_filter_in, filter_mask_pain
|
||||
use filters::{blending_options, delete_filter, edit_filters, move_filter, set_filter_params, set_filter_visible, smart, transfer_filters};
|
||||
pub(crate) use placing::detach_psd;
|
||||
pub(crate) use placing::{affine_homography, set_placement, shift_smart, transform_placement};
|
||||
use placing::{convert, shift_layer, via_copy};
|
||||
use placing::{convert, reset_transform, shift_layer, via_copy};
|
||||
pub use placing::{layer_to_smart, layers_to_smart, placement};
|
||||
#[cfg(test)]
|
||||
pub(crate) use rendering::DISPLAY_NATIVE_HASH_BYTES;
|
||||
@@ -239,6 +239,14 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_smart,
|
||||
edit_contents
|
||||
),
|
||||
spec!(
|
||||
"layer.smartObjects.resetTransform",
|
||||
"Reset Transform",
|
||||
SO,
|
||||
r##"{"layer":id?} (the placement returns to 100 % of the current contents' own size, rotation, skew, Distort and Perspective cleared, centred where the object is; the Warp and the smart filters stay; one undo step)"##,
|
||||
has_smart,
|
||||
reset_transform
|
||||
),
|
||||
spec!("layer.smartObjects.saveContents", "Save Contents", &[], "{} (in an Edit Contents document)", is_smart_child, |s, _| {
|
||||
let i = s.active_index().ok_or(EngineError::NoDocument)?;
|
||||
Ok(json!({"updated": commit_child(s, i)?}))
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use super::source::{SourceImage, buffer_to_surface, cache_key, cache_put, source_bytes};
|
||||
use super::{
|
||||
Affine, Arc, BlendMode, Document, EngineError, Homography, Layer, LayerContent, LayerId, PLACED_KEYS, Rect, Result, Session, Size, SmartContentsId,
|
||||
SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, translate_surface,
|
||||
SmartObject, SmartSource, Surface, Value, encode_source, json, layer_param, other, source_box, translate_surface,
|
||||
};
|
||||
use photocraft_algo::transform::Interp;
|
||||
|
||||
/// Rounds float noise off a composed transform (scale 0.1 then 10 should be exactly 1), so
|
||||
/// repeated transforms land back on exact, lossless placements.
|
||||
@@ -57,6 +58,40 @@ pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Layer ▸ Smart Objects ▸ Reset Transform, and the same item of the Layers panel menu (#11662):
|
||||
/// the placement goes back to 100 % of the current contents' own size with rotation, skew, Distort
|
||||
/// and Perspective cleared, centred where the object sits now. Photoshop resets the *transform*,
|
||||
/// so the Warp (kept in source space) and the smart filters stay as they are.
|
||||
pub(super) fn reset_transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = layer_param(s, p)?;
|
||||
let st = s.active().ok_or(EngineError::NoDocument)?;
|
||||
let LayerContent::Smart(sm) = &st.doc.layer(id).ok_or(EngineError::NoLayer(id))?.content else {
|
||||
return Err(other("the layer is not a smart object"));
|
||||
};
|
||||
// The contents' own box in source pixels: 100 % maps it one-to-one onto the document.
|
||||
let [x0, y0, x1, y1] = source_box(&st.doc, sm).ok_or_else(|| other("the smart object's contents are unavailable"))?;
|
||||
let (cx, cy) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
|
||||
let old = placement(sm);
|
||||
let (dx, dy) = old.apply(cx, cy);
|
||||
let to = Affine { m: [1.0, 0.0, 0.0, 1.0, dx - cx, dy - cy] };
|
||||
let new = affine_homography(&to);
|
||||
// Everything the accumulated transform moved the pixels by, so the linked masks and the Smart
|
||||
// Filter mask follow the placement back as they do under Free Transform.
|
||||
let rel = new.mul(&old.inverse().ok_or_else(|| other("the smart object has a degenerate transform"))?);
|
||||
if ![dx, dy, cx, cy].iter().all(|v| v.is_finite()) || !rel.0.iter().all(|v| v.is_finite()) {
|
||||
return Err(other("the smart object's placement is not a usable transform"));
|
||||
}
|
||||
s.edit("Reset Transform", |doc, _| {
|
||||
crate::transform_cmds::transform_by_map(doc, id, &rel, None, Interp::Bicubic)?;
|
||||
// `new ∘ old⁻¹ ∘ old` only lands on the reset map to within float noise, and could leave a
|
||||
// Distort placement behind as a nearly affine one: store the exact map.
|
||||
if let Some(LayerContent::Smart(sm)) = doc.layer_mut(id).map(|l| &mut l.content) {
|
||||
set_placement(sm, new);
|
||||
}
|
||||
Ok(json!({"layer": id.0, "transform": to.m}))
|
||||
})
|
||||
}
|
||||
|
||||
/// Forget PSD placed-layer data that no longer describes the smart object (its source changed):
|
||||
/// PSD export then writes fresh placed-layer blocks and embeds the new source.
|
||||
pub(crate) fn detach_psd(l: &mut Layer) {
|
||||
|
||||
@@ -503,6 +503,103 @@ fn transforms_re_render_from_source_losslessly() {
|
||||
assert!(active_smart(&smart).perspective.is_some());
|
||||
}
|
||||
|
||||
/// The contents' box centre in document pixels under `sm`'s placement: what Reset Transform keeps.
|
||||
fn placed_centre(s: &Session, sm: &SmartObject) -> (f64, f64) {
|
||||
let b = crate::smart_cmds::source_box(&s.active().unwrap().doc, sm).unwrap();
|
||||
placement(sm).apply((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0)
|
||||
}
|
||||
|
||||
/// Layer ▸ Smart Objects ▸ Reset Transform (#11662): 100 % of the contents' own size, no rotation,
|
||||
/// skew, Distort or Perspective, and the object stays centred where it is.
|
||||
#[test]
|
||||
fn reset_transform_restores_100_percent_in_place() {
|
||||
let mut s = session(8);
|
||||
paint(&mut s);
|
||||
let id = convert(&mut s);
|
||||
let fresh = active_smart(&s).cache.unwrap().content_bounds();
|
||||
s.execute("edit.transform", json!({"layer": id, "scaleX": 200, "scaleY": 200, "rotate": 30})).unwrap();
|
||||
s.execute("layer.translate", json!({"dx": 7, "dy": 4})).unwrap();
|
||||
let sm = active_smart(&s);
|
||||
assert!(sm.transform.m[0].hypot(sm.transform.m[1]) > 1.5, "the object really is scaled up");
|
||||
assert_ne!(sm.transform.m[1], 0.0, "…and rotated");
|
||||
let centre = placed_centre(&s, &sm);
|
||||
s.execute("layer.smartObjects.resetTransform", json!({})).unwrap();
|
||||
let after = active_smart(&s);
|
||||
assert!(after.perspective.is_none(), "no projective placement left");
|
||||
assert_eq!(&after.transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "100 %, square, neither rotated nor skewed");
|
||||
let now = placed_centre(&s, &after);
|
||||
assert!((now.0 - centre.0).abs() < 1e-6 && (now.1 - centre.1).abs() < 1e-6, "centred where it was: {now:?} vs {centre:?}");
|
||||
let r = after.cache.unwrap().content_bounds();
|
||||
assert_eq!((r.width(), r.height()), (fresh.width(), fresh.height()), "the contents at their own size");
|
||||
// Re-rendered from the source rather than resampled from the rotated pixels: the reset object
|
||||
// is exactly the converted layer moved by the same whole-pixel distance.
|
||||
let mut control = session(8);
|
||||
paint(&mut control);
|
||||
convert(&mut control);
|
||||
control.execute("layer.translate", json!({"dx": 7, "dy": 4})).unwrap();
|
||||
let (got, want) = (flat(&s), flat(&control));
|
||||
assert!(max_diff(&got, &want) < 1e-6, "lossless reset (mean {})", mean_diff(&got, &want));
|
||||
// Already reset: the second run changes nothing.
|
||||
s.execute("layer.smartObjects.resetTransform", json!({})).unwrap();
|
||||
assert_eq!(active_smart(&s).transform, after.transform, "idempotent");
|
||||
}
|
||||
|
||||
/// Reset Transform resets the *transform*: the Warp and the smart filter stack survive it (#11662).
|
||||
#[test]
|
||||
fn reset_transform_keeps_the_warp_and_the_smart_filters() {
|
||||
let mut s = session(8);
|
||||
paint(&mut s);
|
||||
let id = convert(&mut s);
|
||||
s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap();
|
||||
s.execute("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap();
|
||||
let before = active_smart(&s);
|
||||
let r = before.cache.unwrap().content_bounds();
|
||||
let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1));
|
||||
s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": [[x0, y0], [x1, y0], [x1 - 12.0, y1 - 8.0], [x0, y1]]})).unwrap();
|
||||
assert!(active_smart(&s).perspective.is_some(), "Distort keeps a projective placement");
|
||||
let centre = placed_centre(&s, &active_smart(&s));
|
||||
s.execute("layer.smartObjects.resetTransform", json!({})).unwrap();
|
||||
let after = active_smart(&s);
|
||||
assert_eq!(after.warp, before.warp, "the Warp is not part of the transform");
|
||||
assert_eq!(after.smart_filters.len(), 1, "nor is the smart filter stack");
|
||||
assert!(after.perspective.is_none(), "Distort is cleared");
|
||||
assert_eq!(&after.transform.m[..4], &[1.0, 0.0, 0.0, 1.0]);
|
||||
let now = placed_centre(&s, &after);
|
||||
assert!((now.0 - centre.0).abs() < 1e-6 && (now.1 - centre.1).abs() < 1e-6, "centred where it was: {now:?} vs {centre:?}");
|
||||
}
|
||||
|
||||
/// Enabled for a smart object only, and one undo step back (#11662).
|
||||
#[test]
|
||||
fn reset_transform_needs_a_smart_object_and_undoes_in_one_step() {
|
||||
let mut empty = Session::new();
|
||||
assert!(!empty.is_enabled("layer.smartObjects.resetTransform"), "no document");
|
||||
assert!(empty.execute("layer.smartObjects.resetTransform", json!({})).is_err());
|
||||
let mut s = session(8);
|
||||
paint(&mut s);
|
||||
let plain = s.active().unwrap().active_layer.unwrap().0;
|
||||
assert!(!s.is_enabled("layer.smartObjects.resetTransform"), "a pixel layer has no placement to reset");
|
||||
assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": plain})).is_err());
|
||||
let id = convert(&mut s);
|
||||
assert!(s.is_enabled("layer.smartObjects.resetTransform"));
|
||||
s.execute("edit.transform", json!({"layer": id, "matrix": [2, 0, 0, 2, 0, 0]})).unwrap();
|
||||
let scaled = active_smart(&s);
|
||||
s.execute("layer.smartObjects.resetTransform", json!({})).unwrap();
|
||||
assert_eq!(&active_smart(&s).transform.m[..4], &[1.0, 0.0, 0.0, 1.0]);
|
||||
s.execute("edit.undo", json!({})).unwrap();
|
||||
let back = active_smart(&s);
|
||||
assert_eq!(back.transform, scaled.transform, "one history step back to the scaled placement");
|
||||
s.execute("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(&active_smart(&s).transform.m[..4], &[1.0, 0.0, 0.0, 1.0], "…and forward again");
|
||||
// Hostile targets are refused, never acted on.
|
||||
assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": u64::MAX})).is_err());
|
||||
assert!(s.execute("layer.smartObjects.resetTransform", json!({"layer": "nope"})).is_err());
|
||||
// A locked layer can't be moved.
|
||||
s.execute("layer.lockLayers", json!({"layer": id, "position": true})).unwrap();
|
||||
let locked = active_smart(&s).transform;
|
||||
assert!(s.execute("layer.smartObjects.resetTransform", json!({})).is_err());
|
||||
assert_eq!(active_smart(&s).transform, locked, "the placement is left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_follow_transforms() {
|
||||
let mut s = session(16);
|
||||
@@ -712,6 +809,7 @@ fn commands_are_registered_with_catalog_ids() {
|
||||
"layer.smartObjects.newSmartObjectViaCopy",
|
||||
"layer.smartObjects.rasterize",
|
||||
"layer.smartObjects.editContents",
|
||||
"layer.smartObjects.resetTransform",
|
||||
"layer.smartObjects.replaceContents",
|
||||
"layer.smartObjects.exportContents",
|
||||
"layer.smartObjects.updateModifiedContent",
|
||||
|
||||
@@ -625,18 +625,23 @@ pub fn split_selected(surf: &Surface, sel: &Surface) -> Result<(Surface, Surface
|
||||
/// masks and Smart Filter mask follow, and type, shapes and smart objects re-render. The document
|
||||
/// selection is left alone.
|
||||
pub(crate) fn transform_by(doc: &mut Document, id: LayerId, affine: Affine, interp: Interp) -> Result<()> {
|
||||
let h = crate::smart_cmds::affine_homography(&affine);
|
||||
transform_by_map(doc, id, &crate::smart_cmds::affine_homography(&affine), Some(affine), interp)
|
||||
}
|
||||
|
||||
/// [`transform_by`] with the map already built, and `affine` only when it is affine (Distort and
|
||||
/// Perspective results aren't: their smart object keeps the full projective placement).
|
||||
pub(crate) fn transform_by_map(doc: &mut Document, id: LayerId, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {
|
||||
let group = group_locks(doc, id);
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
// Price the smart object caches before they are taken: the fallback warp below isn't budgeted.
|
||||
check_layer_budget(None, l, &h)?;
|
||||
check_layer_budget(None, l, h)?;
|
||||
let taken = crate::smart_cmds::take_caches(std::slice::from_mut(l));
|
||||
apply_transform(None, group, l, &h, Some(affine), interp, &Interrupt::NONE)?;
|
||||
apply_transform(None, group, l, h, affine, interp, &Interrupt::NONE)?;
|
||||
let snapshot = doc.clone();
|
||||
if let Some(l) = doc.layer_mut(id) {
|
||||
refresh_text(&snapshot, l);
|
||||
}
|
||||
crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), &h, interp))?;
|
||||
crate::smart_cmds::restore_unrendered(doc, taken, |c| warp_surface(c, c.content_bounds(), h, interp))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user