6543: merge current main and retain overlay indexing

This commit is contained in:
yoriswind committed 2026-11-13 00:04:03 -08:00
commit 95e552ede0
511 files changed
+47912 -2977

No files matched your search

Generated
+13 -11
View File
@@ -217,7 +217,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
"wl-clipboard-rs",
"x11rb",
]
@@ -986,12 +986,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1060,7 +1060,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bb8320f5fa5d20fa78a026d0de06fe4e2f08a099#bb8320f5fa5d20fa78a026d0de06fe4e2f08a099"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1620,7 +1620,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -3869,7 +3869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4391,7 +4391,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4769,7 +4769,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -4828,7 +4828,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -5687,7 +5687,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
@@ -6476,6 +6476,7 @@ dependencies = [
"vectorcraft-plugins",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-trace",
]
[[package]]
@@ -6854,6 +6855,7 @@ dependencies = [
"serde",
"serde_json",
"toml",
"vectorcraft-apischema",
"vectorcraft-brush",
"vectorcraft-cad",
"vectorcraft-color",
@@ -7517,7 +7519,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.52.0",
]
[[package]]
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/vectorcraft"
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "bb8320f5fa5d20fa78a026d0de06fe4e2f08a099", features = ["serde"] }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
# Decides who draws the window frame (desktop vs. app) so the suite shares one native titlebar per
+4 -1
View File
@@ -238,14 +238,17 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there.
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
prefs_dir::attach_new_doc_profiles(&mut h.session);
prefs_dir::attach_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&mut h.session);
prefs_dir::attach_plugin_store(&mut h.session);
prefs_dir::attach_pdf_preset_store(&mut h.session);
prefs_dir::attach_custom_dictionary(&mut h.session);
prefs_dir::attach_arrowheads(&mut h.session);
h
}
+3
View File
@@ -478,6 +478,7 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
prefs_dir::attach_new_doc_profiles(&mut session);
let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone()));
app.set_startup_update_check(true);
load_prefs(&mut app, saved);
@@ -487,6 +488,8 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_pdf_preset_store(&mut app.session);
// The custom dictionary's words, kept in their own file next to the preferences.
prefs_dir::attach_custom_dictionary(&mut app.session);
// The custom arrowheads, kept in their own file next to the preferences.
prefs_dir::attach_arrowheads(&mut app.session);
// Fit the window to its monitor, or put it back where it was (still hidden).
let winit_window = cc.winit_window().cloned();
if let Some(w) = &winit_window {
+16
View File
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("New Document Profiles") {
session.attach_new_doc_profiles(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
@@ -81,6 +89,14 @@ pub fn attach_custom_dictionary(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep the custom arrowheads (Stroke panel menu › Edit Arrowheads…) in the `Arrowheads.vectorcraft`
/// file next to the settings, and list the heads it holds.
pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) {
if let Some(path) = store_dir(vectorcraft_engine::cmd::arrowheads::FILE_NAME) {
session.attach_arrowheads_file(path.to_string_lossy().to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
+7 -2
View File
@@ -250,7 +250,8 @@ impl ParamSchema {
/// What is wrong with the schema itself, or `None`: a parameter name that is empty, repeated
/// or holds `.`, `[` or `]`; a required parameter with a default; a default that isn't JSON or
/// doesn't pass its parameter's type; an enum with no names or a repeated name; a range with
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`].
/// an end that isn't finite or that no value can be in; nesting past [`MAX_DEPTH`], or a
/// [`Type::Ids`] or [`Type::Point`], whose values are all lists, at the nesting limit.
pub fn definition_problem(&self) -> Option<String> {
object_problem("", self.params, 0)
}
@@ -319,7 +320,9 @@ pub enum Problem {
Missing,
/// The value is not of the parameter's type: `expected` says what it must be.
WrongType { expected: String, got: String },
/// The schema nests deeper than [`MAX_DEPTH`] here ([`ParamSchema::definition_problem`]).
/// The value nests deeper than [`MAX_DEPTH`] here: a list given for a [`Type::Color`] at the
/// nesting limit, or any value under a schema that nests too deeply itself
/// ([`ParamSchema::definition_problem`]).
TooDeep,
}
@@ -779,6 +782,8 @@ fn type_problem(at: &str, ty: &Type, depth: usize) -> Option<String> {
Type::Object(params) => object_problem(at, params, depth + 1),
Type::Array(_) if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
Type::Array(item) => type_problem(&format!("{at}[]"), item, depth + 1),
// Every value of these is a list, and a list at the nesting limit is refused.
Type::Ids | Type::Point if depth >= MAX_DEPTH => Some(format!("`{at}` nests deeper than {MAX_DEPTH} levels")),
_ => None,
}
}
+30
View File
@@ -156,6 +156,36 @@ fn id_lists_points_and_color_lists_count_toward_the_nesting_limit() {
assert!(check(MAX_DEPTH, &Type::Color, &json!("#ff0000")).is_ok());
}
/// `ty` inside `levels` lists.
fn in_lists(levels: usize, ty: Type) -> Type {
(0..levels).fold(ty, |inner, _| Type::Array(Box::leak(Box::new(inner))))
}
/// `v` inside `levels` lists.
fn wrapped(levels: usize, v: Value) -> Value {
(0..levels).fold(v, |inner, _| Value::Array(vec![inner]))
}
/// The schema check and the value check agree on the fixed-shape lists at the nesting limit: an id
/// list or a point there could take no value, so the schema is wrong in itself, and a color there
/// takes a string, while a color list is refused as nested too deeply, at its path.
#[test]
fn fixed_shape_lists_at_the_nesting_limit_follow_the_schema_check() {
for ty in [Type::Ids, Type::Point, Type::Color] {
assert_eq!(one(in_lists(MAX_DEPTH - 1, ty)).definition_problem(), None, "{ty:?}");
}
for ty in [Type::Ids, Type::Point] {
let problem = one(in_lists(MAX_DEPTH, ty)).definition_problem();
assert!(problem.as_deref().is_some_and(|p| p.contains("nests deeper")), "{ty:?}: {problem:?}");
}
let color = one(in_lists(MAX_DEPTH, Type::Color));
assert_eq!(color.definition_problem(), None);
assert_eq!(color.validate(&json!({"x": wrapped(MAX_DEPTH, json!("#ff0000"))})).unwrap(), None);
let e = color.validate(&json!({"x": wrapped(MAX_DEPTH, json!([1, 0, 0]))})).unwrap_err();
assert_eq!(e.problem, Problem::TooDeep);
assert_eq!(e.path, format!("x{}", "[0]".repeat(MAX_DEPTH)));
}
#[test]
fn a_saved_retired_key_past_the_nesting_limit_is_refused() {
let params = holding("older", nested_lists(500_000));
+11 -7
View File
@@ -187,6 +187,9 @@ pub struct HpglOutput {
pub pens: Vec<[u8; 3]>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// Notes on the options: sorting the paths or drawing the inner paths first was applied only
/// in part.
pub setting_notes: Vec<String>,
}
/// Write the visible art of `doc` over `opts.region` as an HP-GL plot. Live geometry effects are
@@ -280,10 +283,11 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
if !by_pen.iter().all(Vec::is_empty) {
pen_warnings.iter().for_each(|w| warn(&mut warnings, w));
}
let mut setting_notes = vec![];
if opts.sort || opts.inside_first {
let (mut at, mut work) = ((0, 0), MAX_SORT_WORK);
for paths in &mut by_pen {
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut warnings);
at = reorder(paths, at, &mut work, opts.sort, opts.inside_first, &mut setting_notes);
}
}
if opts.version == Version::Hpgl && by_pen.iter().flatten().flatten().any(|(x, y)| !CLASSIC_RANGE.contains(x) || !CLASSIC_RANGE.contains(y)) {
@@ -293,7 +297,7 @@ pub fn export_regions(doc: &Document, opts: &HpglOptions, regions: &[Rect]) -> R
Version::Hpgl => plain(&by_pen),
Version::Hpgl2 => encoded(&by_pen, &pens),
};
out.push(HpglOutput { bytes, pens: pens.clone(), warnings });
out.push(HpglOutput { bytes, pens: pens.clone(), warnings, setting_notes });
}
Ok(out)
}
@@ -366,20 +370,20 @@ fn box_dist2(p: (i64, i64), b: [i64; 4]) -> i128 {
/// for a closed path any of its points (where it then starts); without, the first in paint order.
/// With `inside_first`, a path is drawn only once every path lying inside it ([`nest::outer`]) is.
/// Once `work` is spent, the paths left keep paint order, each after the paths inside it with
/// `inside_first`, with a warning. Returns where the pen stops.
/// `inside_first`, with a note in `notes`. Returns where the pen stops.
fn reorder(
paths: &mut Vec<Vec<(i64, i64)>>,
mut at: (i64, i64),
work: &mut u64,
nearest: bool,
inside_first: bool,
warnings: &mut Vec<String>,
notes: &mut Vec<String>,
) -> (i64, i64) {
let boxes: Vec<[i64; 4]> = paths.iter().map(|p| nest::bounds(p)).collect();
// The paths each path lies inside, and how many paths inside each are still to draw.
let outer = inside_first.then(|| nest::outer(paths, &boxes, work)).flatten();
if inside_first && outer.is_none() {
warn(warnings, UNNESTED);
warn(notes, UNNESTED);
}
let mut waiting = vec![0usize; paths.len()];
for o in outer.iter().flatten().flatten() {
@@ -430,11 +434,11 @@ fn reorder(
if *work == 0 || best.0 >= left.len() {
match &outer {
Some(outer) => {
warn(warnings, UNSORTED_INSIDE);
warn(notes, UNSORTED_INSIDE);
inner_first(left.into_iter().map(|(j, p, _)| (j, p)).collect(), outer, &mut waiting, paths);
}
None => {
warn(warnings, UNSORTED);
warn(notes, UNSORTED);
paths.extend(left.into_iter().map(|(_, p, _)| p));
}
}
+7 -6
View File
@@ -852,7 +852,8 @@ fn sorting_measures_a_closed_path_by_its_nearest_point() {
fn sorting_stops_at_its_budget_and_keeps_every_path() {
let d = doc_with(|d| (0..600).map(|i| stroked(d, line((1.0 + (i % 100) as f64, 10.0), (1.0 + (i % 100) as f64, 20.0)), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { sort: true, ..opts(&d) });
assert!(out.warnings.iter().any(|w| w == UNSORTED), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [UNSORTED]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(text(&out).matches("PD").count(), 600);
}
@@ -944,18 +945,18 @@ fn inside_first_orders_each_pens_paths() {
}
/// Finding which of 100 nested rings lie inside which is past the budget: they are drawn in
/// paint order, with a warning.
/// paint order, with a note on the option.
#[test]
fn inside_first_past_its_budget_draws_in_paint_order() {
let d = doc_with(|d| (0..100).map(|i| stroked(d, rect(1.0 + 0.4 * f64::from(i), 10.0, 199.0, 90.0), Color::BLACK)).collect());
let out = plot(&d, &HpglOptions { inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED]);
assert_eq!(out.setting_notes, [UNNESTED]);
let l = lefts(&out);
assert_eq!(l.len(), 100);
assert!(l.windows(2).all(|w| w[0] <= w[1]), "{l:?}");
// With `sort` too, the budget is spent before sorting starts: paint order, with both warnings.
// With `sort` too, the budget is spent before sorting starts: paint order, with both notes.
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNNESTED, UNSORTED]);
assert_eq!(out.setting_notes, [UNNESTED, UNSORTED]);
assert_eq!(lefts(&out), l);
}
@@ -969,7 +970,7 @@ fn inside_first_past_its_sorting_budget_keeps_the_rings_last() {
v
});
let out = plot(&d, &HpglOptions { sort: true, inside_first: true, ..opts(&d) });
assert_eq!(out.warnings, [UNSORTED_INSIDE]);
assert_eq!(out.setting_notes, [UNSORTED_INSIDE]);
let l = lefts(&out);
assert_eq!(l.len(), 602);
assert_eq!(l.get(600..), Some(&[plu(0.7), plu(0.5)][..]));
+3
View File
@@ -410,6 +410,9 @@ pub struct DxfOutput {
pub images: Vec<DxfImage>,
/// What was approximated or left out.
pub warnings: Vec<String>,
/// What was left out because an option turns it off (Include Placed Images or Include Fill
/// Hatches off).
pub setting_notes: Vec<String>,
}
/// The smallest and largest `scale` (drawing units per unit).
+16 -4
View File
@@ -520,6 +520,8 @@ pub(crate) struct Scene<'a> {
/// Image keys → index into `images` (`None`: left out).
by_key: HashMap<String, Option<usize>>,
warnings: Vec<String>,
/// What was left out because an option asked for it ([`DxfOutput::setting_notes`]).
setting_notes: Vec<String>,
brushes: Option<Vec<vectorcraft_brush::Brush>>,
extents: Option<[f64; 4]>,
/// The opacity of the containers around the current object.
@@ -554,6 +556,7 @@ impl<'a> Scene<'a> {
files: vec![],
by_key: HashMap::new(),
warnings: vec![],
setting_notes: vec![],
brushes: None,
extents: None,
opacity: 1.0,
@@ -588,15 +591,24 @@ impl<'a> Scene<'a> {
metric: matches!(self.o.unit, Unit::Millimeters | Unit::Centimeters | Unit::Meters),
next: self.next,
};
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings }
DxfOutput { bytes: drawing.write().into_bytes(), images: self.files, warnings: self.warnings, setting_notes: self.setting_notes }
}
/// Note `w`, once, about something of the document that the drawing leaves out or that reaches
/// it changed. A note about an option goes to [`Self::note_setting`].
fn warn(&mut self, w: &str) {
if !self.warnings.iter().any(|x| x == w) {
self.warnings.push(w.to_string());
}
}
/// Note `w`, once, about something left out because an option turns it off.
fn note_setting(&mut self, w: &str) {
if !self.setting_notes.iter().any(|x| x == w) {
self.setting_notes.push(w.to_string());
}
}
fn handle(&mut self) -> Handle {
let h = Handle(self.next);
self.next = self.next.saturating_add(1);
@@ -660,7 +672,7 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(im),
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
NodeKind::SymbolInstance { symbol, xf } => {
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
@@ -930,7 +942,7 @@ impl<'a> Scene<'a> {
// The outlines close as the fill does, so an open path's fill keeps its closing edge.
self.lines(&closed_fill(outline), style, 0.0);
if !self.o.include_hatches {
self.warn(HATCHES_OFF);
self.note_setting(HATCHES_OFF);
return;
}
let h = self.handle();
@@ -1321,7 +1333,7 @@ impl<'a> Scene<'a> {
return;
}
if !self.o.include_images {
self.warn(IMAGES_OFF);
self.note_setting(IMAGES_OFF);
return;
}
let Some(i) = self.image_def(im) else { return };
+13 -8
View File
@@ -881,12 +881,13 @@ fn fills_without_hatches_keep_their_outlines() {
let d = shapes_doc();
let out = export(&d, &DxfOptions { include_hatches: false, ..opts(&d) }).unwrap();
assert_eq!(kinds(&out), ["LWPOLYLINE", "LWPOLYLINE", "CIRCLE"], "the fill's outline, the stroke, the circle");
assert_eq!(out.warnings, [HATCHES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [HATCHES_OFF]);
let e = entities(&out);
assert_eq!((get(&e[0], 70), get(&e[0], 370)), (Some("1"), None), "the closed outline, without a lineweight");
// Hatches stay by default, with no note.
let on = export(&d, &opts(&d)).unwrap();
assert!(kinds(&on).iter().any(|k| k == "HATCH") && !on.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(kinds(&on).iter().any(|k| k == "HATCH") && on.setting_notes.is_empty());
// The outlines are the ones written beside hatches, also for overlapping subpaths, which are
// merged first; a fill with no area (a flat rectangle, a diagonal line) writes nothing either way.
let compound = doc_with(|d| {
@@ -916,13 +917,14 @@ fn fills_without_hatches_keep_their_outlines() {
assert!(!kinds(&altered).iter().any(|k| k == "HATCH") && !kinds(&altered).is_empty(), "{:?}", kinds(&altered));
// Nothing filled: no note.
let lines = doc_with(|d| vec![path(d, shapes::ellipse(Rect::new(120.0, 20.0, 180.0, 80.0)), Paint::None, Paint::solid(Color::BLACK), 1.0)]);
assert!(export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap().warnings.is_empty());
let none = export(&lines, &DxfOptions { include_hatches: false, ..opts(&lines) }).unwrap();
assert!(none.warnings.is_empty() && none.setting_notes.is_empty());
// R12 has no hatches anyway: the same outlines, and its own note alone.
let r12 = |include_hatches| export(&d, &DxfOptions { version: DxfVersion::R12, include_hatches, ..opts(&d) }).unwrap();
let (off, on) = (r12(false), r12(true));
assert_eq!(off.bytes, on.bytes);
assert_eq!(off.warnings, on.warnings);
assert!(!off.warnings.iter().any(|w| w == HATCHES_OFF));
assert!(off.setting_notes.is_empty());
}
#[test]
@@ -957,15 +959,18 @@ fn images_can_be_left_out_with_their_files() {
let p = pairs(&out.bytes);
assert!(!section(&p, "OBJECTS").iter().any(|o| matches!(kind(o), "IMAGEDEF" | "IMAGEDEF_REACTOR" | "RASTERVARIABLES")));
assert!(!section(&p, "CLASSES").iter().any(|o| get(o, 1) == Some("IMAGE")));
assert_eq!(out.warnings, [IMAGES_OFF]);
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert_eq!(out.setting_notes, [IMAGES_OFF]);
// An image that can't be decoded is not read when images are left out.
let mut broken = d.clone();
broken.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(b"not a png".to_vec()), proxy: None });
assert_eq!(export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap().warnings, [IMAGES_OFF]);
let left_out = export(&broken, &DxfOptions { include_images: false, ..opts(&broken) }).unwrap();
assert!(left_out.warnings.is_empty(), "{:?}", left_out.warnings);
assert_eq!(left_out.setting_notes, [IMAGES_OFF]);
assert!(export(&broken, &opts(&broken)).unwrap().warnings.iter().any(|w| w.contains("couldn't be decoded")));
// R12 has no images anyway: its own note alone.
let r12 = export(&d, &DxfOptions { version: DxfVersion::R12, include_images: false, ..opts(&d) }).unwrap();
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && !r12.warnings.iter().any(|w| w == IMAGES_OFF));
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
#[test]
@@ -983,7 +988,7 @@ fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_b
let cnc = run(DxfPreset::Cnc.options());
assert_eq!(kinds(&cnc), ["LWPOLYLINE"]);
assert!(cnc.images.is_empty());
assert!(cnc.warnings.iter().any(|w| w == IMAGES_OFF) && cnc.warnings.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.warnings);
assert!(cnc.setting_notes.iter().any(|w| w == IMAGES_OFF) && cnc.setting_notes.iter().any(|w| w == HATCHES_OFF), "{:?}", cnc.setting_notes);
let custom = DxfPreset::Custom.options();
assert!(custom.include_images && custom.include_hatches, "Custom keeps both");
}
+78 -13
View File
@@ -6,8 +6,9 @@
//! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model
//! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers);
//! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles).
//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`]
//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with
//! the profiles [`use_document_profiles`] last put in place of the working spaces;
//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`].
pub mod generic;
pub mod icc;
@@ -320,6 +321,9 @@ pub struct Cms {
settings: ColorSettings,
rgb: RgbSpace,
cmyk: CmykSpace,
/// The working settings, when a document's assigned profiles take the place of their spaces
/// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space.
working: Option<Arc<Cms>>,
}
impl std::fmt::Debug for Cms {
@@ -330,7 +334,7 @@ impl std::fmt::Debug for Cms {
impl Default for Cms {
fn default() -> Self {
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) }
Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None }
}
}
@@ -338,7 +342,7 @@ impl Cms {
/// Profiles named by a legacy name are stored under their current name.
pub fn new(settings: &ColorSettings) -> Result<Self, CmsError> {
let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() };
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings })
Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None })
}
pub fn settings(&self) -> &ColorSettings {
&self.settings
@@ -542,8 +546,9 @@ impl Cms {
ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA),
ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb),
ProofTarget::WorkingCmyk => {
let cmyk = self.srgb_to_cmyk(srgb, proof.intent);
self.cmyk_to_srgb(cmyk, proof.simulate_paper)
let working = self.working_cms();
let cmyk = working.srgb_to_cmyk(srgb, proof.intent);
working.cmyk_to_srgb(cmyk, proof.simulate_paper)
}
ProofTarget::Cmyk(name) => match cmyk_space(name) {
Ok(sp) => {
@@ -555,20 +560,29 @@ impl Cms {
}
}
/// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets).
/// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB
/// targets).
pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] {
match &proof.target {
ProofTarget::Cmyk(name) => match cmyk_space(name) {
Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc),
Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
},
ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper),
_ => self.cmyk_to_srgb(cmyk, proof.simulate_paper),
}
}
/// The context of the working settings: the one [`use_document_profiles`] put a document's
/// profiles in place of, else this one.
fn working_cms(&self) -> &Cms {
self.working.as_deref().unwrap_or(self)
}
/// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels.
pub fn proof_lut(&self, proof: &ProofSetup) -> Arc<ProofLut> {
let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
let working = self.working.as_ref().map(|w| &w.settings);
let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper);
let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) {
return l.clone();
@@ -890,10 +904,12 @@ impl CmykLut {
// ---------- the active (process-wide) settings ----------
static ACTIVE: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static WORKING: RwLock<Option<Arc<Cms>>> = RwLock::new(None);
static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true);
static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false);
/// The active colour-management context (Edit → Color Settings).
/// The active color-management context: the working settings, with the profiles
/// [`use_document_profiles`] last put in place of the working spaces.
pub fn active() -> Arc<Cms> {
if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
@@ -906,13 +922,62 @@ pub fn active_settings() -> ColorSettings {
active().settings.clone()
}
/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown).
/// The color-management context of Edit → Color Settings (the working spaces, intent and black
/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned.
pub fn working() -> Arc<Cms> {
if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
return c.clone();
}
let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner());
w.get_or_insert_with(|| Arc::new(Cms::default())).clone()
}
/// The settings of [`working`].
pub fn working_settings() -> ColorSettings {
working().settings.clone()
}
/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails,
/// leaving both unchanged, if a profile is unknown).
pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> {
let cms = Cms::new(settings)?;
let cms = Arc::new(Cms::new(settings)?);
*WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone());
install(cms);
Ok(())
}
/// Make the working settings the active settings, with the profiles a document is assigned
/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or
/// is not of its model, leaves the working space. The working settings stay as they are. True when
/// the active settings changed.
pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool {
let working = working();
let mut st = working.settings.clone();
if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) {
st.rgb = p.name;
}
if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) {
st.cmyk = p.name;
}
if st == active().settings {
return false;
}
if st == working.settings {
install(working);
return true;
}
// The working settings were checked when they were set; a working profile removed since then
// leaves the active settings as they are.
let Ok(mut cms) = Cms::new(&st) else { return false };
cms.working = Some(working);
install(Arc::new(cms));
true
}
fn install(cms: Arc<Cms>) {
RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed);
CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed);
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms));
Ok(())
*ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms);
}
/// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB.
+116 -10
View File
@@ -4,7 +4,8 @@
use kurbo::{Point, Rect, Vec2};
use super::{Gradient, GradientGeom, GradientKind, GradientSpread, GradientStop};
use super::{Gradient, GradientGeom, GradientKind, GradientMethod, GradientSpread, GradientStop};
use crate::Color;
/// Most runs of the stops [`Gradient::padded_over`] writes.
pub const MAX_SPREAD_RUNS: usize = 256;
@@ -33,8 +34,8 @@ pub struct Padded {
pub first: f64,
/// How many runs are written, evenly spaced from [`Self::first`] to 1.
pub runs: usize,
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or than [`MAX_SPREAD_STOPS`] allows),
/// or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
/// The area needed more runs than [`MAX_SPREAD_RUNS`] (or more than half the stops allowed,
/// two to a run), or runs past [`MAX_SPREAD_LEVEL`]: the gradient pads past the runs written.
pub capped: bool,
}
@@ -50,7 +51,9 @@ impl Gradient {
self.padded_within(geom, area, MAX_SPREAD_STOPS)
}
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run).
/// [`Self::padded_over`] with at most `max_stops` stops (and at least one run). When the runs
/// written need more stops than that, each run leaves out the stops that change its colors
/// least ([`fit_run`]), so every run is still written.
pub fn padded_within(&self, geom: &GradientGeom, area: Rect, max_stops: usize) -> Option<Padded> {
let kind = self.kind;
if !self.is_spread() || matches!(kind, GradientKind::Conic | GradientKind::Freeform) || self.stops.is_empty() {
@@ -68,8 +71,8 @@ impl Gradient {
// smallest 0 when the area holds the rings' center, else on its edge.
let lo = if centered { inner_level(&period, kind, area).floor() } else { ts.iter().copied().fold(f64::INFINITY, f64::min).floor() };
let hi = ts.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil().max(lo + 1.0);
let one = whole_run(&self.stops);
let most = MAX_SPREAD_RUNS.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
let budget = max_stops.min(MAX_SPREAD_STOPS);
let most = MAX_SPREAD_RUNS.min(budget / 2).max(1);
let capped = hi - lo > most as f64;
// Capped, the runs kept are the area's innermost ones (radial and diamond), or (linear)
// those around the vector's start where the area reaches it, else the area's runs nearest
@@ -79,6 +82,7 @@ impl Gradient {
_ => lo,
};
let n = (hi - lo).min(most as f64).max(1.0);
let one = fit_run(whole_run(&self.stops), budget / n as usize, self.method);
// A radial or diamond writes its runs among the levels from 0, which its stops' offsets
// (single-precision fractions of the outermost level) tell apart only so far out, the
// nearer the closer its stops lie: past that, the runs end there and the gradient pads.
@@ -112,8 +116,9 @@ impl Gradient {
self.unrolled_within(MAX_SPREAD_STOPS)
}
/// [`Self::unrolled`] with at most `max_stops` stops (and at least one run): past the runs
/// that fit, the last one pads.
/// [`Self::unrolled`] with at most `max_stops` stops: every run, each run without the stops
/// that change its colors least ([`fit_run`]) when the runs need more stops than that. Only with
/// fewer than two stops for each run do the runs past those that fit pad with the last one.
pub fn unrolled_within(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if !self.is_spread() {
@@ -123,13 +128,29 @@ impl Gradient {
if self.stops.is_empty() {
return Cow::Owned(Gradient { spread: GradientSpread::Pad, repeats: 1, ..self.clone() });
}
let one = whole_run(&self.stops);
let n = self.repeat_count() as usize;
let kept = n.min(max_stops.min(MAX_SPREAD_STOPS) / one.len().max(1)).max(1);
let budget = max_stops.min(MAX_SPREAD_STOPS);
let kept = n.min(budget / 2).max(1);
let one = fit_run(whole_run(&self.stops), budget / kept, self.method);
let stops = self.runs(&one, false, 0.0, kept, n as f64);
Cow::Owned(Gradient { stops, spread: GradientSpread::Pad, repeats: 1, ..self.clone() })
}
/// The gradient as [`Self::unrolled`] gives it with at most `max_stops` stops (at least two):
/// a gradient that repeats or reflects as [`Self::unrolled_within`] gives it, and one that
/// pads with more stops than that without the stops that change its colors least
/// ([`fit_run`]). Others as they are.
pub fn fitted(&self, max_stops: usize) -> std::borrow::Cow<'_, Gradient> {
use std::borrow::Cow;
if self.is_spread() {
return self.unrolled_within(max_stops);
}
if self.stops.len() <= max_stops.max(2) {
return Cow::Borrowed(self);
}
Cow::Owned(Gradient { stops: fit_run(whole_run(&self.stops), max_stops, self.method), ..self.clone() })
}
/// One cycle of a gradient that repeats or reflects, which repeated end to end paints it, as
/// a gradient that pads: one run of the stops (Repeat), or a run and its mirror (Reflect),
/// between 0 and 1, and how many runs that is (1 or 2). `None` for a gradient that pads and
@@ -257,6 +278,91 @@ fn whole_run(stops: &[GradientStop]) -> Vec<GradientStop> {
out
}
/// `one` (a run of a gradient's stops, [`whole_run`]) with at most `budget` stops (at least two):
/// as it is when it fits, else without the stops that change its colors least, left out one at a
/// time. Leaving out a stop costs how far its color lies from the one that mixing the stops still
/// on either side of it by `method` gives there, and how far its CMYK inks, opacity, tint or
/// process plates lie from the line between theirs (a whole unit when its swatch link or color
/// model differs from either of theirs, and a whole unit more when its midpoint or the one before
/// it is off center), so the ends, sharp steps, ink changes and shaped spans stay. A stop whose
/// next stop was left out gets its midpoint centered. The work is the stops times their logarithm.
fn fit_run(one: Vec<GradientStop>, budget: usize, method: GradientMethod) -> Vec<GradientStop> {
use std::cmp::Reverse;
use std::collections::BinaryHeap;
let budget = budget.max(2);
let n = one.len();
if n <= budget {
return one;
}
let mix = |x: &Color, y: &Color, v: f32| match method {
GradientMethod::Classic => x.lerp_keep_model(y, v),
m => m.mix(x, y, v),
};
let cost = |a: &GradientStop, s: &GradientStop, b: &GradientStop| -> u32 {
let span = b.offset - a.offset;
let u = if span > 0.0 { ((s.offset - a.offset) / span).clamp(0.0, 1.0) } else { 0.0 };
// Left out, the span from `a` to `b` has a centered midpoint, so it mixes them by `u`.
let (want, cs) = (mix(&a.color, &b.color, u).to_rgb(), s.color.to_rgb());
let color = (0..3).map(|k| (want[k] - cs[k]).abs()).fold(0.0, f32::max);
let opacity = (a.opacity + (b.opacity - a.opacity) * u - s.opacity).abs();
// Process inks, which colors that look alike can print differently: off their line, or a
// change of color model.
let process = match (&a.color, &s.color, &b.color) {
(Color::Cmyk { c: c0, m: m0, y: y0, k: k0 }, Color::Cmyk { c, m, y, k }, Color::Cmyk { c: c1, m: m1, y: y1, k: k1 }) => {
[(c0, c, c1), (m0, m, m1), (y0, y, y1), (k0, k, k1)].iter().map(|(p, q, r)| (*p + (*r - *p) * u - *q).abs()).fold(0.0, f32::max)
}
_ if a.color.model() == s.color.model() && s.color.model() == b.color.model() => 0.0,
_ => 1.0,
};
let color = color.max(process);
// Separations: a change of swatch link, or of tint or process plates off their line.
let ink = if s.swatch != a.swatch || s.swatch != b.swatch {
1.0
} else {
let tint = (a.tint + (b.tint - a.tint) * u - s.tint).abs();
let plates = match (a.plates, s.plates, b.plates) {
(None, None, None) => 0.0,
(Some(pa), Some(ps), Some(pb)) => (0..4).map(|k| (pa[k] + (pb[k] - pa[k]) * u - ps[k]).abs()).fold(0.0, f32::max),
_ => 1.0,
};
tint.max(plates)
};
// Leaving it out merges two spans, and an off-center midpoint shapes one of them.
let shaped = if [a.midpoint, s.midpoint].iter().any(|m| (m - 0.5).abs() > 1e-3) { 1.0 } else { 0.0 };
// Non-negative, so the bits order as the numbers do (NaN counts as 0).
(color.max(opacity).max(ink) + shaped).max(0.0).to_bits()
};
// The stops still kept on either side of each stop, and each stop's latest cost entry.
let mut prev: Vec<usize> = (0..n).map(|i| i.saturating_sub(1)).collect();
let mut next: Vec<usize> = (1..=n).collect();
let mut gone = vec![false; n];
let mut version = vec![0u32; n];
let mut heap: BinaryHeap<Reverse<(u32, usize, u32)>> = (1..n - 1).map(|i| Reverse((cost(&one[i - 1], &one[i], &one[i + 1]), i, 0))).collect();
let mut left = n;
while left > budget {
let Some(Reverse((_, i, v))) = heap.pop() else { break };
if gone[i] || v != version[i] {
continue;
}
gone[i] = true;
left -= 1;
let (a, b) = (prev[i], next[i]);
next[a] = b;
prev[b] = a;
for j in [a, b] {
if j != 0 && j != n - 1 {
version[j] += 1;
heap.push(Reverse((cost(&one[prev[j]], &one[j], &one[next[j]]), j, version[j])));
}
}
}
one.into_iter()
.enumerate()
.filter(|(i, _)| !gone[*i])
.map(|(i, s)| if next[i] == i + 1 { s } else { GradientStop { midpoint: 0.5, ..s } })
.collect()
}
/// A run mirrored: the stops in reverse, each midpoint measured from the other side.
fn mirror(run: &[GradientStop]) -> Vec<GradientStop> {
let mut g = Gradient::new(GradientKind::Linear, run.to_vec());
+117 -5
View File
@@ -148,11 +148,12 @@ fn radial_and_diamond_gradients_pad_in_rings_from_their_first_level() {
}
}
/// A run of the stops far too short for the area, or a gradient of many stops, is written with at
/// most so many runs and stops, and pads past them; a conic, a padding gradient and one without
/// stops have nothing to pad.
/// A run of the stops far too short for the area is written with at most so many runs, and pads
/// past them; a gradient of many stops is written with every run the area needs, each run
/// without the stops that change its colors least, within so many stops; a conic, a padding
/// gradient and one without stops have nothing to pad.
#[test]
fn far_repeats_and_many_stops_are_capped() {
fn far_repeats_are_capped_and_many_stops_are_sampled() {
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(0.01, 0.0), aspect: 1.0, focal: None };
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, black_white()) };
let p = g.padded_over(&geom, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
@@ -162,7 +163,13 @@ fn far_repeats_and_many_stops_are_capped() {
let g = Gradient { spread: GradientSpread::Reflect, repeats: 50, ..Gradient::new(GradientKind::Linear, many) };
let wide = GradientGeom { end: Point::new(100.0, 0.0), ..geom };
let p = g.padded_over(&wide, Rect::new(0.0, 0.0, 100.0, 1.0)).unwrap();
assert!(p.capped && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{}", p.gradient.stops.len());
assert!(!p.capped && p.runs == 50 && p.gradient.stops.len() <= MAX_SPREAD_STOPS, "{} {}", p.runs, p.gradient.stops.len());
for x in [0.7, 33.3, 66.1, 99.5] {
let q = Point::new(x, 0.5);
let want = g.sample(g.spread_param(wide.param_at(GradientKind::Linear, q)) as f32).0.to_rgb();
let got = p.gradient.sample(p.geom.param_at(GradientKind::Linear, q) as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{x}: {want:?} vs {got:?}");
}
assert!(g.unrolled().stops.len() <= MAX_SPREAD_STOPS);
assert!(p.gradient.padded_over(&p.geom, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none(), "it pads");
assert!(spread(GradientKind::Conic, GradientSpread::Repeat, 3).padded_over(&wide, Rect::new(0.0, 0.0, 1.0, 1.0)).is_none());
@@ -325,6 +332,111 @@ fn unrolled_and_cycle_stops() {
assert!(matches!(Gradient::default().unrolled(), std::borrow::Cow::Borrowed(_)));
}
/// A gradient of more stops than [`MAX_SPREAD_STOPS`] allows for all its runs keeps every run
/// when unrolled, each run without the stops that change its colors least: its last run ends on
/// its last color instead of the rest padding with it.
#[test]
fn unrolled_many_stops_keep_every_run() {
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: MAX_REPEATS, ..Gradient::new(GradientKind::Linear, stops) };
let u = g.unrolled();
assert!(u.stops.len() <= MAX_SPREAD_STOPS, "{}", u.stops.len());
for t in [0.005, 0.5051, 0.9149, 0.9951] {
let want = g.sample(g.spread_param(t) as f32).0.to_rgb();
let got = u.sample(t as f32).0.to_rgb();
assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 2e-3), "{t}: {want:?} vs {got:?}");
}
// A padding gradient fitted to fewer stops keeps its ends.
let pad = Gradient::new(GradientKind::Linear, g.stops.clone());
let fitted = pad.fitted(16);
assert_eq!(fitted.stops.len(), 16);
for (stop, want) in [(&fitted.stops[0], Color::gray(0.0)), (&fitted.stops[15], Color::gray(1.0))] {
assert!(stop.color.to_rgb().iter().zip(want.to_rgb()).all(|(a, b)| (a - b).abs() < 1e-5), "{:?}", stop.color);
}
assert!(matches!(pad.fitted(500), std::borrow::Cow::Borrowed(_)));
}
/// One run of more stops than the limit (255 inside it, and a copy of each end color at 0 and 1)
/// is written within the limit, every run the area needs included.
#[test]
fn a_run_over_the_stop_limit_is_written_within_it() {
let stops: Vec<GradientStop> = (1..=255).map(|i| GradientStop::new(i as f32 / 256.0, Color::gray(i as f32 / 256.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 2, ..Gradient::new(GradientKind::Linear, stops) };
let geom = GradientGeom { start: Point::new(0.0, 0.0), end: Point::new(20.0, 0.0), aspect: 1.0, focal: None };
let p = g.padded_within(&geom, Rect::new(0.0, 0.0, 20.0, 1.0), 256).unwrap();
assert!(!p.capped && p.runs == 2 && p.gradient.stops.len() <= 256, "{} {} {}", p.capped, p.runs, p.gradient.stops.len());
assert!(g.unrolled_within(256).stops.len() <= 256);
}
/// Fitting a run to fewer stops keeps a narrow band between two sharp steps, a stop linked to a
/// swatch, and each kept stop's link and tint, where sampling at evenly spaced places would lose
/// them.
#[test]
fn fitting_keeps_sharp_steps_and_swatch_links() {
let mut stops: Vec<GradientStop> = (0..300).map(|i| GradientStop::new(i as f32 / 299.0, Color::gray(i as f32 / 299.0))).collect();
let red = Color::rgb(1.0, 0.0, 0.0);
// A band of red from 0.5003 to 0.5013, with a sharp step at each side.
for (offset, color) in [(0.5003, None), (0.5003, Some(red)), (0.5013, Some(red)), (0.5013, None)] {
let gray = Color::gray(offset);
stops.push(GradientStop::new(offset, color.unwrap_or(gray)));
}
let spot = GradientStop { swatch: Some("Ink".into()), tint: 0.4, ..GradientStop::new(0.25, Color::gray(0.25)) };
stops.push(spot.clone());
// Three stops of one ink that look alike but print at different tints.
for (offset, tint) in [(0.8, 0.2), (0.81, 0.9), (0.82, 0.2)] {
stops.push(GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(offset)) });
}
// A span shaped by an off-center midpoint.
if let Some(s) = stops.iter_mut().find(|s| (s.offset - 0.6).abs() < 2e-3) {
s.midpoint = 0.13;
}
stops.sort_by(|a, b| a.offset.total_cmp(&b.offset));
let g = Gradient::new(GradientKind::Linear, stops);
let fitted = g.fitted(32);
assert!(fitted.stops.len() <= 32, "{}", fitted.stops.len());
let red_at = |t: f32| fitted.sample(t).0.to_rgb();
assert_eq!(red_at(0.5008), [1.0, 0.0, 0.0], "the band stays");
assert!(red_at(0.499)[1] > 0.4 && red_at(0.503)[1] > 0.4, "the band stays narrow");
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink") && s.tint == 0.4 && s.offset == 0.25), "{:?}", fitted.stops);
assert!(fitted.stops.iter().any(|s| s.swatch.as_deref() == Some("Ink2") && s.tint == 0.9), "the tint change stays");
assert!(fitted.stops.iter().any(|s| s.midpoint == 0.13), "the shaped span stays");
// Of a stop that changes only its ink's tint and one that the colors' line nearly gives, the
// first stays. (The stop before an ink starts stays as well: leaving it out would blend the
// ink in sooner.)
let ink = |offset: f32, tint: f32| GradientStop { swatch: Some("Ink2".into()), tint, ..GradientStop::new(offset, Color::gray(0.5)) };
let few = vec![
GradientStop::new(0.0, Color::gray(0.0)),
GradientStop::new(0.2, Color::gray(0.17)),
GradientStop::new(0.3, Color::gray(0.3)),
ink(0.4, 0.2),
ink(0.5, 0.9),
ink(0.6, 0.2),
GradientStop::new(1.0, Color::gray(1.0)),
];
let fitted = Gradient::new(GradientKind::Linear, few).fitted(6).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.3, 0.4, 0.5, 0.6, 1.0]);
// A Perceptual gradient leaves out the stop its own mixing gives, not the one the RGB line
// gives.
let (blue, yellow, gray) = (Color::rgb(0.0, 0.0, 1.0), Color::rgb(1.0, 1.0, 0.0), Color::rgb(0.5, 0.5, 0.5));
let on_curve = GradientMethod::Perceptual.mix(&gray, &yellow, 0.5);
let stops = vec![GradientStop::new(0.0, blue), GradientStop::new(0.5, gray), GradientStop::new(0.75, on_curve), GradientStop::new(1.0, yellow)];
let perceptual = Gradient { method: GradientMethod::Perceptual, ..Gradient::new(GradientKind::Linear, stops) };
let fitted = perceptual.fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
// A black of other inks between blacks that look the same prints differently: it stays.
let k = |offset: f32| GradientStop::new(offset, Color::Cmyk { c: 1.0, m: 1.0, y: 1.0, k: 1.0 });
let rich = GradientStop::new(0.5, Color::Cmyk { c: 0.6, m: 0.4, y: 0.4, k: 1.0 });
let blacks = vec![k(0.0), k(0.4), rich, k(0.6), k(1.0)];
let fitted = Gradient::new(GradientKind::Linear, blacks).fitted(3).into_owned();
let offsets: Vec<f32> = fitted.stops.iter().map(|s| s.offset).collect();
assert_eq!(offsets, [0.0, 0.5, 1.0]);
let spread = Gradient { spread: GradientSpread::Repeat, repeats: 4, ..g.clone() };
let u = spread.unrolled_within(128);
assert_eq!(u.stops.iter().filter(|s| s.swatch.as_deref() == Some("Ink")).count(), 4, "one linked stop a run");
}
/// Pixels (what the canvas draws a diamond, dithered or Perceptual gradient as, and what SVG and
/// PDF write as images) repeat with the stops, for each kind.
#[test]
+115
View File
@@ -485,6 +485,88 @@ pub fn cluster(colors: &[Color], weights: &[f32], n: usize) -> Vec<Vec<usize>> {
rows
}
/// The distinct colors [`theme_palette`] clusters, at most.
const THEME_CANDIDATES: usize = 4096;
/// The color palette of the weighted colors `samples` (color, weight), for Recolor Artwork's Color
/// Theme Picker: at most `n` colors. The same color given twice counts once with both weights,
/// and past [`THEME_CANDIDATES`] distinct colors, colors close in Lab merge into the heaviest of
/// them first.
/// The colors are grouped as [`cluster`] groups them, each group shows its heaviest color (a color
/// of `samples`, in its own model; on a tie the one given first), and the heaviest group comes
/// first (on a tie the group whose first color was given first). Samples without a positive,
/// finite weight are left out, so no samples give no colors.
pub fn theme_palette(samples: &[(Color, f32)], n: usize) -> Vec<Color> {
let mut index: std::collections::HashMap<ColorKey, usize> = std::collections::HashMap::new();
let mut colors: Vec<Color> = vec![];
let mut weights: Vec<f32> = vec![];
for (c, w) in samples {
if !(w.is_finite() && *w > 0.0) {
continue;
}
let i = *index.entry(ColorKey::of(c)).or_insert_with(|| {
colors.push(*c);
weights.push(0.0);
colors.len() - 1
});
weights[i] += w;
}
if colors.is_empty() || n == 0 {
return vec![];
}
// At most THEME_CANDIDATES colors are clustered: past that, colors in the same cube of Lab
// space merge into the heaviest of them, the cubes doubling in size until few enough remain.
if colors.len() > THEME_CANDIDATES {
let labs: Vec<[f32; 3]> = colors
.iter()
.map(|c| {
let l = c.to_lab();
[l.l, l.a, l.b]
})
.collect();
let mut side = 2.0f32;
loop {
let mut cube: std::collections::HashMap<[i32; 3], usize> = std::collections::HashMap::new();
let (mut top, mut sum): (Vec<usize>, Vec<f32>) = (vec![], vec![]);
for (i, lab) in labs.iter().enumerate() {
let k = lab.map(|v| (v / side).floor() as i32);
match cube.get(&k) {
Some(&j) => {
sum[j] += weights[i];
if weights[i] > weights[top[j]] {
top[j] = i;
}
}
None => {
cube.insert(k, top.len());
top.push(i);
sum.push(weights[i]);
}
}
}
if top.len() <= THEME_CANDIDATES {
colors = top.iter().map(|&i| colors[i]).collect();
weights = sum;
break;
}
side *= 2.0;
}
}
let mut groups: Vec<(f32, usize, Color)> = cluster(&colors, &weights, n)
.into_iter()
.filter_map(|g| {
let total: f32 = g.iter().map(|&i| weights[i]).sum();
let top = g.iter().copied().fold(None::<usize>, |best, i| match best {
Some(b) if weights[b] >= weights[i] => Some(b),
_ => Some(i),
})?;
Some((total, *g.first()?, colors[top]))
})
.collect();
groups.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
groups.into_iter().map(|g| g.2).collect()
}
/// A set of colours to snap to (Limit to Library), with their Lab values cached.
#[derive(Clone, Debug, Default)]
pub struct Palette(Vec<(Color, Lab)>);
@@ -691,6 +773,39 @@ mod tests {
assert!(cluster(&[], &[], 3).is_empty());
}
/// The Color Theme Picker's palette: similar colors merge, each group shows its heaviest
/// color in its own model, and the heaviest group comes first.
#[test]
fn theme_palette_takes_the_heaviest_color_of_each_group_heaviest_first() {
let red = Color::rgb(1.0, 0.0, 0.0);
let pink = Color::rgb(1.0, 0.2, 0.2);
let blue = Color::cmyk(1.0, 0.8, 0.0, 0.0);
let navy = Color::cmyk(1.0, 0.9, 0.0, 0.3);
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 2.5), (red, 0.5)];
// Blue and navy weigh 4.5, and so do red (3 + 0.5, its two samples add up) and pink.
assert_eq!(theme_palette(&samples, 2), vec![red, navy], "a tie: the group given first");
let samples = [(pink, 1.0), (blue, 2.0), (red, 3.0), (navy, 1.0)];
assert_eq!(theme_palette(&samples, 2), vec![red, blue], "heaviest group first, its heaviest color");
assert_eq!(theme_palette(&samples, 9).len(), 4, "never more colors than given");
assert_eq!(theme_palette(&samples, 1), vec![red]);
assert!(theme_palette(&samples, 0).is_empty());
assert!(theme_palette(&[(red, 0.0), (blue, f32::NAN), (pink, -1.0)], 3).is_empty(), "no weight, no colors");
assert!(theme_palette(&[], 3).is_empty());
}
/// Past 4,096 distinct colors, close colors merge before clustering: the palette still keeps
/// a heavy color apart from thousands of light ones.
#[test]
fn theme_palette_merges_close_colors_past_its_candidate_limit() {
let mut samples: Vec<(Color, f32)> = (0..20_000).map(|i| (Color::rgb(0.0, 0.0, 0.3 + 0.7 * i as f32 / 20_000.0), 0.001)).collect();
samples.extend((0..20_000).map(|i| (Color::rgb(1.0, 0.8 * i as f32 / 20_000.0, 0.0), 0.0001)));
samples.push((Color::rgb(0.0, 1.0, 0.0), 50.0));
let p = theme_palette(&samples, 3);
assert_eq!(p.len(), 3);
assert_eq!(p[0], Color::rgb(0.0, 1.0, 0.0), "the heavy green first, exactly as given");
assert!(p[1].to_hsb()[0] > 180.0 && p[2].to_hsb()[0] < 90.0, "then the blues, then the reds and oranges: {p:?}");
}
#[test]
fn hue_shift_with_own_model_puts_every_colour_of_the_row_in_the_new_model() {
let to = Color::cmyk(0.0, 1.0, 1.0, 0.0);
+1 -1
View File
@@ -10,7 +10,7 @@ mod stroke_style;
pub use layers::{Effect, FillLayer, StrokeGradientMode, StrokeLayer, stroke_paint_bounds};
pub use profile::{AngleProfile, PressureProfile, ProfilePreset, SavedProfile, WidthProfile};
pub use stroke_style::{ArrowAlign, Arrowhead, Dash, LineCap, LineJoin, StrokeAlign};
pub use stroke_style::{ArrowAlign, Arrowhead, CustomArrowhead, Dash, LineCap, LineJoin, StrokeAlign};
/// One entry of the appearance stack.
// A stroke takes 328 bytes and a fill 104; an appearance holds a few of each.
+4 -2
View File
@@ -193,8 +193,10 @@ impl StrokeLayer {
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
pub fn head_reach(&self, end: bool) -> f64 {
let head = if end { self.end_arrow } else { self.start_arrow };
head.map_or(0.0, |k| k.reach() * self.arrow_weight(end) + self.width / 2.0)
let head = if end { &self.end_arrow } else { &self.start_arrow };
// A custom head can paint in front of its tip, which Extend puts past the end point.
let reach = |k: &Arrowhead| if self.arrow_align == ArrowAlign::Extend { k.reach().max(k.length()) } else { k.reach() };
head.as_ref().map_or(0.0, |k| reach(k) * self.arrow_weight(end) + self.width / 2.0)
}
/// How far the arrowheads can reach from the path's end points (0 without heads).
pub fn arrow_reach(&self) -> f64 {
+98 -5
View File
@@ -1,3 +1,7 @@
use std::sync::Arc;
use vectorcraft_geom::{PathData, Rect};
use super::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
@@ -53,8 +57,74 @@ impl Dash {
/// (the open arrow's arms are cut square a little behind the box).
const HEAD_REACH: f64 = 4.6;
/// An arrowhead the user drew (Stroke panel menu › Edit Arrowheads…), carried with its art so a
/// document that uses it draws it wherever it opens.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(from = "CustomArrowheadData")]
pub struct CustomArrowhead {
/// The name the arrowhead menus show (the symbol's name in the arrowheads file).
pub name: String,
/// The filled outline (non-zero rule) in head units: x from the tip (0) back along the line, y
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
/// as the built-in heads are, and a unit is the head's weight.
pub path: PathData,
}
#[derive(Deserialize)]
struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
}
impl From<CustomArrowheadData> for CustomArrowhead {
fn from(d: CustomArrowheadData) -> Self {
CustomArrowhead::new(d.name, d.path)
}
}
impl CustomArrowhead {
/// The most anchors a custom head's outline may have, and the most subpaths.
pub const MAX_ANCHORS: usize = 4096;
/// How far from the tip a custom head's outline may reach, in head units.
pub const MAX_UNITS: f64 = 64.0;
/// Head `name` with outline `path` (in head units). An outline with more than
/// [`Self::MAX_ANCHORS`] anchors or subpaths, a point that is not finite, or a point farther
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
pub fn new(name: String, path: PathData) -> Self {
let path = if Self::fits(&path) { path } else { PathData::default() };
CustomArrowhead { name, path }
}
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
/// finite points within [`Self::MAX_UNITS`] only.
pub fn fits(path: &PathData) -> bool {
let anchors = path.subpaths.iter().map(|s| s.anchors.len()).sum::<usize>();
let near = |p: vectorcraft_geom::Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= Self::MAX_UNITS && p.y.abs() <= Self::MAX_UNITS;
anchors <= Self::MAX_ANCHORS
&& path.subpaths.len() <= Self::MAX_ANCHORS
&& path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| near(a.p) && near(a.h_in) && near(a.h_out))
}
fn bounds(&self) -> Option<Rect> {
self.path.control_bounds()
}
/// How far any part of the head can be from its tip, in head units.
pub fn reach(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x0.hypot(b.y0).max(b.x1.hypot(b.y0)).max(b.x0.hypot(b.y1)).max(b.x1.hypot(b.y1)))
}
/// How far the head spreads either side of its line, in head units.
pub fn half_width(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
}
/// Where the stroke ends under the head, in head units back from the tip: halfway along the
/// head's length.
pub fn stop(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
}
}
/// An arrowhead shape. Saved by variant name: new shapes are appended, never renamed or reordered.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Arrowhead {
Triangle,
TriangleOpen,
@@ -102,6 +172,8 @@ pub enum Arrowhead {
/// more) meeting at right angles in a sharp tip, cut square at their ends. Twice as wide as
/// the other heads.
LineArrow,
/// A head the user drew, with its art.
Custom(Arc<CustomArrowhead>),
}
impl Arrowhead {
@@ -151,23 +223,43 @@ impl Arrowhead {
];
/// How far any part of the head can be from its tip, in units of its weight.
pub fn reach(self) -> f64 {
pub fn reach(&self) -> f64 {
match self {
// Its farthest corners are 4 + ½√2 back and 4 − ½√2 out.
Arrowhead::LineArrow => 5.75,
Arrowhead::Custom(c) => c.reach(),
_ => HEAD_REACH,
}
}
/// How far the head spreads either side of its line, in units of its weight.
pub fn half_width(self) -> f64 {
pub fn half_width(&self) -> f64 {
match self {
Arrowhead::LineArrow => 4.0,
Arrowhead::Custom(c) => c.half_width(),
_ => 2.0,
}
}
/// How far past its end point a head placed with [`ArrowAlign::Extend`] can paint, in units of
/// its weight: the built-in heads' length, or a custom head's reach past its tip, which sits
/// [`CustomArrowhead::stop`] past the end point.
pub fn length(&self) -> f64 {
match self {
Arrowhead::Custom(c) => c.stop() + c.reach(),
_ => 4.0,
}
}
/// The name the arrowhead menus show.
pub fn label(self) -> &'static str {
/// The name the arrowhead menus show: [`Self::label`], or a custom head's own name.
pub fn name(&self) -> &str {
match self {
Arrowhead::Custom(c) => &c.name,
_ => self.label(),
}
}
/// The name the arrowhead menus show for a built-in head ("Custom" for a custom one, whose
/// own name is [`Self::name`]).
pub fn label(&self) -> &'static str {
match self {
Arrowhead::Triangle => "Triangle",
Arrowhead::TriangleOpen => "Triangle (open)",
@@ -210,6 +302,7 @@ impl Arrowhead {
Arrowhead::TriangleBar => "Triangle to Bar",
Arrowhead::Oval => "Oval",
Arrowhead::LineArrow => "Line Arrow",
Arrowhead::Custom(_) => "Custom",
}
}
}
+53 -1
View File
@@ -337,13 +337,65 @@ fn arrowhead_names_are_stable_and_every_one_is_listed_once() {
];
for name in SAVED {
let a: Arrowhead = serde_json::from_value(serde_json::json!(name)).unwrap();
assert_eq!(serde_json::to_value(a).unwrap(), name);
assert_eq!(serde_json::to_value(&a).unwrap(), name);
assert_eq!(Arrowhead::ALL.iter().filter(|x| **x == a).count(), 1, "{name} in the menu once");
}
let labels: std::collections::HashSet<&str> = Arrowhead::ALL.iter().map(|a| a.label()).collect();
assert_eq!(labels.len(), Arrowhead::ALL.len(), "labels are distinct");
}
/// A custom head: a triangle from its tip back 3 units, 2 units right and 1 left of its line.
fn custom_head() -> Arrowhead {
use vectorcraft_geom::{PathData, Point, SubPath};
let path = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), path)))
}
#[test]
fn custom_arrowheads_carry_their_art_and_measure_it() {
let head = custom_head();
assert_eq!((head.name(), head.label()), ("Wedge", "Custom"));
assert_eq!(head.reach(), 3.0f64.hypot(2.0));
assert_eq!(head.half_width(), 2.0);
let Arrowhead::Custom(c) = &head else { panic!("custom") };
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
// Saved with the stroke, art and all, beside the built-in heads' names.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
let json = serde_json::to_value(&st).unwrap();
assert_eq!(json["start_arrow"], "Triangle");
assert_eq!(json["end_arrow"]["Custom"]["name"], "Wedge");
let back: StrokeLayer = serde_json::from_value(json).unwrap();
assert_eq!(back, st);
// Extended, the tip sits the stop past the end point; on it, only the reach counts.
assert_eq!(head.length(), 1.5 + head.reach());
assert_eq!(st.head_reach(true), head.length() * 2.0 + 1.0);
st.arrow_align = ArrowAlign::Tip;
assert_eq!(st.head_reach(true), head.reach() * 2.0 + 1.0);
}
#[test]
fn custom_arrowheads_out_of_bounds_draw_nothing() {
let Arrowhead::Custom(c) = custom_head() else { panic!("custom") };
let mut path = c.path.clone();
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
// A file can hold what `new` drops: reading it drops it too.
let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
let anchors = vec![vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1.0, 0.0)); CustomArrowhead::MAX_ANCHORS + 1];
let many = CustomArrowhead::new("Many".into(), vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::new(anchors, true)));
assert!(many.path.subpaths.is_empty(), "too many anchors");
// Empty subpaths add no anchors, and still count.
let mut hollow = c.path.clone();
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
}
#[test]
fn arrow_align_defaults_to_extend_and_round_trips() {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
+301 -12
View File
@@ -236,7 +236,8 @@ fn lcm(a: usize, b: usize) -> usize {
a.checked_div(x).map_or(0, |q| q * b)
}
/// Interpolate width profiles (none is uniform) at every position either has a width point.
/// Interpolate width profiles (none is uniform) at every position either has a width point,
/// keeping their discontinuous points (a position where either steps gives two points).
fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> Option<WidthProfile> {
if x.is_none() && y.is_none() {
return None;
@@ -245,22 +246,45 @@ fn lerp_profile(x: Option<&WidthProfile>, y: Option<&WidthProfile>, t: f64) -> O
let (x, y) = (x.unwrap_or(&uniform), y.unwrap_or(&uniform));
let mut at: Vec<f64> = x.points.iter().chain(&y.points).map(|p| p.0).filter(|p| p.is_finite()).collect();
at.sort_by(f64::total_cmp);
at.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let points = at
.into_iter()
.map(|p| {
let ((l1, r1), (l2, r2)) = (x.at(p), y.at(p));
(p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t))
})
.collect();
// Within the distance `around` reads a discontinuous point at, so a point near one keeps it.
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-7);
// Each profile is a smooth curve through its own points: samples between the positions keep
// both curves' shapes where the other profile's points and steps change the tangents. Two
// profiles with points at the same positions need none (so a preset on both keys stays it).
let same_positions = x.points.len() == y.points.len() && x.points.iter().zip(&y.points).all(|(p, q)| (p.0 - q.0).abs() <= 1e-7);
let per_span = if same_positions { 1 } else { (4096 / at.len().max(1)).clamp(1, 8) };
let mut points = Vec::with_capacity(at.len() * per_span + 2);
let mix = |p: f64, (l1, r1): (f64, f64), (l2, r2): (f64, f64)| (p, lerp_f64(l1, l2, t), lerp_f64(r1, r2, t));
for (k, &p) in at.iter().enumerate() {
let ((xb, xa), (yb, ya)) = (x.around(p), y.around(p));
points.push(mix(p, xb, yb));
// A discontinuous point ends the curve on each side even where both widths match.
if steps_at(x, p) || steps_at(y, p) {
points.push(mix(p, xa, ya));
}
if let Some(&q) = at.get(k + 1) {
for j in 1..per_span {
let f = p + (q - p) * j as f64 / per_span as f64;
points.push(mix(f, x.at(f), y.at(f)));
}
}
}
Some(WidthProfile { points })
}
/// Whether width profile `w` has a discontinuous point at `p` (two points there, within `1e-7`,
/// as [`WidthProfile::around`] reads them).
fn steps_at(w: &WidthProfile, p: f64) -> bool {
let i = w.points.partition_point(|q| q.0 < p - 1e-7);
w.points.get(i..).unwrap_or_default().iter().take_while(|q| q.0 <= p + 1e-7).count() > 1
}
/// The positions along the stroke where either of two pen recordings has a sample, in order.
fn sample_positions(x: Option<&[(f64, f64)]>, y: Option<&[(f64, f64)]>) -> Vec<f64> {
let mut at: Vec<f64> = x.unwrap_or_default().iter().chain(y.unwrap_or_default()).map(|p| p.0).filter(|p| p.is_finite()).collect();
at.sort_by(f64::total_cmp);
at.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
// Within the distance `step_after` reads a step at, so a sample near a step keeps the step.
at.dedup_by(|a, b| (*a - *b).abs() <= 1e-9);
if at.is_empty() {
at = vec![0.0, 1.0];
}
@@ -487,6 +511,161 @@ fn reverse_closed(sp: &mut SubPath) {
sp.anchors.rotate_right(1);
}
/// How a key's subpaths were turned for its blend, so that its stroke's profiles, pen
/// recordings and arrowheads turn with it: position `u` along the turned subpath is position
/// `start + u` (`start - u` when `reversed`) along the key's own, wrapping round a closed one.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
struct Orient {
start: f64,
reversed: bool,
closed: bool,
}
impl Orient {
fn of(sp: &SubPath) -> Self {
Self { closed: sp.closed, ..Self::default() }
}
/// The subpath now starts at the fraction `f` of its length.
fn rotate(&mut self, f: f64) {
self.start += if self.reversed { -f } else { f };
}
/// The subpath now runs the other way.
fn reverse(&mut self) {
self.start += if self.reversed { -1.0 } else { 1.0 };
self.reversed = !self.reversed;
}
/// As [`start_at`] turns `sp` (call it before).
fn start_at(&mut self, sp: &SubPath, i: usize) {
let n = sp.anchors.len();
if i >= n {
return;
}
if sp.closed {
self.rotate(arc_fraction(sp, i));
} else if i + 1 == n && n > 1 {
self.reverse();
}
}
/// Where a closed subpath now starts, as a fraction of its length; 0 for an open one.
fn seam(&self) -> f64 {
let s = if self.closed { self.start.rem_euclid(1.0) } else { 0.0 };
if s > 1e-9 && s < 1.0 - 1e-9 { s } else { 0.0 }
}
fn is_identity(&self) -> bool {
!self.reversed && self.seam() == 0.0
}
/// Whether two subpaths were turned alike, so one stroke along both turns the same way.
fn same_turn(&self, o: &Self) -> bool {
self.reversed == o.reversed && (self.seam() - o.seam()).abs() < 1e-9
}
}
/// How far along `sp` its anchor `i` sits, as a fraction of its length.
fn arc_fraction(sp: &SubPath, i: usize) -> f64 {
let pos = sp.anchor_arc_positions();
match (pos.get(i), pos.last()) {
(Some(&at), Some(&total)) if total.is_finite() && total > 1e-12 => (at / total).clamp(0.0, 1.0),
_ => 0.0,
}
}
/// Samples (position, value) along a key's subpath, read along the subpath turned as `o` says.
/// A closed subpath starting elsewhere starts the samples there too: the ones before it move
/// past the seam (`wrap` applied), which keeps any step the seam makes, and a value between
/// samples is read with `at`. A reversed subpath then reads them backwards (`flip` applied).
fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wrap: impl Fn(V) -> V, flip: impl Fn(V) -> V) -> Vec<(f64, V)> {
let s = o.seam();
let mut out = points.to_vec();
if s > 0.0
&& let (Some(&(_, first)), Some(&(_, last))) = (points.first(), points.last())
{
let i = points.partition_point(|q| q.0 < s - 1e-9);
let j = points.partition_point(|q| q.0 <= s + 1e-9).max(i);
let (before, after) = match points.get(i..j) {
Some([p, .., q]) => (p.1, q.1),
Some([p]) => (p.1, p.1),
_ => (at(s), at(s)),
};
out = Vec::with_capacity(points.len() + 4);
out.push((0.0, after));
out.extend(points.get(j..).unwrap_or_default().iter().map(|&(t, v)| (t - s, v)));
out.push((1.0 - s, last));
out.push((1.0 - s, wrap(first)));
out.extend(points.get(..i).unwrap_or_default().iter().map(|&(t, v)| (t + 1.0 - s, wrap(v))));
out.push((1.0, wrap(before)));
}
if o.reversed {
out = out.into_iter().rev().map(|(t, v)| (1.0 - t, flip(v))).collect();
}
out
}
/// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap
/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its
/// arrowheads.
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
if o.is_identity() {
return;
}
let same = |v: f64| v;
if let Some(p) = &mut s.profile {
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
// A width profile is a smooth curve through its points: where the new start splits a span,
// samples of that span keep its curve once its ends become ends of the profile.
let seam = o.seam();
let i = p.points.partition_point(|q| q.0 < seam);
if seam > 0.0
&& let (Some(a), Some(b)) = (i.checked_sub(1).and_then(|j| p.points.get(j)), p.points.get(i))
&& seam - a.0 > 1e-9
&& b.0 - seam > 1e-9
{
const SAMPLES: usize = 32;
let (a, b) = (a.0, b.0);
let extra: Vec<(f64, (f64, f64))> =
(1..SAMPLES).map(|k| a + (b - a) * k as f64 / SAMPLES as f64).filter(|f| (f - seam).abs() > 1e-9).map(|f| (f, p.at(f))).collect();
pts.splice(i..i, extra);
}
let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l));
p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect();
}
for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() {
let out = reoriented(&p.points, o, |f| p.at(f), same, same);
p.points = out;
}
for p in [&mut s.bearing, &mut s.rotation].into_iter().flatten() {
// The samples moved past the seam carry the whole turns the recording makes along the
// stroke, so the angle does not jump by them there.
let turns = match (p.points.first(), p.points.last()) {
(Some(a), Some(b)) if (b.1 - a.1).is_finite() => ((b.1 - a.1) / 360.0).round() * 360.0,
_ => 0.0,
};
let out = reoriented(&p.points, o, |f| p.unwrapped_at(f), |v| v + turns, same);
p.points = out;
}
if o.reversed && !o.closed {
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
}
}
/// `n` with every stroke read along its subpaths turned as `o` says.
fn reorient_strokes(n: &mut Node, o: Orient) {
if o.is_identity() {
return;
}
for it in n.appearance.items.iter_mut() {
if let AppearanceItem::Stroke(s) = it {
reorient_stroke(s, o);
}
}
}
/// Anchor positions of a subpath relative to its box, scaled to unit size.
fn normalised(sp: &SubPath) -> Vec<Vec2> {
let pts = sp.anchors.iter().map(|a| a.p);
@@ -524,6 +703,8 @@ fn best_rotation(a: &SubPath, b: &SubPath) -> usize {
pub struct PathPair {
a: Vec<SubPath>,
b: Vec<SubPath>,
/// How each path's subpaths were turned, where all of them turned alike (else unturned).
orient: (Orient, Orient),
}
impl PathPair {
@@ -535,6 +716,7 @@ impl PathPair {
let cb = b.bounds().map(|r| r.center()).unwrap_or_default();
let degenerate = |like: &SubPath, c: Point| SubPath::new(vec![Anchor::corner(c); like.anchors.len().max(1)], like.closed);
let (mut va, mut vb) = (Vec::with_capacity(n), Vec::with_capacity(n));
let mut orient = (Orient::default(), Orient::default());
for i in 0..n {
let (mut sa, mut sb) = match (a.subpaths.get(i), b.subpaths.get(i)) {
(Some(x), Some(y)) => (x.clone(), y.clone()),
@@ -542,17 +724,21 @@ impl PathPair {
(None, Some(y)) => (degenerate(y, ca), y.clone()),
(None, None) => continue,
};
let (mut oa, mut ob) = (Orient::of(&sa), Orient::of(&sb));
let explicit = i == 0 && (starts.0.is_some() || starts.1.is_some());
if explicit {
if let Some(s) = starts.0 {
oa.start_at(&sa, s);
start_at(&mut sa, s);
}
if let Some(s) = starts.1 {
ob.start_at(&sb, s);
start_at(&mut sb, s);
}
}
let closed = sa.closed && sb.closed && sa.anchors.len() > 2 && sb.anchors.len() > 2;
if closed && (sa.area() * sb.area()) < 0.0 {
ob.reverse();
reverse_closed(&mut sb);
}
let m = sa.anchors.len().max(sb.anchors.len());
@@ -560,12 +746,26 @@ impl PathPair {
grow(&mut sb, m);
if closed && !explicit {
let r = best_rotation(&sa, &sb);
if r != 0 {
ob.rotate(arc_fraction(&sb, r));
}
sb.anchors.rotate_left(r);
}
// One stroke runs along every subpath of a key, each reading it by its own length, so
// it turns only when all of the key's subpaths turned alike.
if i == 0 {
orient = (oa, ob);
}
if i < a.subpaths.len() && !orient.0.same_turn(&oa) {
orient.0 = Orient::default();
}
if i < b.subpaths.len() && !orient.1.same_turn(&ob) {
orient.1 = Orient::default();
}
va.push(sa);
vb.push(sb);
}
Self { a: va, b: vb }
Self { a: va, b: vb, orient }
}
/// The path at `t` (0 = `a`, 1 = `b`).
@@ -680,7 +880,12 @@ impl Lerp {
_ => Shape::Other,
},
};
Self { a: a.clone(), b: b.clone(), shape }
let (mut a, mut b) = (a.clone(), b.clone());
if let Shape::Path { pair, .. } = &shape {
reorient_strokes(&mut a, pair.orient.0);
reorient_strokes(&mut b, pair.orient.1);
}
Self { a, b, shape }
}
/// The object at `t` (0 = `a`, 1 = `b`), with id 0.
@@ -1597,6 +1802,7 @@ pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
#[cfg(test)]
mod tests {
use super::*;
use crate::appearance::Arrowhead;
use vectorcraft_geom::{Rect, shapes};
#[test]
@@ -1909,6 +2115,89 @@ mod tests {
assert!(s.pressure.is_none() && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none());
}
#[test]
fn a_point_near_the_other_keys_step_keeps_the_step() {
let flat = PressureProfile { points: vec![(0.0, 0.0), (0.4999995, 0.0), (1.0, 0.0)] };
let stepped = PressureProfile { points: vec![(0.0, 0.0), (0.5, 0.0), (0.5, 1.0), (1.0, 1.0)] };
let p = lerp_pressure(Some(&flat), Some(&stepped), 1.0).unwrap_or_default();
assert!((p.at(0.75) - 1.0).abs() < 1e-9, "{p:?}");
let narrow = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.4999995, 1.0, 1.0), (1.0, 1.0, 1.0)] };
let stepped = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)] };
let w = lerp_profile(Some(&narrow), Some(&stepped), 1.0).unwrap_or_default();
assert!(w.at(0.75).0.abs() < 1e-9, "{w:?}");
// The other key's step doesn't reshape a smooth profile's curve.
let early = WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.25, 1.0, 1.0), (0.25, 0.5, 0.5), (1.0, 0.5, 0.5)] };
let w = lerp_profile(Some(&WidthProfile::lens()), Some(&early), 0.0).unwrap_or_default();
for u in [0.1, 0.125, 0.2, 0.3, 0.4] {
let (got, want) = (w.at(u).0, WidthProfile::lens().at(u).0);
assert!((got - want).abs() < 5e-3, "at {u}: {got} for {want}: {w:?}");
}
let lens = WidthProfile::lens();
assert_eq!(lerp_profile(Some(&lens), Some(&lens), 0.5).and_then(|p| p.preset_id()), Some("lens"));
}
#[test]
fn stroke_profiles_turn_with_a_key_path_started_elsewhere() {
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
let mut ap = Appearance::default();
ap.set_stroke(Paint::solid(Color::BLACK));
if let Some(s) = ap.stroke_mut() {
edit(s);
}
Node::path(NodeId(1), path, ap)
};
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
let pressure = |s: &StrokeLayer, f: f64| s.pressure.as_ref().map_or(PressureProfile::MID, |p| p.at(f));
// An open key clicked at its last anchor runs the other way, and so do its pressure, its
// width profile (whose sides swap) and its arrowheads.
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 10.0, 0.0)], false));
let light = keyed(line(0.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 0.0)] }));
let ramp = keyed(line(100.0), &|s| {
s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] });
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] });
s.start_arrow = Some(Arrowhead::Triangle);
s.arrow_scale = (200.0, 100.0);
});
let blend = Lerp::new(&light, &ramp, (None, Some(1)));
let s = stroke(&blend.at(0.25));
assert!(pressure(&s, 0.0).abs() < 1e-9 && (pressure(&s, 1.0) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
let s = stroke(&blend.at(1.0));
assert_eq!(s.profile.as_ref().map(|p| p.at(1.0)), Some((0.0, 1.0)), "{:?}", s.profile);
assert_eq!((s.start_arrow, s.end_arrow, s.arrow_scale), (None, Some(Arrowhead::Triangle), (100.0, 200.0)));
// A key whose other subpaths keep their direction keeps its one stroke as it is.
let two = |x: f64| {
let sub = |y: f64| SubPath::polyline(&[Point::new(x, y), Point::new(x + 10.0, y)], false);
PathData::new(vec![sub(0.0), sub(20.0)])
};
let ramps = keyed(two(100.0), &|s| s.pressure = Some(PressureProfile { points: vec![(0.0, 1.0), (1.0, 0.0)] }));
let s = stroke(&Lerp::new(&keyed(two(0.0), &|_| {}), &ramps, (None, Some(1))).at(1.0));
assert!((pressure(&s, 0.0) - 1.0).abs() < 1e-9, "{:?}", s.pressure);
// A closed key started half way round starts its recordings there too, keeping the step
// where its own start was and the whole turn its rotation makes.
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
let plain = keyed(square(0.0), &|_| {});
let turning = keyed(square(100.0), &|s| {
s.pressure = Some(PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] });
s.rotation = Some(AngleProfile { points: vec![(0.0, 0.0), (1.0, 360.0)] });
s.profile = Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (1.0, 0.0, 0.0)] });
});
let blend = Lerp::new(&plain, &turning, (Some(0), Some(2)));
let s = stroke(&blend.at(1.0));
assert!((pressure(&s, 0.25) - 0.75).abs() < 1e-9 && (pressure(&s, 0.75) - 0.25).abs() < 1e-9, "{:?}", s.pressure);
let width = s.profile.as_ref().map_or((1.0, 1.0), |p| p.at(0.75));
assert!((width.0 - 0.75).abs() < 1e-6 && (width.1 - 0.75).abs() < 1e-6, "the width steps where the key started: {:?}", s.profile);
// A width curve split by the new start keeps its shape.
let lensed = keyed(square(100.0), &|s| s.profile = Some(WidthProfile::lens()));
let s = stroke(&Lerp::new(&plain, &lensed, (Some(0), Some(1))).at(1.0));
for u in [0.05, 0.125, 0.2, 0.6, 0.7, 0.74, 0.76, 0.8, 0.875, 0.95] {
let (got, want) = (s.profile.as_ref().map_or(1.0, |p| p.at(u).0), WidthProfile::lens().at((u + 0.25) % 1.0).0);
assert!((got - want).abs() < 2e-3, "at {u}: {got} for {want}: {:?}", s.profile);
}
let rot = |t: f64, f: f64| stroke(&blend.at(t)).rotation.as_ref().map_or(0.0, |p| p.unwrapped_at(f));
assert!((vectorcraft_geom::normalize_deg(rot(1.0, 0.25)) + 90.0).abs() < 1e-6, "{:?}", s.rotation);
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
}
#[test]
fn odd_dash_blends_to_solid_with_closed_gaps() {
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
+1 -1
View File
@@ -150,7 +150,7 @@ fn planar(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>) -> bool {
/// stores each pixel's samples together or one plane per channel. `None` when they don't decode to
/// that many samples, which includes images whose planes together need more than the decoder's
/// limit (256 MB of samples).
fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
pub(crate) fn read_samples(d: &mut tiff::decoder::Decoder<Cursor<&[u8]>>, n: usize, per: usize) -> Option<Vec<u8>> {
let mut buf = tiff::decoder::DecodingResult::U8(Vec::new());
let layout = d.read_image_to_buffer(&mut buf).ok()?;
let data = match buf {
+197
View File
@@ -0,0 +1,197 @@
//! Image Tools › Color Mask: colors of an image object that are hidden while its pixels stay as
//! they are.
//!
//! A masked image is an ordinary image ([`NodeKind::Image`]) with a [`ColorMask`] in its extras
//! ([`crate::node::NodeExtras::color_mask`]). The record holds the mask's settings and the key of
//! the image's pixels with the hidden colors made clear ([`ColorMask::key`]), made by the engine
//! from the pixels named by [`ColorMask::from`]. The image's own key keeps naming its own pixels,
//! so removing the mask gives them back. While the image's key is [`ColorMask::from`], it is drawn
//! and output with the masked pixels ([`Document::shown_image`]); when another key replaced it
//! (a link updated, the image cropped), it shows its own pixels until the engine makes the masked
//! pixels again.
//!
//! The concept is that of PDF's color key masking (ISO 32000-1, 8.9.6.4): samples in the chosen
//! colors are not painted and what is behind the image shows through. Which colors match, and how
//! near ones fade out, are VectorCraft's own rules.
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
use crate::{Document, ImageObject, Node, NodeKind};
/// Where a color mask's colors come from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MaskBackground {
/// The most common color along the image's edges.
#[default]
Edges,
/// The average of the image's corner pixels that are not clear.
Corners,
/// The colors in [`ColorMask::colors`].
Colors,
}
/// How near a color must be to a masked one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MaskMatch {
/// The RGB distance, as a percentage of the largest one.
#[default]
Distance,
/// The largest difference on one of red, green and blue, as a percentage of a channel's range.
Channels,
}
/// The colors an image object hides (see the module docs).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ColorMask {
/// Key into [`Document::images`]: the pixels of [`Self::from`] with the hidden colors made
/// clear. Named `key` in the file, so the file keeps those pixels with the document.
pub key: String,
/// The image's own key when the masked pixels were made.
pub from: String,
#[serde(default)]
pub background: MaskBackground,
/// The hidden colors (8-bit RGB) with [`MaskBackground::Colors`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub colors: Vec<[u8; 3]>,
/// Only the matching pixels that reach in from an edge are hidden. A record without it reads
/// as `true`, the command's default.
#[serde(default = "default_contiguous")]
pub contiguous: bool,
#[serde(default, rename = "match")]
pub measure: MaskMatch,
/// How near a color must be to be hidden, 0 to 100 (see [`MaskMatch`]). A record without it
/// reads as 10, the command's default.
#[serde(default = "default_percent")]
pub tolerance: f64,
/// The band past the tolerance over which pixels fade from hidden to shown, 0 to 100. A record
/// without it reads as 10, the command's default.
#[serde(default = "default_percent")]
pub softness: f64,
}
fn default_contiguous() -> bool {
true
}
fn default_percent() -> f64 {
10.0
}
impl ColorMask {
/// Whether the masked pixels were made from the pixels of `im`.
pub fn made_for(&self, im: &ImageObject) -> bool {
im.pixels.is_none() && self.from == im.key
}
}
impl Document {
/// Image `im` of node `n` as it is drawn and output. With a color mask whose masked pixels were
/// made from the image's own pixels and are in this document ([`ColorMask::made_for`]): a copy
/// that shows those pixels and links to no file, so an output that refers to a linked file
/// writes the masked pixels instead. Otherwise, and for a mask that hides nothing (its masked
/// pixels are the image's own), `im` itself.
pub fn shown_image<'a>(&self, n: &Node, im: &'a ImageObject) -> Cow<'a, ImageObject> {
match n.extras().color_mask.as_deref() {
Some(m) if m.key != im.key && m.made_for(im) && self.images.contains_key(&m.key) => {
Cow::Owned(ImageObject { key: m.key.clone(), link: None, ..im.clone() })
}
_ => Cow::Borrowed(im),
}
}
/// The color mask of image node `n`, if it has one.
pub fn color_mask_of(n: &Node) -> Option<&ColorMask> {
matches!(n.kind, NodeKind::Image(_)).then(|| n.extras().color_mask.as_deref()).flatten()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use vectorcraft_geom::Affine;
use super::*;
use crate::{ImageBlob, NodeId};
fn image(key: &str) -> ImageObject {
ImageObject { key: key.into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }
}
fn mask(key: &str, from: &str) -> ColorMask {
ColorMask {
key: key.into(),
from: from.into(),
background: MaskBackground::Colors,
colors: vec![[255, 255, 255]],
contiguous: false,
measure: MaskMatch::Distance,
tolerance: 10.0,
softness: 0.0,
}
}
#[test]
fn a_masked_image_shows_its_masked_pixels_while_they_were_made_from_its_own() {
let mut d = Document::new(100.0, 100.0);
d.images.insert("own".into(), ImageBlob::png(vec![1]));
d.images.insert("masked".into(), ImageBlob::png(vec![2]));
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "own", "no mask: its own pixels");
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "masked");
// Linked: the shown copy links to nothing, so outputs write the masked pixels.
let mut linked = (**im).clone();
linked.link = Some(crate::LinkInfo::new("/a.png"));
assert_eq!(d.shown_image(&n, &linked).link, None);
// Made from other pixels: its own until they are made again.
assert_eq!(d.shown_image(&n, &image("other")).key, "other");
// Masked pixels the document doesn't have: its own.
n.extras_mut().color_mask = Some(Box::new(mask("gone", "own")));
let NodeKind::Image(im) = &n.kind else { unreachable_kind() };
assert_eq!(d.shown_image(&n, im).key, "own");
// Pixels an image holds itself are drawn as they are.
let own = ImageObject { pixels: Some(Arc::new(ImageBlob::png(vec![3]))), ..image("own") };
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
assert_eq!(d.shown_image(&n, &own).key, "own");
// A mask that hides nothing (its masked pixels are the image's own): the image itself, so
// a linked image stays linked in outputs.
n.extras_mut().color_mask = Some(Box::new(mask("own", "own")));
assert_eq!(d.shown_image(&n, &linked).link, linked.link);
}
#[test]
fn a_mask_saves_and_reads_back_with_its_node() {
let mut n = Node::new(NodeId(5), NodeKind::Image(Box::new(image("own"))));
n.extras_mut().color_mask = Some(Box::new(mask("masked", "own")));
let json = serde_json::to_value(&n).unwrap();
assert_eq!(json["color_mask"]["key"], "masked", "the masked pixels' key is a `key` member: {json}");
assert_eq!(json["color_mask"]["match"], "distance");
let back: Node = serde_json::from_value(json).unwrap();
assert_eq!(back, n);
// A node without one writes none.
let plain = Node::new(NodeId(6), NodeKind::Image(Box::new(image("own"))));
assert!(serde_json::to_value(&plain).unwrap().get("color_mask").is_none());
}
/// A record that leaves out settings reads them as the command's defaults: edge color,
/// contiguous, distance, tolerance and softness 10.
#[test]
fn a_record_without_settings_reads_the_defaults() {
let m: ColorMask = serde_json::from_value(serde_json::json!({"key": "masked", "from": "own"})).unwrap();
assert_eq!(
(m.background, m.colors.len(), m.contiguous, m.measure, m.tolerance, m.softness),
(MaskBackground::Edges, 0, true, MaskMatch::Distance, 10.0, 10.0)
);
}
fn unreachable_kind() -> ! {
panic!("an image node")
}
}
+3 -3
View File
@@ -569,7 +569,7 @@ fn clip_contains(clip: &Node, p: Point) -> bool {
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
/// [`clip_contains`].
fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
let frame = |n: &Node| {
let b = n.geometric_bounds()?;
Some(Node::path(n.id, vectorcraft_geom::shapes::rectangle(b), Default::default()))
@@ -640,7 +640,7 @@ fn source_of(n: &Node, scope: Option<NodeId>) -> bool {
/// Do clicks and marquees skip the child `i` of `parent` with `scope` isolated? For a Shaper
/// Group that is its original shapes (its first child), or, in Construction mode, when they are
/// isolated, the art the group shows.
fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
pub fn shaper_hides(parent: &Node, i: usize, scope: Option<NodeId>) -> bool {
parent.extras().shaper.is_some() && (i == 0) != source_of(parent, scope)
}
@@ -1356,7 +1356,7 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
/// when the marquee misses it); otherwise it is all of `r`.
fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
match parent.children().and_then(|c| c.first()) {
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
_ => Some(r),
+7 -5
View File
@@ -11,6 +11,7 @@ pub mod blend;
pub mod cancel;
pub mod clipnest;
pub mod cmyk;
pub mod color_mask;
pub mod compound_shape;
pub mod corners;
pub mod depth;
@@ -51,7 +52,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub mod placed_document;
pub mod plugin_data;
pub mod profiles;
@@ -61,6 +62,7 @@ pub mod rastersettings;
mod reach;
pub mod recolor;
pub mod selection;
pub mod separated;
pub mod setup;
pub mod shaper;
pub mod slices;
@@ -82,8 +84,8 @@ pub(crate) mod skip;
pub use appearance::StrokeGradientMode;
pub use appearance::{
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile, ProfilePreset,
SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
AngleProfile, Appearance, AppearanceItem, ArrowAlign, Arrowhead, CustomArrowhead, Dash, Effect, FillLayer, LineCap, LineJoin, PressureProfile,
ProfilePreset, SavedProfile, StrokeAlign, StrokeLayer, WidthProfile,
};
pub use assets::ExportAsset;
pub use compound_shape::ShapeMode;
@@ -263,8 +265,8 @@ pub struct Document {
/// File → Document Setup (bleed, transparency grid, paper, type options).
#[serde(default, skip_serializing_if = "skip::is_default")]
pub setup: DocSetup,
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers (by name)
/// they were copied from instead of the current layer.
/// Layers panel → Paste Remembers Layers: pasted objects go back into the layers and
/// sublayers they were copied from instead of the current layer.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub paste_remembers_layers: bool,
/// File → File Info (its title is [`Document::info_title`]).
+31
View File
@@ -1025,6 +1025,37 @@ mod tests {
assert_eq!(m.locate_within(Point::new(30.0, 60.0), 3.0), m.locate(Point::new(30.0, 60.0)));
}
/// A point on a mesh's outline locates on the edge it lies on, on all four sides alike, with no
/// tolerance; a point just outside does not, and a tolerance reaches only as far as it says.
/// A point that isn't finite locates nowhere.
#[test]
fn mesh_locate_takes_a_point_on_any_side_of_the_outline() {
for (rows, cols) in [(1, 1), (2, 3)] {
let m =
GradientMesh::for_path(&shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), rows, cols, Color::BLACK, MeshAppearance::Flat, 0.0)
.unwrap();
let sides = [
("top", Point::new(30.0, 0.0), Vec2::new(0.0, -0.01)),
("bottom", Point::new(30.0, 100.0), Vec2::new(0.0, 0.01)),
("left", Point::new(0.0, 70.0), Vec2::new(-0.01, 0.0)),
("right", Point::new(100.0, 70.0), Vec2::new(0.01, 0.0)),
];
for (side, p, out) in sides {
let (r, c, u, v) = m.locate(p).unwrap_or_else(|| panic!("{rows}×{cols} {side}: {p:?} is not located"));
assert!(r < m.rows as usize && c < m.cols as usize && (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v), "{side}");
assert!(m.eval(r, c, u, v).distance(p) < 1e-3, "{rows}×{cols} {side}: {:?}", m.eval(r, c, u, v));
let mut e = m.clone();
assert!(e.add_lines_at(p, 0.0).is_some(), "{rows}×{cols} {side}: no line at {p:?}");
assert_eq!(m.locate(p + out), None, "{rows}×{cols} {side}: just outside");
assert_eq!(m.locate_within(p + out * 100.0, 0.5), None, "{rows}×{cols} {side}: past the tolerance");
assert!(m.locate_within(p + out * 100.0, 1.5).is_some(), "{rows}×{cols} {side}: within the tolerance");
}
for p in [Point::new(f64::NAN, 0.0), Point::new(30.0, f64::INFINITY)] {
assert_eq!(m.locate_within(p, f64::INFINITY), None, "{p:?}");
}
}
}
/// Corners all in CMYK mix in CMYK (the inks halfway), not in RGB.
#[test]
fn a_cmyk_mesh_mixes_its_inks() {
+4 -1
View File
@@ -206,12 +206,14 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
/// that takes the triangle where `f` takes its corners (with `masked`, the image masked by the
/// triangle instead; with `pixelated`, drawn without smoothing). Each piece reaches a little past
/// its edges (at most half a point) so neighbors overlap and no seams show. Each piece keeps the
/// color `n` colorizes a grayscale image with. The result is a group with `n`'s id, name,
/// color `n` colorizes a grayscale image with, and `n`'s color mask. The result is a group with `n`'s id, name,
/// transparency, opacity mask and appearance.
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
let k = cells.max(1);
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
let colorize = n.extras().colorize.clone();
// Each piece shows what the image shows: its color mask's masked pixels.
let color_mask = n.extras().color_mask.clone();
let (pw, ph) = (im.width as f64, im.height as f64);
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
let mut pieces = Vec::with_capacity(2 * k * k);
@@ -236,6 +238,7 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
image.extras_mut().pixelated = pixelated;
image.extras_mut().colorize = colorize.clone();
image.extras_mut().color_mask = color_mask.clone();
if masked {
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
// white opacity mask) instead of its clipping path.
+25 -7
View File
@@ -530,6 +530,10 @@ pub(super) const MAX_BORDER_LINES: usize = 256;
/// The most rounds of new lines a mesh made from a path takes to keep its border on the outline.
const MAX_BORDER_ROUNDS: usize = 64;
/// A point this close (in points) to a mesh's outline is on it, for [`GradientMesh::locate_within`]
/// with any tolerance.
const ON_OUTLINE: f64 = 1e-6;
/// An anchor whose directions in and out differ by more than this (radians) is a corner: a border
/// edge that can't follow the outline takes a mesh line through its sharpest corner first.
const SHARP_TURN: f64 = 0.01;
@@ -1436,17 +1440,23 @@ impl GradientMesh {
}
/// As [`Self::locate`], and for a point outside the mesh within `tol` of its outline, the
/// patch and local (u, v) of the nearest point of the mesh's edge.
/// patch and local (u, v) of the nearest point of the mesh's edge. A point on the outline
/// (within [`ON_OUTLINE`]) locates on its edge on every side, with any `tol`.
pub fn locate_within(&self, p: Point, tol: f64) -> Option<(usize, usize, f64, f64)> {
if !self.is_valid() {
if !self.is_valid() || !p.is_finite() {
return None;
}
let bp = self.outline().to_bezpath();
if bp.winding(p) == 0 {
// A point on the outline takes the nearest point of the edge on every side: the nonzero
// winding number counts a point on some edges as outside (a rectangle's bottom and right
// edges) and on the others as inside.
if let Some((_, r, c, u, v)) = self.nearest_edge(p, ON_OUTLINE).filter(|e| e.0 <= ON_OUTLINE * ON_OUTLINE) {
return Some((r, c, u, v));
}
if self.outline().to_bezpath().winding(p) == 0 {
if tol.is_nan() || tol <= 0.0 {
return None;
}
return self.nearest_edge(p).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
return self.nearest_edge(p, tol).filter(|e| e.0 <= tol * tol).map(|(_, r, c, u, v)| (r, c, u, v));
}
const N: usize = 16;
let mut best = (f64::INFINITY, 0, 0, 0.0, 0.0);
@@ -1484,12 +1494,20 @@ impl GradientMesh {
}
/// The point of the mesh's outer edge nearest `p`: its squared distance from `p`, and its
/// boundary patch and local (u, v).
fn nearest_edge(&self, p: Point) -> Option<(f64, usize, usize, f64, f64)> {
/// boundary patch and local (u, v). Edges whose control points all lie farther than `within`
/// from `p` are skipped, so `None` means no edge is within `within`.
fn nearest_edge(&self, p: Point, within: f64) -> Option<(f64, usize, usize, f64, f64)> {
use vectorcraft_geom::kurbo::ParamCurveNearest;
let (rows, cols) = (self.rows as usize, self.cols as usize);
let mut best: Option<(f64, usize, usize, f64, f64)> = None;
let mut take = |e: CubicBez, at: (usize, usize, Option<f64>, Option<f64>)| {
// The edge lies inside its control points' box, so a box farther than `within` holds
// no point of the edge within it.
let b = Rect::from_points(e.p0, e.p1).union_pt(e.p2).union_pt(e.p3);
let (dx, dy) = ((b.x0 - p.x).max(p.x - b.x1).max(0.0), (b.y0 - p.y).max(p.y - b.y1).max(0.0));
if dx * dx + dy * dy > within * within {
return;
}
let n = e.nearest(p, 1e-9);
if best.is_none_or(|b| n.distance_sq < b.0) {
let (r, c, u, v) = at;
+4
View File
@@ -261,6 +261,10 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
b += ALLOC + size_of::<NodeExtras>();
b += boxed(&e.mask) + boxed(&e.graph) + boxed(&e.shaper) + boxed(&e.attrs) + boxed(&e.slice) + boxed(&e.perspective);
b += boxed(&e.dimension) + boxed(&e.live_paint_gaps) + boxed(&e.colorize);
b += e
.color_mask
.as_deref()
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
+4
View File
@@ -72,6 +72,9 @@ pub struct NodeExtras {
/// Transform panel › Align to Pixel Grid: the path's or compound path's horizontal and vertical
/// segments stay on the pixel grid when it is transformed.
pub pixel_aligned: bool,
/// Image Tools › Color Mask: the colors an image hides while its pixels stay as they are
/// ([`crate::color_mask`]).
pub color_mask: Option<Box<crate::color_mask::ColorMask>>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -99,6 +102,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
symbol_overrides: Vec::new(),
envelope_edit_margin: None,
pixel_aligned: false,
color_mask: None,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+24 -13
View File
@@ -819,7 +819,8 @@ impl Node {
impl Node {
/// Whether this object shows any transparency, itself or anything inside it: object, fill or
/// stroke opacity below 100%, a blend mode, an opacity mask, effects, transparent gradient
/// stops or a colorized image. Hidden objects show none.
/// stops (characters' fills and strokes included) or a colorized image. Hidden objects show
/// none.
pub fn shows_transparency(&self) -> bool {
self.shows_transparency_with(&|_| true)
}
@@ -827,21 +828,31 @@ impl Node {
/// [`Self::shows_transparency`], counting a colorized image by itself only when `colorize`
/// accepts it, for files that write some colorized images in their colorize paint (EPS).
pub fn shows_transparency_with(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
self.visible && (self.own_transparency(colorize) || self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
}
/// [`Self::shows_transparency`] of the object alone, what it holds left out.
pub fn shows_own_transparency(&self) -> bool {
self.visible && self.own_transparency(&|_| true)
}
/// The object's own transparency, as [`Self::shows_transparency_with`] counts it.
fn own_transparency(&self, colorize: &dyn Fn(&Node) -> bool) -> bool {
use vectorcraft_color::Paint;
let see_through = |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.stops.iter().any(|s| s.opacity < 1.0));
let effects = |fx: &[crate::Effect]| fx.iter().any(|e| e.visible);
self.visible
&& (self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
|| self.children().is_some_and(|ch| ch.iter().any(|c| c.shows_transparency_with(colorize))))
self.opacity < 1.0
|| self.blend != BlendMode::Normal
|| self.extras().mask.as_ref().is_some_and(|m| !m.disabled)
|| (matches!(self.kind, NodeKind::Image(_)) && self.extras().colorize.is_some() && colorize(self))
|| effects(&self.appearance.effects)
|| self
.appearance
.items
.iter()
.any(|i| i.visible() && (i.opacity() < 1.0 || i.blend() != BlendMode::Normal || see_through(i.paint()) || effects(i.effects())))
// Characters' own fills and strokes, which draw with the object.
|| matches!(&self.kind, NodeKind::Text(t) if t.runs.iter().any(|r| see_through(&r.style.fill) || (r.style.stroke_width > 0.0 && see_through(&r.style.stroke))))
}
}
+5
View File
@@ -55,6 +55,7 @@ impl Serialize for Node {
e.symbol_overrides.is_empty(),
e.envelope_edit_margin.is_none(),
is_default(&e.pixel_aligned),
e.color_mask.is_none(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -98,6 +99,7 @@ impl Serialize for Node {
field!("symbol_overrides", &e.symbol_overrides);
field!("envelope_edit_margin", &e.envelope_edit_margin);
field!("pixel_aligned", &e.pixel_aligned);
field!("color_mask", &e.color_mask);
st.end()
}
}
@@ -241,6 +243,8 @@ pub(super) struct NodeWire {
envelope_edit_margin: Option<[f32; 4]>,
#[serde(default)]
pixel_aligned: bool,
#[serde(default)]
color_mask: Option<Box<crate::color_mask::ColorMask>>,
}
impl From<NodeWire> for Node {
@@ -269,6 +273,7 @@ impl From<NodeWire> for Node {
symbol_overrides: w.symbol_overrides,
envelope_edit_margin: w.envelope_edit_margin,
pixel_aligned: w.pixel_aligned,
color_mask: w.color_mask,
};
Node {
id: w.id,
+74
View File
@@ -11,6 +11,10 @@ use crate::ImageBlob;
/// address and aborts when an allocation fails, so it keeps the decoder's own 512 MB.
pub const MAX_RASTER_ALLOC: u64 = if cfg!(target_arch = "wasm32") { 512 << 20 } else { 2 << 30 };
/// A box of an image to sample, in 0 to 1 units of its width and height (`None`: all of it), the
/// pixels to sample from it at most, and the pixel centres to take ([`ImageBlob::sample_pixels`]).
pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool);
/// The pixels of encoded image `bytes` as RGBA; `None` when they can't be decoded, would take
/// more than `max` bytes as RGBA, or need more than `max` bytes to decode. The size is read from
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
@@ -61,6 +65,49 @@ impl ImageBlob {
Some(Self::png(png))
}
/// For each of `picks`, at most its budget of the image's pixels (at least one), spread evenly
/// in rows and columns over the pick's box (`[u0, v0, u1, v1]`, where 0 to 1 spans the
/// image's width and height from the top left; clipped to the image; `None`: the whole image),
/// as straight RGBA. Only pixels whose centres the pick's function takes (in the same 0 to 1
/// units) are given, and the function is called once for each pixel sampled. The image is
/// decoded once for all the picks. `None` when it can't be decoded within [`MAX_RASTER_ALLOC`].
pub fn sample_pixels(&self, picks: &[PixelPick<'_>]) -> Option<Vec<Vec<[u8; 4]>>> {
let img = rgba_within(&self.bytes, MAX_RASTER_ALLOC)?;
let (w, h) = img.dimensions();
let (fw, fh) = (f64::from(w), f64::from(h));
let span = |a: f64, b: f64, n: f64| {
let (a, b) = (a.min(b), a.max(b));
((a * n).floor().clamp(0.0, n) as u32, (b * n).ceil().clamp(0.0, n) as u32)
};
let sample = |area: Option<[f64; 4]>, budget: usize, keep: &dyn Fn(f64, f64) -> bool| {
let [u0, v0, u1, v1] = area.unwrap_or([0.0, 0.0, 1.0, 1.0]);
let (x0, x1) = span(u0, u1, fw);
let (y0, y1) = span(v0, v1, fh);
if x0 >= x1 || y0 >= y1 {
return vec![];
}
// Rows and columns in proportion to the box, at most `budget` cells in all.
let (bw, bh, budget) = (f64::from(x1 - x0), f64::from(y1 - y0), budget.max(1) as f64);
let (sx, sy) = if bw * bh <= budget {
(1, 1)
} else {
let rows = (budget * bh / bw).sqrt().floor().clamp(1.0, bh.min(budget));
let cols = (budget / rows).floor().clamp(1.0, bw);
((bw / cols).ceil() as usize, (bh / rows).ceil() as usize)
};
let mut out = vec![];
for y in (y0..y1).step_by(sy) {
for x in (x0..x1).step_by(sx) {
if keep((f64::from(x) + 0.5) / fw, (f64::from(y) + 0.5) / fh) {
out.push(img.get_pixel(x, y).0);
}
}
}
out
};
Some(picks.iter().map(|(area, budget, keep)| sample(*area, *budget, *keep)).collect())
}
/// The image as a grayscale PNG: `f` gives each pixel's gray level from its (straight) RGB, and
/// the PNG has an alpha channel only when some pixel isn't opaque. `f` runs once per distinct
/// color. `None` when the image can't be decoded, or when its file stores grayscale already
@@ -276,6 +323,33 @@ mod tests {
image::load_from_memory(&b.bytes).unwrap().to_rgba8().pixels().map(|p| p.0).collect()
}
/// Sampling reads the pixels of a box of the image, spread to about the budget, and only those
/// whose centres `keep` takes.
#[test]
fn sampled_pixels_stay_in_their_box_and_budget() {
// 4 × 2: a red left half and a blue right half.
let (r, b) = ([255, 0, 0, 255], [0, 0, 255, 255]);
let img = blob(&[r, r, b, b, r, r, b, b], 4, 2);
let any = |_: f64, _: f64| true;
let one = |b: &ImageBlob, area: Option<[f64; 4]>, budget: usize| b.sample_pixels(&[(area, budget, &any)]).unwrap().remove(0);
assert_eq!(one(&img, None, 100).len(), 8, "the budget covers every pixel");
assert_eq!(one(&img, Some([0.5, 0.0, 1.0, 1.0]), 100), vec![b; 4], "the right half");
assert_eq!(one(&img, Some([1.0, 1.0, 0.5, 0.0]), 100), vec![b; 4], "a box given backwards");
assert!(one(&img, Some([2.0, 0.0, 3.0, 1.0]), 100).is_empty(), "outside the image");
assert_eq!(one(&img, None, 2).len(), 2, "every second pixel of every second row");
assert_eq!(one(&img, None, 0), vec![r], "a budget of 0 counts as 1");
let left = |u: f64, _: f64| u < 0.5;
let both = img.sample_pixels(&[(None, 100, &left), (Some([0.5, 0.0, 1.0, 1.0]), 100, &any)]).unwrap();
assert_eq!(both, vec![vec![r; 4], vec![b; 4]], "several picks, each with the centres its function takes");
let sizes: Vec<usize> = img.sample_pixels(&[(None, 2, &any), (None, 100, &any)]).unwrap().iter().map(Vec::len).collect();
assert_eq!(sizes, [2, 8], "each pick keeps to its own budget");
// A narrow image keeps to the budget too.
let tall = blob(&vec![r; 5000], 1, 5000);
let n = one(&tall, None, 100).len();
assert!((50..=100).contains(&n), "{n} pixels");
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
+30 -1
View File
@@ -517,7 +517,12 @@ fn rename(n: &mut Node, prefix: &str) {
paint(&mut r.style.stroke);
}
}
NodeKind::Image(im) => im.key = format!("{prefix}{}", im.key),
NodeKind::Image(im) => {
im.key = format!("{prefix}{}", im.key);
if let Some(m) = n.extras.0.as_deref_mut().and_then(|e| e.color_mask.as_deref_mut()) {
(m.key, m.from) = (format!("{prefix}{}", m.key), format!("{prefix}{}", m.from));
}
}
NodeKind::PlacedDocument(p) => p.key = format!("{prefix}{}", p.key),
NodeKind::SymbolInstance { symbol, .. } => *symbol = format!("{prefix}{symbol}"),
_ => {}
@@ -681,6 +686,30 @@ mod tests {
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
}
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
/// names its resources get.
#[test]
fn a_color_mask_takes_the_prefixed_image_names() {
let im =
ImageObject { key: "own".into(), width: 2, height: 2, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
let mut n = Node::new(NodeId(7), NodeKind::Image(Box::new(im)));
n.extras_mut().color_mask = Some(Box::new(crate::color_mask::ColorMask {
key: "masked".into(),
from: "own".into(),
background: Default::default(),
colors: vec![],
contiguous: true,
measure: Default::default(),
tolerance: 10.0,
softness: 10.0,
}));
rename(&mut n, "p:");
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
let m = Document::color_mask_of(&n).unwrap();
assert_eq!((im.key.as_str(), m.key.as_str(), m.from.as_str()), ("p:own", "p:masked", "p:own"));
assert!(m.made_for(im));
}
#[test]
fn round_trips_through_json() {
let n = Node::new(NodeId(3), NodeKind::PlacedDocument(Box::new(placed("doc1-1"))));
+237 -69
View File
@@ -1,6 +1,7 @@
//! Where a path's strokes paint, from the path's geometry without building their outlines: the
//! visual bounds and the clicks of a stroke take in its alignment, its width profile, miter spikes
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points.
//! up to the miter limit, projecting caps and arrowheads. Butt caps end at the path's end points,
//! and a bevel ends at the corners of the two segments it joins.
use vectorcraft_geom::bez::{CORNER_COS, has_length, kink, segments, subpaths, tangent, unit};
use vectorcraft_geom::hit::fill_contains;
@@ -39,10 +40,20 @@ fn joints(segs: &[PathSeg], closed: bool) -> impl Iterator<Item = (Point, Vec2,
/// path: its tip and the corner's outer offset points, or `None` when the path doesn't turn there
/// or the miter limit bevels it.
fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[Point; 3]> {
let cos = t_in.dot(t_out);
// cos(half the turn) is sin(half the angle between the segments): the miter is side / it.
let half = ((1.0 + cos) / 2.0).max(0.0).sqrt();
if cos >= CORNER_COS || half * limit < 1.0 {
let half = ((1.0 + t_in.dot(t_out)) / 2.0).max(0.0).sqrt();
if half * limit < 1.0 {
return None;
}
let ([a, b], out) = bevel(at, t_in, t_out, side)?;
Some([a, at + out * (side / half), b])
}
/// The bevel at a corner with tangents `t_in`, `t_out` of a stroke reaching `side` from its path:
/// the outer corners of the two segments' strokes and the unit direction out of the turn, or
/// `None` when the path doesn't turn there.
fn bevel(at: Point, t_in: Vec2, t_out: Vec2, side: f64) -> Option<([Point; 2], Vec2)> {
if t_in.dot(t_out) >= CORNER_COS {
return None;
}
let out = unit(t_in - t_out);
@@ -51,7 +62,7 @@ fn miter(at: Point, t_in: Vec2, t_out: Vec2, side: f64, limit: f64) -> Option<[P
let n = Vec2::new(-t.y, t.x);
if n.dot(out) >= 0.0 { n } else { -n }
};
Some([at + outer(t_in) * side, at + out * (side / half), at + outer(t_out) * side])
Some(([at + outer(t_in) * side, at + outer(t_out) * side], out))
}
/// The heads' ends of `bp`: the start of its first subpath and the end of its last, when open (as
@@ -187,26 +198,44 @@ fn in_convex(pts: &[Point], p: Point, tol: f64) -> bool {
}
impl StrokeLayer {
/// Does bounding this stroke need its path's shape: miter spikes, projecting caps, arrowheads,
/// an alignment that depends on whether the path is closed, or butt caps, which stop at the
/// ends of an open path? Else it reaches evenly round it.
/// Does bounding this stroke need its path's shape: miter spikes, bevels, projecting caps,
/// arrowheads, an alignment that depends on whether the path is closed, or butt caps, which
/// stop at the ends of an open path? Else it reaches evenly round it.
fn needs_shape(&self) -> bool {
self.join == LineJoin::Miter
self.join != LineJoin::Round
|| self.cap != LineCap::Round
|| self.start_arrow.is_some()
|| self.end_arrow.is_some()
|| self.align != StrokeAlign::Center
}
/// The box this stroke paints along `segs`, the segments with length of an open subpath, when
/// its caps are butt caps: each segment's [`swept_box`] and, with round joins, the arc each
/// joint between segments paints ([`round_join_box`]), a shallow one included.
/// `None` when `segs` is empty. Butt dashes stop inside the same box. The heads and miter tips
/// are measured apart. A segment in the middle is measured only when its own box grown by
/// `side`, which holds everything it paints, is not inside the box so far.
fn butt_body(&self, segs: &[PathSeg], side: f64) -> Option<Rect> {
/// Does this stroke stop at the corners of its segments along a subpath that is `closed` or
/// open, where its caps are butt caps on an open subpath or its joins are bevels or miters?
/// Dashes with round or projecting caps can end at a corner, so with them only butt caps stop.
fn stops_at_corners(&self, closed: bool) -> bool {
let capped_dashes = self.cap != LineCap::Butt && self.dash.as_ref().is_some_and(Dash::is_dashed);
(self.cap == LineCap::Butt && !closed) || (self.join != LineJoin::Round && !capped_dashes)
}
/// Does this stroke reach past a subpath that is `closed` or open by a margin that follows the
/// direction of its segments at their corners: where it stops at them
/// ([`Self::stops_at_corners`]) or paints miter spikes, which dashes with round or projecting
/// caps also paint?
fn reaches_by_corners(&self, closed: bool) -> bool {
self.stops_at_corners(closed) || self.join == LineJoin::Miter
}
/// The box this stroke's body paints along `segs`, the segments with length of a subpath, short
/// of its caps, joined with `within`: each segment's [`swept_box`] and, with round joins on an
/// open subpath, the arc each joint between segments paints ([`round_join_box`]), a shallow one
/// included. A bevel stays inside the boxes of the segments it joins. `None` when `segs` is
/// empty. Butt dashes stop inside the same box. The caps other than butt ones, the heads and
/// miter tips are measured apart. A segment in the middle is measured only when its own box
/// grown by `side`, which holds everything it paints, is not inside the box so far, which
/// starts as `within` and the first and last segments' boxes.
fn body_along(&self, segs: &[PathSeg], side: f64, within: Rect) -> Option<Rect> {
let (first, last) = (segs.first()?, segs.last()?);
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3));
let ends = swept_box(first, side, 3).union(swept_box(last, side, 3)).union(within);
let body = segs.iter().skip(1).take(segs.len().saturating_sub(2)).fold(ends, |b, s| {
if b.contains_rect(ParamCurveExtrema::bounding_box(s).inflate(side, side)) { b } else { b.union(swept_box(s, side, 3)) }
});
@@ -217,24 +246,28 @@ impl StrokeLayer {
}
/// The box this stroke paints along `bp` (geometric bounds `bounds`): an open subpath with butt
/// caps by [`Self::butt_body`], every other subpath by the box of its segments grown by its
/// reach, with `tips` and, when `measure_tips`, the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points.
/// caps, and every subpath when the joins are bevels or miters, by [`Self::body_along`] with its
/// caps, every other subpath by the box of its segments grown by its reach, with `tips` and,
/// when `measure_tips`, the miter spikes the limit keeps, the corners of projecting caps and the
/// reach of the arrowheads round their end points.
fn reach_along(&self, bp: &BezPath, bounds: Rect, tips: Option<Rect>, measure_tips: bool) -> Rect {
let els = bp.elements();
let subs = subpaths(bp);
let mut out = tips.map_or(bounds, |t| bounds.union(t));
let mut side_max: f64 = 0.0;
// Every subpath reaches evenly unless one is open and butt-capped; only then is each
// subpath's own box needed.
let even_only = self.cap != LineCap::Butt || subs.iter().all(|s| s.1);
let mut even = even_only.then_some(bounds);
// Dashes put a cap on every dash: projecting ones reach a corner's diagonal anywhere.
let capped_dashes = self.cap == LineCap::Square && self.dash.as_ref().is_some_and(Dash::is_dashed);
// A butt cap stops at an open subpath's end, and a bevel, or a miter the limit bevels, at
// the two segments' corners, so such a subpath is measured along its segments. Every
// subpath reaches evenly unless one is measured that way; only then is each subpath's own
// box needed.
let even_only = !subs.iter().any(|s| self.stops_at_corners(s.1));
let mut even = even_only.then_some(bounds);
for (r, closed) in subs {
let side = self.side_reach(closed);
let butt = self.cap == LineCap::Butt && !closed;
if !butt {
let along = self.stops_at_corners(closed);
if !along {
side_max = side_max.max(if capped_dashes { side * std::f64::consts::SQRT_2 } else { side });
}
if side <= 0.0 {
@@ -242,10 +275,10 @@ impl StrokeLayer {
}
let square = self.cap == LineCap::Square && !closed;
let miters = measure_tips && self.join == LineJoin::Miter;
if !(butt || square || miters || !even_only) {
if !(along || square || miters || !even_only) {
continue;
}
let segs = drawn(&els[r]);
let segs = drawn(&els[r.clone()]);
if miters {
for (at, t_in, t_out) in joints(&segs, closed) {
if let Some([_, tip, _]) = miter(at, t_in, t_out, side, self.miter_limit) {
@@ -253,13 +286,24 @@ impl StrokeLayer {
}
}
}
if butt {
if let Some(body) = self.butt_body(&segs, side) {
out = out.union(body);
if along {
// The path's bounds are in the box already, so only the segments that can reach
// past them are measured.
match self.body_along(&segs, side, out) {
Some(body) => out = out.union(body),
// A subpath with no length paints at most its caps' dot.
None if !butt => {
let dot = segments(&els[r]).iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b));
out = dot.map_or(out, |d| out.union(d.inflate(side, side)));
}
None => {}
}
continue;
}
if !even_only {
if self.cap == LineCap::Round && !closed {
for (at, _) in ends(&segs).into_iter().flatten() {
out = out.union(Rect::from_center_size(at, (2.0 * side, 2.0 * side)));
}
}
} else if !even_only {
even = vectorcraft_geom::union_opt(even, segs.iter().map(ParamCurveExtrema::bounding_box).reduce(|a, b| a.union(b)));
}
if square {
@@ -279,7 +323,8 @@ impl StrokeLayer {
/// The box this stroke paints along `bp`, whose geometric bounds are `bounds`: the bounds grown
/// by the body's reach, with the tips of the miter spikes the limit keeps, the corners of
/// projecting caps and the reach of the arrowheads round their end points. An open subpath
/// with butt caps does not reach past its ends ([`Self::butt_body`]).
/// with butt caps does not reach past its ends, and a bevel does not reach round its corner
/// ([`Self::body_along`]).
pub fn bounds_on(&self, bp: &BezPath, bounds: Rect) -> Rect {
self.reach_along(bp, bounds, None, true)
}
@@ -329,6 +374,9 @@ impl StrokeLayer {
let segs = drawn(&els[r]);
let (half, region) = self.body(closed);
let full = half * self.profile_max() * dash_caps.unwrap_or(1.0);
// Past a butt cap or a bevel the stroke stops at the segments' corners. A width profile
// keeps the round reach at the ends.
let squared = self.profile.is_none() && self.stops_at_corners(closed);
// Every segment near enough to reach `p`: with a width profile the wider side of a
// farther segment can paint past the nearest one, so the nearest alone is not enough.
let near = segs.iter().enumerate().filter_map(|(i, s)| {
@@ -365,7 +413,8 @@ impl StrokeLayer {
}
})
};
if d <= half * factor.max(0.0) + tol && on_side(region, d) {
if d <= half * factor.max(0.0) + tol && on_side(region, d) && (!squared || self.paints_at_end(&segs, closed, (i, nr.t), p, half, tol))
{
return true;
}
}
@@ -393,6 +442,35 @@ impl StrokeLayer {
false
}
/// Does this stroke, where it stops at the corners of its segments ([`Self::stops_at_corners`]),
/// paint `p`, which is within `side` (and `tol`) of segment `i` of the subpath `segs`
/// (`closed`: a closed one) and nearest to it at `t`? It does when `p` is not past the end of
/// the segment that `t` is at, by more than `tol`, and past it when a round cap or a round join
/// paints there, when the path does not turn at that end, or when `p` is within `tol` of the
/// bevel's triangle. Projecting caps and
/// miter spikes are checked apart. A curve that bends more tightly than `side` ([`gentle`])
/// counts as painting round its ends.
fn paints_at_end(&self, segs: &[PathSeg], closed: bool, (i, t): (usize, f64), p: Point, side: f64, tol: f64) -> bool {
let (n, at_start) = (segs.len(), t <= 1e-9);
let Some(seg) = segs.get(i) else { return true };
if (!at_start && t < 1.0 - 1e-9) || !(matches!(seg, PathSeg::Line(_)) || gentle(seg, side)) {
return true;
}
let (at, out) = if at_start { (seg.start(), -tangent(seg, 0.0)) } else { (seg.end(), tangent(seg, 1.0)) };
if (p - at).dot(out) <= tol {
return true;
}
// The segment on the other side of this end, `None` at the end of an open subpath.
let other = if at_start { (i > 0 || closed).then(|| (i + n - 1) % n) } else { (i + 1 < n || closed).then(|| (i + 1) % n) };
let Some(other) = other.and_then(|o| segs.get(o)) else { return self.cap == LineCap::Round };
if self.join == LineJoin::Round {
return true;
}
let (t_in, t_out) = if at_start { (tangent(other, 1.0), tangent(seg, 0.0)) } else { (tangent(seg, 1.0), tangent(other, 0.0)) };
// A joint where the path does not turn has no bevel: the stroke runs on through it.
bevel(at, t_in, t_out, side).is_none_or(|([a, b], _)| in_convex(&[at, a, b], p, tol))
}
/// Is `p` within `tol` of where the start (`end == false`) or end arrowhead at `at` (the path
/// leaving along `out`) can paint? A head reaches [`crate::Arrowhead::reach`] weights from its tip and
/// [`crate::Arrowhead::half_width`] either side of its line (4.6 and 2 for most). With
@@ -400,13 +478,15 @@ impl StrokeLayer {
/// past the end; with [`ArrowAlign::Tip`] its tip is on the end and it lies back along the
/// chord the path bends through under it, so anywhere within its length of the end.
fn head_contains(&self, at: Point, out: Vec2, end: bool, p: Point, tol: f64) -> bool {
let Some(kind) = (if end { self.end_arrow } else { self.start_arrow }) else { return false };
let Some(kind) = (if end { &self.end_arrow } else { &self.start_arrow }) else { return false };
let (hw, v) = (self.arrow_weight(end), p - at);
match self.arrow_align {
ArrowAlign::Tip => v.hypot() <= kind.reach() * hw + tol,
ArrowAlign::Extend => {
let along = v.dot(out);
v.cross(out).abs() <= kind.half_width() * hw + tol && along <= 4.0 * hw + self.width / 2.0 + tol && along >= -kind.reach() * hw - tol
v.cross(out).abs() <= kind.half_width() * hw + tol
&& along <= kind.length() * hw + self.width / 2.0 + tol
&& along >= -kind.reach() * hw - tol
}
}
}
@@ -426,7 +506,7 @@ impl Appearance {
}
/// [`Self::stroked_bounds`] with the box of each visible stroke that needs the path's shape
/// (miter spikes, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
/// (miter spikes, bevels, projecting or butt caps, arrowheads or an alignment) given by `shaped`.
pub fn stroked_bounds_by(&self, bounds: Rect, mut shaped: impl FnMut(&StrokeLayer) -> Rect) -> Rect {
self.painted_strokes().fold(bounds, |acc, s| {
if !s.needs_shape() {
@@ -437,17 +517,21 @@ impl Appearance {
})
}
/// Does this appearance have a visible butt-capped stroke?
pub fn has_butt_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.cap == LineCap::Butt)
/// Does this appearance have a visible stroke that stops at the corners of its segments on an
/// open subpath or a closed one, or paints miter spikes: butt caps, or bevel and miter joins
/// ([`StrokeLayer::reaches_by_corners`])?
pub fn has_cornered_stroke(&self) -> bool {
self.painted_strokes().any(|s| s.reaches_by_corners(false))
}
/// Does a visible butt-capped stroke of this appearance run along an open subpath of `bp` with
/// a segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at the stroke's corners there depends on their direction, which a scale
/// out of proportion changes.
pub fn has_slanted_butt_stroke(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_butt_stroke() {
/// Does a visible stroke of this appearance that stops at the corners of its segments (butt
/// caps on an open subpath, bevel and miter joins) or paints miter spikes, dashed ones with
/// round or projecting caps included, run along a subpath of `bp` where it does so, with a
/// segment that starts or ends at a slant, not square to the axes, once placed by `a`? The
/// visual box's margin at those corners, and at miter tips, depends on their direction, which a
/// scale out of proportion changes.
pub fn has_slanted_stroke_corners(&self, bp: &BezPath, a: vectorcraft_geom::Affine) -> bool {
if !self.has_cornered_stroke() {
return false;
}
let slanted = |v: Vec2| {
@@ -455,9 +539,10 @@ impl Appearance {
(d.x * d.y).abs() > 1e-9
};
let els = bp.elements();
subpaths(bp)
.into_iter()
.filter(|(_, closed)| !closed)
let subs = subpaths(bp);
let cornered = |closed: bool| self.painted_strokes().any(|s| s.reaches_by_corners(closed));
subs.into_iter()
.filter(|(_, closed)| cornered(*closed))
.any(|(r, _)| drawn(&els[r]).iter().any(|s| slanted(tangent(s, 0.0)) || slanted(tangent(s, 1.0))))
}
@@ -468,28 +553,28 @@ impl Appearance {
}
}
/// How many symbol instances [`crate::Node::has_slanted_butt_stroke`] looks into for one object
/// How many symbol instances [`crate::Node::has_slanted_stroke_corners`] looks into for one object
/// before it answers yes without looking further.
pub const SLANT_INSTANCES: usize = 4096;
impl crate::Node {
/// Does a visible butt-capped stroke of this object, of an object in it or of an object in a
/// symbol instance's art from `symbols`, placed by `a`, run along an open path with a segment
/// at a slant ([`Appearance::has_slanted_butt_stroke`])? Past [`SLANT_INSTANCES`] instances it
/// answers yes.
pub fn has_slanted_butt_stroke(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_butt(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
/// Does a visible stroke of this object, of an object in it or of an object in a symbol
/// instance's art from `symbols`, placed by `a`, stop at the corners of a segment at a slant
/// ([`Appearance::has_slanted_stroke_corners`])? Past [`SLANT_INSTANCES`] instances it answers
/// yes.
pub fn has_slanted_stroke_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine) -> bool {
self.slanted_corners(symbols, a, &std::cell::Cell::new(SLANT_INSTANCES))
}
/// [`Self::has_slanted_butt_stroke`] with `left` instances still to look into.
fn slanted_butt(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
/// [`Self::has_slanted_stroke_corners`] with `left` instances still to look into.
fn slanted_corners(&self, symbols: &crate::SymbolBoxes, a: vectorcraft_geom::Affine, left: &std::cell::Cell<usize>) -> bool {
if let crate::NodeKind::SymbolInstance { symbol, xf } = &self.kind {
let Some(l) = left.get().checked_sub(1) else { return true };
left.set(l);
return symbols.measure_art(symbol, |art| art.slanted_butt(symbols, a * *xf, left)).unwrap_or(false);
return symbols.measure_art(symbol, |art| art.slanted_corners(symbols, a * *xf, left)).unwrap_or(false);
}
(self.appearance.has_butt_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_butt_stroke(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_butt(symbols, a, left)))
(self.appearance.has_cornered_stroke() && self.stroke_path().is_some_and(|bp| self.appearance.has_slanted_stroke_corners(&bp, a)))
|| self.children().is_some_and(|c| c.iter().any(|c| c.slanted_corners(symbols, a, left)))
}
}
@@ -566,6 +651,79 @@ mod tests {
assert_eq!(stroke(4.0, |s| s.align = StrokeAlign::Outside).bounds_on(&sq, b), b.inflate(4.0, 4.0));
}
#[test]
fn a_bevel_stops_at_the_corners_of_the_segments_it_joins() {
// A 40 × 100 pt triangle stroked 20 pt: a miter limit of 2 or a bevel join bevels its
// 22.6° tip at (20, 0), so the stroke reaches 10 · 20 / √10400 pt above it, not 10 pt.
let mut tri = BezPath::new();
tri.move_to((0.0, 100.0));
tri.line_to((20.0, 0.0));
tri.line_to((40.0, 100.0));
tri.close_path();
let tb = tri.bounding_box();
let (top, side) = (-200.0 / 10400.0_f64.sqrt(), 1000.0 / 10400.0_f64.sqrt());
let limited = stroke(20.0, |s| s.miter_limit = 2.0);
let bevel = stroke(20.0, |s| {
s.join = LineJoin::Bevel;
s.cap = LineCap::Round;
});
let b = limited.bounds_on(&tri, tb);
assert!((b.y0 - top).abs() < 1e-9, "{b:?}");
// The limit keeps the base corners' miters, whose tips reach about 12.2 pt left and right.
assert!(b.x0 < -12.0 && b.x1 > 52.0, "{b:?}");
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0);
*ap.stroke_mut().unwrap() = bevel.clone();
let b = ap.stroked_bounds(tb, || tri.clone());
for (got, want) in [(b.x0, -side), (b.y0, top), (b.x1, 40.0 + side), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// Open, the same corner is beveled and the round caps reach the half weight round the ends.
let chevron = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
let b = bevel.bounds_on(&chevron, chevron.bounding_box());
for (got, want) in [(b.x0, -10.0), (b.y0, top), (b.x1, 50.0), (b.y1, 110.0)] {
assert!((got - want).abs() < 1e-9, "{b:?}");
}
// A round join, and the round caps of dashes, which can end at the tip, reach round it.
let round = stroke(20.0, |s| s.join = LineJoin::Round);
assert!((round.bounds_on(&tri, tb).y0 + 10.0).abs() < 1e-9);
let mut dashed = bevel.clone();
dashed.dash = Some(Dash { pattern: vec![7.0, 4.0], offset: 0.0, align_corners: false });
assert!((dashed.bounds_on(&chevron, chevron.bounding_box()).y0 + 10.0).abs() < 1e-9);
}
#[test]
fn a_click_past_a_bevel_or_a_butt_end_misses() {
// 5 pt above the triangle's tip is within the half weight of it, but past the bevel, which
// reaches about 1.96 pt above it. A round join paints there.
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
let (above, on) = (Point::new(20.0, -5.0), Point::new(20.0, -1.5));
for join in [LineJoin::Bevel, LineJoin::Miter] {
let st = stroke(20.0, |s| (s.join, s.miter_limit) = (join, 2.0));
assert!(!st.hits(&tri, FillRule::NonZero, above, 0.5), "{join:?}");
assert!(st.hits(&tri, FillRule::NonZero, on, 0.0), "{join:?}");
}
assert!(stroke(20.0, |s| s.join = LineJoin::Round).hits(&tri, FillRule::NonZero, above, 0.5));
// 1.5 pt past a butt end of a 4 pt line misses, and a quarter point within it hits; a round
// cap paints past it.
let line = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
let butt = stroke(4.0, |s| s.cap = LineCap::Butt);
assert!(!butt.hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
assert!(butt.hits(&line, FillRule::NonZero, Point::new(1.0, -0.2), 0.25));
assert!(stroke(4.0, |s| s.cap = LineCap::Round).hits(&line, FillRule::NonZero, Point::new(1.0, -1.5), 0.25));
}
#[test]
fn a_joint_too_shallow_to_bevel_paints_past_both_segments_ends() {
// The path turns by about 0.57° at (100, -0.5), too little to bevel, so the stroke runs on
// through the joint: 3.5 pt above it is past the end of both segments and still painted.
let kink = polyline(&[(0.0, 0.0), (100.0, -0.5), (200.0, 0.0)]);
let above = Point::new(100.0, -4.0);
for join in [LineJoin::Bevel, LineJoin::Miter, LineJoin::Round] {
assert!(stroke(10.0, |s| s.join = join).hits(&kink, FillRule::NonZero, above, 0.0), "{join:?}");
}
}
/// An open path through `points`.
fn polyline(points: &[(f64, f64)]) -> BezPath {
let mut bp = BezPath::new();
@@ -691,15 +849,25 @@ mod tests {
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0);
ap.stroke_mut().unwrap().cap = LineCap::Butt;
let id = vectorcraft_geom::Affine::IDENTITY;
assert!(!ap.has_slanted_butt_stroke(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
assert!(!ap.has_slanted_stroke_corners(&polyline(&[(0.0, 0.0), (0.0, 50.0), (30.0, 50.0)]), id));
// Square ends, slanted segments in the middle.
let apex = polyline(&[(0.0, 50.0), (0.0, 40.0), (10.0, 0.0), (20.0, 40.0), (20.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&apex, id));
// A rotation slants a vertical line; a round cap is never slanted.
assert!(ap.has_slanted_stroke_corners(&apex, id));
// A rotation slants a vertical line.
let v = polyline(&[(0.0, 0.0), (0.0, 50.0)]);
assert!(ap.has_slanted_butt_stroke(&v, vectorcraft_geom::Affine::rotate(0.3)));
assert!(ap.has_slanted_stroke_corners(&v, vectorcraft_geom::Affine::rotate(0.3)));
// With round caps, the miter join still stops at the corners of the slanted segments, on a
// closed path too; round caps and round joins never do.
ap.stroke_mut().unwrap().cap = LineCap::Round;
assert!(!ap.has_slanted_butt_stroke(&apex, id));
assert!(ap.has_slanted_stroke_corners(&apex, id));
let mut tri = polyline(&[(0.0, 100.0), (20.0, 0.0), (40.0, 100.0)]);
tri.close_path();
ap.stroke_mut().unwrap().join = LineJoin::Bevel;
assert!(ap.has_slanted_stroke_corners(&tri, id));
assert!(!ap.has_slanted_stroke_corners(&square(), id));
ap.stroke_mut().unwrap().join = LineJoin::Round;
assert!(!ap.has_slanted_stroke_corners(&apex, id));
assert!(!ap.has_slanted_stroke_corners(&tri, id));
}
#[test]
@@ -723,11 +891,11 @@ mod tests {
}
let top = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S12".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let symbols = d.symbol_boxes();
assert!(top.has_slanted_butt_stroke(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(top.has_slanted_stroke_corners(&symbols, vectorcraft_geom::Affine::IDENTITY));
assert!(symbols.art_measured() <= SLANT_INSTANCES, "{}", symbols.art_measured());
// One instance of S1 holds three instances, all looked into.
let one = Node::new(d.alloc_id(), crate::NodeKind::SymbolInstance { symbol: "S1".into(), xf: vectorcraft_geom::Affine::IDENTITY });
assert!(!one.has_slanted_butt_stroke(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
assert!(!one.has_slanted_stroke_corners(&d.symbol_boxes(), vectorcraft_geom::Affine::IDENTITY));
}
#[test]
+533
View File
@@ -0,0 +1,533 @@
//! Separated images: an image whose inks come as one plate each (a DCS file placed linked), kept
//! as a TIFF of several images. The first is the composite, the plates mixed into CMYK
//! ([`Separated::composite`]), which every reader of a CMYK TIFF sees. Each later image is one
//! plate's ink amounts in grayscale (0 is no ink), with its ink's name and CMYK equivalent in its
//! ImageDescription. Print separations take each plate from these ([`Separated::coverage`]).
use std::io::Cursor;
use std::sync::Arc;
use vectorcraft_color::cms::PROCESS_PLATES;
use vectorcraft_geom::PathData;
use crate::ImageBlob;
use crate::cmyk::{Inks, MAX_CMYK_PIXELS};
/// Most plates a separated image holds.
pub const MAX_PLATES: usize = 64;
/// Most directories a separated image's TIFF holds: its composite and its plates.
const MAX_DIRECTORIES: usize = MAX_PLATES + 1;
/// Longest ink name kept (bytes).
pub const MAX_NAME: usize = 255;
/// Most ink amounts the plates of one image hold together (512 MB).
pub const MAX_SAMPLES: u64 = 1 << 29;
/// How a plate's ImageDescription starts.
const MARK: &str = "VectorCraft plate ";
/// How the composite's ImageDescription starts when plates were read from files of their own.
const FILES_MARK: &str = "VectorCraft plate files";
/// A plate file of its own that a separated image was read from, as it was then: a change to it
/// changes the image as a change to the DCS file does.
#[derive(Clone, Debug, PartialEq)]
pub struct PlateFile {
/// Its file name, in the DCS file's folder.
pub name: String,
/// Its size (bytes).
pub size: u64,
/// Its modification time (ms since the Unix epoch; 0 when the file system keeps none).
pub modified: u64,
}
/// `text` in hexadecimal (TIFF text is ASCII).
fn hex(text: &str) -> String {
text.bytes().map(|b| format!("{b:02x}")).collect()
}
/// The text [`hex`] wrote, of at most `max` bytes.
fn unhex(hex: &str, max: usize) -> Option<String> {
if !hex.len().is_multiple_of(2) || hex.len() > max * 2 {
return None;
}
let bytes: Option<Vec<u8>> = (0..hex.len()).step_by(2).map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok()).collect();
String::from_utf8(bytes?).ok()
}
/// One ink's plate: its ink amounts, one byte a pixel (0 is none, 255 is solid), row by row from
/// the top.
#[derive(Clone, Debug, PartialEq)]
pub struct InkPlate {
/// "Cyan", "Magenta", "Yellow", "Black", or a spot ink's name.
pub name: String,
/// The process inks the ink stands for (C, M, Y, K, 0..1): one process ink at 100% for a
/// process plate.
pub cmyk: [f32; 4],
pub data: Vec<u8>,
}
impl InkPlate {
/// Is it a spot ink's plate (not one of the four process inks)?
pub fn spot(&self) -> bool {
!PROCESS_PLATES.contains(&self.name.as_str())
}
}
/// The plates of a separated image, all of one size.
#[derive(Clone, Debug, PartialEq)]
pub struct Separated {
pub width: u32,
pub height: u32,
pub plates: Vec<InkPlate>,
}
impl Separated {
/// `plates` as a `width` × `height` image; `None` when there are none or more than
/// [`MAX_PLATES`], two have the same name, a name is empty or longer than [`MAX_NAME`], a plate
/// doesn't hold that many pixels, an equivalent isn't within 0..1, or the image is empty, has
/// more than [`MAX_CMYK_PIXELS`], or its plates together hold more than [`MAX_SAMPLES`]
/// ([`Self::fits`]). A process plate's equivalent is its own ink.
pub fn new(width: u32, height: u32, mut plates: Vec<InkPlate>) -> Option<Self> {
let n = u64::from(width) * u64::from(height);
if !Self::fits(width, height, plates.len()) {
return None;
}
for p in plates.iter_mut() {
if p.name.is_empty() || p.name.len() > MAX_NAME || p.data.len() as u64 != n {
return None;
}
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == p.name) {
p.cmyk = [0.0; 4];
p.cmyk[j] = 1.0;
}
if !p.cmyk.iter().all(|v| (0.0..=1.0).contains(v)) {
return None;
}
}
let mut names = std::collections::HashSet::new();
if !plates.iter().all(|p| names.insert(p.name.as_str())) {
return None;
}
Some(Self { width, height, plates })
}
/// May an image of `width` × `height` pixels hold `plates` plates? Not when it is empty, has
/// more than [`MAX_CMYK_PIXELS`], has no plate or more than [`MAX_PLATES`], or the plates
/// together would hold more than [`MAX_SAMPLES`].
pub fn fits(width: u32, height: u32, plates: usize) -> bool {
let n = u64::from(width) * u64::from(height);
n > 0 && n <= MAX_CMYK_PIXELS && (1..=MAX_PLATES).contains(&plates) && n * plates as u64 <= MAX_SAMPLES
}
/// The plates of spot inks.
pub fn spots(&self) -> impl Iterator<Item = &InkPlate> {
self.plates.iter().filter(|p| p.spot())
}
/// The plates mixed into process inks: each plate's ink amount times its equivalent, the
/// plates over one another as inks print (`1 − (1 − a)(1 − b)` for each process ink).
pub fn composite(&self) -> Inks {
let n = self.data_len();
let mut data = vec![0u8; n * 4];
for (i, px) in data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let mut clear = [1.0f32; 4];
for p in &self.plates {
let t = f32::from(p.data[i]) / 255.0;
for (c, e) in clear.iter_mut().zip(p.cmyk) {
*c *= 1.0 - t * e;
}
}
for (o, c) in px.iter_mut().zip(clear) {
*o = ((1.0 - c) * 255.0).round() as u8;
}
}
Inks { width: self.width, height: self.height, data }
}
/// The ink amounts that print on plate `plate` (a process ink's name or a spot ink's), one byte
/// a pixel. A spot plate for which `own` is true prints on its own plate only; every other spot
/// plate (the job prints no plate of that name) prints as its process equivalent, mixed as
/// [`Self::composite`] mixes it. A plate name the image has no plate for, and a spot plate that
/// prints as process, print nothing.
pub fn coverage(&self, plate: &str, own: &dyn Fn(&str) -> bool) -> Vec<u8> {
self.coverage_as(plate, own, &|p| p.cmyk)
}
/// [`Self::coverage`], a spot plate that prints as process printing as the process inks
/// `equivalent` gives it (the document's swatch of its ink, when there is one).
pub fn coverage_as(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Vec<u8> {
let n = self.data_len();
if let Some(j) = PROCESS_PLATES.iter().position(|q| *q == plate) {
let mixed: Vec<(&InkPlate, f32)> = self
.plates
.iter()
.filter(|p| !p.spot() || !own(&p.name))
.map(|p| (p, if p.spot() { equivalent(p)[j].clamp(0.0, 1.0) } else { p.cmyk[j] }))
.filter(|(_, e)| *e > 0.0)
.collect();
return (0..n)
.map(|i| {
let clear = mixed.iter().fold(1.0f32, |c, (p, e)| c * (1.0 - f32::from(p.data[i]) / 255.0 * e));
((1.0 - clear) * 255.0).round() as u8
})
.collect();
}
match self.plates.iter().find(|p| p.name == plate && p.spot() && own(&p.name)) {
Some(p) => p.data.clone(),
None => vec![0; n],
}
}
/// [`Self::coverage_as`] as a grayscale PNG, black for solid ink and white for none, as a plate
/// prints; `None` when it can't be written.
pub fn plate_png(&self, plate: &str, own: &dyn Fn(&str) -> bool, equivalent: &dyn Fn(&InkPlate) -> [f32; 4]) -> Option<ImageBlob> {
let gray: Vec<u8> = self.coverage_as(plate, own, equivalent).into_iter().map(|v| 255 - v).collect();
let img = image::GrayImage::from_raw(self.width, self.height, gray)?;
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
Some(ImageBlob::png(png))
}
fn data_len(&self) -> usize {
self.width as usize * self.height as usize
}
}
/// A plate's ImageDescription: the mark, its equivalent and its name in hexadecimal (TIFF text is
/// ASCII).
fn description(p: &InkPlate) -> String {
let [c, m, y, k] = p.cmyk;
format!("{MARK}{c} {m} {y} {k} {}", hex(&p.name))
}
/// A plate's name and equivalent from its ImageDescription; `None` when it isn't one.
fn parse_description(s: &str) -> Option<(String, [f32; 4])> {
let rest = s.strip_prefix(MARK)?;
let mut words = rest.split(' ');
let mut cmyk = [0.0f32; 4];
for v in &mut cmyk {
*v = words.next()?.parse().ok().filter(|v: &f32| v.is_finite())?;
}
let name = unhex(words.next()?, MAX_NAME)?;
words.next().is_none().then_some((name, cmyk))
}
/// Longest plate file name kept (bytes).
const MAX_FILE_NAME: usize = 4096;
/// The composite's ImageDescription line for `files`: the mark, then each file's name in
/// hexadecimal, its size and its modification time.
fn files_description(files: &[PlateFile]) -> String {
let mut out = String::from(FILES_MARK);
for f in files.iter().take(MAX_PLATES) {
out.push_str(&format!(" {} {} {}", hex(&f.name), f.size, f.modified));
}
out
}
/// How the composite's ImageDescription line holding the clipping path starts.
const CLIP_MARK: &str = "VectorCraft clip ";
/// Longest clipping path kept (bytes of its JSON).
const MAX_CLIP: usize = 16 << 20;
/// The composite's ImageDescription line for clipping path `clip`: the mark, then the path's JSON
/// in hexadecimal; `None` when it is longer than [`MAX_CLIP`].
fn clip_description(clip: &PathData) -> Option<String> {
let json = serde_json::to_string(clip).ok().filter(|j| j.len() <= MAX_CLIP)?;
Some(format!("{CLIP_MARK}{}", hex(&json)))
}
/// The plate files of a composite's ImageDescription; none when it isn't one.
fn parse_files(s: &str) -> Vec<PlateFile> {
let Some(rest) = s.lines().find_map(|l| l.strip_prefix(FILES_MARK)) else { return vec![] };
let words: Vec<&str> = rest.split(' ').filter(|w| !w.is_empty()).collect();
let file =
|w: &[&str]| Some(PlateFile { name: unhex(w.first()?, MAX_FILE_NAME)?, size: w.get(1)?.parse().ok()?, modified: w.get(2)?.parse().ok()? });
words.chunks(3).take(MAX_PLATES).filter_map(file).collect()
}
impl ImageBlob {
/// A TIFF of separated image `s`: its composite in CMYK, then its plates (Deflate-compressed),
/// declaring the resolution `ppi` when it is given and both are finite and above 0, and noting
/// `files`, the plate files of their own the plates were read from ([`Self::plate_files`]);
/// `None` when it can't be written.
pub fn separated_tiff(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile]) -> Option<Self> {
Self::separated_tiff_clipped(s, ppi, files, None)
}
/// [`Self::separated_tiff`], noting `clip` too, the clipping path its file draws it through, in
/// its pixel space ([`Self::separated_clip`]).
pub fn separated_tiff_clipped(s: &Separated, ppi: Option<(f64, f64)>, files: &[PlateFile], clip: Option<&PathData>) -> Option<Self> {
use tiff::encoder::{Compression, Rational, TiffEncoder, colortype, compression::DeflateLevel};
use tiff::tags::{ResolutionUnit, Tag};
let ppi = ppi.filter(|(x, y)| [x, y].iter().all(|v| v.is_finite() && **v > 0.0));
// Ten-thousandths of a pixel per inch.
let r = |v: f64| Rational { n: (v * 10_000.0).round() as u32, d: 10_000 };
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).ok()?.with_compression(Compression::Deflate(DeflateLevel::Balanced));
let mut img = enc.new_image::<colortype::CMYK8>(s.width, s.height).ok()?;
if let Some((x, y)) = ppi {
img.encoder().write_tag(Tag::XResolution, r(x)).ok()?;
img.encoder().write_tag(Tag::YResolution, r(y)).ok()?;
img.encoder().write_tag(Tag::ResolutionUnit, ResolutionUnit::Inch).ok()?;
}
// One line for the plate files, one for the clipping path.
let lines: Vec<String> =
[(!files.is_empty()).then(|| files_description(files)), clip.and_then(clip_description)].into_iter().flatten().collect();
if !lines.is_empty() {
img.encoder().write_tag(Tag::ImageDescription, lines.join("\n").as_str()).ok()?;
}
img.write_data(&s.composite().data).ok()?;
for p in &s.plates {
// White is no ink, so a viewer that shows a plate shows it as it prints.
let mut img = enc.new_image::<colortype::Gray8>(s.width, s.height).ok()?;
img.encoder().write_tag(Tag::ImageDescription, description(p).as_str()).ok()?;
let inverted: Vec<u8> = p.data.iter().map(|v| 255 - v).collect();
img.write_data(&inverted).ok()?;
}
Some(Self::new("image/tiff", out.into_inner()))
}
/// Does the image hold plates ([`ImageBlob::separated_tiff`]), at most [`MAX_PLATES`] of them?
/// One with more, or with more directories than its composite and [`MAX_PLATES`] plates, is the
/// CMYK image of its composite only, as [`Self::separated`] refuses it. Reads only the TIFF's
/// directories, at most [`MAX_DIRECTORIES`].
pub fn is_separated(&self) -> bool {
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return false };
let (mut plates, mut directories) = (0usize, 1usize);
while d.more_images() {
directories += 1;
if directories > MAX_DIRECTORIES || d.next_image().is_err() {
return false;
}
if d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().is_some_and(|s| s.starts_with(MARK)) {
plates += 1;
if plates > MAX_PLATES {
return false;
}
}
}
plates > 0
}
/// The plate files of their own a separated image was read from, as they were then; none for
/// other images. Reads only the TIFF's first directory.
pub fn plate_files(&self) -> Vec<PlateFile> {
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().map(parse_files).unwrap_or_default()
}
/// The clipping path a separated image's file draws it through, in its pixel space, as
/// [`Self::separated_tiff_clipped`] noted it; `None` for other images. Reads only the TIFF's
/// first directory.
pub fn separated_clip(&self) -> Option<PathData> {
let (_, mut d) = crate::cmyk::tiff(&self.bytes)?;
let text = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok()?;
let json = unhex(text.lines().find_map(|l| l.strip_prefix(CLIP_MARK))?, MAX_CLIP)?;
serde_json::from_str(&json).ok()
}
/// The spot inks a separated image has plates for, each with its CMYK equivalent; none for
/// other images. Reads only the TIFF's directories.
pub fn spot_plates(&self) -> Vec<(String, [f32; 4])> {
if !self.is_separated() {
return vec![];
}
let Some((_, mut d)) = crate::cmyk::tiff(&self.bytes) else { return vec![] };
let mut inks = vec![];
while d.more_images() && inks.len() < MAX_PLATES {
if d.next_image().is_err() {
break;
}
let plate = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description);
inks.extend(plate.filter(|(name, _)| !PROCESS_PLATES.contains(&name.as_str())));
}
inks
}
/// The plates of a separated image; `None` for other images, and ones whose plates can't be
/// read. The plates of the last image read are kept for the next call (print separates one
/// image plate after plate).
pub fn separated(&self) -> Option<Arc<Separated>> {
thread_local! {
static LAST: std::cell::RefCell<Option<(String, Arc<Separated>)>> = const { std::cell::RefCell::new(None) };
}
if !self.is_separated() {
return None;
}
let key = self.content_key();
LAST.with_borrow_mut(|last| match last {
Some((k, s)) if *k == key => Some(s.clone()),
_ => {
let s = Arc::new(read_plates(&self.bytes)?);
*last = Some((key, s.clone()));
Some(s)
}
})
}
}
/// The plates of TIFF `bytes`, each the size of its first image.
fn read_plates(bytes: &[u8]) -> Option<Separated> {
let (_, mut d) = crate::cmyk::tiff(bytes)?;
let (w, h) = d.dimensions().ok()?;
let n = usize::try_from(u64::from(w) * u64::from(h)).ok()?;
let mut plates = vec![];
// Every plate is read: a file with more than [`MAX_PLATES`] is refused ([`Separated::fits`]),
// not cut short, and so is one with more than [`MAX_DIRECTORIES`] directories.
let mut directories = 1usize;
while d.more_images() {
directories += 1;
if directories > MAX_DIRECTORIES {
return None;
}
d.next_image().ok()?;
let Some((name, cmyk)) = d.get_tag_ascii_string(tiff::tags::Tag::ImageDescription).ok().as_deref().and_then(parse_description) else {
continue;
};
// Checked before the plate is decoded.
if d.dimensions().ok()? != (w, h) || !matches!(d.colortype().ok()?, tiff::ColorType::Gray(8)) || !Separated::fits(w, h, plates.len() + 1) {
return None;
}
let data = crate::cmyk::read_samples(&mut d, n, 1)?.into_iter().map(|v| 255 - v).collect();
plates.push(InkPlate { name, cmyk, data });
}
Separated::new(w, h, plates)
}
#[cfg(test)]
mod tests {
use super::*;
fn plate(name: &str, cmyk: [f32; 4], data: &[u8]) -> InkPlate {
InkPlate { name: name.into(), cmyk, data: data.to_vec() }
}
/// Two pixels: cyan 100% and a spot ink at 50% on the first, nothing on the second.
fn two() -> Separated {
let plates = vec![plate("Cyan", [0.0; 4], &[255, 0]), plate("Spot Orange", [0.0, 0.6, 1.0, 0.0], &[128, 0])];
Separated::new(2, 1, plates).unwrap()
}
#[test]
fn plates_mix_into_the_composite_as_inks_print() {
let s = two();
assert_eq!(s.plates[0].cmyk, [1.0, 0.0, 0.0, 0.0], "a process plate stands for its own ink");
let c = s.composite();
// Magenta: 0.6 × 128/255; yellow: 128/255.
assert_eq!(&c.data[..4], &[255, 77, 128, 0]);
assert_eq!(&c.data[4..], &[0, 0, 0, 0]);
}
#[test]
fn a_spot_plate_prints_on_its_own_plate_or_as_process() {
let s = two();
let own = |_: &str| true;
assert_eq!(s.coverage("Spot Orange", &own), [128, 0]);
assert_eq!(s.coverage("Magenta", &own), [0, 0], "nothing of the spot on a process plate");
assert_eq!(s.coverage("Cyan", &own), [255, 0]);
assert_eq!(s.coverage("Black", &own), [0, 0]);
let process = |_: &str| false;
assert_eq!(s.coverage("Spot Orange", &process), [0, 0]);
assert_eq!(s.coverage("Magenta", &process), [77, 0]);
assert_eq!(s.coverage("Yellow", &process), [128, 0]);
assert_eq!(s.coverage("Other", &own), [0, 0]);
}
#[test]
fn the_tiff_keeps_every_plate_and_shows_the_composite() {
let s = two();
let files =
[PlateFile { name: "pic (1).C".into(), size: 1234, modified: 1_700_000_000_000 }, PlateFile { name: "ü.K".into(), size: 0, modified: 0 }];
let b = ImageBlob::separated_tiff(&s, Some((300.0, 300.0)), &files).unwrap();
assert_eq!(b.plate_files(), files);
assert!(ImageBlob::separated_tiff(&s, None, &[]).unwrap().plate_files().is_empty());
assert!(b.is_separated());
assert!(b.is_cmyk(), "readers of a CMYK TIFF see the composite");
assert_eq!(b.cmyk(), Some(s.composite()));
assert_eq!(*b.separated().unwrap(), s);
assert_eq!(b.spot_plates(), [("Spot Orange".to_string(), [0.0, 0.6, 1.0, 0.0])]);
assert!(ImageBlob::cmyk_tiff(&s.composite()).unwrap().spot_plates().is_empty());
assert!(!ImageBlob::cmyk_tiff(&s.composite()).unwrap().is_separated());
}
#[test]
fn the_tiff_keeps_the_clipping_path_beside_the_plate_files() {
let s = two();
let clip = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 1.5, 1.0));
let files = [PlateFile { name: "a.C".into(), size: 1, modified: 2 }];
let b = ImageBlob::separated_tiff_clipped(&s, None, &files, Some(&clip)).unwrap();
assert_eq!(b.separated_clip(), Some(clip.clone()));
assert_eq!(b.plate_files(), files);
let alone = ImageBlob::separated_tiff_clipped(&s, None, &[], Some(&clip)).unwrap();
assert_eq!(alone.separated_clip(), Some(clip));
assert!(alone.plate_files().is_empty());
assert_eq!(ImageBlob::separated_tiff(&s, None, &files).unwrap().separated_clip(), None);
}
#[test]
fn a_tiff_with_more_plates_than_are_read_is_refused() {
use tiff::encoder::{TiffEncoder, colortype};
let tiff = |plates: usize| {
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).unwrap();
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
for i in 0..plates {
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate(&format!("S{i}"), [0.0; 4], &[0])).as_str()).unwrap();
img.write_data(&[255]).unwrap();
}
ImageBlob::new("image/tiff", out.into_inner())
};
assert_eq!(tiff(MAX_PLATES).separated().map(|s| s.plates.len()), Some(MAX_PLATES));
let over = tiff(MAX_PLATES + 1);
assert!(over.separated().is_none(), "not cut short to the first {MAX_PLATES}");
assert!(!over.is_separated() && over.spot_plates().is_empty(), "the CMYK image of its composite only");
assert!(tiff(MAX_PLATES).is_separated());
}
#[test]
fn a_tiff_with_more_directories_than_a_composite_and_its_plates_is_refused() {
use tiff::encoder::{TiffEncoder, colortype};
let tiff = |others: usize| {
let mut out = Cursor::new(Vec::new());
let mut enc = TiffEncoder::new(&mut out).unwrap();
enc.write_image::<colortype::CMYK8>(1, 1, &[0, 0, 0, 0]).unwrap();
let mut img = enc.new_image::<colortype::Gray8>(1, 1).unwrap();
img.encoder().write_tag(tiff::tags::Tag::ImageDescription, description(&plate("S", [0.0; 4], &[0])).as_str()).unwrap();
img.write_data(&[255]).unwrap();
// Directories that are not plates.
for _ in 0..others {
enc.write_image::<colortype::Gray8>(1, 1, &[255]).unwrap();
}
ImageBlob::new("image/tiff", out.into_inner())
};
let most = tiff(MAX_PLATES - 1);
assert!(most.is_separated() && most.separated().is_some());
let over = tiff(MAX_PLATES);
assert!(!over.is_separated() && over.separated().is_none() && over.spot_plates().is_empty());
assert!(read_plates(&over.bytes).is_none(), "read_plates stops at the limit too");
}
#[test]
fn names_that_are_not_ascii_are_kept() {
let s = Separated::new(1, 1, vec![plate("Grün 100 % (A)", [0.5, 0.0, 1.0, 0.0], &[9])]).unwrap();
let b = ImageBlob::separated_tiff(&s, None, &[]).unwrap();
assert_eq!(b.separated().unwrap().plates[0].name, "Grün 100 % (A)");
}
#[test]
fn bad_plates_are_refused() {
assert!(Separated::new(2, 1, vec![]).is_none(), "no plates");
assert!(Separated::new(2, 1, vec![plate("Cyan", [0.0; 4], &[1])]).is_none(), "too few pixels");
assert!(Separated::new(1, 1, vec![plate("A", [0.0; 4], &[1]), plate("A", [0.0; 4], &[1])]).is_none(), "the same name twice");
assert!(Separated::new(1, 1, vec![plate("", [0.0; 4], &[1])]).is_none(), "no name");
assert!(Separated::new(1, 1, vec![plate("A", [2.0, 0.0, 0.0, 0.0], &[1])]).is_none(), "equivalent past 100%");
assert!(Separated::new(0, 1, vec![plate("A", [0.0; 4], &[])]).is_none(), "empty");
let many: Vec<InkPlate> = (0..=MAX_PLATES).map(|i| plate(&format!("S{i}"), [0.0; 4], &[1])).collect();
assert!(Separated::new(1, 1, many).is_none(), "too many plates");
assert!(Separated::fits(1 << 13, 1 << 13, 8), "512 MB of ink amounts");
assert!(!Separated::fits(1 << 13, 1 << 13, 9), "more than 512 MB together");
assert!(!Separated::fits(1 << 14, 1 << 13, 1), "more pixels than a CMYK image is decoded with");
}
}
+159 -42
View File
@@ -5,7 +5,7 @@
//! tint (`Paint::Solid.swatch` / `.tint`, `GradientStop.swatch` / `.tint`); a tint swatch is a
//! swatch whose own paint links to its base that way. [`Document::map_solid_paints`] rewrites
//! those links (and colours) wherever art and swatches hold them, copying only the nodes that
//! change.
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
@@ -124,6 +124,52 @@ impl Document {
/// ([`Paint::map_links`]). Only nodes holding a changed paint (and the paths to them) are
/// copied. Returns the number of changed paints.
pub fn map_solid_paints(&mut self, f: &mut LinkFn) -> usize {
let mut n = self.map_art_paints(&mut relink(f));
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(item_paint_mut(it).map_links(f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
let mut g = relink(f);
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, &mut g));
}
}
n
}
/// Visit every paint in the places [`Document::map_solid_paints`] visits (fills, strokes, text
/// runs, image colorize paints, dynamic symbol instances' own paints and graphs' stored series and
/// label paints in the art, opacity masks included, symbol definitions, graph designs, pattern tiles and the tile that pattern
/// editing's Cancel puts back; graphic styles; the swatches; character styles' fill and
/// stroke), whatever its kind. `f(paint)` gives the paint to put in its place, or `None` to keep
/// it. Only nodes holding a changed paint (and the paths to them) are copied. Returns the number
/// of changed paints.
pub fn map_paints(&mut self, f: &mut PaintFn) -> usize {
let mut n = self.map_art_paints(f);
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(replace_paint(item_paint_mut(it), f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(replace_paint(&mut w.paint, f));
}
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, f));
}
}
n
}
/// [`Document::map_paints`] limited to the node trees: the art, symbol definitions, graph
/// designs, pattern tiles and the tile that pattern editing's Cancel puts back.
fn map_art_paints(&mut self, f: &mut PaintFn) -> usize {
let mut n = map_trees(&mut self.layers, f);
for s in &mut self.symbols {
n += map_tree(&mut s.art, f);
@@ -134,19 +180,6 @@ impl Document {
for p in self.patterns.iter_mut().chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())) {
n += map_trees(&mut p.art, f);
}
for gs in &mut self.graphic_styles {
for it in &mut gs.appearance.items {
n += usize::from(item_paint_mut(it).map_links(f));
}
}
for w in self.swatches_iter_mut() {
n += usize::from(w.paint.map_links(f));
}
for def in &mut self.char_styles {
for key in ["fill", "stroke"] {
n += usize::from(map_style_paint(&mut def.attrs, key, f));
}
}
n
}
@@ -156,9 +189,10 @@ impl Document {
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
let Some(node) = self.node(id) else { continue };
if let Some((new, count)) = map_node(node, f)
if let Some((new, count)) = map_node(node, &mut g)
&& let Some(slot) = self.node_mut(id)
{
*slot = new;
@@ -176,7 +210,7 @@ impl Document {
pub fn visit_paints(&self, f: &mut dyn FnMut(&Paint)) {
let mut tree = |n: &Node| {
walk_with_masks(n, &mut |m| {
node_paints(m).chain(override_paints(m)).for_each(&mut *f);
node_paints(m).chain(override_paints(m)).chain(graph_paints(m)).for_each(&mut *f);
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&Paint::solid(p.color)));
}
@@ -258,14 +292,39 @@ impl FreeSwatchNames {
/// true when it changed them.
pub type LinkFn<'a> = dyn FnMut(&mut Color, &mut Option<String>, &mut f32) -> bool + 'a;
/// Apply `f` to the paint a character style's attribute `key` holds, as [`Paint::map_links`]
/// does, and store the result in the attribute. True when it changed.
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut LinkFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(mut paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
if !paint.map_links(f) {
return false;
/// What [`Document::map_paints`] applies to each paint: the paint to put in its place, or `None`
/// to keep it.
pub type PaintFn<'a> = dyn FnMut(&Paint) -> Option<Paint> + 'a;
/// `f` as a [`PaintFn`]: a solid or gradient paint with `f` applied ([`Paint::map_links`]) when
/// `f` changed it, `None` for every other paint.
fn relink<'a>(f: &'a mut LinkFn<'_>) -> impl FnMut(&Paint) -> Option<Paint> + 'a {
move |p| match p {
Paint::Solid { .. } | Paint::Gradient(_) => {
let mut q = p.clone();
q.map_links(f).then_some(q)
}
_ => None,
}
}
/// Put `f(p)` in place of `p` when it gives a paint. True when it did.
fn replace_paint(p: &mut Paint, f: &mut PaintFn) -> bool {
match f(p) {
Some(q) => {
*p = q;
true
}
None => false,
}
}
/// Apply `f` to the paint a character style's attribute `key` holds and store the result in the
/// attribute. An attribute that is not a paint stays as it is. True when it changed.
fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key: &str, f: &mut PaintFn) -> bool {
let Some(value) = attrs.get_mut(key) else { return false };
let Ok(paint) = serde_json::from_value::<Paint>(value.clone()) else { return false };
let Some(paint) = f(&paint) else { return false };
match serde_json::to_value(&paint) {
Ok(changed) => {
*value = changed;
@@ -323,6 +382,23 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
}
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
let g = n.extras().graph.as_deref();
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke]))
}
/// Mutable [`graph_paints`] of graph `g`, in the same order.
fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mut Paint> {
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
let l = &mut g.label_styles;
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
series.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
}
/// Mutable [`node_paints`], in the same order.
pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
let runs = match &mut n.kind {
@@ -333,20 +409,11 @@ pub fn node_paints_mut(n: &mut Node) -> impl Iterator<Item = &mut Paint> {
n.appearance.items.iter_mut().map(item_paint_mut).chain(runs.iter_mut().flat_map(|r| [&mut r.style.fill, &mut r.style.stroke])).chain(colorize)
}
/// `n` with `f` applied to its subtree's linkable colours, or `None` when nothing changed (then
/// nothing was copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
// Try each own solid or gradient paint on a scratch copy first, so unchanged nodes are never
// cloned.
let mut changes: Vec<(usize, Paint)> = vec![];
for (i, p) in node_paints(n).enumerate() {
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) {
let mut q = p.clone();
if q.map_links(f) {
changes.push((i, q));
}
}
}
/// `n` with `f` applied to its subtree's paints, or `None` when nothing changed (then nothing was
/// copied). Also returns the number of changed paints.
fn map_node(n: &Node, f: &mut PaintFn) -> Option<(Node, usize)> {
// `f` gives each own paint's replacement first, so unchanged nodes are never cloned.
let changes: Vec<(usize, Paint)> = node_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
let mut count = changes.len();
let mut out: Option<Node> = None;
if !changes.is_empty() {
@@ -366,15 +433,29 @@ fn map_node(n: &Node, f: &mut LinkFn) -> Option<(Node, usize)> {
let mut overrides = n.extras().symbol_overrides.clone();
let mut k = 0;
for p in overrides.iter_mut().flat_map(|o| [&mut o.fill, &mut o.stroke]).flatten() {
if matches!(p, Paint::Solid { .. } | Paint::Gradient(_)) && p.map_links(f) {
k += 1;
}
k += usize::from(replace_paint(p, f));
}
if k > 0 {
out.get_or_insert_with(|| n.clone()).extras_mut().symbol_overrides = overrides;
count += k;
}
}
// A graph's series and label paints, which its marks and labels take when it is drawn again.
let graph: Vec<(usize, Paint)> = graph_paints(n).enumerate().filter_map(|(i, p)| f(p).map(|q| (i, q))).collect();
if !graph.is_empty() {
count += graph.len();
let m = out.get_or_insert_with(|| n.clone());
if let Some(spec) = m.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
let mut graph = graph.into_iter().peekable();
for (i, p) in graph_paints_mut(spec).enumerate() {
if graph.peek().is_some_and(|c| c.0 == i)
&& let Some((_, q)) = graph.next()
{
*p = q;
}
}
}
}
if let Some(ch) = n.children() {
for (i, c) in ch.iter().enumerate() {
if let Some((new, k)) = map_node(c, f) {
@@ -415,6 +496,13 @@ pub fn walk_with_masks<'a>(n: &'a Node, f: &mut dyn FnMut(&'a Node)) {
/// brush: `f` applied to the linkable colors of `n` and its subtree (opacity masks included). Only
/// the nodes holding a changed paint are copied. Returns the number of changed paints.
pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
map_node_paints(n, &mut relink(f))
}
/// [`Document::map_paints`] for art a document keeps outside its trees, such as the art of a brush:
/// `f` applied to every paint of `n` and its subtree (opacity masks included). Only the nodes
/// holding a changed paint are copied. Returns the number of changed paints.
pub fn map_node_paints(n: &mut Node, f: &mut PaintFn) -> usize {
match map_node(n, f) {
Some((new, count)) => {
*n = new;
@@ -424,7 +512,7 @@ pub fn map_node_solid_paints(n: &mut Node, f: &mut LinkFn) -> usize {
}
}
fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
fn map_tree(n: &mut Arc<Node>, f: &mut PaintFn) -> usize {
match map_node(n, f) {
Some((new, count)) => {
*n = Arc::new(new);
@@ -434,7 +522,7 @@ fn map_tree(n: &mut Arc<Node>, f: &mut LinkFn) -> usize {
}
}
fn map_trees(v: &mut [Arc<Node>], f: &mut LinkFn) -> usize {
fn map_trees(v: &mut [Arc<Node>], f: &mut PaintFn) -> usize {
v.iter_mut().map(|n| map_tree(n, f)).sum()
}
@@ -593,6 +681,35 @@ mod tests {
assert_eq!(map_node_solid_paints(&mut loose, &mut to_blue), 0, "nothing left to change");
}
#[test]
fn mapping_reaches_the_series_and_label_paints_a_graph_keeps() {
let (mut d, a, _) = doc();
let red = linked(Color::rgb(1.0, 0.0, 0.0), "Brand");
let spec = crate::graph::GraphSpec {
series_paints: vec![crate::SeriesPaint { fill: Some(red.clone()), stroke: Some(red.clone()), ..Default::default() }],
label_styles: crate::graph::LabelStyles {
legend: Some(crate::CharStyle { fill: red.clone(), stroke: Paint::None, ..Default::default() }),
..Default::default()
},
..Default::default()
};
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == red));
assert_eq!(seen, 4, "the fill and the graph's series fill, series stroke and legend fill");
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
assert_eq!(d.map_solid_paints(&mut to_blue), 4);
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
let legend = g.label_styles.legend.unwrap();
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
assert_eq!(d.map_paints(&mut cleared), 4, "the fill and the graph's three");
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
#[test]
fn mapping_within_ids_visits_each_paint_once() {
let (mut d, a, b) = doc();
+1 -1
View File
@@ -17,7 +17,7 @@ mod wrap;
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
use char_style::yes;
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, ScriptMetrics};
pub use char_style::{CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, ScriptMetrics};
pub use composite::{
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
CompositeParts,
+20 -1
View File
@@ -34,6 +34,16 @@ pub struct CharStyle {
/// before it whose [`Self::kerning`] could space it. Elsewhere it has no effect.
#[serde(default, rename = "kerningBefore", skip_serializing_if = "crate::skip::is_default")]
pub kerning_before: f64,
/// Insert Aki Left (Character panel, East Asian options): space added before the character in
/// reading order, in 1/1000 em as [`Self::tracking`], 0 to 1000. Before is on the left in
/// left-to-right type, on the right in right-to-left type and above in vertical type. A
/// cluster takes the value of its first character, and full justification leaves it as it is.
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
#[serde(default, rename = "akiLeft", skip_serializing_if = "crate::skip::is_default")]
pub aki_left: f64,
/// Insert Aki Right: space added after the character in reading order, as [`Self::aki_left`].
#[serde(default, rename = "akiRight", skip_serializing_if = "crate::skip::is_default")]
pub aki_right: f64,
/// Use glyph shapes for automatic pair spacing; false uses font metrics.
#[serde(default, rename = "opticalKerning", skip_serializing_if = "crate::skip::is_default")]
pub optical_kerning: bool,
@@ -404,6 +414,9 @@ fn hundred() -> f64 {
100.0
}
/// The largest Insert Aki Left or Right ([`CharStyle::aki_left`]), in 1/1000 em: one em.
pub const MAX_AKI: f64 = 1000.0;
pub(super) fn yes() -> bool {
true
}
@@ -420,6 +433,8 @@ impl Default for CharStyle {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: false,
baseline_shift: 0.0,
h_scale: 100.0,
@@ -468,7 +483,8 @@ impl CharStyle {
/// becomes Auto, and a value past [`crate::MAX_COORD`] (a baseline shift past it either way)
/// becomes the nearer end. A leading of 0, which legacy `.ai` import stores, stays, and a
/// baseline shift that is not a number becomes 0. The Tate-chu-yoko Up/Down and Left/Right
/// offsets are kept as the baseline shift is.
/// offsets are kept as the baseline shift is. Insert Aki Left and Right are kept from 0 to
/// [`MAX_AKI`], and one that is not a number becomes 0.
pub fn keep_dimensions_in_range(&mut self) {
let default = Self::default();
let within = |v: f64, or: f64| if v > 0.0 { v.min(crate::MAX_COORD) } else { or };
@@ -480,6 +496,9 @@ impl CharStyle {
self.baseline_shift = shift(self.baseline_shift);
self.tcy_up_down = shift(self.tcy_up_down);
self.tcy_left_right = shift(self.tcy_left_right);
let aki = |v: f64| if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) };
self.aki_left = aki(self.aki_left);
self.aki_right = aki(self.aki_right);
}
/// Do the characters draw a stroke (a paint and a positive weight)?
pub fn has_stroke(&self) -> bool {
+4
View File
@@ -490,6 +490,8 @@ impl crate::Document {
st.baseline_shift = num("baseline_shift").unwrap_or(st.baseline_shift);
st.tcy_up_down = num("tcyUpDown").unwrap_or(st.tcy_up_down);
st.tcy_left_right = num("tcyLeftRight").unwrap_or(st.tcy_left_right);
st.aki_left = num("akiLeft").unwrap_or(st.aki_left);
st.aki_right = num("akiRight").unwrap_or(st.aki_right);
st.keep_dimensions_in_range();
let kept = [
("size", Some(st.size)),
@@ -498,6 +500,8 @@ impl crate::Document {
("baseline_shift", Some(st.baseline_shift)),
("tcyUpDown", Some(st.tcy_up_down)),
("tcyLeftRight", Some(st.tcy_left_right)),
("akiLeft", Some(st.aki_left)),
("akiRight", Some(st.aki_right)),
("leading", st.leading),
];
for (k, v) in kept {
+25
View File
@@ -237,6 +237,10 @@ pub struct ParaStyle {
/// Kinsoku Shori Type (Paragraph panel menu): how a line keeps those characters off its start
/// and end, by pushing them in onto the line or out to the next one. No effect without kinsoku.
pub kinsoku_type: KinsokuShoriType,
/// Bunri-Kinshi (Paragraph panel menu): a line never breaks inside an inseparable pair (two em
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
/// with kinsoku None, where it has no effect. Off by default.
pub bunri_kinshi: bool,
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
@@ -339,6 +343,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kinsoku_type: KinsokuShoriType,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
bunri_kinshi: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -375,6 +381,7 @@ impl From<ParaStyle> for ParaStyleFile {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -401,6 +408,7 @@ impl From<ParaStyle> for ParaStyleFile {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -431,6 +439,7 @@ impl From<ParaStyleFile> for ParaStyle {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -456,6 +465,7 @@ impl From<ParaStyleFile> for ParaStyle {
burasagari,
kinsoku,
kinsoku_type,
bunri_kinshi,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -498,6 +508,21 @@ pub enum Mojikumi {
/// Consecutive punctuation shares one half-em space (JLREQ 3.1.4), and a closing bracket,
/// comma or full stop ending a line is set half width.
LineEndHalf,
/// YakumonoHankaku: every opening and closing bracket, comma and full stop is set half width,
/// a middle dot loses a quarter em on each side, and a quarter em separates Japanese and Latin
/// letters or digits.
YakumonoHankaku,
/// GyomatsuYakumonoHankaku: punctuation keeps its full width, except that an opening bracket
/// starting a line is set flush with the line's start, a closing bracket, comma or full stop
/// ending a line is set half width and a middle dot ending a line loses the quarter em after
/// it; a quarter em separates Japanese and Latin letters or digits.
GyomatsuYakumonoHankaku,
/// GyomatsuYakumonoZenkaku: punctuation keeps its full width at a line's end too; a quarter em
/// separates Japanese and Latin letters or digits.
GyomatsuYakumonoZenkaku,
/// YakumonoZenkaku: punctuation keeps its full width, with no added space between Japanese and
/// Latin text.
YakumonoZenkaku,
}
impl Mojikumi {
+3 -1
View File
@@ -357,7 +357,7 @@ impl ParaList {
/// The style the marker is set in: `first` (the style of the paragraph's first character)
/// without its baseline shift, rotation, superscript or subscript, tracking, manual kerning,
/// tate-chu-yoko, underline and strikethrough.
/// Insert Aki, tate-chu-yoko, underline and strikethrough.
pub fn marker_style(first: &CharStyle) -> CharStyle {
CharStyle {
baseline_shift: 0.0,
@@ -366,6 +366,8 @@ impl ParaList {
tracking: 0.0,
kerning: None,
kerning_before: 0.0,
aki_left: 0.0,
aki_right: 0.0,
optical_kerning: first.optical_kerning,
tate_chu_yoko: false,
underline: false,
+37
View File
@@ -92,6 +92,43 @@ fn font_height_reference_is_saved_only_when_not_the_em_box() {
assert_eq!(serde_json::from_value::<CharStyle>(old).unwrap().font_height_reference, FontHeightReference::EmBox);
}
/// Insert Aki Left and Right are 0 by default and saved only when not 0, each side on its own;
/// styles written before them read as 0, and a value out of range from a file is kept from 0 to one
/// em.
#[test]
fn insert_aki_is_saved_only_when_set() {
let st = CharStyle::default();
assert_eq!((st.aki_left, st.aki_right), (0.0, 0.0));
let saved = serde_json::to_value(&st).unwrap();
assert!(saved.get("akiLeft").is_none() && saved.get("akiRight").is_none());
for set in [
CharStyle { aki_left: 250.0, ..CharStyle::default() },
CharStyle { aki_right: 500.0, ..CharStyle::default() },
CharStyle { aki_left: 125.5, aki_right: 1000.0, ..CharStyle::default() },
] {
let saved = serde_json::to_value(&set).unwrap();
assert_eq!(saved.get("akiLeft").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_left);
assert_eq!(saved.get("akiRight").and_then(serde_json::Value::as_f64).unwrap_or(0.0), set.aki_right);
assert_eq!(saved.get("akiLeft").is_some(), set.aki_left != 0.0);
assert_eq!(serde_json::from_value::<CharStyle>(saved).unwrap(), set);
}
let old = serde_json::to_value(&st).unwrap();
let read = serde_json::from_value::<CharStyle>(old).unwrap();
assert_eq!((read.aki_left, read.aki_right), (0.0, 0.0));
let mut damaged = CharStyle { aki_left: -20.0, aki_right: 4000.0, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
let mut damaged = CharStyle { aki_left: f64::NAN, aki_right: f64::INFINITY, ..CharStyle::default() };
damaged.keep_dimensions_in_range();
assert_eq!((damaged.aki_left, damaged.aki_right), (0.0, MAX_AKI));
// A character style from a file is kept in range the same way.
let mut d = crate::Document::new(100.0, 100.0);
let attrs = serde_json::json!({"akiLeft": 5000, "akiRight": -1});
d.char_styles.push(TextStyleDef { name: "Spaced".into(), attrs: attrs.as_object().cloned().unwrap_or_default() });
d.keep_type_values_in_range();
assert_eq!((d.char_styles[0].attrs["akiLeft"].as_f64(), d.char_styles[0].attrs["akiRight"].as_f64()), (Some(MAX_AKI), Some(0.0)));
}
/// Each Indic numeral system draws 0–9 (and the Arabic-Indic sets) as the ten digits of its
/// script's block; every system saves under its id, which reads back, and other names are refused.
#[test]
+3
View File
@@ -15,6 +15,7 @@ vectorcraft-doc = { workspace = true }
vectorcraft-pathops = { workspace = true }
vectorcraft-text = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-trace = { workspace = true }
image = { workspace = true }
kurbo = { workspace = true }
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
@@ -26,3 +27,5 @@ serde_json = { workspace = true }
[dev-dependencies]
vectorcraft-color = { workspace = true }
# A face built in code from the bundled Source Sans 3 (no font file is committed).
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
+64 -7
View File
@@ -435,11 +435,19 @@ impl ColorVisitor for Live<'_, '_> {
/// adjustments of an object `n` is the art of) on everything it paints. The adjustment effects
/// are gone from the result; embedded images take the keys `images` gives. `swatches` tells the
/// document's global and spot swatches apart ([`crate::addons::duotone::swatch_kind`]).
pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images: &mut ImageHook<'_>) -> Option<Node> {
/// `has_image` tells whether the document holds an image: an image whose color mask's pixels are
/// missing is recoloured from its own pixels, as it is drawn without the adjustment.
pub fn adjust(
n: &Node,
outer: Option<&ColorMap>,
swatches: &SwatchKinds,
images: &mut ImageHook<'_>,
has_image: &dyn Fn(&str) -> bool,
) -> Option<Node> {
let mut m: Option<Node> = None;
if let Some(ch) = n.children() {
for (i, c) in ch.iter().enumerate() {
if let Some(new) = adjust(c, None, swatches, images)
if let Some(new) = adjust(c, None, swatches, images, has_image)
&& let Some(slot) = m.get_or_insert_with(|| n.clone()).children_mut().and_then(|ch| ch.get_mut(i))
{
*slot = Arc::new(new);
@@ -462,11 +470,57 @@ pub fn adjust(n: &Node, outer: Option<&ColorMap>, swatches: &SwatchKinds, images
if let Some(map) = map {
let mm = m.get_or_insert_with(|| n.clone());
mm.appearance.effects.retain(|e| !is_adjustment(&e.id));
show_color_masks(mm, has_image);
recolor_node(mm, Reach::ALL, &mut Live { map: &map, swatches, images });
}
m
}
/// Whether `n` is an image that [`recolor_node`] recolours (embedded, not colorized, without
/// pixels of its own) with a color mask made from its pixels.
fn recoloured_with_mask(n: &Node) -> bool {
match (&n.kind, Document::color_mask_of(n)) {
(NodeKind::Image(im), Some(m)) => im.link.is_none() && n.extras().colorize.is_none() && m.made_for(im),
_ => false,
}
}
/// Whether `n` is or holds an image [`recoloured_with_mask`] counts.
fn holds_recoloured_with_mask(n: &Node) -> bool {
recoloured_with_mask(n) || n.children().is_some_and(|ch| ch.iter().any(|c| holds_recoloured_with_mask(c)))
}
/// Give each image in `n` that [`recoloured_with_mask`] counts its masked pixels as its own,
/// without the mask, so [`recolor_node`] recolours the pixels it shows and the colors the mask
/// hides stay hidden. An image whose masked pixels the document does not hold (`has_image`) is
/// drawn from its own pixels ([`Document::shown_image`]): it keeps its key and loses the mask, so
/// the recoloured copy is drawn the same way.
fn show_color_masks(n: &mut Node, has_image: &dyn Fn(&str) -> bool) {
if recoloured_with_mask(n)
&& let Some(masked) = Document::color_mask_of(n).map(|m| m.key.clone())
{
if let NodeKind::Image(im) = &mut n.kind
&& has_image(&masked)
{
im.key = masked;
}
n.extras_mut().color_mask = None;
}
for c in n.children_mut().into_iter().flatten() {
if holds_recoloured_with_mask(c) {
show_color_masks(Arc::make_mut(c), has_image);
}
}
}
/// The keys of the masked pixels of the color masks in `n` and its members.
fn color_mask_keys<'a>(n: &'a Node, out: &mut Vec<&'a str>) {
out.extend(Document::color_mask_of(n).map(|m| m.key.as_str()));
for c in n.children().into_iter().flatten() {
color_mask_keys(c, out);
}
}
/// [`adjust`] for export and Expand Appearance: recoloured embedded images become new images in
/// `d` (named by their content), and a symbol instance stands for its symbol's art: `symbol_art`
/// when given, otherwise the symbol's art with the instance's own appearance changes.
@@ -482,13 +536,16 @@ pub fn adjust_in_document(d: &mut Document, n: &Node, symbol_art: Option<Node>)
_ => n,
};
let kinds = crate::addons::duotone::swatch_kinds(d);
let mut masked = vec![];
color_mask_keys(src, &mut masked);
masked.retain(|k| d.images.contains_key(*k));
let mut hook = |key: &str, map: &ColorMap| -> Option<String> {
let blob = d.images.get(key)?.map_rgb(|rgb| map.apply_rgb8(rgb))?;
let k = blob.content_key();
d.images.entry(k.clone()).or_insert(blob);
Some(k)
};
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook)
adjust(src, None, &|name| kinds.get(name).copied(), &mut hook, &|key| masked.contains(&key))
}
#[cfg(test)]
@@ -551,17 +608,17 @@ mod tests {
let mut g = Node::group(NodeId(1), vec![leaf(2), leaf(3)]);
g.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
assert!(has_adjustment(&g));
let out = adjust(&g, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
assert!(out.appearance.effects.is_empty());
for c in out.children().unwrap() {
assert_eq!(c.appearance.fill_paint().color().unwrap().to_hex(), "#00ff00");
}
// A hidden effect does nothing; a stroke's own effect recolours just that stroke.
g.appearance.effects[0].visible = false;
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None).is_none());
assert!(!has_adjustment(&g) && adjust(&g, None, &|_| None, &mut |_, _| None, &|_| true).is_none());
let mut p = Node::path(NodeId(5), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
p.appearance.items[1].effects_mut().push(Effect { id: "adjust.levels".into(), params: json!({"outputBlack": 255}), visible: true });
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
assert_eq!(out.appearance.items[1].paint().color().unwrap().to_hex(), "#ffffff");
assert_eq!(out.appearance.items[0].paint(), p.appearance.items[0].paint());
assert!(out.appearance.items[1].effects().is_empty());
@@ -576,7 +633,7 @@ mod tests {
let fill = Appearance::basic(Paint::Gradient(Box::new(gp)), Paint::None, 0.0);
let mut p = Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), fill);
p.appearance.effects.push(Effect { id: "adjust.hueSaturation".into(), params: json!({"hue": 120}), visible: true });
let out = adjust(&p, None, &|_| None, &mut |_, _| None).unwrap();
let out = adjust(&p, None, &|_| None, &mut |_, _| None, &|_| true).unwrap();
let Paint::Gradient(g) = out.appearance.fill_paint() else { panic!("a gradient fill") };
// The points are what a freeform gradient draws from, not its stops.
let hexes: Vec<String> = g.freeform.as_ref().unwrap().points.iter().map(|p| p.color.to_hex()).collect();
+47 -8
View File
@@ -29,7 +29,7 @@ use crate::group::{has_own_paint, paints};
use crate::reshape::{as_art, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
has_item_geometry, has_pathfinder, is_geometry, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, outline_text, reshape,
};
fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
@@ -41,8 +41,8 @@ fn item_effects(item: &AppearanceItem) -> &[vectorcraft_doc::Effect] {
fn clear_item_effects(item: &mut AppearanceItem) {
match item {
AppearanceItem::Fill(f) => f.effects.retain(|e| !is_geometry(&e.id)),
AppearanceItem::Stroke(s) => s.effects.retain(|e| !is_geometry(&e.id)),
AppearanceItem::Fill(f) => f.effects = crate::raster::without_geometry(&f.effects),
AppearanceItem::Stroke(s) => s.effects = crate::raster::without_geometry(&s.effects),
}
}
@@ -104,6 +104,15 @@ fn path_kind(d: &mut Document, path: PathData, rule: FillRule) -> NodeKind {
}
}
thread_local! {
/// How many symbol instances deep [`bake_node`] is baking, through the art of instances whose
/// effects reshape it.
static INSTANCE_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The objects of symbol art that [`bake_document`] has baked for instances inside the art of
/// other instances, counted against [`crate::SYMBOL_ART_MAX_NODES`].
static NESTED_NODES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// `n` with its geometry effects evaluated (`None` = unchanged).
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
@@ -143,8 +152,27 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
}
_ => None,
};
// Instances baked inside the art of others stop at the depth limit, or once their art
// passes the objects one export bakes that way: an instance of a symbol whose art holds
// instances of itself is kept as it is there.
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
if instance && INSTANCE_DEPTH.with(|c| c.get()) > 0 {
let count = symbol.as_ref().map_or(0, |a| a.count() as u64);
let spent = NESTED_NODES.with(|c| c.get()).saturating_add(count);
if INSTANCE_DEPTH.with(|c| c.get()) >= vectorcraft_doc::depth::MAX_DEPTH || spent > crate::SYMBOL_ART_MAX_NODES {
return None;
}
NESTED_NODES.with(|c| c.set(spent));
}
let m = reshape(Some(d), n, symbol.as_ref())?;
return Some(bake_node(d, &m).unwrap_or(m));
if instance {
INSTANCE_DEPTH.with(|c| c.set(c.get() + 1));
}
let baked = bake_node(d, &m);
if instance {
INSTANCE_DEPTH.with(|c| c.set(c.get() - 1));
}
return Some(baked.unwrap_or(m));
}
// A path whose Transform effect copies it with a gradient, or scales its strokes or moves its
// patterns: each copy an object of its own, so its gradient fits it rather than spanning
@@ -337,7 +365,7 @@ fn moved_type_group(n: &Node) -> Option<Node> {
g.knockout = Knockout::Off;
g.knockout_shape = n.knockout_shape;
g.extras_mut().mask = n.extras().mask.clone();
g.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
g.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
Some(g)
}
@@ -397,7 +425,8 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
return None;
}
reshape_leaves(&mut m, &fx, &n.appearance.effects, Some(d));
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !is_geometry(&e.id));
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
m.appearance.items.clear();
m.appearance.contents_index = None;
Some(m)
@@ -439,7 +468,9 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
m.appearance.effects.retain(|e| !is_geometry(&e.id));
// The raster effects of its fills and strokes follow its Transform effects, as on the canvas.
crate::raster::follow_items(&mut m);
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
Some((g, rule, ctx, m))
}
@@ -528,7 +559,9 @@ fn hoist_transparency(mut p: Node) -> Node {
}
/// [`expand_leaf`] every path and compound path in `n` (art made for Expand Appearance, such as a
/// group's own fills and strokes or outlined type), in place.
/// group's own fills and strokes or outlined type), in place. A group or layer in it with an
/// appearance of its own ([`crate::has_container_appearance`]) is first made into the art that
/// appearance paints ([`crate::evaluate_container`]).
pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
if matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) {
if let Some(m) = expand_leaf(d, n, stroke_art) {
@@ -536,6 +569,11 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
}
return;
}
if crate::has_container_appearance(n)
&& let Some(m) = crate::evaluate_container(Some(&*d), n)
{
*n = m;
}
for c in n.children_mut().into_iter().flatten() {
expand_art(d, Arc::make_mut(c), stroke_art);
}
@@ -658,6 +696,7 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
};
}
let mut d = placed.into_owned();
NESTED_NODES.with(|c| c.set(0));
let layers = d.layers.clone();
d.layers = layers.iter().map(|l| bake_node(&mut d, l).map(Arc::new).unwrap_or_else(|| l.clone())).collect();
Some(d)
+9 -7
View File
@@ -94,6 +94,8 @@ fn lengths_of(id: &str) -> Lengths {
"stylize.glowingEdges" => always(&["edgeWidth", "smoothness"]),
"brushStrokes.accentedEdges" => always(&["edgeWidth"]),
"artistic.paletteKnife" => always(&["strokeSize"]),
"artistic.coloredPencil" => always(&["pencilWidth"]),
"artistic.paintDaubs" => always(&["brushSize"]),
"brushStrokes.angledStrokes" | "brushStrokes.crosshatch" | "brushStrokes.inkOutlines" => always(&["strokeLength"]),
"brushStrokes.spatter" => always(&["sprayRadius"]),
"brushStrokes.sprayedStrokes" => always(&["strokeLength", "sprayRadius"]),
@@ -187,8 +189,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
INFLATE,
@@ -201,8 +203,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}),
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}),
),
g(
CLASSIC_EXTRUDE,
@@ -265,7 +267,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"distort.transform",
"Transform…",
DT,
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power)}",
"{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}",
json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}),
),
g(
@@ -294,7 +296,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"path.outlineObject",
"Outline Object",
PATH,
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change",
"{} type is drawn, exported and expanded as its glyph outlines and stays editable, and the effects after it reshape those outlines; paths and images do not change. On an image's own fill or stroke it gives the outline of the image's pixels that are at least half opaque (VectorCraft's own cutoff), and nothing when no pixel is; it gives the image's frame when the image has no transparency, its pixels can't be read, or the image or its outline is too large to trace",
json!({}),
),
g(
@@ -387,7 +389,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"artistic.paintDaubs",
"Paint Daubs…",
ARTISTIC,
"{brushSize: 1..50 (10; dab centres farther apart), sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
"{brushSize: 1..50 (10; spacing of the dab centers in document units),sharpness: 0..40 (25; harder dab edges), brushType: \"simple\"|\"lightRough\"|\"darkRough\"|\"wideSharp\"|\"wideBlurry\"|\"sparkle\" (\"simple\")} repaints the object with thick round brush dabs in the local colours, keeping its coverage. Original visual approximation; chosen VectorCraft defaults.",
json!({"brushSize": 10.0, "sharpness": 25.0, "brushType": "simple"}),
),
r(
+7 -3
View File
@@ -257,6 +257,9 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
if carry.moves(&m.appearance) {
carry.apply(&mut m.appearance);
}
// So do the raster effects of its fills and strokes, by `n`'s Transform effects
// ([`crate::follow_items`]).
crate::raster::follow_items_of(&mut m, &n.appearance.effects);
}
without_geometry_effects(&mut m);
m
@@ -265,7 +268,7 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node {
fn without_geometry_effects(n: &mut Node) {
if n.appearance.effects.iter().any(|e| crate::is_geometry(&e.id)) {
let mut ap = (*n.appearance).clone();
ap.effects.retain(|e| !crate::is_geometry(&e.id));
ap.effects = crate::raster::without_geometry(&ap.effects);
n.appearance = ap.into();
}
}
@@ -686,7 +689,7 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
/// A path node of `id` on `path` (filled under `rule`) painted by `ap`.
fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
pub(crate) fn shape_node(id: NodeId, path: PathData, rule: FillRule, ap: Appearance) -> Node {
let mut n = Node::path(id, path, ap);
if let NodeKind::Path { rule: r, .. } = &mut n.kind {
*r = rule;
@@ -794,7 +797,8 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
carry.apply(&mut m.appearance);
}
}
m.appearance.effects.retain(|e| !is_pathfinder(&e.id) && !crate::is_geometry(&e.id));
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
if paint {
let shapes = member_shapes(doc, &m);
let bounds = m.geometric_bounds();
+17
View File
@@ -1281,6 +1281,23 @@ fn compound_shape(mode: ShapeMode) -> Node {
g
}
/// A compound shape's Transform effect turns its fill's drop shadow with the area it turns.
#[test]
fn a_compound_shapes_transform_turns_its_fills_shadow() {
let mut shape = compound_shape(ShapeMode::Add);
if let Some(item) = shape.appearance.items.first_mut() {
*item.effects_mut() =
vec![Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 0, "blur": 0}), visible: true }];
}
shape.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true });
let art = shape_art(None, &shape, None).unwrap();
let item = art.appearance.items.first().unwrap();
match crate::raster_effects(item.effects()).first() {
Some(crate::RasterFx::DropShadow { dx, dy, .. }) => assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9, "{dx} {dy}"),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
/// A compound shape draws the area its members' modes make, one unpainted path that its own
/// appearance paints; evaluated, it is plain art painted with that appearance.
#[test]
+13 -7
View File
@@ -78,24 +78,30 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects};
pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art,
has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects,
has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES,
classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES,
ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds,
graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes,
three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in,
validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
pub use trap::TRAP;
pub use vectorcraft_three_d::Mesh;
pub use vectorcraft_three_d::PlanarFace;
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
mod catalog;
+216 -5
View File
@@ -1,11 +1,13 @@
//! Raster (painted) effects: descriptions for the renderer.
use serde_json::Value;
use std::borrow::Cow;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Color};
use vectorcraft_doc::rastersettings::MAX_ADD_AROUND;
use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings};
use vectorcraft_doc::{AppearanceItem, Effect, Node, RasterColorModel, RasterEffectsSettings};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use crate::merged_params;
use crate::pixel::{self, PixelFx, PixelSpace};
@@ -384,9 +386,10 @@ fn opacity(p: &Value) -> f32 {
(num(p, "opacity", 75.0) / 100.0).clamp(0.0, 1.0) as f32
}
/// The visible raster effects of `effects`, in stack order.
/// The visible raster effects of `effects`, in stack order, each following the Transform effects
/// listed after it ([`followed`]).
pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
effects
followed(effects)
.iter()
.filter(|e| e.visible)
.filter_map(|e| {
@@ -426,6 +429,214 @@ pub fn raster_effects(effects: &[Effect]) -> Vec<RasterFx> {
.collect()
}
/// `effects` with each raster effect following the visible Transform effects listed after it
/// ([`follow_transform`]): effects apply in the order they are listed, so a Transform effect
/// transforms what the raster effects before it paint, whatever its Scale Strokes & Effects says.
/// A hidden raster effect follows too, so it draws the same when it is shown after the Transform
/// effect has been expanded. A raster effect that a Transform effect making copies or moving at
/// random follows stays as it is, as does one after the last Transform effect. Borrowed when
/// nothing changes.
pub(crate) fn followed(effects: &[Effect]) -> Cow<'_, [Effect]> {
if !effects.iter().any(|e| e.visible && e.id == "distort.transform") {
return Cow::Borrowed(effects);
}
let mut out: Option<Vec<Effect>> = None;
// The linear part of the Transform effects after the effect at hand, the last one outermost;
// `None` once one of them makes copies or moves at random.
let mut after = Some(Affine::IDENTITY);
for (i, e) in effects.iter().enumerate().rev() {
if e.id == "distort.transform" {
after = after.and_then(|a| transform_step(e).map(|s| a * s));
continue;
}
let Some(a) = after.filter(|a| *a != Affine::IDENTITY && follows(&e.id)) else { continue };
let list = out.get_or_insert_with(|| effects.to_vec());
if let Some(e) = list.get_mut(i) {
follow_transform(e, a);
}
}
out.map_or(Cow::Borrowed(effects), Cow::Owned)
}
/// `effects` without their geometry effects, each raster effect following the Transform effects
/// it loses ([`followed`]): what an object, or a fill or stroke, keeps once its geometry effects
/// are applied to its art.
pub fn without_geometry(effects: &[Effect]) -> Vec<Effect> {
followed(effects).iter().filter(|e| !crate::is_geometry(&e.id)).cloned().collect()
}
/// Make the raster effects of `effects`, all listed before Transform effect `t`, follow `t` as
/// [`followed`] makes them follow it, for art that applies its effects one at a time. `false`
/// when `t` leaves them as they are.
pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool {
let Some(a) = transform_step(t).filter(|a| *a != Affine::IDENTITY) else { return false };
let mut changed = false;
for e in effects.iter_mut().filter(|e| follows(&e.id)) {
follow_transform(e, a);
changed = true;
}
changed
}
/// The linear part of the visible Transform effects of `owner`, an object's or a container's own
/// effects, in order: what they do to the raster effects of everything the object paints (its
/// fills and strokes, and a container's members and theirs), which those effects transform with
/// the rest of the art. `None` when they leave them as they are: no Transform effect moves the
/// art, or one of them makes copies or moves at random ([`followed`]).
pub(crate) fn contents_step(owner: &[Effect]) -> Option<Affine> {
let a = owner.iter().filter(|e| e.visible && e.id == "distort.transform").try_fold(Affine::IDENTITY, |a, e| transform_step(e).map(|s| s * a))?;
(a != Affine::IDENTITY).then_some(a)
}
/// Make the raster effects of `effects`, the own effects of something inside an object (a fill's
/// or stroke's, or a member's), follow `a`, the linear part of the object's Transform effects
/// ([`contents_step`]), which apply after all of them. `outer` is what the Transform effects
/// between them and `a` do to them (those of the fill's or stroke's object and of the groups that
/// hold it inside the object). A raster effect that the Transform effects after it in `effects`
/// move ([`followed`]) is set so that it draws as those effects, then `outer` and then `a`
/// transform it, whichever of them is applied first. One that a Transform effect after it in
/// `effects` holds back keeps its value through those effects, so it is set to draw as `outer` and
/// then `a` transform it. `false` when nothing changed.
pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) -> bool {
if a == Affine::IDENTITY || !effects.iter().any(|e| follows(&e.id)) {
return false;
}
let mut changed = false;
// The linear part of the Transform effects after the effect at hand, as `followed` reads it;
// `None` once one of them holds the effect back, which they then leave as it is.
let mut after = Some(Affine::IDENTITY);
for e in effects.iter_mut().rev() {
if e.id == "distort.transform" {
after = after.and_then(|b| transform_step(e).map(|s| b * s));
continue;
}
if !follows(&e.id) {
continue;
}
let b = outer * after.unwrap_or(Affine::IDENTITY);
// The effect is still to be mapped by `b` when it is drawn, so it takes b⁻¹·a·b now:
// drawn, it is a·b of what it was. A `b` that flattens the art takes `a` alone.
let det = b.determinant();
let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b };
if c.is_finite() {
follow_transform(e, c);
changed = true;
}
}
changed
}
/// Make the raster effects of the fills and strokes of `n` follow the Transform effects of its own
/// effect list ([`contents_step`]), as they do while the object is drawn with them: for art that
/// applies those effects and keeps the fills and strokes. `false` when nothing changed.
pub fn follow_items(n: &mut Node) -> bool {
let Some(a) = contents_step(&n.appearance.effects) else { return false };
follow_items_by(n, a)
}
/// [`follow_items`] for `n` holding the fills and strokes of an object whose own effects are
/// `owner` (the area of a compound shape, which carries none of the shape's effects).
pub(crate) fn follow_items_of(n: &mut Node, owner: &[Effect]) -> bool {
let Some(a) = contents_step(owner) else { return false };
follow_items_by(n, a)
}
/// Make the raster effects of the fills and strokes of `n` follow `a` ([`follow_contents`]).
fn follow_items_by(n: &mut Node, a: Affine) -> bool {
if !n.appearance.items.iter().any(|i| i.effects().iter().any(|e| follows(&e.id))) {
return false;
}
let mut changed = false;
for item in &mut n.appearance.items {
changed |= follow_contents(item.effects_mut(), a, Affine::IDENTITY);
}
changed
}
/// Make the raster effects of `items`, the fills and strokes of an object whose own effects are
/// `owner`, follow the Transform effects of `owner` ([`follow_contents`]): for art that applies
/// those effects to the object's path and draws each fill and stroke on it as a node of its own.
pub(crate) fn follow_paints(items: &mut [AppearanceItem], owner: &[Effect]) {
let Some(a) = contents_step(owner) else { return };
for item in items {
follow_contents(item.effects_mut(), a, Affine::IDENTITY);
}
}
/// `effects`, those of a fill or stroke of an object whose own effects are `owner`, with each
/// raster effect following the Transform effects of `owner` as well ([`follow_contents`]): the
/// list to draw that fill's or stroke's raster effects from ([`raster_effects`]). Borrowed when
/// nothing changes.
pub fn item_effects_in<'a>(owner: &[Effect], effects: &'a [Effect]) -> Cow<'a, [Effect]> {
let Some(a) = contents_step(owner) else { return Cow::Borrowed(effects) };
if !effects.iter().any(|e| follows(&e.id)) {
return Cow::Borrowed(effects);
}
let mut out = effects.to_vec();
if follow_contents(&mut out, a, Affine::IDENTITY) { Cow::Owned(out) } else { Cow::Borrowed(effects) }
}
/// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the
/// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform
/// effect among them that makes copies or moves at random.
pub(crate) fn held_back(effects: &[Effect]) -> usize {
let Some(last) = effects.iter().rposition(|e| transform_step(e).is_none()) else { return 0 };
effects.get(..last).unwrap_or_default().iter().filter(|e| !crate::is_geometry(&e.id)).count()
}
/// Does `e` stop the raster effects listed before it from following the Transform effects after
/// it ([`followed`]): is it a visible Transform effect that makes copies or moves at random?
pub(crate) fn holds_back(e: &Effect) -> bool {
transform_step(e).is_none()
}
/// What `e` does to the raster effects listed before it ([`followed`]): the linear part of its map
/// when it is a visible Transform effect that moves the art once, the identity when it is no
/// Transform effect, is hidden or has Transform Objects off (the art stays where it is), and `None`
/// when it makes copies or moves at random.
fn transform_step(e: &Effect) -> Option<Affine> {
if e.id != "distort.transform" || !e.visible {
return Some(Affine::IDENTITY);
}
let p = merged_params(&e.id, &e.params);
if !flag(&p, "objects", true) {
return Some(Affine::IDENTITY);
}
let (map, copies) = crate::distort::transform_map(Rect::ZERO, &p, 0);
(copies == 0 && !flag(&p, "random", false)).then(|| map.with_translation(Vec2::ZERO))
}
/// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG
/// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room
/// around the art.
pub(crate) fn follows(id: &str) -> bool {
crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE
}
/// Make raster effect `e` follow `a`, the linear part of a Transform effect listed after it, as
/// that effect transforms what `e` paints: its distances and raster sizes scale by `a`'s mean
/// scale ([`crate::scale_effect`]), and a Drop Shadow's offset turns, reflects and scales with
/// `a`. Effects that [`follows`] leaves out stay as they are.
fn follow_transform(e: &mut Effect, a: Affine) {
if !follows(&e.id) {
return;
}
let offset = (e.id == "stylize.dropShadow").then(|| {
let p = merged_params(&e.id, &e.params);
a * Point::new(num(&p, "x", 7.0), num(&p, "y", 7.0))
});
if let Some(k) = vectorcraft_doc::Scaling::factor(a) {
crate::scale_effect(e, k);
}
if let Some(o) = offset.filter(|o| o.x.is_finite() && o.y.is_finite()) {
if !e.params.is_object() {
e.params = Value::Object(Map::new());
}
e.params["x"] = json!(o.x);
e.params["y"] = json!(o.y);
}
}
/// How far the visible raster effects of `effects` paint beyond `bounds`, the (effected)
/// geometry's, in document units. Geometry effects are accounted for by evaluating them.
pub fn outset(effects: &[Effect], bounds: Rect) -> f64 {
+502 -56
View File
@@ -10,12 +10,13 @@
//! inline graphics whose own fills or strokes have geometry effects is outlined too: each of those
//! effects reshapes the whole outline that its fill or stroke paints. An image's own fills and
//! strokes paint only the shape that a Convert to Shape or Outline Object effect on them gives
//! them ([`image_rows`]).
//! them ([`image_rows`]): Outline Object follows the outline of the image's opaque area
//! ([`opaque_area`]).
use std::collections::{HashMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock, PoisonError, Weak};
use vectorcraft_doc::live::Hooks;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, ImageObject, Node, NodeId, NodeKind};
@@ -130,19 +131,142 @@ pub fn has_painted_effects(n: &Node) -> bool {
}
/// Is `n` type without inline graphics that has a fill or stroke of its own that paints and has a
/// visible geometry effect, or an image with a fill or stroke of its own that paints a shape
/// ([`image_rows`])? On type, such an effect reshapes the whole outline that its fill or stroke
/// paints ([`outline_text`], which leaves inline graphics out).
/// visible geometry effect, an image with a fill or stroke of its own that paints a shape
/// ([`image_rows`]), or a symbol instance whose active fill or stroke has a visible geometry effect
/// ([`active_fill`], [`active_stroke`])? On type, such an effect reshapes the whole outline that its
/// fill or stroke paints ([`outline_text`], which leaves inline graphics out). On a symbol
/// instance, it reshapes the fills or strokes of the art it places ([`add_instance_row_effects`]).
pub fn has_item_geometry(n: &Node) -> bool {
match &n.kind {
NodeKind::Text(t) => {
t.runs.iter().all(|r| r.inline.is_none()) && n.appearance.items.iter().any(|i| crate::paints(i) && crate::has_geometry(i.effects()))
}
NodeKind::Image(_) => n.appearance.items.iter().any(shapes_image),
NodeKind::SymbolInstance { .. } => {
active_fill(n).is_some_and(|f| crate::has_geometry(&f.effects)) || active_stroke(n).is_some_and(|s| crate::has_geometry(&s.effects))
}
_ => false,
}
}
/// The fill of symbol instance `n` whose effects its art takes: its topmost fill, the one that
/// stains the art, when it is visible and its opacity is above 0. A lower fill's effects do not
/// reach the art.
fn active_fill(n: &Node) -> Option<&vectorcraft_doc::FillLayer> {
n.appearance.fill().filter(|f| f.visible && f.opacity > 0.0)
}
/// The stroke of symbol instance `n` whose effects its art takes: its topmost stroke, when it is
/// visible and its opacity is above 0.
fn active_stroke(n: &Node) -> Option<&vectorcraft_doc::StrokeLayer> {
n.appearance.stroke().filter(|s| s.visible && s.opacity > 0.0)
}
/// The visible geometry effects in `fx`, in order.
fn geometry_of(fx: &[Effect]) -> Vec<Effect> {
fx.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect()
}
/// `art`, the art symbol instance `n` places, with the visible geometry effects of `n`'s active
/// fill added after the effects of every fill in it that paints, and those of its active stroke
/// after the effects of every stroke in it that paints ([`active_fill`], [`active_stroke`]). Each
/// fill or stroke keeps its paint, and the others keep their shapes. Live objects in it that are
/// reached are evaluated first (with the symbols of `doc`), so the effects reshape what they draw.
/// Clip groups' clipping paths, guides and the art of opacity masks keep their shapes. A symbol
/// instance in the art takes the effects on its own active fill or stroke, or on a new fill or
/// stroke without paint when it has none, and passes them on to its own art in turn; an instance
/// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its
/// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no
/// instance in the art takes them.
fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) {
let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return };
let fill = active_fill(n).map_or(vec![], |f| geometry_of(&f.effects));
let stroke = active_stroke(n).map_or(vec![], |s| geometry_of(&s.effects));
if !fill.is_empty() || !stroke.is_empty() {
add_row_effects(doc, symbol, art, &fill, &stroke);
}
}
/// Does the art of the symbol named `from` in `doc` hold an instance of the symbol named `to`, at
/// any depth of the symbols placed in it? `seen` holds the symbols already looked into.
fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet<String>) -> bool {
if !seen.insert(from.to_string()) {
return false;
}
let Some(sym) = doc.symbols.iter().find(|s| s.name == from) else { return false };
let mut names = vec![];
sym.art.walk(&mut |c| {
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
names.push(symbol.clone());
}
});
names.iter().any(|name| name == to || places_symbol(doc, name, to, seen))
}
/// [`add_instance_row_effects`] of `fill` and `stroke` to `n` and the art in it, the art of an
/// instance of the symbol named `outer`.
fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) {
match &n.kind {
NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return,
NodeKind::SymbolInstance { symbol, .. } => {
if let Some(d) = doc
&& !places_symbol(d, symbol, outer, &mut HashSet::new())
{
add_to_instance(n, fill, stroke);
}
return;
}
_ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n),
_ => {}
}
let takes = |i: &AppearanceItem| {
crate::paints(i) && !matches!(i, AppearanceItem::Fill(_) if fill.is_empty()) && !matches!(i, AppearanceItem::Stroke(_) if stroke.is_empty())
};
if n.appearance.items.iter().any(takes) {
for item in n.appearance.items.iter_mut().filter(|i| takes(i)) {
let fx = if matches!(item, AppearanceItem::Fill(_)) { fill } else { stroke };
item.effects_mut().extend_from_slice(fx);
}
}
// A compound path paints its members with its own fills and strokes.
if matches!(n.kind, NodeKind::Compound { .. }) {
return;
}
// A clip group's first member is its clipping path, whatever its kind.
let clips = n.clips();
for (i, c) in n.children_mut().into_iter().flatten().enumerate() {
if !(clips && i == 0) {
add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke);
}
}
}
/// Add `fill` to the effects of symbol instance `n`'s active fill and `stroke` to those of its
/// active stroke ([`active_fill`], [`active_stroke`]); without one, to a new topmost fill or stroke
/// without paint, which neither stains nor strokes its art.
fn add_to_instance(n: &mut Node, fill: &[Effect], stroke: &[Effect]) {
if !fill.is_empty() {
match n.appearance.fill_mut().filter(|f| f.visible && f.opacity > 0.0) {
Some(f) => f.effects.extend_from_slice(fill),
None => {
let mut f = vectorcraft_doc::FillLayer::new(vectorcraft_doc::color::Paint::None);
f.effects = fill.to_vec();
n.appearance.items.push(AppearanceItem::Fill(f));
}
}
}
if !stroke.is_empty() {
match n.appearance.stroke_mut().filter(|s| s.visible && s.opacity > 0.0) {
Some(s) => s.effects.extend_from_slice(stroke),
None => {
let mut s = vectorcraft_doc::StrokeLayer::new(vectorcraft_doc::color::Paint::None, 0.0);
s.effects = stroke.to_vec();
n.appearance.items.push(AppearanceItem::Stroke(s));
}
}
}
}
/// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or
/// Outline Object)?
fn gives_shape(e: &Effect) -> bool {
@@ -164,8 +288,8 @@ pub fn gives_image_shape(effects: &[Effect]) -> bool {
/// The fills and strokes of `items` (an image's own) that paint something ([`shapes_image`]), each
/// without the effects before its first Convert to Shape or Outline Object. Convert to Shape sizes
/// its shape from the image's box, and Outline Object gives the image's frame. The others paint
/// nothing.
/// its shape from the image's box, and Outline Object gives the outline of the image's opaque
/// area ([`opaque_area`]), or its frame when it has no transparency. The others paint nothing.
fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
items
.iter()
@@ -180,11 +304,109 @@ fn image_rows(items: &[AppearanceItem]) -> Vec<AppearanceItem> {
.collect()
}
/// Does `item`, one of [`image_rows`], start from the outline of the image's opaque area (is its
/// first effect Outline Object rather than Convert to Shape)?
fn follows_opaque_area(item: &AppearanceItem) -> bool {
item.effects().first().is_some_and(|e| e.id == "path.outlineObject")
}
/// Is `n` an image with a fill or stroke of its own that follows the outline of the image's opaque
/// area ([`image_rows`], [`opaque_area`])? The shape that fill or stroke paints then changes with
/// the image's pixels in the document while `n` stays the same.
pub fn follows_image_pixels(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_))
&& n.appearance
.items
.iter()
.any(|i| shapes_image(i) && i.effects().iter().find(|e| gives_shape(e)).is_some_and(|e| e.id == "path.outlineObject"))
}
/// The outline of a set of pixels' opaque area, in the pixel space they decode to, with that size
/// ([`traced_opaque_area`]). `None` for pixels that have no transparency or could not be traced.
type Traced = Option<(Arc<PathData>, (u32, u32))>;
/// One of [`Outlines`]' entries: the pixels, held weakly, and their outline once it is traced.
type Entry = (Weak<Vec<u8>>, Arc<OnceLock<Traced>>);
/// The outlines [`opaque_area`] has traced, by the address of the pixels each was traced from.
struct Outlines {
/// Each outline with its pixels. An entry does not keep its pixels, and while it is kept no
/// other pixels can take their address. Entries whose pixels are gone are dropped before a
/// new outline is traced and every [`PRUNE_EVERY`] lookups.
kept: BTreeMap<usize, Entry>,
/// The lookups since the last pruning.
lookups: usize,
}
static OUTLINES: Mutex<Outlines> = Mutex::new(Outlines { kept: BTreeMap::new(), lookups: 0 });
/// How many lookups [`OUTLINES`] takes between two prunings of its entries for pixels that are gone.
const PRUNE_EVERY: usize = 256;
#[cfg(test)]
thread_local! {
/// The outlines [`traced_opaque_area`] has traced on this thread.
pub(crate) static TRACES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Does [`OUTLINES`] keep an entry for `pixels`?
#[cfg(test)]
pub(crate) fn keeps_outline(pixels: &Weak<Vec<u8>>) -> bool {
OUTLINES.lock().unwrap_or_else(PoisonError::into_inner).kept.values().any(|(w, _)| w.ptr_eq(pixels))
}
/// The outline of the opaque area of the image `im` in the document
/// ([`vectorcraft_trace::opaque_outline`]: its pixels that are at least half opaque, outlined with
/// fitted curves), its pixels taken from `im` itself or from the first of `docs` that holds them.
/// `None` when the image has no transparency, its pixels can't be read or are too large to read
/// ([`vectorcraft_trace::decode_alpha`]), or its outline would be too complex: Outline Object then
/// follows the image's frame. The outline is traced once for each set of pixels and kept while
/// those pixels are: a caller that asks while another thread traces the same pixels waits for that
/// trace.
pub(crate) fn opaque_area(docs: &[Option<&Document>], im: &ImageObject) -> Option<PathData> {
let blob = im.pixels.as_deref().or_else(|| docs.iter().flatten().find_map(|d| d.images.get(&im.key)))?;
let bytes = &blob.bytes;
let cell = {
let mut o = OUTLINES.lock().unwrap_or_else(PoisonError::into_inner);
o.lookups += 1;
if o.lookups >= PRUNE_EVERY {
o.lookups = 0;
o.kept.retain(|_, (w, _)| w.strong_count() > 0);
}
let key = Arc::as_ptr(bytes).addr();
match o.kept.get(&key) {
Some((_, cell)) => Arc::clone(cell),
None => {
o.kept.retain(|_, (w, _)| w.strong_count() > 0);
let cell = Arc::new(OnceLock::new());
o.kept.insert(key, (Arc::downgrade(bytes), Arc::clone(&cell)));
cell
}
}
};
// Traced without the lock: another image's outline need not wait for this one.
let (path, (w, h)) = cell.get_or_init(|| traced_opaque_area(bytes)).clone()?;
let to_image = Affine::scale_non_uniform(f64::from(im.width) / f64::from(w.max(1)), f64::from(im.height) / f64::from(h.max(1)));
Some(path.transformed(im.xf * to_image))
}
/// [`opaque_area`]'s outline of the encoded image `bytes`. An image whose format has no alpha is
/// not decoded.
fn traced_opaque_area(bytes: &[u8]) -> Traced {
#[cfg(test)]
TRACES.with(|t| t.set(t.get() + 1));
let (w, h, alpha) = vectorcraft_trace::decode_alpha(bytes).ok()??;
let outline = vectorcraft_trace::opaque_outline(w, h, alpha).ok()??;
Some((Arc::new(outline), (w, h)))
}
/// The shapes that the image `n`'s own fills and strokes paint ([`image_rows`]), each with its fill
/// rule and the fill or stroke that paints it: the paths (or compound paths) along its frame that
/// [`reshape`] makes, with each fill's or stroke's geometry effects applied as the renderer applies
/// them. Empty for anything but an image with such fills or strokes. The swatches and patterns that
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
/// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`]
/// makes along its frame or, for those whose first effect is Outline Object, along the outline of
/// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the
/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches
/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and
/// the image's pixels in `doc` when the image does not hold them.
pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) {
return vec![];
@@ -302,7 +524,9 @@ fn with_id(art: &Node, id: NodeId) -> Node {
/// `n` as plain art that geometry effects can reshape, without its transparency and object
/// effects: type outlined ([`outline_text`]), live objects evaluated (type inside them outlined),
/// a symbol instance as `symbol_art` (the symbol's art, stained as the caller draws it) placed by
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them).
/// the instance's transform (through the symbol's 9-slice guides in `doc`, when it has them), its
/// fills and strokes carrying the geometry effects of the instance's active fill and stroke
/// ([`add_instance_row_effects`]).
/// `None` for other kinds (images, paths, containers), and for an instance whose art placed
/// through the guides could hold more than [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects. A Repeat counts the Repeats in the art of
/// `doc`'s symbols that its instances show toward its instance budget.
@@ -351,6 +575,9 @@ fn outline_art_with(
_ => return None,
};
outline_nested_text(paint_doc, &mut art, false);
if matches!(n.kind, NodeKind::SymbolInstance { .. }) {
add_instance_row_effects(symbols, n, &mut art);
}
art.opacity = 1.0;
art.blend = Default::default();
art.isolate = false;
@@ -480,9 +707,10 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
/// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied:
/// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped
/// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own
/// fills and strokes that paint a shape ([`image_rows`]) become paths along its frame below and
/// above it, reshaped with it, and keep their effects from their first Convert to Shape or Outline
/// Object on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
/// fills and strokes that paint a shape ([`image_rows`]) become paths below and above it, along
/// its frame or, from Outline Object, along the outline of its opaque area ([`opaque_area`]),
/// reshaped with it, and keep their effects from their first Convert to Shape or Outline Object
/// on. The result is a group with `n`'s id, name, visibility, transparency, opacity mask
/// and remaining (raster) effects; `None` when `n` has no visible geometry effect, no perspective
/// and is not type or an image with a fill or stroke of its own that [`has_item_geometry`] counts,
/// or has no art (a symbol instance without `symbol_art`). A path with [`has_transform_art`] is
@@ -497,8 +725,10 @@ pub fn reshape(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> O
/// `n` (see [`needs_outline`], or a path with [`has_transform_art`]) as plain art for Expand
/// Appearance: [`reshape`]d when it has
/// geometry effects, else type with fills or strokes of its own outlined, or an image with fills
/// or strokes of its own that paint a shape, in the same form. `None` when it has none of these.
/// geometry effects, else type with fills or strokes of its own outlined, an image with fills or
/// strokes of its own that paint a shape, or a symbol instance's art reshaped by the geometry
/// effects of its active fill or stroke ([`has_item_geometry`]), in the same form. `None` when it
/// has none of these.
pub fn expand_outlined(doc: Option<&Document>, n: &Node, symbol_art: Option<&Node>) -> Option<Node> {
// A path whose Transform effect copies it, or scales its strokes or moves its patterns: each
// copy an object of its own with the path's fills and strokes, the copies of each Transform
@@ -552,12 +782,13 @@ fn as_art_opts(
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
let mut image = Node::new(n.id, n.kind.clone());
// Its pixels draw as the image's do: colorized by a grayscale image's fill color, and
// smoothed or not.
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
// smoothed or not, and with its color mask's masked pixels.
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
}
let clipped = || {
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
@@ -566,15 +797,33 @@ fn as_art_opts(
}
Node::new(n.id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image.clone())], clip: true })
};
// The fills and strokes that paint a shape, as paths along the frame below and above
// the image.
// The fills and strokes that paint a shape, as paths below and above the image: along
// the frame, or for those whose first effect is Outline Object along the outline of
// the image's opaque area (traced only when one of them needs it). A run of either
// kind is one path; a fill or stroke whose outline is empty (an image with no opaque
// pixel) paints nothing.
let (below, above) = n.appearance.split_contents();
let (below, above) = (image_rows(below), image_rows(above));
if below.is_empty() && above.is_empty() {
clipped()
} else {
let opaque = std::cell::OnceCell::new();
let rows = |items: Vec<AppearanceItem>| {
(!items.is_empty()).then(|| Arc::new(Node::path(n.id, frame.clone(), Appearance { items, ..Default::default() })))
let mut out = vec![];
let mut items = items.into_iter().peekable();
while let Some(first) = items.next() {
let follows = follows_opaque_area(&first);
let mut run = vec![first];
while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) {
run.push(next);
}
let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None };
let path = path.unwrap_or(&frame);
if !path.is_empty() {
out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() })));
}
}
out
};
// Without geometry effects, the image is not clipped.
let image = if fx.is_empty() { image.clone() } else { clipped() };
@@ -604,7 +853,7 @@ fn as_art_opts(
out.knockout = vectorcraft_doc::Knockout::Off;
out.knockout_shape = n.knockout_shape;
out.extras_mut().mask = n.extras().mask.clone();
out.appearance.effects = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
out.appearance.effects = crate::raster::without_geometry(&n.appearance.effects);
Some(out)
}
@@ -740,12 +989,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
wholes.entry(id).or_insert_with(|| copies_whole(m));
});
let mut warped = WarpedImages::new();
// The raster effects of what the art holds follow each Transform effect that moves it once,
// whatever its options, unless one of the effects makes copies or moves at random
// ([`crate::raster::contents_step`], [`follow_art`]).
let held = listed.iter().any(|e| crate::raster::holds_back(e));
for e in fx {
let Some(bounds) = warped.bounds(art) else { break };
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes };
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes, held };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
@@ -768,8 +1021,10 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
/// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its
/// merged params, the reference box and seed of the object's art, where a deferred live-effect
/// plug-in is listed, whether each Transform copy becomes an object, the document that the
/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks.
/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of
/// each linked mask before the first effect, by the id of the object it masks, and whether one of
/// the object's effects holds the raster effects in its art back from its Transform effects
/// ([`follow_art`]).
struct Step<'a> {
e: &'a Effect,
params: &'a serde_json::Value,
@@ -779,6 +1034,7 @@ struct Step<'a> {
apart: bool,
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
held: bool,
}
/// What [`Step::run`] did to a piece of art.
@@ -885,6 +1141,8 @@ impl Step<'_> {
let options = crate::distort::TransformOptions::of(params);
(m, copies, options, crate::distort::transform_affine(bounds, params, seed))
});
// What the effect does to the raster effects in the art, when they follow it.
let raster_map = if self.held { None } else { crate::raster::contents_step(std::slice::from_ref(e)) };
// In a mask's art, images and symbol instances take only a Transform effect
// ([`transform_placed`]): a mask's art that holds one can't take another effect as the art
// it masks does.
@@ -944,7 +1202,7 @@ impl Step<'_> {
// The copies of a path replace it by a group of them, the path included.
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
*used = used.minus(before).plus(made);
if moved {
// With Transform Objects off the path stays, and its mask takes the
@@ -960,7 +1218,7 @@ impl Step<'_> {
}
if separate {
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
let made = copy_leaf(leaf, &path, m, copies, scaling, room);
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
*used = used.minus(before).plus(made);
moved_ids.insert(leaf.id);
short |= counts(leaf.id) && copied(leaf) <= copies;
@@ -1014,12 +1272,22 @@ impl Step<'_> {
*art = Node::group(id, vec![Arc::new(one)]);
}
let placed = if watch { masked_placed(art, own) } else { 0 };
transform_placed(art, m, copies, copy_scaling(options));
// Scale Strokes & Effects leaves the raster effects that follow the effect to
// [`follow_art`].
let mut scaling = copy_scaling(options);
if raster_map.is_some() {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
transform_placed(art, m, copies, scaling);
short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1));
if root && let Some([one]) = art.children().map(Vec::as_slice) {
*art = (**one).clone();
}
}
// A mask's art takes them as a group inside the art: its own raster effects follow too.
if let Some(a) = raster_map {
follow_art(art, a, &kept_ids, Some(&moved_ids), own.then_some(Affine::IDENTITY), depth);
}
if outlines.iter().any(Option::is_some) {
rebase_type_outlines(art, &mut outlines.into_iter());
}
@@ -1239,14 +1507,94 @@ fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::S
}
}
/// [`crate::scale_effect`] for the effects that do not follow a Transform effect as raster effects
/// do ([`crate::raster::follows`]): Scale Strokes & Effects scales them, and [`follow_art`] moves
/// the others.
fn scale_unfollowed(e: &mut Effect, s: f64) {
if !crate::raster::follows(&e.id) {
crate::scale_effect(e, s);
}
}
/// Make the raster effects under `art` follow `a`, the linear part of a Transform effect that moved
/// it ([`crate::raster::follow_contents`]): those of every object in it (its own and its fills' and
/// strokes'), the art's own effects excepted (`up` is `None` for the art itself). A path that kept
/// its shape (in `kept`), and a group with such a path under it, keep their own and their fills'
/// and strokes'. `up` is what the Transform effects of the groups between an object and the art do
/// to the object's effects. A Transform effect of an object's own that makes copies or moves at
/// random leaves the effects it holds back as they are, so those follow `a` and the groups' maps
/// alone. The linked opacity mask of an object that took the effect as an object (in `moved`, and
/// every image and symbol instance) moved with it, so the raster effects in the mask's art follow
/// `a` as those of a mask that takes the effect as art do ([`Step::reshape_masks`]); `moved` is
/// `None` inside such a mask's art, where every linked mask moved. The walk reaches the groups and
/// layers that [`for_each_leaf`] made the art's own, so it copies nothing. Returns whether a path in
/// `kept` is under `n`.
fn follow_art(n: &mut Node, a: Affine, kept: &HashSet<NodeId>, moved: Option<&HashSet<NodeId>>, up: Option<Affine>, depth: usize) -> bool {
if n.is_guide() {
return false;
}
if moved.is_none_or(|moved| moved.contains(&n.id)) || is_placed(n) {
follow_moved_mask(n, a, depth);
}
// What the object's own Transform effects then do to its fills' and strokes' effects and its
// members' (nothing when one of them holds those back); the art's own effects are the ones
// being applied.
let below = up.map_or(Affine::IDENTITY, |up| crate::raster::contents_step(&n.appearance.effects).map_or(up, |s| up * s));
let keeps = match &mut n.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => kept.contains(&n.id),
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => {
let mut keeps = false;
for c in children.iter_mut() {
keeps |= follow_art(Arc::make_mut(c), a, kept, moved, Some(below), depth);
}
keeps
}
_ => false,
};
if !keeps {
if let Some(up) = up
&& contents_raster(&n.appearance.effects)
{
crate::raster::follow_contents(&mut n.appearance.effects, a, up);
}
if n.appearance.items.iter().any(|i| contents_raster(i.effects())) {
for item in &mut n.appearance.items {
crate::raster::follow_contents(item.effects_mut(), a, below);
}
}
}
keeps
}
/// Make the raster effects in the art of the linked opacity mask of `n`, which moved with `n`,
/// follow `a` ([`follow_art`]), with those of the linked masks inside that art, which moved too. A
/// mask past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks stays as it is.
fn follow_moved_mask(n: &mut Node, a: Affine, depth: usize) {
if depth >= vectorcraft_doc::depth::MAX_DEPTH {
return;
}
let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return };
follow_art(Arc::make_mut(&mut m.art), a, &HashSet::new(), None, Some(Affine::IDENTITY), depth + 1);
}
/// Does any of `effects` follow a Transform effect as a raster effect ([`crate::raster::follows`])?
fn contents_raster(effects: &[Effect]) -> bool {
effects.iter().any(|e| crate::raster::follows(&e.id))
}
/// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with
/// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object
/// › Transform with those options transforms an object (#885): the strokes' weights and dashes
/// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its
/// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them
/// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform
/// Objects off the geometry stays and the options apply once. Returns what the leaf costs after,
/// and `false` when the path kept its shape because the moved path would pass `budget`.
/// Objects off the geometry stays and the options apply once. With `follows`, Scale Strokes &
/// Effects leaves the raster effects that follow the Transform effect ([`follow_art`]) to the
/// caller. The effects `kept` names keep their values on the leaf and on each copy
/// ([`keep_listed`]), whether Scale Strokes & Effects scaled them or left them to the caller.
/// Returns what the leaf costs after, and `false` when the path kept its shape because the moved
/// path would pass `budget`.
#[allow(clippy::too_many_arguments)]
fn transform_leaf(
leaf: &mut Node,
path: &PathData,
@@ -1254,8 +1602,13 @@ fn transform_leaf(
copies: usize,
options: crate::distort::TransformOptions,
budget: Budget,
follows: bool,
kept: Kept,
) -> (Budget, bool) {
let scaling = copy_scaling(options);
let mut scaling = copy_scaling(options);
if follows && copies == 0 {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
if !options.objects {
if options.strokes
&& let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0)
@@ -1266,6 +1619,7 @@ fn transform_leaf(
if options.patterns {
vectorcraft_doc::pattern::transform_pattern_paints(leaf, m);
}
keep_listed(leaf, kept);
return (Budget::of(path), true);
}
if copies == 0 {
@@ -1275,9 +1629,10 @@ fn transform_leaf(
return (Budget::of(path), false);
}
leaf.transform(m, scaling);
keep_listed(leaf, kept);
return (Budget::of(&moved), true);
}
(copy_leaf(leaf, path, m, copies, scaling, budget), true)
(copy_leaf(leaf, path, m, copies, scaling, budget, kept), true)
}
/// Does a Transform effect's copies of `art` copy it whole ([`copy_art`])? They do when `art` is a
@@ -1423,9 +1778,10 @@ fn copy_art(art: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc::
/// moves with it) rather than spanning every copy, and its strokes and patterns can differ from the
/// others'. The copies stop where [`crate::distort::transform_within`]'s would, before they pass
/// `budget` with what each copy's own geometry effects make ([`effects_cost`]), and before one's
/// strokes would scale past [`MAX_STROKE_SCALE`]. Returns what the copies cost, the original
/// included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget) -> Budget {
/// strokes would scale past [`MAX_STROKE_SCALE`]. The effects `kept` names keep their values on
/// each copy, before its cost is counted ([`keep_listed`]). Returns what the copies cost, the
/// original included.
fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling: vectorcraft_doc::Scaling, budget: Budget, kept: Kept) -> Budget {
let mut made = Budget::of(path).plus(effects_cost(leaf, path));
let mut placements: Vec<Arc<Node>> = vec![Arc::new(leaf.clone())];
let mut xf = Affine::IDENTITY;
@@ -1438,6 +1794,7 @@ fn copy_leaf(leaf: &mut Node, path: &PathData, m: Affine, copies: usize, scaling
}
let mut copy = leaf.clone();
copy.transform(xf, scaling);
keep_listed(&mut copy, kept);
// Each copy's own geometry effects make a different amount, as the copy and its effects scale.
let mut cost = Budget::of(&moved).plus(effects_cost(&copy, &moved));
// Each copy carries the art of its linked masks, moved with it.
@@ -1584,9 +1941,12 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
/// effects. In paint order, each such fill or stroke is a path of its own: the leaf's geometry after
/// the geometry effects of that fill or stroke before its first such Transform effect, transformed
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
/// stroke's weight and dashes, the distances of its remaining effects and its pattern follow the
/// map. The reference box is that geometry's bounds and the seed is the leaf's id, as the renderer
/// draws a fill's or stroke's own effects. The geometry effects after the Transform effect then
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
/// pattern follow the map, and the raster effects before it that follow it take their followed
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
/// stroke's own effects. The geometry effects after the Transform effect then
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
@@ -1659,9 +2019,16 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let params = merged_params(&fx[at].id, &fx[at].params);
// Where each effect the piece keeps sits among the item's effects.
let kept: Vec<usize> = (0..at).filter(|&k| !is_geometry(&fx[k].id)).chain(at + 1..fx.len()).collect();
// A Transform effect after this one that makes copies or moves at random holds the raster
// effects before this one back from every Transform effect ([`crate::raster::followed`]).
let held_later = fx.get(at + 1..).unwrap_or_default().iter().any(crate::raster::holds_back);
// The effects before the Transform effect that it keeps, each raster effect following the
// geometry effects before it ([`crate::raster::without_geometry`]) unless held back.
let kept_before: Vec<Effect> =
if held_later { before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect() } else { crate::without_geometry(before) };
if let Some(plugin) = painted_plugin(&fx[at]) {
let mut it = item.clone();
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest;
let mut one = Appearance { items: vec![it.clone()], ..Default::default() };
if carry.moves(&one) {
@@ -1683,7 +2050,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
group.push(Arc::new(p));
}
let mut p = Node::group(leaf.id, group);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(before), limit, used, doc);
pieces.push(Arc::new(p));
continue;
}
@@ -1691,16 +2058,22 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(tb, &params, ctx.seed);
let mut it = item.clone();
let rest: Vec<Effect> = before.iter().filter(|e| !is_geometry(&e.id)).chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest;
let rest: Vec<Effect> = kept_before.iter().chain(&fx[at + 1..]).cloned().collect();
*it.effects_mut() = rest.clone();
let mut p = piece(vec![it]);
if carry.moves(&p.appearance) {
carry.apply(&mut p.appearance);
}
set_geometry(&mut p, g.clone(), rule);
let (made, _) = transform_leaf(&mut p, &g, map, copies, options, room);
let after = kept_before.len();
let keep = |k: usize| k >= after || !options.objects;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
*used = used.plus(made);
transform_piece(&mut p, (ctx.seed, i, &kept), limit, used, doc);
let from = crate::raster::held_back(before);
if moved && !held_later {
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
}
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), limit, used, doc);
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -1717,27 +2090,45 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
/// transformed piece of [`transform_item_leaf`] and its copies) to all of `p`'s paths as one piece:
/// each effect takes the bounds of all the paths as its reference box and `seed`, as an object's
/// own effects reshape all its paths ([`reshape_leaves_carrying`]). Each path applies its own copy of
/// the effect, whose distances its Scale Strokes & Effects scaled. A Transform effect with
/// Transform Patterns or Scale Strokes & Effects on transforms each path as [`transform_leaf`] does.
/// the effect, at the effect's own distances. A Transform effect with Transform Patterns or Scale
/// Strokes & Effects on transforms each path as [`transform_leaf`] does, and leaves the values of
/// the effects after it, and with Transform Objects off those before it, as they are
/// ([`keep_listed`]).
/// A live-effect plug-in that paints what it returns ([`painted_plugin`]) makes each path one path
/// for each piece it returns ([`paint_piece`]). The geometry effects then leave the fills and
/// strokes; their other effects stay. The paths keep to `max` together with the rest of the art
/// (`used`), and the swatches and patterns painted pieces name must be in `doc`. `(seed, source,
/// kept)`: the object's seed, the index in the object's appearance of the fill or stroke the
/// piece was made from, and the index among that item's effects of each effect the piece kept,
/// which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), max: Budget, used: &mut Budget, doc: Option<&Document>) {
/// for each piece it returns ([`paint_piece`]). The raster effects before a Transform effect
/// follow it ([`follow_piece`]), except the first `held` effects, which a Transform effect before
/// the piece's effects that makes copies or moves at random holds back, and the effects before
/// such a Transform effect among the piece's effects. The geometry effects then
/// leave the fills and strokes; their other effects stay. The paths keep to `max` together with
/// the rest of the art (`used`), and the swatches and patterns painted pieces name must be in
/// `doc`. `(seed, source, kept)`: the object's seed, the index in the object's appearance of the
/// fill or stroke the piece was made from, and the index among that item's effects of each effect
/// the piece kept, which a deferred live-effect plug-in is listed by.
fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), held: usize, max: Budget, used: &mut Budget, doc: Option<&Document>) {
let mut count = 0;
for_each_leaf(p, &mut |l| {
if let Some(item) = l.appearance.items.first() {
count = count.max(item.effects().len());
}
});
// The effects before a Transform effect among the piece's effects that makes copies or moves at
// random are held back from the Transform effects before it too.
let mut held = held;
for_each_leaf(p, &mut |l| {
if let Some(last) = l.appearance.items.first().and_then(|item| item.effects().iter().rposition(crate::raster::holds_back)) {
held = held.max(last);
}
});
for j in 0..count {
let Some(bounds) = p.geometric_bounds() else { break };
let from = held.min(j);
let mut holds = false;
for_each_leaf(p, &mut |leaf| {
let Some(item) = leaf.appearance.items.first().cloned() else { return };
let Some(e) = item.effects().get(j).filter(|e| e.visible && is_geometry(&e.id)).cloned() else { return };
holds |= crate::raster::holds_back(&e);
// The effects before this one as they were before it moved the path.
let was = item.effects().get(from..j).unwrap_or_default();
let Some((path, rule)) = leaf_geometry(leaf) else { return };
// What the other paths leave of the budget.
let before = Budget::of(&path);
@@ -1754,8 +2145,12 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
let (_, copies) = crate::distort::transform_map(bounds, &params, seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(bounds, &params, seed);
let (made, _) = transform_leaf(leaf, &path, map, copies, options, room);
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
*used = used.minus(before).plus(made);
if moved {
follow_piece(leaf, was, from, &e);
}
return;
}
let appearance = leaf.appearance.clone();
@@ -1772,7 +2167,11 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
carry.apply(&mut leaf.appearance);
}
set_geometry(leaf, out, rule);
follow_piece(leaf, was, from, &e);
});
if holds {
held = held.max(j);
}
}
for_each_leaf(p, &mut |leaf| {
for item in &mut leaf.appearance.items {
@@ -1781,6 +2180,53 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), m
});
}
/// The effects a Transform effect in a fill's or stroke's own list leaves as they were
/// ([`keep_listed`]): the list as it was before the Transform effect was applied, and which of its
/// indices keep their values. `None` for an object's own Transform effect.
type Kept<'a> = Option<(&'a [Effect], &'a dyn Fn(usize) -> bool)>;
/// Put back on the fills and strokes of each path under `p` the effect `kept`'s list holds at each
/// index it takes, in place of what a Transform effect in their own list scaled or moved with its
/// options ([`transform_leaf`]). The effects after the Transform effect apply to the art it made,
/// and with Transform Objects off the effects before it keep their values too. A piece's fills and
/// strokes share one list: a live-effect plug-in that paints what it returns gives each paint a copy
/// of the fill or stroke ([`vectorcraft_plugins::painted::items`]).
fn keep_listed(p: &mut Node, kept: Kept) {
let Some((was, keep)) = kept else { return };
for_each_leaf(p, &mut |leaf| {
for item in &mut leaf.appearance.items {
for (k, (e, old)) in item.effects_mut().iter_mut().zip(was).enumerate() {
if keep(k) {
e.clone_from(old);
}
}
}
});
}
/// Make the raster effects of each of `leaf`'s fills and strokes from index `from` on follow
/// Transform effect `t`, listed after them, once `t` has moved the leaf
/// ([`crate::raster::follow_one`]). The fills and strokes are copies of one fill or stroke (those a
/// painted plug-in returns, [`vectorcraft_plugins::painted::items`]), with the same effects. `was`
/// holds those effects of the first one as they were before `t` was applied: each one that
/// follows takes the value [`crate::raster::followed`] gives it, in place of what Scale Strokes &
/// Effects made of it, and the others keep theirs.
fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
let mut follow = was.to_vec();
if !crate::raster::follow_one(&mut follow, t) {
return;
}
for item in &mut leaf.appearance.items {
for (k, (new, old)) in follow.iter().zip(was).enumerate() {
if new != old
&& let Some(e) = item.effects_mut().get_mut(from + k)
{
*e = new.clone();
}
}
}
}
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
/// order. A group inside one of them is part of it.
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
+118 -16
View File
@@ -8,7 +8,9 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, L
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
use vectorcraft_three_d::{Edge, Revolve};
use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds};
use crate::solids::{
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
};
use crate::util::{flag, num, text};
use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params};
@@ -507,6 +509,60 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
Ok(out)
}
/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol
/// instances, blends and clipping groups already resolved), in document coordinates: with the
/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of
/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for
/// each member, about one shared axis. The swatches and patterns named by a live-effect plug-in
/// after a fill's or stroke's Revolve are looked up in `doc`.
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
let faces = |path: &PathData, b: Rect, options: Revolve| -> Result<Vec<PathData>, String> {
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect())
};
if is_container(n) {
let index = n
.appearance
.effects
.iter()
.position(|e| e.visible && is_revolve(&e.id))
.ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let mut shapes = members(n, "Revolve")?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?;
let options = shared_options(&shapes, fx_options(fx))?;
let mut out = vec![];
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
out.extend(faces(&s.path, b, options)?);
}
return Ok(out);
}
let (path, _) = object_profile(n, "Revolve")?;
let ctx = GeomContext::of(n);
if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) {
let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) };
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
if surface_item(&solid_paints(n)).is_none() {
return Err("the revolved object has no fill or stroke".into());
}
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
return faces(&path, b, fx_options(fx));
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id))
&& let Some(fx) = item.effects().get(index)
{
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
let surface = faces(&p, b, fx_options(fx))?;
out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
let index = n
@@ -538,7 +594,7 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if is_container(n) {
return group_art(n, expand);
}
let (path, _) = profile(n)?;
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
let mut children = vec![];
let mut copies = 0;
@@ -558,23 +614,23 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(surface));
// Later geometry acts on the projected art as a whole through container evaluation.
remaining = n
.appearance
.effects
.iter()
.enumerate()
.filter(|(i, e)| !is_revolve(&e.id) && (!is_geometry(&e.id) || *i > index))
.map(|(_, e)| e.clone())
.collect();
remaining = past_effect(&n.appearance.effects, index);
remaining.retain(|e| !is_revolve(&e.id));
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining.retain(|e| !is_geometry(&e.id));
remaining = crate::without_geometry(&remaining);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too. Each copy keeps its item beside it, which plug-in effects are told they sit
// on.
let originals: Vec<&AppearanceItem> = n.appearance.items.iter().filter(|i| crate::paints(i)).collect();
let mut items: Vec<AppearanceItem> = originals.iter().map(|i| (*i).clone()).collect();
crate::raster::follow_paints(&mut items, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in n.appearance.items.iter().filter(|i| crate::paints(i)) {
for (original, item) in originals.into_iter().zip(&items) {
if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) {
let fx = item.effects().get(index)?;
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
let mut art = object_surface(n, &p, fx, item, expand, &mut copies)?;
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
@@ -586,7 +642,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
}
children.push(Arc::new(art));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -835,8 +892,7 @@ fn group_art(n: &Node, expand: bool) -> Option<Node> {
// One shadow for every member's surface, behind them all.
let mut children = children;
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
@@ -969,6 +1025,52 @@ mod tests {
assert!(surface.children().unwrap().iter().all(|c| c.opacity == 1.0 && !has_revolve(c)));
}
#[test]
fn a_fill_without_the_revolve_keeps_the_even_odd_hole() {
use vectorcraft_geom::FillRule;
use vectorcraft_geom::hit::fill_contains;
// Two nested squares drawn in the same direction: only the even-odd rule leaves a hole.
let [outer, inner] = [(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
});
let flat = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.1, 0.3, 0.9))));
for id in [REVOLVE, CLASSIC_REVOLVE] {
let mut top = AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.8, 0.2, 0.1))));
top.effects_mut().push(crate::new_effect(id, &json!({})).unwrap());
let appearance = Appearance { items: vec![flat.clone(), top], ..Default::default() };
let members = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children: members, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.iter().chain(&inner.subpaths).cloned().collect());
let path = crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance);
for (n, shape) in [(compound, "compound path"), (path, "path")] {
for (art, how) in [(revolve_art(&n), "live"), (expand_revolve_art(&n), "expanded")] {
let what = format!("{id} on the top fill of a {shape}, {how}");
let art = art.unwrap_or_else(|| panic!("{what}"));
let children = art.children().unwrap();
let plain: Vec<usize> = (0..children.len())
.filter(|&i| children[i].appearance.items == [flat.clone()] && children[i].path_data().is_some())
.collect();
let [index] = plain[..] else { panic!("{what}: one flat child, got {plain:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the revolved art is drawn above");
}
}
}
}
#[test]
fn export_bakes_faces_with_unique_ids_and_no_revolve_effects() {
let mut d = Document::new(300.0, 300.0);
let mut n = profile_node();
+318 -36
View File
@@ -6,7 +6,7 @@ use serde_json::Value;
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View};
use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View};
#[cfg(test)]
use vectorcraft_doc::color::Color;
@@ -20,8 +20,20 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO
mod source;
pub(crate) use source::{resolve, resolve_for};
mod graphics;
pub use graphics::{
GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol,
rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic,
};
pub use graphics::{
MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol,
};
pub(crate) mod shadow;
pub(crate) mod wireframe;
pub use wireframe::three_d_wireframe_in;
pub const EXTRUDE: &str = "threeD.extrude";
pub const INFLATE: &str = "threeD.inflate";
pub const ROTATE: &str = "threeD.rotate";
@@ -67,6 +79,12 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
}
// A plane has only a front, so graphics on the back cap are dropped.
if to == ROTATE
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id()));
}
Value::Object(out)
}
@@ -209,6 +227,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
}
crate::lighting::validate(p)?;
shadow::validate(p)?;
graphics::validate(id, p)?;
if let Some(v) = p.get("bevel")
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
{
@@ -238,6 +257,9 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
/// `item`, whose shadow is cast by that item's solid alone.
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option<usize>) -> Result<(), String> {
validate_solid_params(id, p)?;
if let Some(doc) = doc {
graphics::validate_symbols(doc, p)?;
}
let label = label_of(id);
let n = &*source::resolve_for(doc, n, label, is_plane(id))?;
if is_container(n) {
@@ -431,6 +453,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> {
/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]).
pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) }
}
@@ -446,6 +469,7 @@ pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usi
/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a
/// blend and a clipping group take a 3D effect as groups do: on the object itself.
pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> {
graphics::validate(id, p)?;
match at {
Some(_) if is_container(n) || source::resolves(n) => {
Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into())
@@ -460,6 +484,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va
/// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does
/// not need to fit.
pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
graphics::validate(id, p)?;
if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) }
}
@@ -709,8 +734,8 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
/// blending mode, and those of a group it is in, apply to the surfaces of the members it holds
/// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it
/// off), to be drawn behind every surface of the object, and the surfaces.
fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(n, fx, shapes)?;
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
let art = surfaces_for(doc, n, fx, shapes)?;
// A shadow past the limits draws the source path, as a solid past them does; commands report
// the error ([`validate_solid_in`]).
let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? {
@@ -786,8 +811,141 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
/// its member's scopes and ink ([`cast_shadow`]).
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
/// [`art_for`] without the shadow: the solids' surfaces.
fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]):
/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees
/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were
/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which
/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every
/// call for one effect ([`graphics::face_art`]).
fn graphic_art(
doc: Option<&Document>,
id: NodeId,
(effect, p): (&str, &Value),
bounds: Rect,
caps: &[&Facet],
opacity: f32,
elements: &mut usize,
) -> Vec<(PlanarFace, Arc<Node>)> {
let list = graphics::mapped_graphics(p);
if list.is_empty() || !takes_graphics(effect) {
return vec![];
}
let view = view_options(p);
PlanarFace::ALL
.into_iter()
.filter_map(|face| {
let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect();
let map = if effect == ROTATE {
vectorcraft_three_d::plane_face_map(bounds, view)
} else {
vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face)
}?;
graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| {
art.opacity *= opacity;
(face, Arc::new(art))
})
})
.collect()
}
/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its
/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface
/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]).
struct Filled {
at: usize,
member: usize,
caps: Vec<Facet>,
opacity: f32,
blend: BlendMode,
masked: bool,
}
/// Does a surface in `paint` carry an opacity mask ([`surface`])?
fn masks_surface(paint: &Paint, colored: bool) -> bool {
colored && crate::lighting::opaque_paint(paint).1.is_some()
}
/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is
/// drawn right after (the last of those solids holding its face) and its face. Solids in a run
/// with the same opacity and blending mode share their graphics. With `per_member`
/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get
/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes.
/// All the groups share one limit on the path elements drawn: once it is reached, later groups
/// draw no graphics.
fn placed_graphics(
doc: Option<&Document>,
id: NodeId,
effect: (&str, &Value),
bounds: Rect,
filled: &[Filled],
per_member: bool,
) -> Vec<(usize, PlanarFace, Arc<Node>)> {
let mut groups: Vec<Vec<&Filled>> = vec![];
for f in filled {
// Solids whose fills or strokes differ in opacity or blending mode get graphics of their
// own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask
// gets its own too, which takes that mask ([`with_graphics`]). A solid joins only the
// group of the solid before it, so a graphic is never drawn past a solid painted between.
let joins = |first: &Filled| {
(!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked
};
match groups.last_mut().filter(|g| g.first().is_some_and(|first| joins(first))) {
Some(g) => g.push(f),
None => groups.push(vec![f]),
}
}
let mut out = vec![];
let mut elements = 0usize;
for group in groups {
let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect();
let opacity = group.first().map_or(1.0, |f| f.opacity);
let blend = group.first().map_or(BlendMode::Normal, |f| f.blend);
for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) {
if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) {
Arc::make_mut(&mut art).blend = blend;
out.push((f.at, face, art));
}
}
}
out
}
/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's
/// scopes, and for each face the end of a solid it is, when the viewer sees it.
type BuiltSurface<'s> = (Vec<Placed>, Node, &'s [Scope], Vec<Option<PlanarFace>>);
/// [`with_graphics`] of built surfaces, each drawn whole.
fn whole_surfaces<'s>(surfaces: Vec<BuiltSurface<'s>>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts)
}
/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each
/// right after its surface, with that surface's scopes and its opacity mask (a gradient's
/// transparency), so a graphic is hidden where its cap is.
fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc<Node>)>, arts: &[(usize, PlanarFace, Arc<Node>)]) -> Vec<(&'s [Scope], Arc<Node>)> {
let mut out = Vec::with_capacity(surfaces.len() + arts.len());
for (k, (scopes, s)) in surfaces.into_iter().enumerate() {
let mask = s.extras().mask.clone();
out.push((scopes, s));
out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| {
let mut art = art.clone();
if let Some(mask) = &mask {
Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone());
}
(scopes, art)
}));
}
out
}
/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go.
fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
f.iter().filter(|f| f.end.is_some() && !f.away)
}
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -795,11 +953,14 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let masks = has_masks(shapes);
// The paint copies of every solid together: past the allowance the source path is drawn.
let mut paint_bytes = 0usize;
// The caps are copied only when the effect has graphics to draw on them.
let graphics_on = !classic && takes_graphics(&fx.id) && !mapped_graphics(&p).is_empty();
if is_plane(&fx.id) {
// Every part turns about the centre of the object's own bounds (a group's members about
// the centre of theirs), so they stay together.
let mut out = vec![];
for s in shapes {
let mut filled = vec![];
for (member, s) in shapes.iter().enumerate() {
for item in &s.items {
let (paint, opacity, blend) = paint_of(item, s.opacity);
let (area, rule) = region(&s.path, s.rule, item);
@@ -807,10 +968,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
return None;
}
if graphics_on {
let caps: Vec<Facet> = seen_ends(&f).cloned().collect();
if !caps.is_empty() {
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
}
}
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
out.push((s.scopes.as_slice(), Arc::new(art)));
}
}
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
let out = with_graphics(out, &arts);
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
}
let (parts, bounds) = solid_parts(shapes, b);
@@ -842,36 +1011,56 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
let (_, opacity, blend) = paint_of(item, *member);
opacity >= 1.0 && blend == BlendMode::Normal
});
let surfaces: Vec<(Vec<Placed>, Node, &[Scope])> = solids
let arts = if !graphics_on {
vec![]
} else {
let filled: Vec<Filled> = solids
.iter()
.enumerate()
.filter_map(|(at, (item, member, _, f, shape))| {
let caps: Vec<Facet> = seen_ends(f).cloned().collect();
let (paint, opacity, blend) = paint_of(item, *member);
let masked = masks_surface(&paint, colored);
(!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked })
})
.collect();
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
};
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
.map(|(item, member, scopes, f, shape)| {
let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed));
let paints = Paints::of(item, closed);
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
(depths, art, scopes)
(depths, art, scopes, ends)
})
.collect();
if masks {
return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect()));
return Some(masked(n.id, whole_surfaces(surfaces, &arts)));
}
// One order takes a plain group of faces from each solid, one face for each facet. With
// colored lights a surface can instead be one clipped composite of all its facets. A composite
// has no faces to order, so when any surface is one, every surface of the solid, masked ones
// included, draws whole in member order.
let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
if !opaque || !plain {
return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect());
}
let plain =
surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len()));
// A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs
// ([`in_runs`]), and each run carries the mask.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect();
let (mut placed, mut faces) = (vec![], vec![]);
for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() {
// ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole,
// each graphic right after its surface.
let masks: Vec<Option<Box<OpacityMask>>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect();
let masked_faces = masks.iter().any(Option::is_some);
if !opaque || !plain || (masked_faces && !arts.is_empty()) {
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
}
let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]);
for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() {
if let NodeKind::Group { children, .. } = s.kind {
placed.extend(depths);
faces.extend(children.into_iter().map(|face| Some((surface, face))));
ends.extend(e);
}
}
let sealed = match fx.id.as_str() {
@@ -880,8 +1069,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Nod
_ => extrude_options(&p).cap,
};
let order = draw_order(&placed, sealed);
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) };
if masked_faces {
let faces: Vec<(usize, Arc<Node>)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect();
return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]);
}
// Each face's graphics go right after the last of the faces they are drawn on.
let last: Vec<Option<usize>> =
arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect();
let mut children = Vec::with_capacity(order.len() + arts.len());
for (at, k) in order.into_iter().enumerate() {
children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face));
children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone()));
}
Some(vec![Arc::new(Node::group(n.id, children))])
}
@@ -966,7 +1165,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
let n = &*resolve(doc, n, "").ok()?;
if is_container(n) {
return group_solid_art(n);
return group_solid_art(doc, n);
}
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
@@ -975,26 +1174,23 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
let remaining: Vec<Effect>;
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?;
children.extend(shadow.into_iter().chain(surfaces));
// Later geometry effects act on the projected art as a whole.
remaining = n
.appearance
.effects
.iter()
.enumerate()
.filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index))
.map(|(_, e)| e.clone())
.collect();
remaining = past_effect(&n.appearance.effects, index);
} else {
let path = geometry(&path, &n.appearance.effects, &ctx);
remaining = n.appearance.effects.iter().filter(|e| !is_geometry(&e.id)).cloned().collect();
remaining = crate::without_geometry(&n.appearance.effects);
// The object's Transform effects, applied to the path above, transform the items' raster
// effects too.
let mut paints = paints;
crate::raster::follow_paints(&mut paints, &n.appearance.effects);
// Every item's shadow goes behind every item's art.
let mut shadows = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item));
let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
let later: Vec<Effect> = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect();
let with_later = |mut art: Arc<Node>| {
Arc::make_mut(&mut art).appearance.effects = later.clone();
@@ -1003,7 +1199,8 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
shadows.extend(shadow.into_iter().map(with_later));
children.extend(surfaces.into_iter().map(with_later));
} else {
children.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: vec![item.clone()], ..Default::default() })));
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
children.push(Arc::new(crate::group::shape_node(n.id, path.clone(), rule, flat)));
}
}
children.splice(0..0, shadows);
@@ -1018,20 +1215,105 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// geometry effects before it reshape the members, those after it bend the result as a whole; the
/// group's own fills and strokes are not drawn. `None` when the effect is only on one of the
/// group's own fills or strokes, or when its members can't become solids.
fn group_solid_art(n: &Node) -> Option<Node> {
fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
let (index, fx) = solid(&n.appearance.effects)?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
let (shadow, surfaces) = art_for(n, fx, &shapes)?;
let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?;
let children = shadow.into_iter().chain(surfaces).collect();
let remaining =
n.appearance.effects.iter().enumerate().filter(|(i, e)| *i != index && (!is_geometry(&e.id) || *i > index)).map(|(_, e)| e.clone()).collect();
let remaining = past_effect(&n.appearance.effects, index);
let mut art = n.clone();
art.kind = NodeKind::Group { children, clip: false };
art.appearance = Appearance { effects: remaining, ..Default::default() }.into();
Some(art)
}
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
/// Rotate there, or its art can't be built.
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &solid)
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel or Rotate.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e)))
}
/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the
/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or
/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the
/// art before it.
pub fn graphics_reshaped_after(n: &Node, item: Option<usize>, index: usize) -> bool {
n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry)
}
/// Finds a 3D effect in a list of effects, with its index there.
type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p;
/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`.
fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'_>) -> Option<graphics::GraphicFrame> {
let n = &*resolve(doc, n, "").ok()?;
let (fx, shapes) = if is_container(n) {
let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?;
let mut shapes = members(n, "").ok()?;
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
(fx, shapes)
} else {
let (path, rule) = profile(n)?;
let ctx = GeomContext::of(n);
match item {
None => {
let (index, fx) = pick(&n.appearance.effects)?;
let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx);
(fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }])
}
Some(k) => {
let it = n.appearance.items.get(k)?;
let (index, fx) = pick(it.effects())?;
let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it));
(fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }])
}
}
};
if !takes_graphics(&fx.id) {
return None;
}
let p = crate::merged_params(&fx.id, &fx.params);
let b = union_bounds(&shapes)?;
let view = view_options(&p);
if fx.id == ROTATE {
let plane = vectorcraft_three_d::plane_face_map(b, view);
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (_, bounds) = solid_parts(&shapes, b);
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub fn graphic_bounds(doc: &Document, name: &str) -> Option<Rect> {
graphics::art_bounds(doc, name)
}
/// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the
/// art it projects. Each raster effect before it follows the Transform effects among those
/// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at
/// random ([`crate::raster::holds_back`]); the effects after it stay as they are.
pub(crate) fn past_effect(effects: &[Effect], index: usize) -> Vec<Effect> {
let (before, after) = effects.split_at(index.min(effects.len()));
let after = after.get(1..).unwrap_or_default();
let kept: Vec<Effect> = if after.iter().any(crate::raster::holds_back) {
before.iter().filter(|e| !is_geometry(&e.id)).cloned().collect()
} else {
crate::without_geometry(before)
};
kept.into_iter().chain(after.iter().cloned()).collect()
}
/// One solid of a 3D object as a mesh, with the color it is painted.
#[derive(Clone, Debug, PartialEq)]
pub struct SolidMesh {
+631
View File
@@ -0,0 +1,631 @@
//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials ›
//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a
//! plane, turned, foreshortened and shaded with that face and clipped to it.
//!
//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale,
//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of
//! the object's bounds in the face's own plane (points, x to the right and y down as the face is
//! seen from the front of that face), its size as a share of the symbol's own, and its turn
//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from
//! behind, so the graphic reads the right way round there.
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
pub const GRAPHICS: &str = "graphics";
/// The most graphics one 3D effect maps.
pub const MAX_GRAPHICS: usize = 64;
/// The most fills and stroke outlines the art of one symbol draws as a graphic.
const MAX_PIECES: usize = 4096;
/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts
/// their curves.
const MAX_ELEMENTS: usize = 400_000;
/// The pieces each curve of a graphic is cut into under a perspective map, which bends it.
const PERSPECTIVE_PIECES: usize = 8;
/// How deep symbol instances in a graphic's art may nest.
const MAX_NESTING: usize = 8;
/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it
/// places: as deep as an object may be drawn.
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The size range of a graphic, as a percentage of its symbol's own size.
pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0);
/// How far a graphic's center may be from the center of its object, in points.
pub const MAX_OFFSET: f64 = 1e6;
/// One graphic mapped onto a face of a 3D object.
#[derive(Clone, Debug, PartialEq)]
pub struct MappedGraphic {
pub symbol: String,
pub face: PlanarFace,
pub x: f64,
pub y: f64,
/// Percent of the symbol's own size.
pub scale: f64,
/// Degrees, counterclockwise.
pub rotation: f64,
}
impl MappedGraphic {
pub fn to_value(&self) -> Value {
json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation})
}
/// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets
/// and the rotation to 0 and the scale to 100.
pub fn from_value(v: &Value) -> Result<Self, String> {
let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) };
if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) {
return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`"));
}
let symbol = match m.get("symbol") {
Some(Value::String(s)) if !s.trim().is_empty() => s.clone(),
_ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")),
};
let face = match m.get("face") {
None => PlanarFace::Front,
Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?,
};
let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result<f64, String> {
match m.get(key) {
None => Ok(default),
Some(v) => v
.as_f64()
.filter(|n| n.is_finite() && (lo..=hi).contains(n))
.ok_or_else(|| format!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")),
}
};
Ok(Self {
symbol,
face,
x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?,
scale: number("scale", 100.0, SCALE_RANGE)?,
rotation: number("rotation", 0.0, (-360.0, 360.0))?,
})
}
/// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an
/// object whose bounds have center `center`.
fn placement(&self, art: Rect, center: Point) -> Affine {
let place = Affine::translate((center.x + self.x, center.y + self.y))
* Affine::rotate(-self.rotation.to_radians())
* Affine::scale(self.scale / 100.0)
* Affine::translate(-art.center().to_vec2());
match self.face {
PlanarFace::Front => place,
// Seen from behind, the back's right is the front's left.
PlanarFace::Back => {
Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place
}
}
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two
/// object types of the 3D and Materials panel with planar faces.
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
/// anything; commands check every entry with [`validate`]).
pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
match p.get(GRAPHICS) {
Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(),
_ => vec![],
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take
/// graphics, and a plane has only a front.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
let list = match p.get(GRAPHICS) {
None => return Ok(()),
Some(Value::Array(list)) => list,
Some(_) => return Err(format!("`{GRAPHICS}` must be an array")),
};
if list.is_empty() {
return Ok(());
}
if !takes_graphics(id) {
return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into());
}
if list.len() > MAX_GRAPHICS {
return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics"));
}
for v in list {
let g = MappedGraphic::from_value(v)?;
if id == super::ROTATE && g.face == PlanarFace::Back {
return Err("A plane has one face: map its graphics onto the front".into());
}
}
Ok(())
}
/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the
/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol
/// was deleted may stay.
pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option<String> {
let kept = old.map(mapped_graphics).unwrap_or_default();
mapped_graphics(p)
.into_iter()
.map(|g| g.symbol)
.find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name))
}
/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol
/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as
/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once.
pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> {
let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 };
let mut elements = 0usize;
for g in mapped_graphics(p) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
let pieces = pieces_of(doc, symbol)?;
elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum());
if elements > MAX_ELEMENTS {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
}
Ok(())
}
/// The path elements `path` draws when each curve draws `curve` elements, before curves near the
/// eye are split further: one for each straight line, move and close.
fn drawn_elements(path: &PathData, curve: usize) -> usize {
let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::<usize>();
path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum()
}
/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline.
struct Piece {
path: PathData,
rule: FillRule,
paint: Paint,
opacity: f32,
blend: BlendMode,
}
/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of
/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol
/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping
/// groups draw their art unclipped.
fn pieces_of(doc: &Document, symbol: &Symbol) -> Result<Vec<Piece>, String> {
fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec<Piece>) -> Result<(), String> {
if !n.visible || n.is_guide() {
return Ok(());
}
if level > MAX_LEVELS {
return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art"));
}
let opacity = outer * n.opacity;
let shape = match &n.kind {
NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)),
NodeKind::Compound { children, rule } => {
Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule))
}
NodeKind::Text(_) => {
if let Some(mut outlined) = crate::outline_text(n) {
// The outlines take the type's place, with its opacity.
outlined.visible = true;
outlined.opacity = n.opacity;
walk(doc, &outlined, outer, xf, (depth, level + 1), out)?;
}
None
}
NodeKind::SymbolInstance { symbol, xf: at } => {
if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) {
if depth >= MAX_NESTING {
return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art"));
}
// The instance shows its own changes to a dynamic symbol's art, and a symbol
// with 9-slice guides is placed through them, as the canvas draws it. The
// pieces are not clipped, so paths that cross a guide are cut at it.
let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n);
if doc.symbol_slice_map(symbol, *at).is_some() {
let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else {
return Err("A graphic's art holds too many objects: simplify the symbol's art".into());
};
walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?;
} else {
walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?;
}
}
None
}
_ => {
for c in n.children().into_iter().flatten() {
walk(doc, c, opacity, xf, (depth, level + 1), out)?;
}
None
}
};
let Some((path, rule)) = shape else { return Ok(()) };
// Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the
// symbol's square, so a stroke is outlined after the art takes its size.
let path = path.transformed(xf);
for item in n.appearance.items.iter().filter(|i| i.visible()) {
let (area, rule, paint, item_opacity, blend) = match item {
AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend),
AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => {
(crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend)
}
AppearanceItem::Stroke(_) => continue,
};
if matches!(paint, Paint::None) || area.bounds().is_none() {
continue;
}
if out.len() >= MAX_PIECES {
return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art"));
}
// A placed gradient or pattern takes the same size and place as its path.
let mut paint = paint;
match &mut paint {
Paint::Gradient(g) => g.transform(xf),
Paint::Pattern { xf: placed, .. } => *placed = xf * *placed,
Paint::None | Paint::Solid { .. } => {}
}
out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend });
}
Ok(())
}
let mut out = vec![];
walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?;
Ok(out)
}
/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into
/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight
/// under a perspective). Fails when part of it has no page point, or when it takes more than `room`
/// elements.
fn map_path(path: &PathData, map: &FaceMap, affine: Option<Affine>, room: usize) -> Result<BezPath, NotMapped> {
let bp = path.to_bezpath();
if let Some(a) = affine {
return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) };
}
let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind);
let mut out = BezPath::new();
let mut at = Point::ZERO;
for el in bp.elements() {
if out.elements().len() > room {
return Err(NotMapped::Full);
}
match *el {
PathEl::MoveTo(p) => {
out.move_to(to(p)?);
at = p;
}
PathEl::LineTo(p) => {
out.line_to(to(p)?);
at = p;
}
PathEl::QuadTo(c, p) => {
cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::CurveTo(c1, c2, p) => {
cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?;
at = p;
}
PathEl::ClosePath => out.close_path(),
}
}
if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) }
}
/// Why [`map_path`] drew nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum NotMapped {
/// Part of the path has no page point: it is at or behind the eye.
Behind,
/// The path takes more elements than it has room for.
Full,
}
/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of
/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a
/// piece has no page point.
fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> {
for k in 0..PERSPECTIVE_PIECES {
let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64);
let s = c.subsegment(t0..t1);
if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) {
return None;
}
piece_to(out, s, map, MAX_SPLITS)?;
}
Some(())
}
/// How many times [`piece_to`] halves a piece whose control points are behind the eye.
const MAX_SPLITS: usize = 4;
/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of
/// each half have page points, at most `splits` times, and drawn straight past that.
fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> {
let end = map.to_page(s.p3)?;
match (map.to_page(s.p1), map.to_page(s.p2)) {
(Some(c1), Some(c2)) => out.curve_to(c1, c2, end),
_ if splits == 0 => out.line_to(end),
_ => {
let (a, b) = s.subdivide();
piece_to(out, a, map, splits - 1)?;
piece_to(out, b, map, splits - 1)?;
}
}
Some(())
}
/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the
/// object's solids that the viewer sees) through `map`, for an object whose bounds have
/// center `center`: one clipping group of every such graphic, shaded with the first cap's light.
/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol
/// `doc` does not have draws nothing. `elements` counts the path elements
/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by
/// every call for one effect. `None` when there is nothing to draw or that count passes
/// [`MAX_ELEMENTS`].
pub(super) fn face_art(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
(face, map): (PlanarFace, &FaceMap),
center: Point,
caps: &[&Facet],
elements: &mut usize,
) -> Option<Node> {
let doc = doc?;
let light = caps.first()?.illumination;
let affine = map.local_affine(center).filter(|_| map.is_affine());
let mut children = vec![];
for g in graphics.iter().filter(|g| g.face == face) {
let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue };
// A symbol past the limits is left out; the other graphics still draw.
let Ok(pieces) = pieces_of(doc, symbol) else { continue };
let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue };
let place = g.placement(bounds, center);
// Gradients follow the face's map as it is near the graphic's center.
let middle = place * bounds.center();
// When the center is at or behind the eye, they follow it near the middle of the part that
// is in front; a graphic with no part in front is left out.
let local = map.local_affine(middle).or_else(|| {
let part = map.mapped_part(place.transform_rect_bbox(bounds))?;
let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2());
map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64))
});
let Some(local) = local else { continue };
let gradient_map = local * place;
for piece in pieces {
let placed = piece.path.transformed(place);
// Each anchor draws at least one element. A perspective cuts curves into more, and
// straight lines stay one each: the path may take what is left of the limit, and is
// counted as it is drawn. Past the limit, the face draws nothing.
let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum();
let before = *elements;
if before.saturating_add(least) > MAX_ELEMENTS {
return None;
}
let room = MAX_ELEMENTS - before;
let mut rule = piece.rule;
let mapped = match map_path(&placed, map, affine, room) {
Err(NotMapped::Behind) => {
// Part of it is at or behind the eye: the part in front is drawn.
let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue };
let Some(&first) = part.first() else { continue };
let mut front = BezPath::new();
front.move_to(first);
part.iter().skip(1).for_each(|p| front.line_to(*p));
front.close_path();
let cut = vectorcraft_pathops::boolean(
&placed,
piece.rule,
&PathData::from_bezpath(&front),
FillRule::NonZero,
vectorcraft_pathops::BoolOp::Intersect,
);
rule = FillRule::NonZero;
map_path(&cut, map, affine, room)
}
done => done,
};
let mapped = match mapped {
Ok(mapped) => mapped,
Err(NotMapped::Full) => return None,
Err(NotMapped::Behind) => continue,
};
*elements = before.saturating_add(mapped.elements().len());
let mut paint = piece.paint;
vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light));
// A pattern's tiles follow the graphic onto the face, as its gradients do below.
if let Paint::Pattern { xf, .. } = &mut paint {
*xf = gradient_map * *xf;
}
let mut fill = FillLayer::new(paint);
fill.opacity = piece.opacity;
fill.blend = piece.blend;
let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() };
appearance.transform_gradients(gradient_map);
let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance);
if let NodeKind::Path { rule: r, .. } = &mut node.kind {
*r = rule;
}
children.push(Arc::new(node));
}
}
if children.is_empty() {
return None;
}
let mut clip = BezPath::new();
for cap in caps {
// A cap's holes are contours of the same path wound against its outline, so turning the
// whole path keeps them holes under the nonzero rule.
let mut outline = cap.path().to_bezpath();
if outline.area() < 0.0 {
outline = outline.reverse_subpaths();
}
clip.extend(outline.iter());
}
let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true }))
}
/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates.
pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
let symbol = doc.symbols.iter().find(|s| s.name == name)?;
pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b))
}
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center) and the maps of its front and back faces, when it has them.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
PlanarFace::Back => self.back.as_ref(),
}
}
/// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a
/// graphic's center.
fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point {
let c = self.bounds.center();
match face {
PlanarFace::Front => Point::new(c.x + x, c.y + y),
PlanarFace::Back => Point::new(c.x - x, c.y + y),
}
}
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = self.map(face)?.to_art(page)?;
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
/// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most
/// 100: where a newly mapped graphic starts.
pub fn fitting_scale(&self, art: Rect) -> f64 {
let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9));
(fit * 100.0).clamp(SCALE_RANGE.0, 100.0)
}
}
/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes').
pub fn graphic_symbols(n: &Node) -> Vec<String> {
appearance_graphic_symbols(&n.appearance)
}
/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a
/// graphic style's appearance.
pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec<String> {
std::iter::once(&appearance.effects)
.chain(appearance.items.iter().map(AppearanceItem::effects))
.flatten()
.filter(|e| takes_graphics(&e.id))
.flat_map(|e| mapped_graphics(&e.params))
.map(|g| g.symbol)
.collect()
}
/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns
/// whether any changed.
pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool {
// Checked first, so an appearance that names another symbol is not copied.
graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to)
}
/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance.
pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool {
if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) {
return false;
}
let mut lists: Vec<&mut Vec<vectorcraft_doc::Effect>> = vec![];
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
lists.push(effects);
lists.extend(items.iter_mut().map(AppearanceItem::effects_mut));
for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) {
if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) {
for g in list.iter_mut() {
if g.get("symbol").and_then(Value::as_str) == Some(from) {
g["symbol"] = json!(to);
}
}
}
}
true
}
/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`?
pub fn names_graphic_symbol(n: &Node, from: &str) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from));
found
}
/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included.
/// Only the parts that name `from` are copied. Returns whether any changed.
pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool {
let names = names_graphic_symbol;
let mut changed = rename_graphic_symbol(n, from, to);
if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names(c, from)) {
changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to);
}
}
changed
}
/// `p` with graphic `g` added at the end of its list.
pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value {
let mut out = p.as_object().cloned().unwrap_or_else(Map::new);
let mut list = match out.get(GRAPHICS) {
Some(Value::Array(list)) => list.clone(),
_ => vec![],
};
list.push(g.to_value());
out.insert(GRAPHICS.into(), Value::Array(list));
Value::Object(out)
}
#[cfg(test)]
#[path = "tests_graphics.rs"]
mod tests;
+76 -13
View File
@@ -8,7 +8,7 @@ use std::borrow::Cow;
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_pathops as po;
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
@@ -24,6 +24,19 @@ const MAX_DEPTH: usize = 64;
/// many steps.
pub(super) const MAX_WORK: usize = 1 << 18;
/// The most times resolving one 3D effect's art may cut an image's frame to a clipping path to
/// learn whether the clip shows any of it ([`Resolver::hidden`]).
pub(super) const MAX_IMAGE_CUTS: usize = 1024;
/// The area, in square points, under which what a clip shows of an image's frame counts as nothing:
/// the sliver left where the frame only touches the clipping path.
const SHOWN_AREA: f64 = 1e-9;
/// The precision an image's frame is cut to a clipping path with: the cut drops pieces narrower
/// than this, so it is far below [`po::DEFAULT_PRECISION`], and a strip of the image much
/// narrower than a hundredth of a point still counts as shown.
const CUT_PRECISION: f64 = 1e-6;
/// The error for an image a 3D effect is asked to build from.
pub(crate) fn image_refusal(label: &str) -> String {
format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.")
@@ -66,7 +79,7 @@ pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str,
if !needs(n) {
return Ok(Cow::Borrowed(n));
}
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None };
let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, cuts: 0, shown: None };
let children = r.content(n, 0);
#[cfg(test)]
WORK.with(|w| w.set(r.work));
@@ -90,8 +103,18 @@ struct Resolver<'a> {
leaves: usize,
/// The objects visited or made so far, counted against [`MAX_WORK`].
work: usize,
/// Inside clipping groups, the box of what their clipping paths show together.
shown: Option<Rect>,
/// The image frames cut to clipping paths so far, counted against [`MAX_IMAGE_CUTS`].
cuts: usize,
/// Inside clipping groups, what their clipping paths show together.
shown: Option<Shown>,
}
/// The clipping paths around the art being listed, outermost first, with the box of what they
/// show together.
#[derive(Clone)]
struct Shown {
bounds: Rect,
clips: Vec<Arc<(PathData, FillRule)>>,
}
impl Resolver<'_> {
@@ -111,15 +134,52 @@ impl Resolver<'_> {
/// `f` run on the art of `c`. The effects of an object or group can move its art into a clip,
/// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]).
fn inside<T>(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result<T, String>) -> Result<T, String> {
let outer = self.shown;
if has_effects(c) {
self.shown = None;
if !has_effects(c) {
return f(self);
}
let outer = self.shown.take();
let out = f(self);
self.shown = outer;
out
}
/// Does the plain image `c` lie wholly outside what the clips around it show together, each
/// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places
/// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts
/// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
fn hidden(&mut self, c: &Node) -> Result<bool, String> {
let Some(shown) = &self.shown else { return Ok(false) };
let NodeKind::Image(im) = &c.kind else { return Ok(false) };
let Some(b) = c.visual_bounds() else { return Ok(true) };
if b.intersect(shown.bounds).area() <= 0.0 {
return Ok(true);
}
let (w, h) = (f64::from(im.width), f64::from(im.height));
let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y));
if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return Err(image_refusal(self.label));
}
let clips = shown.clips.clone();
let mut left = PathData::single(SubPath::polyline(&corners, true));
for clip in clips {
let Some(here) = clip.0.bounds() else { return Ok(true) };
if left.bounds().is_none_or(|l| l.intersect(here).area() <= 0.0) {
return Ok(true);
}
self.cuts += 1;
if self.cuts > MAX_IMAGE_CUTS {
return Err(self.too_much_work());
}
self.spend(1)?;
left =
po::try_boolean(&left, FillRule::NonZero, &clip.0, clip.1, po::BoolOp::Intersect, CUT_PRECISION).map_err(|_| self.too_complex())?;
if left.subpaths.iter().all(|s| s.area().abs() <= SHOWN_AREA) {
return Ok(true);
}
}
Ok(false)
}
/// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one,
/// shows, as the members of a plain group.
fn content(&mut self, n: &Node, depth: usize) -> Result<Vec<Arc<Node>>, String> {
@@ -162,11 +222,15 @@ impl Resolver<'_> {
if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) {
return Err(self.too_deep());
}
let clip = clip_area(first);
// An image wholly outside every clip around it shows nothing and is left out.
let outer = self.shown;
let clip = Arc::new(clip_area(first));
// An image wholly outside what the clips around it show together draws nothing and
// is left out.
let here = clip.0.bounds().unwrap_or(Rect::ZERO);
self.shown = Some(outer.map_or(here, |o| o.intersect(here)));
let outer = self.shown.take();
let mut inner_shown = outer.clone().unwrap_or(Shown { bounds: here, clips: vec![] });
inner_shown.bounds = inner_shown.bounds.intersect(here);
inner_shown.clips.push(clip.clone());
self.shown = Some(inner_shown);
let listed = self.list(rest, depth + 1);
self.shown = outer;
let (inner, _) = listed?;
@@ -198,8 +262,7 @@ impl Resolver<'_> {
// Only an image with no effects or fills and strokes of its own is measured by its
// frame; any other one may draw inside the clip.
let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible());
let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0));
if hidden {
if plain && self.hidden(c)? {
changed = true;
continue;
}
+62
View File
@@ -457,6 +457,68 @@ fn transparency_stays_on_the_whole_surface_and_items_take_their_own_effect() {
assert!(matches!(surfaces[1].kind, NodeKind::Path { .. }));
}
/// Two nested squares drawn in the same direction, so only the even-odd rule leaves a hole.
fn nested_squares() -> [PathData; 2] {
[(100.0, 200.0), (130.0, 170.0)].map(|(lo, hi)| {
let mut b = BezPath::new();
b.move_to((lo, lo));
b.line_to((hi, lo));
b.line_to((hi, hi));
b.line_to((lo, hi));
b.close_path();
PathData::from_bezpath(&b)
})
}
/// The nested squares as an even-odd compound path and as one even-odd path, painted by `items`.
fn even_odd_shapes(items: Vec<AppearanceItem>) -> [Node; 2] {
let [outer, inner] = nested_squares();
let appearance = Appearance { items, ..Default::default() };
let children = vec![
Arc::new(Node::path(NodeId(2), outer.clone(), Appearance::default())),
Arc::new(Node::path(NodeId(3), inner.clone(), Appearance::default())),
];
let mut compound = Node::new(NodeId(1), NodeKind::Compound { children, rule: FillRule::EvenOdd });
compound.appearance = appearance.clone().into();
let both = PathData::new(outer.subpaths.into_iter().chain(inner.subpaths).collect());
[compound, crate::group::shape_node(NodeId(1), both, FillRule::EvenOdd, appearance)]
}
/// Check that `art` draws `item` as one flat child: an even-odd path with a hole in the middle,
/// below the 3D art after it.
fn assert_flat_item_keeps_the_hole(art: &Node, item: &AppearanceItem, what: &str) {
use vectorcraft_geom::hit::fill_contains;
let children = art.children().unwrap();
let flat: Vec<usize> =
(0..children.len()).filter(|&i| children[i].appearance.items == [item.clone()] && children[i].path_data().is_some()).collect();
let [index] = flat[..] else { panic!("{what}: one flat child, got {flat:?}") };
let NodeKind::Path { path, rule, .. } = &children[index].kind else { panic!("{what}: a path") };
assert_eq!(*rule, FillRule::EvenOdd, "{what}");
let bez = path.to_bezpath();
assert!(fill_contains(&bez, *rule, Point::new(110.0, 150.0)), "{what}: the ring is filled");
assert!(!fill_contains(&bez, *rule, Point::new(150.0, 150.0)), "{what}: the hole stays open");
assert!(index + 1 < children.len(), "{what}: the 3D art is drawn above");
}
#[test]
fn a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole() {
let red = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(RED)));
let blue = AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(BLUE)));
let stroke = AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 4.0));
for id in SOLIDS {
// The top fill and then the top stroke take the effect; the fill below stays flat.
for (top, on) in [(&red, "fill"), (&stroke, "stroke")] {
let mut lifted = top.clone();
lifted.effects_mut().push(fx(id, json!({})));
for (n, shape) in even_odd_shapes(vec![blue.clone(), lifted]).into_iter().zip(["compound path", "path"]) {
let what = format!("{id} on the top {on} of a {shape}");
let art = solid_art(&n).unwrap_or_else(|| panic!("{what}"));
assert_flat_item_keeps_the_hole(&art, &blue, &what);
}
}
}
}
#[test]
fn export_and_expand_bake_faces_with_their_own_ids() {
for id in SOLIDS {
+694
View File
@@ -0,0 +1,694 @@
use serde_json::json;
use vectorcraft_doc::color::Color;
use vectorcraft_doc::{StrokeLayer, Symbol};
use vectorcraft_geom::shapes;
use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params};
use super::*;
fn red() -> Color {
Color::rgb(1.0, 0.0, 0.0)
}
fn square(id: u64, r: Rect, paint: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0))
}
/// A document with symbol "Mark": a red 10 × 10 square.
fn document() -> Document {
let mut d = Document::new(1000.0, 1000.0);
d.symbols.push(Symbol {
dynamic: false,
name: "Mark".into(),
art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))),
});
d
}
/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view
/// straight on.
fn object(id: &str, params: Value) -> Node {
let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false});
if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) {
p.extend(extra.clone());
}
let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
n.appearance.effects.push(crate::new_effect(id, &p).unwrap());
n
}
/// The graphics clip groups in `art`, in drawing order: each one's mapped paths.
fn graphics_in(art: &Node) -> Vec<Vec<(PathData, Paint)>> {
let mut out = vec![];
art.walk(&mut |n| {
if let NodeKind::Group { children, clip: true } = &n.kind
&& let [_, inner] = children.as_slice()
&& let NodeKind::Group { children: paths, clip: false } = &inner.kind
{
let paths: Vec<(PathData, Paint)> = paths
.iter()
.filter_map(|p| {
let fill = p.appearance.items.iter().find_map(|i| match i {
AppearanceItem::Fill(f) => Some(f.paint.clone()),
AppearanceItem::Stroke(_) => None,
})?;
Some((p.path_data()?.clone(), fill))
})
.collect();
if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) {
out.push(paths);
}
}
});
out
}
fn bounds_of(paths: &[(PathData, Paint)]) -> Rect {
paths.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap()
}
fn close(a: Rect, b: Rect) -> bool {
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6)
}
#[test]
fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() {
let d = document();
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let found = graphics_in(&art);
assert_eq!(found.len(), 1);
// Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50).
assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0]));
// Turned 45°, the square's corners reach out to its half diagonal.
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]}));
let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]);
assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6);
}
#[test]
fn without_the_document_or_its_symbol_nothing_is_drawn() {
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]}));
let art = solid_art_in(None, &n).unwrap();
assert!(graphics_in(&art).is_empty());
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]}));
assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty());
// Without graphics, the art is the same as before they existed.
let plain = object(EXTRUDE, json!({}));
assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain));
}
#[test]
fn the_graphic_is_shaded_with_its_face() {
let d = document();
let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let c = found[0][0].1.color().unwrap().to_rgb();
assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}");
}
#[test]
fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() {
let d = document();
let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") };
let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") };
let last = faces.last().unwrap();
assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap");
let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() };
let clip = parts[0].path_data().unwrap().bounds().unwrap();
let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap();
assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}");
}
#[test]
fn the_back_cap_reads_the_right_way_round_from_behind() {
let d = document();
let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]});
let n = object(EXTRUDE, behind);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
assert_eq!(found.len(), 1);
let b = bounds_of(&found[0]);
// Seen from behind, x runs to the right on the page too.
assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}");
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap();
let (at, visible) = frame.handle(&g).unwrap();
assert!(visible && (at.x - 70.0).abs() < 1e-6);
let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap();
assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6);
// From the front the back cap is hidden, and so is its graphic.
let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty());
}
#[test]
fn a_perspective_foreshortens_the_graphic_with_its_face() {
let d = document();
let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]});
let n = object(EXTRUDE, params);
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
// The corners of the 40 × 40 square centered on the object land where the face's map takes them.
let path = &found[0][0].0;
let corners: Vec<Point> = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into();
for c in corners {
let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min);
assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic");
}
}
#[test]
fn a_graphic_behind_the_eye_leaves_the_others_drawn() {
let d = document();
let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
let n = object(EXTRUDE, view.clone());
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let map = frame.map(PlanarFace::Front).unwrap();
let c = frame.bounds.center();
// An offset whose point of the front's plane is at or behind the eye.
let y = [1.0, -1.0]
.into_iter()
.flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0)))
.find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none())
.expect("an offset behind the eye");
let mut params = view;
params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the graphic that projects is still drawn");
// A graphic centered there but large enough to reach over the cap draws the part in front.
let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0});
params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]);
let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap());
assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})");
assert!(!found[0].is_empty());
}
#[test]
fn the_graphic_takes_the_opacity_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
assert_eq!(opacities, vec![0.25], "{id}");
}
}
#[test]
fn the_graphic_takes_the_blending_mode_of_its_fill() {
let d = document();
for id in [EXTRUDE, ROTATE] {
let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.blend = BlendMode::Multiply;
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut blends = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
blends.push(c.blend);
}
});
assert_eq!(blends, vec![BlendMode::Multiply], "{id}");
}
}
#[test]
fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() {
let d = document();
let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = 0.25;
}
let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)));
second.opacity = 0.75;
n.appearance.items.push(AppearanceItem::Fill(second));
let art = solid_art_in(Some(&d), &n).unwrap();
let mut opacities = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Group { clip: true, .. }) {
opacities.push(c.opacity);
}
});
opacities.sort_by(f32::total_cmp);
assert_eq!(opacities, vec![0.25, 0.75]);
}
#[test]
fn a_symbols_gradient_takes_the_size_of_its_art() {
use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
let mut d = document();
// Symbol art kept in its 20 × 20 square, drawn 40 × 20.
let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)]));
g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None });
let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g)));
d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) });
d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]}));
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first())
&& let Paint::Gradient(g) = &f.paint
{
found = Some((p.bounds().unwrap(), g.geom.unwrap()));
}
});
let (bounds, geom) = found.unwrap();
assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}");
assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}");
}
#[test]
fn a_symbols_pattern_follows_the_graphic() {
let mut d = document();
let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]}));
let out = solid_art_in(Some(&d), &n).unwrap();
let mut found = None;
out.walk(&mut |c| {
if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first()
&& let Paint::Pattern { xf, .. } = &f.paint
{
found = Some((c.path_data().unwrap().bounds().unwrap(), *xf));
}
});
let (bounds, xf) = found.unwrap();
// The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it.
assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}");
assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}");
assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}");
}
#[test]
fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() {
let bounds = Rect::new(10.0, 20.0, 70.0, 60.0);
let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() };
let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap();
// Where the page map stops along the line x = `x`, between the center and a point it does not map.
let edge = |x: f64| {
let inside = Point::new(x, bounds.center().y);
let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap();
let (mut a, mut b) = (inside, far);
for _ in 0..200 {
let m = a.midpoint(b);
if map.to_page(m).is_some() { a = m } else { b = m }
}
a
};
let (b1, b2) = (edge(40.0), edge(60.0));
let u = (b2 - b1).normalize();
let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x);
if map.to_page(b1 + n * 10.0).is_none() {
n = -n;
}
// Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays
// about 1 in front, while a control point of one of the pieces it is cut into falls behind.
let at = |s: f64, t: f64| b1 + n * s + u * t;
let mut curve = BezPath::new();
curve.move_to(at(219.17, 0.0));
curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0));
assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front");
let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0));
assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind");
let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps");
// The split pieces count toward the room the path is given: without room, the path is full,
// not behind the eye, so it is not clipped.
assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES);
assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full));
assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite())));
// That piece is split until its halves' control points map, so it stays a curve.
assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}");
// With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends
// of two pieces, which still map: it has no page point there, and is left to the clipping.
let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0));
assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some()));
assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none()));
let mut dips = BezPath::new();
dips.move_to(c.p0);
dips.curve_to(c.p1, c.p2, c.p3);
assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind));
}
#[test]
fn members_with_their_own_blending_get_graphics_of_their_own() {
let d = document();
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &group).unwrap();
let found = graphics_in(&art);
// One graphic clipped to each member's cap: the second stays inside the member's Multiply group.
assert_eq!(found.len(), 2);
let mut blended = 0;
art.walk(&mut |c| {
if c.blend == BlendMode::Multiply {
blended += graphics_in(c).len();
}
});
assert_eq!(blended, 1);
}
#[test]
fn a_graphic_stays_under_a_solid_painted_after_its_own() {
let d = document();
let member = |id: u64, r: Rect, color: Color, opacity: f32| {
let mut n = square(id, r, Paint::solid(color));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.opacity = opacity;
}
Arc::new(n)
};
let gray = Color::rgb(0.5, 0.5, 0.5);
// A and C share their fill's opacity; B, painted between them, has its own and covers part of A.
let a = member(1, Rect::new(0.0, 0.0, 60.0, 100.0), gray, 1.0);
let b = member(2, Rect::new(40.0, 0.0, 100.0, 100.0), Color::rgb(0.0, 0.0, 1.0), 0.5);
let c = member(4, Rect::new(200.0, 0.0, 260.0, 100.0), gray, 1.0);
let mut group = Node::group(NodeId(3), vec![a, b, c]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 3000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &group).unwrap();
// In drawing order: 'G' for a graphic, 'B' for a face of B's solid.
let mut order = String::new();
art.walk(&mut |n| {
if matches!(n.kind, NodeKind::Group { clip: true, .. }) && !graphics_in(n).is_empty() {
order.push('G');
} else if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first()
&& f.paint.color().is_some_and(|c| c.to_rgb()[2] > 0.9 && c.to_rgb()[0] < 0.1)
{
order.push('B');
}
});
// A's graphic is drawn right after A, under B; C's is drawn after B.
assert_eq!(graphics_in(&art).len(), 3, "{order}");
assert!(order.starts_with('G'), "{order}");
}
/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`.
fn dense_document(curved: bool) -> Document {
let mut d = document();
let mut poly = BezPath::new();
let mut last = Point::ZERO;
for k in 0..30_000 {
let a = k as f64 / 30_000.0 * std::f64::consts::TAU;
let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin());
if k == 0 {
poly.move_to(p);
} else if curved {
poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p);
} else {
poly.line_to(p);
}
last = p;
}
poly.close_path();
let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0));
d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) });
d
}
/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense"
/// ([`dense_document`]), seen under a perspective.
fn dense_graphics_drawn(curved: bool) -> usize {
let d = dense_document(curved);
let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5)));
b.blend = BlendMode::Multiply;
let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len()
}
#[test]
fn members_with_graphics_of_their_own_share_one_element_limit() {
// A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not.
// The first member's graphic is drawn; the second would pass the limit, so it draws none.
assert_eq!(dense_graphics_drawn(true), 1);
}
#[test]
fn straight_sides_count_once_under_a_perspective() {
// A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit.
assert_eq!(dense_graphics_drawn(false), 2);
}
#[test]
fn the_symbol_check_counts_what_the_view_draws() {
// Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit;
// curved, they do not.
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
let n = object(EXTRUDE, two.clone());
assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok());
let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// Without a perspective each curve draws once: curved, they fit too.
let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()});
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
}
#[test]
fn a_plane_and_a_hollow_solid() {
let d = document();
let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1);
let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]}));
assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty());
}
#[test]
fn a_stroked_graphic_draws_its_stroke_as_an_outline() {
let mut d = document();
let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None);
ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into();
d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]}));
let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap());
// The 10 × 10 square's 2 pt stroke reaches 1 pt outside it.
assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0]));
}
#[test]
fn graphics_are_checked() {
let n = object(EXTRUDE, json!({}));
let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics}));
assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok());
assert!(check(EXTRUDE, json!([])).is_ok());
for bad in [
json!("Mark"),
json!([{"face": "front"}]),
json!([{"symbol": ""}]),
json!([{"symbol": "Mark", "face": "side"}]),
json!([{"symbol": "Mark", "scale": 0.0}]),
json!([{"symbol": "Mark", "rotation": 400.0}]),
json!([{"symbol": "Mark", "x": "1"}]),
json!([{"symbol": "Mark", "repeat": true}]),
json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]),
] {
assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}");
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err());
// A loaded file's invalid entries are left out when drawn.
assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1);
}
#[test]
fn the_frame_at_an_index_is_that_effects() {
let d = document();
let mut n = object(EXTRUDE, json!({}));
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
// The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without.
assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none());
assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none());
}
#[test]
fn a_change_to_a_plane_drops_the_back_caps_graphics() {
let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]});
let plane = three_d_params_as(EXTRUDE, &p, ROTATE);
assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert!(validate_three_d_params(ROTATE, &plane).is_ok());
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
#[test]
fn a_stroked_solid_carries_its_graphic_too() {
let d = document();
let mut n = Node::path(
NodeId(7),
shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),
Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0),
);
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1);
}
#[test]
fn art_nested_too_deep_is_refused_and_not_drawn() {
let mut d = document();
let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
for k in 0..=MAX_LEVELS {
art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]);
}
d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) });
let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]}));
let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err();
assert!(e.contains("nested"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty());
// A loaded file draws its other graphics.
let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]}));
assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1);
}
#[test]
fn symbols_nested_too_deep_are_refused_and_not_drawn() {
let mut d = document();
// Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square.
d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
for k in 1..=MAX_NESTING + 1 {
let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY });
d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) });
}
let deepest = format!("N{MAX_NESTING}");
let p = json!({"graphics": [{"symbol": deepest}]});
assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok());
assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1);
let past = format!("N{}", MAX_NESTING + 1);
let p = json!({"graphics": [{"symbol": past}]});
let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err();
assert!(e.contains("nest"), "{e}");
assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty());
}
#[test]
fn a_solid_in_a_transparent_gradient_keeps_its_graphic() {
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
let d = document();
let mut stop = GradientStop::new(1.0, red());
stop.opacity = 0.25;
let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop]));
// Under a colored light the faces are drawn opaque and masked by the gradient's transparency.
let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.paint = Paint::Gradient(Box::new(gradient));
}
let art = solid_art_in(Some(&d), &n).unwrap();
let mut masked = false;
art.walk(&mut |c| masked |= c.extras().mask.is_some());
assert!(masked);
assert_eq!(graphics_in(&art).len(), 1);
// Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask.
let masks = |art: &Node| {
let mut out = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind
&& let [_, inner] = children.as_slice()
&& matches!(inner.kind, NodeKind::Group { clip: false, .. })
{
out.push(c.extras().mask.is_some());
}
});
out
};
// The graphic carries the cap's mask, so it is hidden where the gradient is transparent.
assert_eq!(masks(&art), vec![true]);
// With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own
// and the stroke's outline gets an unmasked one.
n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0)));
assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]);
}
#[test]
fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() {
let d = document();
let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath();
let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths();
let mut ring = outer;
ring.extend(hole.iter());
for flip in [false, true] {
let ring = if flip { ring.reverse_subpaths() } else { ring.clone() };
let mut n =
Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0));
let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]});
n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap());
let art = solid_art_in(Some(&d), &n).unwrap();
let mut clips = vec![];
art.walk(&mut |c| {
if let NodeKind::Group { children, clip: true } = &c.kind {
clips.push(children[0].path_data().unwrap().to_bezpath());
}
});
assert_eq!(clips.len(), 1, "flip {flip}");
assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip");
assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it");
}
}
#[test]
fn a_graphic_starts_inside_its_object() {
let d = document();
let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap();
assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0);
assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9);
assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0)));
}
#[test]
fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() {
let mut d = document();
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
// A dynamic symbol whose instance in "Changed" fills its square blue instead of red.
d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) });
let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY });
changed.extras_mut().symbol_overrides =
vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }];
d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap();
assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::<Vec<_>>(), [blue]);
// A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed
// three times as wide: the corner keeps its width while the rest stretches.
let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()));
let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red()));
d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) });
d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap();
let widths: Vec<f64> = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect();
assert_eq!(widths.len(), 2);
assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}");
// With a gradient, the square crossing the guides is cut at them: its pieces cover the
// placed 300 × 100 once, not one whole copy for each cell.
use vectorcraft_doc::color::{Gradient, GradientPaint};
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient);
d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) });
d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default()));
let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) });
d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) });
let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap();
let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum();
assert!((area - 30_000.0).abs() < 1e-3, "{area}");
}
@@ -317,6 +317,86 @@ fn images_are_refused_alone_and_in_a_group_with_image_trace_named() {
}
}
/// A clipping group: `art` inside a clipping path of `path` filled under `rule`.
fn shaped_clip_group(id: u64, path: PathData, rule: FillRule, art: Vec<Node>) -> Node {
let mut clipping = Node::path(NodeId(id + 1), path, Appearance::default());
if let NodeKind::Path { clipping: c, rule: r, .. } = &mut clipping.kind {
*c = true;
*r = rule;
}
let children = std::iter::once(clipping).chain(art).map(Arc::new).collect();
Node::new(NodeId(id), NodeKind::Group { children, clip: true })
}
/// An image `width` by `height` pixels placed by `xf`.
fn placed(id: u64, width: u32, height: u32, xf: Affine) -> Node {
let mut img = image(id);
if let NodeKind::Image(i) = &mut img.kind {
i.width = width;
i.height = height;
i.xf = xf;
}
img
}
#[test]
fn an_image_inside_a_clips_box_but_outside_its_shape_is_left_out() {
let d = document();
let circle = || shapes::ellipse(Rect::new(100.0, 100.0, 200.0, 200.0));
let square = || shapes::rectangle(Rect::new(100.0, 100.0, 150.0, 150.0));
let at = |x: f64, y: f64| Affine::translate((x, y));
// Two circles inside each other's clips: they show together only the lens between them.
let lens = |art: Vec<Node>| {
let inner = shaped_clip_group(70, shapes::ellipse(Rect::new(120.0, 100.0, 220.0, 200.0)), FillRule::NonZero, art);
shaped_clip_group(80, shapes::ellipse(Rect::new(80.0, 100.0, 180.0, 200.0)), FillRule::NonZero, vec![inner])
};
let mut ring = shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0));
ring.subpaths.extend(shapes::rectangle(Rect::new(130.0, 130.0, 170.0, 170.0)).subpaths);
// Turned 45° about its center at (156, 156): its box reaches into the square's corner, and its
// frame does not.
let turned = at(156.0, 156.0) * Affine::rotate(std::f64::consts::FRAC_PI_4) * at(-5.0, -5.0);
// A shown rectangle and an image `w` by `h` at `xf` inside the clipping path `path`.
let clipped = |path: PathData, rule: FillRule, shown: Rect, (w, h, xf): (u32, u32, Affine)| {
shaped_clip_group(60, path, rule, vec![rect(62, shown.x0, shown.y0, shown.x1, shown.y1, 0.0), placed(63, w, h, xf)])
};
let middle = Rect::new(140.0, 140.0, 160.0, 160.0);
let band = Rect::new(100.0, 100.0, 110.0, 200.0);
let left_out = [
// In the corner of the circle's box, outside the circle.
("a circle's corner", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(100.0, 100.0)))),
("a turned frame", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, turned))),
// Above the lens: inside each circle, outside both at once.
("two clips' shared area", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 100.0))])),
("an even-odd hole", clipped(ring.clone(), FillRule::EvenOdd, band, (10, 10, at(140.0, 140.0)))),
];
let shown = [
("part of the circle", clipped(circle(), FillRule::NonZero, middle, (10, 10, at(145.0, 145.0)))),
("a non-zero hole", clipped(ring, FillRule::NonZero, band, (10, 10, at(140.0, 140.0)))),
// A strip 0.005 pt wide inside the square still shows.
("a narrow strip", clipped(square(), FillRule::NonZero, Rect::new(110.0, 110.0, 140.0, 140.0), (10, 10, at(149.995, 120.0)))),
("the lens", lens(vec![rect(62, 145.0, 140.0, 155.0, 160.0, 0.0), placed(63, 8, 3, at(146.0, 108.0))])),
];
for id in TYPES {
for (what, g) in &left_out {
let n = with(g.clone(), id, json!({}));
assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}: {what}");
assert!(art(&d, &n, id).is_some(), "{id}: {what} draws");
assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id}: {what} exports");
}
for (what, g) in &shown {
let n = with(g.clone(), id, json!({}));
assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}: {what}");
assert!(art(&d, &n, id).is_none(), "{id}: {what}");
}
}
// Each frame cut to a clip counts: past the limit the art is refused, never left out unchecked.
let many: Vec<Node> = std::iter::once(rect(62, 140.0, 140.0, 160.0, 160.0, 0.0))
.chain((0..=source::MAX_IMAGE_CUTS as u64).map(|i| placed(100 + i, 10, 10, at(100.0, 100.0))))
.collect();
let n = with(shaped_clip_group(60, circle(), FillRule::NonZero, many), ROTATE, front());
assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("too many objects")));
}
/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one
/// before it.
fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document {
+276
View File
@@ -0,0 +1,276 @@
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
//! can be edited on their own.
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
use vectorcraft_three_d::Facet;
use super::{
INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile,
region, reshape_members, resolve, resolve_for, solid, solid_paints, solid_parts, union_bounds, view_options,
};
use crate::{GeomContext, is_geometry};
/// The most distinct edges one object's wireframe may have.
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
/// The grid points are rounded to before edges are compared, in points: two faces that share an
/// edge give it once.
const GRID: f64 = 1.0 / 1024.0;
const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)";
/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D
/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as
/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path;
/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry
/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a
/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D
/// effect, when its solids can't be built, when the canvas draws the source art in their place, when
/// they draw no face, or past [`MAX_WIRE_EDGES`] edges.
pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if !crate::has_revolve(n) && !has_solid(n) {
return Err(NO_EFFECT.into());
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
// The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries
// it first). When neither draws, past their limits, the canvas shows the source art and there
// is no surface to expand.
let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some();
if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) {
// The builders' own error says why, when there is one. Revolve's art is cut for Revolve,
// as the canvas cuts it.
if crate::has_revolve(n) {
crate::revolve::revolve_face_paths(doc, &*resolve_for(doc, n, label, false)?)?;
} else {
solid_face_paths(doc, &*resolve(doc, n, label)?)?;
}
return Err(format!("{label} draws the source art for this object instead of its 3D surface"));
}
// Revolve's art is cut for Revolve whatever other 3D effect the object carries, as the canvas
// cuts it ([`crate::revolve_art_in`]).
let n = &*if revolve { resolve_for(doc, n, label, false)? } else { resolve(doc, n, label)? };
let faces = if revolve { crate::revolve::revolve_face_paths(doc, n)? } else { solid_face_paths(doc, n)? };
let faces = after_geometry(doc, n, faces, revolve);
let wire = edges(&faces)?;
if wire.is_empty() {
return Err(format!("{label} draws no faces for this object"));
}
Ok(wire)
}
/// `faces` reshaped by the visible geometry effects after the 3D effect of `n`'s own that drew them
/// ([`reshaped`]): its first visible Revolve when `revolve` is set, else its first visible Extrude &
/// Bevel, Inflate or Rotate.
fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec<PathData>, revolve: bool) -> Vec<PathData> {
let fx = &n.appearance.effects;
let drawn = if revolve { fx.iter().position(|e| e.visible && crate::revolve::is_revolve(&e.id)) } else { solid(fx).map(|(i, _)| i) };
let Some(index) = drawn else { return faces };
reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) })
}
/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as
/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect
/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep
/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform,
/// and the document.
pub(crate) fn reshaped(faces: Vec<PathData>, later: &[Effect], ctx: &GeomContext) -> Vec<PathData> {
let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect();
if after.is_empty() {
return faces;
}
let id = NodeId(ctx.seed);
let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect());
crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc);
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect
/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer,
/// the solids of its members, about one shared axis. The swatches and patterns named by a live-effect
/// plug-in after a fill's or stroke's 3D effect are looked up in `doc`.
fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<Vec<PathData>, String> {
if is_container(n) {
let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?;
let mut shapes = members(n, label_of(&fx.id))?;
reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes);
return facet_paths(fx, &shapes);
}
let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id));
let (path, rule) = object_profile(n, label)?;
let ctx = GeomContext::of(n);
let paints = solid_paints(n);
if let Some((index, fx)) = solid(&n.appearance.effects) {
let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx);
return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]);
}
let path = geometry(&path, &n.appearance.effects, &ctx);
let mut out = vec![];
for item in &paints {
if let Some((index, fx)) = solid(item.effects()) {
let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item));
let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?;
out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..ctx }));
}
}
Ok(out)
}
/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and
/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's
/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out,
/// as it is left out of the drawn art.
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<PathData>, String> {
let label = label_of(&fx.id);
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
let p = crate::merged_params(&fx.id, &fx.params);
let mut out = vec![];
if is_plane(&fx.id) {
for s in shapes {
for item in &s.items {
let (area, rule) = region(&s.path, s.rule, item);
out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path));
}
}
return Ok(out);
}
let (parts, bounds) = solid_parts(shapes, b);
let built: Vec<Result<Vec<Facet>, String>> = if fx.id == INFLATE {
let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect();
vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p))
} else {
parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect()
};
for ((item, ..), f) in parts.iter().zip(built) {
match f {
Ok(f) => out.extend(f.iter().map(Facet::path)),
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {}
Err(e) => return Err(e),
}
}
Ok(out)
}
/// A point on the [`GRID`].
type Snap = (i64, i64);
fn snap(p: Point) -> Snap {
((p.x / GRID).round() as i64, (p.y / GRID).round() as i64)
}
fn reversed(c: CubicBez) -> CubicBez {
CubicBez::new(c.p3, c.p2, c.p1, c.p0)
}
/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]).
pub(crate) fn edges(faces: &[PathData]) -> Result<Vec<PathData>, String> {
let mut seen: HashSet<[Snap; 4]> = HashSet::new();
let mut segments: Vec<CubicBez> = vec![];
for sp in faces.iter().flat_map(|f| &f.subpaths) {
for i in 0..sp.segment_count() {
let mut c = sp.segment(i);
if sp.segment_is_line(i) {
c = CubicBez::new(c.p0, c.p0, c.p3, c.p3);
}
if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
continue;
}
let key = [c.p0, c.p1, c.p2, c.p3].map(snap);
// A segment that starts and ends on one grid point with its handles there too draws nothing.
if key.iter().all(|k| *k == key[0]) {
continue;
}
let back = [key[3], key[2], key[1], key[0]];
if seen.contains(&back) || !seen.insert(key) {
continue;
}
if segments.len() >= MAX_WIRE_EDGES {
return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges"));
}
segments.push(c);
}
}
Ok(chain(&segments))
}
/// `segments` joined end to end: each path starts at the first segment not yet used and takes in
/// the unused segments that meet its ends until none is left at either end, or it closes.
fn chain(segments: &[CubicBez]) -> Vec<PathData> {
let mut at: HashMap<Snap, Vec<usize>> = HashMap::new();
for (i, c) in segments.iter().enumerate() {
at.entry(snap(c.p0)).or_default().push(i);
if snap(c.p3) != snap(c.p0) {
at.entry(snap(c.p3)).or_default().push(i);
}
}
let mut used = vec![false; segments.len()];
// The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it.
let mut take = |used: &mut Vec<bool>, point: Snap, leave: bool| -> Option<CubicBez> {
let list = at.get_mut(&point)?;
while let Some(&i) = list.last() {
if used.get(i).copied().unwrap_or(true) {
list.pop();
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let c = *segments.get(i)?;
let starts = snap(c.p0) == point;
return Some(if starts == leave { c } else { reversed(c) });
}
None
};
let mut out = vec![];
for (i, first) in segments.iter().enumerate() {
if used.get(i).copied().unwrap_or(true) {
continue;
}
if let Some(u) = used.get_mut(i) {
*u = true;
}
let mut run: VecDeque<CubicBez> = VecDeque::from([*first]);
// A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment
// that comes back to its start stays open, with its two ends on one point.
let closes = |run: &VecDeque<CubicBez>| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3));
while !closes(&run) {
let Some(end) = run.back().map(|c| snap(c.p3)) else { break };
let Some(c) = take(&mut used, end, true) else { break };
run.push_back(c);
}
while !closes(&run) {
let Some(start) = run.front().map(|c| snap(c.p0)) else { break };
let Some(c) = take(&mut used, start, false) else { break };
run.push_front(c);
}
out.push(PathData::single(subpath(&run, closes(&run))));
}
out
}
/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor.
fn subpath(run: &VecDeque<CubicBez>, closed: bool) -> SubPath {
let mut anchors: Vec<Anchor> = vec![];
if let Some(first) = run.front() {
let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 };
anchors.push(Anchor::with_handles(first.p0, h_in, first.p1));
}
for (k, c) in run.iter().enumerate() {
let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1);
anchors.push(Anchor::with_handles(c.p3, c.p2, h_out));
}
// A closed run's last anchor is its first, whose in handle already comes from the last segment.
if closed {
anchors.pop();
}
SubPath::new(anchors, closed)
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,235 @@
use serde_json::{Value, json};
use vectorcraft_doc::color::{Color, Paint};
use vectorcraft_doc::{Appearance, Node, NodeId};
use vectorcraft_geom::{BezPath, Rect};
use super::*;
fn square(x: f64, y: f64, size: f64) -> PathData {
let mut b = BezPath::new();
b.move_to((x, y));
b.line_to((x + size, y));
b.line_to((x + size, y + size));
b.line_to((x, y + size));
b.close_path();
PathData::from_bezpath(&b)
}
/// A filled 100 pt square without a stroke, with effect `id` and `params`.
fn solid_square(id: &str, params: Value) -> Node {
let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
n
}
/// Every segment of `wire`, each as its two ends on the grid.
fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> {
wire.iter()
.flat_map(|p| &p.subpaths)
.flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i)))
.map(|c| (snap(c.p0), snap(c.p3)))
.collect()
}
fn bounds(paths: &[PathData]) -> Rect {
paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
/// The paths of the faces `art` draws (every leaf of the art).
fn face_paths(art: &Node) -> Vec<PathData> {
let mut out = vec![];
art.walk(&mut |c| out.extend(c.path_data().cloned()));
out
}
#[test]
fn two_faces_that_share_an_edge_give_it_once() {
let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap();
let segs = segments(&wire);
assert_eq!(segs.len(), 7, "{segs:?}");
for (i, a) in segs.iter().enumerate() {
for b in segs.iter().skip(i + 1) {
assert!(a != b && (a.1, a.0) != *b, "{a:?} twice");
}
}
}
#[test]
fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() {
let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap();
assert_eq!(wire.len(), 1);
assert!(wire[0].subpaths[0].closed);
assert_eq!(wire[0].subpaths[0].anchors.len(), 4);
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0));
b.close_path();
let wire = edges(&[PathData::from_bezpath(&b)]).unwrap();
let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i)));
assert!(curved, "{wire:?}");
}
/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on
/// one point, since a path of one anchor has no segment.
#[test]
fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() {
let p = Point::new(0.0, 0.0);
let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)];
let face = PathData::single(SubPath::new(anchors, false));
assert_eq!(face.subpaths[0].segment_count(), 1);
let wire = edges(&[face]).unwrap();
assert_eq!(wire.len(), 1);
let sp = &wire[0].subpaths[0];
assert_eq!(sp.segment_count(), 1, "{sp:?}");
assert!(!sp.segment_is_line(0));
}
#[test]
fn edges_without_length_or_with_non_finite_points_are_left_out() {
let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false));
let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false));
assert!(edges(&[point, bad]).unwrap().is_empty());
assert!(edges(&[]).unwrap().is_empty());
}
#[test]
fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert_eq!(segments(&wire).len(), 9, "{wire:?}");
// The wireframe covers what the effect draws, in the same place.
let art = super::super::solid_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
}
#[test]
fn the_classic_wireframe_surface_expands_to_all_twelve_edges() {
let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"}));
assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12);
}
#[test]
fn revolve_inflate_and_rotate_expand_too() {
for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] {
let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}"));
assert!(!wire.is_empty(), "{id}");
assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}");
}
// Rotate is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same
/// place.
#[test]
fn revolve_classic_and_rotate_classic_expand_too() {
let n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let wire = three_d_wireframe_in(None, &n).unwrap();
assert!(!wire.is_empty());
let art = crate::revolve_art(&n).unwrap();
let (w, a) = (bounds(&wire), bounds(&face_paths(&art)));
for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] {
assert!((x - y).abs() < 1e-6, "{w:?} {a:?}");
}
// On a fill, with a geometry effect after it.
let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap());
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}");
// Rotate (Classic) is one flat face: its outline.
let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap();
assert_eq!(segments(&plane).len(), 4);
}
/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face
/// of the drawn surface: two faces that touch stay two outlines.
#[test]
fn later_geometry_effects_reshape_each_face_on_its_own() {
let n = solid_square(super::super::EXTRUDE, json!({}));
let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()];
let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n));
assert_eq!(out.len(), 2, "{out:?}");
let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap());
assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}");
assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}");
}
/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface.
#[test]
fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() {
for id in [super::super::EXTRUDE, crate::REVOLVE] {
let mut n = solid_square(id, json!({}));
let fx = n.appearance.effects.remove(0);
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(fx.clone());
}
}
let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}")));
for item in &mut n.appearance.items {
if matches!(item, AppearanceItem::Fill(_)) {
item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
}
}
let moved = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}");
}
}
/// With two 3D effects, a geometry effect between them reshapes the faces of the one drawn only
/// once: Revolve is drawn, so a Transform before it moves its profile and not its faces again.
#[test]
fn a_geometry_effect_before_the_drawn_3d_effect_is_not_applied_again() {
let mut n = solid_square(crate::REVOLVE, json!({}));
n.appearance.effects.insert(0, crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap());
let alone = bounds(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.insert(0, crate::new_effect(super::super::EXTRUDE, &json!({})).unwrap());
let both = bounds(&three_d_wireframe_in(None, &n).unwrap());
assert!((both.x0 - alone.x0).abs() < 1e-6 && (both.x1 - alone.x1).abs() < 1e-6, "{alone:?} {both:?}");
}
/// A clipping group with Revolve and Rotate draws Revolve, which cuts the art's fills as one piece
/// in the top fill's place. Its wireframe is cut the same way, so art with more fills than a 3D
/// effect takes members still expands, to the edges of Revolve alone.
#[test]
fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
let mut art = Node::path(NodeId(3), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
let fill = art.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Fill(_))).cloned().unwrap();
art.appearance.items = vec![fill; super::super::MAX_MEMBERS + 4];
let mut clip = Node::path(NodeId(2), square(100.0, 100.0, 50.0), Appearance::default());
if let vectorcraft_doc::NodeKind::Path { clipping, .. } = &mut clip.kind {
*clipping = true;
}
let mut n = Node::new(NodeId(1), vectorcraft_doc::NodeKind::Group { children: vec![Arc::new(clip), Arc::new(art)], clip: true });
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &json!({})).unwrap());
let alone = segments(&three_d_wireframe_in(None, &n).unwrap());
n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap());
assert!(crate::revolve_art_in(None, &n).is_some(), "the canvas draws Revolve");
let both = segments(&three_d_wireframe_in(None, &n).unwrap());
assert_eq!(both, alone);
}
#[test]
fn an_object_without_a_visible_3d_effect_is_an_error() {
let mut n = solid_square(super::super::EXTRUDE, json!({}));
n.appearance.effects[0].visible = false;
assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect"));
n.appearance.effects.clear();
assert!(three_d_wireframe_in(None, &n).is_err());
}
+21 -11
View File
@@ -4,7 +4,8 @@
//! in the back wall of hollow ones (with the cap kept out of the hole) and at the chevron's inner
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]).
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
//! custom heads, whose stroke ends halfway along their length.
use std::borrow::Cow;
@@ -37,8 +38,14 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
let last = subs.last().filter(|s| !s.1).map(|s| s.0.clone());
let cap = cap_extent(st.cap, st.width);
let (hw0, hw1) = (st.arrow_weight(false), st.arrow_weight(true));
let start = st.start_arrow.zip(first).map(|(k, r)| (k, r, inset(k, hw0, cap)));
let end = st.end_arrow.zip(last).map(|(k, r)| (k, r, inset(k, hw1, cap)));
let start = st.start_arrow.clone().zip(first).map(|(k, r)| {
let i = inset(&k, hw0, cap);
(k, r, i)
});
let end = st.end_arrow.clone().zip(last).map(|(k, r)| {
let i = inset(&k, hw1, cap);
(k, r, i)
});
if start.is_none() && end.is_none() {
return StrokePieces { line: Cow::Borrowed(bp), heads: vec![] };
}
@@ -56,7 +63,8 @@ pub(super) fn pieces<'a>(bp: &'a BezPath, st: &StrokeLayer) -> StrokePieces<'a>
} else {
(end_pt + outward * inset, outward)
};
heads.push(Arrow { kind, outline: shape(kind, tip, dir, hw), tip, dir, inset });
let outline = shape(&kind, tip, dir, hw);
heads.push(Arrow { kind, outline, tip, dir, inset });
};
if let Some((k, r, i)) = start {
place(k, r, true, i, hw0);
@@ -181,12 +189,12 @@ pub(super) fn trims(st: &StrokeLayer) -> (f64, f64) {
return (0.0, 0.0);
}
let cap = cap_extent(st.cap, st.width);
let inset_of = |kind: Option<Arrowhead>, end: bool| kind.map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(st.start_arrow, false), inset_of(st.end_arrow, true))
let inset_of = |kind: &Option<Arrowhead>, end: bool| kind.as_ref().map_or(0.0, |k| inset(k, st.arrow_weight(end), cap));
(inset_of(&st.start_arrow, false), inset_of(&st.end_arrow, true))
}
/// Distance from the tip where the stroke ends, for a stroke whose cap reaches `cap` past its end.
fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
fn inset(kind: &Arrowhead, hw: f64, cap: f64) -> f64 {
let l = len(hw);
// Solid heads: halfway in, far enough that the cap stays behind the tip.
let solid = |back: f64| (back / 2.0).max(cap);
@@ -199,6 +207,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
Arrowhead::TriangleOpen | Arrowhead::CircleOpen | Arrowhead::SquareOpen => hollow(l),
// The inner corner of the chevron: arm / sin(half angle).
Arrowhead::ArrowOpen => (arm(hw) * (l * l + l * l / 4.0).sqrt() / (l / 2.0)).max(cap),
Arrowhead::Custom(c) => (c.stop() * hw).max(cap),
_ => match local_stop(kind) {
Stop::At(u) => (u * hw).max(cap),
Stop::Wall(back) => hollow(back * hw),
@@ -207,7 +216,7 @@ fn inset(kind: Arrowhead, hw: f64, cap: f64) -> f64 {
}
/// Outline of a `kind` head of weight `hw` with its tip at `tip`, pointing along `dir`.
fn shape(kind: Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
fn shape(kind: &Arrowhead, tip: Point, dir: Vec2, hw: f64) -> BezPath {
let n = Vec2::new(-dir.y, dir.x);
let l = len(hw);
let half = l / 2.0;
@@ -265,7 +274,7 @@ const HEX: f64 = 2.0 * 1.732_050_807_568_877_2;
const LOCAL_TOL: f64 = 1e-3;
/// Where the stroke ends under a head drawn in local units ([`local`]), in those units.
fn local_stop(kind: Arrowhead) -> Stop {
fn local_stop(kind: &Arrowhead) -> Stop {
match kind {
Arrowhead::Target | Arrowhead::TagOpen | Arrowhead::DiamondOpen => Stop::Wall(4.0),
Arrowhead::HexagonOpen => Stop::Wall(HEX),
@@ -288,8 +297,8 @@ fn local_stop(kind: Arrowhead) -> Stop {
/// The outline of a head added after the first ten, in local units: x from the tip (0) back
/// along the line (to at most 4; the line arrow's square-cut arms 4.71), y across it (−2 to 2,
/// the line arrow −4 to 4; positive to the right of the direction the head points). Every shape
/// is generated here.
fn local(kind: Arrowhead) -> BezPath {
/// is generated here, and a custom head's outline is its own.
fn local(kind: &Arrowhead) -> BezPath {
let mut p = BezPath::new();
let poly = |p: &mut BezPath, pts: &[(f64, f64)]| polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>());
let ring_poly = |p: &mut BezPath, pts: &[(f64, f64)]| ring_polygon(p, &pts.iter().map(|&q| Point::from(q)).collect::<Vec<_>>(), ring(1.0));
@@ -385,6 +394,7 @@ fn local(kind: Arrowhead) -> BezPath {
let t = FRAC_1_SQRT_2;
poly(&mut p, &[(0.0, 0.0), (4.0, 4.0), (4.0 + t, 4.0 - t), (2.0 * t, 0.0), (4.0 + t, t - 4.0), (4.0, -4.0)]);
}
Arrowhead::Custom(c) => p = c.path.to_bezpath(),
// The first ten are drawn by `shape`.
Arrowhead::Triangle
| Arrowhead::TriangleOpen
+27 -6
View File
@@ -32,6 +32,12 @@ const SHARP: f64 = 1.25;
const HAIRPIN: f64 = 4.0;
/// Rows of a mesh across the stroke (more where the gradient has stops).
const MESH_ROWS: usize = 16;
/// The most stops of the gradient [`gradient_meshes`] puts rows or columns at
/// ([`Gradient::fitted`]: past it, the stops that change the colors least are left out).
pub(crate) const MAX_MESH_STOPS: usize = 1024;
/// The most points of one mesh [`gradient_meshes`] makes, unless a single pair of ribs needs more:
/// a subpath with more ribs than leave room for a row at each stop becomes several meshes.
pub(crate) const MAX_MESH_POINTS: usize = 1 << 20;
/// The most of a subpath one column of a mesh along the stroke spans.
const MESH_STEP: f64 = 1.0 / 32.0;
/// The most of a subpath one slice spans while a width profile shapes the across gradient.
@@ -513,26 +519,33 @@ fn mesh_marks(g: &Gradient) -> Vec<f64> {
/// Outline Stroke of stroke `st` of `bp` (filled with `rule`) whose gradient `g` runs along or
/// across it: a gradient mesh per subpath over all the stroke can paint there (clip it to the
/// stroke's outline), coloured as [`gradient_slices`] paint it.
/// stroke's outline), coloured as [`gradient_slices`] paint it. The gradient's stops are fitted to
/// [`MAX_MESH_STOPS`], and a subpath whose mesh would hold more than [`MAX_MESH_POINTS`] points is
/// split into meshes of fewer ribs ([`rib_pieces`]).
pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradient) -> Vec<GradientMesh> {
let g = &*g.unrolled();
let fitted = g.fitted(MAX_MESH_STOPS);
let across = st.gradient_mode == StrokeGradientMode::Across;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
let at_stops = mesh_marks(g);
// Along: a column at each stop (colours are linear between columns), close enough to look smooth.
let marks: Vec<f64> = if across { vec![] } else { at_stops.clone() };
let marks: Vec<f64> = if across { vec![] } else { mesh_marks(&fitted) };
let max_dt = match (across, st.profile.is_some()) {
(false, _) => MESH_STEP,
(true, true) => PROFILE_STEP,
(true, false) => 1.0,
};
// Rows across: the strip's edges, then (across) the band's left edge to its right edge with a row at each stop.
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(at_stops).collect() } else { vec![0.5] };
let mut us: Vec<f64> = if across { (0..=MESH_ROWS).map(|i| i as f64 / MESH_ROWS as f64).chain(mesh_marks(&fitted)).collect() } else { vec![0.5] };
us.sort_by(f64::total_cmp);
us.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let us = &us;
let g = &*fitted;
let color = |t: f64| g.sample_keep_model(t.clamp(0.0, 1.0) as f32);
// A mesh is a point for each row (and its two edges) on each rib: a strip with more ribs than
// that leaves room for is split into meshes of fewer ribs.
let per_mesh = MAX_MESH_POINTS / (us.len() + 2);
strips(bp, rule, st, SLICE_TOL, SLICE_MARGIN, &marks, max_dt)
.into_iter()
.filter(|ribs| ribs.len() > 1)
.flat_map(|ribs| rib_pieces(ribs.len(), per_mesh).into_iter().map(move |r| ribs.get(r).unwrap_or_default().to_vec()))
.map(|ribs| {
let (rows, cols) = (us.len() + 1, ribs.len() - 1);
// Each level across: a point on each rib and the gradient position there.
@@ -569,3 +582,11 @@ pub fn gradient_meshes(bp: &BezPath, rule: FillRule, st: &StrokeLayer, g: &Gradi
})
.collect()
}
/// The ribs (index ranges of `n`, at least two) of each mesh [`gradient_meshes`] makes of a strip:
/// at most `per_mesh` ribs each (at least two), each starting on the last rib of the one before,
/// so the meshes meet without a gap.
pub(crate) fn rib_pieces(n: usize, per_mesh: usize) -> Vec<std::ops::Range<usize>> {
let per_mesh = per_mesh.max(2);
(0..n.saturating_sub(1)).step_by(per_mesh - 1).map(|start| start..(start + per_mesh).min(n)).collect()
}
+5 -5
View File
@@ -280,7 +280,7 @@ fn no_heads_borrows_the_path_and_closed_paths_get_none() {
#[test]
fn tip_mode_shortens_the_stroke_by_the_head_and_puts_the_tip_on_the_end_point() {
for kind in Arrowhead::ALL {
let st = arrows(kind, ArrowAlign::Tip, LineCap::Butt);
let st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Butt);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let [h] = &p.heads[..] else { panic!("one head") };
@@ -335,7 +335,7 @@ fn extend_mode_keeps_the_path_and_overhangs_by_the_inset() {
#[test]
fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
for (kind, cap) in [(Arrowhead::CircleOpen, LineCap::Round), (Arrowhead::SquareOpen, LineCap::Square), (Arrowhead::TriangleOpen, LineCap::Butt)] {
let st = arrows(kind, ArrowAlign::Tip, cap);
let st = arrows(kind.clone(), ArrowAlign::Tip, cap);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
let h = &p.heads[0];
@@ -361,7 +361,7 @@ fn hollow_heads_are_rings_and_the_stroke_stays_out_of_the_hole() {
fn round_caps_never_poke_past_the_tip() {
for kind in Arrowhead::ALL {
for scale in [10.0, 100.0, 300.0] {
let mut st = arrows(kind, ArrowAlign::Tip, LineCap::Round);
let mut st = arrows(kind.clone(), ArrowAlign::Tip, LineCap::Round);
st.arrow_scale = (scale, scale);
let l = line(0.0, 100.0);
let p = stroke_pieces(&l, &st);
@@ -403,8 +403,8 @@ fn degenerate_paths_and_patterns_neither_panic_nor_hang() {
for pat in patterns {
for off in [0.0, -7.0, 1e12, f64::INFINITY] {
let st = stroke(2.0, |s| {
s.start_arrow = Some(kind);
s.end_arrow = Some(kind);
s.start_arrow = Some(kind.clone());
s.end_arrow = Some(kind.clone());
s.arrow_align = align;
s.cap = cap;
s.dash = Some(dashed(pat, off));
+29 -2
View File
@@ -50,7 +50,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
let (o, d) = (Point::ORIGIN, Point::new(2.0, 2.0));
assert!(cross((o, d), (Point::new(0.0, 2.0), Point::new(2.0, 0.0))) && !cross((o, d), (d, Point::new(4.0, 0.0))), "the check itself");
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
assert!(h.outline.area().abs() > 4.0, "{kind:?} is drawn");
let b = h.outline.bounding_box();
let (reach, side) = (2.0 * kind.reach(), 2.0 * kind.half_width());
@@ -73,7 +73,7 @@ fn every_outline_is_drawn_inside_its_box_without_self_intersections() {
#[test]
fn the_stroke_ends_inside_every_head() {
for kind in Arrowhead::ALL {
let h = head(kind);
let h = head(kind.clone());
// Just in front of where the line stops, on its centre line.
let end = h.tip - h.dir * (h.inset - 0.1);
assert_ne!(h.outline.winding(end), 0, "{kind:?}: the line ends outside the head (inset {})", h.inset);
@@ -112,3 +112,30 @@ fn half_arrows_barb_on_their_own_side() {
assert!(head(Arrowhead::HalfArrowLeft).outline.bounding_box().y1 < 1.5);
assert!(head(Arrowhead::HalfArrowRight).outline.bounding_box().y1 > 3.0);
}
#[test]
fn custom_heads_draw_their_own_art_at_the_tip() {
use vectorcraft_doc::CustomArrowhead;
use vectorcraft_geom::{PathData, SubPath};
// From the tip back 3 units, 2 to the right of the line and 1 to the left.
let wedge = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(3.0, 2.0), Point::new(3.0, -1.0)], true));
let kind = Arrowhead::Custom(std::sync::Arc::new(CustomArrowhead::new("Wedge".into(), wedge)));
let h = head(kind.clone());
// Weight 2: drawn back to x 94, right of +x is +y on a y-down page.
let b = h.outline.bounding_box();
assert!((b.x0 - 94.0).abs() < 1e-9 && (b.x1 - 100.0).abs() < 1e-9 && (b.y0 + 2.0).abs() < 1e-9 && (b.y1 - 4.0).abs() < 1e-9, "{b:?}");
assert_eq!(h.outline.winding(Point::new(95.0, 1.0)), h.outline.winding(Point::new(95.0, 0.5)));
assert_ne!(h.outline.winding(Point::new(95.0, 1.0)), 0);
// The line stops halfway along the head.
assert!((h.inset - 3.0).abs() < 1e-9, "inset {}", h.inset);
// Extended, the tip sits the inset past the end point, and scaling scales the art.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.arrow_scale) = (Some(kind), (200.0, 100.0));
let mut l = BezPath::new();
l.move_to((0.0, 0.0));
l.line_to((100.0, 0.0));
let p = stroke_pieces(&l, &st);
let [s] = &p.heads[..] else { panic!("one head") };
assert!((s.tip.x + 6.0).abs() < 1e-9 && s.dir.x < 0.0, "tip {:?}", s.tip);
assert!((s.outline.bounding_box().width() - 12.0).abs() < 1e-9);
}
@@ -345,6 +345,35 @@ fn a_narrow_peak_where_a_reflecting_gradient_turns_back_stays_in_the_mesh() {
}
}
/// Outline Stroke's mesh across a stroke of many ribs, with a gradient of many stops repeated 100
/// times: each mesh holds at most so many points, and every run still starts on its first color.
#[test]
fn a_mesh_across_many_ribs_and_stops_stays_bounded() {
use vectorcraft_color::GradientSpread;
let pts: Vec<(f64, f64)> = (0..1200).map(|i| (i as f64 * 10.0, if i % 2 == 0 { 0.0 } else { 10.0 })).collect();
let bp = poly(&pts, false);
let stops: Vec<GradientStop> = (0..200).map(|i| GradientStop::new(i as f32 / 199.0, Color::gray(1.0 - i as f32 / 199.0))).collect();
let g = Gradient { spread: GradientSpread::Repeat, repeats: 100, ..Gradient::new(vectorcraft_color::GradientKind::Linear, stops) };
let mut st = stroke(4.0, StrokeGradientMode::Across);
st.paint = Paint::Gradient(Box::new(GradientPaint::new(g.clone())));
let meshes = gradient_meshes(&bp, FillRule::NonZero, &st, &g);
assert!(!meshes.is_empty());
for m in &meshes {
assert!(m.points.len() <= super::gradient::MAX_MESH_POINTS, "{} points", m.points.len());
// A row at the start of each of the 100 runs, on every rib, is white.
let light = m.points.iter().filter(|p| p.color.to_rgb()[0] > 0.97).count();
assert!(light >= 100 * (m.cols as usize + 1), "{light} light points of {}", m.points.len());
}
// A strip of more ribs than one mesh has room for is split into meshes that share their end
// ribs, every rib in one of them.
use super::gradient::rib_pieces;
assert_eq!(rib_pieces(5, 3), [0..3, 2..5]);
assert_eq!(rib_pieces(4, 3), [0..3, 2..4]);
let one = rib_pieces(2, 1000);
assert_eq!((one.len(), one.first()), (1, Some(&(0..2))));
assert_eq!(rib_pieces(3, 0), [0..2, 1..3]);
}
/// #5960: with dashes, the ribs reach as far as the stroke gets wide within a cap's length along
/// the path, however many points lie that far: not as far as it is wide anywhere when more than
/// 256 do.
+44 -2
View File
@@ -78,6 +78,35 @@ fn a_butt_capped_open_path_is_measured_where_it_paints() {
}
}
#[test]
fn beveled_corners_are_measured_where_they_paint() {
let mut tip = BezPath::new();
tip.move_to((0.0, 100.0));
tip.line_to((20.0, 0.0));
tip.line_to((40.0, 100.0));
tip.close_path();
let mut chevron = BezPath::new();
chevron.move_to((0.0, 100.0));
chevron.line_to((20.0, 0.0));
chevron.line_to((40.0, 100.0));
// A rectangle with no width turns back at its top and bottom.
let flat = vectorcraft_geom::shapes::rectangle(Rect::new(3.0, 100.0, 3.0, 150.0)).to_bezpath();
let ps = paths();
for (name, bp) in [("tip", &tip), ("chevron", &chevron), ("zigzag", &ps[1]), ("triangle", &ps[2]), ("flat", &flat)] {
for cap in [LineCap::Butt, LineCap::Round, LineCap::Square] {
for (join, limit) in [(LineJoin::Bevel, 10.0), (LineJoin::Miter, 1.0), (LineJoin::Miter, 2.0), (LineJoin::Miter, 10.0)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 20.0);
(st.cap, st.join, st.miter_limit) = (cap, join, limit);
let painted = outline_region(&PathData::from_bezpath(bp), FillRule::NonZero, &st).to_bezpath().bounding_box();
let bounds = st.bounds_on(bp, bp.bounding_box());
for (got, want) in [(bounds.x0, painted.x0), (bounds.y0, painted.y0), (bounds.x1, painted.x1), (bounds.y1, painted.y1)] {
assert!((got - want).abs() < 0.05, "{name} {cap:?} {join:?} {limit}: measured {bounds:?}, paints {painted:?}");
}
}
}
}
}
#[test]
fn bounds_and_clicks_cover_what_every_stroke_paints() {
let profiles = [None, Some(WidthProfile::lens()), Some(WidthProfile { points: vec![(0.0, 2.0, 0.5), (0.6, 0.8, 1.6), (1.0, 1.2, 0.3)] })];
@@ -99,14 +128,27 @@ fn bounds_and_clicks_cover_what_every_stroke_paints() {
}
}
/// Custom heads: one wholly behind its tip, and a long one reaching as far in front of its tip as
/// behind it (its tip sits halfway along it past the end point with Extend).
fn custom_heads() -> Vec<Arrowhead> {
use vectorcraft_geom::{Point as P, SubPath};
let head = |name: &str, pts: &[(f64, f64)]| {
let pts: Vec<P> = pts.iter().map(|&(x, y)| P::new(x, y)).collect();
let path = PathData::single(SubPath::polyline(&pts, true));
Arrowhead::Custom(std::sync::Arc::new(vectorcraft_doc::CustomArrowhead::new(name.into(), path)))
};
vec![head("Wedge", &[(0.0, 0.0), (3.0, 2.0), (3.0, -1.0)]), head("Spindle", &[(-10.0, 0.0), (0.0, 2.0), (10.0, 0.0), (0.0, -2.0)])]
}
#[test]
fn bounds_and_clicks_cover_every_arrowhead() {
let bp = &paths()[0];
for kind in Arrowhead::ALL {
for kind in Arrowhead::ALL.into_iter().chain(custom_heads()) {
for align in [ArrowAlign::Extend, ArrowAlign::Tip] {
for (scale, cap) in [(50.0, LineCap::Round), (100.0, LineCap::Butt), (300.0, LineCap::Square)] {
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 3.0);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) = (Some(kind), Some(kind), align, (scale, scale), cap);
(st.start_arrow, st.end_arrow, st.arrow_align, st.arrow_scale, st.cap) =
(Some(kind.clone()), Some(kind.clone()), align, (scale, scale), cap);
check(bp, &st, &format!("{kind:?} {align:?} {scale}%"));
}
}
+104
View File
@@ -4,6 +4,8 @@ use vectorcraft_geom::{Affine, PathData, Point, Rect, Shape, SubPath, shapes};
use super::*;
mod imageoutline;
mod rasterfollow;
mod scale;
mod transformfx;
@@ -885,6 +887,108 @@ fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move() {
}
}
/// Under a Warp effect a hidden path in a layer that keeps its shape past the budget does not hold
/// the layer's gradient in place either: it moves and scales from the layer's bounds to the warped
/// square's bounds, as the art and inside the art.
#[test]
fn a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_follow_a_warp() {
use std::sync::Arc;
use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop};
use vectorcraft_doc::{AppearanceItem, FillLayer, LayerColor, NodeId, NodeKind, color::Paint};
let stops = vec![GradientStop::new(0.0, vectorcraft_color::Color::BLACK), GradientStop::new(1.0, vectorcraft_color::Color::WHITE)];
let geom = GradientGeom { start: (0.0, 50.0).into(), end: (100.0, 50.0).into(), aspect: 1.0, focal: None };
let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..GradientPaint::new(Gradient::new(GradientKind::Linear, stops)) }));
let ends = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.geom.map(|g| (g.start, g.end)),
_ => None,
};
let oval = || shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0));
// A layer with a visible square and a hidden circle, both 0..100, and a gradient fill of its own.
let layer = || {
let square = Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default()));
let mut circle = Node::path(NodeId(4), oval(), Appearance::default());
circle.visible = false;
let mut layer = Node::layer(NodeId(2), "Layer 1", LayerColor::Preset(0));
if let NodeKind::Layer { children, .. } = &mut layer.kind {
*children = vec![square, Arc::new(circle)];
}
layer.appearance.items.push(AppearanceItem::Fill(FillLayer::new(placed.clone())));
layer
};
// The box map from the layer's bounds (the square's) to `b`: (0, 50) and (100, 50) go to the
// middles of b's sides.
let near = |got: Option<(Point, Point)>, b: Rect| {
let mid = (b.y0 + b.y1) / 2.0;
got.is_some_and(|(s, e)| s.distance(Point::new(b.x0, mid)) < 1e-6 && e.distance(Point::new(b.x1, mid)) < 1e-6)
};
for style in ["arc", "inflate", "flag"] {
let warp = fx(&format!("warp.{style}"), json!({"bend": 40.0, "horizontal": 20.0}));
// Room for the warped square beside the circle as it was, and not for the warped circle
// beside the warped square: the paths take the budget in turn, so the circle keeps its shape.
let mut probe = layer();
crate::reshape::reshape_leaves_within(&mut probe, &[&warp], Budget::EFFECTS, None);
let warped = |k: usize| util::line_estimate(probe.children().unwrap()[k].path_data().unwrap());
let circle = util::line_estimate(&oval());
assert!(warped(1) > circle, "warp.{style}: the warped circle is drawn with more lines");
let budget = Budget { anchors: usize::MAX, lines: warped(0) + circle };
let mut art = layer();
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
assert_eq!(art.children().unwrap()[1].path_data(), Some(&oval()), "{}: the hidden circle keeps its shape", warp.id);
let square = art.children().unwrap()[0].geometric_bounds().unwrap();
assert!(square != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the square takes the effect: {square:?}", warp.id);
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert!(near(ends(&own), square), "{}: the layer's gradient, as the art: {:?} for {square:?}", warp.id, ends(&own));
let mut art = Node::group(NodeId(9), vec![Arc::new(layer())]);
crate::reshape::reshape_leaves_within(&mut art, &[&warp], budget, None);
let got = ends(&art.children().unwrap()[0].appearance);
assert!(near(got, square), "{}: the layer's gradient, inside the art: {got:?} for {square:?}", warp.id);
}
}
/// A freeform gradient whose points were edited moves its points with a Warp effect from the
/// bounds before the warp to the bounds after it, on a path, on a group inside the art and on the
/// art itself, as a placed gradient does.
#[test]
fn edited_freeform_points_follow_a_warp() {
use std::sync::Arc;
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint};
use vectorcraft_doc::{AppearanceItem, FillLayer, NodeId, color::Paint};
let mut ramp = GradientPaint::new(Gradient { kind: GradientKind::Freeform, ..Gradient::default() });
let pt = |x: f64, c| FreeformPoint::new(Point::new(x, 50.0), c);
ramp.set_freeform(Freeform { points: vec![pt(0.0, Color::BLACK), pt(100.0, Color::WHITE)], ..Default::default() });
assert!(ramp.geom.is_none() && !ramp.is_placed());
let freeform = Paint::Gradient(Box::new(ramp));
let points = |ap: &Appearance| match ap.fill_paint() {
Paint::Gradient(g) => g.freeform.as_ref().map(|f| f.points.iter().map(|p| p.at).collect::<Vec<_>>()),
_ => None,
};
let square = |ap: Appearance| Arc::new(Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), ap));
// The box map from the square's bounds to `b`: (0, 50) and (100, 50) go to the middles of b's sides.
let near = |got: Option<Vec<Point>>, b: Rect| {
let mid = (b.y0 + b.y1) / 2.0;
got.is_some_and(|p| p.len() == 2 && p[0].distance(Point::new(b.x0, mid)) < 1e-6 && p[1].distance(Point::new(b.x1, mid)) < 1e-6)
};
for style in ["arc", "inflate", "rise"] {
let e = fx(&format!("warp.{style}"), json!({"bend": 40.0, "vertical": 20.0}));
let mut inner = Node::group(NodeId(2), vec![square(Appearance::default())]);
inner.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let mut art = Node::group(NodeId(9), vec![square(Appearance::basic(freeform.clone(), Paint::None, 0.0)), Arc::new(inner)]);
art.appearance.items.push(AppearanceItem::Fill(FillLayer::new(freeform.clone())));
let carry = crate::reshape::reshape_leaves_within(&mut art, &[&e], Budget::EFFECTS, None);
let b = art.geometric_bounds().unwrap();
assert!(b != Rect::new(0.0, 0.0, 100.0, 100.0), "{}: the warp changes the bounds: {b:?}", e.id);
let members = art.children().unwrap();
assert!(near(points(&members[0].appearance), b), "{}: the path's points {:?} for {b:?}", e.id, points(&members[0].appearance));
assert!(near(points(&members[1].appearance), b), "{}: the inner group's points {:?} for {b:?}", e.id, points(&members[1].appearance));
let mut own = Appearance::clone(&art.appearance);
carry.apply(&mut own);
assert!(near(points(&own), b), "{}: the art's own points {:?} for {b:?}", e.id, points(&own));
}
}
/// A freeform gradient whose points were edited (its vector still fitted to the bounds) moves its
/// points with a Transform effect and Free Distort, on a path, on a group inside the art and on the
/// art itself, as a placed gradient does.
+338
View File
@@ -0,0 +1,338 @@
//! Outline Object on an image's own fill or stroke: the outline of the image's opaque area, for
//! every pixel format with alpha, and the frame for one without.
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{AppearanceItem, Document, Effect, FillLayer, ImageBlob, ImageObject, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, Rect};
use crate::*;
fn fx(id: &str) -> Effect {
Effect { id: id.into(), params: json!({}), visible: true }
}
/// `img` encoded as `format`.
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
let mut out = vec![];
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
out
}
/// A 100×100 RGBA image, transparent but for an opaque disc of radius 30 in its middle.
fn disc() -> image::DynamicImage {
image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(100, 100, |x, y| {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
image::Rgba([255, 0, 0, if r <= 30.0 { 255 } else { 0 }])
}))
}
/// A document holding the encoded image `bytes` (key "img") and an image object of 100×100 pixels
/// placed at (50, 50) with the appearance items `items`, the image's own row at `contents`.
/// → (document, the image's node).
fn image_doc(bytes: Vec<u8>, items: Vec<AppearanceItem>, contents: usize) -> (Document, Node) {
let mut d = Document::new(200.0, 200.0);
d.images.insert("img".into(), ImageBlob::new("image/png", bytes));
let mut n = Node::new(
NodeId(0),
NodeKind::Image(Box::new(ImageObject {
key: "img".into(),
width: 100,
height: 100,
xf: Affine::translate((50.0, 50.0)),
link: None,
placement: Default::default(),
pixels: None,
})),
);
n.id = d.alloc_id();
n.appearance.items = items;
n.appearance.set_contents_at(contents);
let l = d.layers[0].id;
d.insert(Some(l), 0, n.clone()).unwrap();
(d, n)
}
/// A PNG of `w × h` pixels with the color type `color` at `depth` bits, the chunks `extra` before
/// its pixels, and the filtered rows `rows` stored without compression.
fn png(w: u32, h: u32, color: u8, depth: u8, extra: &[(&[u8; 4], Vec<u8>)], rows: &[u8]) -> Vec<u8> {
fn crc(data: &[u8]) -> u32 {
let mut c = !0u32;
for &b in data {
c ^= u32::from(b);
for _ in 0..8 {
c = if c & 1 == 1 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 };
}
}
!c
}
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
let mut chunk = |kind: &[u8; 4], data: &[u8]| {
let mut body = kind.to_vec();
body.extend_from_slice(data);
out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
out.extend_from_slice(&body);
out.extend_from_slice(&crc(&body).to_be_bytes());
};
let mut ihdr = [w.to_be_bytes(), h.to_be_bytes()].concat();
ihdr.extend([depth, color, 0, 0, 0]);
chunk(b"IHDR", &ihdr);
for (kind, data) in extra {
chunk(kind, data);
}
// A zlib stream of stored blocks.
let mut z = vec![0x78, 0x01];
let blocks: Vec<&[u8]> = if rows.is_empty() { vec![rows] } else { rows.chunks(65_535).collect() };
for (i, block) in blocks.iter().enumerate() {
let len = u16::try_from(block.len()).unwrap();
z.push(u8::from(i + 1 == blocks.len()));
z.extend(len.to_le_bytes());
z.extend((!len).to_le_bytes());
z.extend_from_slice(block);
}
let (mut a, mut b) = (1u32, 0u32);
for &byte in rows {
a = (a + u32::from(byte)) % 65_521;
b = (b + a) % 65_521;
}
z.extend(((b << 16) | a).to_be_bytes());
chunk(b"IDAT", &z);
chunk(b"IEND", &[]);
out
}
fn stroke(effects: Vec<Effect>) -> AppearanceItem {
let mut s = StrokeLayer::new(Paint::solid(Color::BLACK), 4.0);
s.effects = effects;
AppearanceItem::Stroke(s)
}
/// The bounds of the paths the image's own fills and strokes paint, below it first.
fn row_bounds(d: &Document, n: &Node) -> Vec<Rect> {
let art = reshape::reshape(Some(d), n, None).unwrap();
let mut out = vec![];
for c in art.children().unwrap() {
if matches!(c.kind, NodeKind::Path { .. }) {
out.push(c.geometric_bounds().unwrap());
}
}
out
}
fn near(r: Rect, want: [f64; 4], tol: f64) -> bool {
[r.x0 - want[0], r.y0 - want[1], r.x1 - want[2], r.y1 - want[3]].iter().all(|d| d.abs() < tol)
}
#[test]
fn outline_object_follows_the_opaque_area_of_an_image_with_alpha() {
let gray_alpha = image::DynamicImage::ImageLumaA8(disc().to_luma_alpha8());
let deep = image::DynamicImage::ImageRgba16(disc().to_rgba16());
for (name, img) in [("rgba", disc()), ("gray and alpha", gray_alpha), ("16 bits a channel", deep)] {
let (d, n) = image_doc(encoded(img, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 1, "{name}");
// The disc runs from 70 to 130; the frame from 50 to 150.
assert!(near(rows[0], [70.0, 70.0, 130.0, 130.0], 0.5), "{name}: {:?}", rows[0]);
}
}
#[test]
fn outline_object_follows_the_frame_of_an_image_without_transparency() {
let opaque = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(100, 100, image::Rgb([0, 0, 255])));
let solid = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 255, 200])));
let formats = [
("jpeg", encoded(opaque.clone(), image::ImageFormat::Jpeg)),
("rgb png", encoded(opaque, image::ImageFormat::Png)),
("rgba png, every pixel more than half opaque", encoded(solid, image::ImageFormat::Png)),
];
for (name, bytes) in formats {
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert!(rows.len() == 1 && near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{name}: {rows:?}");
}
// Pixels that can't be read keep the frame too.
let (d, n) = image_doc(b"not an image".to_vec(), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(near(row_bounds(&d, &n)[0], [50.0, 50.0, 150.0, 150.0], 1e-9));
}
#[test]
fn convert_to_shape_keeps_the_frame_beside_outline_object() {
// Below the image: a fill with Convert to Shape, then a stroke with Outline Object; above it
// a stroke with Convert to Shape before Outline Object, which starts from the frame.
let rect = Effect { id: "convertToShape.rectangle".into(), params: json!({"relative": true, "extraW": 0, "extraH": 0}), visible: true };
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![rect.clone()];
let items = vec![AppearanceItem::Fill(fill), stroke(vec![fx("path.outlineObject")]), stroke(vec![rect, fx("path.outlineObject")])];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), items, 2);
let rows = row_bounds(&d, &n);
assert_eq!(rows.len(), 3, "{rows:?}");
assert!(near(rows[0], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
assert!(near(rows[1], [70.0, 70.0, 130.0, 130.0], 0.5), "{rows:?}");
assert!(near(rows[2], [50.0, 50.0, 150.0, 150.0], 1e-9), "{rows:?}");
// The image keeps its place between them.
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap()[2].kind, NodeKind::Image(_)));
}
#[test]
fn a_transparent_image_gives_outline_object_nothing_to_paint() {
let clear = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(100, 100, image::Rgba([0, 0, 0, 100])));
let (d, n) = image_doc(encoded(clear, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(row_bounds(&d, &n).is_empty());
let art = reshape::reshape(Some(&d), &n, None).unwrap();
assert!(matches!(art.children().unwrap().as_slice(), [only] if matches!(only.kind, NodeKind::Image(_))));
}
#[test]
fn the_outline_follows_the_images_own_pixels_and_placement() {
// Pixels kept on the image itself (art made outside a document), placed at half size.
let (_, mut n) = image_doc(vec![], vec![stroke(vec![fx("path.outlineObject")])], 1);
if let NodeKind::Image(im) = &mut n.kind {
im.pixels = Some(Arc::new(ImageBlob::new("image/png", encoded(disc(), image::ImageFormat::Png))));
im.xf = Affine::translate((10.0, 20.0)) * Affine::scale(0.5);
}
let art = reshape::reshape(None, &n, None).unwrap();
let b = art.children().unwrap()[0].geometric_bounds().unwrap();
// The disc runs from 20 to 80 pixels: half that, moved by (10, 20).
assert!(near(b, [20.0, 30.0, 50.0, 60.0], 0.3), "{b:?}");
}
#[test]
fn an_off_center_outline_turns_and_reflects_with_a_smaller_copy_of_the_pixels() {
// A 120×60 image whose opaque area is the rectangle from (12, 6) to (40, 24), its pixels a
// copy at half size (as a linked image's preview is), turned a quarter and reflected.
let half = image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(60, 30, |x, y| {
image::Rgba([255, 0, 0, if (6..20).contains(&x) && (3..12).contains(&y) { 255 } else { 0 }])
}));
let (d, mut n) = image_doc(encoded(half, image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let xf = Affine::translate((100.0, 40.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2) * Affine::scale_non_uniform(-1.0, 1.0);
if let NodeKind::Image(im) = &mut n.kind {
(im.width, im.height, im.xf) = (120, 60, xf);
}
let rows = row_bounds(&d, &n);
let want = xf.transform_rect_bbox(Rect::new(12.0, 6.0, 40.0, 24.0));
// The rectangle runs from (76, 0) to (94, 28); a flip in either direction, or the copy's
// width and height swapped, would move it.
assert!(near(want, [76.0, 0.0, 94.0, 28.0], 1e-9), "{want:?}");
assert!(rows.len() == 1 && near(rows[0], [want.x0, want.y0, want.x1, want.y1], 0.5), "{rows:?}");
}
#[test]
fn an_image_in_a_group_exports_with_its_outline() {
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let g = d.alloc_id();
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(n)])).unwrap();
let baked = bake_document(&d).unwrap();
let mut paths = vec![];
for layer in &baked.layers {
layer.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
paths.push(c.geometric_bounds().unwrap());
}
});
}
assert!(matches!(paths.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{paths:?}");
}
/// The bounds of the paths stroked 4 pt in `d` with its effects baked, as exports write it.
fn baked_strokes(d: &Document) -> Vec<Rect> {
let baked = bake_document(d).unwrap();
let mut paths = vec![];
for layer in &baked.layers {
layer.walk(&mut |c| {
if matches!(c.kind, NodeKind::Path { .. }) && (c.appearance.stroke_width() - 4.0).abs() < 1e-9 {
paths.push(c.geometric_bounds().unwrap());
}
});
}
paths
}
#[test]
fn an_image_under_a_clipping_mask_or_with_an_opacity_mask_exports_with_its_outline() {
let disc_outline = |paths: &[Rect]| matches!(paths, [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5));
// Under a clipping mask that covers the whole image.
let (mut d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let l = d.layers[0].id;
d.remove(n.id).unwrap();
let clip = Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
let g = d.alloc_id();
d.insert(Some(l), 0, Node::new(g, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(n)], clip: true })).unwrap();
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
// With an opacity mask.
let (mut d, mut n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let mut white = Node::path(NodeId(999), vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), Default::default());
white.appearance.set_fill(Paint::solid(Color::WHITE));
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(Node::group(NodeId(998), vec![Arc::new(white)]), true)));
let id = n.id;
*d.node_mut(id).unwrap() = n;
let paths = baked_strokes(&d);
assert!(disc_outline(&paths), "{paths:?}");
}
#[test]
fn outline_object_on_a_fill_and_on_an_indexed_image_follows_the_opaque_area() {
let mut fill = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
fill.effects = vec![fx("path.outlineObject")];
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![AppearanceItem::Fill(fill)], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
// A palette image whose first color is transparent (a tRNS chunk).
let mut rows = vec![];
for y in 0..100 {
rows.push(0);
for x in 0..100 {
let r = (f64::from(x) + 0.5 - 50.0).hypot(f64::from(y) + 0.5 - 50.0);
rows.push(u8::from(r <= 30.0));
}
}
let palette = png(100, 100, 3, 8, &[(b"PLTE", vec![0, 0, 0, 255, 0, 0]), (b"tRNS", vec![0, 255])], &rows);
let (d, n) = image_doc(palette, vec![stroke(vec![fx("path.outlineObject")])], 1);
let rows = row_bounds(&d, &n);
assert!(matches!(rows.as_slice(), [b] if near(*b, [70.0, 70.0, 130.0, 130.0], 0.5)), "{rows:?}");
}
#[test]
fn an_image_too_large_or_too_complex_to_outline_keeps_its_frame() {
// 72 megapixels at 8 bits a channel, and 42 at 16: refused before their pixels are read.
for (w, h, depth) in [(9000, 8000, 8), (7000, 6000, 16)] {
let bytes = png(w, h, 6, depth, &[], &[]);
assert!(matches!(vectorcraft_trace::decode_alpha(&bytes), Err(vectorcraft_trace::TraceError::TooLarge { .. })), "{w}×{h}");
let (d, n) = image_doc(bytes, vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)), "{w}×{h}");
}
// A checkerboard of 2 px squares, whose outline would need more than 100,000 anchor points.
let checker = image::RgbaImage::from_fn(640, 640, |x, y| image::Rgba([0, 0, 0, if (x / 2 + y / 2) % 2 == 0 { 255 } else { 0 }]));
let (d, n) =
image_doc(encoded(image::DynamicImage::ImageRgba8(checker), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
assert!(matches!(row_bounds(&d, &n).as_slice(), [b] if near(*b, [50.0, 50.0, 150.0, 150.0], 1e-9)));
}
#[test]
fn an_outline_is_traced_once_for_its_pixels_and_dropped_with_them() {
let traces = || reshape::TRACES.with(std::cell::Cell::get);
let (d, n) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![stroke(vec![fx("path.outlineObject")])], 1);
let NodeKind::Image(im) = &n.kind else { panic!("not an image") };
let before = traces();
let first = reshape::opaque_area(&[Some(&d)], im).unwrap();
assert_eq!(traces(), before + 1);
for _ in 0..3 {
row_bounds(&d, &n);
}
assert_eq!(reshape::opaque_area(&[Some(&d)], im).unwrap(), first);
assert_eq!(traces(), before + 1);
let pixels = Arc::downgrade(&d.images.get(&im.key).unwrap().bytes);
assert!(reshape::keeps_outline(&pixels));
// Once the document and its pixels are gone, the next trace drops their entry.
drop(d);
assert!(pixels.upgrade().is_none());
let (other, _) = image_doc(encoded(disc(), image::ImageFormat::Png), vec![], 1);
reshape::opaque_area(&[Some(&other)], im).unwrap();
assert_eq!(traces(), before + 2);
assert!(!reshape::keeps_outline(&pixels));
}
+652
View File
@@ -0,0 +1,652 @@
//! Raster effects listed before a Transform effect follow it: the Transform effect transforms
//! what they paint.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
use vectorcraft_geom::{Rect, shapes};
use crate::{RasterFx, bake_document, expand_outlined, raster_effects};
fn fx(id: &str, params: Value) -> Effect {
Effect { id: id.into(), params, visible: true }
}
fn shadow(x: f64, y: f64, blur: f64) -> Effect {
fx("stylize.dropShadow", json!({"x": x, "y": y, "blur": blur}))
}
fn transform(params: Value) -> Effect {
fx("distort.transform", params)
}
/// The offset and blur of the first Drop Shadow `effects` draw.
fn drawn_shadow(effects: &[Effect]) -> (f64, f64, f64) {
match raster_effects(effects).first() {
Some(RasterFx::DropShadow { dx, dy, blur, .. }) => (*dx, *dy, *blur),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
fn close(a: (f64, f64, f64), b: (f64, f64, f64)) -> bool {
(a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 && (a.2 - b.2).abs() < 1e-9
}
/// A 50 pt red square with `effects`.
fn square(id: u64, effects: Vec<Effect>) -> Node {
let mut n = Node::path(
NodeId(id),
shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)),
Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0),
);
n.appearance.effects = effects;
n
}
#[test]
fn a_transform_after_a_drop_shadow_scales_its_offset_and_blur() {
for strokes in [false, true] {
let effects = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200, "strokes": strokes}))];
assert!(close(drawn_shadow(&effects), (20.0, 20.0, 8.0)), "Scale Strokes & Effects {strokes}: {:?}", drawn_shadow(&effects));
}
}
#[test]
fn a_drop_shadow_after_a_transform_keeps_its_offset() {
let effects = [transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 10.0, 4.0)];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
}
#[test]
fn the_offset_follows_an_uneven_scale_a_rotation_and_a_reflection() {
let uneven = [shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 100}))];
assert!(close(drawn_shadow(&uneven), (20.0, 10.0, 4.0 * 2f64.sqrt())), "{:?}", drawn_shadow(&uneven));
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
let turned = [shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90}))];
let (dx, dy, blur) = drawn_shadow(&turned);
assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9 && (blur - 4.0).abs() < 1e-9, "{dx} {dy} {blur}");
let reflected = [shadow(10.0, 0.0, 4.0), transform(json!({"reflectX": true}))];
assert!(close(drawn_shadow(&reflected), (-10.0, 0.0, 4.0)), "{:?}", drawn_shadow(&reflected));
}
#[test]
fn transforms_after_the_shadow_apply_in_order() {
let effects = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(json!({"rotate": 90}))];
let (dx, dy, _) = drawn_shadow(&effects);
assert!(dx.abs() < 1e-9 && (dy + 20.0).abs() < 1e-9, "{dx} {dy}");
// Only the Transform after a shadow moves it.
let between = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), shadow(0.0, 10.0, 0.0)];
let drawn = raster_effects(&between);
let offsets: Vec<(f64, f64)> = drawn
.iter()
.filter_map(|r| match r {
RasterFx::DropShadow { dx, dy, .. } => Some((*dx, *dy)),
_ => None,
})
.collect();
assert_eq!(offsets, vec![(20.0, 0.0), (0.0, 10.0)]);
}
#[test]
fn transforms_that_leave_the_art_or_copy_it_leave_the_shadow() {
for params in [
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "copies": 1}),
json!({"scaleH": 200, "scaleV": 200, "random": true}),
] {
let effects = [shadow(10.0, 10.0, 4.0), transform(params.clone())];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{params}: {:?}", drawn_shadow(&effects));
}
let mut hidden = transform(json!({"scaleH": 200, "scaleV": 200}));
hidden.visible = false;
let effects = [shadow(10.0, 10.0, 4.0), hidden];
assert!(close(drawn_shadow(&effects), (10.0, 10.0, 4.0)), "{:?}", drawn_shadow(&effects));
}
/// A hidden shadow kept when the Transform effect is applied (Expand Appearance) draws as it would
/// have before, once it is shown.
#[test]
fn a_hidden_shadow_follows_the_transform_it_loses() {
let mut hidden = shadow(10.0, 10.0, 4.0);
hidden.visible = false;
let kept = crate::raster::without_geometry(&[hidden, transform(json!({"scaleH": 200, "scaleV": 200}))]);
assert_eq!(kept.len(), 1);
let mut shown = kept[0].clone();
shown.visible = true;
assert!(close(drawn_shadow(&[shown]), (20.0, 20.0, 8.0)));
}
/// Rasterize keeps its room around the art: its image keeps its own pixel grid.
#[test]
fn rasterize_before_a_transform_keeps_its_options() {
let rasterize = fx(crate::RASTERIZE, json!({"addAround": 6}));
let effects = [rasterize.clone(), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::raster::followed(&effects)[0], rasterize);
assert_eq!(crate::raster::without_geometry(&effects), vec![rasterize]);
}
/// An SVG filter keeps its options: it paints in its own user space.
#[test]
fn an_svg_filter_before_a_transform_keeps_its_options() {
let filter = fx(crate::SVG_FILTER, json!({"origin": [10, 10]}));
let effects = [filter.clone(), transform(json!({"scaleH": 200, "scaleV": 200, "rotate": 90}))];
assert_eq!(crate::raster::followed(&effects)[0], filter);
assert_eq!(crate::raster::without_geometry(&effects), vec![filter]);
}
/// The offset of every Drop Shadow drawn on `n` and the nodes under it, from the object's effects
/// and from each fill's and stroke's.
fn shadows_in(n: &Node) -> Vec<(f64, f64)> {
let mut out = vec![];
n.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
for list in lists {
for r in raster_effects(list) {
if let RasterFx::DropShadow { dx, dy, .. } = r {
out.push((dx, dy));
}
}
}
});
out
}
fn near(a: &[(f64, f64)], b: &[(f64, f64)]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(p, q)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9)
}
/// A square whose fill carries `effects` of its own.
fn fill_square(id: u64, effects: Vec<Effect>) -> Node {
let mut n = square(id, vec![]);
if let Some(item) = n.appearance.items.first_mut() {
*item.effects_mut() = effects;
}
n
}
/// A fill's own Transform effect transforms the fill's raster effects before it: drawn as they are
/// (no options), drawn through the art the Transform Patterns or Scale Strokes & Effects option
/// makes, expanded and baked. Scale Strokes & Effects does not scale a shadow that follows the
/// Transform effect a second time.
#[test]
fn a_fills_shadow_follows_the_fills_own_transform() {
let cases = [
(json!({"rotate": 90}), (0.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (0.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "strokes": true}), (20.0, 0.0)),
(json!({"scaleH": 200, "scaleV": 200, "patterns": true}), (20.0, 0.0)),
(json!({"reflectX": true, "patterns": true}), (-10.0, 0.0)),
];
for (params, want) in cases {
let n = fill_square(11, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
// Drawn and expanded through its art when an option makes some.
if crate::has_transform_art(&n) {
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[want]), "{params}: drawn {:?}", shadows_in(&art));
let expanded = expand_outlined(None, &n, None).unwrap();
assert!(near(&shadows_in(&expanded), &[want]), "{params}: expanded {:?}", shadows_in(&expanded));
} else {
assert!(near(&shadows_in(&n), &[want]), "{params}: drawn {:?}", shadows_in(&n));
}
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let b = baked.node(NodeId(11)).unwrap();
assert!(near(&shadows_in(b), &[want]), "{params}: baked {:?}", shadows_in(b));
}
}
/// A Transform effect after a fill's own Transform effect with Scale Strokes & Effects on turns the
/// shadow between them, which the first one leaves as it is; a Transform effect that moves at random
/// holds the shadow before it back from the Transform effects after it.
#[test]
fn a_fills_later_transform_turns_the_shadow_after_its_first() {
let n = fill_square(
12,
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90}))],
);
let art = crate::reshape(None, &n, None).unwrap();
assert!(near(&shadows_in(&art), &[(0.0, -10.0)]), "{:?}", shadows_in(&art));
let held = fill_square(
13,
vec![
shadow(10.0, 0.0, 0.0),
transform(json!({"scaleH": 200, "scaleV": 200, "random": true, "strokes": true})),
transform(json!({"rotate": 90})),
],
);
let art = crate::reshape(None, &held, None).unwrap();
let drawn = shadows_in(&art);
assert!(drawn.len() == 1 && drawn[0].0 > 0.0 && drawn[0].1.abs() < 1e-9, "{drawn:?}");
}
/// A fill's own Transform effect with Transform Patterns or Scale Strokes & Effects on leaves the
/// fill's raster effects after it as they are: they paint around the transformed art, its copies
/// included. With Transform Objects off it leaves the raster effects before it as they are too.
/// Drawn, expanded and baked alike.
#[test]
fn a_fills_own_transform_leaves_the_shadow_after_it() {
let cases = [
vec![transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 120, "copies": 1, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true})), shadow(10.0, 0.0, 0.0)],
vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}))],
// A later Transform effect with an option leaves the shadow after it as well.
vec![
transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true})),
transform(json!({"scaleH": 150, "scaleV": 150, "strokes": true})),
shadow(10.0, 0.0, 0.0),
],
];
for effects in cases {
let n = fill_square(18, effects.clone());
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{effects:?}: drawn {drawn:?}");
let expanded = shadows_in(&expand_outlined(None, &n, None).unwrap());
assert!(!expanded.is_empty() && near(&expanded, &vec![(10.0, 0.0); expanded.len()]), "{effects:?}: expanded {expanded:?}");
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let b = shadows_in(baked.node(NodeId(18)).unwrap());
assert!(!b.is_empty() && near(&b, &vec![(10.0, 0.0); b.len()]), "{effects:?}: baked {b:?}");
}
}
/// A geometry effect after a fill's own Transform effect with Scale Strokes & Effects on reshapes
/// the transformed art by its own distance, as it does after an object's Transform effect.
#[test]
fn a_fills_own_transform_leaves_the_offset_after_it() {
let offset = fx("path.offsetPath", json!({"offset": 5}));
let scaled = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
let n = fill_square(19, vec![scaled.clone(), offset.clone()]);
let on_fill = crate::reshape(None, &n, None).unwrap();
let on_object = crate::reshape(None, &square(20, vec![scaled, offset]), None).unwrap();
let (fill, object) = (on_fill.geometric_bounds().unwrap(), on_object.geometric_bounds().unwrap());
// The 50 pt square scaled to 100 pt about its center, then offset by 5 pt on each side.
assert!((fill.width() - 110.0).abs() < 1e-6 && (fill.height() - 110.0).abs() < 1e-6, "{fill:?}");
assert!((fill.width() - object.width()).abs() < 1e-6 && (fill.x0 - object.x0).abs() < 1e-6, "{fill:?} {object:?}");
let expanded = expand_outlined(None, &n, None).unwrap().geometric_bounds().unwrap();
assert!((expanded.width() - 110.0).abs() < 1e-6 && (expanded.x0 - fill.x0).abs() < 1e-6, "expanded {expanded:?}");
}
/// The SVG filters on `n` and the nodes under it, from the object's effects and from each fill's
/// and stroke's.
fn filters_in(n: &Node) -> Vec<Effect> {
let mut out = vec![];
n.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
out.extend(lists.flatten().filter(|e| e.id == crate::SVG_FILTER).cloned());
});
out
}
/// An SVG filter after a fill's own Transform effect with Scale Strokes & Effects on keeps its
/// scale and the origin of its user space, as it does after the same Transform effect without
/// options and after an object's own Transform effect.
#[test]
fn a_fills_own_transform_leaves_the_svg_filter_after_it() {
let filter = fx(crate::SVG_FILTER, json!({"scale": 1.0, "origin": [10.0, 10.0]}));
for params in [
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "patterns": true}),
json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1, "strokes": true}),
json!({"scaleH": 200, "scaleV": 200, "objects": false, "strokes": true}),
] {
let art = crate::reshape(None, &fill_square(21, vec![transform(params.clone()), filter.clone()]), None).unwrap();
let drawn = filters_in(&art);
assert!(!drawn.is_empty() && drawn.iter().all(|e| *e == filter), "{params}: {drawn:?}");
}
let object = square(22, vec![transform(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "strokes": true})), filter.clone()]);
let art = crate::reshape(None, &object, None).unwrap();
assert!(!filters_in(&art).is_empty() && filters_in(&art).iter().all(|e| *e == filter), "{:?}", filters_in(&art));
}
/// The 3D effects keep the shadow before a Transform effect that shapes the art they project, the
/// object's and its fill's 3D effect alike.
#[test]
fn a_shadow_before_a_transform_follows_it_into_3d_art() {
let before = vec![shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let mut on_object = before.clone();
on_object.push(fx(three_d, json!({})));
let projected = art(&square(14, on_object)).unwrap();
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the object: {:?}", shadows_in(&projected));
let mut on_fill = square(15, before.clone());
if let Some(item) = on_fill.appearance.items.first_mut() {
*item.effects_mut() = vec![fx(three_d, json!({}))];
}
let projected = art(&on_fill).unwrap();
assert!(near(&shadows_in(&projected), &[(20.0, 0.0)]), "{three_d} on the fill: {:?}", shadows_in(&projected));
}
}
/// An object's Transform effect transforms the raster effects of its fills when only a fill has a
/// 3D effect: the shadow after that fill's 3D effect and another fill's shadow, as it does without
/// the 3D effect.
#[test]
fn an_objects_transform_moves_its_fills_shadows_beside_a_fills_3d_effect() {
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let mut n = fill_square(18, vec![fx(three_d, json!({})), shadow(10.0, 10.0, 0.0)]);
let mut other = n.appearance.items[0].clone();
*other.effects_mut() = vec![shadow(10.0, 10.0, 0.0)];
n.appearance.items.push(other);
n.appearance.effects = vec![transform(json!({"scaleH": 200, "scaleV": 100}))];
let drawn = shadows_in(&art(&n).unwrap());
assert!(drawn.len() > 1 && near(&drawn, &vec![(20.0, 10.0); drawn.len()]), "{three_d}: {drawn:?}");
}
}
#[test]
fn glows_blurs_and_feathers_scale_with_the_transform_after_them() {
let effects = [
fx("stylize.outerGlow", json!({"blur": 5})),
fx("stylize.innerGlow", json!({"blur": 5})),
fx("stylize.feather", json!({"radius": 5})),
fx("blur.gaussian", json!({"radius": 5})),
transform(json!({"scaleH": 50, "scaleV": 50})),
];
let sizes: Vec<f64> = raster_effects(&effects)
.iter()
.map(|r| match r {
RasterFx::OuterGlow { blur, .. } | RasterFx::InnerGlow { blur, .. } => *blur,
RasterFx::Feather { radius } | RasterFx::GaussianBlur { radius, .. } => *radius,
other => panic!("unexpected {other:?}"),
})
.collect();
assert_eq!(sizes, vec![2.5; 4]);
// How far the shadow paints past the object follows too.
let shadowed = [shadow(10.0, 10.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
assert_eq!(crate::outset(&shadowed, Rect::new(0.0, 0.0, 100.0, 100.0)), 20.0);
}
#[test]
fn pixel_filter_sizes_scale_with_the_transform_after_them() {
let effects = [
fx("artistic.coloredPencil", json!({"pencilWidth": 5})),
fx("artistic.paintDaubs", json!({"brushSize": 10})),
transform(json!({"scaleH": 200, "scaleV": 200})),
];
let drawn = raster_effects(&effects);
assert!(matches!(drawn.first(), Some(RasterFx::Pixel(crate::PixelFx::ColoredPencil { width, .. })) if (width - 10.0).abs() < 1e-9), "{drawn:?}");
assert!(matches!(drawn.get(1), Some(RasterFx::Pixel(crate::PixelFx::PaintDaubs { size, .. })) if (size - 20.0).abs() < 1e-9), "{drawn:?}");
}
/// A Transform effect after a 3D effect that makes copies or moves at random holds back the shadow
/// before the 3D effect, as it does without the 3D effect.
#[test]
fn a_copying_transform_after_3d_holds_the_shadow_back() {
for later in [json!({"copies": 1}), json!({"scaleH": 150, "scaleV": 150, "random": true})] {
let plain = [shadow(10.0, 0.0, 0.0), transform(json!({"scaleH": 200, "scaleV": 200})), transform(later.clone())];
assert!(close(drawn_shadow(&plain), (10.0, 0.0, 0.0)), "{later}: {:?}", drawn_shadow(&plain));
for three_d in [crate::EXTRUDE, crate::REVOLVE] {
let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) };
let effects = vec![plain[0].clone(), plain[1].clone(), fx(three_d, json!({})), plain[2].clone()];
let projected = art(&square(16, effects)).unwrap();
let drawn = shadows_in(&projected);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{three_d} {later}: {drawn:?}");
}
}
}
/// In a fill's own effects, a Transform effect that makes copies after a Transform effect with
/// Transform Patterns on holds back the shadow before both, and before a Transform effect between
/// them.
#[test]
fn a_fills_copying_transform_holds_back_the_shadow_before_an_earlier_transform() {
let patterns = transform(json!({"scaleH": 200, "scaleV": 200, "patterns": true}));
let copies = transform(json!({"copies": 1}));
let lists = [
vec![shadow(10.0, 0.0, 0.0), patterns.clone(), copies.clone()],
vec![shadow(10.0, 0.0, 0.0), patterns, transform(json!({"rotate": 90})), copies],
];
for effects in lists {
let n = fill_square(17, effects.clone());
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 0.0); drawn.len()]), "{} effects: {drawn:?}", effects.len());
}
}
#[test]
fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() {
let effects = vec![shadow(10.0, 10.0, 4.0), transform(json!({"scaleH": 200, "scaleV": 200}))];
// A path drawn through its art (Scale Strokes & Effects on), expanded.
let mut with_options = effects.clone();
with_options[1] = transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
let n = square(7, with_options);
let expanded = expand_outlined(None, &n, None).unwrap();
assert!(close(drawn_shadow(&expanded.appearance.effects), (20.0, 20.0, 8.0)), "{:?}", expanded.appearance.effects);
// A path and a group, baked for export.
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, square(8, effects.clone())).unwrap();
let mut g = Node::group(NodeId(9), vec![std::sync::Arc::new(square(10, vec![]))]);
g.appearance.effects = effects.clone();
d.insert(Some(layer), 1, g).unwrap();
let baked = bake_document(&d).unwrap();
for id in [8, 9] {
let b = baked.node(NodeId(id)).unwrap();
assert!(!b.appearance.effects.iter().any(|e| e.id == "distort.transform"), "{id}: {:?}", b.appearance.effects);
assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects);
}
}
/// A group of `members` with `effects` of its own.
fn group(id: u64, members: Vec<Node>, effects: Vec<Effect>) -> Node {
let mut g = Node::group(NodeId(id), members.into_iter().map(std::sync::Arc::new).collect());
g.appearance.effects = effects;
g
}
/// The node with `id` under `n`.
fn node_in(n: &Node, id: u64) -> Node {
let mut found = None;
n.walk(&mut |m| {
if m.id == NodeId(id) && found.is_none() {
found = Some(m.clone());
}
});
found.unwrap_or_else(|| panic!("no node {id}"))
}
/// The offset of the Drop Shadow that the first fill of `n` draws, its own effects and `n`'s
/// Transform effects applied ([`crate::item_effects_in`]).
fn fill_shadow(n: &Node) -> (f64, f64) {
let item = n.appearance.items.first().unwrap();
match raster_effects(&crate::item_effects_in(&n.appearance.effects, item.effects())).first() {
Some(RasterFx::DropShadow { dx, dy, .. }) => (*dx, *dy),
other => panic!("expected a drop shadow, got {other:?}"),
}
}
/// A group's Transform effect transforms the raster effects of what the group holds with the art,
/// whatever its options: a member's own shadow, a member's fill's shadow and a nested group's own
/// shadow, drawn (the group's art) and baked.
#[test]
fn a_groups_transform_moves_its_members_shadows() {
let cases = [
(json!({"scaleH": 200, "scaleV": 200}), (20.0, 20.0)),
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
];
for (params, want) in cases {
let members = vec![
square(21, vec![shadow(10.0, 10.0, 0.0)]),
fill_square(22, vec![shadow(10.0, 10.0, 0.0)]),
group(23, vec![square(24, vec![])], vec![shadow(10.0, 10.0, 0.0)]),
];
let g = group(20, members, vec![transform(params.clone())]);
let art = crate::evaluate_container(None, &g).unwrap();
assert!(near(&shadows_in(&art), &[want; 3]), "{params}: drawn {:?}", shadows_in(&art));
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, g).unwrap();
let baked = bake_document(&d).unwrap();
for id in [21, 22, 23] {
let b = baked.node(NodeId(id)).unwrap();
assert!(near(&shadows_in(b), &[want]), "{params}: {id} baked {:?}", shadows_in(b));
}
}
}
/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as
/// they are, as it leaves the shadows listed before it in its own effects.
#[test]
fn a_groups_copying_transform_leaves_its_members_shadows() {
for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] {
let g = group(25, vec![square(26, vec![shadow(10.0, 10.0, 0.0)]), square(27, vec![])], vec![transform(params.clone())]);
let art = crate::evaluate_container(None, &g).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 10.0); drawn.len()]), "{params}: {drawn:?}");
}
}
/// The Transform effects inside a group apply before the group's: a member's own turn of 90°
/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its
/// fill's shadow, and the shadow of a member of a nested group that has the turn.
#[test]
fn a_groups_transform_applies_after_its_members_own() {
let turn = || transform(json!({"rotate": 90}));
let uneven = || transform(json!({"scaleH": 200, "scaleV": 100}));
// Turned first, (10, 0) goes to (0, -10), which the scale leaves; scaled first, it would be (0, -20).
let want = (0.0, -10.0);
let own = group(30, vec![square(31, vec![shadow(10.0, 0.0, 0.0), turn()])], vec![uneven()]);
let art = crate::evaluate_container(None, &own).unwrap();
assert!(near(&shadows_in(&art), &[want]), "own: {:?}", shadows_in(&art));
let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]);
on_fill.appearance.effects = vec![turn()];
let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap();
assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33)));
let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]);
let art = crate::evaluate_container(None, &nested).unwrap();
let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap();
assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner));
}
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
/// makes copies leaves them.
#[test]
fn an_objects_transform_moves_its_fills_shadows() {
let cases = [
(json!({"scaleH": 200, "scaleV": 100}), (20.0, 10.0)),
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
];
for (params, want) in cases {
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
n.appearance.effects = vec![transform(params.clone())];
if crate::has_transform_art(&n) {
let art = crate::reshape(None, &n, None).unwrap();
let drawn = shadows_in(&art);
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: drawn {drawn:?}");
} else {
assert!(near(&[fill_shadow(&n)], &[want]), "{params}: drawn {:?}", fill_shadow(&n));
}
let mut d = Document::new(800.0, 800.0);
let layer = d.layers[0].id;
d.insert(Some(layer), 0, n).unwrap();
let baked = bake_document(&d).unwrap();
let drawn = shadows_in(baked.node(NodeId(40)).unwrap());
assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: baked {drawn:?}");
}
}
/// A 10 pt image at the origin with `effects`.
fn image(id: u64, effects: Vec<Effect>) -> Node {
let mut n = Node::new(
NodeId(id),
vectorcraft_doc::NodeKind::Image(Box::new(vectorcraft_doc::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
})),
);
n.appearance.effects = effects;
n
}
/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster
/// effects that a member's own Transform effect with copies holds back: they keep their value
/// through the member's effect and transform with the group's. That holds for a shadow listed
/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow
/// of a member of a nested group with such an effect, and an image's shadow.
#[test]
fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() {
let copies = || transform(json!({"moveH": 60, "copies": 1}));
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5).
let want = (5.0, -5.0);
for strokes in [false, true] {
let mut on_fill = fill_square(73, vec![shadow(10.0, 10.0, 0.0)]);
on_fill.appearance.effects = vec![copies()];
let members = vec![
square(71, vec![shadow(10.0, 10.0, 0.0), copies()]),
square(72, vec![copies(), shadow(10.0, 10.0, 0.0)]),
on_fill,
group(74, vec![square(75, vec![shadow(10.0, 10.0, 0.0)])], vec![copies()]),
image(76, vec![shadow(10.0, 10.0, 0.0)]),
];
let g = group(70, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
let art = crate::evaluate_container(None, &g).unwrap();
for id in [71, 72, 73, 75, 76] {
let drawn = shadows_in(&node_in(&art, id));
assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
/// A group's Transform effect transforms the raster effects in the art of a member's linked opacity
/// mask with the member, a path's or an image's, with Scale Strokes & Effects off or on.
#[test]
fn a_groups_transform_moves_the_shadow_in_a_members_mask() {
let masked = |mut n: Node, id: u64| {
n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(square(id, vec![shadow(10.0, 10.0, 0.0)]), true)));
n
};
for strokes in [false, true] {
let params = json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes});
let g = group(80, vec![masked(square(81, vec![]), 82), masked(image(83, vec![]), 84)], vec![transform(params)]);
let art = crate::evaluate_container(None, &g).unwrap();
for id in [81, 83] {
let member = node_in(&art, id);
let mask = member.extras().mask.as_deref().unwrap();
assert!(near(&shadows_in(&mask.art), &[(5.0, -5.0)]), "Scale Strokes & Effects {strokes}: {id} {:?}", shadows_in(&mask.art));
}
}
}
/// A group's Transform effect transforms the shadows of its members' fills that carry a Transform
/// effect of their own with Scale Strokes & Effects on, with the group's Scale Strokes & Effects off
/// or on: a shadow listed after the fill's Transform effect keeps its value through that effect and
/// transforms with the group's, and one listed before it follows the fill's Transform effect and
/// then the group's. Drawn through each member's art.
#[test]
fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform() {
let scaled = || transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true}));
// Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5); doubled first by
// the fill's own Transform effect, it goes to (10, -10).
let cases = [(91, vec![scaled(), shadow(10.0, 10.0, 0.0)], (5.0, -5.0)), (92, vec![shadow(10.0, 10.0, 0.0), scaled()], (10.0, -10.0))];
for strokes in [false, true] {
let members = cases.iter().map(|(id, effects, _)| fill_square(*id, effects.clone())).collect();
let g = group(90, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]);
let art = crate::evaluate_container(None, &g).unwrap();
for (id, _, want) in &cases {
let member = node_in(&art, *id);
let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap());
assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}");
}
}
}
+3 -3
View File
@@ -222,7 +222,7 @@ fn each_copy_of_a_strokes_own_transform_scales_its_weight_once_more() {
}
#[test]
fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects() {
fn a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects() {
let mut n = stroke_with_effect(json!({}));
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() {
f.effects.push(transform(json!({"scaleH": 300, "scaleV": 300, "strokes": true})));
@@ -231,10 +231,10 @@ fn a_fills_own_transform_with_scale_strokes_and_effects_scales_its_later_effects
let art = reshape(None, &n, None).unwrap();
let fill = leaves(&art).into_iter().find(|p| p.appearance.stroke().is_none()).unwrap();
let AppearanceItem::Fill(f) = &fill.appearance.items[0] else { panic!("not a fill") };
// The Offset Path, scaled from 5 to 15, applies to the transformed fill's path.
// The Offset Path applies to the transformed fill's path at its own 5 pt.
assert!(f.effects.is_empty(), "{:?}", f.effects);
let w = fill.geometric_bounds().unwrap().width();
assert!(close(w, 330.0), "{w}");
assert!(close(w, 310.0), "{w}");
}
#[test]
+21 -3
View File
@@ -6,20 +6,38 @@
use std::sync::Arc;
use vectorcraft_doc::{CharStyle, Node, NodeId, NodeKind, TextObject};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_geom::{Point, Rect, Shape};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
/// The largest distance between the edges of `a` and `b`.
fn off(a: Rect, b: Rect) -> f64 {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()))
}
/// "Type" at 48 pt in a face the test adds, so its glyphs draw on a machine without craft-fonts or
/// system fonts.
fn type_in_test_face() -> TextObject {
assert!(vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap()) > 0, "the test face loads");
TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { font_family: HEIGHT_FAMILY.into(), size: 48.0, ..Default::default() })
}
/// The box of the outlines `t`'s glyphs draw, in document space, measured glyph by glyph.
fn outline_box(t: &TextObject) -> Rect {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let outlines: Vec<Rect> = laid.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| (t.xf * &g.outline).bounding_box()).collect();
assert_eq!(outlines.len(), 4, "every glyph of \"Type\" draws an outline");
outlines.into_iter().reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn live_evaluation_measures_type_in_envelopes_by_its_glyphs() {
let t = TextObject::point(Point::new(10.0, 60.0), "Type", CharStyle { size: 48.0, ..Default::default() });
let t = type_in_test_face();
let n = Arc::new(Node::new(NodeId(1), NodeKind::Text(Box::new(t.clone()))));
let laid = n.geometric_bounds().unwrap();
let ink = t.xf.transform_rect_bbox(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).ink_bounds().unwrap());
let ink = outline_box(&t);
assert!(laid.height() - ink.height() > 1.0, "the laid-out box {laid:?} reaches past the glyphs {ink:?}");
let measured = vectorcraft_text::envelope_ink(&t, t.xf, None).unwrap();
assert!(off(measured, ink) < 1e-6, "the envelope measure gives the glyphs' box: {measured:?} vs {ink:?}");
let before = vectorcraft_doc::live::envelope_content_bounds(std::slice::from_ref(&n)).unwrap();
assert!(off(before, laid) < 1e-6, "with nothing registered, type keeps its laid-out box: {before:?} vs {laid:?}");
+14 -3
View File
@@ -4,6 +4,8 @@ pub mod actionset;
mod addons;
mod apiref;
pub(crate) mod appearance;
pub mod arrowheads;
mod artboardalign;
mod assets;
mod attributes;
pub mod brushlib;
@@ -80,7 +82,7 @@ pub mod rasterfx;
mod recolor;
pub mod recovery;
pub mod scripts;
mod select;
pub(crate) mod select;
pub(crate) mod shaper;
pub mod shortcutset;
pub(crate) mod slices;
@@ -105,6 +107,7 @@ mod variablecmds;
pub(crate) mod views;
pub mod wand;
pub mod webexport;
mod wireframe;
mod xform;
use serde::Serialize;
@@ -297,6 +300,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
// Split out of `paint` (M3.8); kept next to it so lists in registry order (the command
// palette, `engine.commands`) show them where they always were.
v.extend(stroke::specs());
v.extend(arrowheads::specs());
v.extend(appearance::specs());
v.extend(style::specs());
v.extend(swatch::specs());
@@ -308,6 +312,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(draw2::specs());
v.extend(xform::specs());
v.extend(effectcmd::specs());
v.extend(wireframe::specs());
v.extend(pathops::specs());
v.extend(compoundshape::specs());
v.extend(typecmd::specs());
@@ -334,6 +339,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(variablecmds::specs());
v.extend(docinfo::specs());
v.extend(panelcmds::specs());
v.extend(artboardalign::specs());
v.extend(buildcmds::specs());
v.extend(shaper::specs());
v.extend(brushsym::specs());
@@ -420,8 +426,13 @@ pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
pub(crate) fn f64_or(p: &Value, key: &str, default: f64) -> f64 {
p.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The number `p` gives for `key`. A missing key or null is "missing number `{key}`"; any other
/// value, such as `"40"`, is "`{key}` must be a number, not {v}", as [`number_or`] words it.
pub(crate) fn f64_req(p: &Value, key: &str, cmd: &str) -> Result<f64> {
p.get(key).and_then(Value::as_f64).ok_or_else(|| bad(cmd, format!("missing number `{key}`")))
match p.get(key) {
None | Some(Value::Null) => Err(bad(cmd, format!("missing number `{key}`"))),
Some(v) => v.as_f64().ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))),
}
}
/// The number `p` gives for `key`, or `default` when `p` leaves it out or gives null. Any other
/// value, such as `"40"`, is an error: "`{key}` must be a number, not {v}".
@@ -766,7 +777,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap<
/// The most presets one presets file imports: each is looked up among the saved ones.
pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::DecodedImages;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
pub use docmenu::guide_indexes;
pub(crate) use edit::{settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+1 -1
View File
@@ -14,7 +14,7 @@ mod select;
mod shapes;
mod typetools;
pub(crate) use image::DecodedImages;
pub(crate) use image::{DecodedImages, refresh_color_masks};
use super::CommandSpec;
+6 -5
View File
@@ -12,7 +12,7 @@ use vectorcraft_doc::{CharStyle, Document, Justify, Node, NodeId, NodeKind, Para
use vectorcraft_geom::{Affine, Point, Vec2};
use vectorcraft_text::{FontDb, FontMatch, TextLayout, edit};
use crate::cmd::fonts::{edit_symbol_texts, symbol_texts};
use crate::cmd::fonts::{art_texts_of, edit_art_texts_of};
use crate::cmd::textedit::{editing_range, editing_story};
use crate::cmd::typecmd::refresh_bounds;
use crate::cmd::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
@@ -108,7 +108,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Missing Fonts…",
["Object", "Plug-ins", "Artwork Cleanup"],
None,
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in the art of its symbols included) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
"{font?: family (default: the default type font, Source Sans 3; any of its names)} set every character of the document's type (the type in its opacity masks and in the art of its symbols and patterns included, hidden or locked type and disabled masks too) whose font family isn't available in `font`, in the style it has closest to the one each had, as one undo step → {runs (style runs changed), font}",
has_doc,
replace_fonts
),
@@ -982,8 +982,9 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The type in the symbols' art too, which exports name when its font is missing.
if ids.is_empty() && !symbol_texts(d, None).into_iter().any(|(t, _)| lacks(t)) {
// The type in opacity masks and in the art of symbols and patterns too, hidden or locked type
// included, which exports name when its font is missing.
if ids.is_empty() && !art_texts_of(d).into_iter().any(|(_, t, _)| lacks(t)) {
return Err(EngineError::Other("No fonts are missing".into()));
}
let runs = s.edit("Replace Missing Fonts", |d, _| {
@@ -1008,7 +1009,7 @@ fn replace_fonts(s: &mut Session, p: &Value) -> Result<Value> {
replace(t);
}
}
edit_symbol_texts(d, None, &|t, _| lacks(t), &mut replace);
edit_art_texts_of(d, &lacks, &mut replace);
Ok(runs)
})?;
Ok(json!({ "runs": runs, "font": family }))
@@ -415,3 +415,53 @@ fn replace_missing_fonts_reaches_the_type_in_symbols() {
s.execute("symbol.exitEditing", &json!({})).unwrap();
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
}
/// Replace Missing Fonts reaches the type in opacity masks (of a hidden object, disabled, in a
/// symbol's art) and in a pattern swatch nothing paints with, and the export warning, the missing
/// fonts list and Find Font name that type's font until it is replaced.
#[test]
fn replace_missing_fonts_reaches_the_type_in_masks_and_patterns() {
let mut s = session();
let mask = |s: &mut Session, owner: NodeId, art: NodeId| {
s.edit("Mask", |d, _| {
let art = d.remove(art)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
};
let lost = |s: &mut Session| text(s, json!({"x": 40, "y": 60, "text": "Lost", "size": 20, "font": "No Such Font Family"}));
let rect =
|s: &mut Session| NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 50, "height": 20})).unwrap()["id"].as_u64().unwrap());
let (hidden, disabled, in_symbol) = (rect(&mut s), rect(&mut s), rect(&mut s));
for owner in [hidden, disabled, in_symbol] {
let t = lost(&mut s);
mask(&mut s, owner, t);
}
s.execute("select.set", &json!({"ids": [hidden.0]})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [disabled.0]})).unwrap();
s.execute("transparency.disableOpacityMask", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = lost(&mut s);
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
select(&mut s, &[t]);
s.execute("edit.clear", &json!({})).unwrap();
let mut on_layers = 0;
s.doc().unwrap().doc.walk(|n| on_layers += usize::from(matches!(n.kind, NodeKind::Text(_))));
assert_eq!(on_layers, 0, "the type is only in masks, a symbol and a pattern");
let missing = |s: &Session| crate::cmd::fontfiles::missing_fonts(&s.doc().unwrap().doc).into_iter().map(|f| f.family).collect::<Vec<_>>();
assert_eq!(missing(&s), ["No Such Font Family"]);
assert!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc).is_some_and(|w| w.contains("No Such Font Family")));
let listed = s.execute("text.fonts", &json!({})).unwrap();
assert_eq!((listed[0]["family"].as_str(), listed[0]["objects"].as_u64()), (Some("No Such Font Family"), Some(4)), "{listed}");
let steps = |s: &Session| s.doc().unwrap().history.undo.len();
let before = steps(&s);
let r = s.execute("addon.cleanup.replaceFonts", &json!({})).unwrap();
assert_eq!(r["runs"].as_u64(), Some(4), "{r}");
assert_eq!(steps(&s), before + 1);
assert!(missing(&s).is_empty());
assert_eq!(crate::cmd::fonts::substitution_warning(&s.doc().unwrap().doc), None);
assert_eq!(other(s.execute("addon.cleanup.replaceFonts", &json!({}))), "No fonts are missing");
assert_eq!(steps(&s), before + 1);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Weed Box and Lines…",
["Object", "Plug-ins", "Cutting Tools"],
None,
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt (instead of count: as few lines as keep them at most this far apart), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
"{margin?: pt 0..100000 (9: from the art to the weed box), box?: true (false: the weeding lines only), direction?: \"horizontal\" | \"vertical\" | \"both\" (\"both\"), count?: whole number 0..1000 of lines each way (1), spacing?: pt more than 0 and at most 100000 (instead of count, never with it: as few lines as keep them at most this far apart, up to 1000 each way), gap?: pt 0..100000 (0: the lines stop at the art's outlines), weight?: pt 0.01..1000 (0.3), swatch?: a color swatch the lines are stroked in (\"[Registration]\")} add a weed box around the selected art and weeding lines across it that divide it evenly, each running from one side of the box to the other and left out over the art and within `gap` of its outlines, so the waste lifts off in pieces. The art is measured by the outlines a cutter cuts: closed paths enclose their area by their fill rule and open paths are lines, compound paths by all their subpaths, type by its glyph outlines, a clip group by what shows inside its clipping path, images by their frames, placed files by the art they show (by their boxes when the file can't be read), symbol instances by their art and live objects by the art they draw; strokes, effects and hidden objects are left out. One group named Weeding, stroked with no fill, on top of the current layer (outside the clip groups around a group edited in isolation), selected, as one undo step → {id: the group, box: its weed box or null, lines (pieces of weeding line)}",
has_selection,
weed
)]
@@ -723,12 +723,13 @@ pub(super) fn lines(region: &Region, outline: &[Segment], frame: Rect, n: Counts
continue;
}
// The lines (0-based) each outline segment comes within `gap` of: lines k (1-based) lie at
// v0 + k·step.
// v0 + k·step. The range is widened by a small tolerance so that a line whose position
// rounds just past a segment's end is still measured; `near` drops lines the segment misses.
let reach = |&(a, b): &Segment| {
let (va, vb) = (uv(a, vertical).1, uv(b, vertical).1);
let (lo, hi) = (va.min(vb) - gap, va.max(vb) + gap);
let first = ((lo - v0) / step).ceil().max(1.0);
let last = ((hi - v0) / step).floor().min(count as f64);
let first = ((lo - v0) / step - 1e-9).ceil().max(1.0);
let last = ((hi - v0) / step + 1e-9).floor().min(count as f64);
if step > 0.0 && first <= last { (first as usize - 1)..(last as usize) } else { 0..0 }
};
// The outlines near each line, found once for all of them, by index into `outline`.
@@ -541,6 +541,24 @@ fn indexed_crossings_find_the_same_stretches() {
}
}
/// An outline that lies on a weeding line stops it even when the line's position rounds just past
/// the outline's: the one line across 0.1 to 0.5 lies at 0.1 + 0.2, which is 0.30000000000000004,
/// and (0.30000000000000004 - 0.1) / 0.2 is 1.0000000000000002.
#[test]
fn an_outline_on_a_rounded_line_position_stops_the_line() {
let doc = vectorcraft_doc::Document::new(800.0, 600.0);
let c = 0.1 + 0.2;
let mut p = BezPath::new();
p.move_to((20.0, c));
p.line_to((80.0, c));
let n = Node::path(NodeId(1), PathData::from_bezpath(&p), Appearance::default());
let region = super::geometry::Reader::new(&doc).read(&[&n]).unwrap().unwrap();
let outline = region.outline().unwrap();
let counts = super::geometry::Counts { horizontal: 1, vertical: 0 };
let pieces = super::geometry::lines(&region, &outline, Rect::new(0.0, 0.1, 100.0, 0.5), counts, 0.0, 100).unwrap();
assert_eq!(pieces, [(Point::new(0.0, c), Point::new(20.0, c)), (Point::new(80.0, c), Point::new(100.0, c))]);
}
#[test]
fn art_nested_too_deep_is_refused() {
// A rectangle inside `levels` groups, each holding the next. A document keeps none this deep,
+114 -69
View File
@@ -2,12 +2,16 @@
//! selected images transparent in their own pixels, as one undo step. The background is the most
//! common color along an image's edges, the average of its four corners, or colors the caller
//! picks. It is cleared where it reaches in from an edge, or wherever it is. The work is done here,
//! on the pixels; nothing is sent anywhere. It is a VectorCraft addition. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialog are the UI's.
//! on the pixels; nothing is sent anywhere. Color Mask ([`mask`]) hides colors matched the same
//! way while the image keeps its pixels. They are VectorCraft additions. Its submenu (Object ›
//! Plug-ins › Image Tools) and dialogs are the UI's.
mod mask;
#[cfg(test)]
mod tests;
pub(crate) use mask::refresh as refresh_color_masks;
use std::collections::{HashMap, HashSet};
use std::io::Cursor;
use std::sync::{Arc, Weak};
@@ -15,11 +19,12 @@ use std::sync::{Arc, Weak};
use image::{DynamicImage, ImageBuffer, LumaA, Rgba};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_doc::{ImageBlob, NodeId, NodeKind};
use vectorcraft_doc::{ImageBlob, ImageObject, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::fileio::{MAX_RASTER_ALLOC, ppi};
use super::super::menucmds::has_image;
use super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::{CommandSpec, Result, Session, bad, checked_ids_param, cmd, hex_with_alpha, number_or, switch_or, text_param};
/// Remove Background's command.
@@ -34,15 +39,17 @@ const MAX_COLORS: usize = 16;
const WORK_BYTES: u64 = 10;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
let mut v = vec![cmd!(
"addon.image.removeBackground",
"Remove Background…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, and a result with no pixel left are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
"{background?: \"edges\" (default: the most common color along the image's edges; nothing is cleared when the edges hold at least as many clear pixels as pixels of that color) | \"corners\" (the average of the image's four corner pixels that are not clear; nothing is cleared when all four are clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 colors, each a hex color \"#rrggbb\" or \"#rgb\" with or without the # or one of black, white, red, green and blue; needed with background: colors, and checked but not used with edges or corners), contiguous?: bool (true: only background pixels that reach in from an edge are cleared; false: they are cleared wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a background color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (with distance, % of the largest RGB distance; with channels, % of 255 steps on one channel; a pixel this near a background color is cleared; 10), softness?: 0..100 (% past the tolerance over which pixels fade from cleared to kept; 10), ids?: [id…] (default: the selected images)} make the background of each image transparent in its own pixels, as one undo step: the image stays an image, embedded as a PNG with an alpha channel at the depth of its pixels (16-bit images keep 16 bits and grayscale images stay gray) with the source's color profile and resolution, and a linked image is embedded; a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a result with no pixel left, and a grayscale image colorized with a process color (which can't colorize gray pixels with transparency) are refused, and an image whose pixels do not change is left as it is (no undo step when none changes) → {changed: the images changed, ids, cleared: the pixels made fully clear in them}",
has_image,
remove_background
)]
)];
v.extend(mask::specs());
v
}
/// Where the background's colors come from.
@@ -78,50 +85,50 @@ pub(crate) struct Settings {
}
impl Settings {
/// The settings `p` gives, each checked.
fn read(p: &Value) -> Result<Self> {
/// The settings `p` gives to command `cmd`, each checked.
fn read(p: &Value, cmd: &str) -> Result<Self> {
let percent = |key: &str| -> Result<f64> {
let v = number_or(p, key, 10.0, C)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(C, format!("`{key}` must be from 0 to 100"))) }
let v = number_or(p, key, 10.0, cmd)?;
if v.is_finite() && (0.0..=100.0).contains(&v) { Ok(v) } else { Err(bad(cmd, format!("`{key}` must be from 0 to 100"))) }
};
let (tolerance, softness) = (percent("tolerance")?, percent("softness")?);
let colors = match p.get("colors") {
None | Some(Value::Null) => None,
Some(v) => Some(colors(v)?),
Some(v) => Some(colors(v, cmd)?),
};
let background = match text_param(p, "background", C)? {
let background = match text_param(p, "background", cmd)? {
None | Some("edges") => Background::Edges,
Some("corners") => Background::Corners,
Some("colors") => Background::Colors(colors.ok_or_else(colors_error)?),
Some(_) => return Err(bad(C, "`background` must be edges, corners or colors")),
Some("colors") => Background::Colors(colors.ok_or_else(|| colors_error(cmd))?),
Some(_) => return Err(bad(cmd, "`background` must be edges, corners or colors")),
};
let measure = match text_param(p, "match", C)? {
let measure = match text_param(p, "match", cmd)? {
None | Some("distance") => Match::Distance,
Some("channels") => Match::Channels,
Some(_) => return Err(bad(C, "`match` must be distance or channels")),
Some(_) => return Err(bad(cmd, "`match` must be distance or channels")),
};
let contiguous = switch_or(p, "contiguous", true, C)?;
let contiguous = switch_or(p, "contiguous", true, cmd)?;
Ok(Self { background, contiguous, measure, tolerance, softness })
}
}
fn colors_error() -> crate::EngineError {
bad(C, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue")
fn colors_error(cmd: &str) -> crate::EngineError {
bad(cmd, "`colors` must list 1 to 16 colors, each hex (#rrggbb or #rgb) or black, white, red, green or blue")
}
/// The colors `v` lists: an array of strings, or one string of them split by commas or spaces.
/// Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused.
fn colors(v: &Value) -> Result<Vec<[u8; 3]>> {
/// The colors `v` lists to command `cmd`: an array of strings, or one string of them split by
/// commas or spaces. Each is read as [`Color::from_hex`] reads it; one with an alpha part is refused.
fn colors(v: &Value, cmd: &str) -> Result<Vec<[u8; 3]>> {
// One past the most is enough to tell a list that is too long.
let texts: Vec<&str> = match v {
Value::String(s) => s.split([',', ' ', '\t', '\n']).filter(|t| !t.is_empty()).take(MAX_COLORS + 1).collect(),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(colors_error)?,
_ => return Err(colors_error()),
Value::Array(a) => a.iter().take(MAX_COLORS + 1).map(Value::as_str).collect::<Option<_>>().ok_or_else(|| colors_error(cmd))?,
_ => return Err(colors_error(cmd)),
};
if texts.is_empty() || texts.len() > MAX_COLORS {
return Err(colors_error());
return Err(colors_error(cmd));
}
texts.into_iter().map(|t| rgb8(t).ok_or_else(colors_error)).collect()
texts.into_iter().map(|t| rgb8(t).ok_or_else(|| colors_error(cmd))).collect()
}
/// The 8-bit RGB of the color `t` writes.
@@ -134,7 +141,7 @@ fn rgb8(t: &str) -> Option<[u8; 3]> {
}
fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
let settings = Settings::read(p)?;
let settings = Settings::read(p, C)?;
// A preview step keeps the pixels it decodes for the next step; other runs keep none.
let mut kept = std::mem::take(&mut s.decoded_images);
let previewing = s.previewing;
@@ -164,34 +171,15 @@ fn remove_background(s: &mut Session, p: &Value) -> Result<Value> {
/// cleared as `settings` say and the transform that keeps its place and size. Decoded pixels are
/// taken from and kept in `kept` when it is given.
fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<(NodeId, Cleared, Affine)>> {
let images = images(s, p, C)?;
// The result has an alpha channel, which a grayscale image colorized with a process color
// can't take. The pixels that are cleared are checked, the image's own, not the ones a color
// mask shows.
let st = s.doc()?;
let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) {
// Each image once, however often `ids` names it.
let mut given = HashSet::new();
let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", C)?.into_iter().filter(|id| given.insert(*id)).collect();
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
return Err(bad(C, format!("object {} is not an image", id.0)));
for (id, _, blob) in &images {
if blob.gray_source().is_some() && st.doc.node(*id).is_some_and(|n| colorized_with_process(&st.doc, n)) {
return Err(bad(C, PROCESS_ON_TRANSPARENCY));
}
ids
} else {
st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect()
};
if ids.is_empty() {
return Err(bad(C, "select an image"));
}
// Every image is checked before any is decoded.
let mut images = vec![];
for id in ids {
let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(C, "the image's pixels are missing"))?;
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(C, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
}
images.push((id, im, blob));
}
// Each image's pixels once, however many objects show them.
let mut cleared: HashMap<&str, Option<Cleared>> = HashMap::new();
@@ -200,7 +188,7 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
let out = match cleared.get(im.key.as_str()) {
Some(out) => out.clone(),
None => {
let out = clear(blob, settings, kept.as_deref_mut())?;
let out = clear(blob, settings, kept.as_deref_mut(), C)?;
cleared.insert(&im.key, out.clone());
out
}
@@ -218,6 +206,58 @@ fn changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut De
Ok(changes)
}
/// The image objects command `cmd` acts on (`ids`, each once, or the selected images), each with
/// its pixels, all checked before any is decoded: an object that is not an image, missing pixels,
/// a linked image that shows its preview and a CMYK image are errors, as is no image at all.
fn images<'a>(s: &'a Session, p: &Value, cmd: &str) -> Result<Vec<(NodeId, &'a ImageObject, &'a ImageBlob)>> {
let st = s.doc()?;
let mut images = vec![];
for id in targets(s, p, cmd)? {
let Some(NodeKind::Image(im)) = st.doc.node(id).map(|n| &n.kind) else { continue };
let blob = st.doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?;
// The preview stands in for a file that hasn't been read, or that is kept at its preview.
if im.link.is_some() && blob.is_proxy() {
return Err(bad(cmd, "the linked image shows its preview: embed or relink it first"));
}
if blob.is_cmyk() {
return Err(cmyk_refusal(cmd));
}
images.push((id, &**im, blob));
}
Ok(images)
}
/// The image objects command `cmd` acts on: `ids`, each once, or the selected images. An object in
/// `ids` that is not an image is an error, as is no image at all.
fn targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let st = s.doc()?;
let ids: Vec<NodeId> = if p.get("ids").is_some_and(|v| !v.is_null()) {
// Each image once, however often `ids` names it.
let mut given = HashSet::new();
let ids: Vec<NodeId> = checked_ids_param(s, p, "ids", cmd)?.into_iter().filter(|id| given.insert(*id)).collect();
if let Some(id) = ids.iter().find(|id| !matches!(st.doc.node(**id).map(|n| &n.kind), Some(NodeKind::Image(_)))) {
return Err(bad(cmd, format!("object {} is not an image", id.0)));
}
ids
} else {
st.selection.objects.iter().copied().filter(|id| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_)))).collect()
};
if ids.is_empty() {
return Err(bad(cmd, "select an image"));
}
Ok(ids)
}
/// Whether `cmd` is one of Color Mask's commands, which hide pixels instead of clearing them.
fn masks(cmd: &str) -> bool {
matches!(cmd, mask::COLOR_MASK | mask::REMOVE_COLOR_MASK | mask::APPLY_COLOR_MASK)
}
/// Command `cmd`'s refusal of a CMYK image.
fn cmyk_refusal(cmd: &str) -> crate::EngineError {
if masks(cmd) { bad(cmd, "a CMYK image can't take a color mask") } else { bad(cmd, "a CMYK image has no transparency to set") }
}
/// An image with its background cleared: its PNG, its size in pixels, and how many of its pixels
/// were made fully clear.
#[derive(Clone, Debug)]
@@ -345,16 +385,16 @@ impl Pixels {
/// `blob` with its background cleared as `settings` say, or `None` when no pixel changes. A CMYK
/// image, one that can't be decoded or is too large to change, and a result with no pixel left are
/// errors. The PNG keeps the source's ICC profile and resolution. The decoded pixels are taken
/// from and kept in `kept` when it is given.
pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Option<Cleared>> {
/// errors of command `cmd`. The PNG keeps the source's ICC profile and resolution. The decoded
/// pixels are taken from and kept in `kept` when it is given.
pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<Cleared>> {
if blob.is_cmyk() {
return Err(bad(C, "a CMYK image has no transparency to set"));
return Err(cmyk_refusal(cmd));
}
let found = kept.as_deref_mut().and_then(|k| k.get(&blob.bytes));
let (source, gray, icc) = match found {
Some(found) => found,
None => decode(blob, kept)?,
None => decode(blob, kept, cmd)?,
};
// The pixels kept for the next run stay as they are; ones not kept are worked on in place.
let mut px = Arc::try_unwrap(source).unwrap_or_else(|kept| Pixels::clone(&kept));
@@ -366,7 +406,11 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
Pixels::Sixteen(img) => img.pixels().any(|p| p.0[3] > 0),
};
if !left {
return Err(bad(C, "every pixel matches the background: no image would be left"));
return Err(if masks(cmd) {
bad(cmd, "the mask would hide every pixel")
} else {
bad(cmd, "every pixel matches the background: no image would be left")
});
}
let out = match (px, gray) {
(Pixels::Eight(img), false) => DynamicImage::ImageRgba8(img),
@@ -382,9 +426,9 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
let mut encoder = image::codecs::png::PngEncoder::new(&mut png);
if let Some(icc) = icc {
use image::ImageEncoder as _;
encoder.set_icc_profile(icc).map_err(|e| bad(C, e.to_string()))?;
encoder.set_icc_profile(icc).map_err(|e| bad(cmd, e.to_string()))?;
}
out.write_with_encoder(encoder).map_err(|e| bad(C, e.to_string()))?;
out.write_with_encoder(encoder).map_err(|e| bad(cmd, e.to_string()))?;
// The resolution the file declares, which sizes the image at 100% when it is replaced or relinked.
if let Some(r) = ppi::resolution(&blob.bytes) {
png = ppi::with_png_resolution(&png, r);
@@ -394,11 +438,12 @@ pub(crate) fn clear(blob: &ImageBlob, settings: &Settings, mut kept: Option<&mut
/// `blob`'s pixels as straight RGBA, whether they were gray, and its ICC profile. An image that
/// can't be decoded or is too large to change is an error. The pixels are kept in `kept`, when it
/// is given, if a copy of them fits the decode allowance beside the work.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader =
|| image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(C, "the image's pixels can't be read"));
let mut decoder = reader()?.into_decoder().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
/// is given, if a copy of them fits the decode allowance beside the work. Errors are command `cmd`'s.
fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<(Arc<Pixels>, bool, Option<Vec<u8>>)> {
let reader = || {
image::ImageReader::new(Cursor::new(blob.bytes.as_slice())).with_guessed_format().map_err(|_| bad(cmd, "the image's pixels can't be read"))
};
let mut decoder = reader()?.into_decoder().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
// The ICC profile the colors are in goes with them into the PNG.
let (w, h, kind, icc) = {
use image::ImageDecoder as _;
@@ -411,13 +456,13 @@ fn decode(blob: &ImageBlob, kept: Option<&mut DecodedImages>) -> Result<(Arc<Pix
let deep = kind.bytes_per_pixel() > kind.channel_count();
let per_pixel = u64::from(kind.bytes_per_pixel()) + 2 * if deep { 8 } else { 4 } + WORK_BYTES;
if u64::from(w).checked_mul(u64::from(h)).and_then(|n| n.checked_mul(per_pixel)).is_none_or(|n| n > MAX_RASTER_ALLOC) {
return Err(bad(C, format!("an image of {w} × {h} pixels is too large to change")));
return Err(bad(cmd, format!("an image of {w} × {h} pixels is too large to change")));
}
let mut reader = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(MAX_RASTER_ALLOC);
reader.limits(limits);
let img = reader.decode().map_err(|e| bad(C, format!("the image's pixels can't be read: {e}")))?;
let img = reader.decode().map_err(|e| bad(cmd, format!("the image's pixels can't be read: {e}")))?;
#[cfg(test)]
DECODES.with(|c| c.set(c.get() + 1));
let gray = matches!(img.color(), image::ColorType::L8 | image::ColorType::La8 | image::ColorType::L16 | image::ColorType::La16);
+443
View File
@@ -0,0 +1,443 @@
//! Image Tools › Color Mask (`addon.image.colorMask`, `addon.image.removeColorMask`,
//! `addon.image.applyColorMask`): colors of the selected images are hidden while their pixels
//! stay as they are. The colors are matched as Remove Background matches them ([`super::clear`]);
//! the image keeps its own pixels, and the mask's settings and the masked pixels are kept with it
//! ([`vectorcraft_doc::color_mask`]), so the mask can be changed, removed, or applied to the
//! pixels later. When an image's own pixels are replaced (a link updated or relinked, the image
//! cropped or recolored), its mask is applied to the new pixels ([`refresh`]).
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::color_mask::{ColorMask, MaskBackground, MaskMatch};
use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
use super::super::super::paint::{PROCESS_ON_TRANSPARENCY, colorized_with_process};
use super::super::super::{CommandSpec, Result, Session, bad, cmd};
use super::{Background, DecodedImages, MAX_COLORS, Match, Settings, clear, images, targets};
/// Color Mask's command.
pub const COLOR_MASK: &str = "addon.image.colorMask";
/// Remove Color Mask's command.
pub const REMOVE_COLOR_MASK: &str = "addon.image.removeColorMask";
/// Apply Color Mask's command.
pub const APPLY_COLOR_MASK: &str = "addon.image.applyColorMask";
/// The params that set a mask; with none of them, Color Mask only reports.
const SETTINGS: [&str; 6] = ["background", "colors", "contiguous", "match", "tolerance", "softness"];
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"addon.image.colorMask",
"Color Mask…",
["Object", "Plug-ins", "Image Tools"],
None,
"{background?: \"edges\" (default: the most common color along the image's edges) | \"corners\" (the average of the image's four corner pixels that are not clear) | \"colors\" (the colors in `colors`), colors?: [color…] or one string of them split by commas or spaces (1 to 16 hex colors or black, white, red, green and blue, as addon.image.removeBackground takes them; needed with background: colors), contiguous?: bool (true: only matching pixels that reach in from an edge are hidden; false: wherever they are; true), match?: \"distance\" (default: a color's RGB distance from a hidden color) | \"channels\" (its largest difference on one of red, green and blue), tolerance?: 0..100 (% as addon.image.removeBackground measures it; a pixel this near a hidden color is hidden; 10), softness?: 0..100 (% past the tolerance over which pixels fade from hidden to shown; 10), ids?: [id…] (default: the selected images)} hide colors of each image without changing its pixels, as one undo step: the image keeps its own pixels, and the mask (these settings, and the image's pixels with the hidden colors made clear, made as Remove Background makes them) is kept with the image and saved with the document; the canvas, printing and separations, PDF, SVG, EPS, raster formats, DXF, EMF, WMF, the legacy .ai and the .ai editing data, copy and paste, and placing a document show the masked pixels, and a click on any part of the image's frame selects it (the Eyedropper, Object Mosaic, Create Gradient Mesh, Crop Image's trim and Image Trace read the image's own pixels); setting the mask again replaces it, and an image whose mask does not change is left as it is (no undo step when none changes); when the image's own pixels are replaced later (Update Link, Relink, Crop Image, a recolor, a linked file read again on open), the mask is made again for the new pixels; an object in `ids` that is not an image, a CMYK image, a linked image that shows its preview (embed or relink it first), an image too large to change, a mask that would hide every pixel, and a mask that would hide pixels of a grayscale image colorized with a process color (masked gray pixels have transparency, which only a spot color, black or white colorizes; each image is checked on the pixels its new mask shows) are refused. With none of background, colors, contiguous, match, tolerance and softness given, nothing changes and the mask settings of the first image (or the defaults when it has no mask) are returned → {changed: the images changed, ids, hidden: the pixels made fully clear in them} or {background, colors, contiguous, match, tolerance, softness, masked}",
super::has_image,
color_mask
),
cmd!(
"addon.image.removeColorMask",
"Remove Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} take the color mask off each image, as one undo step: the image shows its own pixels again; images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image is refused → {changed, ids}",
has_color_mask,
remove_color_mask
),
cmd!(
"addon.image.applyColorMask",
"Apply Color Mask",
["Object", "Plug-ins", "Image Tools"],
None,
"{ids?: [id…] (default: the selected images)} make each image's color mask part of its pixels, as one undo step: the masked pixels become the image's own, embedded as a PNG with an alpha channel (a linked image is embedded), and the mask is taken off; a mask that hides nothing is only taken off (the image keeps its pixels and its link); images without a mask are left as they are (no undo step when none has one), and an object in `ids` that is not an image, and a mask made again for new pixels that would give a grayscale image colorized with a process color an alpha channel, are refused → {changed, ids}",
has_color_mask,
apply_color_mask
),
]
}
/// Enabled when a selected image has a color mask.
fn has_color_mask(s: &Session) -> std::result::Result<(), String> {
let st = s.active().ok_or("no document open")?;
if st.selection.objects.iter().any(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()) {
Ok(())
} else {
Err("select an image with a color mask".into())
}
}
impl Settings {
/// The settings a mask was made with, `None` when a file gave ones out of range.
fn of(m: &ColorMask) -> Option<Self> {
let percent = |v: f64| v.is_finite() && (0.0..=100.0).contains(&v);
if !percent(m.tolerance) || !percent(m.softness) {
return None;
}
let background = match m.background {
MaskBackground::Edges => Background::Edges,
MaskBackground::Corners => Background::Corners,
MaskBackground::Colors if (1..=MAX_COLORS).contains(&m.colors.len()) => Background::Colors(m.colors.clone()),
MaskBackground::Colors => return None,
};
let measure = match m.measure {
MaskMatch::Distance => Match::Distance,
MaskMatch::Channels => Match::Channels,
};
Some(Self { background, contiguous: m.contiguous, measure, tolerance: m.tolerance, softness: m.softness })
}
/// A mask with these settings whose masked pixels are `key`, made from the pixels `from`.
fn mask(&self, key: String, from: String) -> ColorMask {
let (background, colors) = match &self.background {
Background::Edges => (MaskBackground::Edges, vec![]),
Background::Corners => (MaskBackground::Corners, vec![]),
Background::Colors(c) => (MaskBackground::Colors, c.clone()),
};
let measure = match self.measure {
Match::Distance => MaskMatch::Distance,
Match::Channels => MaskMatch::Channels,
};
ColorMask { key, from, background, colors, contiguous: self.contiguous, measure, tolerance: self.tolerance, softness: self.softness }
}
}
/// The masked pixels of `blob` (`None`: no pixel is hidden, the image's own pixels show) as
/// `settings` say, with errors of command `cmd`.
fn masked(blob: &ImageBlob, settings: &Settings, kept: Option<&mut DecodedImages>, cmd: &str) -> Result<Option<(String, ImageBlob, u64)>> {
Ok(clear(blob, settings, kept, cmd)?.map(|out| (out.blob.content_key(), out.blob, out.cleared)))
}
fn color_mask(s: &mut Session, p: &Value) -> Result<Value> {
if !SETTINGS.iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
return report(s, p);
}
let settings = Settings::read(p, COLOR_MASK)?;
// A preview step keeps the pixels it decodes for the next step; other runs keep none.
let mut kept = std::mem::take(&mut s.decoded_images);
let previewing = s.previewing;
let found = mask_changes(s, p, &settings, previewing.then_some(&mut kept));
s.decoded_images = kept;
let changes = found?;
let ids: Vec<u64> = changes.iter().map(|c| c.0.0).collect();
let hidden: u64 = changes.iter().map(|c| c.3).sum();
if !changes.is_empty() {
s.edit("Color Mask", |d, _| {
for (id, mask, blob, _) in changes {
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
if let Some(n) = d.node_mut(id) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids, "hidden": hidden }))
}
/// The images `p` names whose mask changes, each with its new mask, the masked pixels to add (when
/// the document doesn't have them) and how many pixels they hide.
type MaskChange = (NodeId, ColorMask, Option<ImageBlob>, u64);
fn mask_changes(s: &Session, p: &Value, settings: &Settings, mut kept: Option<&mut DecodedImages>) -> Result<Vec<MaskChange>> {
let st = s.doc()?;
// Each image's pixels once, however many objects show them.
let mut made: HashMap<&str, (String, Option<ImageBlob>, u64)> = HashMap::new();
let mut out = vec![];
for (id, im, blob) in images(s, p, COLOR_MASK)? {
let (key, pixels, hidden) = match made.get(im.key.as_str()) {
Some(m) => m.clone(),
None => {
let m = match masked(blob, settings, kept.as_deref_mut(), COLOR_MASK)? {
Some((key, blob, hidden)) => (key, Some(blob), hidden),
None => (im.key.clone(), None, 0),
};
made.insert(&im.key, m.clone());
m
}
};
let mask = settings.mask(key, im.key.clone());
if st.doc.node(id).and_then(Document::color_mask_of) == Some(&mask) {
continue;
}
// Masked pixels that hide something have an alpha channel, which a grayscale image
// colorized with a process color can't take. The pixels the new mask shows are checked,
// made from the image's own pixels, not the ones an earlier mask shows.
let shown = pixels.as_ref().or_else(|| st.doc.images.get(&mask.key));
if st.doc.node(id).is_some_and(|n| refused_colorize(&st.doc, n, shown)) {
return Err(bad(COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let pixels = pixels.filter(|_| !st.doc.images.contains_key(&mask.key));
out.push((id, mask, pixels, hidden));
}
Ok(out)
}
/// Whether masked pixels `shown`, made for image node `n`, have transparency that `n`'s colorize
/// color can't take: gray pixels with an alpha channel and a process color
/// ([`colorized_with_process`]).
fn refused_colorize(doc: &Document, n: &Node, shown: Option<&ImageBlob>) -> bool {
shown.and_then(ImageBlob::gray_source).is_some_and(|g| g.alpha) && colorized_with_process(doc, n)
}
/// Color Mask without settings: the first image's mask settings, or the defaults. It reads them
/// for images a change would refuse too (CMYK, a linked image at its preview), so the dialog opens.
fn report(s: &Session, p: &Value) -> Result<Value> {
let st = s.doc()?;
let first = targets(s, p, COLOR_MASK)?.first().and_then(|id| st.doc.node(*id)).and_then(Document::color_mask_of).cloned();
let m = first.as_ref();
let hex = |c: &[u8; 3]| format!("#{:02x}{:02x}{:02x}", c[0], c[1], c[2]);
let colors =
m.filter(|m| !m.colors.is_empty()).map_or_else(|| "#ffffff".to_string(), |m| m.colors.iter().map(hex).collect::<Vec<_>>().join(", "));
let name = |v: Value| v.as_str().map(str::to_string).unwrap_or_default();
Ok(json!({
"background": name(serde_json::to_value(m.map_or(MaskBackground::Edges, |m| m.background)).unwrap_or_default()),
"colors": colors,
"contiguous": m.is_none_or(|m| m.contiguous),
"match": name(serde_json::to_value(m.map_or(MaskMatch::Distance, |m| m.measure)).unwrap_or_default()),
"tolerance": m.map_or(10.0, |m| m.tolerance),
"softness": m.map_or(10.0, |m| m.softness),
"masked": m.is_some(),
}))
}
/// The image objects `p` names ([`targets`]: `ids`, or the selected images) that have a color mask.
fn masked_images(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
let st = s.doc()?;
Ok(targets(s, p, cmd)?.into_iter().filter(|id| st.doc.node(*id).and_then(Document::color_mask_of).is_some()).collect())
}
fn remove_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, REMOVE_COLOR_MASK)?;
if !ids.is_empty() {
s.edit("Remove Color Mask", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
n.extras_mut().color_mask = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
fn apply_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let ids = masked_images(s, p, APPLY_COLOR_MASK)?;
// Each image's masked pixels, made again first when its own pixels changed since. A mask that
// hides nothing (its masked pixels are the image's own) is only taken off: the image keeps its
// pixels and its link.
let mut made = vec![];
{
let st = s.doc()?;
for id in &ids {
let Some(n) = st.doc.node(*id) else { continue };
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { continue };
let mask = match fresh(&st.doc, n, APPLY_COLOR_MASK) {
Some(Ok(fresh)) => fresh,
Some(Err(e)) => return Err(e),
None => (m.clone(), None),
};
if mask.0.key == im.key {
made.push((*id, None));
continue;
}
let shown = st.doc.images.get(&mask.0.key).or(mask.1.as_ref());
if refused_colorize(&st.doc, n, shown) {
return Err(bad(APPLY_COLOR_MASK, PROCESS_ON_TRANSPARENCY));
}
let size = mask_size(shown, im.width, im.height);
made.push((*id, Some((mask, size))));
}
}
if !made.is_empty() {
s.edit("Apply Color Mask", |d, _| {
for (id, applied) in made {
let Some(n) = d.node_mut(id) else { continue };
n.extras_mut().color_mask = None;
let Some(((mask, blob), (w, h))) = applied else { continue };
if let Some(blob) = blob {
d.images.entry(mask.key.clone()).or_insert(blob);
}
let Some(n) = d.node_mut(id) else { continue };
if let NodeKind::Image(im) = &mut n.kind {
// Masked pixels of another size than the object's keep its place and size.
if (w, h) != (im.width, im.height) {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(w), f64::from(im.height) / f64::from(h));
(im.width, im.height) = (w, h);
}
im.key = mask.key;
im.link = None;
}
}
Ok(())
})?;
}
Ok(json!({ "changed": ids.len(), "ids": ids.iter().map(|id| id.0).collect::<Vec<_>>() }))
}
/// The size in pixels of masked pixels `blob` (from its header), or the object's when it can't be
/// read.
fn mask_size(blob: Option<&ImageBlob>, width: u32, height: u32) -> (u32, u32) {
blob.and_then(|b| image::ImageReader::new(std::io::Cursor::new(b.bytes.as_slice())).with_guessed_format().ok()?.into_dimensions().ok())
.filter(|(w, h)| *w > 0 && *h > 0)
.unwrap_or((width, height))
}
/// The mask of image node `n` made again for the image's own pixels, with the masked pixels when
/// `doc` doesn't have them: `None` when the mask is up to date (or `n` has none), an error when the
/// pixels can't be masked (missing, CMYK, a linked preview, too large, every pixel hidden, or
/// settings a file gave out of range).
fn fresh(doc: &Document, n: &Node, cmd: &str) -> Option<Result<(ColorMask, Option<ImageBlob>)>> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(doc, n) {
return None;
}
let made = || -> Result<(ColorMask, Option<ImageBlob>)> {
let settings = Settings::of(m).ok_or_else(|| bad(cmd, "the color mask's settings are out of range"))?;
let blob = doc.images.get(&im.key).ok_or_else(|| bad(cmd, "the image's pixels are missing"))?;
if im.link.is_some() && blob.is_proxy() {
return Err(bad(cmd, "the linked image shows its preview: embed or relink it first"));
}
Ok(match masked(blob, &settings, None, cmd)? {
Some((key, blob, _)) => {
let blob = (!doc.images.contains_key(&key)).then_some(blob);
(settings.mask(key, im.key.clone()), blob)
}
None => (settings.mask(im.key.clone(), im.key.clone()), None),
})
};
Some(made())
}
/// After an edit from `before` (`None`: everything is new, as after a document's links are read):
/// the color masks of images in `doc`'s art ([`Document::art_roots`]: layers, symbols, graph
/// designs, patterns and the original of the pattern being edited, opacity mask art included)
/// whose own pixels were replaced are made again for the new pixels ([`Refresh::made`]). Only the
/// art that changed since `before` is looked at.
pub(crate) fn refresh(before: Option<&Document>, doc: &mut Document) {
let old: Vec<&Arc<Node>> = before.map(|b| b.art_roots().collect()).unwrap_or_default();
let mut pass = Refresh { doc: &*doc, made: HashMap::new(), blobs: vec![] };
let mut fixed = vec![];
for (i, root) in doc.art_roots().enumerate() {
let counterpart = old.get(i).copied().filter(|o| o.id == root.id);
if stale_in(doc, root, counterpart) {
let mut root = root.clone();
pass.fix(Arc::make_mut(&mut root));
fixed.push((i, root));
}
}
let blobs = pass.blobs;
if fixed.is_empty() {
return;
}
for (key, blob) in blobs {
doc.images.entry(key).or_insert(blob);
}
let mut fixed = fixed.into_iter().peekable();
for (i, root) in doc.art_roots_mut().enumerate() {
if fixed.peek().is_some_and(|(at, _)| *at == i)
&& let Some((_, new)) = fixed.next()
{
*root = new;
}
}
}
/// Whether `n`, or anything in it (opacity-mask art included), is an image whose mask is out of
/// date ([`stale_mask`]). What is the same as in `old`, `n`'s counterpart before an edit, is not
/// looked at.
fn stale_in(doc: &Document, n: &Arc<Node>, old: Option<&Arc<Node>>) -> bool {
if old.is_some_and(|o| Arc::ptr_eq(o, n)) {
return false;
}
if stale_mask(doc, n) {
return true;
}
let old_mask = old.and_then(|o| o.extras().mask.as_ref()).map(|m| &m.art);
if n.extras().mask.as_ref().is_some_and(|m| stale_in(doc, &m.art, old_mask)) {
return true;
}
let Some(children) = n.children() else { return false };
let before = old.and_then(|o| o.children()).map_or(&[][..], Vec::as_slice);
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
children.iter().enumerate().any(|(i, c)| {
let b = match before.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
};
stale_in(doc, c, b)
})
}
/// Whether `n` is an image whose color mask was not made from its own pixels (or whose masked
/// pixels `doc` doesn't have). A mask that hides nothing (its masked pixels are the image's own)
/// is up to date while the image's key stays the same, even when its pixels are missing.
fn stale_mask(doc: &Document, n: &Node) -> bool {
matches!((&n.kind, Document::color_mask_of(n)), (NodeKind::Image(im), Some(m))
if im.pixels.is_none() && !(m.made_for(im) && (m.key == im.key || doc.images.contains_key(&m.key))))
}
/// One [`refresh`] pass: the masks made so far, by the image's pixels, the mask's settings and
/// whether a process color colorizes the image (an image shown by many objects is decoded once),
/// and the masked pixels to add to the document.
struct Refresh<'a> {
doc: &'a Document,
made: HashMap<(String, String, bool), ColorMask>,
blobs: Vec<(String, ImageBlob)>,
}
impl Refresh<'_> {
/// Make the masks out of date in `n` (a copy of the document's art) again.
fn fix(&mut self, n: &mut Node) {
if let Some(mask) = self.made(n) {
n.extras_mut().color_mask = Some(Box::new(mask));
}
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
&& stale_in(self.doc, &m.art, None)
{
self.fix(Arc::make_mut(&mut m.art));
}
for c in n.children_mut().into_iter().flatten() {
if stale_in(self.doc, c, None) {
self.fix(Arc::make_mut(c));
}
}
}
/// The mask of image node `n` made again for the image's own pixels ([`fresh`]), `None` when
/// it is up to date. A mask that can't be made for them (every pixel hidden, CMYK pixels, a
/// linked preview, too large, gray pixels with transparency under a process color) keeps its
/// settings and hides nothing: the image shows its own pixels, and setting the mask again
/// reports why.
fn made(&mut self, n: &Node) -> Option<ColorMask> {
let (NodeKind::Image(im), Some(m)) = (&n.kind, Document::color_mask_of(n)) else { return None };
if !stale_mask(self.doc, n) {
return None;
}
let settings = ColorMask { key: String::new(), from: String::new(), ..m.clone() };
let at = (im.key.clone(), format!("{settings:?}"), colorized_with_process(self.doc, n));
if let Some(made) = self.made.get(&at) {
return Some(made.clone());
}
let hides_nothing = || ColorMask { key: im.key.clone(), from: im.key.clone(), ..m.clone() };
let mask = match fresh(self.doc, n, COLOR_MASK)? {
Ok((mask, blob)) if refused_colorize(self.doc, n, blob.as_ref().or_else(|| self.doc.images.get(&mask.key))) => hides_nothing(),
Ok((mask, blob)) => {
self.blobs.extend(blob.map(|b| (mask.key.clone(), b)));
mask
}
Err(_) => hides_nothing(),
};
self.made.insert(at, mask.clone());
Some(mask)
}
}
File diff suppressed because it is too large. Load diff
+51 -2
View File
@@ -1,8 +1,9 @@
use std::io::Cursor;
use std::sync::Arc;
use image::{DynamicImage, ImageBuffer, Luma, Rgb};
use image::{DynamicImage, ImageBuffer, Luma, LumaA, Rgb};
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{ImageBlob, ImageObject, LinkInfo, Node, NodeId, NodeKind};
use vectorcraft_geom::Affine;
@@ -333,6 +334,54 @@ fn sixteen_bit_and_gray_images_keep_their_depth_and_channels() {
assert_eq!((out.get_pixel(0, 0).0, out.get_pixel(3, 3).0), ([61_000, 0], [7_000, 65_535]));
}
/// A process color can't colorize a grayscale image with transparency, so a gray image colorized
/// with one keeps its pixels. Black, white and spot colors can, so those images are cleared.
#[test]
fn a_gray_image_colorized_with_a_process_color_is_refused() {
let gray = || {
png(DynamicImage::ImageLuma8(ImageBuffer::from_fn(8, 8, |x, y| Luma([if (2..6).contains(&x) && (2..6).contains(&y) { 30u8 } else { 240 }]))))
};
let (mut s, id) = open(&gray());
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the fill colorizes the image");
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute(C, &json!({})).unwrap_err();
assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}");
assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "the document and its undo steps are unchanged");
// Another image that already has an alpha channel and a process colorize color, as an opened
// file can hold, neither lets this one through nor stops a run on an image that can be cleared.
let held = ImageBlob::png(png(DynamicImage::ImageLumaA8(ImageBuffer::from_pixel(2, 2, LumaA([128u8, 100])))));
let other = place_linked(&mut s, "held", held, (2, 2));
s.edit("Embed and colorize", |d, _| {
let n = d.node_mut(other).unwrap();
n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::rgb8(255, 0, 0))));
if let NodeKind::Image(im) = &mut n.kind {
im.link = None;
}
Ok(())
})
.unwrap();
let (before, steps) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute(C, &json!({"ids": [id.0]})).unwrap_err();
assert!(e.to_string().contains("a process color can't colorize a grayscale image with transparency"), "{e}");
assert_eq!((&s.doc().unwrap().doc, undo_len(&s)), (&before, steps), "with another image refused already, nothing changes");
s.execute("paint.setFill", &json!({"color": "#000000", "ids": [id.0]})).unwrap();
assert_eq!(s.execute(C, &json!({"ids": [id.0]})).unwrap()["changed"], 1, "an image colorized with black is cleared beside the other");
let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") };
assert_eq!(out.get_pixel(0, 0).0[1], 0, "the background is cleared");
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "the image stays colorized");
for fill in [json!({"color": "#000000"}), json!({"color": "#ffffff"}), json!({"swatch": "Ink"})] {
let (mut s, id) = open(&gray());
s.execute("swatch.new", &json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 100, "k": 0}, "spot": true})).unwrap();
s.execute("paint.setFill", &fill).unwrap();
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} colorizes the image");
s.execute(C, &json!({})).unwrap();
let DynamicImage::ImageLumaA8(out) = pixels(&s, id) else { panic!("gray with alpha") };
assert_eq!(out.get_pixel(0, 0).0[1], 0, "{fill}: the background is cleared");
assert!(s.doc().unwrap().doc.node(id).unwrap().extras().colorize.is_some(), "{fill} still colorizes the image");
}
}
/// The ICC profile the colors are in stays with them.
#[test]
fn the_color_profile_is_kept() {
@@ -343,7 +392,7 @@ fn the_color_profile_is_kept() {
encoder.set_icc_profile(icc.clone()).unwrap();
DynamicImage::ImageRgba8(framed()).write_with_encoder(encoder).unwrap();
let blob = ImageBlob::png(bytes);
let out = super::clear(&blob, &settings(Background::Edges), None).unwrap().unwrap();
let out = super::clear(&blob, &settings(Background::Edges), None, super::C).unwrap().unwrap();
let mut decoder = image::codecs::png::PngDecoder::new(Cursor::new(out.blob.bytes.as_slice())).unwrap();
assert_eq!(decoder.icc_profile().unwrap(), Some(icc));
}
+453
View File
@@ -0,0 +1,453 @@
//! Custom arrowheads (Stroke panel menu › Edit Arrowheads…). The arrowheads file is a native
//! document kept next to the preferences ([`Session::attach_arrowheads_file`]). Each of its symbols
//! is one arrowhead, listed by the symbol's name after the built-in heads in the Stroke panel's
//! arrowhead menus. A head points right (+x): the symbol's registration point is its tip, and the
//! art's height (its extent across the line) is drawn as wide as the built-in heads, four times
//! the head's weight. A head covers what its art paints: the visible fills, and the visible
//! strokes outlined, of the paths, compound paths and groups in it, and its gradient meshes, with
//! their geometry effects applied and clip groups clipped. A head is one solid shape in the stroke's paint: art at 0 %
//! opacity is left out, and other opacities, blend modes and opacity masks do not change the
//! shape. Saving the file reloads the heads. A stroke that uses a custom head carries a copy of its art
//! ([`vectorcraft_doc::CustomArrowhead`]), so its document draws it anywhere.
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, CustomArrowhead, Document, Node, NodeId, NodeKind, Symbol, SymbolRegistration};
use vectorcraft_geom::{Affine, FillRule, PathData, Point, SubPath};
use vectorcraft_pathops::BoolOp;
use super::{CommandSpec, Result, Session, always, bad, cmd};
/// The arrowheads file's name, in the folder of the preferences.
pub const FILE_NAME: &str = "Arrowheads.vectorcraft";
/// The largest arrowheads file read, and the most its document or its images may unpack to when
/// compressed.
pub const MAX_FILE_BYTES: u64 = 64 << 20;
/// The most heads read from the file; symbols past it are skipped.
pub const MAX_HEADS: usize = 256;
/// The most anchors a symbol's art, and the shapes it paints, may have; a symbol past it is skipped.
pub const MAX_ART_ANCHORS: usize = 16 * CustomArrowhead::MAX_ANCHORS;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
query "stroke.arrowheads.list",
"Arrowheads",
[],
None,
"{} → {arrowheads: [{name (stroke.set `startArrow`/`endArrow` as {custom: name}), reach, halfWidth (in head weights)}], file: the arrowheads file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not heads, error: why the file could not be read, or null} the custom arrowheads, listed after the built-in ones in the Stroke panel's arrowhead menus",
always,
list
),
cmd!(
"stroke.arrowheads.edit",
"Edit Arrowheads",
[],
None,
"{} open the arrowheads file (a native document next to the preferences; created first with one example head when it is missing). Each symbol in it is one custom arrowhead named after the symbol: it points right, its registration point is the tip, and its height is drawn as wide as the built-in heads; its visible fills and outlined strokes make the head. Saving the file reloads the heads → {path, created: whether the file was made now}",
has_file,
edit
),
cmd!(
"stroke.arrowheads.reload",
"Reload Arrowheads",
[],
None,
"{} read the arrowheads file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}",
has_file,
reload
),
]
}
/// The custom arrowheads read from the arrowheads file.
#[derive(Default)]
pub struct Arrowheads {
path: Option<String>,
heads: Vec<Arc<CustomArrowhead>>,
skipped: Vec<(String, String)>,
error: Option<String>,
}
impl Arrowheads {
/// The arrowheads file's path; `None` without one (the web, runs without preferences).
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// The heads, in the order of the file's symbols.
pub fn heads(&self) -> &[Arc<CustomArrowhead>] {
&self.heads
}
/// Head `name`.
pub fn get(&self, name: &str) -> Option<Arc<CustomArrowhead>> {
self.heads.iter().find(|h| h.name == name).cloned()
}
fn set(&mut self, read: Read) {
(self.heads, self.skipped) = (read.heads.into_iter().map(Arc::new).collect(), read.skipped);
self.error = None;
}
}
/// The heads a document holds, and the symbols that are not heads with the reason.
#[derive(Debug, Default)]
pub struct Read {
pub heads: Vec<CustomArrowhead>,
pub skipped: Vec<(String, String)>,
}
/// The heads of document `doc`: one per symbol, up to [`MAX_HEADS`] (see the module docs).
pub fn heads_of(doc: &Document) -> Read {
let mut d = doc.clone();
let brushes = vectorcraft_brush::library(&d);
let mut out = Read::default();
for (i, sym) in doc.symbols.iter().enumerate() {
if i >= MAX_HEADS {
out.skipped.push((sym.name.clone(), format!("only the first {MAX_HEADS} symbols are read")));
continue;
}
if out.heads.iter().any(|h| h.name == sym.name) {
out.skipped.push((sym.name.clone(), "another symbol has this name".into()));
continue;
}
match head(&mut d, &brushes, sym) {
Ok(h) => out.heads.push(h),
Err(why) => out.skipped.push((sym.name.clone(), why.into())),
}
}
out
}
/// Symbol `sym` of `d` as a head.
fn head(d: &mut Document, brushes: &[vectorcraft_brush::Brush], sym: &Symbol) -> std::result::Result<CustomArrowhead, &'static str> {
const TOO_DETAILED: &str = "its art is too long or too detailed for a head";
const UNITED: &str = "its shapes could not be combined into one";
if art_anchors(&sym.art) > MAX_ART_ANCHORS {
return Err(TOO_DETAILED);
}
let art = baked_art(d, sym);
let mut shapes = Shapes::default();
painted(d, brushes, &art, &mut shapes);
if shapes.too_detailed {
return Err(TOO_DETAILED);
}
if shapes.failed {
return Err(UNITED);
}
let area = shapes.united().ok_or(UNITED)?;
let b = area.bounds().filter(|b| b.height() > 1e-9 && b.is_finite()).ok_or("its art paints nothing")?;
let tip = b.center() + d.symbol_registration(&sym.name).offset_from_center(b.width(), b.height());
// Head units: x back from the tip, y across to the right of +x, 4 units to the art's height.
let k = 4.0 / b.height();
let local = Affine::new([-k, 0.0, 0.0, k, k * tip.x, -k * tip.y]);
let h = CustomArrowhead::new(sym.name.clone(), area.transformed(local));
if h.path.subpaths.is_empty() {
return Err(TOO_DETAILED);
}
Ok(h)
}
/// The anchors of the paths in `n` and of the pieces of its gradient meshes ([`mesh_anchors`]), its
/// members' included.
fn art_anchors(n: &Node) -> usize {
let own = match &n.kind {
NodeKind::Mesh(m) => mesh_anchors(m),
_ => n.path_data().map_or(0, PathData::anchor_count),
};
n.children().map_or(own, |c| c.iter().fold(own, |sum, c| sum.saturating_add(art_anchors(c))))
}
/// The art of symbol `sym` of `d` with every geometry effect in it applied (its objects', fills',
/// strokes' and groups'), as the canvas draws it: the art baked as for export, on a copy of `d`.
fn baked_art(d: &Document, sym: &Symbol) -> Node {
// A plain new layer, so the file's own layers' effects stay out of the art.
let mut tmp = d.clone();
tmp.layers = Document::new(1.0, 1.0).layers;
let Some(children) = tmp.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) else { return (*sym.art).clone() };
*children = vec![sym.art.clone()];
let baked = vectorcraft_render::effects::bake_document(&tmp);
baked.as_ref().and_then(|b| b.layers.first()?.children()?.first().map(|c| (**c).clone())).unwrap_or_else(|| (*sym.art).clone())
}
/// The shapes a symbol's art paints, up to [`MAX_ART_ANCHORS`] anchors in all.
#[derive(Default)]
struct Shapes {
list: Vec<(PathData, FillRule)>,
anchors: usize,
/// More anchors were asked for than fit; the shapes past the limit were not made.
too_detailed: bool,
/// A clip group's art could not be combined or clipped, so a shape it paints is missing.
failed: bool,
}
impl Shapes {
/// Whether `anchors` more fit; when they do not, the shapes are too detailed.
fn room(&mut self, anchors: usize) -> bool {
self.too_detailed |= self.anchors.saturating_add(anchors) > MAX_ART_ANCHORS;
!self.too_detailed
}
fn push(&mut self, shape: (PathData, FillRule)) {
if self.room(shape.0.anchor_count()) {
self.anchors += shape.0.anchor_count();
self.list.push(shape);
}
}
/// The shapes united, or `None` when one of them could not be (the union would miss it).
fn united(&self) -> Option<PathData> {
let refs: Vec<(&PathData, FillRule)> = self.list.iter().map(|(p, r)| (p, *r)).collect();
vectorcraft_pathops::try_unite_all(&refs).ok()
}
/// The shapes of `inside` clipped to `outline` (filled under `rule`), added as one.
fn push_clipped(&mut self, inside: Shapes, outline: &PathData, rule: FillRule) {
if inside.too_detailed || !self.room(inside.anchors) {
self.too_detailed = true;
return;
}
self.failed |= inside.failed;
let clip = |art: PathData| {
vectorcraft_pathops::try_boolean(&art, FillRule::NonZero, outline, rule, BoolOp::Intersect, vectorcraft_pathops::DEFAULT_PRECISION).ok()
};
let Some(clipped) = inside.united().and_then(clip) else {
self.failed = true;
return;
};
if !clipped.subpaths.is_empty() {
self.push((clipped, FillRule::NonZero));
}
}
}
/// The shapes the shown paths and compound paths in `n` (baked art) paint: their filled areas and
/// their strokes' outlines, its groups' members included (baking has already made a group's own
/// fills and strokes art among its members), and the areas its gradient meshes cover. A clip
/// group's clipped art is clipped to
/// its clipping path, whose own fill and stroke paint unclipped, as on the canvas; a group used as
/// the clipping path paints nothing ([`clip_paint`]). Hidden or fully
/// transparent art is left out.
fn painted(d: &mut Document, brushes: &[vectorcraft_brush::Brush], n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Path { guide: true, .. } => {}
NodeKind::Path { .. } | NodeKind::Compound { .. } => {
fills(n, out);
// The outline holds a copy of the path for each fill too, which adds nothing new.
if let Some(o) = super::pathops::outline_strokes(d, brushes, n) {
fills_in(&o, out);
}
}
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| painted(d, brushes, part, out));
// Nothing to clip by hides the clipped art, as on the canvas.
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| painted(d, brushes, c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => children.iter().for_each(|c| painted(d, brushes, c, out)),
NodeKind::Mesh(_) => mesh_area(n, out),
_ => {}
}
}
/// What clipping path `clip` paints ([`Node::clip_paint`]): its fills and its strokes, each as a
/// copy of it keeping only those. A group or another object that does not paint as a clipping
/// path gives neither.
fn clip_paint(clip: &Node) -> Vec<Node> {
let paint = clip.clip_paint();
[paint.fill, paint.stroke].into_iter().flatten().collect()
}
/// The areas the shown paths and gradient meshes in `n` (an outlined stroke) fill, clipped by its
/// clip groups, whose clipping paths' own fills paint unclipped. A stroke with a gradient along or
/// across it is outlined as gradient meshes clipped to the stroke's outline.
fn fills_in(n: &Node, out: &mut Shapes) {
if !n.visible || n.opacity <= 0.0 || out.too_detailed {
return;
}
match &n.kind {
NodeKind::Mesh(_) => mesh_area(n, out),
NodeKind::Group { children, clip: true } => {
let Some((clip, rest)) = children.split_first() else { return };
clip_paint(clip).iter().for_each(|part| fills_in(part, out));
let Some((outline, rule)) = vectorcraft_render::effects::clip_outline(clip) else { return };
let mut inside = Shapes { anchors: out.anchors, ..Default::default() };
rest.iter().for_each(|c| fills_in(c, &mut inside));
inside.anchors -= out.anchors;
out.push_clipped(inside, &PathData::from_bezpath(&outline), rule);
}
_ => match n.children() {
Some(children) => children.iter().for_each(|c| fills_in(c, out)),
None => fills(n, out),
},
}
}
/// The anchors [`mesh_area`] makes at most of mesh `m`: its outline's, one a patch along each side,
/// when no point of it is fully transparent, else four by four quads of four anchors a patch.
fn mesh_anchors(m: &vectorcraft_doc::GradientMesh) -> usize {
let (rows, cols) = (m.rows as usize, m.cols as usize);
if opaque(m) { rows.saturating_add(cols).saturating_mul(2) } else { rows.saturating_mul(cols).saturating_mul(64) }
}
fn opaque(m: &vectorcraft_doc::GradientMesh) -> bool {
m.points.iter().all(|p| p.opacity > 0.0)
}
/// The area gradient mesh `n` paints: its outline when no point of it is fully transparent, else
/// the pieces of it that are not fully transparent (four by four quads a patch). A mesh whose
/// pieces do not fit in `out` makes the shapes too detailed.
fn mesh_area(n: &Node, out: &mut Shapes) {
let NodeKind::Mesh(m) = &n.kind else { return };
if !out.room(mesh_anchors(m)) {
return;
}
if opaque(m) {
let outline = m.outline();
if !outline.subpaths.is_empty() {
out.push((outline, FillRule::NonZero));
}
return;
}
for q in m.quads(4) {
if q.opacity > 0.0 || q.corners.iter().any(|(_, o)| *o > 0.0) {
out.push((PathData::single(SubPath::polyline(&q.pts, true)), FillRule::NonZero));
}
}
}
/// The area path `n` fills, when a shown fill paints it.
fn fills(n: &Node, out: &mut Shapes) {
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none());
if n.appearance.items.iter().any(paints)
&& let Some(shape) = super::pathops::node_path(n)
{
out.push(shape);
}
}
/// The document a missing arrowheads file starts as: one example head, a solid triangle.
pub fn starter() -> Document {
let mut doc = Document::new(612.0, 792.0);
doc.title = "Arrowheads".into();
let name = "Example Arrowhead";
let tri = SubPath::polyline(&[Point::new(-10.0, -8.0), Point::new(10.0, 0.0), Point::new(-10.0, 8.0)], true);
let art = Node::path(NodeId(0), PathData::single(tri), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0));
let art = doc.reid(&art);
doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false });
// The tip is the right edge's middle.
doc.set_symbol_registration(name, SymbolRegistration(5));
let id = doc.alloc_id();
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((306.0, 396.0)) });
let layer = doc.layers.first().map(|l| l.id);
let _ = doc.insert(layer, 0, instance);
doc
}
impl Session {
/// Keep the custom arrowheads in the file at `path` and read the heads it holds (none while it
/// is missing; an unreadable file is reported by `stroke.arrowheads.list`).
pub fn attach_arrowheads_file(&mut self, path: String) {
self.arrowheads.path = Some(path);
self.reload_arrowheads();
}
/// Read the arrowheads file again.
fn reload_arrowheads(&mut self) {
let Some(path) = self.arrowheads.path.clone() else { return };
match read(&path) {
Ok(Some(doc)) => self.arrowheads.set(heads_of(&doc)),
Ok(None) => self.arrowheads.set(Read::default()),
Err(e) => {
self.arrowheads.set(Read::default());
self.arrowheads.error = Some(e);
}
}
}
/// A document was saved to `path`: when that is the arrowheads file, its heads are read back
/// from what was written.
pub(crate) fn arrowheads_saved(&mut self, path: &str) {
if self.arrowheads.path.as_deref().is_some_and(|a| same_file(a, path)) {
self.reload_arrowheads();
}
}
}
fn same_file(a: &str, b: &str) -> bool {
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p));
std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b)
}
/// The document in the arrowheads file at `path`; `None` when there is no file.
fn read(path: &str) -> std::result::Result<Option<Document>, String> {
let size = match std::fs::metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(format!("{path}: {e}")),
Ok(m) if !m.is_file() => return Err(format!("{path}: not a file")),
Ok(m) => m.len(),
};
if size > MAX_FILE_BYTES {
return Err(format!("{path}: larger than {} MB", MAX_FILE_BYTES >> 20));
}
let bytes = crate::file_access::unconfined(|| super::fileio::read_file(path)).map_err(|e| e.to_string())?;
// A compressed file's document, and its images, may unpack to no more than an uncompressed
// file may hold.
let parse = || vectorcraft_format::load_file_capped(&bytes, MAX_FILE_BYTES).map(|f| f.doc).map_err(|e| format!("{path}: {e}"));
crate::guard::catch_panic(parse).map_err(|_| format!("{path}: could not be read"))?.map(Some)
}
fn has_file(s: &Session) -> std::result::Result<(), String> {
if s.arrowheads.path.is_some() { Ok(()) } else { Err("no arrowheads file here".into()) }
}
fn skipped(s: &Session) -> Vec<Value> {
s.arrowheads.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect()
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let heads: Vec<Value> = s.arrowheads.heads.iter().map(|h| json!({"name": h.name, "reach": h.reach(), "halfWidth": h.half_width()})).collect();
Ok(json!({"arrowheads": heads, "file": s.arrowheads.path, "skipped": skipped(s), "error": s.arrowheads.error}))
}
fn reload(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.reload";
s.reload_arrowheads();
if let Some(e) = &s.arrowheads.error {
return Err(bad(C, e.clone()));
}
Ok(json!({"count": s.arrowheads.heads.len(), "skipped": skipped(s)}))
}
fn edit(s: &mut Session, _: &Value) -> Result<Value> {
const C: &str = "stroke.arrowheads.edit";
let path = s.arrowheads.path.clone().ok_or_else(|| bad(C, "no arrowheads file here"))?;
if let Some(dir) = std::path::Path::new(&path).parent() {
std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?;
}
// Made only when no file is there, also when another run makes one at the same moment.
let bytes = vectorcraft_format::save_file(&starter());
let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) {
Ok(()) => true,
Err(_) if std::path::Path::new(&path).exists() => false,
Err(e) => return Err(bad(C, e.to_string())),
};
if created {
s.reload_arrowheads();
}
// Already open: that document comes to the front.
let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path)));
match open {
Some(i) => {
s.set_active(i);
}
None => {
crate::file_access::unconfined(|| s.execute("document.open", &json!({ "path": path })))?;
}
}
Ok(json!({"path": path, "created": created}))
}
+271
View File
@@ -0,0 +1,271 @@
//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool
//! is chosen.
use serde_json::{Value, json};
use vectorcraft_doc::Scaling;
use vectorcraft_geom::{Rect, Vec2};
use super::object::choice;
use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards};
use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or};
use crate::EngineError;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"artboard.align",
"Align",
[],
None,
"{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it, art inside two of them with the first by index, which may stay; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}",
has_doc,
align
),
cmd!(
"artboard.distribute",
"Distribute",
[],
None,
"{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
has_doc,
distribute
),
cmd!(
"artboard.distributeSpacing",
"Distribute Spacing",
[],
None,
"{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}",
has_doc,
distribute_spacing
),
]
}
/// What an artboard Align or Distribute command acts on, read from its params.
struct Boards {
/// The artboards named, in artboard order, each with its rectangle.
items: Vec<(usize, Rect)>,
/// With `to: "artboard"`, the artboard to align to and its rectangle.
reference: Option<(usize, Rect)>,
/// Whether the art inside each artboard moves with it.
move_art: bool,
/// Whether locked and hidden art moves too.
locked_art: bool,
}
/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing`
/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The
/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the
/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails
/// when every artboard named is locked.
fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result<Boards> {
check_switches(p, &["patterns"], cmd)?;
let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard");
let indices = named_or_selected(s, p, cmd)?;
let given = |key: &str| -> Result<Option<usize>> {
match p.get(key).filter(|v| !v.is_null()) {
Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some),
None => Ok(None),
}
};
let (named, recorded) = (given("artboard")?, given("activeArtboard")?);
let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?;
let locked_art = locked_and_hidden(s, p, move_art, cmd)?;
note_artboards(s, p, &indices);
s.note_journal("moveArt", json!(move_art));
let reference = match (to_artboard, named.or(recorded)) {
(false, _) => None,
(true, Some(i)) => Some(i),
(true, None) => {
let active = s.tool_options_of("artboard")["active"].clone();
Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?)
}
};
if let Some(i) = reference.filter(|_| named.is_none()) {
s.note_journal("activeArtboard", json!(i));
}
let d = &s.doc()?.doc;
let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into()));
let items = indices.iter().map(|i| rect(*i)).collect::<Result<Vec<_>>>()?;
if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) {
return Err(EngineError::Other("the artboard is locked".into()));
}
Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art })
}
/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null.
fn spacing(p: &Value, cmd: &str) -> Result<Option<f64>> {
p.get("spacing")
.filter(|v| !v.is_null())
.map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number")))
.transpose()
}
/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it
/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error
/// (`no such artboard`), since the gap is measured from it.
fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option<f64>) -> Result<Option<usize>> {
let Some((reference, _)) = b.reference else { return Ok(None) };
match items.iter().position(|(i, _)| *i == reference) {
None if gap.is_some() => Err(EngineError::Other("no such artboard".into())),
at => Ok(at),
}
}
/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when
/// `b` says so, the art inside it; art inside two of the artboards `b` names goes with the one
/// first in artboard order, and stays when that one stays. Locked artboards stay where they are.
/// When no artboard moves
/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit
/// fails with nothing changed when an artboard would end up past the canvas, as every edit does.
fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result<Value> {
let d = &s.doc()?.doc;
let mut moves: Vec<(usize, Vec2)> =
moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect();
// In artboard order, as the other artboard edits take them, whatever order the Distribute
// commands spaced them in.
moves.sort_by_key(|(i, _)| *i);
let moved: Vec<usize> = moves.iter().map(|(i, _)| *i).collect();
if moves.is_empty() {
return Ok(json!({ "moved": moved }));
}
// The art of every artboard named, those that stay included, so that art on overlapping
// artboards goes with the first by index; then that of the artboards that move.
let named: Vec<usize> = b.items.iter().map(|(i, _)| *i).collect();
let arts: Vec<(usize, Vec<NodeId>)> =
artboards_art(s, &named, b.move_art, b.locked_art, true)?.into_iter().filter(|(i, _)| moved.contains(i)).collect();
let ids: Vec<NodeId> = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect();
let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() };
s.edit(label, |d, _| {
for ((i, dv), (_, art)) in moves.iter().zip(&arts) {
let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?;
a.rect = a.rect + *dv;
let id = a.id;
d.move_artboard_guides(id, *dv);
for id in art {
if let Some(n) = d.node_mut(*id) {
n.transform(Affine::translate(*dv), sc);
super::object::keep_pixel_aligned(n, sc);
}
}
}
Ok(())
})?;
Ok(json!({ "moved": moved }))
}
fn align(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.align";
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
if h.is_none() && v.is_none() {
return Err(bad(C, "give horizontal or vertical"));
}
let b = boards(s, p, C)?;
let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else {
return Ok(json!({ "moved": [] }));
};
let moves: Vec<(usize, Vec2)> = b
.items
.iter()
.map(|(i, a)| {
let dx = match h {
Some("left") => r.x0 - a.x0,
Some("center") => r.center().x - a.center().x,
Some("right") => r.x1 - a.x1,
_ => 0.0,
};
let dy = match v {
Some("top") => r.y0 - a.y0,
Some("center") => r.center().y - a.center().y,
Some("bottom") => r.y1 - a.y1,
_ => 0.0,
};
(*i, Vec2::new(dx, dy))
})
.collect();
apply(s, "Align", p, &b, &moves)
}
fn distribute(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.distribute";
let h = choice(p, C, "horizontal", &["left", "center", "right"])?;
let v = choice(p, C, "vertical", &["top", "center", "bottom"])?;
let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) {
(Some("left"), _) => (true, |r| r.x0),
(Some("right"), _) => (true, |r| r.x1),
(Some(_), _) => (true, |r| r.center().x),
(None, Some("top")) => (false, |r| r.y0),
(None, Some("bottom")) => (false, |r| r.y1),
(None, Some(_)) => (false, |r| r.center().y),
(None, None) => return Err(bad(C, "give horizontal or vertical")),
};
let gap = spacing(p, C)?;
let b = boards(s, p, C)?;
let mut items = b.items.clone();
items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1)));
let kept = kept(&b, &items, gap)?;
// With a spacing: the place in the order and the line of the artboard it is measured from.
let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r))));
let n = items.len();
// Two artboards are the ends already; with a spacing the second is placed from the first.
if n < if from.is_some() { 2 } else { 3 } {
return Ok(json!({ "moved": [] }));
}
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
let (first, last) = (line(first), line(last));
let deltas: Vec<f64> = items
.iter()
.enumerate()
.map(|(k, (_, r))| {
let target = match from {
Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64),
None => first + (last - first) * k as f64 / (n - 1) as f64,
};
target - line(r)
})
.collect();
// The artboard aligned to stays where it is, and the others keep their places from it.
let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0);
let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect();
apply(s, "Distribute", p, &b, &moves)
}
fn distribute_spacing(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "artboard.distributeSpacing";
let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical");
let gap = spacing(p, C)?;
let b = boards(s, p, C)?;
let start = |r: &Rect| if horiz { r.x0 } else { r.y0 };
let size = |r: &Rect| if horiz { r.width() } else { r.height() };
let mut items = b.items.clone();
items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1)));
let kept = kept(&b, &items, gap)?;
let gap = gap.filter(|_| kept.is_some());
let n = items.len();
if n < if gap.is_some() { 2 } else { 3 } {
return Ok(json!({ "moved": [] }));
}
let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) };
let (lo, hi) = (start(first), start(last) + size(last));
let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::<f64>()) / (n - 1) as f64);
let mut pos = lo;
let mut deltas = Vec::with_capacity(n);
for (i, r) in &items {
deltas.push((*i, pos - start(r)));
pos += size(r) + gap;
}
// The artboard aligned to stays where it is, and the others keep their places from it.
let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1);
let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect();
apply(s, "Distribute Spacing", p, &b, &moves)
}
/// An offset of `d` along the axis: x when `horiz`, else y.
fn along(horiz: bool, d: f64) -> Vec2 {
if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) }
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,310 @@
//! Align and Distribute for artboards.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
use crate::tooling::ViewInfo;
/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner:
/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids.
fn three_boards() -> (Session, [u64; 3]) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap();
s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap();
let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
let ids = [sq(5, 5), sq(155, 45), sq(405, 15)];
s.execute("select.none", &json!({})).unwrap();
(s, ids)
}
/// The top-left corner of each artboard.
fn corners(s: &Session) -> Vec<(f64, f64)> {
s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect()
}
/// The top-left corner of object `id`.
fn corner(s: &Session, id: u64) -> (f64, f64) {
let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
(b.x0, b.y0)
}
fn undo_steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
const ALL: [u64; 3] = [0, 1, 2];
/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside
/// it, in one undo step.
#[test]
fn align_moves_the_artboards_to_their_common_edge_with_their_art() {
let (mut s, [a, b, c]) = three_boards();
let before = corners(&s);
let steps = undo_steps(&s);
let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
assert_eq!(out, json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]);
assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard");
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step");
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap();
assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap();
assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250");
assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art");
}
/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not
/// be one of the artboards aligned.
#[test]
fn align_to_an_artboard_keeps_that_artboard_in_place() {
let (mut s, _) = three_boards();
let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap();
assert_eq!(out, json!({"moved": [0, 1]}));
assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap();
assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80");
}
/// With no artboard named, the commands act on the artboards the Artboard tool has selected and
/// align to its active one; the journal records both for a replay, and an action leaves them out.
#[test]
fn the_artboard_tools_selection_is_the_default_and_is_recorded() {
let (mut s, [_, _, c]) = three_boards();
s.select_tool("artboard", ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([1, 2]));
let start = s.journal.len();
assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]);
assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on");
let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false});
assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded));
assert_eq!(
s.journal_for_action(start),
[("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))]
);
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1");
assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1));
assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap();
assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap();
assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one");
let action = s.journal_for_action(start);
let entry = &action.last().unwrap().1;
assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap();
s.set_tool_option("moveArt", &json!(false));
s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap();
assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays");
}
/// A command that moves no artboard leaves the document and its undo history as they are.
#[test]
fn nothing_to_move_records_no_undo_step() {
let (mut s, _) = three_boards();
s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap();
let (steps, before) = (undo_steps(&s), corners(&s));
for (id, p) in [
("artboard.align", json!({"indices": ALL, "vertical": "top"})),
("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})),
("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})),
("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})),
("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})),
("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})),
("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})),
] {
assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}");
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}");
}
}
/// A locked artboard stays where it is and still counts in the bounds and in the order. When every
/// artboard named is locked, the command fails.
#[test]
fn a_locked_artboard_stays_where_it_is() {
let (mut s, _) = three_boards();
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked");
let out =
s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap();
assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200");
s.execute("edit.undo", &json!({})).unwrap();
let (steps, before) = (undo_steps(&s), corners(&s));
for (id, p) in [
("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})),
("artboard.distribute", json!({"index": 1, "horizontal": "left"})),
("artboard.distributeSpacing", json!({"indices": [1]})),
] {
assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}");
assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}");
}
}
/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards;
/// with a spacing and an artboard to align to, it places them that far apart from that artboard.
#[test]
fn distribute_spaces_the_edges_or_centers() {
let (mut s, [_, b, _]) = three_boards();
assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450");
assert_eq!(corner(&s, b), (225.0, 45.0));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap();
assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120");
s.execute("edit.undo", &json!({})).unwrap();
let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100});
assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place");
s.execute("edit.undo", &json!({})).unwrap();
let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150});
assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]}));
assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500");
s.execute("edit.undo", &json!({})).unwrap();
let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1});
assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place");
}
/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard
/// to align to, the gaps are that wide and that artboard stays.
#[test]
fn distribute_spacing_makes_the_gaps_equal() {
let (mut s, _) = three_boards();
assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap();
assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55");
s.execute("edit.undo", &json!({})).unwrap();
let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap();
assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them");
s.execute("edit.undo", &json!({})).unwrap();
let held = json!({"indices": ALL, "to": "artboard", "artboard": 1});
assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]}));
assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place");
}
/// A value outside what a param takes is an error, and nothing changes.
#[test]
fn bad_params_are_errors() {
let (mut s, _) = three_boards();
let (steps, before) = (undo_steps(&s), corners(&s));
let with = |extra: Value| {
let mut p = json!({"indices": ALL, "horizontal": "left"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
p
};
let shared = [
json!({"horizontal": "middle"}),
json!({"horizontal": 1}),
json!({"to": "key"}),
json!({"to": "artboard", "artboard": 9}),
json!({"artboard": "1"}),
json!({"artboard": -1}),
json!({"moveArt": "yes"}),
json!({"patterns": 1}),
json!({"lockedAndHidden": "no"}),
json!({"indices": [9]}),
json!({"indices": []}),
json!({"indices": "0"}),
];
for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] {
let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) };
for extra in &shared {
let mut p = with(axis.clone());
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() {
p = json!({"indices": ALL, "axis": extra["horizontal"]});
}
assert!(s.execute(id, &p).is_err(), "{id} {p}");
}
}
for (id, p) in [
("artboard.align", json!({"indices": ALL})),
("artboard.align", json!({"indices": ALL, "vertical": "middle"})),
("artboard.distribute", json!({"indices": ALL})),
("artboard.distribute", with(json!({"spacing": "10"}))),
("artboard.distribute", with(json!({"spacing": true}))),
("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})),
("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})),
("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})),
] {
assert!(s.execute(id, &p).is_err(), "{id} {p}");
}
// Spacings that would put an artboard past the canvas, or overflow to infinity.
for (id, p) in [
("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))),
("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))),
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})),
("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})),
] {
let e = s.execute(id, &p).unwrap_err().to_string();
assert!(e.contains("exceed the canvas"), "{id} {p}: {e}");
}
assert_eq!((undo_steps(&s), corners(&s)), (steps, before));
}
/// Art inside two overlapping artboards moves with the one first in artboard order, as with the
/// other artboard edits, even when Distribute spaces the other one first: artboard 2 at x 140 is
/// left of artboard 1 at x 200, and the square inside both goes with artboard 1.
#[test]
fn art_on_overlapping_artboards_moves_with_the_first_by_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 140, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 210, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 10});
assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [1, 2]}));
assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 0.0), (110.0, 0.0)]);
assert_eq!(corner(&s, sq), (230.0, 10.0), "with artboard 1, 20 pt to the right");
}
/// Art inside an artboard that stays and a later one that moves stays with the first: artboard 2
/// overlaps artboard 0, and aligning it to artboard 0 leaves the square inside both in place.
#[test]
fn art_shared_with_an_artboard_that_stays_stays() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 200, "y": 0, "width": 100, "height": 100})).unwrap();
s.execute("artboard.new", &json!({"x": 60, "y": 0, "width": 100, "height": 100})).unwrap();
let sq = s.execute("shape.rectangle", &json!({"x": 70, "y": 10, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.none", &json!({})).unwrap();
let p = json!({"indices": [0, 2], "horizontal": "left", "to": "artboard", "artboard": 0});
assert_eq!(s.execute("artboard.align", &p).unwrap(), json!({"moved": [2]}));
assert_eq!(corners(&s)[2], (0.0, 0.0));
assert_eq!(corner(&s, sq), (70.0, 10.0), "with artboard 0, which stays");
}
/// An artboard's own guides move with it.
#[test]
fn an_artboards_guides_move_with_it() {
let (mut s, _) = three_boards();
s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap();
s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap();
let d = &s.doc().unwrap().doc;
let positions: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect();
assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1");
}
+2 -2
View File
@@ -208,7 +208,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Options…",
[],
None,
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
"{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}",
has_doc,
symbol_options
),
@@ -326,7 +326,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Select All Unused",
[],
None,
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
"{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used",
has_doc,
symbol_unused
),
+31
View File
@@ -115,6 +115,8 @@ fn art_symbols(n: &Node, out: &mut Vec<String>) {
if let NodeKind::SymbolInstance { symbol, .. } = &m.kind {
out.push(symbol.clone());
}
// A graphic on a 3D object draws its symbol's art too.
out.extend(vectorcraft_render::effects::graphic_symbols(m));
});
}
@@ -129,6 +131,8 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art));
trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo));
// A graphic in a graphic style draws its symbol's art wherever the style is applied.
todo.extend(d.graphic_styles.iter().flat_map(|g| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance)));
let mut used = std::collections::BTreeSet::new();
while let Some(name) = todo.pop() {
if !used.contains(&name) {
@@ -290,6 +294,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result<Value> {
*symbol = n.clone();
}
}
// The graphics mapped onto 3D objects follow the new name: in the layers, the art of
// symbols, patterns, graph designs and brushes, their opacity masks, and graphic styles.
let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()));
let trees = d
.layers
.iter_mut()
.chain(d.symbols.iter_mut().map(|sym| &mut sym.art))
.chain(d.graph_designs.iter_mut().map(|g| &mut g.art))
.chain(patterns.flat_map(|p| p.art.iter_mut()));
for art in trees.filter(|art| vectorcraft_render::effects::names_graphic_symbol(art, &name)) {
vectorcraft_render::effects::rename_graphic_symbol_in(Arc::make_mut(art), &name, n);
}
let styled = |g: &vectorcraft_doc::GraphicStyle| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance).contains(&name);
if d.graphic_styles.iter().any(styled) {
for style in d.graphic_styles.iter_mut() {
vectorcraft_render::effects::rename_appearance_graphic_symbol(&mut style.appearance, &name, n);
}
}
// The brush library is stored again only when a brush's art changed.
let mut lib = brush::library(d);
let mut brushes = false;
for art in lib.iter_mut().flat_map(|b| b.art_mut()) {
brushes |= vectorcraft_render::effects::rename_graphic_symbol_in(art, &name, n);
}
if brushes {
brush::store(d, &lib);
}
rename_natural_size(d, &name, n);
d.rename_symbol_registration(&name, n);
d.rename_symbol_export_type(&name, n);
+1 -1
View File
@@ -144,7 +144,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Image Trace"],
None,
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, automatic: flat art with its own colours, else fullTone, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px, method: \"abutting\"|\"overlapping\", ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
has_selection_or_ids,
|s, p| trace_make(s, p, false)
),
+29 -5
View File
@@ -88,8 +88,9 @@ pub struct Clipboard {
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
pub source_artboard: Option<Rect>,
/// Per object: the name of the layer it was copied from (Paste Remembers Layers).
pub source_layers: Vec<Option<String>>,
/// Per object: the layer or sublayer it was copied from and the layers around it (Paste
/// Remembers Layers); none when that layer has no name.
pub source_layers: Vec<Option<SourceLayer>>,
/// The open document the objects came from ([`DocState::uid`]): pasting back into it uses its
/// own resources as they are now.
pub source_doc: Option<u64>,
@@ -101,6 +102,29 @@ pub struct Clipboard {
pub guides: Vec<vectorcraft_doc::Guide>,
}
/// The layer an object was copied from, as Paste Remembers Layers finds it again: the top-level
/// layer first, down to the layer or sublayer that holds the object.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct SourceLayer {
/// The layers' ids in the source document ([`Clipboard::source_doc`]).
pub ids: Vec<NodeId>,
/// The layers' names (an unnamed layer above the one that holds the object is "").
pub names: Vec<String>,
}
impl SourceLayer {
/// The layers around the object `anc` ends with ([`Document::ancestry`]); none when the layer
/// that holds it has no name.
fn of(d: &Document, anc: &[NodeId]) -> Option<Self> {
let layers: Vec<&Node> = anc.iter().rev().skip(1).filter_map(|a| d.node(*a).filter(|l| l.is_layer())).collect();
layers.first()?.name.as_ref()?;
Some(Self {
ids: layers.iter().rev().map(|l| l.id).collect(),
names: layers.iter().rev().map(|l| l.name.clone().unwrap_or_default()).collect(),
})
}
}
/// Indices of segments selected on `sp` (either explicitly or via incident anchors).
pub(crate) fn subpath_selected_segments(
sp: &vectorcraft_geom::SubPath,
@@ -256,7 +280,7 @@ impl Clipboard {
let mut compound_bounds: std::collections::HashMap<NodeId, Option<vectorcraft_geom::Rect>> = std::collections::HashMap::new();
for id in roots {
let (Some(n), Some(anc)) = (d.node(*id), d.ancestry(*id)) else { continue };
let layer_name = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|l| l.is_layer())).and_then(|l| l.name.clone());
let source_layer = SourceLayer::of(d, &anc);
let compound_parent = anc.iter().rev().skip(1).find_map(|a| d.node(*a).filter(|p| matches!(p.kind, NodeKind::Compound { .. })));
// Gradients fitted to the compound's bounds are pinned there, as a split pins them.
let gradient_box = compound_parent
@@ -299,11 +323,11 @@ impl Clipboard {
if direct && let Some(pieces) = extract_direct_selection(n, &st.selection) {
for piece in pieces {
nodes.push(inherit_appearance(piece));
source_layers.push(layer_name.clone());
source_layers.push(source_layer.clone());
}
} else {
nodes.push(inherit_appearance(n.clone()));
source_layers.push(layer_name);
source_layers.push(source_layer);
}
}
// Symbol instances are measured by their art.
+51 -70
View File
@@ -86,6 +86,10 @@ fn paint_refs(p: &Paint, f: Visit) {
}
fn appearance_refs(a: &Appearance, f: Visit) {
// The graphics mapped onto the faces of its 3D effects name symbols.
for s in vectorcraft_render::effects::appearance_graphic_symbols(a) {
f(Ref::Name(Res::Symbol, &s));
}
for it in &a.items {
paint_refs(it.paint(), f);
if let AppearanceItem::Stroke(l) = it
@@ -119,6 +123,10 @@ fn node_refs(n: &Node, f: Visit) {
if let Some(mask) = &m.extras().mask {
node_refs(&mask.art, f);
}
// A color-masked image's masked pixels go with it.
if let Some(cm) = Document::color_mask_of(m) {
f(Ref::Name(Res::Image, &cm.key));
}
match &m.kind {
NodeKind::Text(t) => {
for r in &t.runs {
@@ -620,6 +628,17 @@ impl Relink {
}
}
}
// A 3D effect's mapped graphics follow their symbols' names in the document. Each name is
// looked up once, so renames that chain (A to B, B to C) do not apply twice.
let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut());
for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) {
let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut);
for g in list.into_iter().flatten() {
if let Some(Value::String(s)) = g.get_mut("symbol") {
self.name(Res::Symbol, s);
}
}
}
for it in &mut a.items {
self.paint(it.paint_mut());
if let AppearanceItem::Stroke(l) = it
@@ -648,6 +667,10 @@ impl Relink {
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
self.node(Arc::make_mut(&mut m.art));
}
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
self.name(Res::Image, &mut cm.key);
self.name(Res::Image, &mut cm.from);
}
match &mut n.kind {
NodeKind::Text(t) => {
for r in &mut t.runs {
@@ -697,15 +720,6 @@ fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
relinked(&Relink::default(), ours) == relinked(r, theirs)
}
/// Does brush `b`'s art show symbols or patterns?
fn shows_definitions(b: &Brush) -> bool {
let mut found = false;
for a in b.art() {
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
}
found
}
/// A symbol's Symbol Options, which its document keeps by symbol name: copied with the symbol and
/// given to it under the name pasting adds it as.
#[derive(Clone, Debug, PartialEq)]
@@ -739,7 +753,7 @@ impl SymbolOptions {
}
/// A character or paragraph style, symbol (with the Symbol Options copied with it), pattern or
/// brush (placed with the others only when they are placed in use order) to place
/// brush to place
/// ([`Clipboard::import_used`]).
#[derive(Clone, Copy)]
enum Def<'c> {
@@ -1055,49 +1069,40 @@ impl Clipboard {
}
/// Add the resources the objects use to `d` (inside the paste's undo step) and work out how
/// pasted copies relink to them. An error, with `d` unchanged, when a pasted SVG filter finds no
/// free name ([`Self::filter_links`]).
/// pasted copies relink to them. Each style, symbol, pattern and brush is placed after those it
/// uses, as [`import_text_styles`] places them, so that a style that paints with a pattern added
/// under a free name ("Dots 2") is compared and added with that name. An error, with `d`
/// unchanged, when a pasted SVG filter finds no free name ([`Self::filter_links`]).
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used(d, &self.used(), choices, same_doc, false)
self.import_used(d, &self.used(), choices, same_doc)
}
/// [`Self::import_into`] for the resources `used` names. The character and paragraph styles
/// come before the symbols and patterns, whose art may set type in them; with `in_use_order`,
/// each style, symbol, pattern and brush comes after the styles, symbols, patterns and brushes it uses
/// ([`use_order`]), so that it is compared and relinked with their names here, and each loop
/// of definitions that use each other is matched on its own ([`loop_groups`]).
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, in_use_order: bool) -> Result<Imported> {
/// [`Self::import_into`] for the resources `used` names. Each style, symbol, pattern and brush
/// comes after the styles, symbols, patterns and brushes it uses ([`use_order`]), so that it is
/// compared and relinked with their names here, and each loop of definitions that use each
/// other is matched on its own ([`loop_groups`]). Pasted back into its own document
/// (`same_doc`), each definition of a loop is the document's of its name.
fn import_used(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
self.import_images(d, used, same_doc, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
// they may brush; the others once those are in. With `in_use_order`, the brushes are
// placed in use order with the others.
let mut added_brushes: HashSet<String> =
if in_use_order { HashSet::new() } else { self.import_brushes(d, used, same_doc, false, &mut out).into_iter().collect() };
let mut defs: Vec<Def<'_>> = vec![];
for (r, list) in [(Res::CharStyle, &self.char_styles), (Res::ParaStyle, &self.para_styles)] {
defs.extend(list.iter().filter(|s| used.has(r, &s.name)).map(|s| Def::Style(r, s)));
}
defs.extend(self.symbols.iter().filter(|s| used.has(Res::Symbol, &s.name)).map(|s| Def::Symbol(s, self.symbol_options.get(&s.name))));
defs.extend(self.patterns.iter().filter(|p| used.has(Res::Pattern, &p.name)).map(Def::Pattern));
if in_use_order {
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
}
defs.extend(self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).map(Def::Brush));
// Groups to place in order; true for a loop of definitions that use each other.
let groups: Vec<(Vec<Def<'_>>, bool)> = if in_use_order {
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
std::iter::once((order, false)).chain(loops).collect()
} else {
vec![(defs, false)]
};
// Styles (their colors relinked first), symbols and patterns (compared once relinked,
// symbols with their options too). The symbols and patterns added are relinked at the end,
// when every new name and graphic style id is known; with `in_use_order`, so are the
// styles added, which a loop of uses may place before a pattern they paint with.
let (mut added_symbols, mut added_patterns, mut added_styles) = (HashSet::new(), HashSet::new(), vec![]);
let (order, rest) = use_order(defs);
let loops = loop_groups(&rest).into_iter().map(|(at, looped)| (at.into_iter().filter_map(|i| rest.get(i).copied()).collect(), looped));
let groups: Vec<(Vec<Def<'_>>, bool)> = std::iter::once((order, false)).chain(loops).collect();
// Styles (their colors relinked first), symbols, patterns and brushes (compared once
// relinked, symbols with their options too). The styles, symbols, patterns and brushes
// added are relinked at the end, when every new name and graphic style id is known: a loop
// of uses may place one before a definition it uses.
let (mut added_symbols, mut added_patterns, mut added_brushes, mut added_styles) = (HashSet::new(), HashSet::new(), HashSet::new(), vec![]);
// Each definition, whether it is in a loop, and the loop it starts.
let steps = groups
.iter()
@@ -1107,8 +1112,8 @@ impl Clipboard {
let mut fresh = false;
// The names in the document of the loop being placed, when it has them all at once.
let mut matched: BTreeMap<(Res, String), String> = BTreeMap::new();
// The document's brush library, read the first time a brush is placed in use order and
// stored again after each brush added; nothing else in the loop changes it.
// The document's brush library, read the first time a brush is placed and stored again
// after each brush added; nothing else in the loop changes it.
let mut library: Option<Vec<Brush>> = None;
for (def, looped, starts) in steps {
fresh &= looped;
@@ -1116,8 +1121,9 @@ impl Clipboard {
matched.clear();
}
// A loop of uses that the document has all at once is known under those names before
// its definitions are compared.
if let Some(group) = starts {
// its definitions are compared. In its own document, each definition is the
// document's of its name, as outside a loop.
if let Some(group) = starts.filter(|_| !same_doc) {
matched.clear();
match names_of_loop(d, group, &out.relink) {
Some(names) => {
@@ -1146,7 +1152,7 @@ impl Clipboard {
out.relink.attrs(&mut s.attrs);
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
let p = place(theirs, &s, same_doc, |a, b| !fresh && a == b);
if in_use_order && let Some(name) = p.new_name(&def.name) {
if let Some(name) = p.new_name(&def.name) {
added_styles.push((r, name, def));
}
out.placed(r, &def.name, &p);
@@ -1200,9 +1206,6 @@ impl Clipboard {
}
}
}
if !in_use_order {
added_brushes.extend(self.import_brushes(d, used, same_doc, true, &mut out));
}
self.import_graphic_styles(d, used, same_doc, &mut out);
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
@@ -1323,28 +1326,6 @@ impl Clipboard {
}
}
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
/// document has (its art compared once relinked) is used, the others are added. → the names of
/// those added, whose art is relinked at the end.
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
if brushes.is_empty() {
return vec![];
}
let mut lib = vectorcraft_brush::library(d);
let mut added = vec![];
for b in brushes {
let r = &out.relink;
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
added.extend(p.new_name(&b.name));
out.placed(Res::Brush, &b.name, &p);
}
if !added.is_empty() {
vectorcraft_brush::store(d, &lib);
}
added
}
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
/// swatches of the tints used and the gradient swatches.
fn import_swatches(&self, d: &mut Document, used: &Used, choices: &SwatchChoices, same_doc: bool, out: &mut Imported) {
@@ -1429,7 +1410,7 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
let used = Used::of_text_styles(&Defs::of(src, &library), chars, paras);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let before = [&d.char_styles, &d.para_styles].map(|l| l.iter().map(|s| s.name.clone()).collect::<BTreeSet<_>>());
let out = clip.import_used(d, &used, &SwatchChoices::default(), false, true)?;
let out = clip.import_used(d, &used, &SwatchChoices::default(), false)?;
let mut placed: Vec<LoadedStyle> = vec![];
for (para, r, list) in [(false, Res::CharStyle, &clip.char_styles), (true, Res::ParaStyle, &clip.para_styles)] {
for s in list {
+82 -29
View File
@@ -5,7 +5,9 @@
//! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`,
//! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in
//! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and
//! become active when assigned.
//! take the place of the working spaces in the active settings when assigned, and when the working
//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay
//! as Edit → Color Settings set them.
use std::collections::BTreeMap;
use std::sync::Arc;
@@ -59,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Assign Profile…",
["Edit"],
None,
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (colour numbers are kept) → {rgb, cmyk}",
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
has_doc,
assign_profile
),
@@ -176,9 +178,19 @@ fn touch_all(s: &mut Session) {
}
}
/// Make the active settings the working settings with the profiles the front document is assigned
/// in place of the working spaces (none, or no document open: the working spaces). The open
/// documents redraw when the active settings change.
fn use_front_profiles(s: &mut Session) {
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) {
touch_all(s);
}
}
fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "edit.colorSettings";
let mut st = cms::active_settings();
let mut st = cms::working_settings();
let before = st.clone();
if let Some(v) = text_param(p, "rgb", C)? {
st.rgb = cms::canonical_name(v).to_string();
@@ -194,6 +206,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result<Value> {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
// Saved for the next start when the app attached a settings file (#6335).
s.store_color_settings(&st);
use_front_profiles(s);
touch_all(s);
}
Ok(settings_json(&st))
@@ -208,10 +221,18 @@ fn load_profile(s: &mut Session, p: &Value) -> Result<Value> {
let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?;
// The bytes are kept, not the path: the file may move or go away.
let remembered = s.store_profile(&info.name, &bytes);
// A new file of a working space: the active settings still hold the old one.
let working = cms::active_settings();
if working.rgb == info.name || working.cmyk == info.name {
// A new file of a working space or of an assigned profile in use: the active settings still
// hold the old one. A profile the front document is assigned, loaded after it was removed, is
// in use again.
let (working, active) = (cms::working_settings(), cms::active_settings());
let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default();
let front = [rgb, cmyk].iter().any(|n| n.as_deref() == Some(info.name.as_str()));
if front || [&working.rgb, &working.cmyk, &active.rgb, &active.cmyk].contains(&&info.name) {
cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?;
use_front_profiles(s);
touch_all(s);
} else if proof_targets(&info.name) {
// A new file of the CMYK profile View → Proof Setup targets: redraw.
touch_all(s);
}
Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered}))
@@ -225,18 +246,32 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result<Value> {
if info.builtin {
return Err(bad(C, format!("`{name}` is a built-in profile and stays")));
}
let working = cms::active_settings();
let working = cms::working_settings();
if working.rgb == name || working.cmyk == name {
return Err(bad(C, format!("`{name}` is a working space: choose another with edit.colorSettings first")));
}
let active = cms::active_settings();
if !cms::unregister_icc(&info.name) {
return Err(bad(C, format!("no profile named `{name}`")));
}
s.unstore_profile(&info.name);
touch_all(s);
// An assigned profile in use: the working space takes its place, as for any document assigned
// a profile that is not available.
if active.rgb == name || active.cmyk == name {
use_front_profiles(s);
}
// The CMYK profile View → Proof Setup targets: redraw.
if proof_targets(&info.name) {
touch_all(s);
}
Ok(json!({"removed": info.name}))
}
/// Whether View → Proof Setup targets the CMYK profile `name`.
fn proof_targets(name: &str) -> bool {
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name)
}
#[cfg(target_arch = "wasm32")]
fn load_profile(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("color.loadProfile", "loading profiles from disk isn't available in the browser"))
@@ -273,18 +308,9 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result<Value> {
d.color_profiles = profiles;
Ok(())
})?;
let mut st = cms::active_settings();
let before = st.clone();
if let Some(r) = &rgb {
st.rgb = r.clone();
}
if let Some(c) = &cmyk {
st.cmyk = c.clone();
}
if st != before {
cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?;
touch_all(s);
}
// The document draws through its profiles now, and a Document Color Mode later in the same
// batch converts through them. The working spaces stay as they are.
use_front_profiles(s);
}
Ok(json!({"rgb": rgb, "cmyk": cmyk}))
}
@@ -371,7 +397,9 @@ pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> {
Ok(())
}
fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
/// Record new-art paints `before` and the session's current ones with the step just made (or the
/// interaction or undo group in progress), so Undo puts `before` back and Redo the current ones.
pub(super) fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> {
let after = s.paint.clone();
if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() {
let st = s.doc_mut()?;
@@ -396,7 +424,9 @@ fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaul
Ok(())
}
fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
/// The new-art paints an undo step that starts now puts back: those at the start of the undo group
/// or interaction in progress, else the session's current ones.
pub(super) fn new_art_colors_before(s: &Session) -> Result<vectorcraft_tools::PaintDefaults> {
let st = s.doc()?;
Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone()))
}
@@ -763,17 +793,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(on) = on_param(p, "proof", C)? {
v.proof_colors = on;
}
proof::set_view(v.clone());
touch_all(s);
store_view(s, v.clone());
Ok(view_json(&v))
}
/// Make `v` the proof view and redraw every document. When `v` equals the current view, the view
/// and the revisions stay as they are; Separations Preview's visible plates are compared as a set.
fn store_view(s: &mut Session, v: proof::ProofView) {
let shown = |v: &proof::ProofView| proof::ProofView {
separations: v.separations.as_ref().map(|vis| {
let mut vis = vis.clone();
vis.sort();
vis.dedup();
vis
}),
..v.clone()
};
if shown(&v) != shown(&proof::view()) {
proof::set_view(v);
touch_all(s);
}
}
fn toggle_view(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut proof::ProofView, Option<bool>)) -> Result<Value> {
let on = on_param(p, "on", cmd)?;
let mut v = proof::view();
f(&mut v, on);
proof::set_view(v.clone());
touch_all(s);
store_view(s, v.clone());
Ok(view_json(&v))
}
@@ -805,7 +851,15 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
match p.get("plates") {
None | Some(Value::Null) => {}
Some(Value::Array(a)) if a.iter().all(Value::is_string) => {
v.separations = Some(a.iter().filter_map(Value::as_str).map(check).collect::<Result<Vec<_>>>()?);
let mut vis: Vec<String> = Vec::new();
for n in a.iter().filter_map(Value::as_str) {
let n = check(n)?;
// A plate named twice is shown once.
if !vis.contains(&n) {
vis.push(n);
}
}
v.separations = Some(vis);
}
Some(_) => {
let key = "plates";
@@ -824,8 +878,7 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> {
vis.push(n);
}
}
proof::set_view(v);
touch_all(s);
store_view(s, v);
Ok(plates_json(s))
}
+33 -13
View File
@@ -7,8 +7,8 @@ use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_svg::{CssOptions, CssSheet, css_rules};
use super::fileio::{default_name, encode_with_warnings, isolated, write_file};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, str_param, targets};
use super::fileio::{Note, default_name, encode_with_notes, isolated, note_texts, write_file};
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, named_ids, targets};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -21,13 +21,13 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
selection
),
cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document", has_doc, generate),
cmd!(query "css.generate", "Generate CSS", [], None, "{…options as css.selection} css.selection of every object in the document; ids and id are not used, and a malformed one is an error", has_doc, generate),
cmd!(
"css.export",
"Export CSS",
[],
None,
"{path?, scope?: selection|all (default selection; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
"{path?: string, scope?: selection|all (default selection when left out; ids? picks the objects), …options as css.selection, id?: object id (default: the selection)} a path or scope given as anything but a string, null included, is an error, and so is a malformed ids or id with scope all, which does not use them; write the CSS (css.selection, or css.generate for all) to path and, with rasterize, each picture its rules refer to next to it (PNG of what the object draws, with the clips, masks and effects of the groups and layers that hold it, 1 px per point) → {path, bytes, rules: n, images: [path…], warnings}; no path → {data: the CSS, name: <document>.css, rules, images: [{name, dataBase64}], warnings}; warnings are css.selection's and the pictures' as document.export gives them (an image that couldn't be decoded, type in the fallback font or that doesn't fit its frame), each once",
has_doc,
export
),
@@ -77,16 +77,34 @@ fn selection(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result(&sheet(s, p, ids, "css.selection")?))
}
/// Checks the form of the `ids` or `id` that `p` gives a command that exports every object and does
/// not use them: a malformed one is an error, as it is for the selection.
fn unused_ids(p: &Value) -> Result<()> {
named_ids(p).map(|_| ())
}
fn generate(s: &mut Session, p: &Value) -> Result<Value> {
unused_ids(p)?;
let ids = everything(s)?;
Ok(result(&sheet(s, p, ids, "css.generate")?))
}
/// The string `p` gives for `key`, or `None` when `p` leaves it out. Any value given that is not a
/// string, null included, is an error: "`{key}` must be a string".
fn given_text<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<Option<&'a str>> {
p.get(key).map(|v| v.as_str().ok_or_else(|| bad(cmd, format!("`{key}` must be a string")))).transpose()
}
fn export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "css.export";
let ids = match str_param(p, "scope").unwrap_or("selection") {
let scope = given_text(p, "scope", C)?;
let path = given_text(p, "path", C)?;
let ids = match scope.unwrap_or("selection") {
"selection" => targets(s, p)?,
"all" => everything(s)?,
"all" => {
unused_ids(p)?;
everything(s)?
}
other => return Err(bad(C, format!("scope must be selection or all (got {other})"))),
};
let sheet = sheet(s, p, ids, C)?;
@@ -100,22 +118,24 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
}
let css = format!("{}\n", sheet.text());
let doc = &s.doc()?.doc;
// Encode the pictures of rasterized art, and add each of their warnings once.
// Encode the pictures of rasterized art, and add each of their warnings once. What CSS can't
// describe is a loss.
let mut images = Vec::new();
let mut warnings = sheet.warnings.clone();
let mut notes: Vec<Note> = sheet.warnings.iter().cloned().map(Note::loss).collect();
for r in &sheet.rules {
let Some(name) = &r.image else { continue };
let (d, _) = isolated(doc, &[r.id], name).ok_or_else(|| bad(C, format!("{} paints nothing to rasterize", r.selector)))?;
let (png, notes) = encode_with_warnings(&d, "png", &json!({}))?;
let (png, given) = encode_with_notes(&d, "png", &json!({}))?;
images.push((name, png));
for w in notes {
if !warnings.contains(&w) {
warnings.push(w);
for n in given {
if !notes.iter().any(|x| x.text == n.text) {
notes.push(n);
}
}
}
let warnings = note_texts(&notes);
let n = sheet.rules.len();
match str_param(p, "path") {
match path {
Some(path) => {
write_file(path, css.as_bytes())?;
let folder = std::path::Path::new(path).parent();
+1 -1
View File
@@ -568,7 +568,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) ->
ArrowStyle::Tick => Some(Arrowhead::Slash),
ArrowStyle::None => None,
};
st.start_arrow = head;
st.start_arrow = head.clone();
st.end_arrow = head;
st.arrow_scale = (o.arrow_scale, o.arrow_scale);
st.arrow_align = vectorcraft_doc::appearance::ArrowAlign::Tip;
+261 -34
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient with a stop above opacity 0, at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
has_doc,
info
),
@@ -131,14 +131,16 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
}
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
/// rows of its objects filled or stroked with a spot color, with a pattern and with a gradient.
/// `document.info` reports), its fonts, its image objects, the rows of the brushes its art uses, the
/// rows of its Repeat objects and the rows of its objects filled or stroked with a spot color, with a
/// pattern and with a gradient.
#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
fonts: &BTreeSet<super::fonts::UsedFont>,
images: &[ImageRow],
brushes: &[(String, String)],
repeats: &[(String, String)],
spot_objects: &[(String, String)],
pattern_objects: &[(String, String)],
@@ -184,7 +186,7 @@ fn sections(
rows
}
"graphicStyles" => names("graphicStyleNames"),
"brushes" => names("brushNames"),
"brushes" => brushes.to_vec(),
"spotColors" => spot_objects.to_vec(),
"patterns" => pattern_objects.to_vec(),
"gradients" => gradient_objects.to_vec(),
@@ -326,12 +328,18 @@ fn painted_runs<'a>(d: &Document, spots: &HashSet<&str>, n: &'a Node) -> Option<
if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
return None;
}
Some((t, drawn_runs(d, t)))
}
/// The runs of type `t` that its layout draws: those with a glyph outline (list markers and ruby
/// included) or an underline or strikethrough bar, laid out as the renderer lays it out.
fn drawn_runs(d: &Document, t: &vectorcraft_doc::TextObject) -> BTreeSet<usize> {
let db = vectorcraft_text::FontDb::global();
let resolved = d.inline_resolved(t);
let lay = vectorcraft_text::layout(db, &resolved);
let mut painted: BTreeSet<usize> = lay.glyphs.iter().chain(&lay.ruby).filter(|g| !g.outline.elements().is_empty()).map(|g| g.run).collect();
painted.extend(vectorcraft_text::decorations(&lay, db, &resolved).into_iter().map(|(run, _)| run));
Some((t, painted))
painted
}
/// The names a paint is listed by in a Document Info category: its spot colors, its pattern or its
@@ -340,7 +348,8 @@ type PaintNames<'a> = dyn Fn(&Paint) -> Vec<String> + 'a;
/// The spot colors, patterns or gradients (`label`: [`spot_labels`], [`pattern_label`] or
/// [`gradient_label`], each paint's names) that `n`'s own fills and strokes paint, each once. A
/// hidden fill or stroke and a stroke with no width paint nothing, and neither does any fill or
/// hidden fill or stroke, a fill or stroke at an opacity of 0 and a stroke with no width paint
/// nothing, and neither does any fill or
/// stroke of a guide (drawn in the guide color), of a compound path's member (`members`: the
/// compound path's own fills and strokes paint it) or of type whose layout draws nothing
/// (`painted_runs`). An image's fills and strokes paint only where an effect gives them a shape.
@@ -364,7 +373,7 @@ fn own_paints(
.then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().flat_map(|(_, _, item)| label(item.paint())).collect());
let mut out: Vec<String> = vec![];
for item in &n.appearance.items {
if !item.visible() || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
if !item.visible() || item.opacity() <= 0.0 || matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) {
continue;
}
for name in label(item.paint()) {
@@ -381,6 +390,41 @@ fn one_label(label: fn(&Paint) -> Option<String>) -> impl Fn(&Paint) -> Vec<Stri
move |p| label(p).into_iter().collect()
}
/// The brushes `n`'s own strokes draw with, in the order of its appearance. A hidden stroke, a
/// stroke at an opacity of 0, a stroke with no paint and a stroke with no width draw nothing, and neither does any stroke of a
/// guide (drawn in the guide color) or of a compound path's member (`members`: the compound path's
/// own strokes draw it). An image's strokes draw only where an effect gives them a shape, and only
/// paths, compound paths, type and images draw strokes of their own.
fn applied_brushes(d: &Document, n: &Node, members: &HashSet<*const Node>) -> Vec<String> {
if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) {
return vec![];
}
let brush = |item: &vectorcraft_doc::AppearanceItem| match item {
vectorcraft_doc::AppearanceItem::Stroke(st) if item.visible() && st.opacity > 0.0 && !st.paint.is_none() && st.width > 0.0 => {
st.brush.clone().filter(|b| !b.is_empty())
}
_ => None,
};
if matches!(n.kind, NodeKind::Image(_)) {
return vectorcraft_render::effects::image_paint(Some(d), n).iter().filter_map(|(_, _, item)| brush(item)).collect();
}
let used: Vec<String> = n.appearance.items.iter().filter_map(brush).collect();
if used.is_empty() {
return used;
}
// A path or compound path with no segment gives its strokes nothing to follow, and neither does
// type whose layout draws nothing (spaces and line breaks without an underline or strikethrough).
let segments = |pd: &vectorcraft_geom::PathData| pd.subpaths.iter().any(|sp| sp.segment_count() > 0);
let follows = match &n.kind {
NodeKind::Path { .. } => n.path_data().is_some_and(segments),
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).any(segments),
NodeKind::Text(t) => !drawn_runs(d, t).is_empty(),
// A brush on any other kind of object (a layer, a group, a ruler guide) is not listed.
_ => false,
};
if follows { used } else { vec![] }
}
fn info(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "document.info";
let category = str_param(p, "category");
@@ -425,8 +469,10 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let mut spot = BTreeSet::new();
let (spot_label, pattern, gradient) = (|p: &Paint| spot_labels(&spot_swatches, p), one_label(pattern_label), one_label(gradient_label));
let mut styles: Vec<&str> = if selection_only { vec![] } else { d.graphic_styles.iter().map(|g| g.name.as_str()).collect() };
// `brushes` holds the Brushes panel's brushes, or with selectionOnly it holds the brushes that the selected objects' strokes use.
let mut brushes: Vec<String> = if selection_only { vec![] } else { vectorcraft_brush::library(d).into_iter().map(|b| b.name).collect() };
// `library` holds the Brushes panel's brushes, and `brushes` the brushes the visited objects' strokes draw with, each once,
// in walk order.
let library = vectorcraft_brush::library(d);
let mut brushes: Vec<String> = vec![];
// `repeats` and `repeat_rows` hold the `repeatObjects` entries and the rows of the Repeat objects that the walk visits, in walk order.
let mut repeats: Vec<Value> = vec![];
let mut repeat_rows: Vec<(String, String)> = vec![];
@@ -569,14 +615,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
{
styles.push(&g.name);
}
if selection_only {
for item in &n.appearance.items {
if let vectorcraft_doc::AppearanceItem::Stroke(st) = item
&& let Some(b) = &st.brush
&& !brushes.contains(b)
{
brushes.push(b.clone());
}
for b in applied_brushes(d, n, &members) {
if !brushes.contains(&b) {
brushes.push(b);
}
}
if let NodeKind::Repeat(spec) = &n.kind {
@@ -586,7 +627,24 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
}
});
}
// The document's fonts include those of the type in opacity masks and in the art of its
// symbols and patterns, as Find Font lists them.
if !selection_only {
fonts.extend(super::fonts::art_texts_of(d).into_iter().flat_map(|(_, t, _)| t.runs.iter().map(|r| super::fonts::font_of(&r.style))));
}
let font_names: Vec<String> = fonts.iter().map(super::fonts::font_label).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect();
let brush_entries: Vec<Value> =
brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect();
let brush_rows: Vec<(String, String)> = brushes
.iter()
.map(|name| {
(name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} Brush", k.label())))
})
.collect();
let mut out = json!({
"document": document_summary(d),
"objects": counts,
@@ -601,6 +659,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
"graphicStyles": d.graphic_styles.len(),
"graphicStyleNames": styles,
"brushNames": brushes,
"brushes": brush_entries,
"panelBrushNames": library.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(),
"repeatObjects": repeats,
"characterStyles": d.char_styles.len(),
"paragraphStyles": d.para_styles.len(),
@@ -612,7 +672,7 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
let sections = sections(d, &out, &fonts, &image_rows, &brush_rows, &repeat_rows, &spot_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, &sections) }));
}
@@ -701,6 +761,40 @@ mod tests {
assert!(i["objects"]["textObjects"].is_null() && i["objects"]["paths"] == 1);
}
/// Document Info's fonts include the type in an opacity mask, in a symbol's art and in a
/// pattern swatch that nothing paints with; with `selectionOnly`, only the selected type's.
#[test]
fn info_fonts_include_masks_symbols_and_patterns() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let id = |v: Value| NodeId(v["id"].as_u64().unwrap());
let text = |s: &mut Session, font: &str| id(s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": font})).unwrap());
let rect = |s: &mut Session| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap());
let (masked, in_symbol) = (rect(&mut s), rect(&mut s));
for (owner, font) in [(masked, "Mask Family"), (in_symbol, "Symbol Mask Family")] {
let t = text(&mut s, font);
s.edit("Mask", |d, _| {
let art = d.remove(t)?;
d.node_mut(owner).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new((*art).clone(), true)));
Ok(())
})
.unwrap();
}
s.execute("symbol.new", &json!({"name": "Mark", "ids": [in_symbol.0]})).unwrap();
let t = text(&mut s, "Pattern Family");
s.execute("object.pattern.make", &json!({"ids": [t.0], "name": "Unused", "edit": false})).unwrap();
s.execute("select.set", &json!({"ids": [t.0]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let plain = text(&mut s, "Source Sans 3");
let fonts = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap()["fonts"].clone();
assert_eq!(
fonts(&mut s, json!({})),
json!(["Mask Family Regular", "Pattern Family Regular", "Source Sans 3 Regular", "Symbol Mask Family Regular"])
);
s.execute("select.set", &json!({"ids": [plain.0]})).unwrap();
assert_eq!(fonts(&mut s, json!({"selectionOnly": true})), json!(["Source Sans 3 Regular"]));
}
/// Document Info › Objects gives the paths' total length in the document's units (#1958): an
/// open line, a closed rectangle's perimeter and a compound path's pieces count, a guide doesn't.
#[test]
@@ -725,38 +819,129 @@ mod tests {
assert_eq!(length(&mut s, json!({"selectionOnly": true})), 0.0);
}
/// Document Info › Brushes lists the Brushes panel's brushes, and with Selection Only it lists
/// the brushes the selected objects' strokes use, each once.
/// Document Info › Brushes lists the brushes the art's strokes use, each once with its type, and
/// leaves out the Brushes panel's brushes no art uses (`panelBrushNames` lists those). With
/// Selection Only it lists the brushes the selected objects' strokes use.
#[test]
fn info_lists_the_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let panel: Vec<Value> =
s.execute("brush.list", &json!({})).unwrap()["brushes"].as_array().unwrap().iter().map(|b| b["name"].clone()).collect();
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushNames"], json!(panel));
let brushes = |s: &mut Session, p: Value| s.execute("document.info", &p).unwrap();
// No art uses a brush: the category is empty.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!((i["brushNames"].clone(), i["brushes"].clone(), i["panelBrushNames"].clone()), (json!([]), json!([]), json!(panel)));
assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("brushes"), Some("Brushes")));
let rows: Vec<Value> = panel.iter().map(|n| json!([n, ""])).collect();
assert_eq!(i["sections"][0]["rows"], json!(rows));
assert_eq!(i["sections"][0]["rows"], json!([]));
let a = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let c = s.execute("shape.rectangle", &json!({"x": 40, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("brush.apply", &json!({"ids": [a], "name": "Charcoal"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Arrow"})).unwrap();
s.execute("brush.apply", &json!({"ids": [b], "name": "Dots"})).unwrap();
s.execute("brush.apply", &json!({"ids": [c], "name": "Charcoal"})).unwrap();
let names =
|s: &mut Session| s.execute("document.info", &json!({"selectionOnly": true, "category": "brushes"})).unwrap()["brushNames"].clone();
// The whole document: the two brushes the art uses, each once, with their types; "3 pt. Round" (a Calligraphic
// brush in the panel) is left out.
let i = brushes(&mut s, json!({"category": "brushes"}));
assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"]));
assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}]));
assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art Brush"], ["Dots", "Scatter Brush"]]));
assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel));
let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nCharcoal: Art Brush\nDots: Scatter Brush\n") && !text.contains("3 pt. Round"), "{text}");
assert!(!text.contains("OBJECTS"), "{text}");
// Selection Only: the brushes the selected objects' strokes use.
let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"}));
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
assert_eq!(names(&mut s), json!(["Charcoal", "Arrow"]));
assert_eq!(selected(&mut s)["brushNames"], json!(["Charcoal", "Dots"]));
s.execute("select.set", &json!({"ids": [b]})).unwrap();
assert_eq!(names(&mut s), json!(["Arrow"]));
let i = selected(&mut s);
assert_eq!(
(i["brushes"].clone(), i["sections"][0]["rows"].clone()),
(json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter Brush"]]))
);
let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string();
assert!(text.contains("\nBRUSHES\nDots: Scatter Brush\n") && !text.contains("Charcoal"), "{text}");
// A stroke without a brush lists none.
let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.set", &json!({"ids": [plain]})).unwrap();
assert_eq!(names(&mut s), json!([]));
let text = s.execute("document.info", &json!({"category": "brushes", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains(&format!("\nBRUSHES\n{}\n", panel[0].as_str().unwrap())), "{text}");
assert!(text.contains("\nCharcoal\n") && text.contains("\nArrow\n") && !text.contains("OBJECTS"), "{text}");
assert_eq!(selected(&mut s)["brushNames"], json!([]));
}
/// Document Info › Brushes leaves out brushes on strokes that draw nothing (hidden, at an
/// opacity of 0, with no width or paint, a guide's, a compound path member's, a path's with no segment, type's that
/// draws no characters, a group's own), lists a brush the Brushes panel does
/// not hold with no type, and gives a name two panel brushes share the type the renderer uses.
#[test]
fn info_brushes_skip_undrawn_strokes_and_name_missing_brushes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap();
let square = |s: &mut Session, x: f64| {
s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()
};
let (hidden, thin, guide, missing) = (square(&mut s, 0.0), square(&mut s, 20.0), square(&mut s, 40.0), square(&mut s, 60.0));
let (empty, faint) = (square(&mut s, 80.0), square(&mut s, 200.0));
s.execute("brush.apply", &json!({"ids": [hidden, thin, guide, missing, empty, faint], "name": "Charcoal"})).unwrap();
let (p, q) = (square(&mut s, 100.0), square(&mut s, 120.0));
s.execute("select.set", &json!({"ids": [p, q]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
// A compound path's member: the compound path's own stroke draws it.
let NodeKind::Compound { children, .. } = &mut d.node_mut(NodeId(compound)).unwrap().kind else { panic!("not a compound path") };
let member = &mut std::sync::Arc::make_mut(&mut children[0]).appearance;
member.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
member.stroke_mut().unwrap().brush = Some("Dots".into());
d.node_mut(NodeId(hidden)).unwrap().appearance.stroke_mut().unwrap().visible = false;
d.node_mut(NodeId(thin)).unwrap().appearance.stroke_mut().unwrap().width = 0.0;
// A stroke at an opacity of 0 draws nothing.
d.node_mut(NodeId(faint)).unwrap().appearance.stroke_mut().unwrap().opacity = 0.0;
if let NodeKind::Path { guide: g, .. } = &mut d.node_mut(NodeId(guide)).unwrap().kind {
*g = true;
}
// A path with no segment: its stroke follows nothing.
if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(empty)).unwrap().kind {
*path = vectorcraft_geom::PathData::default();
}
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Gone".into());
let i = s.execute("document.info", &json!({"category": "brushes"})).unwrap();
assert_eq!(i["brushes"], json!([{"name": "Gone", "type": null}]));
assert_eq!(i["sections"][0]["rows"], json!([["Gone", "missing from the Brushes panel"]]));
// A stroke with no paint draws nothing.
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
d.node_mut(NodeId(missing)).unwrap().appearance.stroke_mut().unwrap().paint = Paint::None;
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([]));
// Two panel brushes with one name: the type is the one the renderer draws with, the last one's.
let twin = square(&mut s, 140.0);
s.execute("brush.apply", &json!({"ids": [twin], "name": "Charcoal"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let mut lib = vectorcraft_brush::library(d);
let kinds: Vec<vectorcraft_brush::BrushKind> =
["Charcoal", "Dots"].iter().map(|n| lib.iter().find(|b| b.name == *n).unwrap().kind.clone()).collect();
lib.extend(kinds.into_iter().map(|kind| vectorcraft_brush::Brush { name: "Twin".into(), kind }));
vectorcraft_brush::store(d, &lib);
d.node_mut(NodeId(twin)).unwrap().appearance.stroke_mut().unwrap().brush = Some("Twin".into());
assert_eq!(s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushes"], json!([{"name": "Twin", "type": "scatter"}]));
// Type: a brushed stroke on drawn characters is listed, one on spaces alone is not.
let blank = s.execute("text.create", &json!({"x": 10, "y": 60, "text": " "})).unwrap()["id"].as_u64().unwrap();
let word = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "Hi"})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
for (id, name) in [(blank, "Dots"), (word, "Arrow")] {
let ap = &mut d.node_mut(NodeId(id)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some(name.into());
}
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
// A group's own stroke: the group draws its members.
let (m1, m2) = (square(&mut s, 160.0), square(&mut s, 180.0));
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let ap = &mut d.node_mut(NodeId(group)).unwrap().appearance;
ap.set_stroke(Paint::solid(vectorcraft_color::Color::BLACK));
ap.stroke_mut().unwrap().brush = Some("Leaves".into());
let names = s.execute("document.info", &json!({"category": "brushes"})).unwrap()["brushNames"].clone();
assert_eq!(names, json!(["Twin", "Arrow"]));
}
/// Document Info › Repeat Objects lists each Repeat object by name with its kind and the number
@@ -867,6 +1052,11 @@ mod tests {
s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [e], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
// Nor does a pattern fill at an opacity of 0.
let clear = square(&mut s, 220.0);
s.execute("paint.setStroke", &json!({"ids": [clear], "none": true})).unwrap();
s.execute("paint.setFill", &json!({"ids": [clear], "swatch": "Dots"})).unwrap();
s.execute("appearance.setItem", &json!({"ids": [clear], "index": 0, "opacity": 0})).unwrap();
// A type object with no characters paints nothing either.
let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Dots"})).unwrap();
@@ -927,7 +1117,7 @@ mod tests {
assert_eq!(i["patternNames"], json!(["Dots"]));
// Objects counts the objects that Pattern Objects lists.
assert_eq!(i["objects"]["patterns"].as_u64(), Some(5), "{}", i["objects"]);
s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
s.execute("select.set", &json!({"ids": [d, e, clear, empty, blank, guide, compound, image.0]})).unwrap();
let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert!(i["objects"]["patterns"].is_null() && i["patternObjects"] == json!([]), "{}", i["objects"]);
let i = s.execute("document.info", &json!({"category": "patterns"})).unwrap();
@@ -1228,6 +1418,43 @@ mod tests {
assert_eq!(i["objects"]["spots"].as_u64(), Some(1), "{}", i["objects"]);
}
/// Spot Color Objects leaves out a fill or stroke at an opacity of 0, which prints no ink, and
/// keeps the object while another of its fills or strokes prints the spot color. Gradient
/// Objects leaves out a clear gradient fill as well.
#[test]
fn spot_color_objects_skip_clear_fills_and_strokes() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s.execute("swatch.new", &json!({"name": "Ink", "color": {"model": "cmyk", "c": 0, "m": 1, "y": 1, "k": 0}, "spot": true})).unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect], "swatch": "Ink"})).unwrap();
let ramp = s.execute("shape.rectangle", &json!({"x": 50, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let stops = json!([{"offset": 0, "color": "#000", "swatch": "Ink"}, {"offset": 1, "color": "#fff", "swatch": "Ink"}]);
s.execute("paint.setFill", &json!({"ids": [ramp], "gradient": {"kind": "linear", "stops": stops}})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [ramp], "none": true})).unwrap();
let items = |s: &Session, id: &Value| s.doc().unwrap().doc.node(NodeId(id.as_u64().unwrap())).unwrap().appearance.items.clone();
let spots = |s: &mut Session| {
let i = s.execute("document.info", &json!({})).unwrap();
let mut ids: Vec<u64> = i["spotObjects"].as_array().unwrap().iter().map(|o| o["id"].as_u64().unwrap()).collect();
ids.sort_unstable();
(ids, i["objects"]["spots"].as_u64(), i["objects"]["gradients"].as_u64())
};
// The rectangle's fill at an opacity of 0: its stroke still prints the spot color.
s.execute("select.set", &json!({"ids": [rect]})).unwrap();
let fill = items(&s, &rect).iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": fill, "opacity": 0})).unwrap();
assert_eq!(spots(&mut s), (vec![rect.as_u64().unwrap(), ramp.as_u64().unwrap()], Some(2), Some(1)));
// Every fill and stroke of both objects at an opacity of 0.
for id in [&rect, &ramp] {
s.execute("select.set", &json!({"ids": [id]})).unwrap();
for index in 0..items(&s, id).len() {
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
}
}
assert_eq!(spots(&mut s), (vec![], None, None));
}
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
+121 -18
View File
@@ -1,6 +1,6 @@
//! File (document-level) and Edit commands, plus document queries.
use std::collections::{BTreeMap, BTreeSet};
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::Arc;
use serde_json::{Value, json};
@@ -13,7 +13,7 @@ use super::{
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
object_param, ok, point_param, str_param, switch_or,
};
use crate::{Clipboard, EngineError, inspect};
use crate::{Clipboard, EngineError, SourceLayer, inspect};
/// Register editing commands, including document-to-document artwork drops and their parameter contracts.
pub fn specs() -> Vec<CommandSpec> {
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"New…",
["File"],
None,
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent",
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
always,
super::newdoc::file_new
),
@@ -38,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_move
),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.inspect", "Inspect Document", [], None, "{depth?, childLimit?, ids?: [id…] (list just these nodes, of any level, in this order, under `nodes` in place of `layers`; an unknown id is an error; at most 10000), kind?: panel label such as Layer; Group; Path; Type or Image (exact, ignoring case; list every such node under `nodes`, each with `path`, its ancestor ids with the layer first, searching the subtrees of `ids` when given), limit?: at most this many entries of the list, offset?: entries skipped first (default 0; with `ids`, `kind`, `limit` or `offset` the reply adds `total`, the entries before paging)} → path (the document's file; null when automation read roots are in force and the file is outside them), layer tree (each node: id, name, kind, visible, locked, bounds, opacity (0–1) and opacityPct (0–100 %, the scale object.setProps takes) when below 1, blend when not Normal, fill, stroke and strokeWidth of objects and compound paths; a compound path's members have compoundMember: true instead of paint, which is the compound's), artboards, selection, history (a sliced tree reports childCount); without the scope options the reply is the whole layer tree", has_doc, doc_inspect),
cmd!(query "document.node", "Inspect Object", [], None, "{id, summary?: compact summary, depth?: child levels in the summary (default all), childLimit?: children shown per node (default all; a level that shows fewer reports childCount)} → one object", has_doc, doc_node),
cmd!(query "document.find", "Find Objects", [], None, "{name?: substring of the Layers panel name, kind?: panel label such as Group; Path; Type or Image (exact), text?: substring of type content, within?: [x, y, width, height] (an object's geometric bounds inside this rectangle, edges included; document points as document.inspect's bounds; layers never match this or the size filters), intersects?: [x, y, width, height] (bounds touching or overlapping it), minWidth?, maxWidth?, minHeight?, maxHeight?: pt (the bounds' size), minThickness?, maxThickness?: pt (the smaller of the bounds' width and height), minArea?, maxArea?: pt² (the bounds' width × height), minAnchors?, maxAnchors?: anchor points of a path (a compound path's members together; other objects never match), select?: bool (also select the matches, leaving out hidden and locked ones, those inside another match, and a compound path's members unless the compound path is isolated; Select > Reselect repeats it), limit?: max matches listed (default 100, 0 counts only)} → {matches: [{id, name, kind, path}], total, selected (with select: the count selected)}; at least one filter, all of them matching", has_doc, doc_find),
cmd!(
@@ -50,7 +50,11 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
doc_compare
),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model", has_doc, |s, _| Ok(serde_json::to_value(&*s.doc()?.doc).unwrap_or(Value::Null))),
cmd!(query "document.json", "Document JSON", [], None, "{} → complete document model (with automation read roots, a linked or placed file outside them is named by its file name alone, without its relative path, size or date, in brush art too, and so are a data set's image value and a linked JavaScript file in svg_scripts outside them (a URL is kept); a relative path that leads outside them is left out; a stored brush entry that does not read as a brush is left out; a folder outside them is left out of export_settings)", has_doc, |s, _| {
let st = s.doc()?;
let d = super::links::with_hidden_paths_named(&st.doc, super::links::LinkBase::of(st));
Ok(serde_json::to_value(&*d).unwrap_or(Value::Null))
}),
cmd!(
"document.setUnits",
"Units",
@@ -175,7 +179,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Paste",
["Edit"],
Some("Cmd+V"),
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers they came from (by name; made when missing). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
"{center?: [x, y], artboardsAt?: [x, y], dx?, dy?, swatchConflict?} paste centred on `center` (the app passes the view centre), else offset by dx/dy (default: the Paste Offset preference). Pasting brings the image blobs, symbols, patterns, global and spot swatches (with the tint swatches of the tints used), gradient swatches, graphic styles, character and paragraph styles and brushes the objects use; one of the same name that differs comes in renamed. swatchConflict, for a swatch whose name the document gives another colour (clipboard.conflicts): \"merge\" (default: the objects take the document's swatch) | \"add\" (the pasted swatch comes in renamed) | {name: \"merge\"|\"add\"}. With Paste Remembers Layers on (layer.pasteRemembersLayers), objects go back into the layers and sublayers they came from (by the names of the layer and the layers around it in another document; a missing sublayer is made inside its layer; a hidden or locked one is an error and nothing is pasted). Artboards copied with artboard.copy come with their art, together right of the last artboard as they lay, or centered on `artboardsAt` (the Artboard tool's canvas menu passes the right-click point; a value that is not [x, y] is an error) (the other paste commands but Paste on All Artboards: where they were), their art back in the layers it came from, and the Artboard tool, when chosen, selects them. In Draw Inside (view.drawMode) the objects go inside the object drawn into, as new art does, and Paste Remembers Layers doesn't apply; edit.pasteInPlace and edit.pasteOnAllArtboards do the same, and in Draw Behind they go behind the selection as edit.pasteInBack puts them; edit.pasteInFront and edit.pasteInBack ignore the drawing mode → {ids, artboard: the first new artboard's index or null, artboards: the new artboards' indices, added: resources added, merged: conflicts merged, renamed: [{kind, from, to}]}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Offset)
),
@@ -1376,6 +1380,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
&& inside.is_none()
&& (st.doc.paste_remembers_layers || boards.is_some())
&& parent.is_some_and(|p| st.doc.node(p).is_some_and(Node::is_layer));
// Each object's remembered layer, found before anything is pasted: a hidden or locked one
// refuses the whole paste.
let remembered = if remember { remembered_layers(&st.doc, &clip.source_layers, same_doc)? } else { vec![] };
// Front/back: relative to the selection (top-most / bottom-most selected object); with
// nothing selected, the top / bottom of the current layer. Art other than paths goes beside
// the compound path that holds the selected object, not into it.
@@ -1419,7 +1426,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
.flat_map(|(all, dv)| all.iter().map(move |a| (a, dv)))
.map(|(a, dv)| super::panelcmds::push_artboard_copy(d, a, a.rect + dv))
.collect();
let mut layers: BTreeMap<&str, NodeId> = BTreeMap::new();
// The layers made for remembered layers the document lacks, by parent and name.
let mut made = HashMap::new();
// Objects pasted into each parent so far (keeps their order in front and back pastes).
let mut placed: BTreeMap<Option<NodeId>, usize> = BTreeMap::new();
let mut new_ids = vec![];
@@ -1433,8 +1441,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
// including the pattern phase, independently of transform-tool settings.
c.transform(xf, sc);
}
let layer = match clip.source_layers.get(k) {
Some(Some(name)) if remember => Some(*layers.entry(name).or_insert_with(|| layer_named(d, name))),
let layer = match remembered.get(k) {
Some(Some(Remembered::Layer(l))) => Some(*l),
Some(Some(Remembered::Make { parent, names })) => make_layers(d, &mut made, *parent, names)?,
_ => None,
};
// In a clip group or a clipping layer the bottom child is the clipping path: art pasted
@@ -1553,17 +1562,111 @@ fn paste_anchor(doc: &Document, id: NodeId, can_enter_compound: bool) -> NodeId
}
}
/// The first unlocked layer or sublayer called `name` (topmost first), or a new top layer.
fn layer_named(d: &mut Document, name: &str) -> NodeId {
let mut found = None;
for l in d.layers.iter().rev() {
l.walk(&mut |n| {
if found.is_none() && n.is_layer() && !n.locked && n.name.as_deref() == Some(name) {
found = Some(n.id);
/// Where Paste Remembers Layers puts an object: a layer or sublayer of the document, or new
/// layers `names`, each inside the one before, the first under `parent` (none: on top).
#[derive(Clone, Debug, PartialEq)]
enum Remembered {
Layer(NodeId),
Make { parent: Option<NodeId>, names: Vec<String> },
}
/// [`remembered_layer`] for each object's source layer, worked out once for each layer.
fn remembered_layers(d: &Document, sources: &[Option<SourceLayer>], same_doc: bool) -> Result<Vec<Option<Remembered>>> {
let mut found: HashMap<&SourceLayer, Remembered> = HashMap::new();
sources
.iter()
.map(|src| {
let Some(src) = src else { return Ok(None) };
if let Some(r) = found.get(src) {
return Ok(Some(r.clone()));
}
});
let r = remembered_layer(d, src, same_doc)?;
found.insert(src, r.clone());
Ok(Some(r))
})
.collect()
}
/// The layer `src` names in `d`. In the document it was copied from, the layer that held the
/// object is kept while it is there with its name, wherever it was moved; else the layers around
/// it still where they were (by id) are kept. Below them, and in another document from the top,
/// each name is matched among the layers inside the one above (the topmost of the same name whose
/// layers match the most names, a shown and unlocked one first). The names left unmatched are
/// made. A matched layer that is hidden or locked, or inside one that is, is an error.
fn remembered_layer(d: &Document, src: &SourceLayer, same_doc: bool) -> Result<Remembered> {
let held = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_layer() && n.name.as_ref() == src.names.last());
let kept = if same_doc && src.ids.last().is_some_and(held) {
src.ids.len()
} else if same_doc {
(1..=src.ids.len())
.rev()
.find(|&j| d.node(src.ids[j - 1]).is_some_and(Node::is_layer) && d.ancestry(src.ids[j - 1]).is_some_and(|a| a == src.ids[..j]))
.unwrap_or(0)
} else {
0
};
let rest = &src.names[kept..];
let (end, matched, _) = named_chain(d, kept.checked_sub(1).map(|j| src.ids[j]), rest);
if let Some(l) = end
&& !d.ancestry(l).is_some_and(|a| a.iter().all(|i| d.node(*i).is_some_and(|n| n.visible && !n.locked)))
{
return Err(EngineError::Other("the target layer is locked or hidden".into()));
}
found.unwrap_or_else(|| d.add_layer(Some(name)))
Ok(match end {
Some(l) if matched == rest.len() => Remembered::Layer(l),
parent => Remembered::Make { parent, names: rest[matched..].to_vec() },
})
}
/// The deepest chain of layers inside `parent` (none: the top level) named `names` one inside the
/// other: its last layer (`parent` when none matches), how many names it matched and whether all
/// its layers are shown and unlocked. Of chains as deep, the topmost shown and unlocked one wins.
fn named_chain(d: &Document, parent: Option<NodeId>, names: &[String]) -> (Option<NodeId>, usize, bool) {
let mut best = (parent, 0, true);
let Some((name, rest)) = names.split_first() else { return best };
let siblings = match parent {
None => Some(&d.layers),
Some(p) => d.node(p).and_then(Node::children),
};
for l in siblings.into_iter().flatten().rev().filter(|l| l.is_layer() && l.name.as_deref() == Some(name.as_str())) {
let (end, n, open) = named_chain(d, Some(l.id), rest);
let chain = (end, n + 1, open && l.visible && !l.locked);
if (chain.1, chain.2) > (best.1, best.2) {
best = chain;
}
}
best
}
/// Layers `names`, each inside the one before, the first under `parent` (none: on top); `made`
/// keeps the ones a paste has made, by parent and name, so they are made once. The last one, or
/// none when `names` is empty.
fn make_layers(
d: &mut Document,
made: &mut HashMap<(Option<NodeId>, String), NodeId>,
parent: Option<NodeId>,
names: &[String],
) -> Result<Option<NodeId>> {
let mut at = parent;
for name in names {
let key = (at, name.clone());
let id = match made.get(&key) {
Some(id) => *id,
None => {
let id = match at {
None => d.add_layer(Some(name)),
Some(p) => {
let layer = super::layer::make_layer(d, Some(name));
d.insert(Some(p), usize::MAX, layer)?
}
};
made.insert(key, id);
id
}
};
at = Some(id);
}
Ok(at.filter(|_| !names.is_empty()))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
+73 -9
View File
@@ -16,7 +16,7 @@ use vectorcraft_render::effects;
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
use super::expand::has_seeded;
use super::rasterfx;
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, fileio, has_doc, str_param, switch_or};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
/// The name of the `svg.filter` effect drawing `xml`: its `<filter>` id. An effect names the
/// document's filter of that name, so `xml` that differs from the document's filter of the same
@@ -34,8 +34,15 @@ fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result<String> {
Ok(name)
}
/// The effect commands of the Effect menu and the Appearance panel.
/// The effect commands of the Effect menu and the Appearance panel, and the 3D and Materials
/// panel's Graphics.
pub fn specs() -> Vec<CommandSpec> {
let mut specs = effect_specs();
specs.extend(graphics::specs());
specs
}
fn effect_specs() -> Vec<CommandSpec> {
vec![
cmd!(
"effect.apply",
@@ -69,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Effect Options",
[],
None,
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool, item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
has_doc,
set_params
),
@@ -87,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Expand Appearance",
["Object"],
None,
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
"{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says)}",
can_expand,
expand_appearance
),
@@ -454,6 +461,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len())));
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
if let Some(name) = effects::missing_symbol(d, &effect.params, None) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if id == effects::REVOLVE && effects::has_revolve(n) {
return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead."));
}
@@ -639,15 +649,28 @@ pub(crate) fn set_params_effects(s: &Session, p: &Value) -> Vec<String> {
return vec![];
};
let Ok(targets) = effect_targets(s, p, item, index, C) else { return vec![] };
// A 3D effect whose type `threeDType` changes takes the new effect's parameters.
// A 3D effect whose type `threeDType` changes, and a Warp whose style `warpStyle` changes, take
// the new effect's parameters.
let kind = three_d_type(p, C).ok().flatten();
let warp = p.get("warpStyle").and_then(Value::as_str).filter(|style| effects::WarpStyle::from_id(style).is_some());
let effect = |&(id, at, index): &(NodeId, Option<usize>, usize)| {
let id = &st.doc.node(id)?.appearance.effects_at(at)?.get(index)?.id;
Some(kind.filter(|_| effects::is_three_d(id)).map_or_else(|| id.clone(), str::to_string))
Some(edited_effect_id(id, kind, warp))
};
targets.iter().filter_map(effect).collect()
}
/// The id effect `id` has once `effect.setParams` sets its 3D type to `kind` or its Warp style to
/// `warp` (each when given and when `id` is an effect of that family).
fn edited_effect_id(id: &str, kind: Option<&str>, warp: Option<&str>) -> String {
let is_warp = id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_some();
match (kind, warp) {
(Some(to), _) if effects::is_three_d(id) => to.to_string(),
(_, Some(style)) if is_warp => format!("warp.{style}"),
_ => id.to_string(),
}
}
/// The effect `threeDType` in `p` turns a 3D effect into ([`effects::THREE_D_TYPES`]), when given.
fn three_d_type(p: &Value, cmd: &str) -> Result<Option<&'static str>> {
let key = "threeDType";
@@ -708,6 +731,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
Ok(format!("warp.{style}"))
})
.transpose()?;
check_switches(p, &["visible"], C)?;
let visible = p.get("visible").and_then(Value::as_bool);
let item = item_target(s, p, C)?;
let edited = set_params_effects(s, p);
@@ -758,6 +782,9 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, &params)) {
cur.extend(new);
}
if let Some(name) = effects::missing_symbol(d, &prospective, Some(&e.params)) {
return Err(bad(C, format!("no symbol named `{name}`")));
}
if visible != Some(false) {
effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?;
} else {
@@ -835,8 +862,9 @@ fn load_texture(params: &mut Value, cmd: &str) -> Result<()> {
/// Has `n` an appearance Expand Appearance turns into objects: a path that isn't basic (several
/// fills or strokes, effects, transparency of a fill or stroke, a brush), a group or layer with
/// fills, strokes or effects of its own or such members, other objects with effects, or type with
/// fills or strokes of its own?
/// fills, strokes or effects of its own or such members, other objects with effects, type with
/// fills or strokes of its own, or a symbol instance whose active fill or stroke has a geometry
/// effect ([`effects::has_item_geometry`])?
pub(crate) fn expandable(n: &Node) -> bool {
expandable_except(n, &[])
}
@@ -853,7 +881,7 @@ pub(crate) fn expandable_except(n: &Node, skip: &[NodeId]) -> bool {
!n.appearance.items.is_empty() || !n.appearance.effects.is_empty() || children.iter().any(|c| expandable_except(c, skip))
}
NodeKind::Text(_) => !n.appearance.items.is_empty() || !n.appearance.effects.is_empty(),
NodeKind::Image(_) => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => effects::has_item_geometry(n) || !n.appearance.effects.is_empty(),
_ => !n.appearance.effects.is_empty(),
}
}
@@ -926,6 +954,38 @@ fn expand_pieces(
expanded
}
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
/// active fill or stroke has a geometry effect ([`effects::has_item_geometry`]) by its art as
/// [`effects::expand_outlined`] makes it, and the instances in that art in turn, so
/// [`expand_pieces`] bakes their effects with the rest. An instance stays as it is when it is more
/// than [`vectorcraft_doc::depth::MAX_DEPTH`] instances deep, its symbol is missing, or its art
/// would take the objects placed so far past `budget`.
fn expand_nested_instances(d: &Document, m: &mut Node, depth: usize, budget: &mut u64) {
for c in m.children_mut().into_iter().flatten() {
if !matches!(c.kind, NodeKind::SymbolInstance { .. }) {
if c.children().is_some() {
expand_nested_instances(d, Arc::make_mut(c), depth, budget);
}
continue;
}
let NodeKind::SymbolInstance { symbol, .. } = &c.kind else { continue };
if depth >= vectorcraft_doc::depth::MAX_DEPTH || !effects::has_item_geometry(c) {
continue;
}
let Some(sym) = d.symbols.iter().find(|s| s.name == *symbol) else { continue };
let count = sym.art.count() as u64;
if count > *budget {
continue;
}
*budget -= count;
let art = vectorcraft_render::instance_art(&sym.art, c);
if let Some(mut a) = effects::expand_outlined(Some(d), c, Some(&art)) {
expand_nested_instances(d, &mut a, depth + 1, budget);
*c = Arc::new(a);
}
}
}
/// Does `n` hold an id of `seen`, or one id twice: does [`effects::fresh_ids`] give it new ids?
fn repeats_an_id(n: &Node, seen: &std::collections::HashSet<NodeId>) -> bool {
let mut ids = std::collections::HashSet::new();
@@ -1081,6 +1141,8 @@ fn expanded_node(d: &mut Document, mut n: Node, brushes: &[vectorcraft_brush::Br
_ => None,
};
effects::expand_outlined(Some(&*d), &v, symbol.as_ref()).map(|mut m| {
let mut budget = vectorcraft_doc::MAX_SYMBOL_NODES;
expand_nested_instances(d, &mut m, 1, &mut budget);
expand_pieces(d, &mut m, true, brushes, &mut stroke_art);
m
})
@@ -1201,6 +1263,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
mod graphics;
#[cfg(test)]
mod lighting_presets_tests;
+153
View File
@@ -0,0 +1,153 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_render::effects;
use super::super::appearance::{appearance_targets, index_param, item_target};
use super::super::brushsym::{normalize, selection_art, store_symbol};
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
use super::{effect_targets, ids_json};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"threeD.addGraphic",
"Add as Single Graphic",
[],
None,
"{name?: string (default Graphic; made unique), ids?|id?} keep the selection's art as a new document symbol, listed among the 3D and Materials panel's Graphics; the selection stays as it is → {name}",
has_selection,
add_graphic
),
cmd!(
"threeD.mapGraphic",
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}",
has_doc,
map_graphic
),
]
}
/// `threeD.addGraphic`: stores the selection's art as a symbol without replacing it with an
/// instance.
fn add_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.addGraphic";
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !["name", "ids", "id"].contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
if p.get("name").is_some_and(|v| v.as_str().is_none_or(|n| n.trim().is_empty())) {
return Err(bad(C, "`name` must be a name that is not empty"));
}
let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?;
crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art);
let (art, size, _) = normalize(art)?;
let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Graphic"));
s.edit("Add as Single Graphic", |d, _| {
store_symbol(d, &art, &name, size);
Ok(())
})?;
Ok(json!({ "name": name }))
}
/// The 3D effect of `n` that a graphic goes on when none is named: its own first, then its fills'
/// and strokes', as the 3D and Materials panel finds it.
fn first_three_d(n: &Node) -> Option<(Option<usize>, usize)> {
let at = |fx: &[Effect]| fx.iter().position(|e| effects::is_three_d(&e.id));
at(&n.appearance.effects)
.map(|i| (None, i))
.or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i))))
}
/// `threeD.mapGraphic`: appends a graphic to the 3D effect of each target, after checking that every
/// target takes it.
fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "threeD.mapGraphic";
const KEYS: [&str; 10] = ["symbol", "face", "x", "y", "scale", "rotation", "index", "item", "ids", "id"];
if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) {
return Err(bad(C, format!("unknown parameter `{key}`")));
}
// An item names where the effect is in that item's list, so it takes an index too.
if p.get("item").is_some() && p.get("index").is_none() {
return Err(bad(C, "`item` needs `index`"));
}
// The graphic's own settings, checked as the effect checks them.
let mut given = Map::new();
for key in ["symbol", "face", "x", "y", "scale", "rotation"] {
if let Some(v) = p.get(key) {
given.insert(key.into(), v.clone());
}
}
let base = effects::MappedGraphic::from_value(&Value::Object(given)).map_err(|e| bad(C, e))?;
let d = &s.doc()?.doc;
if !d.symbols.iter().any(|sym| sym.name == base.symbol) {
return Err(bad(C, format!("no symbol named `{}`", base.symbol)));
}
let targets: Vec<(NodeId, Option<usize>, usize)> = if p.get("index").is_some() {
let index = index_param(p, "index", C)?;
let item = item_target(s, p, C)?;
effect_targets(s, p, item, index, C)?
} else {
let mut out = vec![];
for id in appearance_targets(s, p)? {
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
out.push((id, item, index));
}
out
};
if targets.is_empty() {
return Err(bad(C, "select an object with a 3D effect"));
}
let mut edits = Vec::with_capacity(targets.len());
for &(id, item, index) in &targets {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else {
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
};
if !effects::takes_graphics(&effect.id) {
return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0)));
}
// A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again,
// but has no cap to show a new one on.
let merged = effects::merged_params(&effect.id, &effect.params);
let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged));
if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) {
return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0)));
}
// With a depth of 0 the art is a plane, which has only a front.
if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol))
{
graphic.scale = frame.fitting_scale(art);
}
let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic);
effects::validate_three_d_at_in(Some(d), n, &effect.id, &params, item.map(|i| (i, index))).map_err(|e| bad(C, e))?;
edits.push((id, item, index, graphic));
}
let first = edits.first().map(|(.., g)| g.to_value());
let ids = s.edit("Map Graphic", |d, _| {
let mut done = vec![];
for (id, item, index, graphic) in &edits {
let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)) else { continue };
let current = effects::upgrade_params(&e.id, &e.params);
e.params = effects::with_graphic(&current, graphic);
done.push(*id);
}
Ok(done)
})?;
Ok(json!({ "ids": ids_json(&ids), "graphic": first }))
}
#[cfg(test)]
#[path = "graphics_tests.rs"]
mod tests;
@@ -0,0 +1,289 @@
#![allow(clippy::unwrap_used, clippy::panic)]
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use crate::Session;
/// A 100 × 100 square with `effect`, and a 10 × 20 red rectangle beside it kept as graphic "Mark".
fn setup(effect: &str) -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone();
s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap();
let made = s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap();
assert_eq!(made["name"], "Mark");
let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap();
s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap();
(s, id)
}
fn graphics(s: &Session, id: NodeId) -> Value {
s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["graphics"].clone()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
#[test]
fn add_as_single_graphic_keeps_the_art_and_makes_a_symbol() {
let (s, _) = setup("threeD.extrude");
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|sym| sym.name == "Mark"));
// The art stays a plain path: no instance replaced it.
let mut instances = 0;
for l in &d.layers {
l.walk(&mut |n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. })));
}
assert_eq!(instances, 0);
// The 10 × 20 rectangle and its 1 pt stroke.
assert_eq!(vectorcraft_render::effects::graphic_bounds(d, "Mark").map(|r| (r.width(), r.height())), Some((11.0, 21.0)));
}
#[test]
fn map_graphic_adds_to_the_selected_object_in_one_undo_step_and_undoes() {
let (mut s, id) = setup("threeD.extrude");
let before = s.doc().unwrap().doc.clone();
let history = undo_len(&s);
let r = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap();
assert_eq!(r["ids"], json!([id.0]));
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 5.0, "y": 0.0, "scale": 100.0, "rotation": 30.0}]));
assert_eq!(undo_len(&s), history + 1);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back"})).unwrap();
assert_eq!(graphics(&s, id).as_array().unwrap().len(), 2);
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc.layers, before.layers);
}
#[test]
fn a_large_graphic_starts_inside_its_object() {
let (mut s, id) = setup("threeD.rotate");
let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap();
// 401 pt wide with its stroke, in a 100 pt square.
let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap();
assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}");
}
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Extrude or Plane"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
(json!({"face": "front"}), "needs `symbol`"),
(json!({"symbol": "Mark", "face": "back"}), "one face"),
(json!({"symbol": "Mark", "scale": 0.0}), "scale"),
(json!({"symbol": "Mark", "tile": true}), "`tile`"),
(json!({"symbol": "Mark", "item": 0}), "`item` needs `index`"),
(json!({"symbol": "Mark", "item": null}), "`item` needs `index`"),
] {
let mut p = p;
p["ids"] = json!([id.0]);
let e = s.execute("threeD.mapGraphic", &p).unwrap_err().to_string();
assert!(e.contains(says), "{p}: {e}");
}
assert_eq!(undo_len(&s), history);
// An object without a 3D effect.
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [plain]})).unwrap_err().to_string();
assert!(e.contains("3D effect"), "{e}");
// A hollow Extrude & Bevel has no cap to show a new graphic on.
let (mut s, id) = setup("threeD.extrude");
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("turn on Cap"), "{e}");
assert_eq!(undo_len(&s), history);
// With a depth of 0 there is no back.
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": true, "depth": 0.0}})).unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("one face"), "{e}");
assert_eq!(undo_len(&s), history);
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok());
}
#[test]
fn set_params_edits_graphics_and_checks_them() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let moved = json!([{"symbol": "Mark", "face": "front", "x": -12.0, "y": 8.0, "scale": 150.0, "rotation": 0.0}]);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": moved}})).unwrap();
assert_eq!(graphics(&s, id), moved);
let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": [{"symbol": "Mark", "face": "top"}]}});
assert!(s.execute("effect.setParams", &bad).is_err());
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
assert!(s.execute("effect.setParams", &null).is_err());
assert_eq!(graphics(&s, id), moved);
// Extrude to Plane keeps the graphics; to Inflate drops them.
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
assert_eq!(graphics(&s, id), moved);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
assert_eq!(graphics(&s, id), Value::Null);
}
#[test]
fn effect_commands_refuse_an_unknown_symbol_but_keep_a_deleted_ones_graphic() {
let (mut s, id) = setup("threeD.extrude");
let unknown = json!([{"symbol": "Nowhere"}]);
let history = undo_len(&s);
assert!(s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": unknown}})).is_err());
s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap();
let created = undo_len(&s);
assert!(s.execute("effect.apply", &json!({"effect": "threeD.extrude", "item": null, "params": {"graphics": unknown}})).is_err());
assert_eq!((history + 1, undo_len(&s)), (created, created));
// A graphic whose symbol was deleted stays while the effect's other settings change.
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.retain(|sym| sym.name != "Mark");
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"depth": 30.0}})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Mark");
}
#[test]
fn a_symbol_a_graphic_uses_is_used_and_follows_a_rename() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let unused = s.execute("symbol.unused", &json!({})).unwrap();
assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "Mark"), "{unused}");
// A 3D object with the graphic kept in another symbol's art follows the rename too.
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
s.execute("symbol.new", &json!({"name": "Holder"})).unwrap();
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
assert_eq!(graphics(&s, id)[0]["symbol"], "Label");
let d = &s.doc().unwrap().doc;
let holder = d.symbols.iter().find(|sym| sym.name == "Holder").unwrap();
let mut held = vec![];
holder.art.walk(&mut |n| held.extend(vectorcraft_render::effects::graphic_symbols(n)));
assert_eq!(held, vec!["Label".to_string()]);
}
#[test]
fn a_rename_reaches_graphics_in_graph_designs_and_opacity_masks() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
let held = d.node(id).unwrap().clone();
d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(held.clone()) });
d.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", (*held.appearance).clone()));
let mut lib = vectorcraft_brush::library(d);
let scatter = lib.iter_mut().find(|b| !b.art().is_empty()).unwrap();
*scatter.art_mut()[0] = held.clone();
vectorcraft_brush::store(d, &lib);
d.node_mut(id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(held, true)));
s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap();
let d = &s.doc().unwrap().doc;
let style = d.graphic_styles.iter().find(|g| g.name == "Boxed").unwrap();
assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&style.appearance), vec!["Label".to_string()]);
let brush: Vec<String> =
vectorcraft_brush::library(d).iter().flat_map(|b| b.art()).flat_map(vectorcraft_render::effects::graphic_symbols).collect();
assert_eq!(brush, vec!["Label".to_string()]);
let names = |n: &vectorcraft_doc::Node| {
let mut out = vec![];
n.walk(&mut |c| out.extend(vectorcraft_render::effects::graphic_symbols(c)));
out
};
assert_eq!(names(&d.graph_designs[0].art), vec!["Label".to_string()]);
let mask = d.node(id).unwrap().extras().mask.as_deref().map(|m| names(&m.art));
assert_eq!(mask, Some(vec!["Label".to_string()]));
}
#[test]
fn pasted_into_another_document_a_graphic_brings_its_symbol() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// The symbol the pasted object's graphic names, and the size of that symbol's art.
let pasted = |s: &mut Session| {
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
let name = n.appearance.effects[0].params["graphics"][0]["symbol"].as_str().unwrap().to_string();
let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height()));
(name, size)
};
// A document without the symbol gets it.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0))));
// A document whose symbol "Mark" is other art gets the copied symbol under a free name.
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone();
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap();
let (name, size) = pasted(&mut s);
assert_ne!(name, "Mark");
assert_eq!(size, Some((11.0, 21.0)));
}
#[test]
fn a_symbol_only_a_graphic_style_uses_is_used() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let appearance = (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone();
s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"graphics": []}})).unwrap();
let unused = |s: &mut Session| s.execute("symbol.unused", &json!({})).unwrap()["names"].clone();
assert!(unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", appearance));
assert!(!unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark"));
}
#[test]
fn add_graphic_refuses_bad_parameters_and_changes_nothing() {
let (mut s, _) = setup("threeD.extrude");
let art = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone();
let (symbols, history) = (s.doc().unwrap().doc.symbols.len(), undo_len(&s));
for p in [
json!({"name": 5, "ids": [art]}),
json!({"name": null, "ids": [art]}),
json!({"name": "", "ids": [art]}),
json!({"name": " ", "ids": [art]}),
json!({"tile": true, "ids": [art]}),
] {
assert!(s.execute("threeD.addGraphic", &p).is_err(), "{p}");
}
assert_eq!((s.doc().unwrap().doc.symbols.len(), undo_len(&s)), (symbols, history));
}
#[test]
fn map_graphic_refuses_a_selection_with_an_object_without_a_3d_effect() {
let (mut s, id) = setup("threeD.extrude");
let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].as_u64().unwrap();
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0, plain]})).unwrap_err().to_string();
assert!(e.contains(&format!("object {plain} needs a 3D effect")), "{e}");
assert_eq!(undo_len(&s), history);
assert_eq!(graphics(&s, id).as_array().map_or(0, Vec::len), 0);
}
#[test]
fn the_graphic_is_drawn_on_the_object() {
let (mut s, id) = setup("threeD.extrude");
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap();
let d = &s.doc().unwrap().doc;
let art = vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()).unwrap();
let mut red = None;
art.walk(&mut |n| {
if let (Some(p), Some(vectorcraft_doc::AppearanceItem::Fill(f))) = (n.path_data(), n.appearance.items.first())
&& f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1)
{
red = p.bounds();
}
});
// Seen straight on, the 10 × 20 graphic sits at the center of the square.
let r = red.unwrap();
assert!(
(r.center().x - 150.0).abs() < 1e-6
&& (r.center().y - 150.0).abs() < 1e-6
&& (r.width() - 10.0).abs() < 1e-6
&& (r.height() - 20.0).abs() < 1e-6,
"{r:?}"
);
}
+44
View File
@@ -626,6 +626,50 @@ fn warp_options_non_warp_target_rejection_is_atomic() {
assert!(!state.is_dirty());
}
/// `effect.setParams` refuses a `visible` that is not true or false, when called and when a step
/// plays, and the effect, the document and the undo history stay as they were. `null` leaves the
/// visibility as it is.
#[test]
fn set_params_refuses_a_visible_that_is_not_true_or_false() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": null})).unwrap();
s.doc_mut().unwrap().mark_saved();
let before = s.doc().unwrap().doc.clone();
let undo = s.doc().unwrap().history.undo.len();
for visible in [json!(1), json!(0), json!("false"), json!([])] {
let p = json!({"index": 0, "item": null, "visible": visible, "params": {"size": 9}});
for replay in [false, true] {
let r = if replay { s.replay("effect.setParams", &p) } else { s.execute("effect.setParams", &p) };
let err = r.err().map(|e| e.to_string()).unwrap_or_default();
assert!(err.contains("`visible` must be true or false"), "{visible} (replay {replay}): {err}");
let state = s.doc().unwrap();
assert_eq!(state.doc, before, "{visible} (replay {replay})");
assert_eq!(state.history.undo.len(), undo, "{visible} (replay {replay})");
assert!(!state.is_dirty());
}
}
s.execute("effect.setParams", &json!({"index": 0, "item": null, "visible": null, "params": {"size": 9}})).unwrap();
let n = node(&s, id);
assert!(n.appearance.effects[0].visible);
assert_eq!(n.appearance.effects[0].params["size"], 9);
}
/// The effect `effect.setParams` checks the parameters against is the one it leaves: a Warp's new
/// style and a 3D effect's new type, and the effect as it is otherwise.
#[test]
fn set_params_checks_the_effect_it_leaves() {
use super::edited_effect_id;
assert_eq!(edited_effect_id("warp.arc", None, Some("flag")), "warp.flag");
assert_eq!(edited_effect_id("warp.arc", None, None), "warp.arc");
assert_eq!(edited_effect_id("distort.roughen", None, Some("flag")), "distort.roughen");
assert_eq!(edited_effect_id("threeD.extrude", Some("threeD.revolve"), None), "threeD.revolve");
assert_eq!(edited_effect_id("warp.arc", Some("threeD.revolve"), None), "warp.arc");
let (mut s, _) = session_with_rect();
s.execute("effect.apply", &json!({"effect": "warp.arc", "item": null})).unwrap();
let p = json!({"index": 0, "item": null, "warpStyle": "flag", "params": {"bend": 25}});
assert_eq!(super::set_params_effects(&s, &p), ["warp.flag"]);
}
#[test]
fn list_remove_and_set_params() {
let (mut s, id) = session_with_rect();
Loaded 100 of 511 files, more files were not shown because too many files have changed in this diff. Show more