Free Transform: Perspective Distort and Free Distort put type and symbol instances' corners on the handles

object.distort gave type and symbol instances the warp's affine
approximation at their center, so their corners missed the handles.
They now keep their art and are drawn through the warp, composed after
any projection they had, as type and symbols on the Perspective Grid
are. Corners that would fold the box, cross the warp's horizon or lie
too close together for a perspective map are refused with an error that
names the object.

Images in the art of a symbol drawn through a projection now have their
corners placed by it, and their linked masks are projected with them.
Before, they stayed flat while the rest of the art moved.
This commit is contained in:
dotCooCoo committed 2026-11-28 03:12:46 -08:00
1 parent 0e41019424
commit 5ff876c327
6 files changed
+391 -36

No files matched your search

+38
View File
@@ -1780,6 +1780,44 @@ fn perspective_projects_the_masks_in_a_symbols_art() {
assert_eq!(mask, path, "and so is its mask");
}
/// The images in the art of a symbol instance drawn through a projection have their corners where
/// the projection takes them, beside a path, in a group and in the art of a linked mask, and an
/// image's own linked mask is projected with it.
#[test]
fn a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them() {
let masked = masked_by(white_square(22), image_node(23), true);
let art = Node::group(NodeId(20), vec![Arc::new(image_node(21)), Arc::new(Node::group(NodeId(24), vec![Arc::new(masked)]))]);
// An image with a linked mask of its own, whose path has a linked mask too.
let inner = masked_by(white_square(32), white_square(33), true);
let own = Node::group(NodeId(30), vec![Arc::new(masked_by(image_node(31), inner, true))]);
let at = vectorcraft_doc::PerspectiveAttachment { projection: Some([1.0, 0.2, 3.0, 0.1, 1.0, 2.0, 0.01, 0.02, 1.0]), ..Default::default() };
let h = at.homography().unwrap();
let mut instance = Node::new(NodeId(2), NodeKind::SymbolInstance { symbol: "t".into(), xf: vectorcraft_geom::Affine::IDENTITY });
instance.extras_mut().perspective = Some(Box::new(at.clone()));
let out = crate::reshape::reshape(None, &instance, Some(&own)).unwrap();
let mut masks = vec![];
out.walk(&mut |c| masks.extend(c.image_corners().and(c.extras().mask.as_deref()).map(|m| m.art.clone())));
let [mask] = masks.as_slice() else { panic!("one masked image: {out:?}") };
assert!(mask.path_data() != white_square(32).path_data(), "the image's mask is projected");
let inner = mask.extras().mask.as_deref().map(|m| m.art.path_data().cloned());
assert_eq!(inner, Some(mask.path_data().cloned()), "and so is the mask on that mask's path");
let mut instance = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "s".into(), xf: vectorcraft_geom::Affine::IDENTITY });
instance.extras_mut().perspective = Some(Box::new(at));
let out = crate::reshape::reshape(None, &instance, Some(&art)).unwrap();
let want = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)].map(|(x, y)| h.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
let mut images = vec![];
out.walk(&mut |c| {
images.extend(c.image_corners());
images.extend(c.extras().mask.as_deref().and_then(|m| m.art.image_corners()));
});
assert_eq!(images.len(), 2, "{out:?}");
for q in images {
for (got, want) in q.iter().zip(want) {
assert!(got.distance(want) < 1e-9, "{q:?} against {want:?}");
}
}
}
/// A group with `effect` holding `n` vertical then `n` horizontal bars, 2 wide on a 4-unit
/// pitch, each crossing every bar of the other direction: n² crossings.
fn crossing_bars(n: usize, effect: &str) -> Node {
+51 -1
View File
@@ -1544,11 +1544,40 @@ pub(crate) fn own_effects_art(doc: Option<&Document>, n: &Node) -> Option<Node>
/// follow it. The type and live objects in the art of those masks are outlined and evaluated
/// first ([`outlined_members`], with the symbols of `doc`).
fn project_leaves(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
project_art(art, h, doc, false);
}
/// [`project_leaves`], the linked opacity mask of `art` itself included when `own`.
fn project_art(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>, own: bool) {
project_paths(art, h);
each_linked_mask_mut(art, false, 0, &mut |m| {
each_linked_mask_mut(art, own, 0, &mut |m| {
*m = outlined_mask_art(doc, m);
project_paths(m, h);
project_image_masks(m, h, doc);
});
project_image_masks(art, h, doc);
}
/// The art of the linked opacity masks of the images under `art` (`art` itself, and in groups and
/// layers, as [`project_images`] reaches them) projected through `h` as [`project_leaves`]
/// projects art, the linked mask of that art's own root included, so that each mask stays on the
/// object it masks. Unlinked masks stay where they are.
fn project_image_masks(art: &mut Node, h: &vectorcraft_geom::Homography, doc: Option<&Document>) {
match &mut art.kind {
NodeKind::Image(_) => {
if let Some(m) = art.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|m| m.linked) {
let a = Arc::make_mut(&mut m.art);
*a = outlined_mask_art(doc, a);
project_art(a, h, doc, true);
}
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
for c in children.iter_mut() {
project_image_masks(Arc::make_mut(c), h, doc);
}
}
_ => {}
}
}
/// `art`, the art of an opacity mask, with type and live objects in it outlined and evaluated
@@ -1584,6 +1613,27 @@ fn project_paths(art: &mut Node, h: &vectorcraft_geom::Homography) {
_ => {}
}
});
project_images(art, h);
}
/// Place the corners of every image under `art` (in groups and layers, as [`for_each_leaf`] reaches
/// paths) where the projective map `h` takes them, so that its pixels are drawn in perspective
/// between them ([`Node::set_image_corners`]). An image with a corner that `h` sends past its
/// horizon keeps its place, as the points of a path there do.
fn project_images(n: &mut Node, h: &vectorcraft_geom::Homography) {
match &mut n.kind {
NodeKind::Image(_) => {
if let Some([Some(a), Some(b), Some(c), Some(d)]) = n.image_corners().map(|q| q.map(|p| h.apply(p))) {
let _ = n.set_image_corners([a, b, c, d]);
}
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
for c in children.iter_mut() {
project_images(Arc::make_mut(c), h);
}
}
_ => {}
}
}
/// The visible geometry effects of `n`'s own effect list, in order.
+126 -35
View File
@@ -4,8 +4,9 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use vectorcraft_doc::{Node, NodeKind, OrientedBox, Scaling, SymbolBoxes};
use vectorcraft_geom::{Affine, Homography, Point, Rect, Vec2};
use vectorcraft_tools::distort::project_node;
use super::edit::{outermost, selected_roots};
use super::{
@@ -21,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Free Distort",
[],
None,
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); the corners of a type object's or symbol instance's box go exactly where the warp takes them too, and it stays type or an instance, drawn through the warp after any projection it had (the same errors, naming the object); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
has_doc,
distort
),
@@ -105,6 +106,21 @@ impl Projective {
Point::new((a * u + b * v + c) / w, (d * u + e * v + f) / w)
}
/// Whether the warp is a perspective map rather than an affine one.
fn is_projective(&self) -> bool {
let [.., g, h] = self.m;
g != 0.0 || h != 0.0
}
/// The warp as one page-to-page map, which [`Self::apply`] matches in front of the horizon.
fn homography(&self) -> Homography {
let [a, b, c, d, e, f, g, h] = self.m;
let scale = |len: f64| if len.abs() > 1e-12 { 1.0 / len } else { 0.0 };
let (sx, sy) = (scale(self.src.width()), scale(self.src.height()));
let to_unit = Affine::new([sx, 0.0, 0.0, sy, -self.src.x0 * sx, -self.src.y0 * sy]) * self.pre;
Homography([[a, b, c], [d, e, f], [g, h, 1.0]]).then_after(&Homography::from_affine(to_unit))
}
/// Affine approximation at a point (for objects that can't be warped: text, images, symbols).
fn affine_near(&self, p: Point) -> Affine {
let eps = 1.0;
@@ -127,6 +143,8 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
n.pin_gradients();
// The children before these are left out of a group's or compound path's bounds.
let skip = n.children().map_or(0, Vec::len) - n.editing_children().len();
// Type and symbol instances drawn through the warp keep their gradients in their own art.
let mut projected = false;
let before = match &mut n.kind {
NodeKind::Path { path, live, .. } => {
let b = path.bounds();
@@ -156,6 +174,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
}
b
}
// Type and symbol instances keep their art and are drawn through the warp, after the
// projection they had ([`project_node`]), so the corners of their box follow it exactly;
// [`distort`] has checked that the projection stays finite and their corners in front of
// the horizon.
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } if pr.is_projective() => {
let b = n.geometric_bounds();
projected = project_node(n, &pr.homography());
b
}
_ => {
// No editable points: the affine approximation (which maps the gradients too).
let b = n.geometric_bounds();
@@ -171,7 +198,9 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
if let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) {
warp_node(Arc::make_mut(&mut m.art), pr);
}
n.appearance.warp_gradients(&|p| pr.affine_near(p));
if !projected {
n.appearance.warp_gradients(&|p| pr.affine_near(p));
}
before
}
@@ -199,17 +228,19 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
})
}
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
/// why.
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
/// The first image, type object or symbol instance in `n` (its children and the art of linked
/// opacity masks, as [`warp_node`] reaches them) whose corners `pr` would fold, collapse or carry
/// past the warp's horizon, or type being edited flat, with why. `symbols` measures the boxes of
/// symbol instances.
fn unwarpable(n: &Node, pr: &Projective, symbols: &SymbolBoxes) -> Option<(vectorcraft_doc::NodeId, Cornered, Unwarpable)> {
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
if !q.iter().all(|p| pr.in_front(*p)) {
return Some((n.id, Unwarpable::Horizon));
return Some((n.id, Cornered::Image, Unwarpable::Horizon));
}
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
return Some((
n.id,
Cornered::Image,
match e {
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
@@ -217,24 +248,79 @@ fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeI
));
}
}
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
// Type and symbol instances are drawn through the warp ([`warp_node`]): their box's corners
// must stay in front of its horizon, and the projection they end with must be one that draws.
if let Some(kind) = Cornered::of(n).filter(|k| *k != Cornered::Image && pr.is_projective()) {
if kind == Cornered::Type && n.extras().perspective.as_deref().is_some_and(|p| p.editing) {
return Some((n.id, kind, Unwarpable::EditingFlat));
}
if n.drawn_corners(symbols).is_some_and(|q| !q.iter().all(|p| pr.in_front(*p))) {
return Some((n.id, kind, Unwarpable::Horizon));
}
let had = n.extras().perspective.as_deref().and_then(|p| p.homography()).unwrap_or(Homography::IDENTITY);
let Some(after) = pr.homography().checked_then_after(&had).and_then(|h| Homography::from_array(h.to_array())) else {
return Some((n.id, kind, Unwarpable::TooNarrow));
};
// The map it ends with must place its flat corners by the rules it is drawn with.
let flat = match n.extras().perspective.is_some() {
true => {
let mut flat = n.clone();
flat.extras_mut().perspective = None;
flat.drawn_corners(symbols)
}
false => n.drawn_corners(symbols),
};
if flat.is_some_and(|q| q.iter().any(|p| after.apply(*p).is_none())) {
return Some((n.id, kind, Unwarpable::Horizon));
}
}
warped_parts(n).into_iter().find_map(|c| unwarpable(c, pr, symbols))
}
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
/// masks).
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
if matches!(n.kind, NodeKind::Image(_)) {
return Some(n.id);
/// The first image, type object or symbol instance in `n` that [`warp_node`] reaches (its children
/// and the art of linked opacity masks), whose corners follow the warp exactly.
fn first_cornered(n: &Node) -> Option<(vectorcraft_doc::NodeId, Cornered)> {
if let Some(kind) = Cornered::of(n) {
return Some((n.id, kind));
}
warped_parts(n).into_iter().find_map(first_cornered)
}
/// The objects whose corners follow a distort exactly.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Cornered {
Image,
Type,
Symbol,
}
impl Cornered {
fn of(n: &Node) -> Option<Self> {
match n.kind {
NodeKind::Image(_) => Some(Self::Image),
NodeKind::Text(_) => Some(Self::Type),
NodeKind::SymbolInstance { .. } => Some(Self::Symbol),
_ => None,
}
}
/// The object's name in an error.
fn noun(self) -> &'static str {
match self {
Self::Image => "image",
Self::Type => "type object",
Self::Symbol => "symbol instance",
}
}
warped_parts(n).into_iter().find_map(first_image)
}
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
/// and compound paths, and the art of a linked opacity mask on those, paths, images, type and
/// symbol instances. Other objects (blends, envelopes, repeats and the rest) take the warp's affine
/// approximation whole.
fn warped_parts(n: &Node) -> Vec<&Node> {
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_) | NodeKind::Text(_) | NodeKind::SymbolInstance { .. });
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
children.chain(mask).collect()
@@ -246,9 +332,11 @@ pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId)
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
}
/// Why an image cannot follow the corners of a distort.
/// Why an image, type object or symbol instance cannot follow the corners of a distort.
#[derive(Clone, Copy)]
enum Unwarpable {
/// Type is being edited flat in Edit Text.
EditingFlat,
/// Its corners would fold over, meet or fall on one line.
NotConvex,
/// A corner would cross the warp's horizon.
@@ -257,14 +345,16 @@ enum Unwarpable {
TooNarrow,
}
/// The error of `object.distort` when image `id` cannot follow its corners.
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
/// The error of `object.distort` when object `id` (`kind`) cannot follow its corners.
fn unwarpable_error(id: vectorcraft_doc::NodeId, kind: Cornered, why: Unwarpable) -> EngineError {
const C: &str = "object.distort";
let noun = kind.noun();
match why {
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
Unwarpable::EditingFlat => bad(C, format!("{noun} {} cannot be distorted this way: it is being edited flat in Edit Text", id.0)),
Unwarpable::NotConvex => bad(C, format!("{noun} {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
Unwarpable::Horizon => bad(C, format!("{noun} {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
Unwarpable::TooNarrow => {
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
bad(C, format!("{noun} {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
}
}
}
@@ -311,25 +401,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(ids_json);
}
let pr = Projective::from_box(src, [tl, tr, br, bl]);
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
// changes when one would not.
// The corners of an image, a type object or a symbol instance follow the handles exactly, so
// they must stay a convex shape: nothing changes when one would not.
let doc = &s.doc()?.doc;
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
// affine one), so an image cannot follow them.
// affine one), so such an object cannot follow them.
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
{
return Err(unwarpable_error(id, Unwarpable::NotConvex));
return Err(unwarpable_error(id, kind, Unwarpable::NotConvex));
}
// Corners so close together that the map falls back to an affine one: the box's corners do
// not reach the handles, so an image cannot follow them either.
// not reach the handles, so such an object cannot follow them either.
if !reaches_corners(src, [tl, tr, br, bl])
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
&& let Some((id, kind)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_cornered)
{
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
return Err(unwarpable_error(id, kind, Unwarpable::TooNarrow));
}
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
return Err(unwarpable_error(id, why));
let symbols = doc.symbol_boxes();
if let Some((id, kind, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable(n, &pr, &symbols)) {
return Err(unwarpable_error(id, kind, why));
}
s.edit("Free Distort", |d, _| {
for id in &ids {
+160
View File
@@ -1235,6 +1235,166 @@ fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_recor
assert_eq!(undo_len(&s), undo);
}
/// A type object or (`symbol`) a symbol instance made of a 100 × 60 rectangle, selected alone.
fn type_or_instance(s: &mut Session, symbol: bool) -> NodeId {
let r = if symbol {
rect(s, 20.0, 30.0, 100.0, 60.0);
s.execute("symbol.new", &json!({"name": "Box"})).unwrap()
} else {
s.execute("text.create", &json!({"x": 20, "y": 80, "text": "Distort", "size": 40})).unwrap()
};
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
id
}
/// Where the corners of `id`'s box are drawn (top left, top right, bottom right, bottom left).
fn drawn_corners(s: &Session, id: NodeId) -> [Point; 4] {
let doc = &s.doc().unwrap().doc;
doc.node(id).unwrap().drawn_corners(&doc.symbol_boxes()).unwrap()
}
fn assert_near_corners(got: [Point; 4], want: [Point; 4]) {
for (g, w) in got.iter().zip(want) {
assert!(g.distance(w) < 1e-6, "{got:?} against {want:?}");
}
}
/// Perspective Distort and Free Distort put the corners of a type object's box and of a symbol
/// instance's box exactly on the handles, in one undo step: the object stays type or an instance,
/// drawn through the warp, it is bounded by those corners, a move takes them along, and undo gives
/// back the flat object.
#[test]
fn distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles() {
// Perspective Distort, then Free Distort, as fractions of the box.
let quads = [[(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)], [(0.1, 0.05), (0.9, 0.0), (1.2, 1.1), (0.0, 1.0)]];
for symbol in [false, true] {
for quad in quads {
let mut s = session();
let id = type_or_instance(&mut s, symbol);
let b = bounds(&s, id);
let flat = [(b.x0, b.y0), (b.x1, b.y0), (b.x1, b.y1), (b.x0, b.y1)].map(|(x, y)| Point::new(x, y));
assert_near_corners(drawn_corners(&s, id), flat);
let want = quad.map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()));
let undo = undo_len(&s);
s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert_near_corners(drawn_corners(&s, id), want);
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(matches!(n.kind, vectorcraft_doc::NodeKind::Text(_) | vectorcraft_doc::NodeKind::SymbolInstance { .. }), "{:?}", n.kind);
assert!(n.projection().is_some());
let got = bounds(&s, id);
let (xs, ys) = (want.map(|p| p.x), want.map(|p| p.y));
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(
near(got.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(got.x1, xs.iter().copied().fold(f64::MIN, f64::max)),
"{got:?}"
);
assert!(
near(got.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(got.y1, ys.iter().copied().fold(f64::MIN, f64::max)),
"{got:?}"
);
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0)));
// Distorted type opens flat in Edit Text.
assert_eq!(s.execute("perspective.editText", &json!({"id": id.0})).is_ok(), !symbol);
if !symbol {
assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none());
s.execute("object.exitIsolation", &json!({})).unwrap();
assert_near_corners(drawn_corners(&s, id), want.map(|p| p + Vec2::new(10.0, 20.0)));
}
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
if !symbol {
s.execute("edit.undo", &json!({})).unwrap();
}
assert!(s.doc().unwrap().doc.node(id).unwrap().projection().is_none());
assert_near_corners(drawn_corners(&s, id), flat);
}
}
}
/// Distorted together with paths, the corners of a type object's box and of a symbol instance's
/// box follow the same warp as the anchors of a path drawn on that box.
#[test]
fn distort_moves_type_and_symbol_instances_with_a_path_as_one() {
for symbol in [false, true] {
let mut s = session();
let id = type_or_instance(&mut s, symbol);
let b = bounds(&s, id);
// A path on the object's box, and one beside it so that the box is not the selection's.
let frame = rect(&mut s, b.x0, b.y0, b.width(), b.height());
let side = rect(&mut s, b.x1 + 50.0, b.y0 - 40.0, 80.0, 80.0);
s.execute("select.set", &json!({"ids": [id.0, frame.0, side.0]})).unwrap();
let all = s.doc().unwrap().doc.bounds_of(&[id, frame, side], false).unwrap();
let corners = [[all.x0 + 30.0, all.y0], [all.x1 - 10.0, all.y0 + 20.0], [all.x1 + 40.0, all.y1], [all.x0, all.y1 - 5.0]];
s.execute("object.distort", &json!({ "corners": corners })).unwrap();
let anchors = match &s.doc().unwrap().doc.node(frame).unwrap().kind {
vectorcraft_doc::NodeKind::Path { path, .. } => path.subpaths[0].anchors.iter().map(|a| a.p).collect::<Vec<_>>(),
k => panic!("not a path: {k:?}"),
};
let got = drawn_corners(&s, id);
// The rectangle's first anchor may be any of its corners: each drawn corner is one of them.
for c in got {
assert!(anchors.iter().any(|p| p.distance(c) < 1e-6), "{got:?} against {anchors:?}");
}
}
}
/// Corners that would carry a type object's or a symbol instance's box past the warp's horizon,
/// or fold it over, are refused, and nothing changes.
#[test]
fn distort_refuses_corners_type_and_symbol_instances_cannot_follow() {
for symbol in [false, true] {
let mut s = session();
let id = type_or_instance(&mut s, symbol);
let noun = if symbol { "symbol instance" } else { "type object" };
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
// y = 15, across the object.
let e =
s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("horizon"), "{e}");
let b = bounds(&s, id);
let folded = [[b.x0, b.y0], [b.x1, b.y1], [b.x1, b.y0], [b.x0, b.y1]];
let e = s.execute("object.distort", &json!({ "corners": folded })).unwrap_err().to_string();
assert!(e.contains(&format!("{noun} {}", id.0)) && e.contains("convex"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
// Near the edge of the canvas, the corners still reach the handles.
s.execute("object.move", &json!({"dx": 0, "dy": 3.9e6})).unwrap();
let b = bounds(&s, id);
let want = [(0.4, 0.0), (0.6, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| Point::new(b.x0 + u * b.width(), b.y0 + v * b.height()));
s.execute("object.distort", &json!({ "corners": want.map(|p| [p.x, p.y]) })).unwrap();
let got = drawn_corners(&s, id);
assert!(got.iter().zip(want).all(|(g, w)| g.distance(w) < 1e-3), "{got:?} against {want:?}");
}
}
/// Projective distort refuses type being edited flat without changing the document or history;
/// the same warp works after Edit Text ends.
#[test]
fn distort_refuses_type_being_edited_flat() {
let mut s = session();
let id = type_or_instance(&mut s, false);
let b = bounds(&s, id);
let corners = [(0.2, 0.0), (0.8, 0.0), (1.0, 1.0), (0.0, 1.0)].map(|(u, v)| [b.x0 + u * b.width(), b.y0 + v * b.height()]);
let p = json!({"ids": [id.0], "from": [b.x0, b.y0, b.x1, b.y1], "corners": corners});
s.execute("object.distort", &p).unwrap();
s.execute("perspective.editText", &json!({"id": id.0})).unwrap();
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute("object.distort", &p).unwrap_err().to_string();
assert!(e.contains("object.distort") && e.contains(&format!("type object {}", id.0)) && e.contains("being edited flat in Edit Text"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
s.execute("object.exitIsolation", &json!({})).unwrap();
let before = drawn_corners(&s, id);
let undo = undo_len(&s);
s.execute("object.distort", &p).unwrap();
assert_ne!(drawn_corners(&s, id), before);
assert_eq!(undo_len(&s), undo + 1);
}
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
/// before the distort.
#[test]
+15
View File
@@ -8513,6 +8513,21 @@ image between its corners and makes a plain image of the result. These rules are
{"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}}
```
## Perspective Distort and Free Distort on type and symbol instances
`object.distort` puts the corners of a type object's box and of a symbol instance's box (its symbol's art box placed
by its transform) exactly where the warp takes them, alone or with other objects. The object stays type or a symbol
instance: it keeps its flat art and is drawn through the warp, as type and symbols in perspective are, so the canvas,
printing and exports draw its outlines in perspective. An image in a symbol's art drawn this way, on the Perspective
Grid too, has its corners where the projection takes them and its pixels drawn in perspective between them, and its
linked opacity mask is projected with it. It is bounded by those corners, a move or another transform
takes them along, and Object › Perspective › Edit Text (`perspective.editText`) shows distorted type flat for editing.
A type object or symbol instance already drawn in perspective takes the warp after its projection. Corners that would
fold the box over, put three corners on one line, carry a corner of the box past the warp's horizon or lie too close
together for a perspective map are an error that names the object, and nothing changes; so is a warp of type that Edit
Text shows flat, until Edit Text ends. A warp whose corners make a
parallelogram moves, scales, rotates or shears the object as before. These rules are VectorCraft's own.
## Transform Each: Relative and Absolute
`object.transformEach` scales by percentages of each object's size (the dialog's Relative, the default), or with
+1
View File
@@ -1299,6 +1299,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`).
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
- Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`).
- Perspective Distort and Free Distort (`object.distort`) put the corners of a type object's box and of a symbol instance's box exactly where the warp takes them, alone or with other objects; the object stays type or a symbol instance and is drawn through the warp, after any perspective projection it had, as type and symbols in perspective are, with the images in a symbol's art and their linked masks drawn in perspective between the corners the projection gives them; and corners that would fold its box over, carry it past the warp's horizon or lie too close together for a perspective map are refused with an error that names it, as is a perspective warp of type that Edit Text shows flat. VectorCraft's own rule (engine `xform::distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles`, `distort_moves_type_and_symbol_instances_with_a_path_as_one`, `distort_refuses_corners_type_and_symbol_instances_cannot_follow`, `distort_refuses_type_being_edited_flat`; effects `group::tests::a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them`).
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
- With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`).
- Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).