Preserve symbol pattern resources and affine stroke scaling in AI exports

This commit is contained in:
Terra854 committed 2026-12-02 05:29:36 +08:00
1 parent 085d231803
commit 1e2bc0fee8
10 files changed
+265 -25

No files matched your search

+2 -2
View File
@@ -181,7 +181,7 @@
//! (gradients that dither are written without dither's noise, Perceptual gradients and gradients
//! mixed around the hue wheel as the stops on their curve in process colors, at most 256, and
//! gradient stops linked to global process colors as their colors), pattern fills whose tiles aren't a grid, whose art reaches past
//! the tile or is painted with patterns, and pattern fills in symbols, as their tiles cut
//! the tile or is painted with patterns, and pattern fills in large-canvas symbols, as their tiles cut
//! to the shape, clipping groups and clipping layers whose clipping object isn't a path,
//! and the clipping groups inside them, as their art cut to that object (its fill cut too, its
//! stroke not; an image in a clipping group of the region it is cut to), images that can't be
@@ -225,7 +225,7 @@ use vectorcraft_pdf::PrivateData;
use crate::ps;
mod writer;
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
use writer::Writer;
+171 -6
View File
@@ -6521,12 +6521,12 @@ fn instances_the_data_cant_hold_are_written_as_their_art() {
}
/// Symbols whose art paints with a pattern, directly, through a nested symbol, in an opacity mask
/// and through an inline graphic: their definitions hold the pattern fills as tiles cut to the shape (the reader keeps no
/// symbol whose art paints with a pattern), and their instances are written as their art, whose
/// and through an inline graphic: their definitions retain native pattern resources, and their
/// instances are written as their art, whose
/// pattern fills keep the document's placement as the canvas draws them, each with a warning. An
/// instance of a symbol without pattern paint stays an instance.
#[test]
fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
fn symbols_with_pattern_fills_keep_resources_and_place_as_art() {
let mut doc = Document::new(200.0, 100.0);
// Tiles that cover the shape, so its tiles cut to it draw its box.
let dot = Arc::new(square(&mut doc, Rect::new(0.0, 0.0, 8.0, 8.0), Color::BLACK));
@@ -6561,12 +6561,17 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
let filled = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(150.0, 10.0, 182.0, 42.0)), fill());
doc.insert(Some(layer), usize::MAX, filled).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART) && out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "grid resources must not become tiles: {:?}", out.warnings);
let back = read_back(&doc);
let names: Vec<&str> = back.symbols.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["Patch", "Outer", "Masked", "Plain", "Typed"]);
let patch = &back.symbols[0].art;
assert!(matches!(patch.kind, NodeKind::Group { .. }), "the symbol's art is its tiles: {:?}", patch.kind);
assert!(
matches!(patch.kind, NodeKind::Path { .. }) && vectorcraft_doc::pattern::uses_pattern(patch, Some("Dots")),
"the symbol must retain its original pattern-filled path: {:?}",
patch.kind
);
assert_eq!(instances(&back.symbols[1].art), 0, "the nested instance is its art");
let kids = back.layers[0].children().unwrap();
let kinds: Vec<bool> = kids.iter().map(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })).collect();
@@ -6596,8 +6601,164 @@ fn symbols_with_pattern_fills_are_defined_with_tiles_and_placed_as_art() {
same_lines(&boxes(&back), &boxes(&doc));
}
/// Original ruled tile shared by symbol art and an ordinary canvas object. The symbol's pattern
/// and geometry are scaled together, as editing its art with Transform Pattern Tiles does.
fn ruled_pattern_symbol(strokes: bool, tile_type: vectorcraft_doc::TileType, extent: f64) -> Document {
let mut doc = Document::new(240.0, 140.0);
let line =
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::BLACK), 2.0));
let mut tile = vectorcraft_doc::PatternDef::new("Rules", vec![Arc::new(line)]);
tile.tile = Rect::new(0.0, 0.0, 10.0, 10.0);
tile.tile_type = tile_type;
doc.patterns.push(tile);
let fill = || Appearance::basic(Paint::Pattern { pattern: "Rules".into(), xf: Affine::IDENTITY }, Paint::None, 0.0);
let mut art = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, extent, extent)), fill());
art.transform(Affine::scale(0.2), vectorcraft_doc::Scaling { strokes, patterns: true, ..Default::default() });
doc.symbols.push(Symbol { name: "Scaled".into(), art: Arc::new(art), dynamic: false });
let layer = doc.layers[0].id;
let one = instance(&mut doc, "Scaled", Affine::translate((20.0, 20.0)));
doc.insert(Some(layer), usize::MAX, one).unwrap();
let shared = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(125.0, 5.0, 225.0, 105.0)), fill());
doc.insert(Some(layer), usize::MAX, shared).unwrap();
doc
}
#[test]
fn scaled_pattern_symbol_keeps_native_pattern_resources_in_editing_data() {
let small = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
let large = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 200.0);
let (a, b) = (program(&small), program(&large));
eprintln!("pattern symbol editing bytes: {} -> {} for four times the tile area", a.len(), b.len());
let back = read_back(&small);
let art = &back.symbols.iter().find(|s| s.name == "Scaled").unwrap().art;
assert!(vectorcraft_doc::pattern::uses_pattern(art, Some("Rules")), "the symbol must retain pattern paint rather than one object per tile");
assert_eq!(a.matches("%AI3_BeginPattern: (Rules)").count(), 1);
assert!(b.len() < a.len() * 2, "editing data must not grow with every covered tile: {} -> {}", a.len(), b.len());
let tile = back.pattern("Rules").unwrap();
assert_eq!(tile.tile, small.patterns[0].tile);
assert_eq!(tile.art[0].geometric_bounds().unwrap().width(), 8.0);
let strokes: Vec<_> =
tile.art[0].appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(stroke) = i { Some(stroke.width) } else { None }).collect();
assert_eq!(strokes, [2.0], "the shared tile keeps its original stroke");
}
// Four editing-stream round trips and native raster probes cover the flag and fallback cases.
#[test]
fn scaled_pattern_symbol_new_instances_match_native_tile_stroke_weight() {
for strokes in [true, false] {
for tile_type in [vectorcraft_doc::TileType::Grid, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }] {
let doc = ruled_pattern_symbol(strokes, tile_type, 100.0);
// Native rendering scales a 2pt pattern stroke to 0.4pt with its pattern affine,
// under either flag. The flag controls the selected object's own stroke separately.
let native = vectorcraft_testkit::raster::render_region(&doc, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
let native_weight = (0..native.height).filter(|y| native.pixel(20, *y)[0] < 64).count();
assert!((6..=10).contains(&native_weight), "native weight={native_weight}, strokes={strokes}, {tile_type:?}");
let mut back = read_back(&doc);
// Place afresh from the editing stream's symbol definition, rather than measuring
// the already-expanded canvas instance or the file's native payload.
back.layers.clear();
let layer = back.add_layer(Some("New instance"));
let one = instance(&mut back, "Scaled", Affine::translate((20.0, 20.0)));
back.insert(Some(layer), usize::MAX, one).unwrap();
let placed = vectorcraft_testkit::raster::render_region(&back, Rect::new(20.0, 20.0, 22.0, 22.0), 20.0);
let weight = (0..placed.height).filter(|y| placed.pixel(20, *y)[0] < 64).count();
assert!((6..=10).contains(&weight), "editing symbol weight={weight}, native={native_weight}, strokes={strokes}, {tile_type:?}");
}
}
}
// Each case goes through the real editing stream and renderer: the mask stroke has to be
// transformed as geometry even when writing its dictionary temporarily clears the tile clip.
#[test]
fn pattern_tile_fallback_preserves_affine_mask_stroke_weight() {
for matrix in
[Affine::scale(0.2), Affine::scale_non_uniform(0.2, 0.4), Affine::new([0.2, 0.0, 0.1, 0.2, 0.0, 0.0]), Affine::scale_non_uniform(-0.2, 0.2)]
{
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::BrickByRow { offset: 0.5 }, 100.0);
let white_line =
Node::path(doc.alloc_id(), shapes::line((1.0, 5.0).into(), (9.0, 5.0).into()), Appearance::basic(Paint::None, solid(Color::WHITE), 2.0));
let mut tile = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), Color::BLACK);
tile.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(white_line), clip: true, invert: false, disabled: false, linked: true }));
doc.patterns[0].art = vec![Arc::new(tile)];
Arc::make_mut(&mut doc.symbols[0].art)
.transform(matrix * Affine::scale(5.0), vectorcraft_doc::Scaling { patterns: true, ..Default::default() });
// This fallback bakes the unsupported brick phase. Place on whole super-tile periods
// so the probe isolates stroke geometry, rather than that existing placement limitation.
doc.layers.clear();
let native_layer = doc.add_layer(Some("Native instance"));
let native_one = instance(&mut doc, "Scaled", Affine::translate((60.0, 40.0)));
doc.insert(Some(native_layer), usize::MAX, native_one).unwrap();
let bounds = doc.symbols[0].art.geometric_bounds().unwrap() + vectorcraft_geom::Vec2::new(60.0, 40.0);
let period_y = 10.0 * matrix.as_coeffs()[3].abs();
let region = Rect::new(bounds.x0, bounds.y0, bounds.x0 + 2.0, bounds.y0 + period_y);
let native = vectorcraft_testkit::raster::render_region(&doc, region, 20.0);
// Brick rows shift the line horizontally; select a visible native column and compare
// that same column after the editing-stream round trip.
let (column, native_weight) = (0..native.width)
.map(|x| (x, (0..native.height).filter(|y| native.pixel(x, *y)[0] < 64).count()))
.max_by_key(|(_, weight)| *weight)
.unwrap();
assert!(native_weight > 0 && native_weight < native.height as usize, "native mask stroke: {matrix:?}, {native_weight}");
let mut back = read_back(&doc);
back.layers.clear();
let layer = back.add_layer(Some("New instance"));
let one = instance(&mut back, "Scaled", Affine::translate((60.0, 40.0)));
back.insert(Some(layer), usize::MAX, one).unwrap();
let placed = vectorcraft_testkit::raster::render_region(&back, region, 20.0);
let weight = (0..placed.height).filter(|y| placed.pixel(column, *y)[0] < 64).count();
assert!(weight.abs_diff(native_weight) <= 2, "mask stroke {matrix:?}: editing={weight}, native={native_weight}");
}
}
#[test]
fn pattern_definition_dictionary_is_scoped_away_from_its_symbol() {
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
// Definitions can hold freshly generated id-less art. Its dictionary must not consume the
// surrounding symbol's root entries just because these independent art scopes share id 0.
Arc::make_mut(&mut doc.patterns[0].art[0]).id = vectorcraft_doc::NodeId(0);
let art = (*doc.symbols[0].art).clone();
let other = square(&mut doc, Rect::new(25.0, 0.0, 30.0, 5.0), Color::BLACK);
let mut root = group(&mut doc, vec![art, other], false);
root.id = vectorcraft_doc::NodeId(0);
doc.symbols[0].art = Arc::new(root);
let back = read_back(&doc);
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("pattern art must not steal its symbol's declaration");
let mut uses = false;
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| uses |= vectorcraft_doc::pattern::uses_pattern(n, Some("Rules")));
assert!(uses);
}
#[test]
fn symbol_pattern_matrices_stay_readable_or_use_the_bounded_fallback() {
for scale in [0.00001, 0.0, 1e-9] {
let mut doc = ruled_pattern_symbol(true, vectorcraft_doc::TileType::Grid, 100.0);
let art = Arc::make_mut(&mut doc.symbols[0].art);
for item in art.appearance.items.iter_mut() {
if let Paint::Pattern { xf, .. } = item.paint_mut() {
*xf = Affine::scale(scale);
}
}
let out = export_ai_editing(&doc, &opts()).unwrap();
let back = read_back(&doc);
let symbol = back.symbols.iter().find(|s| s.name == "Scaled").expect("a bad paint matrix must not discard its symbol");
let mut paints = vec![];
vectorcraft_doc::swatches::walk_with_masks(&symbol.art, &mut |n| {
for item in &n.appearance.items {
if let Paint::Pattern { xf, .. } = item.paint() {
paints.push(*xf);
}
}
});
if scale == 0.00001 {
assert_eq!(paints, [Affine::scale(scale)], "a small invertible affine must survive serialization");
} else {
assert!(paints.is_empty() && out.warnings.iter().any(|w| w == writer::PATTERN_PLACEMENT), "{:?}", out.warnings);
}
}
}
/// A symbol whose art paints with a pattern only through a brushed stroke, whose brush's art is
/// filled with a pattern: the definition holds the tiles, and its instance is written as its art.
/// filled with a pattern: the definition keeps that resource, and its instance is written as art.
#[test]
fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
let mut doc = Document::new(200.0, 100.0);
@@ -6625,9 +6786,13 @@ fn symbols_painting_patterns_through_brush_art_are_placed_as_art() {
doc.insert(Some(layer), usize::MAX, one).unwrap();
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().any(|w| w == writer::SYMBOL_ART), "{:?}", out.warnings);
assert!(!out.warnings.iter().any(|w| w == writer::PATTERNS), "{:?}", out.warnings);
let back = read_back(&doc);
assert_eq!(back.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Brushed"]);
assert_eq!(instances(&back.layers[0]), 0, "the instance is its art");
let mut pattern = false;
vectorcraft_doc::swatches::walk_with_masks(&back.symbols[0].art, &mut |n| pattern |= vectorcraft_doc::pattern::uses_pattern(n, Some("Dots")));
assert!(pattern, "indirect brush paint retains its pattern resource in the definition");
}
/// A symbol first defined from the drawn look of a group with a style, through a member's scatter
+34 -6
View File
@@ -48,7 +48,7 @@ pub(super) use paints::{
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
SWATCH_PLACEMENT, free_gradient_name,
};
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode};
pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, PATTERN_SPACE_KEY, hex_decode};
#[cfg(test)]
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS};
#[cfg(test)]
@@ -62,8 +62,10 @@ pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES};
pub(super) const MAX_NEST: u32 = 8;
pub(super) const TYPE: &str = "type in opacity masks, pattern tiles, symbols and art cut to a clipping object, mirrored type, area type and type on a path that is turned or unevenly scaled or whose frame or path has several parts, area type in an open frame, type on an open path whose ends meet, area type whose text wrap cannot be preserved from the saved objects, type of only white space, threads of type on a path, threads whose frames differ in orientation or hold a frame written as outlines, type of sizes past what the reader reads, stories past what the reader reads (1,048,576 bytes a story, 16,777,216 bytes in all, and the size of text document it reads), and type with inline graphics, ruby, gradient or pattern paint, or fills, strokes, effects or an opacity mask of the object's own, is written as its outlines in the editing data for other apps";
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const PATTERNS: &str = "pattern fills whose tiles aren't a grid or whose art reaches past the tile, pattern fills in another pattern's tile or in a large canvas's symbol, and pattern fills nested more than 8 deep are written as their tiles cut to the shape in the editing data for other apps";
pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fill places are written filled gray in the editing data for other apps";
pub(super) const PATTERN_PLACEMENT: &str =
"pattern fills and strokes whose placement cannot be read are written gray in the editing data for other apps";
pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps";
pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps";
pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps";
@@ -269,10 +271,10 @@ pub(super) struct Writer<'a> {
/// Whether each symbol's art paints with a pattern, nested symbols included
/// ([`Self::symbol_paints_pattern`]).
patterned_symbols: HashMap<String, bool>,
/// Pattern tiles were written in the art being written ([`Self::define_symbol`] starts it over
/// Pattern references or tiles were written in the art ([`Self::define_symbol`] starts it over
/// for each symbol's art).
wrote_pattern: bool,
/// The symbols whose definitions hold pattern tiles: a brushed stroke's brush art or a live
/// The symbols whose definitions write pattern paint: a brushed stroke's brush art or a live
/// object's art can paint with a pattern that the symbol's own objects don't name.
pattern_written: HashSet<String>,
/// Art that draws as it should only where it is was written in the art being written
@@ -1031,6 +1033,7 @@ impl<'a> Writer<'a> {
mask = None;
mask_written = false;
}
let symbol_root = self.root_entries.as_ref().is_some_and(|(id, _)| *id == n.id);
let entries = match &self.root_entries {
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
_ => None,
@@ -1081,6 +1084,10 @@ impl<'a> Writer<'a> {
}
mask_written = false;
}
// A pattern may first be written by the root's mask, so declare its space afterwards.
if symbol_root && self.in_symbol && self.symbols_live && self.wrote_pattern {
let _ = writeln!(self.body, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
}
self.body.push_str("%_;\n%_\n");
mask_written
}
@@ -1480,7 +1487,8 @@ impl<'a> Writer<'a> {
let flat = FillLayer { paint: Paint::solid(Color::gray(0.5)), ..f.clone() };
return self.path_object(path, rule, Some(&flat), None, xy);
};
let tiles = def.instances_in(*xf, path.to_bezpath().bounding_box());
let inverse = xf.inverse();
let tiles = def.instances_in(Affine::IDENTITY, inverse.transform_rect_bbox(path.to_bezpath().bounding_box()));
// More tiles than a fill places come back as none: the shape is filled gray, as a
// pattern that isn't found is.
if tiles.is_empty() && !def.art.is_empty() {
@@ -1494,8 +1502,26 @@ impl<'a> Writer<'a> {
}
self.wrote_pattern = true;
let outer = self.clip.clone();
let region = self.cut(path, rule);
let mut region = self.cut(path, rule);
region.transform(inverse);
self.clip = Some(region);
let shown = std::mem::take(&mut self.shown);
self.shown = shown
.iter()
.map(|p| {
let mut p = p.clone();
p.apply_affine(inverse);
p
})
.collect();
// Outline and clip strokes in pattern space before applying its affine. Moving
// just their centerlines first kept 2pt strokes at 2pt under a 20% pattern scale;
// scaling by one mean factor would still distort nonuniform/sheared patterns.
let spaces = (self.to_art, self.grad_space, self.canvas, self.instance_space);
self.to_art *= *xf;
self.grad_space *= *xf;
self.canvas *= *xf;
self.instance_space *= *xf;
self.nest += 1;
self.drawn += 1;
for t in &tiles {
@@ -1508,6 +1534,8 @@ impl<'a> Writer<'a> {
self.end_group("U", xy);
self.nest -= 1;
self.clip = outer;
self.shown = shown;
(self.to_art, self.grad_space, self.canvas, self.instance_space) = spaces;
}
Paint::None => {}
}
+1 -1
View File
@@ -430,7 +430,7 @@ impl Writer<'_> {
}
/// `[a b c d tx ty]`, each number to ten decimals ([`ps::num`] writes four).
fn matrix(m: Affine) -> String {
pub(super) fn matrix(m: Affine) -> String {
let n: Vec<String> = m.as_coeffs().iter().map(|v| precise(*v)).collect();
format!("[{}]", n.join(" "))
}
+31 -6
View File
@@ -367,7 +367,12 @@ impl Writer<'_> {
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
/// write it)?
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
self.direct(&s.paint) && stroke::is_plain(s)
let [a, b, c, d, ..] = self.to_art.as_coeffs();
// Operators receive transformed path coordinates, but their width is in art units.
// A non-isometric map needs the stroke's outline transformed too (including in masks,
// whose dictionary temporarily clears the clipping region of a pattern fallback).
let isometry = (a * a + b * b - 1.0).abs() < 1e-9 && (c * c + d * d - 1.0).abs() < 1e-9 && (a * c + b * d).abs() < 1e-9;
isometry && self.direct(&s.paint) && stroke::is_plain(s)
}
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
@@ -576,10 +581,10 @@ impl Writer<'_> {
/// Can pattern `name` be written as a definition and painted with from here: the document has
/// it, its tiles make a grid, its art is within its tile and holds something, and it isn't used
/// in another pattern's tile or a symbol's art (the reader keeps no symbol whose art paints with
/// a pattern) or nested more than [`MAX_NEST`] deep?
/// in another pattern's tile or nested more than [`MAX_NEST`] deep? A large canvas's symbol
/// art uses the original document, whose same-name tiles can differ from the reduced page's.
pub(super) fn pattern_writable(&self, name: &str) -> bool {
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
if !self.defining.is_empty() || self.nest >= MAX_NEST || (self.in_symbol && !self.symbols_live) {
return false;
}
if self.patterns.find(name).is_some() {
@@ -605,7 +610,14 @@ impl Writer<'_> {
let doc = self.doc;
// The tile's box is an object of the definition ([`Self::take_objects`]).
let (before, bound) = (self.charges(), self.bound.len());
let Some(def) = doc.pattern(name).filter(|_| self.take_objects(1)) else { return false };
let Some(def) = doc.pattern(name) else { return false };
// A pattern is a separate global resource, even when first discovered in symbol art.
// Charge its objects outside the symbol-art budget and isolate parent dictionaries.
let in_symbol = std::mem::take(&mut self.in_symbol);
if !self.take_objects(1) {
self.in_symbol = in_symbol;
return false;
}
self.defining.push(name.to_string());
// The art is written in the pattern's space, y up, from the state a definition starts in.
let saved = (
@@ -617,6 +629,7 @@ impl Writer<'_> {
self.block_end,
// The tile's masks' objects are written with their art styles, those of no other art.
(std::mem::replace(&mut self.styled, self.pattern_styled.get(name).cloned().unwrap_or_default()), self.mask_level.take()),
(in_symbol, self.root_entries.take(), self.instance_entries.take(), self.block_start),
);
// `Bg` places a gradient in a pattern's tile as on the canvas, mirrored top to bottom: its
// placement is worked out in the tile's space turned y up.
@@ -647,6 +660,7 @@ impl Writer<'_> {
(self.clip, self.shown),
self.block_end,
(self.styled, self.mask_level),
(self.in_symbol, self.root_entries, self.instance_entries, self.block_start),
) = saved;
let art = std::mem::replace(&mut self.body, art);
self.defining.pop();
@@ -679,7 +693,18 @@ impl Writer<'_> {
return self.plain_color(Color::gray(0.5), stroke);
};
let m = self.to_art * xf * Affine::translate((0.0, h)) * Affine::FLIP_Y;
let _ = writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), ps::matrix(m), if stroke { 'P' } else { 'p' });
let written = Affine::new(m.as_coeffs().map(|v| (v * 1e10).round() / 1e10));
// Keep a definition's reference readable after serialization; a singular or rounded-flat
// paint must not make the reader discard the entire symbol that contains it.
if !written.as_coeffs().iter().all(|v| v.is_finite()) || !written.determinant().is_finite() || written.determinant().abs() < 1e-12 {
self.warn(super::PATTERN_PLACEMENT);
return self.plain_color(Color::gray(0.5), stroke);
}
// Indirect pattern paint (for example in brush art) also prevents a live symbol
// instance: the canvas keeps its pattern phase fixed when placing that instance.
self.wrote_pattern = true;
let _ =
writeln!(self.body, "{} 0 0 1 1 0 0 0 0 0 {} {}", ps::bytes(name.as_bytes()), super::images::matrix(m), if stroke { 'P' } else { 'p' });
}
/// The definitions, in the setup before the palette: the gradients the art uses (`n Bn`, then
@@ -19,6 +19,9 @@ pub(in crate::ai_editing) const SYMBOL_CHANGES: &str =
"the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out";
pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol";
pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides";
/// Version 1 declares that pattern matrices in this definition use its art coordinates.
/// Foreign definitions without that declaration retain the reader's conservative fallback.
pub(crate) const PATTERN_SPACE_KEY: &str = "VectorCraftSymbolPatternSpace";
const MAX_OVERRIDES_BYTES: usize = 1 << 20;
pub(crate) fn hex_decode(s: &str) -> Option<Vec<u8>> {
@@ -311,6 +314,9 @@ impl Writer<'_> {
if wrap {
self.line("u");
self.node(root);
if self.symbols_live && self.wrote_pattern {
let _ = writeln!(entries, "%_1 /Int ({PATTERN_SPACE_KEY}) ,");
}
let _ = write!(self.body, "U\n%_/ArtDictionary :\n{entries}%_;\n%_\n9 () XW\n");
} else {
// A group always writes its dictionary ([`Self::dictionary`]), which takes the entries.
+6 -2
View File
@@ -631,8 +631,12 @@ impl<'a> Reader<'a> {
let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1;
let Some(frame) = sub.frames.pop().filter(|_| measured) else { return };
let mut kids = frame.children;
// Where a symbol's art puts a pattern's tiles isn't known.
let whole = !head.left_out && sub.unread.is_empty() && sub.hidden_unread.is_empty() && !kids.iter().any(|n| paints_pattern(n, 0));
// Unmarked foreign symbols do not declare the coordinate convention of their patterns.
// Our writer explicitly declares symbol-art space, so those definitions can retain paint.
let whole = !head.left_out
&& sub.unread.is_empty()
&& sub.hidden_unread.is_empty()
&& (head.pattern_space || !kids.iter().any(|n| paints_pattern(n, 0)));
if !whole {
let boxes = self.doc.symbol_boxes();
let bounds = kids.iter().fold(None, |acc, n| vectorcraft_geom::union_opt(acc, n.visual_bounds_with(&boxes)));
@@ -805,6 +805,12 @@ impl<'a> Reader<'a> {
{
head.dynamic = true;
}
if self.frames.len() == 1
&& let Some(head) = self.symbol.as_mut()
&& o.nums(crate::ai_editing::PATTERN_SPACE_KEY).first().copied() == Some(1.0)
{
head.pattern_space = true;
}
if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY)
&& let Some(bytes) = crate::ai_editing::hex_decode(&text)
&& let Ok(list) = serde_json::from_slice::<Vec<vectorcraft_doc::SymbolOverride>>(&bytes)
+2
View File
@@ -245,6 +245,8 @@ pub(super) struct SymbolHead {
/// `AI13PatternRegistrationType` in the dictionary after the art.
pub(super) registration: Option<f64>,
pub(super) dynamic: bool,
/// The writer declares its pattern matrices to be in symbol-art coordinates (version 1).
pub(super) pattern_space: bool,
/// Art the reader left out (type, a placed file, non-native art, an image it can't read or
/// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the
/// page draws them, within the box of the rest.
+6 -2
View File
@@ -137,8 +137,12 @@ private editing data. VectorCraft:
symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object,
instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects,
instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art,
instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art, pattern fills in a
symbol's art are written as their tiles cut to the shape, symbols past 4,096 are written only as their
instances that scale their symbol more than 100 times and instances on the layers of a large canvas are written as their art. Pattern fills in
large-canvas symbol art are written as their tiles cut to the shape. On normal canvases, supported pattern
fills in symbol definitions retain the shared pattern resource and their affine; VectorCraft declares that
coordinate convention in its own dictionary entry, while unmarked foreign symbol patterns keep the reader's
conservative fallback. Tile fallback transforms stroke outlines with the full pattern affine, including
strokes in opacity masks. Symbols past 4,096 are written only as their
instances' art, and symbols' 9-slice guides and export types are left out, each with a
warning. A dynamic symbol instance whose only changes of its own are its parts' changes is not written as its
art when it otherwise qualifies: it stays a live instance. The symbol's dynamic type and the instance's changes