mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 22:33:08 +00:00
.ai save: the editing copy keeps gradient meshes
The editing copy of a PDF-compatible .ai wrote every gradient mesh as
its drawn look. Meshes the .ai reader reads back as they are are now
written as meshes:
- Each mesh is a /Mesh record: 2 /Version, its type and grid size,
/Data, then each patch row by row with its place, the color space
where it changes (gray, RGB or CMYK) and its four corners: color,
opacity, point, and the handles towards the next corner and the one
before it. Its opacity, blending mode and knockout shape are set
before the record, and its name and opacity mask follow it.
- A reflected mesh, whose patches all turn the other way, is written
with its columns in reverse order, which draws the same mesh.
- In a symbol's art the corners are written about the canvas point of
the ruler origin, y up, as an image's matrix there is. An envelope's
grid in a symbol's art is now written in the same space, and the
envelope's contents in its dictionary in the canvas's space, y down.
- Each mesh is checked with the reader's own reading before it is
written. Written as their drawn look with a warning: meshes with a
point in a Lab color, with more than 128 rows or columns, folded
meshes (patches that turn different ways), meshes the reader would
read with other points, handles or colors, meshes in pattern tiles
and in art cut to a clipping object, and every mesh on a large
canvas. A mesh's drawn look is written at any depth of nested
symbols and live objects.
Each construct is written in the form the .ai reader at e142c5fcee
reads: /CS, /Type, /Size, /P, /N and /E in mesh.rs:180-234, corners
with or without an opacity by their count of values in read_corners
(mesh.rs:239), the patches joined into one mesh in one_mesh
(mesh.rs:298); /Mesh X!, X# and /End X! in read/ops.rs:219-232; the
transparency after the record in read/art.rs:281 (end_mesh) and
read/ops.rs:344. /Version and /Data are passed over by that reader
(mesh.rs:234). Corners in a symbol's art rest on a reader change in
this commit.
The reader changes how any .ai opens:
- Mesh records and envelope grids in a symbol's art are read in canvas
space (read/document.rs:947 image_space), and an envelope's contents
in its dictionary in the canvas's space, y down. In a file without a
template box such a mesh is left unread, its symbol is not read
whole, as with an image there (read/art.rs:634), and its instances
open as the page draws them. Envelopes in symbols in .ai files saved
by earlier VectorCraft builds open differently.
- A point of a patch whose corners differ in color model keeps its own
color when the patches are joined into one mesh.
Gradient meshes, mesh points and their opacity:
https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=200
Patch meshes (corners joined by cubic edges with control points):
https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf#page=321
Tests: the round trip of meshes with RGB, CMYK and gray points, a moved
point with handles of its own, part-transparent points, a name,
opacity, blending mode and knockout shape, hidden and locked, with an
inverted, unlinked opacity mask, in groups, opacity masks, symbols,
opacity masks in symbols, a document of two artboards and eight levels
down, compared point by point, handle by handle and channel by channel
at the 4 decimals written; reflected meshes, mirrored across and
along; the record's form, including corners in a symbol's art and an
envelope's grid and contents there; an envelope in a symbol read back
with its contents and their gradient in place; the same bytes on a
second write; each case written as its drawn look, with its paths read
back over the mesh's box; reading a mesh in a symbol's art with and
without a template box; /Version and /Data passed over; the color
model rule; fuzz cases for damaged written meshes, a symbol's
included.
Docs: docs/file-format-parity.md, docs/target-app-parity.md.
This commit is contained in:
@@ -8124,3 +8124,95 @@ proptest! {
|
||||
prop_assert_eq!(paths, 2, "{:?}", notes);
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// A `.ai` whose gradient meshes, as the writer writes them, are damaged: the record's type,
|
||||
/// size, places, color spaces and corners on `%_` lines, its `/Mesh X!` and `/End X!`, and the
|
||||
/// mesh's transparency and name, cut short or edited.
|
||||
#[test]
|
||||
fn ai_written_meshes_never_panic(cut in 0usize..MESHES_FUZZ_CHARS, edits in prop::collection::vec((0usize..MESHES_FUZZ_CHARS, prop::sample::select(vec!['0', '1', '2', '9', '-', '.', 'e', ' ', '\n', '[', ']', '(', ')', '/', '%', '_', 'X', '!', '#', 'N', 'P', 'E'])), 0..12)) {
|
||||
let text = mutate_text(meshes_text(), cut, &edits);
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat();
|
||||
survive("mutated .ai meshes", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, false, 1.0).0))?;
|
||||
survive("mutated .ai meshes, trusted", || Some(vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of [`ai_written_meshes_never_panic`]'s cuts and edits: past the end of [`meshes_text`].
|
||||
const MESHES_FUZZ_CHARS: usize = 24_000;
|
||||
|
||||
/// The editing data VectorCraft writes for a document with two gradient meshes: 2 × 3 patches whose
|
||||
/// rows of points are RGB, CMYK and gray, at half opacity and named; a 1 × 1 mesh with a point at
|
||||
/// 40% opacity; and an instance of a symbol whose art is a 2 × 1 mesh.
|
||||
fn meshes_text() -> &'static str {
|
||||
static TEXT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
|
||||
TEXT.get_or_init(|| {
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, MeshPoint, grid_points, smooth_handles};
|
||||
use vectorcraft_doc::{Node, NodeKind};
|
||||
use vectorcraft_geom::Rect;
|
||||
let mesh = |r: Rect, rows: u32, cols: u32, color: &dyn Fn(usize) -> Color| {
|
||||
let pts = grid_points(r, rows, cols);
|
||||
let handles = smooth_handles(rows, cols, &pts);
|
||||
let width = cols as usize + 1;
|
||||
let points = pts
|
||||
.iter()
|
||||
.zip(handles)
|
||||
.enumerate()
|
||||
.map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width), opacity: 1.0, handles: h })
|
||||
.collect();
|
||||
GradientMesh { rows, cols, points }
|
||||
};
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let sheet = mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, &|row| match row {
|
||||
0 => Color::rgb(1.0, 0.5, 0.0),
|
||||
1 => Color::cmyk(0.1, 0.6, 0.2, 0.05),
|
||||
_ => Color::gray(0.4),
|
||||
});
|
||||
let mut sheet = Node::new(doc.alloc_id(), NodeKind::Mesh(sheet));
|
||||
(sheet.name, sheet.opacity) = (Some("Sheet".into()), 0.5);
|
||||
doc.insert(Some(layer), usize::MAX, sheet).unwrap();
|
||||
let mut small = mesh(Rect::new(220.0, 20.0, 280.0, 80.0), 1, 1, &|row| Color::rgb(0.0, 0.3, 0.3 + 0.5 * row as f32));
|
||||
small.points[1].opacity = 0.4;
|
||||
let small = Node::new(doc.alloc_id(), NodeKind::Mesh(small));
|
||||
doc.insert(Some(layer), usize::MAX, small).unwrap();
|
||||
let patch = mesh(Rect::new(0.0, 0.0, 40.0, 30.0), 2, 1, &|row| Color::rgb(0.2 * row as f32, 0.6, 0.1));
|
||||
let patch = Node::new(doc.alloc_id(), NodeKind::Mesh(patch));
|
||||
doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Patch".into(), art: std::sync::Arc::new(patch) });
|
||||
let instance =
|
||||
Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Patch".into(), xf: vectorcraft_geom::Affine::translate((20.0, 140.0)) });
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let out = vectorcraft_eps::export_ai_editing(&doc, &vectorcraft_eps::AiEditingOptions::default()).unwrap();
|
||||
String::from_utf8(out.program).unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// The data [`ai_written_meshes_never_panic`] damages, as it is, opens with both meshes, the symbol
|
||||
/// with its mesh and its instance, and the property's cuts and edits reach all of it.
|
||||
#[test]
|
||||
fn the_written_meshes_fuzz_data_opens_as_meshes() {
|
||||
use vectorcraft_doc::NodeKind;
|
||||
let text = meshes_text();
|
||||
assert!(text.chars().count() < MESHES_FUZZ_CHARS, "{}", text.chars().count());
|
||||
for mark in ["%AI14_BeginSymbol", "%AI5_BeginLayer", "/Mesh X!", "%_[2 3] /Size X#", "%_/DeviceCMYK /CS X#", "/End X!", "/SymbolInstance :"] {
|
||||
assert!(text.replace("\r\n", "\n").contains(mark), "{mark}");
|
||||
}
|
||||
let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(text)].concat();
|
||||
let (d, warnings, layered) = vectorcraft_eps::layered_ai(&private, Document::new(300.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(layered, "{warnings:?}");
|
||||
let art = d.layers[0].children().unwrap();
|
||||
let kinds: Vec<&str> = art
|
||||
.iter()
|
||||
.map(|n| match n.kind {
|
||||
NodeKind::Mesh(_) => "mesh",
|
||||
NodeKind::SymbolInstance { .. } => "instance",
|
||||
_ => "other",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(kinds, ["mesh", "mesh", "instance"], "{warnings:?}");
|
||||
let patch = d.symbols.iter().find(|s| s.name == "Patch").map(|s| &s.art.kind);
|
||||
assert!(matches!(patch, Some(NodeKind::Mesh(_))), "{patch:?}");
|
||||
}
|
||||
|
||||
@@ -120,7 +120,9 @@
|
||||
//! and opacity mask and a state block as a group's with its opacity and blending mode (an
|
||||
//! instance with isolation, knockout or knockout shape of its own is written as its art). The
|
||||
//! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there.
|
||||
//! a gradient's take the art to the canvas's space turned y up about art space's origin there,
|
||||
//! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are
|
||||
//! in the canvas's space with y down.
|
||||
//! - Art styles, as the reader reads them (`style.rs`, `read/ops.rs`): a path, compound path or
|
||||
//! group with live effects or linked to a graphic style is written as its drawn look (`u`, its
|
||||
//! vector art as its geometry effects leave it, without shadows, glows or feathers, `U`, its
|
||||
@@ -147,6 +149,13 @@
|
||||
//! reader reads back as the same graph ([`crate::ai_graph`]) is written as its group between
|
||||
//! `%_Gs`, its functional records and `%_GS`, each series' group tagged `Go` right after its end;
|
||||
//! any other graph, and a graph with art left out, as its art, with a warning.
|
||||
//! - Gradient meshes, as the reader reads them (`mesh.rs`): `/Mesh X!`, `2 /Version`, the grid's type
|
||||
//! and size, `/Data` (the reader passes over the version and `/Data`), and each patch's place, color
|
||||
//! space and four corners (color, opacity, point and handles) as `X#` entries on `%_` lines,
|
||||
//! `/End X!`; the mesh's transparency before it, its name and opacity mask after it
|
||||
//! (`writer::meshes`). A mesh is written as it is only when the reader reads it back so, when every
|
||||
//! patch turns the same way (a reflected mesh's columns are written in reverse order), and outside
|
||||
//! pattern tiles, art cut to a clipping object and a large canvas.
|
||||
//!
|
||||
//! Lines end in CR LF. Strings are written in UTF-8. Art space is ruler space: y up, its origin at
|
||||
//! the first artboard's top-left corner. On the canvas ([`CANVAS_SIZE`] points square, y down) the
|
||||
@@ -175,7 +184,9 @@
|
||||
//! and instances of
|
||||
//! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects
|
||||
//! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice
|
||||
//! guides, export types and dynamic type left out, live objects (placed documents included) as their art,
|
||||
//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as
|
||||
//! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh
|
||||
//! on a large canvas as their drawn look, other live objects (placed documents included) as their art,
|
||||
//! strokes a plain line can't draw and the object's art style doesn't hold
|
||||
//! as their filled outlines, several fills or strokes as a group of a path for each, freeform
|
||||
//! gradient swatches, gradient swatches of more than 256 stops, swatches of patterns written as
|
||||
@@ -318,6 +329,7 @@ fn export_held(source: &Document, o: &AiEditingOptions, max_objects: usize, keep
|
||||
// On a large canvas the layers' symbol instances are written as their art.
|
||||
w.symbols_live = scale == 1.0;
|
||||
w.brushes_live = scale == 1.0;
|
||||
w.meshes_live = scale == 1.0;
|
||||
w.symbol_doc = symbol_doc;
|
||||
w.max_objects = max_objects;
|
||||
w.wraps_held = wraps_held;
|
||||
|
||||
@@ -1089,6 +1089,7 @@ fn counted() -> Vec<(&'static str, Document)> {
|
||||
("blend", blend_doc()),
|
||||
("brushes", brushes_document()),
|
||||
("envelopes", envelopes_document()),
|
||||
("meshes", meshes_document()),
|
||||
("wrap bounds", wrap_bounds_doc()),
|
||||
]
|
||||
}
|
||||
@@ -10780,7 +10781,7 @@ fn envelopes_are_read_back_live() {
|
||||
}
|
||||
|
||||
/// An envelope that is a symbol's art is written live in the symbol's definition, and the symbol
|
||||
/// opens with it as a live envelope.
|
||||
/// opens with it as a live envelope, its contents where they were.
|
||||
#[test]
|
||||
fn an_envelope_in_a_symbol_is_read_back_live() {
|
||||
use vectorcraft_doc::live::EnvelopeOptions;
|
||||
@@ -10797,15 +10798,103 @@ fn an_envelope_in_a_symbol_is_read_back_live() {
|
||||
let (back, notes) = crate::ai_alone(&p.data).unwrap();
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{name}: {:?}", back.symbols));
|
||||
let mut envelopes = vec![];
|
||||
let mut boxes = vec![];
|
||||
symbol.art.walk(&mut |n| {
|
||||
if let NodeKind::Envelope { kind, .. } = &n.kind {
|
||||
if let NodeKind::Envelope { kind, content, .. } = &n.kind {
|
||||
envelopes.push((**kind).clone());
|
||||
boxes.extend(content.iter().map(|c| c.geometric_bounds()));
|
||||
}
|
||||
});
|
||||
assert!(matches!(envelopes.as_slice(), [k] if same_envelope_kind(&kind, k)), "{name}: {envelopes:?} {notes:?}");
|
||||
let near = |a: Option<Rect>, b: Rect| {
|
||||
a.is_some_and(|a| (a.x0 - b.x0).abs() + (a.y0 - b.y0).abs() + (a.x1 - b.x1).abs() + (a.y1 - b.y1).abs() < 1e-6)
|
||||
};
|
||||
let want = [Rect::new(40.0, 20.0, 100.0, 80.0), Rect::new(100.0, 20.0, 160.0, 80.0)];
|
||||
assert!(boxes.len() == 2 && boxes.iter().zip(want).all(|(a, b)| near(*a, b)), "{name}: {boxes:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient-filled path in the contents of an envelope in a symbol's art opens with its gradient
|
||||
/// where it was on the path.
|
||||
#[test]
|
||||
fn a_gradient_in_an_envelopes_contents_in_a_symbol_keeps_its_place() {
|
||||
use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
let mut art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
let geom = GradientGeom { start: (50.0, 30.0).into(), end: (90.0, 70.0).into(), aspect: 1.0, focal: None };
|
||||
let fill = gradient_paint(sunset(), Some(geom), None);
|
||||
let shaded = painted(&mut doc, shapes::rectangle(Rect::new(40.0, 20.0, 100.0, 80.0)), vec![AppearanceItem::Fill(FillLayer::new(fill))]);
|
||||
if let NodeKind::Envelope { content, .. } = &mut art.kind {
|
||||
content[0] = Arc::new(shaded);
|
||||
}
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) });
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let symbol = back.symbols.iter().find(|s| s.name == "Bent").unwrap_or_else(|| panic!("{:?}", back.symbols));
|
||||
let mut geoms = vec![];
|
||||
symbol.art.walk(&mut |n| {
|
||||
if let NodeKind::Envelope { content, .. } = &n.kind {
|
||||
for c in content {
|
||||
if let Paint::Gradient(g) = c.appearance.fill_paint() {
|
||||
geoms.push(g.geom);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let near = |a: vectorcraft_geom::Point, b: vectorcraft_geom::Point| (a - b).hypot() < 1e-6;
|
||||
assert!(matches!(geoms.as_slice(), [Some(g)] if near(g.start, geom.start) && near(g.end, geom.end)), "{geoms:?}, want {geom:?}");
|
||||
}
|
||||
|
||||
/// The contents of an envelope in a symbol's art are written in the canvas's space with y down:
|
||||
/// about the canvas point of art space's origin.
|
||||
#[test]
|
||||
fn an_envelopes_contents_in_a_symbol_are_written_in_the_canvas_space() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
let art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) });
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let p = program(&doc);
|
||||
let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect();
|
||||
let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]);
|
||||
let def = &p[p.find("%AI14_BeginSymbol\n(Bent)\n").unwrap()..];
|
||||
let block = &def[def.find("%_X=\n").unwrap()..];
|
||||
let moves: Vec<&str> = block.lines().filter_map(|l| l.trim_start_matches("%_").strip_suffix(" m")).collect();
|
||||
// The red square's points are the rectangle 40 20 to 100 80, in the symbol's space.
|
||||
let xs: Vec<f64> = moves.first().unwrap().split(' ').map(|v| v.parse().unwrap()).collect();
|
||||
assert!([40.0, 100.0].iter().any(|x| (xs[0] - (x + ox)).abs() < 1e-6), "{xs:?}, origin {ox} {oy}");
|
||||
assert!([20.0, 80.0].iter().any(|y| (xs[1] - (y + oy)).abs() < 1e-6), "{xs:?}, origin {ox} {oy}");
|
||||
}
|
||||
|
||||
/// The grid of an envelope in a symbol's art is written in the space a gradient mesh's corners are
|
||||
/// written in there: about the canvas point of art space's origin, y up.
|
||||
#[test]
|
||||
fn an_envelopes_grid_in_a_symbol_is_written_about_the_canvas_point_of_the_origin() {
|
||||
use vectorcraft_doc::live::{EnvelopeKind, EnvelopeOptions};
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] };
|
||||
let art = envelope_node(&mut doc, kind, 50.0, false, EnvelopeOptions::NEW);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Bent".into(), art: Arc::new(art) });
|
||||
let instance = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: "Bent".into(), xf: Affine::translate((10.0, 5.0)) });
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), usize::MAX, instance).unwrap();
|
||||
let p = program(&doc);
|
||||
let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect();
|
||||
let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]);
|
||||
let def = &p[p.find("%AI14_BeginSymbol\n(Bent)\n").unwrap()..];
|
||||
let first = def.lines().find(|l| l.ends_with(" /N X#")).unwrap();
|
||||
// The grid's top left point, at 30 10.
|
||||
let want = format!("[0 1 {} {} ", ps::num(30.0 - ox), ps::num(oy - 10.0));
|
||||
assert!(first.trim_start_matches("%_").starts_with(&want), "{first}, want {want}");
|
||||
}
|
||||
|
||||
/// An envelope with an opacity mask comes back live with its mask, and the plugin's `XP` follows
|
||||
/// the envelope's dictionary rather than its mask's art.
|
||||
#[test]
|
||||
@@ -13004,3 +13093,578 @@ fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- gradient meshes ----------
|
||||
|
||||
use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_RIGHT, MeshPoint, grid_points, smooth_handles};
|
||||
|
||||
/// A mesh over `r` of `rows` × `cols` patches: its points on a grid with smooth handles, each
|
||||
/// colored `color(row, col)` and opaque.
|
||||
fn grid_mesh(r: Rect, rows: u32, cols: u32, color: impl Fn(usize, usize) -> Color) -> GradientMesh {
|
||||
let pts = grid_points(r, rows, cols);
|
||||
let handles = smooth_handles(rows, cols, &pts);
|
||||
let width = cols as usize + 1;
|
||||
let points = pts
|
||||
.iter()
|
||||
.zip(handles)
|
||||
.enumerate()
|
||||
.map(|(i, (p, h))| MeshPoint { p: *p, color: color(i / width, i % width), opacity: 1.0, handles: h })
|
||||
.collect();
|
||||
GradientMesh { rows, cols, points }
|
||||
}
|
||||
|
||||
fn mesh_node(doc: &mut Document, m: GradientMesh) -> Node {
|
||||
Node::new(doc.alloc_id(), NodeKind::Mesh(m))
|
||||
}
|
||||
|
||||
/// The gradient meshes in `doc`'s layers, in order (groups and clipping groups included).
|
||||
fn meshes_in(doc: &Document) -> Vec<Arc<Node>> {
|
||||
fn walk(nodes: &[Arc<Node>], out: &mut Vec<Arc<Node>>) {
|
||||
for n in nodes {
|
||||
if matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
out.push(n.clone());
|
||||
} else if let Some(c) = n.children() {
|
||||
walk(c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&doc.layers, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn mesh_of(n: &Node) -> &GradientMesh {
|
||||
match &n.kind {
|
||||
NodeKind::Mesh(m) => m,
|
||||
_ => panic!("not a mesh: {n:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 400 × 400 document with gradient meshes: `Sheet`, 2 × 3 patches over 20 20 200 120, its top row
|
||||
/// of points RGB, its middle row CMYK and its bottom row gray, its middle point moved with handles of
|
||||
/// its own, its top left point's handle to the right bent up, two points part transparent, at 60%
|
||||
/// in Multiply, followed by a path at 80%; a hidden, locked 1 × 1 gray mesh `Shy` in a group `Box`;
|
||||
/// `Masked`, 1 × 2 with an inverted, unlinked opacity mask, knockout shape, isolation and knockout;
|
||||
/// and a mesh in a clipping group.
|
||||
fn meshes_document() -> Document {
|
||||
let mut doc = Document::new(400.0, 400.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut sheet = grid_mesh(Rect::new(20.0, 20.0, 200.0, 120.0), 2, 3, |r, c| match r {
|
||||
0 => Color::rgb(1.0, 0.5 * c as f32 / 3.0, 0.0),
|
||||
1 => Color::cmyk(0.1 * c as f32, 0.6, 0.2, 0.05),
|
||||
_ => Color::gray(0.2 + 0.2 * c as f32),
|
||||
});
|
||||
let middle = &mut sheet.points[5];
|
||||
middle.p += vectorcraft_geom::Vec2::new(7.0, -5.0);
|
||||
middle.handles[H_RIGHT] = vectorcraft_geom::Vec2::new(20.0, 8.0);
|
||||
middle.handles[H_DOWN] = vectorcraft_geom::Vec2::new(-4.0, 12.0);
|
||||
sheet.points[0].handles[H_RIGHT] = vectorcraft_geom::Vec2::new(15.0, -10.0);
|
||||
sheet.points[2].opacity = 0.4;
|
||||
sheet.points[11].opacity = 0.0;
|
||||
let mut sheet = mesh_node(&mut doc, sheet);
|
||||
(sheet.name, sheet.opacity, sheet.blend) = (Some("Sheet".into()), 0.6, BlendMode::Multiply);
|
||||
doc.insert(Some(layer), usize::MAX, sheet).unwrap();
|
||||
let mut after = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(240.0, 20.0, 260.0, 40.0)),
|
||||
Appearance::basic(solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0),
|
||||
);
|
||||
after.opacity = 0.8;
|
||||
doc.insert(Some(layer), usize::MAX, after).unwrap();
|
||||
let mut shy = mesh_node(&mut doc, grid_mesh(Rect::new(20.0, 150.0, 80.0, 190.0), 1, 1, |_, c| Color::gray(0.25 + 0.5 * c as f32)));
|
||||
(shy.name, shy.visible, shy.locked) = (Some("Shy".into()), false, true);
|
||||
let mut group = Node::group(doc.alloc_id(), vec![Arc::new(shy)]);
|
||||
group.name = Some("Box".into());
|
||||
doc.insert(Some(layer), usize::MAX, group).unwrap();
|
||||
let mut masked = mesh_node(&mut doc, grid_mesh(Rect::new(120.0, 150.0, 220.0, 190.0), 1, 2, |r, _| Color::rgb(0.0, 0.3, 0.3 + 0.5 * r as f32)));
|
||||
masked.name = Some("Masked".into());
|
||||
// Knockout shape is a mesh's own; isolation and knockout are a group's.
|
||||
(masked.knockout_shape, masked.isolate, masked.knockout) = (true, true, vectorcraft_doc::Knockout::On);
|
||||
let mask_art = Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(120.0, 150.0, 170.0, 190.0)),
|
||||
Appearance::basic(solid(Color::WHITE), Paint::None, 0.0),
|
||||
);
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(mask_art), clip: true, invert: true, disabled: false, linked: false }));
|
||||
doc.insert(Some(layer), usize::MAX, masked).unwrap();
|
||||
let clip = Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(250.0, 150.0, 350.0, 250.0)), Appearance::default());
|
||||
let inside = mesh_node(&mut doc, grid_mesh(Rect::new(250.0, 150.0, 350.0, 250.0), 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 1.0)));
|
||||
let clipped = Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(inside)], clip: true });
|
||||
doc.insert(Some(layer), usize::MAX, clipped).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
/// How far a coordinate, color channel or opacity written to 4 decimals may move: half the last
|
||||
/// decimal, and a little for the arithmetic.
|
||||
const MESH_ROUNDING: f64 = 5e-5 + 1e-9;
|
||||
|
||||
/// `read` is `want` as written, checked without the writer's own test: the same grid; each point
|
||||
/// within [`MESH_ROUNDING`] of its place along each axis; each handle that points into the grid
|
||||
/// ending within it of where `want`'s ends, and each handle on the mesh's outside edge read as
|
||||
/// none (the reader gives those none, and they draw nothing); each color in the same model with
|
||||
/// each channel within it of `want`'s clamped to 0 to 1; each opacity within it.
|
||||
fn assert_mesh_exact(read: &GradientMesh, want: &GradientMesh, what: &str) {
|
||||
use vectorcraft_doc::live::H_LEFT;
|
||||
use vectorcraft_doc::live::H_UP;
|
||||
assert_eq!((read.rows, read.cols, read.points.len()), (want.rows, want.cols, want.points.len()), "{what}: the grid");
|
||||
let (rows, cols) = (want.rows as usize, want.cols as usize);
|
||||
let close = |a: f64, b: f64| (a - b).abs() <= MESH_ROUNDING;
|
||||
let channels = |c: &Color| -> (u8, Vec<f64>) {
|
||||
match *c {
|
||||
Color::Gray { k } => (0, vec![f64::from(k)]),
|
||||
Color::Rgb { r, g, b } => (1, vec![f64::from(r), f64::from(g), f64::from(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (2, vec![f64::from(c), f64::from(m), f64::from(y), f64::from(k)]),
|
||||
Color::Lab { .. } => (3, vec![]),
|
||||
}
|
||||
};
|
||||
for (i, (a, b)) in read.points.iter().zip(&want.points).enumerate() {
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
assert!(close(a.p.x, b.p.x) && close(a.p.y, b.p.y), "{what}: point {i} at {:?}, want {:?}", a.p, b.p);
|
||||
for (h, inside) in [(H_RIGHT, c < cols), (H_LEFT, c > 0), (H_DOWN, r < rows), (H_UP, r > 0)] {
|
||||
if inside {
|
||||
let (ea, eb) = (a.p + a.handles[h], b.p + b.handles[h]);
|
||||
assert!(close(ea.x, eb.x) && close(ea.y, eb.y), "{what}: point {i}'s handle {h} ends at {ea:?}, want {eb:?}");
|
||||
} else {
|
||||
assert_eq!(a.handles[h], vectorcraft_geom::Vec2::ZERO, "{what}: point {i}'s outside handle {h}");
|
||||
}
|
||||
}
|
||||
let ((ma, ca), (mb, cb)) = (channels(&a.color), channels(&b.color));
|
||||
assert_eq!(ma, mb, "{what}: point {i}'s color model: {:?}, want {:?}", a.color, b.color);
|
||||
assert!(ca.iter().zip(&cb).all(|(x, y)| close(*x, y.clamp(0.0, 1.0))), "{what}: point {i}'s color {:?}, want {:?}", a.color, b.color);
|
||||
assert!(close(f64::from(a.opacity), f64::from(b.opacity.clamp(0.0, 1.0))), "{what}: point {i}'s opacity {}, want {}", a.opacity, b.opacity);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each mesh of `doc` comes back from the editing data alone as a mesh: the same grid, points,
|
||||
/// handles, colors in their own models and opacities ([`assert_mesh_exact`]), name, transparency
|
||||
/// (opacity, blending mode and knockout shape; isolation and knockout are a group's and are written
|
||||
/// off, as for a path), lock and hidden state, and opacity mask (its flags and its art's kind and
|
||||
/// box).
|
||||
fn assert_meshes_read_back(doc: &Document) {
|
||||
let back = read_back(doc);
|
||||
let (ours, theirs) = (meshes_in(doc), meshes_in(&back));
|
||||
assert_eq!(theirs.len(), ours.len(), "{:#?}", back.layers[0]);
|
||||
for (a, b) in ours.iter().zip(&theirs) {
|
||||
assert_mesh_exact(mesh_of(b), mesh_of(a), &format!("{:?}", a.name));
|
||||
assert_eq!((&b.name, b.opacity, b.blend, b.visible, b.locked), (&a.name, a.opacity, a.blend, a.visible, a.locked));
|
||||
// Isolation and knockout are written off (`Xy`); a mesh read keeps a new object's.
|
||||
let fresh = Node::new(b.id, NodeKind::Mesh(mesh_of(b).clone()));
|
||||
assert_eq!((b.knockout_shape, b.isolate, b.knockout), (a.knockout_shape, fresh.isolate, fresh.knockout), "{:?}'s knockout", a.name);
|
||||
match (&a.extras().mask, &b.extras().mask) {
|
||||
(None, None) => {}
|
||||
(Some(ma), Some(mb)) => {
|
||||
assert_eq!((mb.clip, mb.invert, mb.disabled, mb.linked), (ma.clip, ma.invert, ma.disabled, ma.linked), "{:?}'s mask flags", a.name);
|
||||
assert_eq!(std::mem::discriminant(&mb.art.kind), std::mem::discriminant(&ma.art.kind), "{:?}'s mask art", a.name);
|
||||
let (ba, bb) = (ma.art.geometric_bounds().unwrap(), mb.art.geometric_bounds().unwrap());
|
||||
assert!(
|
||||
(ba.x0 - bb.x0).abs() < 1e-3 && (ba.y0 - bb.y0).abs() < 1e-3 && (ba.x1 - bb.x1).abs() < 1e-3 && (ba.y1 - bb.y1).abs() < 1e-3,
|
||||
"{:?}'s mask art box {bb:?}, want {ba:?}",
|
||||
a.name
|
||||
);
|
||||
}
|
||||
(want, got) => panic!("{:?}'s opacity mask: {} read back, want {}", a.name, got.is_some(), want.is_some()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn meshes_are_read_back_as_they_are() {
|
||||
let doc = meshes_document();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::MESHES || w == writer::LIVE), "{:?}", out.warnings);
|
||||
assert_eq!(program(&doc).matches("/Mesh X!\n").count(), 4);
|
||||
assert_meshes_read_back(&doc);
|
||||
let back = read_back(&doc);
|
||||
let art = back.layers[0].children().unwrap();
|
||||
assert_eq!((art[1].opacity, matches!(art[1].kind, NodeKind::Path { .. })), (0.8, true), "the path after the mesh keeps its own opacity");
|
||||
// The moved point keeps its place and handles exactly (to the 4 decimals written).
|
||||
let sheet = mesh_of(&art[0]);
|
||||
assert!((sheet.points[5].p - vectorcraft_geom::Point::new(87.0, 65.0)).hypot() < 1e-4, "{:?}", sheet.points[5].p);
|
||||
assert!((sheet.points[5].handles[H_RIGHT] - vectorcraft_geom::Vec2::new(20.0, 8.0)).hypot() < 1e-4);
|
||||
}
|
||||
|
||||
/// A mesh is `/Mesh X!`, its version (2: corners with an opacity), type and size, `/Data`, each
|
||||
/// patch row by row with its place, the color space where it changes and four corners (from the
|
||||
/// top left point down, right and up: color, opacity, point, the handle towards the next corner and
|
||||
/// the one before it, in art space), `/End X!`; its transparency before it, its name after it, then
|
||||
/// `0 0 Xd` and `6 () XW`. Gray is written as lightness.
|
||||
#[test]
|
||||
fn meshes_are_written_in_their_form() {
|
||||
let doc = meshes_document();
|
||||
let text = program(&doc);
|
||||
let start = text.find("/Mesh X!\n").unwrap();
|
||||
let end = start + text[start..].find("/End X!\n").unwrap() + "/End X!\n".len();
|
||||
let sheet = &text[start..end];
|
||||
assert!(
|
||||
sheet.starts_with("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[2 3] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceRGB /CS X#\n"),
|
||||
"{sheet}"
|
||||
);
|
||||
let places: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /P X#")).collect();
|
||||
assert_eq!(places, ["%_[0 0] /P X#", "%_[0 1] /P X#", "%_[0 2] /P X#", "%_[1 0] /P X#", "%_[1 1] /P X#", "%_[1 2] /P X#"]);
|
||||
// The top left point, at 20 20 (art 20 -20): its handle down a third of the way to the next row,
|
||||
// its handle to the right bent up.
|
||||
let corners: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /N X#")).collect();
|
||||
assert_eq!(corners.len(), 24);
|
||||
assert_eq!(corners[0], "%_[1 0 0 1 20 -20 20 -36.6667 1 35 -10 1] /N X#");
|
||||
// The color space only where it changes.
|
||||
let spaces: Vec<&str> = sheet.lines().filter(|l| l.ends_with(" /CS X#")).collect();
|
||||
assert!(spaces.windows(2).all(|w| w[0] != w[1]), "{spaces:?}");
|
||||
assert!(spaces.contains(&"%_/DeviceCMYK /CS X#") && spaces.contains(&"%_/DeviceGray /CS X#"), "{spaces:?}");
|
||||
// Gray 0.2 of ink is 0.8 of lightness: the bottom left point, the second corner of the second row's first patch.
|
||||
assert!(corners[13].starts_with("%_[0.8 1 20 -120 "), "{}", corners[13]);
|
||||
// Only what the reader reads: no `/R` entries.
|
||||
assert!(!sheet.contains("/R X#"), "{sheet}");
|
||||
// Its transparency before it; its name, then its state block, after it.
|
||||
assert!(text[..start].ends_with("0 XR\n1 0.6 0 0 0 Xy\n"), "{}", &text[start.saturating_sub(80)..start]);
|
||||
let rest = &text[end..];
|
||||
assert!(rest.starts_with("%_/ArtDictionary :\n%_/XMLUID : (Sheet) ; (AI10_ArtUID) ,\n%_;\n%_\n0 0 Xd\n6 () XW\n"), "{}", &rest[..200]);
|
||||
}
|
||||
|
||||
/// A document with meshes is written as the same bytes again, and what the reader reads back is
|
||||
/// written with the same layers.
|
||||
#[test]
|
||||
fn meshes_write_the_same_bytes_again() {
|
||||
let doc = meshes_document();
|
||||
let first = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert_eq!(first.program, export_ai_editing(&doc, &opts()).unwrap().program);
|
||||
let again = String::from_utf8(export_ai_editing(&read_back(&doc), &opts()).unwrap().program).unwrap();
|
||||
let first = String::from_utf8(first.program).unwrap();
|
||||
let (again, first) = (mesh_layer_lines(&again), mesh_layer_lines(&first));
|
||||
let differ = again.iter().zip(&first).enumerate().find(|(_, (a, b))| a != b);
|
||||
assert_eq!(differ, None, "the first line that differs");
|
||||
assert_eq!(again.len(), first.len());
|
||||
}
|
||||
|
||||
/// The lines of the layers, `%AI5_BeginLayer` to the end.
|
||||
fn mesh_layer_lines(program: &str) -> Vec<&str> {
|
||||
program.lines().skip_while(|l| !l.starts_with("%AI5_BeginLayer")).collect()
|
||||
}
|
||||
|
||||
/// A document holding one mesh made by `make`, on a 400 × 400 page.
|
||||
fn mesh_document(make: impl FnOnce(&mut Document) -> Node) -> Document {
|
||||
let mut doc = Document::new(400.0, 400.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let n = make(&mut doc);
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
doc
|
||||
}
|
||||
|
||||
/// Whether `doc` holds a gradient mesh anywhere: on its layers (opacity masks' art included), in a
|
||||
/// symbol's art or in a pattern's tile.
|
||||
fn holds_a_mesh(doc: &Document) -> bool {
|
||||
fn any(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Mesh(_))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| any(&m.art))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| any(c)))
|
||||
}
|
||||
doc.layers.iter().any(|n| any(n)) || doc.symbols.iter().any(|s| any(&s.art)) || doc.patterns.iter().any(|p| p.art.iter().any(|n| any(n)))
|
||||
}
|
||||
|
||||
/// The box and color of each path with a solid fill in `nodes` and what they hold.
|
||||
fn filled_paths(nodes: &[Arc<Node>], out: &mut Vec<(Rect, Color)>) {
|
||||
for n in nodes {
|
||||
if let NodeKind::Path { .. } = n.kind {
|
||||
for item in &n.appearance.items {
|
||||
if let AppearanceItem::Fill(f) = item
|
||||
&& let Paint::Solid { color, .. } = &f.paint
|
||||
&& let Some(b) = n.geometric_bounds()
|
||||
{
|
||||
out.push((b, *color));
|
||||
}
|
||||
}
|
||||
} else if let Some(c) = n.children() {
|
||||
filled_paths(c, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Meshes the reader wouldn't read back as they are, and meshes in places where the writer doesn't
|
||||
/// write them as meshes, are written as their drawn look, with a warning: a point in a Lab color;
|
||||
/// more than 128 rows (129); more than 128 columns (129); a mesh whose points all lie in one place
|
||||
/// (the reader takes its rows for columns); a folded mesh, whose patches turn different ways; a mesh
|
||||
/// in art cut to a clipping object; and a mesh on a large canvas. The drawn look reads back as
|
||||
/// filled paths in more than one color covering the mesh's box, and no mesh.
|
||||
#[test]
|
||||
fn meshes_the_reader_cant_read_are_written_as_their_drawn_look() {
|
||||
let r = Rect::new(20.0, 20.0, 120.0, 120.0);
|
||||
let mut cases: Vec<(&str, Document)> = vec![
|
||||
(
|
||||
"Lab point",
|
||||
mesh_document(|doc| {
|
||||
let mut m = grid_mesh(r, 1, 1, |_, _| Color::rgb(0.2, 0.4, 0.6));
|
||||
m.points[3].color = MINT;
|
||||
mesh_node(doc, m)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"129 rows",
|
||||
mesh_document(|doc| mesh_node(doc, grid_mesh(Rect::new(20.0, 20.0, 120.0, 300.0), 129, 1, |r, _| Color::gray(r as f32 / 129.0)))),
|
||||
),
|
||||
(
|
||||
"129 columns",
|
||||
mesh_document(|doc| mesh_node(doc, grid_mesh(Rect::new(20.0, 20.0, 300.0, 120.0), 1, 129, |_, c| Color::gray(c as f32 / 129.0)))),
|
||||
),
|
||||
(
|
||||
"folded",
|
||||
mesh_document(|doc| {
|
||||
let mut m = grid_mesh(r, 1, 2, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0));
|
||||
// The right column's points fold back over the left patch; the edges are straight.
|
||||
for row in 0..2 {
|
||||
m.points[row * 3 + 2].p = vectorcraft_geom::Point::new(40.0, m.points[row * 3 + 2].p.y);
|
||||
}
|
||||
for p in &mut m.points {
|
||||
p.handles = [vectorcraft_geom::Vec2::ZERO; 4];
|
||||
}
|
||||
mesh_node(doc, m)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"collapsed",
|
||||
mesh_document(|doc| {
|
||||
let mut m = grid_mesh(r, 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 0.0));
|
||||
for p in &mut m.points {
|
||||
(p.p, p.handles) = (vectorcraft_geom::Point::new(50.0, 50.0), [vectorcraft_geom::Vec2::ZERO; 4]);
|
||||
}
|
||||
mesh_node(doc, m)
|
||||
}),
|
||||
),
|
||||
(
|
||||
"art cut to a clipping object",
|
||||
mesh_document(|doc| {
|
||||
let square = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)), Appearance::default());
|
||||
let clipper = Node::group(doc.alloc_id(), vec![Arc::new(square)]);
|
||||
let m = mesh_node(doc, grid_mesh(r, 1, 1, |_, c| Color::rgb(c as f32, 0.0, 0.0)));
|
||||
Node::new(doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clipper), Arc::new(m)], clip: true })
|
||||
}),
|
||||
),
|
||||
];
|
||||
let mut large = Document::new(20000.0, 400.0);
|
||||
let layer = large.layers[0].id;
|
||||
let m = mesh_node(&mut large, grid_mesh(Rect::new(1000.0, 20.0, 1600.0, 320.0), 2, 2, |r, c| Color::rgb(0.5 * r as f32, 0.5 * c as f32, 0.5)));
|
||||
large.insert(Some(layer), usize::MAX, m).unwrap();
|
||||
cases.push(("large canvas", large));
|
||||
let mut failed = vec![];
|
||||
for (name, doc) in &cases {
|
||||
let out = export_ai_editing(doc, &opts()).unwrap();
|
||||
let warned = out.warnings.iter().any(|w| w == writer::MESHES);
|
||||
let written = String::from_utf8(out.program).unwrap();
|
||||
let back = read_back(doc);
|
||||
let mut paths = vec![];
|
||||
filled_paths(&back.layers, &mut paths);
|
||||
let mut want = mesh_of(&meshes_in(doc)[0]).bounds().unwrap();
|
||||
if *name == "art cut to a clipping object" {
|
||||
// Its drawn look is cut to the clipping object.
|
||||
want = want.intersect(Rect::new(20.0, 20.0, 80.0, 80.0));
|
||||
}
|
||||
let got = paths.iter().fold(None, |acc: Option<Rect>, (b, _)| Some(acc.map_or(*b, |a| a.union(*b))));
|
||||
let colors = paths.iter().map(|(_, c)| format!("{c:?}")).collect::<std::collections::HashSet<_>>().len();
|
||||
// The collapsed mesh has no area to cover.
|
||||
let covers = *name == "collapsed"
|
||||
|| got.is_some_and(|g| {
|
||||
(g.x0 - want.x0).abs() < 0.5 && (g.y0 - want.y0).abs() < 0.5 && (g.x1 - want.x1).abs() < 0.5 && (g.y1 - want.y1).abs() < 0.5
|
||||
});
|
||||
if !(warned && !written.contains("/Mesh X!") && !holds_a_mesh(&back) && covers && (*name == "collapsed" || colors > 1)) {
|
||||
failed.push(format!("{name}: warned {warned}, box {got:?} want {want:?}, {colors} colors"));
|
||||
}
|
||||
}
|
||||
assert!(failed.is_empty(), "written as meshes, without a warning or not as their drawn look: {failed:#?}");
|
||||
}
|
||||
|
||||
/// A reflected mesh, mirrored across or along, is written as a mesh with its columns in reverse
|
||||
/// order, without a warning, and reads back as that mesh: each row's points from the last to the
|
||||
/// first, with their handles to the right and left swapped.
|
||||
#[test]
|
||||
fn a_reflected_mesh_is_written_with_its_columns_reversed() {
|
||||
use vectorcraft_doc::live::{H_LEFT, H_RIGHT};
|
||||
let r = Rect::new(20.0, 20.0, 120.0, 120.0);
|
||||
for (name, mirror) in [("across", Affine::new([-1.0, 0.0, 0.0, 1.0, 140.0, 0.0])), ("along", Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 140.0]))] {
|
||||
let mut m = grid_mesh(r, 2, 3, |r, c| Color::rgb(0.5 * r as f32, c as f32 / 3.0, 0.2));
|
||||
m.points[5].p += vectorcraft_geom::Vec2::new(4.0, -3.0);
|
||||
m.points[5].opacity = 0.5;
|
||||
m.transform(mirror);
|
||||
let doc = mesh_document(|doc| mesh_node(doc, m.clone()));
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::MESHES), "{name}: {:?}", out.warnings);
|
||||
let back = meshes_in(&read_back(&doc));
|
||||
assert_eq!(back.len(), 1, "{name}: {back:#?}");
|
||||
let width = m.cols as usize + 1;
|
||||
let mut want = m.clone();
|
||||
want.points = m
|
||||
.points
|
||||
.chunks(width)
|
||||
.flat_map(|row| {
|
||||
row.iter().rev().map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.handles.swap(H_RIGHT, H_LEFT);
|
||||
p
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
assert_mesh_exact(mesh_of(&back[0]), &want, name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Meshes in pattern tiles, a symbol's pattern tile among them, are written as their drawn look with
|
||||
/// a warning: the tile reads back with filled paths and no mesh.
|
||||
#[test]
|
||||
fn meshes_in_pattern_tiles_are_written_as_their_drawn_look() {
|
||||
let tile = |doc: &mut Document| {
|
||||
let m = mesh_node(doc, grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 1, 1, |_, c| Color::rgb(0.5 * c as f32, 0.2, 0.5)));
|
||||
doc.patterns.push(vectorcraft_doc::PatternDef {
|
||||
tile: Rect::new(0.0, 0.0, 60.0, 40.0),
|
||||
..vectorcraft_doc::PatternDef::new("Patches", vec![Arc::new(m)])
|
||||
});
|
||||
Node::path(
|
||||
doc.alloc_id(),
|
||||
shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)),
|
||||
Appearance::basic(Paint::Pattern { pattern: "Patches".into(), xf: Affine::IDENTITY }, Paint::None, 0.0),
|
||||
)
|
||||
};
|
||||
let on_layer = mesh_document(tile);
|
||||
let in_symbol = mesh_document(|doc| {
|
||||
let art = tile(doc);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Tiled".into(), art: Arc::new(art) });
|
||||
instance(doc, "Tiled", Affine::translate((20.0, 20.0)))
|
||||
});
|
||||
for (name, doc) in [("on a layer", &on_layer), ("in a symbol", &in_symbol)] {
|
||||
let out = export_ai_editing(doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::MESHES), "{name}: {:?}", out.warnings);
|
||||
let written = String::from_utf8(out.program).unwrap();
|
||||
assert!(!written.contains("/Mesh X!"), "{name}");
|
||||
// The reader doesn't read a symbol whose art has a pattern fill whole, whatever the tile
|
||||
// holds: the drawn look is checked in the program there.
|
||||
if name == "in a symbol" {
|
||||
assert!(written.contains("%AI3_BeginPattern: (Patches)"), "{name}");
|
||||
continue;
|
||||
}
|
||||
let back = read_back(doc);
|
||||
assert!(!holds_a_mesh(&back), "{name}");
|
||||
let tile = back.patterns.iter().find(|p| p.name == "Patches").unwrap();
|
||||
let mut paths = vec![];
|
||||
filled_paths(&tile.art, &mut paths);
|
||||
assert!(!paths.is_empty(), "{name}: {:#?}", tile.art);
|
||||
}
|
||||
}
|
||||
|
||||
/// Meshes in an opacity mask's art, a symbol's art, an opacity mask in a symbol's art, and a
|
||||
/// symbol's art in a document of several artboards (which moves the canvas's center) are written
|
||||
/// as meshes and come back as meshes.
|
||||
#[test]
|
||||
fn meshes_in_masks_and_symbols_are_read_back() {
|
||||
let r = Rect::new(0.0, 0.0, 60.0, 40.0);
|
||||
let colors = |r: usize, c: usize| Color::rgb(0.5 * c as f32, 0.2, 0.5 * r as f32);
|
||||
let square_with = |doc: &mut Document, fill: Paint| {
|
||||
Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(20.0, 100.0, 180.0, 180.0)), Appearance::basic(fill, Paint::None, 0.0))
|
||||
};
|
||||
let mask_of = |n: &Node| n.extras().mask.as_ref().unwrap().art.clone();
|
||||
// Opacity mask.
|
||||
let doc = mesh_document(|doc| {
|
||||
let m = mesh_node(doc, grid_mesh(Rect::new(20.0, 100.0, 180.0, 180.0), 1, 2, colors));
|
||||
let mut n = square_with(doc, solid(Color::BLACK));
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(m), clip: false, invert: false, disabled: false, linked: true }));
|
||||
n
|
||||
});
|
||||
assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES));
|
||||
let back = read_back(&doc);
|
||||
assert_mesh_exact(mesh_of(&mask_of(&back.layers[0].children().unwrap()[0])), mesh_of(&mask_of(&doc.layers[0].children().unwrap()[0])), "mask");
|
||||
// Symbol, on one artboard and with a second artboard far to the right and below.
|
||||
for boards in [1, 2] {
|
||||
let mut doc = mesh_document(|doc| {
|
||||
let m = mesh_node(doc, grid_mesh(r, 2, 1, colors));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(m) });
|
||||
instance(doc, "Patch", Affine::translate((20.0, 20.0)))
|
||||
});
|
||||
if boards == 2 {
|
||||
let id = doc.artboards[0].id + 1;
|
||||
doc.artboards.push(Artboard { id, rect: Rect::new(3000.0, 2000.0, 3400.0, 2600.0), ..doc.artboards[0].clone() });
|
||||
}
|
||||
assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES));
|
||||
let back = read_back(&doc);
|
||||
let sym = back.symbols.iter().find(|s| s.name == "Patch").unwrap();
|
||||
assert_mesh_exact(mesh_of(&sym.art), mesh_of(&doc.symbols[0].art), &format!("symbol, {boards} artboards"));
|
||||
}
|
||||
// An opacity mask in a symbol's art.
|
||||
let doc = mesh_document(|doc| {
|
||||
let m = mesh_node(doc, grid_mesh(r, 1, 2, colors));
|
||||
let mut n = square_with(doc, solid(Color::BLACK));
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask { art: Arc::new(m), clip: false, invert: false, disabled: false, linked: true }));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Masked".into(), art: Arc::new(n) });
|
||||
instance(doc, "Masked", Affine::translate((20.0, 20.0)))
|
||||
});
|
||||
assert!(!export_ai_editing(&doc, &opts()).unwrap().warnings.iter().any(|w| w == writer::MESHES));
|
||||
let back = read_back(&doc);
|
||||
let sym = back.symbols.iter().find(|s| s.name == "Masked").unwrap();
|
||||
assert_mesh_exact(mesh_of(&mask_of(&sym.art)), mesh_of(&mask_of(&doc.symbols[0].art)), "mask in a symbol");
|
||||
}
|
||||
|
||||
/// In a symbol's art a mesh's corners are written about the canvas point of art space's origin, y
|
||||
/// up, as an image's matrix there is (the template box's center is the canvas's).
|
||||
#[test]
|
||||
fn a_mesh_in_a_symbol_is_written_about_the_canvas_point_of_the_origin() {
|
||||
let doc = mesh_document(|doc| {
|
||||
let m = mesh_node(doc, grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 2, 1, |r, c| Color::rgb(0.5 * c as f32, 0.2, 0.5 * r as f32)));
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Patch".into(), art: Arc::new(m) });
|
||||
instance(doc, "Patch", Affine::translate((20.0, 20.0)))
|
||||
});
|
||||
let p = program(&doc);
|
||||
let t: Vec<f64> = p.lines().find_map(|l| l.strip_prefix("%AI3_TemplateBox: ")).unwrap().split(' ').map(|v| v.parse().unwrap()).collect();
|
||||
let (ox, oy) = (f64::from(CANVAS_SIZE) / 2.0 - t[0], f64::from(CANVAS_SIZE) / 2.0 + t[1]);
|
||||
let def = &p[p.find("%AI14_BeginSymbol\n(Patch)\n").unwrap()..];
|
||||
let first = def.lines().find(|l| l.ends_with(" /N X#")).unwrap();
|
||||
// The top left point, at 0 0: its handle down a third of the way to the next row, its handle
|
||||
// to the right a third of the way to the next column.
|
||||
let want = format!(
|
||||
"%_[0 0.2 0 1 {} {} {} {} 1 {} {} 1] /N X#",
|
||||
ps::num(-ox),
|
||||
ps::num(oy),
|
||||
ps::num(-ox),
|
||||
ps::num(oy - 20.0 / 3.0),
|
||||
ps::num(20.0 - ox),
|
||||
ps::num(oy)
|
||||
);
|
||||
assert_eq!(first, want);
|
||||
}
|
||||
|
||||
/// A mesh eight levels down in art written in place of symbol instances (where deeper art is left
|
||||
/// out) is written as a mesh: it holds no objects of its own. A folded one there is written as its
|
||||
/// drawn look, whose paths hold nothing either.
|
||||
#[test]
|
||||
fn a_mesh_eight_levels_down_is_written_as_a_mesh() {
|
||||
let nested = |fold: bool| {
|
||||
mesh_document(|doc| {
|
||||
let mut m = grid_mesh(Rect::new(0.0, 0.0, 60.0, 40.0), 1, 2, |_, c| Color::rgb(0.5 * c as f32, 0.0, 0.0));
|
||||
if fold {
|
||||
// The right column's points fold back over the left patch.
|
||||
for row in 0..2 {
|
||||
m.points[row * 3 + 2].p.x = 10.0;
|
||||
}
|
||||
}
|
||||
let m = mesh_node(doc, m);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "S0".into(), art: Arc::new(m) });
|
||||
for i in 1..8 {
|
||||
let mut inner = instance(doc, &format!("S{}", i - 1), Affine::IDENTITY);
|
||||
inner.isolate = true;
|
||||
doc.symbols.push(Symbol { dynamic: false, name: format!("S{i}"), art: Arc::new(inner) });
|
||||
}
|
||||
let mut top = instance(doc, "S7", Affine::translate((20.0, 20.0)));
|
||||
top.isolate = true;
|
||||
top
|
||||
})
|
||||
};
|
||||
let folded = nested(true);
|
||||
let out = export_ai_editing(&folded, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w == writer::MESHES), "{:?}", out.warnings);
|
||||
let back = read_back(&folded);
|
||||
let mut paths = vec![];
|
||||
filled_paths(&back.layers, &mut paths);
|
||||
assert!(!holds_a_mesh(&back) && paths.len() > 1, "{:#?}", back.layers);
|
||||
let doc = nested(false);
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(!out.warnings.iter().any(|w| w == writer::MESHES), "{:?}", out.warnings);
|
||||
assert!(mesh_layer_lines(std::str::from_utf8(&out.program).unwrap()).contains(&"/Mesh X!"));
|
||||
let back = meshes_in(&read_back(&doc));
|
||||
let mut want = mesh_of(&doc.symbols[0].art).clone();
|
||||
want.transform(Affine::translate((20.0, 20.0)));
|
||||
assert_eq!(back.len(), 1, "{back:#?}");
|
||||
assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down");
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::ps;
|
||||
mod brushes;
|
||||
mod envelopes;
|
||||
mod images;
|
||||
mod meshes;
|
||||
mod paints;
|
||||
mod styles;
|
||||
mod symbols;
|
||||
@@ -28,6 +29,8 @@ mod variables;
|
||||
pub(super) use brushes::BRUSHES;
|
||||
#[cfg(test)]
|
||||
pub(super) use envelopes::ENVELOPES;
|
||||
#[cfg(test)]
|
||||
pub(super) use meshes::MESHES;
|
||||
pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects};
|
||||
#[cfg(test)]
|
||||
pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance};
|
||||
@@ -56,7 +59,7 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil
|
||||
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";
|
||||
pub(super) const LIVE: &str = "blends, meshes, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const LIVE: &str = "blends, repeats, placed documents and intertwines are written as their art in the editing data for other apps";
|
||||
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
|
||||
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
|
||||
pub(super) const ITEM_TRANSPARENCY: &str =
|
||||
@@ -302,6 +305,9 @@ pub(super) struct Writer<'a> {
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
pub(super) brushes_live: bool,
|
||||
/// Gradient meshes may be written as meshes; false on a large canvas, where they are written as
|
||||
/// their drawn look.
|
||||
pub(super) meshes_live: bool,
|
||||
/// The object just written is an envelope's distorted art, which the plugin's `XP` follows
|
||||
/// ([`Self::envelope`]).
|
||||
deform: bool,
|
||||
@@ -393,6 +399,7 @@ impl<'a> Writer<'a> {
|
||||
wrap_moved: false,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
meshes_live: true,
|
||||
deform: false,
|
||||
checks_left: crate::import::ENVELOPE_CHECKS,
|
||||
objects: 0,
|
||||
@@ -721,6 +728,11 @@ impl<'a> Writer<'a> {
|
||||
return self.styled_object(n, &orig, &name);
|
||||
}
|
||||
self.effects(n);
|
||||
// A gradient mesh the reader reads as it is; else it is written as its drawn look.
|
||||
let mut mesh = match &n.kind {
|
||||
NodeKind::Mesh(m) => self.mesh_record(m),
|
||||
_ => None,
|
||||
};
|
||||
self.state(n.locked, !n.visible);
|
||||
let mut xy = Xy::of(n);
|
||||
if masked_warp_pieces(n) {
|
||||
@@ -736,6 +748,11 @@ impl<'a> Writer<'a> {
|
||||
let charged = self.charges();
|
||||
match &n.kind {
|
||||
NodeKind::Layer { .. } => {}
|
||||
NodeKind::Mesh(_) if mesh.is_some() => {
|
||||
if let Some(record) = mesh.take() {
|
||||
self.write_mesh(&record, xy);
|
||||
}
|
||||
}
|
||||
NodeKind::Group { children, clip: true } => self.clip_group(children, xy),
|
||||
NodeKind::Group { children, clip: false } => {
|
||||
if self.open_group("u") {
|
||||
@@ -838,7 +855,8 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
NodeKind::Envelope { .. } if self.envelope(n, xy) => {}
|
||||
NodeKind::Envelope { .. } => self.drawn_art(n, xy, Some(envelopes::ENVELOPES), true),
|
||||
NodeKind::Blend { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
NodeKind::Mesh(_) => self.drawn_art(n, xy, Some(meshes::MESHES), true),
|
||||
NodeKind::Blend { .. } | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => {
|
||||
self.drawn_art(n, xy, Some(LIVE), true);
|
||||
}
|
||||
// Ruler guides are kept in the document's native copy only.
|
||||
@@ -917,7 +935,8 @@ impl<'a> Writer<'a> {
|
||||
self.warn(w);
|
||||
}
|
||||
let moved = bounds && self.wrap_on_bounds(n, state);
|
||||
if self.nest < MAX_NEST {
|
||||
// A gradient mesh's drawn look is paths, which hold nothing: it is written at any depth.
|
||||
if self.nest < MAX_NEST || matches!(n.kind, NodeKind::Mesh(_)) {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! Contents (`AIDeformEditModeKey`), a warp's style, bend, distortions and orientation
|
||||
//! (`DeformStyle`, `DeformValue`, `DeformHoriz`, `DeformVert`, `Rotate`), with Distort Appearance
|
||||
//! the size of the box the contents map from (`AIDeformArtWidthKey`, `AIDeformArtHeightKey`), the
|
||||
//! contents in an `X=` … `X+` block (while they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! contents in an `X=` … `X+` block (in a symbol's art, in the canvas's space with y down; while
|
||||
//! they are edited, the grid) as `AIDeformArtKey`, and the
|
||||
//! kind (`AIDeformStyle`: 1 a warp, 2 a mesh, 3 a top object); then the distorted art on plain
|
||||
//! lines, and the plugin's `XP` after it. A top object's outline is the edge of the grid written
|
||||
//! for it, one grid edge to each segment of its sides, a side with fewer segments than the side
|
||||
@@ -401,7 +402,13 @@ impl Writer<'_> {
|
||||
if *editing {
|
||||
self.grid(record.grid.as_ref());
|
||||
} else if self.open_group("u") {
|
||||
// In a symbol's art, the contents in the dictionary are in the canvas's space, y down.
|
||||
let to_art = self.to_art;
|
||||
if self.in_symbol {
|
||||
self.to_art = Affine::translate(self.canvas_origin) * to_art;
|
||||
}
|
||||
self.contents(content, true);
|
||||
self.to_art = to_art;
|
||||
self.end_group("U", Xy::PLAIN);
|
||||
}
|
||||
let block = std::mem::replace(&mut self.body, outer);
|
||||
@@ -448,15 +455,17 @@ impl Writer<'_> {
|
||||
/// An envelope's grid, when it has one, as a gray gradient mesh (`/Mesh X!` … `/End X!`): its
|
||||
/// size (`[cols rows] /Size`), then each patch's place (`[col row] /P`), its four corners
|
||||
/// (`/N`: gray, opacity, the point, the handle towards the next corner and a weight, the handle
|
||||
/// towards the previous one and a weight, in art space), from its top left one down, across and
|
||||
/// up, and `/E`. One object.
|
||||
/// towards the previous one and a weight, in art space; in a symbol's art, in the space a
|
||||
/// gradient mesh's corners are written in there), from its top left one down, across and up,
|
||||
/// and `/E`. One object.
|
||||
fn grid(&mut self, grid: Option<&(usize, usize, Vec<GridPoint>)>) {
|
||||
let Some((rows, cols, pts)) = grid else { return };
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
let (rows, cols, width) = (*rows, *cols, cols + 1);
|
||||
let to_art = self.to_art;
|
||||
// In a symbol's art, corners are written in the space a gradient mesh's are written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
let s = &mut self.body;
|
||||
let _ = writeln!(s, "/Mesh X!\n2 /Version X#\n/Cartesian /Type X#\n[{cols} {rows}] /Size X#\n/Data X#\n/DeviceGray /CS X#");
|
||||
let num = |s: &mut String, v: f64| {
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Gradient meshes: a mesh as the `.ai` reader reads one ([`crate::import`]'s `.ai` reader,
|
||||
//! `mesh.rs` and `read/art.rs`' `end_mesh`).
|
||||
//!
|
||||
//! `/Mesh X!`, then on `%_` lines `value /key X#` entries: `2 /Version` (corners with an opacity),
|
||||
//! `/Cartesian /Type`, `[rows cols] /Size`, `/Data` (the patches follow), and for each patch, row by
|
||||
//! row, its place `[row col] /P`, the color space (`/DeviceGray`,
|
||||
//! `/DeviceRGB` or `/DeviceCMYK`) with `/CS` where it changes, its four corners with `/N` and `/E`;
|
||||
//! then `/End X!`. A corner is `[color… opacity x y nx ny 1 px py 1]` in art space (in a symbol's
|
||||
//! art, in the canvas's space turned y up about art space's origin there, as an image's matrix in
|
||||
//! it is): its color (gray as lightness), its opacity, the point, the
|
||||
//! handle towards the next corner and the handle towards the one before it, each with a weight of 1.
|
||||
//! The corners go from the patch's top left mesh point to the one below it, then to the right, then
|
||||
//! up: the first index of `/P` runs along the first edge. The mesh's transparency is set before it
|
||||
//! (`0 XR`, `Xy`), its name and opacity mask follow `/End X!` in an `/ArtDictionary`, then `0 0 Xd`
|
||||
//! and `6 () XW`.
|
||||
//!
|
||||
//! Each mesh is checked with the reader's own reading ([`crate::import::mesh_reads`]) before it is
|
||||
//! written: one the reader would read otherwise is written as its drawn look, as are folded meshes
|
||||
//! (patches that turn different ways, or a patch with no area), meshes in pattern tiles and in art
|
||||
//! cut to a clipping object, and every mesh on a large canvas. A reflected mesh, whose patches all
|
||||
//! turn the negative way, is written with its columns in reverse order.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_doc::live::{GradientMesh, H_DOWN, H_LEFT, H_RIGHT, H_UP, MeshPoint};
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
|
||||
use super::{Writer, Xy};
|
||||
use crate::ai_ops::unit;
|
||||
use crate::import::{MAX_MESH_SIDE, mesh_reads};
|
||||
use crate::ps;
|
||||
|
||||
pub(in crate::ai_editing) const MESHES: &str = "gradient meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes that would not open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every gradient mesh on a large canvas are written as their drawn look in the editing data for other apps";
|
||||
|
||||
/// How far (in the document's units, at a scale of 1) a written point or handle's end may move:
|
||||
/// coordinates are written to 4 decimals, which moves a point at most 0.00005 along each axis.
|
||||
const SETTLE_POINT: f64 = 1e-4;
|
||||
/// How far a written color channel or opacity may move: they are written to 4 decimals too.
|
||||
const SETTLE_COLOR: f32 = 1e-4;
|
||||
|
||||
/// The color space a corner's color is written in.
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum Space {
|
||||
Gray,
|
||||
Rgb,
|
||||
Cmyk,
|
||||
}
|
||||
|
||||
impl Space {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Space::Gray => "/DeviceGray",
|
||||
Space::Rgb => "/DeviceRGB",
|
||||
Space::Cmyk => "/DeviceCMYK",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
/// Mesh `m`'s record as the reader reads it, or `None` when it would read it otherwise (the
|
||||
/// mesh is then written as its drawn look).
|
||||
pub(super) fn mesh_record(&self, m: &GradientMesh) -> Option<String> {
|
||||
// Art cut to a clipping object is written cut, which a mesh can't be. Meshes in pattern
|
||||
// tiles and on a large canvas are written as their drawn look too. (A mesh holds no objects,
|
||||
// so it is written as a mesh however deep it is nested.) A grid the reader doesn't read as
|
||||
// one mesh is left before its record is built.
|
||||
if !self.meshes_live
|
||||
|| self.clip.is_some()
|
||||
|| !self.defining.is_empty()
|
||||
|| !m.is_valid()
|
||||
|| m.rows as usize > MAX_MESH_SIDE
|
||||
|| m.cols as usize > MAX_MESH_SIDE
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// In a symbol's art, corners are written in the space an image's matrix is written in there.
|
||||
let to_art = if self.in_symbol { self.instance_space } else { self.to_art };
|
||||
// Every patch turns the positive way where it is written: from its first corner, the second
|
||||
// (below it) then the fourth (beside it) go anticlockwise, y up. A reflected mesh, whose
|
||||
// patches all turn the other way, is written with its columns in reverse order, which turns
|
||||
// each of them the positive way and draws the same mesh; any other mesh with a patch that
|
||||
// doesn't turn the positive way is written as its drawn look.
|
||||
let reversed;
|
||||
let m = match turns(m, to_art)? {
|
||||
true => m,
|
||||
false => {
|
||||
reversed = columns_reversed(m);
|
||||
&reversed
|
||||
}
|
||||
};
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c);
|
||||
// Version 2: each corner has an opacity.
|
||||
let mut s = String::from("/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n");
|
||||
let _ = writeln!(s, "%_[{rows} {cols}] /Size X#\n%_/Data X#");
|
||||
let mut space = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let _ = writeln!(s, "%_[{r} {c}] /P X#");
|
||||
// From the top left point down, right and up; each with its handles towards the
|
||||
// next corner and the one before it.
|
||||
for (p, next, prev) in
|
||||
[(at(r, c)?, H_DOWN, H_RIGHT), (at(r + 1, c)?, H_RIGHT, H_UP), (at(r + 1, c + 1)?, H_UP, H_LEFT), (at(r, c + 1)?, H_LEFT, H_DOWN)]
|
||||
{
|
||||
corner(&mut s, &mut space, to_art, p, next, prev)?;
|
||||
}
|
||||
s.push_str("%_/E X#\n");
|
||||
}
|
||||
}
|
||||
s.push_str("/End X!\n");
|
||||
let read = mesh_reads(s.as_bytes(), to_art.inverse())?;
|
||||
same_mesh(&read, m, SETTLE_POINT * to_art.inverse().determinant().abs().sqrt().max(1.0)).then_some(s)
|
||||
}
|
||||
|
||||
/// Mesh `n` written as `record`: its transparency before it (`xy`), the record, and the block
|
||||
/// its name and opacity mask go before ([`Self::node`]). The mesh is one object
|
||||
/// ([`Self::take_objects`]); nothing is written when there is no room for it.
|
||||
pub(super) fn write_mesh(&mut self, record: &str, xy: Xy) {
|
||||
if !self.take_objects(1) {
|
||||
return;
|
||||
}
|
||||
self.set_object_xy(xy.object());
|
||||
self.body.push_str(record);
|
||||
self.block_start = self.body.len();
|
||||
self.line("0 0 Xd\n6 () XW");
|
||||
self.block_end = self.body.len();
|
||||
}
|
||||
}
|
||||
|
||||
/// Which way every patch of `m` turns where `to_art` takes it, from its top left point to the one
|
||||
/// below it then to the one beside it, y up: `Some(true)` when all turn anticlockwise,
|
||||
/// `Some(false)` when all turn clockwise, and `None` when they differ or one has no area.
|
||||
fn turns(m: &GradientMesh, to_art: Affine) -> Option<bool> {
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let at = |r: usize, c: usize| m.points.get(r * (cols + 1) + c).map(|p| to_art * p.p);
|
||||
let mut way = None;
|
||||
for r in 0..rows {
|
||||
for c in 0..cols {
|
||||
let (a, b, d) = (at(r, c)?, at(r + 1, c)?, at(r, c + 1)?);
|
||||
let cross = (b - a).cross(d - a);
|
||||
let positive = match cross {
|
||||
x if x > 0.0 => true,
|
||||
x if x < 0.0 => false,
|
||||
_ => return None,
|
||||
};
|
||||
if *way.get_or_insert(positive) != positive {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
way
|
||||
}
|
||||
|
||||
/// `m` with its columns in reverse order: each row's points from the last to the first, each
|
||||
/// point's handles to the right and left swapped. It draws the same mesh.
|
||||
fn columns_reversed(m: &GradientMesh) -> GradientMesh {
|
||||
let width = m.cols as usize + 1;
|
||||
let points = m
|
||||
.points
|
||||
.chunks(width)
|
||||
.flat_map(|row| {
|
||||
row.iter().rev().map(|p| {
|
||||
let mut p = p.clone();
|
||||
p.handles.swap(H_RIGHT, H_LEFT);
|
||||
p
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
GradientMesh { rows: m.rows, cols: m.cols, points }
|
||||
}
|
||||
|
||||
/// A corner `p` of a patch: its color space when it changes (in `space`), then `[color… opacity x y
|
||||
/// nx ny 1 px py 1] /N X#` with its handles `next` and `prev`, `to_art` taking the document to the
|
||||
/// space the corners are written in.
|
||||
fn corner(s: &mut String, space: &mut Option<Space>, to_art: Affine, p: &MeshPoint, next: usize, prev: usize) -> Option<()> {
|
||||
let (sp, values): (Space, Vec<f32>) = match p.color {
|
||||
// The format's gray is lightness.
|
||||
Color::Gray { k } => (Space::Gray, vec![1.0 - unit(k)]),
|
||||
Color::Rgb { r, g, b } => (Space::Rgb, vec![unit(r), unit(g), unit(b)]),
|
||||
Color::Cmyk { c, m, y, k } => (Space::Cmyk, vec![unit(c), unit(m), unit(y), unit(k)]),
|
||||
// The reader reads no Lab mesh colors.
|
||||
Color::Lab { .. } => return None,
|
||||
};
|
||||
if *space != Some(sp) {
|
||||
let _ = writeln!(s, "%_{} /CS X#", sp.name());
|
||||
*space = Some(sp);
|
||||
}
|
||||
let art = |q: Point| to_art * q;
|
||||
let (at, n, b) = (art(p.p), art(p.p + *p.handles.get(next)?), art(p.p + *p.handles.get(prev)?));
|
||||
s.push_str("%_[");
|
||||
for v in values {
|
||||
ps::push_num(s, f64::from(v));
|
||||
s.push(' ');
|
||||
}
|
||||
ps::push_num(s, f64::from(unit(p.opacity)));
|
||||
for v in [at.x, at.y, n.x, n.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1");
|
||||
for v in [b.x, b.y] {
|
||||
s.push(' ');
|
||||
ps::push_num(s, v);
|
||||
}
|
||||
s.push_str(" 1] /N X#\n");
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether `read` is `m` as written: the same grid, each point within `tol` of its place, each
|
||||
/// handle that points into the grid within `tol` (the reader gives the others none, and they draw
|
||||
/// nothing), each color in the same model and within [`SETTLE_COLOR`] a channel, and each opacity
|
||||
/// within it.
|
||||
fn same_mesh(read: &GradientMesh, m: &GradientMesh, tol: f64) -> bool {
|
||||
if (read.rows, read.cols) != (m.rows, m.cols) || read.points.len() != m.points.len() {
|
||||
return false;
|
||||
}
|
||||
let (rows, cols) = (m.rows as usize, m.cols as usize);
|
||||
let near = |a: Point, b: Point| (a - b).hypot() <= tol * (1.0 + 1e-9 * a.to_vec2().hypot());
|
||||
read.points.iter().zip(&m.points).enumerate().all(|(i, (a, b))| {
|
||||
let (r, c) = (i / (cols + 1), i % (cols + 1));
|
||||
let inside = [c < cols, c > 0, r < rows, r > 0];
|
||||
let handles = [H_RIGHT, H_LEFT, H_DOWN, H_UP].iter().zip(inside).all(|(&h, inside)| {
|
||||
!inside || near(a.p + a.handles.get(h).copied().unwrap_or(Vec2::ZERO), b.p + b.handles.get(h).copied().unwrap_or(Vec2::ZERO))
|
||||
});
|
||||
near(a.p, b.p) && handles && same_color(&a.color, &b.color) && (a.opacity - unit(b.opacity)).abs() <= SETTLE_COLOR
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `a` is `b` as written: the same model, each channel within [`SETTLE_COLOR`] of `b`'s
|
||||
/// clamped to 0 to 1.
|
||||
fn same_color(a: &Color, b: &Color) -> bool {
|
||||
let close = |x: &[f32], y: &[f32]| x.iter().zip(y).all(|(x, y)| (x - unit(*y)).abs() <= SETTLE_COLOR);
|
||||
match (a, b) {
|
||||
(Color::Gray { k }, Color::Gray { k: k2 }) => close(&[*k], &[*k2]),
|
||||
(Color::Rgb { r, g, b }, Color::Rgb { r: r2, g: g2, b: b2 }) => close(&[*r, *g, *b], &[*r2, *g2, *b2]),
|
||||
(Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c2, m: m2, y: y2, k: k2 }) => close(&[*c, *m, *y, *k], &[*c2, *m2, *y2, *k2]),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -91,8 +91,8 @@ pub use ai::NameEncoding;
|
||||
pub(crate) use ai::objects_read;
|
||||
pub(crate) use ai::{
|
||||
BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, read_art_style, read_brush_object,
|
||||
read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads,
|
||||
read_art_style, read_brush_object, read_style_list, style_moves_with, symbol_art_member, warp_number,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN};
|
||||
|
||||
@@ -42,6 +42,7 @@ pub(crate) use envelope::{GridPoint as EnvelopeGridPoint, PLUGIN as DEFORM_PLUGI
|
||||
pub(crate) use envelope::{MAX_ANY as ENVELOPE_MAX_ANY, MAX_SOLID as ENVELOPE_MAX_SOLID};
|
||||
pub(crate) use envelope::{WARPED_TYPE_DRAWN, WarpedType};
|
||||
pub(crate) use frames::text_frames;
|
||||
pub(crate) use mesh::{MAX_SIDE as MAX_MESH_SIDE, mesh_reads};
|
||||
pub use obj::{NameEncoding, Names};
|
||||
pub(crate) use paint::MAX_STOPS as MAX_GRADIENT_STOPS;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -25,7 +25,7 @@ const MAX_PATCHES: usize = 16_384;
|
||||
const MAX_POINTS: usize = MAX_PATCHES * 16;
|
||||
|
||||
/// The largest grid `/Size` read as one mesh, a side.
|
||||
const MAX_SIDE: usize = 128;
|
||||
pub(crate) const MAX_SIDE: usize = 128;
|
||||
/// The most inks of an `/NChannel` colour space read.
|
||||
const MAX_INKS: usize = 32;
|
||||
/// The most rows or columns a mesh stitched from its patches may have once the lines through the
|
||||
@@ -556,6 +556,14 @@ impl Path {
|
||||
|
||||
/// `a` towards `b` by `t`, in their own colour model where they share one.
|
||||
fn mix(a: &Color, b: &Color, t: f32) -> Color {
|
||||
// At either end, that end's own color in its own model: a mesh point of a patch whose corners
|
||||
// differ in model keeps its color.
|
||||
if t <= 0.0 {
|
||||
return *a;
|
||||
}
|
||||
if t >= 1.0 {
|
||||
return *b;
|
||||
}
|
||||
let l = |x: f32, y: f32| x + (y - x) * t;
|
||||
match (a, b) {
|
||||
(Color::Rgb { r, g, b: bl }, Color::Rgb { r: r2, g: g2, b: b2 }) => Color::rgb(l(*r, *r2), l(*g, *g2), l(*bl, *b2)),
|
||||
@@ -565,6 +573,51 @@ fn mix(a: &Color, b: &Color, t: f32) -> Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most values one entry of [`mesh_reads`]' record holds (a corner of [`MAX_INKS`] inks has
|
||||
/// 41).
|
||||
const MAX_ENTRY: usize = 64;
|
||||
|
||||
/// The gradient mesh the reader reads from `record`, a mesh's lines (`/Mesh X!` … `/End X!`,
|
||||
/// entries on `%_` lines or not), with `to_doc` taking art space to the document: one mesh, or
|
||||
/// `None` where the reader would read none or a group of its patches.
|
||||
pub(crate) fn mesh_reads(record: &[u8], to_doc: Affine) -> Option<GradientMesh> {
|
||||
use super::lex::{Lexer, Tok};
|
||||
let mut lex = Lexer::new(record);
|
||||
let mut m: Option<MeshReader> = None;
|
||||
let mut stack: Vec<V> = vec![];
|
||||
let mut marks: Vec<usize> = vec![];
|
||||
while let Some(t) = lex.next_token() {
|
||||
match t.tok {
|
||||
Tok::Num(v) => stack.push(V::Num(v)),
|
||||
Tok::Name(n) => stack.push(V::Name(super::obj::text(n))),
|
||||
Tok::Str(s) | Tok::Hex(s) => stack.push(V::Str(s)),
|
||||
Tok::Word(b"[") => marks.push(stack.len()),
|
||||
Tok::Word(b"]") => {
|
||||
let at = marks.pop()?;
|
||||
let items = stack.split_off(at.min(stack.len()));
|
||||
stack.push(V::Arr(items));
|
||||
}
|
||||
Tok::Word(b"X!") => match (stack.last().and_then(V::text).as_deref(), m.take()) {
|
||||
(Some("Mesh"), None) => m = Some(MeshReader::default()),
|
||||
(Some("End"), Some(read)) => {
|
||||
if read.unread || read.patches.is_empty() {
|
||||
return None;
|
||||
}
|
||||
return read.one_mesh().ok();
|
||||
}
|
||||
_ => return None,
|
||||
},
|
||||
Tok::Word(b"X#") => m.as_mut()?.entry(&std::mem::take(&mut stack), to_doc),
|
||||
Tok::Comment(_) => {}
|
||||
_ => return None,
|
||||
}
|
||||
if stack.len() > MAX_ENTRY {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -885,6 +938,51 @@ mod tests {
|
||||
assert!(!reader.unread && reader.patches[0].points[0].color == Color::gray(1.0));
|
||||
}
|
||||
|
||||
/// `/Version` and `/Data` entries, before or after the patches, are passed over: corners with
|
||||
/// and without an opacity are read by their count of values either way.
|
||||
#[test]
|
||||
fn version_and_data_entries_are_passed_over() {
|
||||
for (with_opacity, data_first) in [(true, true), (false, true), (true, false), (false, false)] {
|
||||
let mut reader = MeshReader::default();
|
||||
for (value, key) in [(V::Name("Cartesian".into()), "Type"), (nums(&[1.0, 1.0]), "Size")] {
|
||||
reader.entry(&[value, V::Name(key.into())], Affine::IDENTITY);
|
||||
}
|
||||
if data_first {
|
||||
reader.entry(&[V::Num(2.0), V::Name("Version".into())], Affine::IDENTITY);
|
||||
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
|
||||
}
|
||||
reader.entry(&[nums(&[0.0, 0.0]), V::Name("P".into())], Affine::IDENTITY);
|
||||
let colors: [&[f64]; 4] =
|
||||
if with_opacity { [&[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25], &[0.5, 0.25]] } else { [&[0.5], &[0.5], &[0.5], &[0.5]] };
|
||||
square(&mut reader, colors, Default::default());
|
||||
if !data_first {
|
||||
reader.entry(&[V::Name("Data".into())], Affine::IDENTITY);
|
||||
reader.entry(&[V::Num(1.0), V::Name("Version".into())], Affine::IDENTITY);
|
||||
}
|
||||
assert!(!reader.unread, "{with_opacity} {data_first}");
|
||||
let mesh = reader.one_mesh().unwrap();
|
||||
let want = if with_opacity { 0.25 } else { 1.0 };
|
||||
assert!(mesh.points.iter().all(|p| p.opacity == want), "{with_opacity} {data_first}: {mesh:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A patch whose corners differ in color space keeps each corner's color in its own model when
|
||||
/// the patches are stitched into one mesh.
|
||||
#[test]
|
||||
fn stitched_corners_keep_their_own_color_models() {
|
||||
let cs = |n: &str| (V::Name(n.into()), "CS");
|
||||
let mut reader = MeshReader::default();
|
||||
let first = vec![(nums(&[1.0, 1.0]), "Size"), (nums(&[0.0, 0.0]), "P"), cs("DeviceRGB")];
|
||||
square(
|
||||
&mut reader,
|
||||
[&[1.0, 0.0, 0.0], &[0.25], &[0.0, 1.0, 0.0, 0.0], &[0.0, 0.0, 1.0]],
|
||||
[first, vec![cs("DeviceGray")], vec![cs("DeviceCMYK")], vec![cs("DeviceRGB")]],
|
||||
);
|
||||
let mesh = reader.one_mesh().unwrap();
|
||||
let colors: Vec<Color> = mesh.points.iter().map(|p| p.color).collect();
|
||||
assert_eq!(colors, [Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0), Color::gray(0.75), Color::cmyk(0.0, 1.0, 0.0, 0.0)]);
|
||||
}
|
||||
|
||||
/// A named colour (`[c m y k /DeviceCMYK (name) /Process]`) paints at each corner's tint, 1 its
|
||||
/// full colour; `/NChannel` inks overprint at their tints. Ones that don't add up stay unread.
|
||||
#[test]
|
||||
|
||||
@@ -97,7 +97,9 @@
|
||||
//! have is the object's own appearance, not a link.
|
||||
//!
|
||||
//! - Symbols: `%AI14_BeginSymbol` (or `%AI10_`), `(name)`, `0 A 0 Xw 0 Ae`, the art (in the
|
||||
//! symbol's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
|
||||
//! symbol's space, y down; an image's matrix and a gradient mesh's corners in the canvas's space
|
||||
//! turned y up about art space's origin there, an envelope's contents in its dictionary in the
|
||||
//! canvas's space, y down), a dictionary whose `AI13PatternRegistrationType` is the registration
|
||||
//! point (1 to 9, from the top left, row by row), `%AI10_EndSymbol`; each is read by a reader of
|
||||
//! its own into the document's symbols. `%AI24_BeginSymbolList` (or `%AI10_`) lists their names
|
||||
//! in the Symbols panel's order. An instance: `/SymbolInstance : (name) /SymbolRef , a b c d tx
|
||||
|
||||
@@ -277,6 +277,18 @@ impl<'a> Reader<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A gradient mesh's `X#` entry `vals`. In a symbol's art, corners are in the space an image's
|
||||
/// matrix is in there; a mesh there in a file that doesn't say where the canvas is is unread.
|
||||
pub(super) fn mesh_entry(&mut self, vals: &[V]) {
|
||||
let to_doc = self.image_space();
|
||||
if let Some((m, _)) = self.mesh.as_mut() {
|
||||
match to_doc {
|
||||
Some(to_doc) => m.entry(vals, to_doc),
|
||||
None => m.unread = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `/End X!`: the gradient mesh read, as one object.
|
||||
pub(super) fn end_mesh(&mut self) -> Result<(), String> {
|
||||
let Some((m, hidden)) = self.mesh.take() else { return Ok(()) };
|
||||
@@ -351,11 +363,15 @@ impl<'a> Reader<'a> {
|
||||
pub(super) fn set_instance(&mut self, i: &Instance) {
|
||||
let mut to_doc = self.space();
|
||||
// In a pattern's definition a gradient's `Xm` and `Bm` are written y down about the canvas point of art space's
|
||||
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are.
|
||||
// origin, as the file's PDF part draws them; in a symbol's, as the instances in its art are, an envelope's
|
||||
// contents' included (which `space` moves alone).
|
||||
if (self.pattern.is_some() || self.symbol.is_some())
|
||||
&& i.has_matrix()
|
||||
&& let Some(t) = self.template
|
||||
{
|
||||
if self.pattern.is_none() && !self.envelope_blocks.is_empty() {
|
||||
to_doc = Affine::IDENTITY;
|
||||
}
|
||||
let (cx, cy) = ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0);
|
||||
to_doc *= Affine::new([1.0, 0.0, 0.0, -1.0, CANVAS_CENTRE - cx, CANVAS_CENTRE + cy]);
|
||||
}
|
||||
|
||||
@@ -923,12 +923,17 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// Art space → where the art being read goes: the document, or while a pattern's definition is
|
||||
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space.
|
||||
/// read, the pattern's space (y down). A symbol's definition is written in the symbol's space,
|
||||
/// except an envelope's contents in its dictionary (its `AIDeformArtKey` block), which are in the
|
||||
/// canvas's space, y down (in the symbol's space in a file without a template box).
|
||||
pub(crate) fn space(&mut self) -> Affine {
|
||||
if self.pattern.is_some() {
|
||||
FLIP
|
||||
} else if self.symbol.is_some() {
|
||||
Affine::IDENTITY
|
||||
match self.canvas_origin() {
|
||||
Some(o) if !self.envelope_blocks.is_empty() => Affine::translate(-o.to_vec2()),
|
||||
_ => Affine::IDENTITY,
|
||||
}
|
||||
} else {
|
||||
self.ensure_space()
|
||||
}
|
||||
|
||||
@@ -226,10 +226,7 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
("X!", Some("End")) if self.mesh.is_some() => return self.end_mesh(),
|
||||
("X#", _) => {
|
||||
let to_doc = self.space();
|
||||
if let Some((m, _)) = self.mesh.as_mut() {
|
||||
m.entry(&vals, to_doc);
|
||||
}
|
||||
self.mesh_entry(&vals);
|
||||
return Ok(());
|
||||
}
|
||||
_ if self.mesh.is_some() => return Ok(()),
|
||||
|
||||
@@ -5251,6 +5251,39 @@ fn an_image_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
assert_eq!(r.unread.len(), 1, "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mesh_in_a_symbols_art_is_placed_from_the_canvas() {
|
||||
// The template box's center is (100.5, 50.5): art space's origin is at canvas (8091, 8242). A
|
||||
// mesh's corners in a symbol's art are in the canvas's space turned y up about that point, as an
|
||||
// image's matrix there is: (-8096, 8244.5) is (-5, -2.5) in the symbol's art.
|
||||
let corners: String = [(-8096.0, 8244.5), (-8096.0, 8239.5), (-8086.0, 8239.5), (-8086.0, 8244.5)]
|
||||
.iter()
|
||||
.map(|(x, y)| format!("%_[0.5 1 {x} {y} {x} {y} 1 {x} {y} 1] /N X#\n"))
|
||||
.collect();
|
||||
let mesh = format!(
|
||||
"/Mesh X!\n%_2 /Version X#\n%_/Cartesian /Type X#\n%_[1 1] /Size X#\n%_/Data X#\n%_[0 0] /P X#\n%_/DeviceGray /CS X#\n{corners}%_/E X#\n/End X!\n"
|
||||
);
|
||||
let doc = read_ok(&format!("%AI3_TemplateBox: 100.5 50.5 100.5 50.5\n{}{}", symbols(&symbol("Patch", &mesh, 5)), layer(""))).doc;
|
||||
assert_eq!(doc.symbols.len(), 1);
|
||||
let mut found = vec![];
|
||||
let mut stack = vec![doc.symbols[0].art.clone()];
|
||||
while let Some(n) = stack.pop() {
|
||||
match &n.kind {
|
||||
NodeKind::Mesh(m) => found.push(m.points.iter().map(|p| p.p).collect::<Vec<_>>()),
|
||||
_ => stack.extend(n.children().into_iter().flatten().cloned()),
|
||||
}
|
||||
}
|
||||
assert_eq!(found.len(), 1, "{:?}", doc.symbols[0].art);
|
||||
let want = [Point::new(-5.0, -2.5), Point::new(5.0, -2.5), Point::new(-5.0, 2.5), Point::new(5.0, 2.5)];
|
||||
assert!(want.iter().all(|w| found[0].iter().any(|p| (*p - *w).hypot() < 1e-9)), "{:?}", found[0]);
|
||||
// Without a template box the mesh can't be placed, as an image there can't: the symbol isn't read
|
||||
// whole and its instance comes in as the page draws it.
|
||||
let group = format!("0 Ae\nu\n{}{RED}{}f\nU\n", instance("Patch", [1.0, 0.0, 0.0, -1.0, 20.0, 50.0]), rect_path(10.0, 0.0, 14.0, 4.0));
|
||||
let r = read_ok(&(symbols(&symbol("Patch", &mesh, 5)) + &layer(&group)));
|
||||
assert!(r.doc.symbols.is_empty(), "{:?}", r.doc.symbols.iter().map(|s| &s.name).collect::<Vec<_>>());
|
||||
assert!(!r.unread.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_keeps_its_hide_lock_transparency_and_clip() {
|
||||
let m = [1.0, 0.0, 0.0, -1.0, 20.0, 50.0];
|
||||
|
||||
@@ -127,7 +127,12 @@ private editing data. VectorCraft:
|
||||
on its stroke; other brushed strokes are
|
||||
written as their brush's art. A document that uses a new document's brushes writes none until a path keeps one on
|
||||
its stroke; then the brushes are written, and the file opens without the new document's Pattern and Bristle
|
||||
brushes.
|
||||
brushes. Gradient meshes are written as meshes: each mesh point's place, color, opacity and handles, patch by
|
||||
patch; a reflected mesh is written with its columns in reverse order. Meshes with a point in a Lab color, with
|
||||
more than 128 rows or columns, folded meshes (patches that turn different ways), meshes VectorCraft's reader
|
||||
wouldn't open as they are drawn, meshes in pattern tiles and in art cut to a clipping object, and every mesh on a
|
||||
large canvas are written as their drawn look with a warning. In a symbol's art, an envelope's contents are written in
|
||||
the canvas's space with y down.
|
||||
Point type, area type (with its rows, columns,
|
||||
gutters and first baseline, threaded frames included) and type on a path are written as text: a text object for
|
||||
each, naming its story in the text document, with the characters, fonts, sizes, leading, tracking, baseline shift,
|
||||
@@ -280,6 +285,8 @@ An object in a pattern's art or in a brush's art takes the file's art styles in
|
||||
|
||||
Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets) are read as Windows-1252 unless `legacyNameEncoding` (`convert --legacy-name-encoding`) picks `macintosh`, `windows-949`, `shift_jis`, `gbk` or `big5`; the open result's warnings list the first three such names as read and count the rest. The text values of data sets are read in the same encoding.
|
||||
|
||||
Gradient meshes in the editing data keep each point's own color where a patch's corners differ in color model. In a symbol's art, a gradient mesh's corners and an envelope's grid are read in the space an image's matrix is read in there, and an envelope's contents in its dictionary in the canvas's space with y down. In a file without a template box such a mesh is not read, and its symbol's instances open as the page draws them, as with an image there.
|
||||
|
||||
## Format by format
|
||||
|
||||
| Format | Illustrator | Ours: open/place | Ours: save/export | Fidelity and tests |
|
||||
|
||||
@@ -1878,6 +1878,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
On a large canvas ([the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/large-canvas-faq.html); VectorCraft writes one when the artboards together are wider or taller than 16,381 points, its own limit), that `.ai` keeps warp, mesh and top object envelopes editable too: the editing copy writes them live at 1/10 of their size with the rest of the art, and VectorCraft's `.ai` reader opens them at their size, from the editing data alone or beside the PDF part. Read from the editing data alone, an envelope's saved box size is compared with its contents at the same scale, so a bounds margin kept with Distort Appearance comes back, and every path's stroke weight, dashes and dash offset come back at their size, not at 1/10 (`large_canvas_envelope_kinds_round_trip_on_both_ai_routes`, `large_canvas_envelope_stroke_margin_round_trips_on_both_ai_routes` and `a_large_canvas_path_keeps_its_stroke_weight_and_dashes_read_alone` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
An envelope whose contents hold type keeps the type editable in that `.ai`: the editing copy writes the type as type in the envelope's contents, in the form the `.ai` reader opens as a live envelope of type (`TypedEnvelope` in `crates/eps/src/import/ai/envelope.rs`), so the file opens with the type shown and editable in the envelope's contents, with Edit Contents off or on. An envelope of type in a symbol's art, and one whose type is threaded, has text wrap options or is written as its outlines (mirrored type, for example), is written as its distorted art, as before (`an_envelope_of_type_is_read_back_live_with_its_type`, `an_envelope_of_type_written_as_its_art_leaves_no_story` and `an_envelope_of_type_in_a_symbol_or_a_thread_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
A top object whose top and bottom sides, or left and right sides, have different numbers of segments is also saved live: the side with fewer segments is split into as many as the side across from it has (each segment into equal spans of its curve, a straight one at even steps), up to the 50 a side the grid holds, so the file opens with the same corners and the same mapping of the contents, its outline holding the added anchors. Where the split side would share out the contents another way, as a side of two curves that aren't one curve can, or a side has more than 50 segments, the envelope is written as its distorted art, with the warning (`a_top_object_with_uneven_sides_is_read_back_live`, `a_top_object_split_to_the_grids_limit_is_read_back_live` and `a_top_object_whose_split_side_would_map_another_way_is_written_as_its_art` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps gradient meshes editable ([gradient meshes](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=200)): its editing copy writes each mesh point's place, color (gray, RGB or CMYK), opacity and handles patch by patch, with the mesh's transparency, name and opacity mask, in the form VectorCraft's `.ai` mesh reader reads (`crates/eps/src/import/ai/mesh.rs`), so the file opens with the same mesh. A reflected mesh is written with its columns in reverse order. Meshes with a point in a Lab color, with more than 128 rows or columns, folded meshes, meshes the reader would open otherwise, meshes in pattern tiles and in art cut to a clipping object, and every mesh on a large canvas are written as their drawn look, with a warning (`meshes_are_read_back_as_they_are`, `meshes_in_masks_and_symbols_are_read_back`, `a_reflected_mesh_is_written_with_its_columns_reversed` and `meshes_the_reader_cant_read_are_written_as_their_drawn_look` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes eligible paths, compound paths and groups with live effects with an art style when the writer supports their appearance and effects (not a filled path that uses the even-odd rule, and none on a large canvas), which VectorCraft's `.ai` reader opens as the same appearance with its effects live (`objects_with_live_effects_are_read_back` and `every_effect_setting_written_on_an_object_is_read_back` in `crates/eps/src/ai_editing/tests.rs`; [file-format-parity.md](file-format-parity.md) lists the objects written without one and the effects they lose).
|
||||
The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
Opacity masks in a symbol's art and in a pattern's tile are written the same way, so a symbol or pattern whose mask art has Offset Path opens with the effect live in its definition, and its instances and pattern fills draw as they did; each definition's mask art keeps its own style, and mask art linked to a graphic style opens still linked to it (`a_symbols_mask_art_keeps_live_offset_path`, `a_pattern_tiles_mask_art_keeps_live_offset_path`, `mask_art_styles_stay_with_their_own_art` and `opacity_mask_art_keeps_its_graphic_style_link` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
|
||||
Reference in New Issue
Block a user