diff --git a/Cargo.lock b/Cargo.lock index 7b0de73006..cec8e7aef7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7108,6 +7108,7 @@ dependencies = [ name = "vectorcraft-text" version = "0.24.1" dependencies = [ + "craft-proof", "harfrust 0.13.3", "icu_segmenter", "kurbo 0.13.1", @@ -7116,6 +7117,7 @@ dependencies = [ "subsetter", "unicode-bidi", "unicode-general-category", + "unicode-normalization", "unicode-script", "unicode-segmentation", "vectorcraft-doc", diff --git a/crates/doc/Cargo.toml b/crates/doc/Cargo.toml index a7d2850a1e..1280e7d998 100644 --- a/crates/doc/Cargo.toml +++ b/crates/doc/Cargo.toml @@ -11,6 +11,8 @@ workspace = true [features] # `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only). spine-count = [] +# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only). +symbol-read-count = [] [dependencies] vectorcraft-geom = { workspace = true } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 11711b3f1d..7f26dc9a50 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -75,6 +75,9 @@ pub mod style_libs; pub mod swatches; mod symbols; pub use symbols::SymbolBoxes; +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub use symbols::symbols_read; pub mod text; pub mod trace; pub mod twist; diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index a1d34e6adb..f2b96c4843 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use vectorcraft_geom::{Affine, Rect}; use crate::symbol_nine_slice::transformed; -use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF}; +use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol}; /// The box a symbol instance is measured by when its symbol's art has no box /// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin @@ -312,7 +312,7 @@ impl Document { /// Each symbol name of this document → the index of the first symbol of that name (the one a /// name finds). pub(crate) fn symbol_names(&self) -> SymbolNames { - #[cfg(test)] + #[cfg(any(test, feature = "symbol-read-count"))] SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len())); let mut names = HashMap::with_capacity(self.symbols.len()); for (i, s) in self.symbols.iter().enumerate() { @@ -322,7 +322,7 @@ impl Document { } } -#[cfg(test)] +#[cfg(any(test, feature = "symbol-read-count"))] thread_local! { /// How many symbols [`Document::symbol_names`] has read on this thread. pub(crate) static SYMBOLS_READ: Cell = const { Cell::new(0) }; @@ -330,12 +330,31 @@ thread_local! { static ART_BOXES_MEASURED: Cell = const { Cell::new(0) }; } +/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests +/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count` +/// feature, dev-dependencies only). +#[cfg(any(test, feature = "symbol-read-count"))] +#[doc(hidden)] +pub fn symbols_read() -> usize { + SYMBOLS_READ.with(Cell::get) +} + impl<'a> SymbolBoxes<'a> { /// The document whose symbols these are. pub fn document(&self) -> &'a Document { self.doc } + /// New boxes for the same document, none measured yet and with none of the options set, that + /// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring + /// objects one at a time in boxes of their own made this way measures them as boxes made by + /// [`Document::symbol_boxes`] do, without reading the symbol list again. + pub fn unmeasured(&self) -> SymbolBoxes<'a> { + let doc: &'a Document = self.doc; + let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); + doc.symbol_boxes().with_names(names) + } + /// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the /// document's symbols while they had the names and order they have now. pub(crate) fn with_names(self, names: &Arc) -> Self { @@ -343,19 +362,24 @@ impl<'a> SymbolBoxes<'a> { self } - /// The art of the first symbol of the document named `name`, found in time independent of the - /// number of symbols after the first lookup. - pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + /// The first symbol of the document named `name`, found in time independent of the number of + /// symbols after the first lookup. + pub fn symbol(&self, name: &str) -> Option<&'a Symbol> { let doc: &'a Document = self.doc; let names = self.names.get_or_init(|| Arc::new(doc.symbol_names())); let i = *names.get(name)?; match doc.symbols.get(i) { - Some(s) if s.name == name => Some(&s.art), + Some(s) if s.name == name => Some(s), // Names that no longer match the symbols: the first symbol of that name. - _ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art), + _ => doc.symbols.iter().find(|s| s.name == name), } } + /// The art of the first symbol of the document named `name` ([`Self::symbol`]). + pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc> { + self.symbol(name).map(|s| &s.art) + } + /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The @@ -904,6 +928,57 @@ mod tests { assert_eq!(s.sliced_placed.get(), 13); } + #[test] + fn symbols_are_found_by_name_reading_the_list_once() { + // 2,000 symbols, then two named "Mark": a name finds the first. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Filler {i}"), vec![r]); + } + let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0)); + symbol(&mut d, "Mark", vec![first]); + symbol(&mut d, "Mark", vec![second]); + let read = || SYMBOLS_READ.with(Cell::get); + let before = read(); + let s = d.symbol_boxes(); + for _ in 0..1000 { + assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000]))); + assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7]))); + assert!(s.symbol("Nowhere").is_none()); + } + assert_eq!(read() - before, d.symbols.len()); + } + + #[test] + fn unmeasured_boxes_share_the_index_and_nothing_measured() { + // 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend + // the boxes' budget of placed objects. + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0); + symbol(&mut d, &format!("Filler {i}"), vec![r]); + } + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0); + symbol(&mut d, "Panel", vec![frame]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + symbol(&mut d, "Holder", vec![wide]); + let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5)); + let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick()); + let read = || SYMBOLS_READ.with(Cell::get); + let s = d.symbol_boxes().quick(); + assert_eq!(holder.visual_bounds_with(&s), fresh); + assert!(s.sliced_placed.get() > 0); + let before = read(); + let u = s.unmeasured(); + assert_eq!(read(), before, "the index is shared"); + assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty()); + assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false)); + assert_eq!(holder.visual_bounds_with(&u.quick()), fresh); + assert_eq!(read(), before); + } + #[test] fn measuring_9_slice_instances_reads_the_symbol_list_once() { // 2,000 symbols, then a frame with guides and a symbol with guides holding the frame diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 271ce1c162..9eae81118a 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -94,13 +94,13 @@ 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, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, 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, renders_wireframe, 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, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES, + 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, + mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, 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, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index c065e507df..acd6cf7c94 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -801,7 +801,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; let (paint, opacity, _) = paint_of(item); let mesh = vectorcraft_three_d::revolve_mesh(path, rule, b, fx_options(fx))?; - Ok(crate::SolidMesh { mesh, color: crate::solids::mesh_color(&paint, opacity) }) + Ok(crate::SolidMesh::plain(mesh, crate::solids::mesh_color(&paint, opacity))) }; if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let before = n.appearance.effects.get(..index).unwrap_or_default(); @@ -924,7 +924,7 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, +} + +impl SolidMesh { + /// A mesh painted `color`, with no graphics. + pub fn plain(mesh: Mesh, color: [f32; 4]) -> Self { + Self { mesh, color, graphics: None } + } +} + +/// The parts of `mesh`, a solid that 3D effect `id` with parameters `p` built about `bounds`, painted +/// `color` from a fill or stroke at `opacity`: for each planar face that carries graphics (Extrude & +/// Bevel's caps, the plane), the triangles on it as a mesh of their own with the art point of each +/// corner ([`MeshGraphics`]), then the rest. Revolve's side, whose graphics are not mapped onto its +/// mesh, stays plain. +fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity): ([f32; 4], f32)) -> Vec { + let list = graphics::mapped_graphics(p); + if list.is_empty() || !takes_graphics(id) || id == crate::REVOLVE { + return vec![SolidMesh::plain(mesh, color)]; + } + let view = view_options(p); + let mut rest = mesh; + let mut out = vec![]; + for face in PlanarFace::ALL { + if !list.iter().any(|g| g.face == face) { + continue; + } + let on_mesh = if id == ROTATE { + vectorcraft_three_d::plane_mesh_face(bounds, view) + } else { + vectorcraft_three_d::extrude_mesh_face(bounds, extrude_options(p), view, face) + }; + let Some(on_mesh) = on_mesh else { continue }; + let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]); + for t in &rest.triangles { + let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied()); + let Some(corners) = t.iter().map(|&i| corner(i)).collect::>>() else { continue }; + let points: Option> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect(); + let into = match points { + Some(points) => { + art.extend(points); + &mut taken + } + None => &mut left, + }; + let base = into.positions.len() as u32; + for (m, n) in corners { + into.positions.push(m); + into.normals.push(n); + } + into.triangles.push([base, base + 1, base + 2]); + } + rest = left; + if !taken.is_empty() { + let graphics = list.iter().filter(|g| g.face == face).cloned().collect(); + let graphics = MeshGraphics { face, graphics, center: bounds.center(), art, opacity, object: 1.0 }; + out.push(SolidMesh { mesh: taken, color, graphics: Some(graphics) }); + } + } + if !rest.is_empty() { + out.insert(0, SolidMesh::plain(rest, color)); + } + out } /// The color a mesh of `paint` at `opacity` takes ([`SolidMesh::color`]). @@ -2363,13 +2428,18 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) let p = crate::merged_params(&fx.id, &fx.params); let view = view_options(&p); let mut out = vec![]; - let mut keep = |out: &mut Vec, mesh: Mesh, color: [f32; 4]| keep_mesh(out, total, SolidMesh { mesh, color }, limit); + // A solid's parts with and without graphics count together against the limit. + let mut keep = |out: &mut Vec, mesh: Mesh, (paint, opacity): (&Paint, f32), bounds: Rect| { + split_graphics(&fx.id, &p, bounds, mesh, (mesh_color(paint, opacity), opacity)) + .into_iter() + .try_for_each(|part| keep_mesh(out, total, part, limit)) + }; if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (paint, opacity, _) = paint_of(item, s.opacity); let (area, rule) = region(&s.path, s.rule, item); - keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, mesh_color(&paint, opacity))?; + keep(&mut out, vectorcraft_three_d::plane_mesh(&area, rule, b, view)?, (&paint, opacity), b)?; } } return Ok(out); @@ -2406,7 +2476,7 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) match solid.mesh() { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *member); - keep(&mut out, mesh, mesh_color(&paint, opacity))?; + keep(&mut out, mesh, (&paint, opacity), bounds)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), @@ -2494,6 +2564,9 @@ fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usi .filter(|m| !m.mesh.is_empty()) .map(|mut m| { m.color[3] *= n.opacity.clamp(0.0, 1.0); + if let Some(g) = &mut m.graphics { + g.object *= n.opacity.clamp(0.0, 1.0); + } m }) .collect(); diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index 7c0087e15b..7ef2fe4e28 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -519,6 +519,71 @@ pub(super) fn face_art( Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true })) } +/// The graphics on one planar face of a solid's mesh ([`super::SolidMesh`]): those mapped onto +/// `face`, placed about `center` (the center of the bounds the solids were built with), and the +/// point of the art's plane that each corner of the mesh shows (document coordinates of the art +/// before its 3D effect, y down). +#[derive(Clone, Debug, PartialEq)] +pub struct MeshGraphics { + pub face: PlanarFace, + pub graphics: Vec, + pub center: Point, + /// One for each position of the mesh. + pub art: Vec, + /// The opacity of the fill or stroke the face is painted with, which the graphics take too, as + /// the canvas draws them; neither a gradient's stops nor the object's own opacity is in it. + pub opacity: f32, + /// The opacity of the object the face belongs to, which applies to the face and its graphics + /// together. + pub object: f32, +} + +impl MeshGraphics { + /// The bounds of the art points of the mesh's corners; `None` without corners. + pub fn art_bounds(&self) -> Option { + let first = *self.art.first()?; + Some(self.art.iter().fold(Rect::from_points(first, first), |r, p| r.union_pt(*p))) + } +} + +/// The art `graphics` draws on its face, flat in the art's plane, unshaded and unclipped: each +/// graphic's fills and stroke outlines at its place ([`MappedGraphic`]), back to front, as one +/// group of objects with id `id`. A graphic whose symbol `doc` does not have, or whose art is past +/// the limits of [`pieces_of`], is left out, as the canvas leaves it out. `Ok(None)` when nothing +/// is drawn; an error when the graphics' art draws more than [`MAX_ELEMENTS`] path elements +/// together. +pub fn mesh_graphics_art(doc: &Document, id: NodeId, graphics: &MeshGraphics) -> Result, String> { + let mut children = vec![]; + let mut elements = 0usize; + for g in graphics.graphics.iter().filter(|g| g.face == graphics.face) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + 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, graphics.center); + for piece in pieces { + elements = elements.saturating_add(drawn_elements(&piece.path, 1)); + if elements > MAX_ELEMENTS { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + let mut paint = piece.paint; + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = place * *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(place); + let mut node = Node::path(id, piece.path.transformed(place), appearance); + if let NodeKind::Path { rule, .. } = &mut node.kind { + *rule = piece.rule; + } + children.push(Arc::new(node)); + } + } + Ok((!children.is_empty()).then(|| Node::group(id, children))) +} + /// One area of a graphic placed on Revolve's unrolled side surface, cut into straight pieces. struct Unrolled { polygons: Vec>, diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index f0da6b992b..fe89dd1f84 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -86,6 +86,48 @@ fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() { assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6); } +#[test] +fn a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane() { + let d = document(); + let graphics = + json!([{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}, {"symbol": "Mark", "face": "back", "x": 20.0, "y": -10.0, "scale": 200.0}]); + // Turned, so the caps' corners in the mesh are not the art's. + let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0, "graphics": graphics})); + let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap(); + // The walls first, then the front cap and the back cap, each two triangles. + assert_eq!( + parts.iter().map(|p| p.graphics.as_ref().map(|g| g.face)).collect::>(), + [None, Some(PlanarFace::Front), Some(PlanarFace::Back)] + ); + let total: usize = parts.iter().map(|p| p.mesh.triangles.len()).sum(); + let plain = super::super::three_d_meshes_in(Some(&d), &object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 35.0, "rotationZ": 10.0}))); + assert_eq!(total, plain.as_ref().map_or(0, |p| p.iter().map(|p| p.mesh.triangles.len()).sum()), "no triangle is lost or doubled"); + assert!(plain.unwrap().iter().all(|p| p.graphics.is_none())); + // The art points of each cap's corners are the art's own square; the graphic is drawn flat at + // its place, mirrored on the back so it reads from behind. + for (part, drawn) in parts[1..].iter().zip([Rect::new(60.0, 30.0, 80.0, 50.0), Rect::new(20.0, 30.0, 40.0, 50.0)]) { + let Some(g) = &part.graphics else { panic!("no graphics") }; + assert_eq!(g.art.len(), part.mesh.positions.len()); + assert!(close(g.art_bounds().unwrap(), Rect::new(0.0, 0.0, 100.0, 100.0)), "{:?}", g.art_bounds()); + assert_eq!(g.graphics.len(), 1); + let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap(); + let paths: Vec<(PathData, Paint)> = art + .children() + .into_iter() + .flatten() + .filter_map(|c| Some((c.path_data()?.clone(), c.appearance.items.first()?.paint().clone()))) + .collect(); + assert!(close(bounds_of(&paths), drawn), "{:?}: {:?}", g.face, bounds_of(&paths)); + assert_eq!(paths[0].1, Paint::solid(red()), "unshaded"); + } + // A plane is all one face; a graphic whose symbol is gone draws nothing. + let n = object(ROTATE, json!({"rotationY": 35.0, "graphics": [{"symbol": "Gone"}]})); + let parts = super::super::three_d_meshes_in(Some(&d), &n).unwrap(); + assert_eq!(parts.len(), 1); + let Some(g) = &parts[0].graphics else { panic!("no graphics") }; + assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None)); +} + #[test] fn without_the_document_or_its_symbol_nothing_is_drawn() { let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]})); @@ -563,6 +605,15 @@ fn art_nested_too_deep_is_refused_and_not_drawn() { // 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); + // A mesh's graphics leave it out as well and draw the others. + let parts = super::super::three_d_meshes_in(Some(&d), &both).unwrap(); + let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") }; + let art = mesh_graphics_art(&d, NodeId(9), g).unwrap().unwrap(); + assert_eq!(art.children().map_or(0, |c| c.len()), 1); + let deep = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]})); + let parts = super::super::three_d_meshes_in(Some(&d), &deep).unwrap(); + let Some(g) = parts.iter().find_map(|p| p.graphics.as_ref()) else { panic!("no graphics") }; + assert_eq!(mesh_graphics_art(&d, NodeId(9), g), Ok(None)); } #[test] diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index a9de7cd7f9..b7ecb75384 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -238,7 +238,7 @@ fn meshes_built_apart(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: match mesh { Ok(mesh) => { let (paint, opacity, _) = paint_of(item, *opacity); - keep_mesh(&mut out, total, SolidMesh { mesh, color: mesh_color(&paint, opacity) }, limit)?; + keep_mesh(&mut out, total, SolidMesh::plain(mesh, mesh_color(&paint, opacity)), limit)?; } Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} Err(e) => return Err(e), diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f972cbb7b3..4e07b323c1 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -47,6 +47,7 @@ vectorcraft-js = { workspace = true } vectorcraft-apischema = { workspace = true } image = { workspace = true } craft-image-codecs = { workspace = true } +tiff = { workspace = true } jxl-oxide = { workspace = true } jxl-color = { workspace = true } jxl-grid = { workspace = true } @@ -88,7 +89,6 @@ craft-jxl = { workspace = true } # vectorcraft-doc's Group 3 TIFF reader before craft-stream-codecs, the reference # tests/group3_reference.rs compares it with. hayro-ccitt = { workspace = true } -tiff = { workspace = true } craft-stream-codecs = { workspace = true } vectorcraft-affinity = { workspace = true, features = ["synth"] } crc32fast = { workspace = true } @@ -98,6 +98,8 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index fcb251347d..05c2fda1d7 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -10,8 +10,8 @@ use vectorcraft_doc::{ExportAsset, NodeId}; use super::edit::{refuse_symbol_part, roots_of, selected_roots}; use super::fileio::{ - DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, check_screen_settings, create_dir, export_crop, export_screens, mesh_file_names, mesh_files, - safe_file_name, store_screen_settings, with_screen_export_preset, write_file, + DEFAULT_FORMAT_3D, FORMATS_3D, SCREEN_SETTINGS_KEYS, TEXTURE_SIZE, TEXTURE_SIZES, check_screen_settings, create_dir, export_crop, export_screens, + image_maps, mesh_file_names, mesh_files, safe_file_name, store_screen_settings, textures, with_screen_export_preset, write_file, }; use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, checked_ids_param, cmd, has_doc, ok, str_param, switch_or, text_param}; @@ -80,7 +80,7 @@ pub fn specs() -> Vec { "Export 3D Assets", [], None, - "{assets?: [asset id…] (default every 3D asset), folder?, zip?} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", + "{assets?: [asset id…] (default every 3D asset), folder?, zip?, textureSize?: 128…4096 (default 1024: the pixels along the longer side of each face's texture)} each 3D asset's object as a mesh file in its format (assets.set3DFormat), named after the asset: USDA or USDZ, glTF 2.0 (one .gltf, its buffer embedded) or OBJ with its .mtl (whitespace and # in an OBJ's name become _). Every solid of the object (the fill's, each stroke's, a group's members') is a mesh with a material in the color it is painted; faces turned away from the viewer are included, at the object's 3D rotation, y up, about the point it turns about, in points (glTF: meters). The graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (threeD.mapGraphic) are a PNG texture of that face: its color with the graphics drawn over it, flat and unlit, on a mesh of the face's own with texture coordinates; glTF embeds it, USDZ stores it after the layer, and OBJ and USDA write it beside them as -texture-1.png… (whitespace, # and @ become _); a face that is not opaque keeps its opacity in the texture's alpha, and an OBJ also gets -texture-1-opacity.png…, the alpha as gray levels for its map_d. Graphics on Revolve's side are not exported. Files that would share a name get -2, -3…; an object with a hole that crosses its face's outline or another hole, or with more than 2,000,000 triangles, or textures of more than 67,108,864 pixels in one export, is refused → {files: [path…]} (no folder: {files: [{name, dataBase64}]}, or with zip one zip as {name, dataBase64, files})", has_doc, export_3d ), @@ -299,6 +299,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } let folder = text_param(p, "folder", C)?.filter(|f| !f.is_empty()); let zip = switch_or(p, "zip", false, C)?; + let size = texture_size_param(p, C)?; + let mut pixels = 0u64; // Every file's name, compared without case: a later file that would take one gets -2, -3… let mut taken: HashSet = HashSet::new(); let mut files: Vec<(String, Vec)> = vec![]; @@ -311,18 +313,20 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { let what = &a.name; let parts = vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let pictures = textures(d, &parts, size, &mut pixels).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let images = image_maps(&pictures); let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); let mut stem = base.clone(); let mut k = 1; loop { - let names = mesh_file_names(&stem, format).map_err(|e| bad(C, e))?; + let names = mesh_file_names(&stem, format, &images).map_err(|e| bad(C, e))?; if names.iter().all(|n| !taken.contains(&n.to_lowercase())) { break; } k += 1; stem = format!("{base}-{k}"); } - let made = mesh_files(&stem, format, &parts).map_err(|e| bad(C, e))?; + let made = mesh_files(&stem, format, &parts, &pictures).map_err(|e| bad(C, e))?; taken.extend(made.iter().map(|(n, _)| n.to_lowercase())); files.extend(made); } @@ -360,6 +364,21 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { } } +/// Param `textureSize` of command `cmd`: the pixels along the longer side of each face's texture, +/// [`TEXTURE_SIZE`] when it is not given. +fn texture_size_param(p: &Value, cmd: &str) -> Result { + let key = "textureSize"; + let (lo, hi) = TEXTURE_SIZES; + match p.get(key) { + None | Some(Value::Null) => Ok(TEXTURE_SIZE), + Some(v) => v + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .filter(|n| (lo..=hi).contains(n)) + .ok_or_else(|| bad(cmd, format!("`{key}` must be a whole number of pixels from {lo} to {hi}"))), + } +} + /// The asset ids of param `key`. fn asset_ids(p: &Value, key: &str, cmd: &str) -> Result> { let ids = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("`{key}` must be an array of asset ids (see assets.list)")))?; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 39dc0db8a2..a15af16360 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -38,6 +38,7 @@ mod shape_builder; mod trace; pub use live_paint::live_paint_gaps; +pub(crate) use live_paint::{isolated_live_paint, merge_drawn_in_isolation}; use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; @@ -144,7 +145,7 @@ pub fn specs() -> Vec { "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 (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), 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)}", + "{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, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, 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 (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), 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) ), diff --git a/crates/engine/src/cmd/buildcmds/live_paint.rs b/crates/engine/src/cmd/buildcmds/live_paint.rs index 7938c07879..2eea5c2c00 100644 --- a/crates/engine/src/cmd/buildcmds/live_paint.rs +++ b/crates/engine/src/cmd/buildcmds/live_paint.rs @@ -1,8 +1,8 @@ use super::{ Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, - PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, - fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, - source_nodes, source_shapes, switch_or, + PathData, Point, Rect, Result, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, fit_to_old_edge, ids_json, + is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, + switch_or, }; /// `options` as stored on a Live Paint group: none for the defaults. @@ -53,6 +53,27 @@ fn make_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result< Ok((gid, nf, ne)) } +/// The children of Live Paint group `g` besides its sources group ([`b::sources`]) and its faces and +/// edges (paths named [`FACE_NAME`] or [`EDGE_NAME`]), back to front: objects drawn in it in +/// isolation mode. A group or other object named like a part is one of them. +fn others_in(g: &Node) -> impl Iterator> { + let src = b::sources(g).map(|s| s.id); + g.children() + .into_iter() + .flatten() + .filter(move |c| Some(c.id) != src && !(c.path_data().is_some() && matches!(c.name.as_deref(), Some(FACE_NAME | EDGE_NAME)))) +} + +/// Make `parts` (a sources group, faces and edges made again) the children of Live Paint group `g`, +/// with its other children ([`others_in`]) that are not among `gone` kept in front of them, in their +/// order. +fn set_parts(g: &mut Node, mut parts: Vec>, gone: &[NodeId]) { + parts.extend(others_in(g).filter(|c| !gone.contains(&c.id)).cloned()); + if let Some(ch) = g.children_mut() { + *ch = parts; + } +} + /// Select `ids` alone, without an undo step, when they are not selected that way already. fn select_only(s: &mut Session, ids: &[NodeId]) -> Result<()> { let st = s.doc()?; @@ -134,9 +155,15 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect(); let old_parts = old.clone(); let mut sources = source_nodes(&old); + // The objects drawn in the other Live Paint groups besides their parts stay in the merged group. + let mut others = vec![]; for r in roots { if *r != target { - sources.extend(source_nodes(d.node(*r).ok_or(EngineError::NoNode(*r))?)); + let n = d.node(*r).ok_or(EngineError::NoNode(*r))?; + sources.extend(source_nodes(n)); + if is_live_paint(n) { + others.extend(others_in(n).cloned()); + } } } // Merge applies the Gap Options' merge rules to the groups' options, bottom-most first. @@ -146,8 +173,9 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result // The group keeps its name, lock, visibility, transparency, appearance, opacity mask, graphic // style link and the rest; its children are made again and its Gap Options set to the merged ones. let mut g = old; + set_parts(&mut g, children, roots); if let Some(ch) = g.children_mut() { - *ch = children; + ch.extend(others); } g.extras_mut().live_paint_gaps = stored_gap_options(options); for (pt, carried) in keep_faces { @@ -199,6 +227,38 @@ pub(super) fn lp_merge(s: &mut Session, p: &Value) -> Result { Ok(json!({ "id": id.0, "faces": faces, "edges": edges })) } +/// The Live Paint group whose drawn art is added when isolation mode leaves `isolated`: the innermost +/// Live Paint group that is `isolated` or holds it, such as a group drawn in an isolated Live Paint +/// group and then isolated itself. None when `isolated` is not in a Live Paint group. +pub(crate) fn isolated_live_paint(d: &Document, isolated: NodeId) -> Option { + d.ancestry(isolated)?.into_iter().rev().find(|id| d.node(*id).is_some_and(is_live_paint)) +} + +/// The children of Live Paint group `g` besides its parts ([`others_in`]) that Live Paint takes +/// ([`b::live_paint_takes`]) and that are shown and unlocked with everything in them, back to +/// front: the paths drawn in it in isolation mode. +fn drawn_in(g: &Node) -> Vec { + fn open(n: &Node) -> bool { + n.visible && !n.locked && n.children().is_none_or(|ch| ch.iter().all(|c| open(c))) + } + others_in(g).filter(|c| open(c) && b::live_paint_takes(c)).map(|c| c.id).collect() +} + +/// Leaving isolation mode in Live Paint group `g` adds the paths drawn in it to the group as +/// `livePaint.merge` does, in one "Merge Live Paint" undo step; → whether any were added. Type, +/// images, other objects Live Paint does not take, and hidden or locked objects stay where they +/// are. With nothing to add, or when `g` is not a Live Paint group, nothing changes and no undo +/// step is recorded. +pub(crate) fn merge_drawn_in_isolation(s: &mut Session, g: NodeId) -> Result { + let drawn = s.doc()?.doc.node(g).filter(|n| is_live_paint(n)).map(drawn_in).unwrap_or_default(); + if drawn.is_empty() { + return Ok(false); + } + let roots: Vec = std::iter::once(g).chain(drawn).collect(); + s.edit("Merge Live Paint", |d, sel| merge_live(d, sel, &roots))?; + Ok(true) +} + fn live_targets(s: &Session, p: &Value) -> Result> { let d = &s.doc()?.doc; let ids = root_ids(s, p)?; @@ -216,7 +276,8 @@ pub(super) fn lp_release(s: &mut Session, p: &Value) -> Result { let mut released = Beside::replacing(d, &targets); for g in &targets { let n = d.node(*g).cloned().ok_or(EngineError::NoNode(*g))?; - let srcs: Vec = source_nodes(&n).iter().map(|c| (**c).clone()).collect(); + // The objects drawn in the group besides its parts are released in front of its paths. + let srcs: Vec = source_nodes(&n).iter().chain(others_in(&n)).map(|c| (**c).clone()).collect(); out.extend(srcs.iter().map(|c| c.id)); released.put(d, *g, srcs)?; } @@ -245,10 +306,12 @@ pub(super) fn lp_expand(s: &mut Session, p: &Value) -> Result { e.trace = None; e.live_paint_gaps = None; } + // Objects drawn in the group ([`others_in`]) stay, whatever they are named. + let src = b::sources(n).map(|c| c.id); if let Some(ch) = n.children_mut() { ch.retain(|c| match c.name.as_deref() { - Some(SOURCES_NAME) => false, - Some(FACE_NAME | EDGE_NAME) => draws(c), + _ if Some(c.id) == src => false, + Some(FACE_NAME | EDGE_NAME) if c.path_data().is_some() => draws(c), _ => true, }); } @@ -354,9 +417,7 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result { // The faces change only with what paint stops at, or with new paths. if added > 0 || options.max_gap() != old.gap_options().max_gap() { let (children, _, _) = build_children(d, sources, options.max_gap())?; - if let Some(ch) = n.children_mut() { - *ch = children; - } + set_parts(&mut n, children, &[]); repaint_from(&mut n, &old); } n.extras_mut().live_paint_gaps = stored_gap_options(options); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index c17d6a4428..680e2902c8 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -209,7 +209,7 @@ pub fn specs() -> Vec { "Load Metafile into Clipboard", [], None, - "{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; then run edit.paste", + "{dataBase64 (EMF or WMF bytes), center?: [x, y]} replace the clipboard with the picture's objects (paths, clipping groups, images, point type; the images they use), centred on `center` (default: the first artboard) → {count, warnings}; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning; then run edit.paste", has_doc, import_emf ), diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..a6e913f9f6 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -39,7 +39,7 @@ pub mod jxlread; mod legacy_ai; mod load; mod mesh3d; -pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, png_clip, size_note}; +pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, image_clip, size_note}; mod heifread; mod hpgl; mod jp2read; @@ -87,8 +87,10 @@ pub use load::{ }; pub(crate) use load::{check_files_not_lossy_overwrite, check_not_lossy_overwrite, lossy_source}; pub use load::{losses_summary, overwrite_losses}; -pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, format_3d_label}; -pub(crate) use mesh3d::{mesh_file_names, mesh_files}; +#[cfg(test)] +pub(crate) use mesh3d::MAX_TEXTURE_PIXELS; +pub use mesh3d::{DEFAULT_FORMAT_3D, FORMATS_3D, draws_textures, format_3d_label}; +pub(crate) use mesh3d::{TEXTURE_SIZE, TEXTURE_SIZES, image_maps, mesh_file_names, mesh_files, textures}; pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name}; pub(crate) use native::preview_png; pub use native::with_compression_pref; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 554d088b79..adc73c2c85 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -9,7 +9,7 @@ pub fn specs() -> Vec { "Open Document", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", + "{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible .ai or a PDF saved with its editing data opens on its trim boxes for crop), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a PDF-compatible .ai: its trim box for crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), importer?: \"plugin.\" (an importer plug-in's format id, see document.formats: it opens the file, which must have an extension it lists, also one a built-in format reads), params?: {…} (the importer's own parameters, see plugin.info)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; the color management policies of edit.colorSettings keep, take off or convert from the profiles the file is tagged with, their notes go to warnings, and a document they changed opens with unsaved changes; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning; a picture cut short by a reader limit, images and pattern brushes that can't be read, clips that can't be applied and raster operations other than a plain copy each add a warning), PICT .pct/.pic/.pict (QuickDraw versions 1 and 2, with or without the file's 512-byte header: one artboard, the picture's frame; shapes, lines and regions as paths, text as point type, bitmaps, pixel maps and QuickTime JPEG images as images; what isn't read is listed in warnings), HP-GL plot files .plt/.hpgl/.hgl/.hpg (one artboard round the art; what isn't drawn is listed in warnings), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again) and opens on the artboard its editing copy names as active. A file that no built-in format reads, by its content or its extension, opens with the installed importer plug-in that lists its extension (the one whose id sorts first, when several do): it is given the file, at most 128 MiB, and its objects become a new document whose artboard is their bounds; Save then asks for a name, and the warnings are the importer's. Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks). An SVG's variable data (SVG Options › Include Variable Data, a variableSets element) gives the document its text variables and data sets, each text variable bound to the type object its docRef names, unless the SVG restores the native document; variable data variable.loadLibrary would refuse is left out with a warning", always, load::open ), diff --git a/crates/engine/src/cmd/fileio/export.rs b/crates/engine/src/cmd/fileio/export.rs index 1e27778aac..2fb2b63357 100644 --- a/crates/engine/src/cmd/fileio/export.rs +++ b/crates/engine/src/cmd/fileio/export.rs @@ -211,17 +211,11 @@ fn selected_part(n: &Arc, keep: &HashSet, holders: &HashSet Document { - fn kept( - n: &Arc, - doc: &Document, - symbols: &SymbolBoxes, - rect: vectorcraft_geom::Rect, - renderer: &mut vectorcraft_render::Renderer, - ) -> Option> { + fn kept(n: &Arc, symbols: &SymbolBoxes, rect: vectorcraft_geom::Rect, renderer: &mut vectorcraft_render::Renderer) -> Option> { if matches!(n.kind, NodeKind::Layer { clip: false, .. }) { let mut layer = Node::clone(n); let children = layer.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return Some(Arc::new(layer)); } // A group that doesn't clip keeps only its members over the artboard, so art gathered in one @@ -230,20 +224,21 @@ pub(super) fn art_over(doc: &Document, rect: vectorcraft_geom::Rect, renderer: & if matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.appearance.effects.is_empty() { let mut group = Node::clone(n); let children = group.children_mut()?; - *children = children.iter().filter_map(|c| kept(c, doc, symbols, rect, renderer)).collect(); + *children = children.iter().filter_map(|c| kept(c, symbols, rect, renderer)).collect(); return (!children.is_empty()).then(|| Arc::new(group)); } let over = |b: vectorcraft_geom::Rect| b.x0 <= rect.x1 && rect.x0 <= b.x1 && b.y0 <= rect.y1 && rect.y0 <= b.y1; let mut holds_instance = false; n.walk(&mut |c| holds_instance |= matches!(c.kind, NodeKind::SymbolInstance { .. })); - let painted = || holds_instance && vectorcraft_render::painted_bounds(doc, n).is_some_and(over); + // Measured in boxes of its own, which find symbols through the same index. + let painted = || holds_instance && vectorcraft_render::painted_bounds_with(&symbols.unmeasured(), n).is_some_and(over); let reach = vectorcraft_brush::reach_within(n); let brushed = |b: vectorcraft_geom::Rect| over(if reach > 0.0 { b.inflate(reach, reach) } else { b }); (n.visual_bounds_with(symbols).is_none_or(brushed) || renderer.effect_bounds(symbols, n).is_some_and(brushed) || painted()).then(|| n.clone()) } let symbols = doc.symbol_boxes().with_brush_art(); let mut d = doc.clone(); - d.layers = doc.layers.iter().filter_map(|l| kept(l, doc, &symbols, rect, renderer)).collect(); + d.layers = doc.layers.iter().filter_map(|l| kept(l, &symbols, rect, renderer)).collect(); d } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..4e59e378a5 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -60,8 +60,7 @@ impl Loaded { } } -/// An image ready to embed: PNG/JPEG/GIF/WebP keep their bytes, other formats are stored as PNG -/// (what browsers, PDF and SVG viewers show). +/// An image ready to embed. CMYK images use JPEG or TIFF; other images use browser-readable formats. #[derive(Clone)] pub struct RasterImage { /// Content key for `Document::images` (identical files share one blob). @@ -937,8 +936,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]); /// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color /// settings' CMYK, whichever of their extra channels is the alpha -/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose -/// merged image is read ([`psdread`]). +/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]). Opaque CMYK PSD/PSB merged images retain +/// 8- or 16-bit inks and their CMYK ICC profile as TIFF, within the native CMYK pixel and allocation limits; +/// other CMYK composites use the RGBA decoder's allocation limit ([`psdread`]). /// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA /// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]). /// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read @@ -961,14 +961,27 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option { /// or TIFF keeps its inks, at the 8 or 16 bits the file has, and its CMYK ICC profile as a CMYK /// TIFF ([`vectorcraft_doc::cmyk::turned_cmyk`]). An image the decoder reads and that is stored as /// PNG keeps its gray or RGB samples at 8 or 16 bits, and the gray or RGB ICC profile they are in; -/// other samples become 8-bit RGBA. A Photoshop document's PNG keeps the clipping path the file -/// names ([`png_with_clip`]). +/// other samples become 8-bit RGBA. A PSD/PSB composite's stored image keeps its imported +/// clipping path ([`image_clip`]). pub fn raster_image(bytes: &[u8]) -> Result { let ppi = super::ppi::resolution(bytes); if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) { return Err(err(format!("an image of {w} × {h} pixels is too large to draw"))); } if psdread::is_psd(bytes) { + if let Some(mut native) = psdread::decode_cmyk(bytes, MAX_RASTER_ALLOC).map_err(err)? { + native.meta.dpi = ppi.map(|(x, y)| (x as f32, y as f32)); + let clip = psdread::clipping_path(bytes).and_then(|path| { + let json = serde_json::to_string(&path).ok().filter(|j| j.len() <= MAX_PNG_CLIP)?; + native.meta.text.push(("Description".into(), format!("{CLIP_KEYWORD}\n{json}"))); + Some((path, vectorcraft_geom::FillRule::EvenOdd)) + }); + let data = + craft_image_codecs::encode(&native, craft_image_codecs::Format::Tiff, &craft_image_codecs::EncodeOptions::default()).map_err(err)?; + let mut img = stored(data, "image/tiff", native.dimensions(), ppi)?; + img.clip = clip; + return Ok(img); + } let cms = vectorcraft_color::cms::active(); let img = as_png(psdread::decode(bytes, MAX_RASTER_ALLOC, |c| cms.cmyk_to_srgb(c, false)).map_err(err)?, None, ppi)?; return Ok(png_with_clip(img, psdread::clipping_path(bytes))); @@ -1173,6 +1186,31 @@ pub(crate) fn png_clip(png: &[u8]) -> Option { vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) } +/// The imported clipping-path marker in a stored PNG or CMYK TIFF, within the path budget. +pub(crate) fn image_clip(blob: &ImageBlob) -> Option { + if blob.mime == "image/png" { + return png_clip(&blob.bytes); + } + if blob.mime != "image/tiff" { + return None; + } + use tiff::tags::{Tag, Type, ValueBuffer}; + let mut d = tiff::decoder::Decoder::new(std::io::Cursor::new(blob.bytes.as_slice())).ok()?; + let mut ifd = d.image_ifd(); + let entry = ifd.find_entry(Tag::ImageDescription)?; + if entry.field_type() != Type::ASCII || entry.count() > (MAX_PNG_CLIP + CLIP_KEYWORD.len() + 2) as u64 { + return None; + } + let mut buf = ValueBuffer::empty(Type::ASCII); + ifd.find_tag_buf(Tag::ImageDescription, &mut buf).ok()??; + let json = buf.as_bytes().strip_prefix(CLIP_KEYWORD.as_bytes())?.strip_prefix(b"\n")?; + let json = json.strip_suffix(b"\0").unwrap_or(json); + if json.len() > MAX_PNG_CLIP { + return None; + } + vectorcraft_geom::path::with_anchor_budget(vectorcraft_geom::path::MAX_READ_ANCHORS, || serde_json::from_slice(json).ok()) +} + /// An image as a document of its physical size at the resolution it declares (as Place sizes it; /// 72 ppi, 1 px = 1 pt, when it declares none), the image named after the file. pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result { diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 50a919d834..2e781772ea 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -9,13 +9,24 @@ //! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since //! an open solid or a turned plane is seen from both sides. //! +//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its +//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through +//! texture coordinates and a material of its own. glTF embeds each PNG as a data URI, USDZ stores it +//! after the layer, and OBJ and USDA name PNG files written beside them (`-texture-1.png`…). +//! //! Formats: glTF 2.0 , USD -//! (USDZ: ). +//! (USDZ: ; +//! textures: ), OBJ and MTL +//! . use std::fmt::Write as _; +use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_render::effects::SolidMesh; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Affine, Rect}; +use vectorcraft_render::effects::{MeshGraphics, SolidMesh}; /// The formats a 3D asset exports to, as `assets.set3DFormat` names them: USDA first, the default. pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; @@ -23,6 +34,12 @@ pub const FORMATS_3D: [&str; 4] = ["usda", "usdz", "gltf", "obj"]; pub const DEFAULT_FORMAT_3D: &str = "usda"; /// The meters in a point (1/72 inch). const METERS_PER_POINT: f64 = 0.0254 / 72.0; +/// The pixels along the longer side of a face's texture, unless `assets.export3D` is given another +/// size, and the sizes it takes. +pub(crate) const TEXTURE_SIZE: u32 = 1024; +pub(crate) const TEXTURE_SIZES: (u32, u32) = (128, 4096); +/// The most texture pixels one export draws, all its assets together. +pub(crate) const MAX_TEXTURE_PIXELS: u64 = 4 * 4096 * 4096; /// The label of `format` for menus: `USDA`, `USDZ`, `glTF`, `OBJ`. pub fn format_3d_label(format: &str) -> &'static str { @@ -40,14 +57,44 @@ fn obj_stem(stem: &str) -> String { stem.chars().map(|c| if c.is_whitespace() || c == '#' { '_' } else { c }).collect() } -/// The names of the files [`mesh_files`] writes for `stem` in `format`. -pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, String> { +/// The name of texture `k` (from 0) of the object named `stem`: whitespace, `#` and `@` become `_`, +/// so an MTL `map_Kd` line and a USD asset path name it as one word. +fn texture_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}.png", texture_stem(stem), k + 1) +} + +/// The name of the opacity map of texture `k` (from 0) of the object named `stem`, as +/// [`texture_name`] names the texture. +fn opacity_name(stem: &str, k: usize) -> String { + format!("{}-texture-{}-opacity.png", texture_stem(stem), k + 1) +} + +/// `stem` with whitespace, `#` and `@` turned into `_`, for the names of its textures. +fn texture_stem(stem: &str) -> String { + stem.chars().map(|c| if c.is_whitespace() || c == '#' || c == '@' { '_' } else { c }).collect() +} + +/// The names of the files [`mesh_files`] writes for `stem` in `format` with the textures `images` +/// ([`image_maps`]: for each, whether it has an opacity map): OBJ and USDA name a PNG file for each +/// texture after them, and OBJ also one for each opacity map, after its texture; glTF and USDZ hold +/// theirs. +pub(crate) fn mesh_file_names(stem: &str, format: &str, images: &[bool]) -> Result, String> { + let beside = |mut names: Vec, stem: &str, maps: bool| { + for (k, map) in images.iter().enumerate() { + names.push(texture_name(stem, k)); + if maps && *map { + names.push(opacity_name(stem, k)); + } + } + names + }; match format { "obj" => { let stem = obj_stem(stem); - Ok(vec![format!("{stem}.obj"), format!("{stem}.mtl")]) + Ok(beside(vec![format!("{stem}.obj"), format!("{stem}.mtl")], &stem, true)) } - "gltf" | "usda" | "usdz" => Ok(vec![format!("{stem}.{format}")]), + "usda" => Ok(beside(vec![format!("{stem}.usda")], stem, false)), + "gltf" | "usdz" => Ok(vec![format!("{stem}.{format}")]), _ => { let key = "format"; Err(format!("`{key}` must be one of {}", FORMATS_3D.join(", "))) @@ -55,35 +102,109 @@ pub(crate) fn mesh_file_names(stem: &str, format: &str) -> Result, S } } +/// A picture painted on one part of a 3D object ([`SolidMesh`]): a PNG, and for each corner of the +/// part's mesh where it falls on the picture (0 to 1 across from the left, 0 to 1 down from the +/// top). `opacity` is a grayscale PNG of the picture's alpha when some of it is not opaque. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Texture { + pub png: Arc>, + pub opacity: Option>>, + pub uv: Vec<[f64; 2]>, +} + +/// A distinct picture of a 3D object: the PNG and its opacity map. +type Picture = (Arc>, Option>>); + +/// The distinct pictures of `textures` in order of first use, and the index among them of each +/// part's (`None` for a part without one). +fn images(parts: usize, textures: &[Option]) -> (Vec, Vec>) { + let mut out: Vec = vec![]; + let index = (0..parts) + .map(|k| { + let t = textures.get(k)?.as_ref()?; + Some(out.iter().position(|(p, _)| Arc::ptr_eq(p, &t.png) || p == &t.png).unwrap_or_else(|| { + out.push((t.png.clone(), t.opacity.clone())); + out.len() - 1 + })) + }) + .collect(); + (out, index) +} + +/// For each distinct picture of `textures`, whether it has an opacity map ([`mesh_file_names`]). +pub(crate) fn image_maps(textures: &[Option]) -> Vec { + images(textures.len(), textures).0.iter().map(|(_, map)| map.is_some()).collect() +} + /// The files of a 3D object named `stem` in `format` ([`FORMATS_3D`]): `(file name, bytes)`, the -/// OBJ with its MTL after it. -pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { - let names = mesh_file_names(stem, format)?; - let bytes = match format { +/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after +/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`. +pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option]) -> Result)>, String> { + let (images, image) = images(parts.len(), textures); + let maps: Vec = images.iter().map(|(_, map)| map.is_some()).collect(); + let names = mesh_file_names(stem, format, &maps)?; + let pictures: Vec>> = images.iter().map(|(p, _)| p.clone()).collect(); + let scene = Scene { parts, textures, image: &image, pictures: &pictures, maps: &maps }; + let pngs = || pictures.iter().map(|p| p.as_ref().clone()); + let bytes: Vec> = match format { "obj" => { - let (obj, mtl) = obj(&obj_stem(stem), parts); - vec![obj.into_bytes(), mtl.into_bytes()] + let stem = obj_stem(stem); + let (obj, mtl) = obj(&stem, &scene); + let with_maps = images.iter().flat_map(|(p, map)| std::iter::once(p.as_ref().clone()).chain(map.as_ref().map(|m| m.as_ref().clone()))); + [obj.into_bytes(), mtl.into_bytes()].into_iter().chain(with_maps).collect() + } + "gltf" => vec![gltf(stem, &scene).into_bytes()], + "usda" => std::iter::once(usda(stem, &scene).into_bytes()).chain(pngs()).collect(), + _ => { + let mut members = vec![(format!("{stem}.usda"), usda(stem, &scene).into_bytes())]; + members.extend(pngs().enumerate().map(|(k, png)| (texture_name(stem, k), png))); + vec![super::zip::store_aligned(&members, 64)?] } - "gltf" => vec![gltf(stem, parts).into_bytes()], - "usda" => vec![usda(stem, parts).into_bytes()], - _ => vec![super::zip::store_aligned(&[(format!("{stem}.usda"), usda(stem, parts).into_bytes())], 64)?], }; Ok(names.into_iter().zip(bytes).collect()) } -/// The distinct colors of `parts` in order, and each part's index among them. -fn materials(parts: &[SolidMesh]) -> (Vec<[f32; 4]>, Vec) { - let mut colors: Vec<[f32; 4]> = vec![]; - let index = parts +/// The parts of an object with their pictures: `image` is each part's index among `pictures`, and +/// `maps` says for each picture whether it has an opacity map. +struct Scene<'a> { + parts: &'a [SolidMesh], + textures: &'a [Option], + image: &'a [Option], + pictures: &'a [Arc>], + maps: &'a [bool], +} + +impl Scene<'_> { + /// Part `k`'s texture coordinates and picture, when it has a picture. + fn texture(&self, k: usize) -> Option<(&[[f64; 2]], usize)> { + let t = self.textures.get(k)?.as_ref()?; + Some((t.uv.as_slice(), (*self.image.get(k)?)?)) + } +} + +/// A material: a color, with a picture that replaces its red, green and blue. +#[derive(Clone, Copy, PartialEq)] +struct Material { + color: [f32; 4], + image: Option, +} + +/// The distinct materials of `scene`'s parts in order, and each part's index among them. +fn materials(scene: &Scene) -> (Vec, Vec) { + let mut out: Vec = vec![]; + let index = scene + .parts .iter() - .map(|p| { - colors.iter().position(|c| *c == p.color).unwrap_or_else(|| { - colors.push(p.color); - colors.len() - 1 + .enumerate() + .map(|(k, p)| { + let m = Material { color: p.color, image: scene.texture(k).map(|(_, i)| i) }; + out.iter().position(|c| *c == m).unwrap_or_else(|| { + out.push(m); + out.len() - 1 }) }) .collect(); - (colors, index) + (out, index) } /// An sRGB channel (0..1) as linear light. @@ -96,8 +217,9 @@ fn num(v: f64) -> String { format!("{v}") } -fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { - let (colors, material) = materials(parts); +fn obj(stem: &str, scene: &Scene) -> (String, String) { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut o = String::new(); let _ = writeln!(o, "mtllib {stem}.mtl"); let _ = writeln!(o, "o {stem}"); @@ -106,33 +228,64 @@ fn obj(stem: &str, parts: &[SolidMesh]) -> (String, String) { let _ = writeln!(o, "v {} {} {}", num(v[0]), num(v[1]), num(v[2])); } } + // OBJ's texture coordinates run up from the picture's bottom. + for k in 0..parts.len() { + for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() { + let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1])); + } + } for p in parts { for n in &p.mesh.normals { let _ = writeln!(o, "vn {} {} {}", num(n[0]), num(n[1]), num(n[2])); } } - let mut base = 1usize; + let (mut base, mut uv_base) = (1usize, 1usize); for (k, p) in parts.iter().enumerate() { let _ = writeln!(o, "g Solid_{}", k + 1); let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1); + let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some(); for t in &p.mesh.triangles { - let [a, b, c] = t.map(|i| i as usize + base); - let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + if textured { + let [a, b, c] = t.map(|i| i as usize); + let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base); + let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c)); + } else { + let [a, b, c] = t.map(|i| i as usize + base); + let _ = writeln!(o, "f {a}//{a} {b}//{b} {c}//{c}"); + } } base += p.mesh.positions.len(); + uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len()); } let mut m = String::new(); - for (k, c) in colors.iter().enumerate() { + for (k, mat) in materials.iter().enumerate() { + let c = mat.color; let _ = writeln!(m, "newmtl Material_{}", k + 1); - let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); - let _ = writeln!(m, "d {}", num(f64::from(c[3]))); + match mat.image { + // The picture holds the color; Kd multiplies it. + Some(_) => { + let _ = writeln!(m, "Kd 1 1 1"); + } + None => { + let _ = writeln!(m, "Kd {} {} {}", num(f64::from(c[0])), num(f64::from(c[1])), num(f64::from(c[2]))); + } + } + // A picture's opacity map holds the opacity, as gray levels. + let _ = writeln!(m, "d {}", if mat.image.is_some() { "1".to_string() } else { num(f64::from(c[3])) }); let _ = writeln!(m, "illum 1"); + if let Some(i) = mat.image { + let _ = writeln!(m, "map_Kd -clamp on {}", texture_name(stem, i)); + if scene.maps.get(i).copied().unwrap_or(false) { + let _ = writeln!(m, "map_d -clamp on {}", opacity_name(stem, i)); + } + } } (o, m) } -fn gltf(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn gltf(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let mut buffer: Vec = vec![]; let (mut views, mut accessors, mut primitives) = (vec![], vec![], vec![]); let mut view = |buffer: &mut Vec, bytes: Vec, target: u32| -> usize { @@ -154,16 +307,25 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { })); accessors.push(json!({ "bufferView": normals, "componentType": 5126, "count": count, "type": "VEC3" })); accessors.push(json!({ "bufferView": indices, "componentType": 5125, "count": p.mesh.triangles.len() * 3, "type": "SCALAR" })); - primitives.push(json!({ + let mut primitive = json!({ "attributes": { "POSITION": at, "NORMAL": at + 1 }, "indices": at + 2, "material": material.get(k).copied().unwrap_or(0), - })); + }); + // glTF's texture coordinates run down from the picture's top, as the picture's own do. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) { + let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect(); + let coords = view(&mut buffer, bytes, 34962); + primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len()); + accessors.push(json!({ "bufferView": coords, "componentType": 5126, "count": count, "type": "VEC2" })); + } + primitives.push(primitive); } - let materials: Vec = colors + let materials: Vec = materials .iter() .enumerate() - .map(|(k, c)| { + .map(|(k, mat)| { + let c = mat.color; let mut m = json!({ "name": format!("Material_{}", k + 1), "pbrMetallicRoughness": { @@ -173,13 +335,18 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { }, "doubleSided": true, }); + if let Some(i) = mat.image { + // The picture holds the color and the opacity; the factor multiplies them. + m["pbrMetallicRoughness"]["baseColorFactor"] = json!([1.0, 1.0, 1.0, 1.0]); + m["pbrMetallicRoughness"]["baseColorTexture"] = json!({ "index": i }); + } if c[3] < 1.0 { m["alphaMode"] = json!("BLEND"); } m }) .collect(); - let doc = json!({ + let mut doc = json!({ "asset": { "version": "2.0", "generator": "VectorCraft" }, "scene": 0, "scenes": [{ "nodes": [0] }], @@ -193,6 +360,14 @@ fn gltf(stem: &str, parts: &[SolidMesh]) -> String { "bufferViews": views, "accessors": accessors, }); + if !scene.pictures.is_empty() { + // Linear filtering, mipmaps, and coordinates held at the picture's edge. + doc["samplers"] = json!([{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }]); + doc["textures"] = Value::Array((0..scene.pictures.len()).map(|i| json!({ "sampler": 0, "source": i })).collect()); + doc["images"] = Value::Array( + scene.pictures.iter().map(|p| json!({ "uri": format!("data:image/png;base64,{}", vectorcraft_format::base64_encode(p)) })).collect(), + ); + } serde_json::to_string_pretty(&doc).unwrap_or_default() } @@ -205,8 +380,9 @@ fn prim_name(name: &str) -> String { out } -fn usda(stem: &str, parts: &[SolidMesh]) -> String { - let (colors, material) = materials(parts); +fn usda(stem: &str, scene: &Scene) -> String { + let parts = scene.parts; + let (materials, material) = materials(scene); let root = prim_name(stem); let triple = |v: [f64; 3]| format!("({}, {}, {})", num(v[0]), num(v[1]), num(v[2])); let list = |items: Vec| items.join(", "); @@ -238,23 +414,178 @@ fn usda(stem: &str, parts: &[SolidMesh]) -> String { linear(c[2]) ); let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]); + // USD's texture coordinates run up from the picture's bottom. + if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) { + let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect()); + let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )"); + } let _ = writeln!(u, " uniform token subdivisionScheme = \"none\"\n }}\n"); } let _ = writeln!(u, " def Scope \"Materials\"\n {{"); - for (k, c) in colors.iter().enumerate() { - let m = k + 1; + for (k, mat) in materials.iter().enumerate() { + let (m, c) = (k + 1, mat.color); + let at = format!("/{root}/Materials/Material_{m}"); let _ = writeln!(u, " def Material \"Material_{m}\"\n {{"); - let _ = writeln!(u, " token outputs:surface.connect = \n"); + let _ = writeln!(u, " token outputs:surface.connect = <{at}/Surface.outputs:surface>\n"); let _ = writeln!(u, " def Shader \"Surface\"\n {{"); let _ = writeln!(u, " uniform token info:id = \"UsdPreviewSurface\""); - let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); - let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + match mat.image { + // The picture holds the color, and the opacity when the face is not opaque. + Some(_) => { + let _ = writeln!(u, " color3f inputs:diffuseColor.connect = <{at}/Texture.outputs:rgb>"); + if c[3] < 1.0 { + let _ = writeln!(u, " float inputs:opacity.connect = <{at}/Texture.outputs:a>"); + } else { + let _ = writeln!(u, " float inputs:opacity = 1"); + } + } + None => { + let _ = writeln!(u, " color3f inputs:diffuseColor = ({}, {}, {})", linear(c[0]), linear(c[1]), linear(c[2])); + let _ = writeln!(u, " float inputs:opacity = {}", c[3]); + } + } let _ = writeln!(u, " float inputs:roughness = 1"); - let _ = writeln!(u, " token outputs:surface\n }}\n }}"); + let _ = writeln!(u, " token outputs:surface\n }}"); + if let Some(i) = mat.image { + let _ = writeln!(u, "\n def Shader \"Texture\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdUVTexture\""); + let _ = writeln!(u, " asset inputs:file = @{}@", texture_name(stem, i)); + let _ = writeln!(u, " float2 inputs:st.connect = <{at}/Coordinates.outputs:result>"); + let _ = writeln!(u, " token inputs:sourceColorSpace = \"sRGB\""); + let _ = writeln!(u, " token inputs:wrapS = \"clamp\""); + let _ = writeln!(u, " token inputs:wrapT = \"clamp\""); + let _ = writeln!(u, " float3 outputs:rgb"); + if c[3] < 1.0 { + let _ = writeln!(u, " float outputs:a"); + } + let _ = writeln!(u, " }}"); + let _ = writeln!(u, "\n def Shader \"Coordinates\"\n {{"); + let _ = writeln!(u, " uniform token info:id = \"UsdPrimvarReader_float2\""); + let _ = writeln!(u, " string inputs:varname = \"st\""); + let _ = writeln!(u, " float2 outputs:result\n }}"); + } + let _ = writeln!(u, " }}"); } let _ = writeln!(u, " }}\n}}"); u } +/// The pictures of the graphics on `parts` ([`SolidMesh::graphics`]), one for each part in order +/// (`None` for a part without graphics, or whose graphics draw nothing): the part's color with its +/// graphics drawn over it, flat and unshaded ([`vectorcraft_render::effects::mesh_graphics_art`]), +/// over the bounds of the art points of its corners, `size` pixels along the longer side. Parts with +/// the same color, face, graphics and bounds share one picture. `pixels` counts the pixels drawn so +/// far, and every call of one export shares it: an error when it passes [`MAX_TEXTURE_PIXELS`]. +pub(crate) fn textures(doc: &Document, parts: &[SolidMesh], size: u32, pixels: &mut u64) -> Result>, String> { + let mut renderer: Option = None; + // Each picture drawn: the part it was drawn for, its bounds, and the PNG with its opacity map + // (`None`: nothing drawn). + let mut drawn: Vec = vec![]; + let mut out = vec![]; + for part in parts { + let Some(g) = &part.graphics else { + out.push(None); + continue; + }; + let Some(frame) = texture_frame(g) else { + out.push(None); + continue; + }; + let scale = f64::from(size) / frame.width().max(frame.height()); + let fit = |side: f64| ((side * scale).ceil() as u32).clamp(1, size); + let (w, h) = (fit(frame.width()), fit(frame.height())); + let same = |(p, r, _): &&Drawn| p.color == part.color && *r == frame && p.graphics.as_ref().is_some_and(|o| same_graphics(o, g)); + let png = match drawn.iter().find(same) { + Some((_, _, png)) => png.clone(), + None => { + let png = match vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g)? { + None => None, + Some(art) => { + *pixels = pixels.saturating_add(u64::from(w) * u64::from(h)); + if *pixels > MAX_TEXTURE_PIXELS { + return Err(format!( + "the graphics need more than {MAX_TEXTURE_PIXELS} pixels of textures: lower textureSize (now {size})" + )); + } + let renderer = renderer.get_or_insert_with(vectorcraft_render::Renderer::new); + Some(picture(doc, renderer, (part.color, g.opacity, g.object), art, (frame, scale), (w, h))?) + } + }; + drawn.push((part, frame, png.clone())); + png + } + }; + out.push(png.map(|(png, opacity)| { + let uv = g.art.iter().map(|p| [(p.x - frame.x0) * scale / f64::from(w), (p.y - frame.y0) * scale / f64::from(h)]).collect(); + Texture { png, opacity, uv } + })); + } + Ok(out) +} + +/// Does [`textures`] draw a picture for one of `parts`: a part with graphics whose corners span an +/// area and whose graphics draw something? Nothing is rendered. +pub fn draws_textures(doc: &Document, parts: &[SolidMesh]) -> bool { + parts.iter().any(|p| { + p.graphics + .as_ref() + .is_some_and(|g| texture_frame(g).is_some() && matches!(vectorcraft_render::effects::mesh_graphics_art(doc, NodeId(0), g), Ok(Some(_)))) + }) +} + +/// The part of the art's plane a picture of `g` covers: the bounds of its corners' art points, when +/// they span an area. +fn texture_frame(g: &MeshGraphics) -> Option { + g.art_bounds().filter(|r| r.width() > 1e-9 && r.height() > 1e-9 && r.width().is_finite() && r.height().is_finite()) +} + +/// A picture [`textures`] drew: the part, the bounds and the PNG with its opacity map. +type Drawn<'a> = (&'a SolidMesh, Rect, Option); + +/// Do `a` and `b` draw the same graphics on their face? +fn same_graphics(a: &MeshGraphics, b: &MeshGraphics) -> bool { + a.face == b.face && a.center == b.center && a.graphics == b.graphics && a.opacity == b.opacity && a.object == b.object +} + +/// `art` drawn over `color` as a PNG of `w` × `h` pixels whose top left is `frame`'s top left, at +/// `scale` pixels a point, with a grayscale PNG of its alpha when some of it is not opaque. As on +/// the canvas, the art is drawn at `face` (the opacity of the face's fill or stroke), the color at +/// its own opacity without `object`'s, and `object` (the object's opacity) applies to the whole +/// picture. +fn picture( + doc: &Document, + renderer: &mut vectorcraft_render::Renderer, + (color, face, object): ([f32; 4], f32, f32), + mut art: Node, + (frame, scale): (Rect, f64), + (w, h): (u32, u32), +) -> Result { + // The color reaches two pixels past the frame, so the picture's edge pixels are covered. + let reach = 2.0 / scale; + let back = Rect::new(frame.x0 - reach, frame.y0 - reach, frame.x0 + f64::from(w) / scale + reach, frame.y0 + f64::from(h) / scale + reach); + let fill = Paint::solid(Color::rgb(color[0], color[1], color[2])); + let mut ground = Node::path(NodeId(0), vectorcraft_geom::shapes::rectangle(back), Appearance::basic(fill, Paint::None, 0.0)); + let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; + let object = unit(object); + ground.opacity = if object > 0.0 { unit(color[3] / object) } else { 0.0 }; + art.opacity *= unit(face); + let mut group = Node::group(NodeId(0), vec![Arc::new(ground), Arc::new(art)]); + group.opacity = object; + let group = Arc::new(group); + let (pw, ph) = (u16::try_from(w).map_err(|_| "texture too large")?, u16::try_from(h).map_err(|_| "texture too large")?); + let view = Affine::scale(scale) * Affine::translate((-frame.x0, -frame.y0)); + let drawn = renderer.render_node(doc, &group, pw, ph, view).ok_or_else(|| "the graphics could not be drawn".to_string())?; + let alpha: Vec = drawn.pixels.iter().skip(3).step_by(4).copied().collect(); + let opacity = if alpha.iter().all(|a| *a == 255) { + None + } else { + let gray = image::GrayImage::from_raw(w, h, alpha).ok_or("the texture's opacity could not be drawn")?; + let mut png = vec![]; + gray.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| format!("PNG encoding failed: {e}"))?; + Some(Arc::new(png)) + }; + Ok((Arc::new(drawn.to_png()?), opacity)) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 7c467fafad..876140fce7 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -7,7 +7,7 @@ use super::*; fn square(color: [f32; 4]) -> SolidMesh { let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]]; let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] }; - SolidMesh { mesh, color } + SolidMesh::plain(mesh, color) } const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; @@ -18,9 +18,14 @@ fn text(files: &[(String, Vec)], name: &str) -> String { String::from_utf8(bytes.clone()).unwrap() } +/// [`mesh_files`] without textures. +fn plain_files(stem: &str, format: &str, parts: &[SolidMesh]) -> Result)>, String> { + mesh_files(stem, format, parts, &[]) +} + #[test] fn obj_numbers_corners_across_solids_and_names_its_materials() { - let files = mesh_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); + let files = plain_files("Box", "obj", &[square(RED), square(BLUE), square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = text(&files, "Box.obj"); assert!(obj.starts_with("mtllib Box.mtl\no Box\n")); @@ -36,7 +41,7 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() { #[test] fn gltf_holds_its_buffer_and_every_accessor_fits_it() { - let files = mesh_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); + let files = plain_files("Box", "gltf", &[square(RED), square(BLUE)]).unwrap(); let g: Value = serde_json::from_str(&text(&files, "Box.gltf")).unwrap(); assert_eq!(g["asset"]["version"], "2.0"); let uri = g["buffers"][0]["uri"].as_str().unwrap(); @@ -59,11 +64,13 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() { assert_eq!(g["materials"][1]["alphaMode"], "BLEND"); assert!(g["materials"][0].get("alphaMode").is_none()); assert_eq!(g["materials"][0]["doubleSided"], true); + // Without graphics there are no textures. + assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none()); } #[test] fn usda_is_y_up_in_points_with_a_material_for_each_color() { - let files = mesh_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); + let files = plain_files("My Box", "usda", &[square(RED), square([0.5, 0.5, 0.5, 1.0])]).unwrap(); let u = text(&files, "My Box.usda"); assert!(u.starts_with("#usda 1.0\n")); assert!(u.contains("defaultPrim = \"My_Box\"") && u.contains("upAxis = \"Y\"") && u.contains("def Xform \"My_Box\""), "{u}"); @@ -75,11 +82,12 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() { // sRGB 0.5 is about 0.214 linear. assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}"); assert_eq!(u.matches('{').count(), u.matches('}').count()); + assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture")); } #[test] fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { - let files = mesh_files("Box", "usdz", &[square(RED)]).unwrap(); + let files = plain_files("Box", "usdz", &[square(RED)]).unwrap(); let (name, zip) = &files[0]; assert_eq!(name, "Box.usdz"); // The local header: 30 bytes, the name, then the extra field. @@ -88,7 +96,7 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { assert_eq!(u16_at(8), 0, "stored, not deflated"); let start = 30 + u16_at(26) + u16_at(28); assert_eq!(start % 64, 0); - let layer = mesh_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; + let layer = plain_files("Box", "usda", &[square(RED)]).unwrap().remove(0).1; assert_eq!(&zip[start..start + layer.len()], layer.as_slice()); let archive = super::super::zip::Archive::open(zip, 8).unwrap(); assert_eq!(archive.read("Box.usda", usize::MAX).unwrap(), Some(layer)); @@ -96,11 +104,11 @@ fn usdz_stores_the_layer_uncompressed_on_a_64_byte_boundary() { #[test] fn an_obj_names_its_mtl_file_without_spaces_or_comment_marks() { - let files = mesh_files("Box #1", "obj", &[square(RED)]).unwrap(); + let files = plain_files("Box #1", "obj", &[square(RED)]).unwrap(); assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box__1.obj", "Box__1.mtl"]); assert!(text(&files, "Box__1.obj").starts_with("mtllib Box__1.mtl\n")); - assert_eq!(mesh_file_names("Box #1", "obj").unwrap(), ["Box__1.obj", "Box__1.mtl"]); - assert_eq!(mesh_file_names("Box #1", "usda").unwrap(), ["Box #1.usda"]); + assert_eq!(mesh_file_names("Box #1", "obj", &[]).unwrap(), ["Box__1.obj", "Box__1.mtl"]); + assert_eq!(mesh_file_names("Box #1", "usda", &[]).unwrap(), ["Box #1.usda"]); } #[test] @@ -108,17 +116,17 @@ fn obj_and_usda_keep_coordinates_a_32_bit_float_would_merge() { let mut part = square(RED); part.mesh.positions[0] = [20_000_000.0, 0.0, 0.0]; part.mesh.positions[1] = [20_000_001.0, 0.0, 0.0]; - let obj = text(&mesh_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); + let obj = text(&plain_files("Box", "obj", std::slice::from_ref(&part)).unwrap(), "Box.obj"); assert!(obj.contains("v 20000000 0 0\nv 20000001 0 0\n"), "{obj}"); - let usda = text(&mesh_files("Box", "usda", &[part]).unwrap(), "Box.usda"); + let usda = text(&plain_files("Box", "usda", &[part]).unwrap(), "Box.usda"); assert!(usda.contains("(20000001, 0, 0)")); } #[test] fn an_unknown_format_is_refused() { - assert!(mesh_files("Box", "fbx", &[square(RED)]).is_err()); - assert!(mesh_file_names("Box", "").is_err()); - assert_eq!(mesh_file_names("Box", "obj").unwrap(), ["Box.obj", "Box.mtl"]); + assert!(plain_files("Box", "fbx", &[square(RED)]).is_err()); + assert!(mesh_file_names("Box", "", &[]).is_err()); + assert_eq!(mesh_file_names("Box", "obj", &[]).unwrap(), ["Box.obj", "Box.mtl"]); } #[test] @@ -128,3 +136,114 @@ fn prim_names_are_usd_identifiers() { assert_eq!(prim_name(""), "_"); assert_eq!(prim_name("é/x"), "__x"); } + +/// A red square, then a blue one whose corners show picture `png` (u to the right, v down). +fn textured(png: &[u8]) -> (Vec, Vec>) { + let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]; + let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv }; + (vec![square(RED), square(BLUE)], vec![None, Some(texture)]) +} + +#[test] +fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() { + let png = b"\x89PNG picture".to_vec(); + let (parts, pictures) = textured(&png); + // OBJ: vt runs up from the picture's bottom, the textured faces name it, and map_Kd the PNG + // written beside it, with its name in one word. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]); + assert_eq!(files[2].1, png); + let obj = text(&files, "My_Box.obj"); + assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]); + assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12")); + assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates"); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}"); + assert_eq!(mtl.matches("map_Kd").count(), 1); + // glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI. + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let prims = g["meshes"][0]["primitives"].as_array().unwrap(); + assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none()); + let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize]; + assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126))); + let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize]; + let data = vectorcraft_format::base64_decode(g["buffers"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + let at = view["byteOffset"].as_u64().unwrap() as usize; + let first: Vec = (0..2).map(|k| f32::from_le_bytes(data[at + 4 * k..at + 4 * k + 4].try_into().unwrap())).collect(); + assert_eq!(first, [0.0, 1.0]); + let material = &g["materials"][prims[1]["material"].as_u64().unwrap() as usize]; + assert_eq!(material["pbrMetallicRoughness"]["baseColorTexture"]["index"], 0); + assert_eq!(material["pbrMetallicRoughness"]["baseColorFactor"], serde_json::json!([1.0, 1.0, 1.0, 1.0])); + assert_eq!(g["textures"][0]["source"], 0); + assert_eq!(g["samplers"][0]["wrapS"], 33071); + let image = g["images"][0]["uri"].as_str().unwrap().strip_prefix("data:image/png;base64,").unwrap(); + assert_eq!(vectorcraft_format::base64_decode(image).unwrap(), png); + // USDA: st up from the bottom, read by a primvar reader into a UV texture of the PNG beside it. + let files = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.usda", "Box-texture-1.png"]); + let u = text(&files, "Box.usda"); + assert_eq!(u.matches("primvars:st").count(), 1); + assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}"); + assert!(u.contains("color3f inputs:diffuseColor.connect = "), "{u}"); + assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\"")); + assert!(u.contains("float2 inputs:st.connect = ")); + assert!(u.contains("string inputs:varname = \"st\"")); + assert_eq!(u.matches('{').count(), u.matches('}').count()); + // USDZ: the layer first, then the picture, each on a 64-byte boundary. + let zip = mesh_files("Box", "usdz", &parts, &pictures).unwrap().remove(0).1; + let archive = super::super::zip::Archive::open(&zip, 8).unwrap(); + assert_eq!(archive.read("Box.usda", usize::MAX).unwrap().map(String::from_utf8), Some(Ok(u))); + assert_eq!(archive.read("Box-texture-1.png", usize::MAX).unwrap(), Some(png.clone())); + let u16_at = |at: usize| u16::from_le_bytes([zip[at], zip[at + 1]]) as usize; + let u32_at = |at: usize| u32::from_le_bytes([zip[at], zip[at + 1], zip[at + 2], zip[at + 3]]) as usize; + let first = 30 + u16_at(26) + u16_at(28); + let second = first + u32_at(18); + assert_eq!(&zip[second..second + 4], &[0x50, 0x4b, 0x03, 0x04], "the picture comes second"); + let data = second + 30 + u16_at(second + 26) + u16_at(second + 28); + assert_eq!((first % 64, data % 64), (0, 0)); + assert_eq!(&zip[data..data + png.len()], png.as_slice()); +} + +#[test] +fn a_textured_face_that_is_not_opaque_takes_its_opacity_from_the_picture() { + let (parts, mut pictures) = textured(b"picture"); + if let Some(t) = pictures[1].as_mut() { + t.opacity = Some(Arc::new(b"gray".to_vec())); + } + // OBJ: the opacity map, written after its texture, is the MTL's map_d. + let files = mesh_files("My Box", "obj", &parts, &pictures).unwrap(); + let names: Vec<&str> = files.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png", "My_Box-texture-1-opacity.png"]); + assert_eq!(files[3].1, b"gray"); + assert_eq!(mesh_file_names("My Box", "obj", &image_maps(&pictures)).unwrap(), names); + let mtl = text(&files, "My_Box.mtl"); + assert!(mtl.contains("d 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\nmap_d -clamp on My_Box-texture-1-opacity.png\n"), "{mtl}"); + let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap(); + let material = &g["materials"][1]; + assert_eq!((material["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64(), material["alphaMode"].as_str()), (Some(1.0), Some("BLEND"))); + let usda = mesh_files("Box", "usda", &parts, &pictures).unwrap(); + assert_eq!(usda.len(), 2, "USD reads the opacity from the texture's alpha"); + let u = text(&usda, "Box.usda"); + assert!(u.contains("float inputs:opacity.connect = ") && u.contains("float outputs:a"), "{u}"); + // An opaque textured face reads no opacity from its picture. + let (_, plain) = textured(b"picture"); + let opaque = vec![square(RED), square([0.0, 0.0, 1.0, 1.0])]; + let u = text(&mesh_files("Box", "usda", &opaque, &plain).unwrap(), "Box.usda"); + assert!(!u.contains("outputs:a") && u.contains("float inputs:opacity = 1"), "{u}"); + let mtl = text(&mesh_files("Box", "obj", &opaque, &plain).unwrap(), "Box.mtl"); + assert!(!mtl.contains("map_d") && mtl.contains("Kd 1 1 1\nd 1\n"), "{mtl}"); +} + +#[test] +fn parts_sharing_a_picture_write_it_once() { + let (mut parts, mut pictures) = textured(b"one"); + parts.push(square(BLUE)); + pictures.push(pictures[1].clone()); + assert_eq!(image_maps(&pictures), [false]); + let files = mesh_files("Box", "obj", &parts, &pictures).unwrap(); + assert_eq!(files.len(), 3); + assert_eq!(text(&files, "Box.mtl").matches("newmtl").count(), 2, "the blue parts share the textured material"); + assert_eq!(mesh_file_names("Box", "usda", &[false, true]).unwrap(), ["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]); + assert_eq!(mesh_file_names("A @b", "gltf", &[false, false]).unwrap(), ["A @b.gltf"]); + assert_eq!(texture_name("A @b#c", 0), "A__b_c-texture-1.png"); +} diff --git a/crates/engine/src/cmd/fileio/psdread.rs b/crates/engine/src/cmd/fileio/psdread.rs index 8571a19e4e..0b421e6c90 100644 --- a/crates/engine/src/cmd/fileio/psdread.rs +++ b/crates/engine/src/cmd/fileio/psdread.rs @@ -500,6 +500,48 @@ pub(super) fn to_rgb(h: &Header<'_>, v: impl Fn(usize) -> f32, cmyk: &impl Fn([f } } +/// An opaque CMYK composite as its original 8- or 16-bit ink samples. Other modes, +/// composites with transparency, and images beyond the native CMYK pixel or allocation limit return `None`. +pub(super) fn decode_cmyk(bytes: &[u8], max_alloc: u64) -> Result, String> { + use craft_image_codecs::{ChannelLayout, Image, SampleType}; + let mut r = Reader::new(bytes); + let h = header(&mut r)?; + if h.mode != Mode::Cmyk || (h.channels > 4 && merged_alpha(h.layers, h.psb)) { + return Ok(None); + } + let pixels = u64::from(h.width) * u64::from(h.height); + if pixels > vectorcraft_doc::cmyk::MAX_CMYK_PIXELS { + return Ok(None); + } + let sample_bytes = usize::from(h.depth / 8); + let samples = pixels * 4 * sample_bytes as u64; + let icc = resources(h.resources, false) + .find(|(id, _, _)| *id == 1039) + .map(|(_, _, data)| data) + .filter(|data| data.len() <= 16 << 20 && vectorcraft_doc::cmyk::icc_color_space(data) == Some(*b"CMYK")); + if samples.saturating_mul(2).saturating_add(icc.map_or(0, |p| p.len() as u64)) > max_alloc { + return Ok(None); + } + let count = pixels as usize; + let data = channel_data(r.rest(), &h, 4, row_bytes(h.width as usize, h.depth))?; + let mut out = Vec::with_capacity(samples as usize); + for i in 0..count { + for channel in 0..4 { + let at = (channel * count + i) * sample_bytes; + if h.depth == 8 { + out.push(255 - data.get(at).copied().ok_or(TRUNCATED)?); + } else { + let pair = data.get(at..at + 2).ok_or(TRUNCATED)?.try_into().map_err(|_| TRUNCATED)?; + out.extend((65535 - u16::from_be_bytes(pair)).to_ne_bytes()); + } + } + } + let sample = if h.depth == 16 { SampleType::U16 } else { SampleType::U8 }; + let mut image = Image::from_raw(h.width, h.height, ChannelLayout::Cmyk, sample, out).map_err(|e| e.to_string())?; + image.icc = icc.map(<[u8]>::to_vec); + Ok(Some(image)) +} + /// A Photoshop document's merged image as straight RGBA. CMYK converts through `cmyk` (ink /// amounts 0..1 → sRGB). Fails, without allocating, when the image would need more than /// `max_alloc` bytes. diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index ac728c8cb9..249a3f320c 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -97,6 +97,132 @@ fn every_colour_mode_and_depth_reads() { assert_eq!(pixels(&psd(1, 1, (1, 1), 8, 8, &[0; 40], &[], &[], &raw(&[&[64]]))), [[64, 64, 64, 255]]); } +#[test] +fn cmyk_psd_place_keeps_the_native_ink_samples() { + let f = psd(1, 4, (2, 1), 8, 4, &[], &[], &[], &raw(&[&[191, 255], &[127, 0], &[63, 127], &[223, 0]])); + let p = json!({"name": "inks.psd", "dataBase64": vectorcraft_format::base64_encode(&f)}); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 40, "height": 20})).unwrap(); + let info = s.execute("file.place.info", &p).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + let placed = s.execute("file.place", &p).unwrap(); + let id = NodeId(placed["ids"][0].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(id).unwrap().kind else { panic!("placed PSD is an image") }; + let blob = d.images.get(&im.key).unwrap(); + assert!(blob.is_cmyk()); + assert_eq!(blob.cmyk().unwrap().data, [64, 128, 192, 32, 0, 255, 128, 255]); +} + +#[test] +fn cmyk_psd_native_budget_keeps_the_rgba_fallback_available() { + let bytes = psd(1, 4, (2, 1), 16, 4, &[], &[], &[], &raw(&[&[0xff; 4], &[0xff; 4], &[0xff; 4], &[0; 4]])); + assert!(super::psdread::decode_cmyk(&bytes, 24).unwrap().is_none()); + assert_eq!(decode(&bytes, 24, naive).unwrap().into_raw(), [0, 0, 0, 255, 0, 0, 0, 255]); + assert!(decode(&bytes, 1, naive).is_err()); +} + +#[test] +fn cmyk_psd_depth_and_compression_preserve_exact_samples() { + for version in [1, 2] { + for depth in [8, 16] { + let values = if depth == 8 { [191u16, 127, 63, 223] } else { [0xcdef, 0x89ab, 0x4567, 0x0123] }; + let planes: Vec> = values.iter().map(|v| if depth == 8 { vec![*v as u8] } else { v.to_be_bytes().to_vec() }).collect(); + let uncompressed = planes.concat(); + for method in 0..=3u16 { + let mut data = method.to_be_bytes().to_vec(); + match method { + 0 => data.extend(&uncompressed), + 1 => { + for p in &planes { + let count = (p.len() + 1) as u32; + if version == 2 { data.extend(count.to_be_bytes()) } else { data.extend((count as u16).to_be_bytes()) } + } + for p in &planes { + data.push((p.len() - 1) as u8); + data.extend(p); + } + } + _ => { + // One sample per row has the same bytes with or without prediction. + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut z, &uncompressed).unwrap(); + data.extend(z.finish().unwrap()); + } + } + let bytes = psd(version, 4, (1, 1), depth, 4, &[], &[], &[], &data); + let img = raster_image(&bytes).unwrap(); + assert!(img.blob.is_cmyk(), "version {version}, depth {depth}, compression {method}"); + assert_eq!(img.blob.is_cmyk16(), depth == 16); + let decoded = craft_image_codecs::decode(&img.blob.bytes).unwrap(); + let expected: Vec = + values.iter().flat_map(|v| if depth == 8 { vec![255 - *v as u8] } else { (65535 - v).to_ne_bytes().to_vec() }).collect(); + assert_eq!(decoded.data(), expected); + assert!(super::psdread::decode_cmyk(&bytes, 1).unwrap().is_none()); + assert!(super::psdread::decode_cmyk(&bytes[..bytes.len() - data.len() + 2], 1 << 30).is_err()); + } + } + } + let planes: [&[u8]; 5] = [&[255], &[255], &[255], &[255], &[128]]; + let saved = psd(1, 5, (1, 1), 8, 4, &[], &[], &[], &raw(&planes)); + assert!(raster_image(&saved).unwrap().blob.is_cmyk(), "a saved selection is not transparency"); + let alpha = psd(1, 5, (1, 1), 8, 4, &[], &[], &layer_count(-1, false), &raw(&planes)); + let img = raster_image(&alpha).unwrap(); + assert!(!img.blob.is_cmyk()); + assert_eq!(craft_image_codecs::decode(&img.blob.bytes).unwrap().to_rgba8()[3], 128); +} + +#[test] +fn cmyk_psd_links_keep_inks_profile_resolution_and_clipping() { + let profile = vectorcraft_color::cms::icc_bytes(vectorcraft_color::cms::GENERIC_CMYK).unwrap(); + let mut res = Vec::new(); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + res.extend((144u32 << 16).to_be_bytes()); + res.extend([0, 1, 0, 1]); + let make = |clip: &[u8], ink: u8| { + let resources = [resource(1039, b"", &profile), resource(1005, b"", &res), clip.to_vec()].concat(); + psd(1, 4, (2, 1), 8, 4, &[], &resources, &[], &raw(&[&[255 - ink; 2], &[127; 2], &[63; 2], &[223; 2]])) + }; + let dir = vectorcraft_testkit::TempDir::new("psd-cmyk-links"); + let cut = write_file(&dir, "cut.psd", &make(&triangle_resources(), 64)); + let square = write_file(&dir, "square.psd", &make(&square_resources(), 96)); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 20, "height": 10, "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.execute("file.place.info", &json!({"path": cut})).unwrap()["colorMode"], "CMYK"); + let r = s.execute("file.place", &json!({"path": cut, "at": [0.5, 0.25]})).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = r["image"].as_u64().unwrap(); + assert_eq!(r["width"], 1.0); + assert_eq!(r["height"], 0.5); + let check = |s: &mut Session, ink, linked| { + let info = s.execute("links.info", &json!({"id": id})).unwrap(); + assert_eq!(info["colorMode"], "CMYK"); + assert_eq!(info["linked"], linked); + assert_eq!(info["ppi"], json!([144.0, 144.0])); + let d = &s.doc().unwrap().doc; + let NodeKind::Image(im) = &d.node(NodeId(id)).unwrap().kind else { panic!("placed image") }; + let blob = d.images.get(&im.key).unwrap(); + assert_eq!(blob.cmyk().unwrap().data, [ink, 128, 192, 32, ink, 128, 192, 32]); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(profile.as_ref())); + assert_eq!( + super::load::image_clip(blob), + Some(clipping_path(&make(&if ink == 64 { triangle_resources() } else { square_resources() }, ink)).unwrap()) + ); + }; + check(&mut s, 64, true); + let triangle = clip_group(&s.doc().unwrap().doc, group); + s.execute("links.relink", &json!({"ids": [id], "path": square})).unwrap(); + check(&mut s, 96, true); + assert_ne!(clip_group(&s.doc().unwrap().doc, group).0, triangle.0); + std::fs::write(&square, make(&triangle_resources(), 64)).unwrap(); + s.execute("links.update", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, true); + assert_eq!(clip_group(&s.doc().unwrap().doc, group), triangle); + s.execute("links.embed", &json!({"ids": [id]})).unwrap(); + check(&mut s, 64, false); +} + #[test] fn transparency_comes_back_straight_and_extra_channels_without_it_stay_out() { // Half-transparent red, stored on white: (255, 127, 127) with alpha 128. diff --git a/crates/engine/src/cmd/fileio/tests_svgenc.rs b/crates/engine/src/cmd/fileio/tests_svgenc.rs index 7884c1e86b..944f373474 100644 --- a/crates/engine/src/cmd/fileio/tests_svgenc.rs +++ b/crates/engine/src/cmd/fileio/tests_svgenc.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::json; -use vectorcraft_doc::Document; +use vectorcraft_doc::{Document, Node, NodeKind}; use super::*; @@ -212,6 +212,44 @@ fn a_chosen_artboard_s_svg_keeps_nested_brush_art_but_not_unpainted_or_clipped_a assert!(kept.node(compounds[1]).is_some(), "a compound path that is brushed itself"); } +/// The art over an artboard, among 300 instances with drop shadows and 2,000 symbols, is found +/// reading the symbol list once, and keeps the instances over it. +#[test] +fn art_over_an_artboard_reads_the_symbol_list_once() { + let mut d = Document::new(100.0, 100.0); + let square = |d: &mut Document, side: f64| { + let r = vectorcraft_geom::Rect::new(-side, -side, side, side); + let ap = + vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), vectorcraft_color::Paint::None, 0.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), ap)) + }; + for i in 0..2000 { + let art = square(&mut d, 0.5); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art }); + } + let art = square(&mut d, 2.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art }); + let layer = d.layers[0].id; + // Twenty rows of 15: the first ten over the artboard, the rest below it. + let ids: Vec<_> = (0..300) + .map(|i| { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 15) * 6.0 + 5.0, f64::from(i / 15) * 10.0 + 5.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(layer), usize::MAX, n).unwrap() + }) + .collect(); + let before = vectorcraft_doc::symbols_read(); + let kept = export::art_over(&d, d.artboards[0].rect, &mut vectorcraft_render::Renderer::new()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + assert_eq!(ids.iter().filter(|id| kept.node(**id).is_some()).count(), 150); +} + /// #3544: an SVG of one artboard on its own (an `artboard` or `range`, Export for Screens, an asset) /// has the artboard's (or asset's) name as ``; Save's SVG and Export for Screens' Full /// Document keep the document's. diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs index f98386bcf1..45689adc17 100644 --- a/crates/engine/src/cmd/fonts.rs +++ b/crates/engine/src/cmd/fonts.rs @@ -247,10 +247,11 @@ impl Resources { fn expand(&mut self, d: &Document) { let mut symbols: Vec<String> = self.symbols.iter().cloned().collect(); let mut patterns: Vec<String> = self.patterns.iter().cloned().collect(); + let boxes = d.symbol_boxes(); while !symbols.is_empty() || !patterns.is_empty() { let mut more = Resources::default(); for name in symbols.drain(..) { - if let Some(sym) = d.symbols.iter().find(|sym| sym.name == name) { + if let Some(sym) = boxes.symbol(&name) { more.add(&sym.art); } } @@ -511,7 +512,7 @@ pub(super) fn art_fonts(d: &Document, art: &[Node]) -> BTreeSet<UsedFont> { /// art of a placed document (`d` as [`Document::with_placed_art`] gives it, for that art's /// resources). pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) -> (BTreeSet<UsedFont>, BTreeSet<NodeId>) { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, Some(areas)); } @@ -523,7 +524,7 @@ pub(super) fn printed_type(d: &Document, layers: &[Arc<Node>], areas: &[Rect]) - /// found as [`printed_type`] finds them for Print: visible objects of the document that aren't on /// a template layer. pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: Option<&[Rect]>) -> Option<String> { - let mut walk = Printed { d, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() }; + let mut walk = Printed::new(d); for l in layers { walk.node(l, areas); } @@ -534,6 +535,9 @@ pub(super) fn export_overflow_warning(d: &Document, layers: &[Arc<Node>], areas: /// The walk of [`printed_type`]. struct Printed<'a> { d: &'a Document, + /// `d`'s symbols, found by name. Each object is measured in boxes of its own made from these + /// ([`vectorcraft_doc::SymbolBoxes::unmeasured`]). + boxes: vectorcraft_doc::SymbolBoxes<'a>, /// Whether the walk is among the objects of the document, not in art drawn for one. own: bool, fonts: BTreeSet<UsedFont>, @@ -544,7 +548,13 @@ struct Printed<'a> { patterns: BTreeSet<String>, } -impl Printed<'_> { +impl<'a> Printed<'a> { + /// A walk of `d` among its own objects, nothing found yet. + fn new(d: &'a Document) -> Self { + let boxes = d.symbol_boxes(); + Self { d, boxes, own: true, fonts: BTreeSet::new(), overflow: BTreeSet::new(), symbols: BTreeSet::new(), patterns: BTreeSet::new() } + } + /// Adds the fonts of `n` and its descendants that print, and the ids of those that don't fit /// while [`Printed::own`] is set: those whose bounds meet one of `areas`, or with `None` (in the /// art of a symbol, opacity mask, pattern or placed document, in brush pieces, or in a live @@ -625,7 +635,7 @@ impl Printed<'_> { let clipped = match (clip, areas) { (false, _) => None, (true, Some(a)) => Some(self.clip(n, a)), - (true, None) => vectorcraft_render::painted_bounds(self.d, n).map(|c| vec![c]), + (true, None) => vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n).map(|c| vec![c]), }; for c in children { self.node(c, clipped.as_deref().or(areas)); @@ -641,9 +651,8 @@ impl Printed<'_> { /// Adds the fonts of symbol `name`'s art, the first time it is shown. fn symbol(&mut self, name: &str) { - let d = self.d; if self.symbols.insert(name.to_string()) - && let Some(s) = d.symbols.iter().find(|s| s.name == name) + && let Some(s) = self.boxes.symbol(name) { self.art(&s.art); } @@ -660,12 +669,13 @@ impl Printed<'_> { /// Whether what `n` paints, its effects applied, meets one of `areas`. fn meets(&self, n: &Node, areas: &[Rect]) -> bool { - vectorcraft_render::painted_bounds(self.d, n).is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) + vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) + .is_some_and(|b| areas.iter().any(|r| b.intersect(*r).area() > 0.0 || r.contains_rect(b))) } /// The parts of `areas` inside the bounds of clip group `n` (its clipping path's). fn clip(&self, n: &Node, areas: &[Rect]) -> Vec<Rect> { - let Some(c) = vectorcraft_render::painted_bounds(self.d, n) else { return areas.to_vec() }; + let Some(c) = vectorcraft_render::painted_bounds_with(&self.boxes.unmeasured(), n) else { return areas.to_vec() }; areas.iter().filter(|r| c.intersect(**r).area() > 0.0 || r.contains_rect(c)).map(|r| r.intersect(c)).collect() } } @@ -2378,4 +2388,40 @@ mod dirty_tests { s.execute("edit.undo", &json!({})).unwrap(); assert!(!s.doc().unwrap().is_dirty(), "back to the saved state"); } + + /// The walk Print and the exports make over 300 instances with drop shadows, among 2,000 + /// symbols, reads the symbol list once to find their symbols. + #[test] + fn printed_type_reads_the_symbol_list_once() { + let mut d = Document::new(200.0, 200.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + let art = Node::path( + d.alloc_id(), + vectorcraft_geom::shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), + vectorcraft_doc::Appearance::basic(Paint::solid(vectorcraft_color::Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(art) }); + let l = d.layers[0].id; + for i in 0..300 { + let xf = vectorcraft_geom::Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 10.0)); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + printed_type(&d, &d.layers, &[Rect::new(0.0, 0.0, 100.0, 100.0)]); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); + } } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 3c517c006a..81d1c72497 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -713,12 +713,12 @@ type FileClip = (PathData, FillRule); /// The clipping path the file of image content `blob` draws it through, in its pixel space, as it /// was kept when the file was read: a DCS file's ([`ImageBlob::separated_clip`]) or a PSD or PSB -/// file's ([`fileio::png_clip`]). +/// file's ([`fileio::image_clip`]). fn file_clip(blob: &ImageBlob) -> Option<FileClip> { if let Some(path) = blob.separated_clip() { return Some((path, FillRule::NonZero)); } - (blob.mime == "image/png").then(|| fileio::png_clip(&blob.bytes)).flatten().map(|path| (path, FillRule::EvenOdd)) + fileio::image_clip(blob).map(|path| (path, FillRule::EvenOdd)) } /// What happens to the clip of an object a link update remakes. diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index d925ac34c9..17568d50b9 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -357,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { && prev != isolation { crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, prev, Some(isolation))?; let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, prev); } @@ -369,6 +370,19 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> { ok() } +/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn +/// in the Live Paint group isolation put new art in to that group, as `livePaint.merge` does, in one +/// undo step ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]), unless `next` is that group or is +/// inside it; → the group when paths were added. +fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> { + let d = &s.doc()?.doc; + let Some(g) = crate::cmd::buildcmds::isolated_live_paint(d, isolated) else { return Ok(None) }; + if next.is_some_and(|n| d.ancestry(n).is_some_and(|a| a.contains(&g))) { + return Ok(None); + } + Ok(crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)?.then_some(g)) +} + pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's @@ -378,10 +392,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { && let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer))) { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner); let st = s.doc_mut()?; crate::cmd::distortcmds::finish_edit_text(st, inner); st.isolation = Some(layer); - st.selection.set([inner]); + st.selection.set([left]); st.revision += 1; return ok(); } @@ -396,6 +411,8 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { }; if let Some(leave_mode) = leave_mode { if let Some(i) = st.isolation { + crate::cmd::settle_interaction(s)?; + add_drawn_live_paint(s, i, None)?; crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i); } leave_mode(s, p)?; @@ -405,10 +422,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { let prev = s.active().and_then(|d| d.isolation); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; + let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); let st = s.doc_mut()?; st.isolation = None; crate::cmd::distortcmds::finish_edit_text(st, i); - let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i); + let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); // A guide path isolated while Lock Guides is on isn't selected (#1534). crate::deselect_hidden(&menu, &st.doc, &mut st.selection); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 7f620b17ff..0c638ceb5e 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -245,7 +245,15 @@ pub fn specs() -> Vec<CommandSpec> { crate::cmd::maskedit::outside_mask_editing, isolate ), - cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation), + cmd!( + "object.exitIsolation", + "Exit Isolation Mode", + [], + None, + "{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + has_doc, + exit_isolation + ), cmd!( "object.setProps", "Object Properties", diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index a155245fbc..aa83466693 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -1276,7 +1276,7 @@ fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool { /// The frames of the story that type object `id` belongs to (its thread in thread order, else `id` /// alone), each with the length of its text in bytes. -fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { +pub(crate) fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> { let Some(st) = s.active() else { return vec![] }; let d = &st.doc; let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]); @@ -1314,6 +1314,16 @@ fn move_editing_selection( at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>() }; let (anchor, caret) = (story(anchor), story(caret)); + select_story_range(s, id, anchor, caret) +} + +/// The Type tool's anchor and caret become story positions `anchor` and `caret` of the story that +/// frame `id` belongs to, as its frames are now. The caret stays in `id` while its place is there, +/// and else goes to the frame that holds it, with the anchor in that frame; that frame becomes the +/// selection when it was not selected. +pub(crate) fn select_story_range(s: &mut Session, id: NodeId, anchor: usize, caret: usize) -> Result<()> { + let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>(); + let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n); let after = story_frames(s, id); let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret); let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) }; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 85d2f769fc..486a5633a7 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -91,7 +91,7 @@ pub fn specs() -> Vec<CommandSpec> { "Placed File Info", [], None, - "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", + "{path | name | dataBase64 (a file's path, or its name with its bytes), page?, crop?, password?, thumbnail?: px, link?: bool, dxf?: {…}, layers?, hiddenLayers?, importSlices? (all as file.place)} what file.place would place, without placing it → {name, format, width, height (pt at 100%), pixelWidth?, pixelHeight?, ppi?: [x, y], colorMode?: RGB|Grayscale|CMYK (raster images; opaque CMYK PSD/PSB merged images keep 8- or 16-bit inks within VectorCraft's 67,108,864-pixel native CMYK limit and allocation allowance; other CMYK composites use the RGB decoder's allocation limit), plates?: [ink names] (a DCS file), slices?: the user slices a PSD or PSB file would bring in, warnings, thumbnailBase64?: PNG of at most `thumbnail` (≤ 512) px on its longer side}", always, info ), diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 9079f7b892..cf0ceb82ee 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -270,7 +270,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { Ok((a.min(b), a.max(b))) } -fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { +pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "text.editRange"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; let t = text_ref(s, id)?; diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index da930d7e59..359b369a89 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -10,8 +10,8 @@ use super::object::choice; use super::threads::ThreadIndex; use super::typecmd::{area_text, block_gaps, needed_room, refresh_bounds}; use super::{ - CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, - switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, named_ids, + number_or, switch_or, targets, text_param, }; pub fn specs() -> Vec<CommandSpec> { @@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> { "Insert Character", ["Type"], None, - "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} append to the selected text objects", + "{char: \"bullet\"|\"copyright\"|\"ellipsis\"|\"paragraph\"|\"registered\"|\"section\"|\"trademark\"|\"emDash\"|\"enDash\"|\"discretionaryHyphen\"|\"nonBreakingHyphen\"|\"doubleLeftQuote\"|\"doubleRightQuote\"|\"singleLeftQuote\"|\"singleRightQuote\"|\"emSpace\"|\"enSpace\"|\"hairSpace\"|\"sixthSpace\"|\"thinSpace\"|\"nonBreakingSpace\"|\"figureSpace\"|\"punctuationSpace\"|\"thirdSpace\"|\"quarterSpace\"|\"tab\"|\"forcedLineBreak\"|\"paragraphReturn\" | text: string | code: Windows Alt+0 code (0–255 in Windows-1252, a Unicode code point above: 176 → °, 151 → —) | unicode: hex code point (\"00B0\" or \"U+00B0\"), ids?|id?: object ids (default: the selection)} insert at the Type tool's caret, replacing its selection, while it edits text and no ids are given; otherwise append to the selected text objects. forcedLineBreak is U+2028, a new line in the same paragraph; paragraphReturn is a line feed, which starts a new paragraph", has_selection, insert_char ), @@ -786,8 +786,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> { let plain = t.plain_text(); let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8); // Soft wraps → explicit breaks (replace the space before the wrap when there is one). - let mut breaks: Vec<usize> = - lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && plain.as_bytes().get(b - 1) != Some(&b'\n')).collect(); + // A line after a paragraph return or a forced line break (U+2028) already starts there. + let hard = |b: usize| plain.get(..b).is_some_and(|s| s.ends_with(['\n', '\u{2028}'])); + let mut breaks: Vec<usize> = lay.lines.iter().skip(1).map(|l| l.start).filter(|&b| b > 0 && !hard(b)).collect(); breaks.sort_unstable(); breaks.dedup(); for b in breaks.into_iter().rev() { @@ -1525,8 +1526,9 @@ pub(crate) fn special_char(name: &str) -> Option<&'static str> { "thirdSpace" => "\u{2004}", "quarterSpace" => "\u{2005}", "tab" => "\t", - // Our text model breaks lines at paragraph returns only. - "forcedLineBreak" | "paragraphReturn" => "\n", + // A line break inside the paragraph, as Shift+Enter types it. + "forcedLineBreak" => "\u{2028}", + "paragraphReturn" => "\n", _ => return None, }) } @@ -1576,6 +1578,11 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { (None, None, None, Some(u)) => unicode_char(u).ok_or_else(|| bad(C, format!("`{u}` is no Unicode character")))?.to_string(), (None, None, None, None) => return Err(bad(C, "give `char`, `text`, `code` or `unicode`")), }; + if named_ids(p)?.is_none() + && let Some(r) = insert_at_type_caret(s, &text)? + { + return Ok(r); + } let ids = texts(s, p, C)?; // When `text` is empty and every object ends with a run of text, the document and its undo // history stay as they are. @@ -1606,6 +1613,44 @@ fn insert_char(s: &mut Session, p: &Value) -> Result<Value> { Ok(ids_json(&ids)) } +/// `type.insert` while the Type tool edits text: `text` replaces the tool's selection (inserts at +/// its caret) as one undo step, and the caret goes after it. `None` when no text is being edited. +fn insert_at_type_caret(s: &mut Session, text: &str) -> Result<Option<Value>> { + let tool = s.tool_options(); + let Some(id) = tool.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let d = &s.doc()?.doc; + let Some(NodeKind::Text(t)) = d.node(id).map(|n| &n.kind) else { return Ok(None) }; + let len = vectorcraft_text::edit::runs_len(&t.runs); + let g = |k: &str| tool.get(k).and_then(Value::as_u64).map_or(len, |v| (v as usize).min(len)); + let (x, y) = (g("start"), g("end")); + let (a, b) = (x.min(y), x.max(y)); + // After Select All in threaded text the whole story is selected: the other frames' text goes + // in the same edit, as when typing replaces it. + let story: Vec<NodeId> = tool.get("story").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect(); + let clear: Vec<u64> = if a == 0 && b == len && story.contains(&id) { + let has_text = |f: &NodeId| matches!(d.node(*f).map(|n| &n.kind), Some(NodeKind::Text(o)) if !o.runs.iter().all(|r| r.text.is_empty())); + story.iter().filter(|f| **f != id && has_text(f)).map(|f| f.0).collect() + } else { + vec![] + }; + if text.is_empty() && a == b && clear.is_empty() { + return Ok(Some(ids_json(&[id]))); + } + // A typing session ends first: the insertion is a step of its own. + if tool.get("typing").and_then(Value::as_bool) == Some(true) { + s.set_tool_option("commitTyping", &Value::Bool(true)); + s.commit_interaction()?; + } + // The frame's place in the story once the edit has cleared the frames in `clear`. + let start: usize = + super::panelcmds::story_frames(s, id).iter().take_while(|(f, _)| *f != id).filter(|(f, _)| !clear.contains(&f.0)).map(|(_, n)| n).sum(); + let r = super::textedit::edit_range(s, &json!({"id": id.0, "start": a, "end": b, "insert": text, "clear": clear}))?; + let caret = r.get("caret").and_then(Value::as_u64).map_or(a + text.len(), |c| c as usize); + // Threaded text re-flows in the edit: the caret goes to the frame its place moved to. + super::panelcmds::select_story_range(s, id, start + caret, start + caret)?; + Ok(Some(ids_json(&[id]))) +} + // ---------- Find and Replace ---------- fn is_word(c: char) -> bool { diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 2d1fbd7761..d546eed793 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -246,6 +246,163 @@ fn export_3d_writes_into_a_folder_or_one_zip() { let _ = std::fs::remove_dir_all(&dir); } +/// A blue 100 × 100 square extruded straight on, with a red 10 × 20 graphic "Mark" mapped onto its +/// front at its center and onto its back 30 pt to the right (as the back is seen from behind), +/// collected as a 3D asset in `format`. +fn mapped(format: &str) -> (Session, u64) { + let mut s = session(); + let mark = run(&mut s, "path.create", json!({"d": "M300 300L310 300L310 320L300 320Z"}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "threeD.addGraphic", json!({"name": "Mark", "ids": [mark]})); + let id = run(&mut s, "path.create", json!({"d": "M100 100L200 100L200 200L100 200Z"}))["id"].as_u64().unwrap(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "params": {"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "depth": 20.0}})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "ids": [id]})); + run(&mut s, "threeD.mapGraphic", json!({"symbol": "Mark", "face": "back", "x": 30.0, "ids": [id]})); + run(&mut s, "layer.setProps", json!({"id": id, "name": "Box"})); + let asset = run(&mut s, "assets.add3D", json!({"ids": [id], "format": format}))["assets"][0].as_u64().unwrap(); + (s, asset) +} + +/// The color of pixel `(x, y)` of PNG `png`. +fn pixel(png: &[u8], x: u32, y: u32) -> [u8; 4] { + image::load_from_memory(png).unwrap().to_rgba8().get_pixel(x, y).0 +} + +fn is_red(p: [u8; 4]) -> bool { + p[0] > 200 && p[1] < 50 && p[2] < 50 && p[3] == 255 +} + +fn is_blue(p: [u8; 4]) -> bool { + p[0] < 50 && p[1] < 50 && p[2] > 200 && p[3] == 255 +} + +#[test] +fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { + for (format, names) in [ + ("usda", vec!["Box.usda", "Box-texture-1.png", "Box-texture-2.png"]), + ("usdz", vec!["Box.usdz"]), + ("gltf", vec!["Box.gltf"]), + ("obj", vec!["Box.obj", "Box.mtl", "Box-texture-1.png", "Box-texture-2.png"]), + ] { + let (mut s, _) = mapped(format); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), names, "{format}"); + } + // The front's picture: the cap's 100 pt across 128 pixels, blue with the red graphic at the + // middle; the back's: the graphic 30 pt to the right as seen from behind, which is to the left + // in the art's plane. + let (mut s, _) = mapped("usda"); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (front, back) = (&out[1].1, &out[2].1); + assert_eq!(image::load_from_memory(front).unwrap().to_rgba8().dimensions(), (128, 128)); + assert!(is_red(pixel(front, 64, 64)) && is_blue(pixel(front, 2, 2)) && is_blue(pixel(front, 64, 10))); + let at = |pt: f64| (pt * 1.28) as u32; + assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); + // The USDA's front cap shows the front picture through st, up from the picture's bottom. + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + // glTF holds both pictures, and a cap's coordinates stay inside its picture. + let (mut s, _) = mapped("gltf"); + let out = files(&run(&mut s, "assets.export3D", json!({}))); + let g: Value = serde_json::from_slice(&out[0].1).unwrap(); + assert_eq!(g["images"].as_array().map(Vec::len), Some(2)); + let png = vectorcraft_format::base64_decode(g["images"][0]["uri"].as_str().unwrap().split(',').nth(1).unwrap()).unwrap(); + assert_eq!(image::load_from_memory(&png).unwrap().to_rgba8().dimensions(), (1024, 1024), "1024 pixels by default"); +} + +#[test] +fn a_texture_takes_the_opacity_of_the_fill_and_of_the_object_as_the_canvas_draws_them() { + let half = |a: u8| (120..=135).contains(&a); + // A half-opaque fill: the face and the graphic over it are each drawn at half opacity, so the + // graphic covers three quarters. + let (mut s, asset) = mapped("usda"); + let doc = &s.active().unwrap().doc; + let id = doc.asset(asset).unwrap().nodes[0]; + let fill = doc.node(id).unwrap().appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "transparency.set", json!({"item": fill, "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > on[2] && (185..=197).contains(&on[3]), "{on:?}"); + assert!(around[2] > 200 && half(around[3]), "{around:?}"); + let usda = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(usda.contains("float inputs:opacity.connect"), "the texture's alpha is the opacity"); + // An OBJ's opacity map has the alpha as gray levels. + run(&mut s, "assets.set3DFormat", json!({"assets": [asset], "format": "obj"})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out[3].0, "Box-texture-1-opacity.png"); + let gray = image::load_from_memory(&out[3].1).unwrap().to_luma8(); + let (g_on, g_around) = (gray.get_pixel(64, 64).0[0], gray.get_pixel(2, 2).0[0]); + assert!((185..=197).contains(&g_on) && half(g_around), "{g_on} {g_around}"); + // A half-opaque object: the face and the graphic are drawn opaque, and the whole picture at + // half opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "transparency.set", json!({"ids": [id.0], "opacity": 50})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(on[0] > 200 && on[2] < 50 && half(on[3]), "{on:?}"); + assert!(around[2] > 200 && around[0] < 50 && half(around[3]), "{around:?}"); + // A gradient whose stops are clear: the face is clear, and the graphic keeps its opacity. + let (mut s, asset) = mapped("usda"); + let id = s.active().unwrap().doc.asset(asset).unwrap().nodes[0]; + run(&mut s, "select.set", json!({"ids": [id.0]})); + let clear = json!({"stops": [{"offset": 0, "color": "#0000ff", "opacity": 0}, {"offset": 1, "color": "#0000ff", "opacity": 0}]}); + run(&mut s, "paint.setFill", json!({"gradient": clear})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + let (on, around) = (pixel(&out[1].1, 64, 64), pixel(&out[1].1, 2, 2)); + assert!(is_red(on), "{on:?}"); + assert_eq!(around[3], 0, "{around:?}"); +} + +#[test] +fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() { + let (mut s, asset) = mapped("obj"); + for bad in [json!(64), json!(5000), json!(512.5), json!("512"), json!(-1)] { + assert!(s.execute("assets.export3D", &json!({"textureSize": bad})).is_err(), "{bad}"); + } + // Without its graphics the box is one plain mesh, as before. + let id = s.doc().unwrap().doc.asset(asset).unwrap().nodes[0].0; + run(&mut s, "select.set", json!({"ids": [id]})); + run(&mut s, "effect.setParams", json!({"index": 0, "params": {"graphics": []}})); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); + let obj = String::from_utf8(out[0].1.clone()).unwrap(); + assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); +} + +#[test] +fn texture_pixels_are_counted_across_one_export() { + let (s, asset) = mapped("gltf"); + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + let parts = vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap(); + let mut pixels = 0; + let made = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap(); + assert_eq!((made.iter().flatten().count(), pixels), (2, 2 * 128 * 128)); + let mut pixels = crate::cmd::fileio::MAX_TEXTURE_PIXELS - 128 * 128; + let e = crate::cmd::fileio::textures(d, &parts, 128, &mut pixels).unwrap_err(); + assert!(e.contains("textureSize"), "{e}"); +} + +#[test] +fn only_graphics_that_draw_count_as_textures() { + let parts_of = |s: &Session, asset: u64| { + let d = &s.doc().unwrap().doc; + let node = d.node(d.asset(asset).unwrap().nodes[0]).unwrap(); + vectorcraft_render::effects::three_d_meshes_in(Some(d), node).unwrap() + }; + let (mut s, asset) = mapped("obj"); + assert!(crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + // With its symbol gone the graphic draws nothing, so the export writes no texture. + run(&mut s, "symbol.delete", json!({"name": "Mark"})); + assert!(!crate::cmd::fileio::draws_textures(&s.doc().unwrap().doc, &parts_of(&s, asset))); + let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); + assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.obj", "Box.mtl"]); +} + #[test] fn three_d_assets_round_trip_through_the_native_format() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 011e76752e..8a0ba40084 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -4762,6 +4762,279 @@ fn live_paint_refuses_type_and_images_and_changes_nothing() { assert!(!vectorcraft_tools::builder::live_paint_takes(&node(&s, text_group))); } +/// A horizontal open path across [`live`]'s group at `y`, drawn with the Pen's defaults. +fn line_across(s: &mut Session, y: f64) -> NodeId { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 160, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +/// Paths drawn in an isolated Live Paint group join it when isolation mode ends: they go among its +/// sources and cut the faces they cross, which take their sources' fill, a painted face they do not +/// cross keeps its fill, and the whole addition is one undo step, which Undo takes back to the +/// drawn paths in the group and Redo makes again. +#[test] +fn live_paint_isolation_adds_drawn_paths_on_exit() { + use vectorcraft_tools::builder::{face_at, faces, sources}; + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [125, 50], "color": "#00ff00"})).unwrap(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + // Two lines from left of the group that end in its right face, so they cut only the other two. + let line = |s: &mut Session, y: f64| { + let r = s.execute("path.create", &json!({"anchors": [{"x": -10, "y": y}, {"x": 105, "y": y}]})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) + }; + let (a, b) = (line(&mut s, 30.0), line(&mut s, 70.0)); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "a path drawn in isolation goes into the group"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let d = s.doc().unwrap(); + assert_eq!(d.isolation, None); + assert_eq!(d.history.undo.len(), steps + 1, "both paths join in one undo step"); + assert_eq!(d.selection.objects, vec![g]); + let n = node(&s, g); + let src = sources(&n).unwrap(); + assert_eq!(src.children().unwrap().len(), 4); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(src.id), "{id} joined the sources"); + } + assert_eq!(faces(&n).len(), 7, "two lines cut each of the two faces they cross in three"); + assert_eq!(face_at(&n, Point::new(125.0, 50.0)).unwrap().appearance.fill_paint(), green, "the face the lines do not cross keeps its fill"); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + for y in [15.0, 85.0] { + assert_eq!(face_at(&n, Point::new(25.0, y)).unwrap().appearance.fill_paint(), red, "a new face takes its source's fill"); + } + s.execute("edit.undo", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 3); + assert_eq!(sources(&n).unwrap().children().unwrap().len(), 2); + for id in [a, b] { + assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(g), "Undo puts {id} back in the group as drawn"); + } + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 7); +} + +/// Leaving isolation mode in a Live Paint group with nothing drawn in it records no undo step and +/// leaves the document as it is. Type, and a path that is hidden, stay in the group as they are, +/// while a group of paths drawn beside them joins it. +#[test] +fn live_paint_isolation_adds_only_paths_it_takes() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc == before.0, "an exit with nothing drawn changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), before.1, "and records no undo step"); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + let hidden = line_across(&mut s, 50.0); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "type and a hidden path add nothing"); + assert_eq!(faces(&node(&s, g)).len(), 3); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group of paths joined"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.parent_of(paths), Some(sources(&n).unwrap().id)); + for id in [text, hidden] { + assert_eq!(d.parent_of(id), Some(g), "{id} stays in the group"); + assert!(d.node(id).is_some()); + } +} + +/// A group drawn in an isolated Live Paint group that holds a locked path stays in it as it is when +/// isolation mode ends, as a locked path drawn there does. +#[test] +fn live_paint_isolation_leaves_a_group_holding_a_locked_path() { + use vectorcraft_tools::builder::faces; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(b).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(g)); + assert_eq!(faces(&node(&s, g)).len(), 3); +} + +/// Type drawn in an isolated Live Paint group stays in it when Gap Options or Merge make the group's +/// faces and edges again, including type in a Live Paint group merged into another, and Release +/// puts it beside the released paths. +#[test] +fn live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release() { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type"); + let c = rect(&mut s, 120.0, 20.0, 100.0, 20.0); + s.execute("livePaint.merge", &json!({"ids": [g.0, c.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Merge keeps the type"); + let other = rect(&mut s, 300.0, 300.0, 50.0, 50.0); + let h = NodeId(s.execute("livePaint.make", &json!({"ids": [other.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": h.0})).unwrap(); + let text2 = NodeId(s.execute("text.create", &json!({"x": 310, "y": 320, "text": "Yo"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + s.execute("livePaint.merge", &json!({"ids": [g.0, h.0]})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text2), Some(g), "the type of the merged group moves with its paths"); + s.execute("livePaint.release", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for id in [text, text2] { + assert_eq!(d.parent_of(id), d.default_layer(), "Release keeps {id}"); + } +} + +/// Art drawn in an isolated Live Paint group and named like one of the group's parts is not taken +/// for one: type named "Live Paint Sources" stays in the group through Gap Options, and a group of +/// paths named "Face" joins the group when isolation mode ends. +#[test] +fn live_paint_isolation_keeps_art_named_like_its_parts() { + use vectorcraft_tools::builder::{SOURCES_NAME, faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let text = NodeId(s.execute("text.create", &json!({"x": 20, "y": 20, "text": "Hi"})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": text.0, "name": SOURCES_NAME})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": paths.0, "name": "Face"})).unwrap(); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the group named Face joined"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(text), Some(g), "Gap Options keeps the type named like the sources"); +} + +/// Type drawn in an isolated Live Paint group under the name of a face, an edge or the sources +/// group is not one of the group's parts: Gap Options, Info and Make count only the faces and edges +/// Live Paint made, and Expand keeps the type. +#[test] +fn live_paint_does_not_count_art_named_like_its_parts() { + use vectorcraft_tools::builder::{EDGE_NAME, FACE_NAME, SOURCES_NAME}; + let mut s = session(); + let g = live(&mut s); + let edges = s.execute("livePaint.info", &json!({"group": g.0})).unwrap()["edges"].as_array().unwrap().len(); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let mut texts = vec![]; + for (i, name) in [FACE_NAME, EDGE_NAME, SOURCES_NAME].into_iter().enumerate() { + let r = s.execute("text.create", &json!({"x": 20 + 20 * i, "y": 20, "text": "Hi"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + s.execute("object.setProps", &json!({"id": t.0, "name": name})).unwrap(); + texts.push(t); + } + s.execute("object.exitIsolation", &json!({})).unwrap(); + let r = s.execute("livePaint.gapOptions", &json!({"ids": [g.0], "detect": true})).unwrap(); + assert_eq!(r["faces"], 3, "Gap Options counts the faces Live Paint made"); + let info = s.execute("livePaint.info", &json!({"group": g.0})).unwrap(); + assert_eq!(info["faces"].as_array().unwrap().len(), 3); + assert_eq!(info["edges"].as_array().unwrap().len(), edges); + let r = s.execute("livePaint.make", &json!({"ids": [g.0]})).unwrap(); + assert_eq!((r["faces"].as_u64(), r["edges"].as_u64()), (Some(3), Some(edges as u64))); + s.execute("livePaint.expand", &json!({"ids": [g.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + for t in texts { + assert_eq!(d.parent_of(t), Some(g), "Expand keeps {t}"); + } +} + +/// With Real-time Drawing and Editing off, a rectangle still being drawn in a Live Paint group +/// isolated in a pattern tile is drawn first when Exit Isolation Mode leaves pattern editing, and +/// joins the group with the tile saved. +#[test] +fn live_paint_in_a_pattern_tile_adds_a_shape_still_being_drawn_on_exit() { + use vectorcraft_tools::builder::{is_live_paint, sources}; + let mut s = session(); + two(&mut s); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let g = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("rectangle", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 40.0, 40.0), v).unwrap(); + assert!(s.interaction_unapplied()); + s.execute("object.exitIsolation", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(st.doc.pattern_edit.is_none()); + let art = &st.doc.pattern("P").unwrap().art; + let n = art.iter().find(|n| is_live_paint(n)).expect("the tile holds the Live Paint group"); + assert_eq!(sources(n).unwrap().children().unwrap().len(), 3, "the rectangle joined the sources"); +} + +/// Isolating a level outside an isolated Live Paint group, as the isolation bar's back arrow does, +/// leaves the group and adds the paths drawn in it; isolating a path drawn in it does not. +#[test] +fn live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside() { + use vectorcraft_tools::builder::{faces, sources}; + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let a = line_across(&mut s, 50.0); + s.execute("object.isolate", &json!({"id": a.0})).unwrap(); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(g), "the path is still being drawn in the group"); + assert_eq!(faces(&node(&s, g)).len(), 3); + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + assert_eq!(s.doc().unwrap().isolation, Some(layer)); + let n = node(&s, g); + assert_eq!(faces(&n).len(), 6); + assert_eq!(s.doc().unwrap().doc.parent_of(a), Some(sources(&n).unwrap().id)); +} + +/// A group of paths drawn in an isolated Live Paint group and then isolated itself joins the Live +/// Paint group when isolation mode ends, or when a level outside the Live Paint group is isolated. +#[test] +fn live_paint_isolation_adds_a_drawn_group_isolated_inside_it() { + use vectorcraft_tools::builder::{faces, sources}; + for to_layer in [false, true] { + let mut s = session(); + let g = live(&mut s); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + let (a, b) = (line_across(&mut s, 30.0), line_across(&mut s, 70.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let paths = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("object.isolate", &json!({"id": paths.0})).unwrap(); + assert_eq!(faces(&node(&s, g)).len(), 3, "isolating the drawn group stays in the Live Paint group"); + if to_layer { + let layer = s.doc().unwrap().doc.parent_of(g).unwrap(); + s.execute("object.isolate", &json!({"id": layer.0})).unwrap(); + } else { + s.execute("object.exitIsolation", &json!({})).unwrap(); + } + let n = node(&s, g); + assert_eq!(faces(&n).len(), 9, "the drawn group joined (to the layer: {to_layer})"); + assert_eq!(s.doc().unwrap().doc.parent_of(paths), Some(sources(&n).unwrap().id)); + } +} + /// Give Live Paint group `g` a lock, hidden state, appearance, knockout, opacity mask and /// graphic style link, and return it as it then is. fn dress_live_group(s: &mut Session, g: NodeId) -> Node { diff --git a/crates/engine/src/tests/eyedropper.rs b/crates/engine/src/tests/eyedropper.rs index f4728f8a18..182d989662 100644 --- a/crates/engine/src/tests/eyedropper.rs +++ b/crates/engine/src/tests/eyedropper.rs @@ -615,6 +615,141 @@ fn clicking_an_image_samples_its_pixel() { assert_eq!(node(&s, dst).appearance.fill_paint().color(), Some(Color::rgb8(128, 128, 64)), "5 x 5 average of both pixels"); } +/// Gradient mesh points picked with Direct Selection or the Mesh tool take the color the +/// Eyedropper then samples from an image or from other art, each sample one undo step, and only +/// they change: the mesh's other points and its appearance stay as they were (#8090). +#[test] +fn picked_mesh_points_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let red = rect(&mut s, 100.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + assert!(colors(&s).iter().all(|c| *c == white && *c != Color::rgb8(255, 0, 0))); + let appearance = node(&s, m).appearance; + let v = ViewInfo::default(); + let pick = |s: &mut Session, tool: &str, i: usize, shift: bool| { + s.select_tool(tool, v).unwrap(); + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + let mods = Mods { shift, ..Default::default() }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + pick(&mut s, "directSelection", 0, false); + let undo = undo_len(&s); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, white, white, white], "the picked point takes the image's color"); + assert_eq!(node(&s, m).appearance, appearance, "the mesh's appearance stays"); + assert_eq!(undo_len(&s), undo + 1, "one undo step"); + // The Eyedropper keeps the picks: a Shift-click samples into the point again. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0).with_mods(Mods { shift: true, ..Default::default() }), v).unwrap(); + assert_eq!(colors(&s), [orange, white, white, white]); + assert_eq!(undo_len(&s), undo + 2); + // A sample of the color the point already has changes nothing and adds no step. + s.pointer(&PointerEvent::new(PointerKind::Down, 350.0, 50.0), v).unwrap(); + assert_eq!(undo_len(&s), undo + 2, "no step when nothing changes"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(colors(&s), [teal, white, white, white]); + // Two points picked with the Mesh tool both take a plain click's sample of other art, and the + // art keeps its fill. + pick(&mut s, "mesh", 1, false); + pick(&mut s, "mesh", 3, true); + let undo = undo_len(&s); + click(&mut s, 125.0, 35.0, Mods::default()); + let r = Color::rgb8(255, 0, 0); + assert_eq!(colors(&s), [teal, r, white, r]); + assert_eq!(undo_len(&s), undo + 1, "one undo step for every picked point"); + assert_eq!(node(&s, m).appearance, appearance); + assert_eq!(node(&s, red).appearance.fill_paint().color(), Some(r)); + // Back in the Mesh tool the two points are still picked: a fill color recolors just them. + s.select_tool("mesh", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + let b = Color::rgb8(0, 0, 255); + assert_eq!(colors(&s), [teal, b, white, b], "the picks go back to the Mesh tool"); + // Without picked points a click on an image samples into the whole selected mesh as before. + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [teal, b, white, b], "the points keep their colors"); + assert_ne!(node(&s, m).appearance, appearance); +} + +/// A Cmd-click with the Direct Selection tool the Eyedropper lends picks gradient mesh points for +/// the Eyedropper: the lent tool starts from the Eyedropper's picks, so a Shift-click adds to +/// them, and the Eyedropper samples into what the lent tool left picked (#8090). +#[test] +fn mesh_points_picked_through_the_lent_tool_take_the_eyedropper_sample() { + let mut s = session(); + // Two pixels, orange and teal, 100 pt each, at (300, 0). + let rgba = [[255u8, 128, 0, 255], [0, 128, 128, 255]].concat(); + let img = craft_image_codecs::Image::from_raw(2, 1, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, rgba).unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + s.edit("Place", |d, _| { + d.images.insert("px".into(), ImageBlob::png(png.to_vec())); + let l = d.layers[0].id; + let id = d.alloc_id(); + let xf = vectorcraft_geom::Affine::translate((300.0, 0.0)) * vectorcraft_geom::Affine::scale(100.0); + let im = ImageObject { key: "px".into(), width: 2, height: 1, xf, link: None, placement: Default::default(), pixels: None }; + d.insert(Some(l), 0, Node::new(id, NodeKind::Image(Box::new(im)))).map_err(|e| crate::EngineError::Other(e.to_string())) + }) + .unwrap(); + let m = rect(&mut s, 10.0); + s.execute("object.mesh.create", &json!({"ids": [m.0], "rows": 1, "cols": 1})).unwrap(); + let colors = |s: &Session| match node(s, m).kind { + NodeKind::Mesh(g) => g.points.iter().map(|p| p.color).collect::<Vec<_>>(), + k => panic!("not a mesh: {k:?}"), + }; + let white = colors(&s)[0]; + let v = ViewInfo::default(); + let press = |s: &mut Session, i: usize, mods: Mods| { + let q = match node(s, m).kind { + NodeKind::Mesh(g) => g.points[i].p, + k => panic!("not a mesh: {k:?}"), + }; + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y).with_mods(mods), v).unwrap(); + } + }; + let (teal, orange) = (Color::rgb8(0, 128, 128), Color::rgb8(255, 128, 0)); + s.execute("select.set", &json!({"ids": [m.0]})).unwrap(); + s.select_tool("directSelection", v).unwrap(); + press(&mut s, 0, Mods::default()); + s.select_tool("eyedropper", v).unwrap(); + // Cmd-click point 3: Direct Selection, lent, picks it in place of point 0. + press(&mut s, 3, Mods { cmd: true, ..Default::default() }); + assert_eq!(s.tool_id(), "eyedropper"); + click(&mut s, 450.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [white, white, white, teal], "the point the lent tool picked takes the sample"); + // Cmd+Shift-click point 0 adds it to the Eyedropper's pick. + press(&mut s, 0, Mods { cmd: true, shift: true, ..Default::default() }); + click(&mut s, 350.0, 50.0, Mods::default()); + assert_eq!(colors(&s), [orange, white, white, orange], "both picked points take the sample"); +} + /// A CMYK document with one image of `px` (one row, 100 pt a pixel) at (300, 0). fn cmyk_doc_with_image(px: &[[u8; 4]]) -> Session { let mut s = Session::new(); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ae40324b9e..1faeaa76ad 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4109,6 +4109,17 @@ fn area_to_point_turns_wraps_into_breaks() { assert_eq!(txt.replace('\n', " "), "one two three four five six"); } +/// Convert To Point Type keeps the lines that a paragraph return or a forced line break (U+2028) +/// starts as they are: neither gets a paragraph return added after it. +#[test] +fn area_to_point_keeps_forced_line_breaks() { + let mut s = session(); + let a = id_of(&s.execute("text.create", &json!({"x": 0, "y": 0, "text": "ab\u{2028}c\nd", "area": {"width": 300, "height": 200}})).unwrap()); + sel(&mut s, &[a]); + s.execute("type.convertToPointType", &json!({})).unwrap(); + assert_eq!(plain(&s, a), "ab\u{2028}c\nd"); +} + #[test] fn placeholder_and_insert_characters() { let mut s = session(); @@ -4124,6 +4135,76 @@ fn placeholder_and_insert_characters() { assert!(s.execute("type.insert", &json!({"char": "nope"})).is_err()); } +/// Type › Insert Break Character › Forced Line Break (`type.insert {char: "forcedLineBreak"}`) +/// starts a new line in the same paragraph (U+2028, as Shift+Enter types it), so the paragraph's +/// space before does not come between the two lines; `paragraphReturn` starts a new paragraph. +/// Each insert is one undo step. +#[test] +fn insert_forced_line_break_differs_from_paragraph_return() { + fn second_line_gap(s: &Session, id: NodeId) -> f64 { + let NodeKind::Text(t) = &node(s, id).kind else { panic!("not text") }; + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + assert_eq!(lay.lines.len(), 2, "{:?}", t.plain_text()); + lay.lines[1].baseline - lay.lines[0].baseline + } + let mut s = session(); + let mut gaps = Vec::new(); + for (c, want) in [("forcedLineBreak", "ab\u{2028}c"), ("paragraphReturn", "ab\nc")] { + let t = text(&mut s, "ab"); + sel(&mut s, &[t]); + s.execute("text.setFormat", &json!({"ids": [t.0], "spaceBefore": 30})).unwrap(); + let steps = undo_len(&s); + s.execute("type.insert", &json!({"char": c})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{c}"); + s.execute("type.insert", &json!({"text": "c"})).unwrap(); + assert_eq!(plain(&s, t), want, "{c}"); + gaps.push(second_line_gap(&s, t)); + } + assert!(gaps[1] - gaps[0] > 29.0, "space before only at the paragraph return: {gaps:?}"); + // The same character by `unicode` and by `text`. + let t = text(&mut s, ""); + sel(&mut s, &[t]); + s.execute("type.insert", &json!({"unicode": "2028"})).unwrap(); + s.execute("type.insert", &json!({"text": "\u{2028}"})).unwrap(); + assert_eq!(plain(&s, t), "\u{2028}\u{2028}"); +} + +/// While the Type tool edits text, the Insert Special, Whitespace and Break menu items +/// (`type.insert` without `ids`) insert at its caret or replace its selection, as one undo step, +/// and the caret goes after the insertion; `ids` still appends to those objects. +#[test] +fn insert_character_goes_to_the_type_tool_caret() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, 50.0, 300.0), v).unwrap(); + } + let t = s.doc().unwrap().selection.objects[0]; + s.tool_text("abcd", v).unwrap(); + for _ in 0..2 { + s.tool_key(ToolKey::Left, Mods::default(), v).unwrap(); + } + let steps = undo_len(&s); + s.execute("type.insert", &json!({"text": ""})).unwrap(); + assert_eq!(undo_len(&s), steps, "an empty insert changes nothing"); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}cd"); + assert_eq!(s.tool_options()["caret"], json!(5)); + s.tool_text("X", v).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd"); + s.tool_key(ToolKey::Left, Mods { shift: true, ..Mods::default() }, v).unwrap(); + s.execute("type.insert", &json!({"char": "paragraphReturn"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd"); + s.execute("type.insert", &json!({"ids": [t.0], "text": "!"})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}\ncd!"); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(plain(&s, t), "ab\u{2028}Xcd", "the replacement is one undo step"); +} + /// `type.insert` by code (#5108): `code` as a Windows Alt+0 code types (Windows-1252 for /// 128–159, the code point otherwise), `unicode` as a hex code point. #[test] diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index ed4a82dce6..4f1edcc62a 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -2289,6 +2289,41 @@ fn threaded_list_edited_in_its_second_frame() -> (Session, NodeId, NodeId, Strin (s, a, b, story) } +/// Type › Insert Break Character › Forced Line Break (`type.insert`) after Select All in threaded +/// text replaces the whole story, every frame's text, as one undo step. +#[test] +fn insert_character_replaces_the_whole_story_that_select_all_selected() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + s.execute("select.all", &json!({})).unwrap(); + let steps = undo_labels(&s).len(); + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + assert_eq!(undo_labels(&s).len(), steps + 1, "one undo step"); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), "\u{2028}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), story); +} + +/// When `type.insert` at the caret in the first frame of threaded text pushes the caret's place on +/// into the next frame, the Type tool's caret goes there with it, and typing goes after the +/// insertion. +#[test] +fn insert_character_moves_the_caret_with_the_text_it_flows_on() { + let (mut s, a, b, story) = threaded_story_edited_in_its_second_frame(); + let first = obj(&s, a).plain_text(); + // Before the last word of the first frame: two line breaks there push the line after the + // first one on into the second frame. + let at = first.trim_end().rfind(' ').map_or(0, |k| k + 1); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": a.0, "anchor": at, "caret": at})); + for _ in 0..2 { + s.execute("type.insert", &json!({"char": "forcedLineBreak"})).unwrap(); + } + assert!(obj(&s, a).plain_text().len() < at + 6, "the second break flows on into the second frame"); + s.tool_text("X", ViewInfo::default()).unwrap(); + let want = format!("{}\u{2028}\u{2028}X{}", &story[..at], &story[at..]); + assert_eq!(format!("{}{}", obj(&s, a).plain_text(), obj(&s, b).plain_text()), want); +} + #[test] fn remove_breaks_takes_the_whole_story_that_select_all_selected() { let (mut s, a, b, story) = threaded_list_edited_in_its_second_frame(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..8b8cf4628b 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -173,6 +173,12 @@ impl Session { let text_selection = ((id == "eyedropper" && is_type(self.tool.id())) || (self.tool.id() == "eyedropper" && is_type(id))) .then(|| self.tool.options()) .filter(|o| o.get("editing").is_some_and(|v| !v.is_null()) && o.get("start") != o.get("end")); + // The gradient mesh points the Mesh tool, Direct Selection or the Lasso picked stay picked + // for the Eyedropper, which samples into them (#8090), and for the tool after it. + let mesh_points = (id == "eyedropper" || self.tool.id() == "eyedropper") + .then(|| self.tool.options().get("meshPoints").cloned()) + .flatten() + .filter(|v| v.as_array().is_some_and(|a| !a.is_empty())); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); self.apply_actions(acts)?; self.keep_tool_settings(); @@ -180,6 +186,9 @@ impl Session { if let Some(selection) = text_selection { self.tool.set_option("textSelection", &selection); } + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); self.select_whole_instance(id); @@ -258,7 +267,13 @@ impl Session { // The lending tool does not see the press: it counts as a press elsewhere for the clicks a // double-click or triple-click compares. self.tool.press_elsewhere(); - let lent = self.make_tool(id); + let mut lent = self.make_tool(id); + // The gradient mesh points the Eyedropper holds are the lent tool's picks, which a Shift + // click adds to (#8090). + if self.tool.id() == "eyedropper" { + let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); + lent.set_option("meshPoints", &points); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) @@ -269,10 +284,17 @@ impl Session { /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { let Some(lender) = self.lender.take() else { return Ok(()) }; + // The points the lent tool left picked go back to the Eyedropper, none when it unpicked + // them all (#8090). Group Selection picks no mesh points, so the Eyedropper keeps its own. + let mesh_points = + (lender.id() == "eyedropper" && self.tool.id() != "groupSelection").then(|| self.tool.options().get("meshPoints").cloned()).flatten(); let acts = self.with_tool_cx(view, |t, cx| t.deactivate(cx)); let r = self.apply_actions(acts); self.keep_tool_settings(); self.tool = lender; + if let Some(points) = mesh_points { + self.tool.set_option("meshPoints", &points); + } // A gesture that left the selection as it found it (a Shift marquee over nothing) picked // nothing: the selection keeps what it was, the Pen's last anchor or an earlier pick. let left = self.active().map(|d| (d.uid, d.selection.clone())); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 865adcc282..a6d1fe6c5d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1569,6 +1569,16 @@ fn headless_backend_methods() { assert_eq!(entry["label"], "Trim at Crossings Tool"); assert!(entry["shortcut"].is_null()); assert_eq!(h.call("ui.tool.select", json!({"tool": trim})).unwrap()["tool"], trim); + // The Enclosing Lasso Tool is listed once, in the Lasso tool's group after the Lasso. + let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; + let with_enclosing: Vec<_> = + groups.iter().map(|group| group.as_array().unwrap()).filter(|group| group.iter().any(|entry| entry["id"] == enclosing)).collect(); + assert_eq!(with_enclosing.len(), 1, "{enclosing} is in one group"); + let ids: Vec<_> = with_enclosing[0].iter().map(|entry| entry["id"].clone()).collect(); + assert_eq!(ids, [json!("lasso"), json!(enclosing)]); + assert_eq!(with_enclosing[0][1]["label"], "Enclosing Lasso Tool"); + assert!(with_enclosing[0][1]["shortcut"].is_null()); + assert_eq!(h.call("ui.tool.select", json!({"tool": enclosing})).unwrap()["tool"], enclosing); let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso"); assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool"))); assert!(h.call("ui.resize", json!({})).is_err()); diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index d04b223b44..125126790c 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -46,12 +46,7 @@ use crate::{Imported, Kind}; const PATTERNS: &str = "hatched and pattern brushes are filled with their average color"; const ENDS_EARLY: &str = "the file ends early: what it held was imported"; const TOO_MANY: &str = "objects past the most one file may hold were left out"; -const AT_LIMIT: &str = "the file reached the most objects one file may hold: any after them were not read"; - -/// The most items `craft_metafile` keeps from one file (its `MAX_ITEMS`). It stops reading at the -/// limit and does not say whether more items followed, so a picture holding this many may have -/// been cut short. -const READER_ITEMS: usize = 200_000; +const AT_LIMIT: &str = "the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read"; /// Points a unit of a WMF without a placeable header (1440 units an inch). const WMF_UNIT: f64 = 72.0 / 1440.0; @@ -217,6 +212,18 @@ struct Pending { path: BezPath, } +/// What `craft_metafile` counted as not read or not played as the file asks. +struct Lost { + /// Records of kinds it doesn't read. + skipped: u32, + /// Images, and pattern brushes (a pen's included), whose bitmap it couldn't read. + images: u32, + /// Clip changes it didn't apply as the file sets them. + clips: u32, + /// Raster operations drawn as a plain copy or left out. + rops: u32, +} + /// Clip paths already made, by address (the `Arc` keeps the address from being reused); None for /// one that clips nothing in the picture. type MadeClips = HashMap<*const ClipPath, (Arc<ClipPath>, Option<Arc<Clip>>)>; @@ -720,14 +727,38 @@ impl Mapper { } /// The document: what was drawn on one layer, clipped art in clipping groups. - fn finish(mut self, kind: Kind, skipped: u32) -> Imported { + fn finish(mut self, kind: Kind, lost: Lost) -> Imported { self.flush(); - if skipped > 0 { - let n = skipped; + let s = |n: u32| if n == 1 { "" } else { "s" }; + let was = |n: u32| if n == 1 { "was" } else { "were" }; + let n = lost.skipped; + if n > 0 { + self.warnings.push(format!("{n} record{} of kinds VectorCraft doesn't read {} skipped", s(n), was(n))); + } + let n = lost.images; + if n > 0 { self.warnings.push(format!( - "{n} record{} of kinds VectorCraft doesn't read {} skipped", - if n == 1 { "" } else { "s" }, - if n == 1 { "was" } else { "were" } + "{n} image{} or pattern brush{} that couldn't be read {} left out", + s(n), + if n == 1 { "" } else { "es" }, + was(n) + )); + } + let n = lost.clips; + if n > 0 { + self.warnings.push(format!( + "{n} clip{} couldn't be applied as the file sets {}: what is drawn after {} may show more or less than the file does", + s(n), + if n == 1 { "it" } else { "them" }, + if n == 1 { "it" } else { "them" } + )); + } + let n = lost.rops; + if n > 0 { + self.warnings.push(format!( + "{n} raster operation{} other than a plain copy (masks, inversions) {} drawn as a plain copy or left out", + s(n), + was(n) )); } let out = std::mem::take(&mut self.out); @@ -981,11 +1012,12 @@ pub(crate) fn import(bytes: &[u8]) -> Result<Imported, String> { if ends_early(bytes, kind) { m.warn(ENDS_EARLY); } - if pic.items.len() >= READER_ITEMS { + if pic.truncated { m.warn(AT_LIMIT); } + let lost = Lost { skipped: pic.skipped_records, images: pic.dropped_images, clips: pic.ignored_clips, rops: pic.unplayed_raster_ops }; for item in pic.items { m.item(item); } - Ok(m.finish(kind, pic.skipped_records)) + Ok(m.finish(kind, lost)) } diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 61126ef228..1ba560d05e 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -16,6 +16,8 @@ //! [`import`] reads either format (an EMF with its EMF+ records too, through `craft_metafile`) //! into a document of one artboard (the picture's frame) and one layer: paths with fills and //! strokes, clipping, images and text. Records it doesn't read are skipped, with one warning. +//! A picture cut short by a reader limit, images and pattern brushes that can't be read, clips +//! that can't be applied and raster operations other than a plain copy each add a warning. //! [`import_pict`] reads QuickDraw pictures (PICT, versions 1 and 2) into the same kind of //! document. //! diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 07749872ed..01883c740b 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -527,11 +527,100 @@ fn a_file_with_more_objects_than_are_read_says_so() { let many = hand_emf(5000, 3000, &vec![rect.clone(); 200_010]); let back = import(&many).unwrap(); assert_eq!(paths(&back.document).len(), 200_000); - assert!(back.warnings.iter().any(|w| w.contains("reached the most objects")), "{:?}", back.warnings); + assert!(back.warnings.iter().any(|w| w.contains("reached a limit")), "{:?}", back.warnings); + // Exactly as many as the reader keeps: nothing was left unread. + let full = import(&hand_emf(5000, 3000, &vec![rect.clone(); 200_000])).unwrap(); + assert_eq!(paths(&full.document).len(), 200_000); + assert!(full.warnings.is_empty(), "{:?}", full.warnings); let few = import(&hand_emf(5000, 3000, &vec![rect; 3])).unwrap(); assert!(few.warnings.is_empty(), "{:?}", few.warnings); } +#[test] +fn a_file_cut_short_by_another_limit_says_so() { + // SAVEDC past the 1,024 levels the reader keeps stops the parse: the rectangle after them is + // not read. + let mut records = vec![(43, le(&[0, 0, 100, 100]))]; + records.extend(vec![(33, vec![]); 1100]); + records.push((43, le(&[200, 200, 300, 300]))); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["the file or a picture inside it reached a limit on what one file may hold: what came after the limit was not read".to_string()] + ); +} + +#[test] +fn images_the_reader_does_not_read_are_counted() { + let records = vec![(81, png_stretch_dibits(&png_claiming(1 << 13, 1 << 13))); 2]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(back.warnings, vec!["2 images or pattern brushes that couldn't be read were left out".to_string()]); + let back = import(&hand_emf(5000, 3000, &records[..1])).unwrap(); + assert_eq!(back.warnings, vec!["1 image or pattern brush that couldn't be read was left out".to_string()]); +} + +#[test] +fn a_wmf_reports_unread_pattern_brushes_and_raster_operations() { + let records = vec![ + // DIBCREATEPATTERNBRUSH (style 5, usage 0) whose bitmap header can't be read. + (0x0142, [le16(&[5, 0]), vec![0xFF; 8]].concat()), + // A bitmap-less DIBBITBLT with DSTINVERT (0x00550009): rop, ySrc, xSrc, reserved, height, + // width, yDest, xDest. + (0x0940, le16(&[0x0009, 0x0055, 0, 0, 0, 100, 100, 0, 0])), + ]; + let back = import(&hand_wmf(1440, 1440, &records)).unwrap(); + assert_eq!( + back.warnings, + vec![ + "1 image or pattern brush that couldn't be read was left out".to_string(), + "1 raster operation other than a plain copy (masks, inversions) was drawn as a plain copy or left out".to_string(), + ] + ); +} + +#[test] +fn clips_that_are_not_applied_are_counted() { + // BEGINPATH, a rectangle, ENDPATH, SELECTCLIPPATH with RGN_XOR (3), then a rectangle drawn after it. + let records = vec![(59, vec![]), (43, le(&[100, 100, 2000, 2000])), (60, vec![]), (67, le(&[3])), (43, le(&[500, 500, 600, 600]))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!(paths(&back.document).len(), 1); + assert_eq!( + back.warnings, + vec!["1 clip couldn't be applied as the file sets it: what is drawn after it may show more or less than the file does".to_string()] + ); + // RGN_AND (1) is applied. + let mut records = records; + records[3] = (67, le(&[1])); + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + +/// An EMR_BITBLT of the 100 × 100 box at the origin with `rop` and no source bitmap. +fn bitblt(rop: u32) -> Vec<u8> { + // Bounds; destination; the operation; the source origin, transform (identity) and background + // color; usage, then no BITMAPINFO and no bits. + let mut body = vec![0; 16]; + body.extend(le(&[0, 0, 100, 100, rop as i32, 0, 0])); + body.extend(le_f32(&[1.0, 0.0, 0.0, 1.0, 0.0, 0.0])); + body.extend(le(&[0, 0, 0, 0, 0, 0])); + body +} + +#[test] +fn raster_operations_that_are_not_played_are_counted() { + // DSTINVERT and PATINVERT take no source bitmap and are left out. + let records = vec![(76, bitblt(0x0055_0009)), (76, bitblt(0x005A_0049))]; + let back = import(&hand_emf(5000, 3000, &records)).unwrap(); + assert_eq!( + back.warnings, + vec!["2 raster operations other than a plain copy (masks, inversions) were drawn as a plain copy or left out".to_string()] + ); + // WHITENESS is played. + let back = import(&hand_emf(5000, 3000, &[(76, bitblt(0x00FF_0062))])).unwrap(); + assert!(back.warnings.is_empty(), "{:?}", back.warnings); +} + /// An EMR_STRETCHDIBITS copying `png` (a BI_PNG bitmap) to a 10 × 10 box. fn png_stretch_dibits(png: &[u8]) -> Vec<u8> { // Bounds; destination, source and its size; the BITMAPINFO and the bits (from the record start); diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 817d334fb8..69bcf84f7f 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -54,6 +54,8 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } serde_json = { workspace = true } # `draw_text`, to write test files with live text as other writers do. krilla = { workspace = true, features = ["simple-text"] } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } # An independent raster oracle for gradient placement in PDF forms. These are test-only macOS # bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer. diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index c6b165bbd5..2a2ab1a884 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -118,7 +118,7 @@ impl Exporter<'_> { if several && !elements.iter().skip(1).all(|(c, _)| shape_is_coverage(c)) { let doc = self.doc; let brushes = self.brushes.get_or_insert_with(|| vectorcraft_brush::library(doc)); - match knockout_masks(BrushSearch::new(doc, brushes), &elements) { + match knockout_masks(BrushSearch::new(&self.symbols, brushes), &elements) { Ok(above) => { // Every mask is made before anything is drawn: when the symbol objects the // masks may hold run out, one would leave out art its element covers, and @@ -452,7 +452,7 @@ impl Exporter<'_> { // A dynamic symbol's instance shows its own appearance changes, and the instance's // fill stains its art, as on the canvas. let doc = self.doc; - if let Some(sym) = doc.symbols.iter().find(|x| &x.name == symbol) { + if let Some(sym) = self.symbols.symbol(symbol) { let changed; let art: &Node = if n.extras().symbol_overrides.is_empty() && vectorcraft_doc::symbol_overrides::stain(n).is_none() { &sym.art @@ -968,8 +968,10 @@ enum SharedArt { /// A search for the brushed strokes drawing an object draws, whose brush art can hold many more /// objects than the stroked path. -struct BrushSearch<'a> { - doc: &'a Document, +struct BrushSearch<'a, 'd> { + doc: &'d Document, + /// `doc`'s symbols, found by name. + symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, /// The brushes the export draws strokes with ([`Exporter::brush_art`]); a stroke whose brush /// is not among them is drawn as a plain stroke. brushes: &'a [vectorcraft_brush::Brush], @@ -983,9 +985,10 @@ struct BrushSearch<'a> { exhausted: bool, } -impl<'a> BrushSearch<'a> { - fn new(doc: &'a Document, brushes: &'a [vectorcraft_brush::Brush]) -> Self { - Self { doc, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } +impl<'a, 'd> BrushSearch<'a, 'd> { + /// A search through the document of `symbols`. + fn new(symbols: &'a vectorcraft_doc::SymbolBoxes<'d>, brushes: &'a [vectorcraft_brush::Brush]) -> Self { + Self { doc: symbols.document(), symbols, brushes, seen: HashMap::new(), left: MAX_KNOCKOUT_MASK_OBJECTS, exhausted: false } } /// Takes `n` objects from [`Self::left`]; false, and the search exhausted, when fewer are left. @@ -1046,8 +1049,7 @@ impl<'a> BrushSearch<'a> { NodeKind::SymbolInstance { symbol, .. } => { // A dynamic symbol's instance draws its art with its own appearance changes: the // art is copied once for each set of changes, counted before it is copied. - let doc = self.doc; - match doc.symbols.iter().find(|s| &s.name == symbol) { + match self.symbols.symbol(symbol) { Some(s) if !n.extras().symbol_overrides.is_empty() => { let key = format!("{symbol}\u{0}{:?}", n.extras().symbol_overrides); self.shared(SharedArt::Dynamic, &key, |search| { @@ -1080,8 +1082,7 @@ impl<'a> BrushSearch<'a> { /// Whether the art of the symbol named `name` draws a brushed stroke. fn symbol(&mut self, name: &str, depth: usize) -> bool { - let doc = self.doc; - let Some(s) = doc.symbols.iter().find(|s| s.name == name) else { return false }; + let Some(s) = self.symbols.symbol(name) else { return false }; self.shared(SharedArt::Symbol, name, |search| search.node(&s.art, true, depth)) } @@ -1177,7 +1178,8 @@ mod tests { let square = Node::path(NodeId(0), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(Paint::None, Paint::None, 0.0)); let art = Node::group(NodeId(0), vec![Arc::new(square), Arc::new(instance())]); d.symbols.push(Symbol { dynamic: true, name: "Loop".into(), art: Arc::new(art) }); - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&instance(), true, 0)); assert!(!search.exhausted); assert!(MAX_KNOCKOUT_MASK_OBJECTS - search.left < 10, "{} objects", MAX_KNOCKOUT_MASK_OBJECTS - search.left); @@ -1205,11 +1207,12 @@ mod tests { .collect(); Node::group(NodeId(0), instances) }; - let mut search = BrushSearch::new(&d, &[]); + let symbols = d.symbol_boxes(); + let mut search = BrushSearch::new(&symbols, &[]); assert!(search.node(&group(true), true, 0)); assert!(search.exhausted); assert_eq!(search.left, 0); - let mut search = BrushSearch::new(&d, &[]); + let mut search = BrushSearch::new(&symbols, &[]); assert!(!search.node(&group(false), true, 0)); assert!(!search.exhausted); // The group, the 1,000 instances, and one copy of the art counted and looked through. @@ -1247,6 +1250,6 @@ mod tests { vectorcraft_doc::placed_document::prime(&placed, Arc::new(vec![]), brushed_art()); let n = Node::new(NodeId(0), NodeKind::PlacedDocument(Box::new(placed))); let brushes = vectorcraft_brush::library(&d); - assert!(BrushSearch::new(&d, &brushes).node(&n, true, 0)); + assert!(BrushSearch::new(&d.symbol_boxes(), &brushes).node(&n, true, 0)); } } diff --git a/crates/pdf/src/export/text.rs b/crates/pdf/src/export/text.rs index c3d30b7953..0ad1e2d4ff 100644 --- a/crates/pdf/src/export/text.rs +++ b/crates/pdf/src/export/text.rs @@ -134,7 +134,7 @@ impl Exporter<'_> { self.inline_depth += 1; for ig in &layout.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = doc.symbols.iter().find(|x| x.name == art.symbol) else { continue }; + let Some(sym) = self.symbols.symbol(&art.symbol) else { continue }; let mut node = (*sym.art).clone(); // Strokes scale with the art, as on the canvas. node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true); diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 3fcefd7b8e..45ca7f7081 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,6 +1,6 @@ use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ - Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline, + Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgb_png, rgba_png, same_outline, stroke_layer, stroke_outline, }; use super::{ @@ -304,27 +304,39 @@ impl<'a> Device<'a> for Builder<'_> { self.add_image(key, || None, xf); return; } - let mut decoded: Option<Decoded> = None; + // RGB samples, or RGBA when the image has an alpha channel or is drawn white. + let mut decoded: Option<(Decoded, bool)> = None; r.with_rgba( |img, alpha| { let (w, h, sf) = (img.width(), img.height(), img.scale_factors()); - let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); - let rgba: Vec<u8> = match img { - _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), - ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), - ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + let px = match (img, alpha) { + // An opaque image's RGB samples are encoded as they are, with no copy. + (ImageData::Rgb(d), None) if !white => (d.data, false), + // Gray samples are stored as RGB: as a gray PNG, the image would become a + // grayscale image that a fill color colorizes. + (ImageData::Luma(d), None) if !white => (d.data.iter().flat_map(|g| [*g; 3]).collect(), false), + (img, alpha) => { + let a = alpha.map(|a| resize_alpha(&a, w, h)).unwrap_or_else(|| vec![255; (w * h) as usize]); + let rgba: Vec<u8> = match img { + _ if white => a.into_iter().flat_map(|a| [255, 255, 255, a]).collect(), + ImageData::Rgb(d) => d.data.as_chunks::<3>().0.iter().zip(a).flat_map(|(c, a)| [c[0], c[1], c[2], a]).collect(), + ImageData::Luma(d) => d.data.iter().zip(a).flat_map(|(g, a)| [*g, *g, *g, a]).collect(), + }; + (rgba, true) + } }; - decoded = Some((rgba, w, h, sf)); + decoded = Some(((px.0, w, h, sf), px.1)); }, None, ); - let Some((rgba, w, h, sf)) = decoded else { + let Some(((px, w, h, sf), alpha)) = decoded else { self.warn("an image could not be decoded and was skipped"); return; }; self.raster_scales.insert(key, sf); let xf = transform * Affine::scale_non_uniform(sf.0 as f64, sf.1 as f64); - self.add_image(key, || rgba_png(rgba, w, h).map(|png| (ImageBlob::new("image/png", png), w, h)), xf); + let png = move || if alpha { rgba_png(px, w, h) } else { rgb_png(px, w, h) }; + self.add_image(key, || png().map(|png| (ImageBlob::new("image/png", png), w, h)), xf); } Image::Stencil(s) => { let white = self.white_images; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 1eeb8a5539..ba0c23a808 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -340,6 +340,11 @@ pub(super) fn rgba_png(rgba: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() } +pub(super) fn rgb_png(rgb: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { + let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Rgb, craft_image_codecs::SampleType::U8, rgb).ok()?; + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() +} + pub(super) fn gray_png(gray: Vec<u8>, w: u32, h: u32) -> Option<Vec<u8>> { let img = craft_image_codecs::Image::from_raw(w, h, craft_image_codecs::ChannelLayout::Gray, craft_image_codecs::SampleType::U8, gray).ok()?; craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok() diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..470432aa8f 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -215,7 +215,7 @@ fn stream_kind(pdf: &Pdf, id: ObjectIdentifier, dict: &Dict<'_>) -> String { } /// `bytes` for a message, in whole megabytes, or gigabytes when it is a whole number of them. -fn decoded_size(bytes: usize) -> String { +pub(crate) fn decoded_size(bytes: usize) -> String { const GB: usize = 1 << 30; if bytes >= GB && bytes.is_multiple_of(GB) { format!("{} GB", bytes / GB) } else { format!("{} MB", bytes >> 20) } } @@ -323,10 +323,13 @@ pub struct TrimPages { pub bleed: [f64; 4], } -/// Preserve the application's existing accepted file sizes. Ordinary stream decoding still -/// uses the shared reader's immutable per-document limits, and its input copy is fallible. +/// The shared reader's options: files of any size are accepted. Ordinary stream decoding uses the shared reader's immutable per-document limits, and its input +/// copy is fallible. One image may decode to the bytes and pixels of +/// [`crate::streams::image_limits`] for this build, past the shared reader's defaults. pub(crate) fn open_options() -> craft_pdf::OpenOptions { - craft_pdf::OpenOptions { max_input_bytes: usize::MAX, ..Default::default() } + let (bytes, pixels) = crate::streams::image_limits(crate::streams::LARGE_IMAGES); + let decode_limits = craft_pdf::syntax::DecodeLimits::default().with_max_decoded_image(bytes).with_max_image_pixels(pixels); + craft_pdf::OpenOptions { max_input_bytes: usize::MAX, decode_limits } } pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result<Pdf, PdfError> { diff --git a/crates/pdf/src/streams.rs b/crates/pdf/src/streams.rs index 3f99b8b82a..1cb23b2768 100644 --- a/crates/pdf/src/streams.rs +++ b/crates/pdf/src/streams.rs @@ -15,9 +15,21 @@ use craft_pdf::syntax::object::{Array, Dict, FromBytes, MaybeRef, Name, Object, /// million, 4 bytes each). pub(crate) const MAX_DECODED: usize = 256 << 20; +/// Whether this build reads the larger images of [`image_limits`]: a 64-bit build that isn't for +/// the web. +pub(crate) const LARGE_IMAGES: bool = cfg!(all(target_pointer_width = "64", not(target_family = "wasm"))); + +/// The most bytes one image XObject may decode to and the most pixels it may have, for a build +/// that reads `large` images: 4 GiB and 2^30 pixels (31404 × 31403 pixels are 2.76 GiB in RGB and +/// 3.67 GiB in CMYK), otherwise 1 GiB and 2^28 pixels (an A0 sheet scanned at 300 ppi is 399 MiB +/// in RGB and 532 MiB in CMYK). The shared reader takes the same two figures ([`crate::pages::open_options`]). +pub(crate) const fn image_limits(large: bool) -> (u64, u64) { + if large { (1 << 32, 1 << 30) } else { (1 << 30, 1 << 28) } +} + /// The most an image XObject may decode to when its own size asks for more than -/// [`MAX_DECODED`]: 1 GB (an A0 sheet scanned at 300 ppi is 418 MB in RGB, 557 MB in CMYK). -const MAX_IMAGE_DECODED: usize = 1 << 30; +/// [`MAX_DECODED`]: the bytes of [`image_limits`] for this build. +const MAX_IMAGE_DECODED: usize = image_limits(LARGE_IMAGES).0 as usize; /// The longest row a predictor may have, in bytes. const MAX_ROW: usize = 1 << 24; @@ -779,31 +791,42 @@ mod tests { /// A one-page PDF drawing one flat 8-bit DeviceRGB image of `w` × `h` pixels, Flate-compressed. fn one_image_pdf(w: usize, h: usize) -> Vec<u8> { + image_pdf(&format!("/Width {w} /Height {h} /ColorSpace /DeviceRGB"), &flat(&[200, 180, 150].repeat(w), h), None) + } + + /// `row` repeated `h` times, Flate-compressed as it is written. + fn flat(row: &[u8], h: usize) -> Vec<u8> { let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best()); - let row: Vec<u8> = [200, 180, 150].repeat(w); for _ in 0..h { - std::io::Write::write_all(&mut e, &row).unwrap(); + std::io::Write::write_all(&mut e, row).unwrap(); } - let image = e.finish().unwrap(); + e.finish().unwrap() + } + + /// A one-page PDF drawing one 8-bit image with the size and color space of `keys` and the + /// Flate-compressed samples `data`; with `smask`, a soft mask with those keys and data. + fn image_pdf(keys: &str, data: &[u8], smask: Option<(&str, &[u8])>) -> Vec<u8> { + let stream = |keys: &str, data: &[u8]| { + let dict = + format!("<< /Type /XObject /Subtype /Image {keys} /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", data.len()); + [dict.as_bytes(), data, b"\nendstream"].concat() + }; let content = b"q 595 0 0 842 0 0 cm /Im0 Do Q"; let mut out = b"%PDF-1.6\n".to_vec(); let mut offsets = vec![]; - let objects: Vec<Vec<u8>> = vec![ + let mut objects: Vec<Vec<u8>> = vec![ b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /XObject << /Im0 5 0 R >> >> >>".to_vec(), [format!("<< /Length {} >>\nstream\n", content.len()).as_bytes(), content, b"\nendstream"].concat(), - [ - format!( - "<< /Type /XObject /Subtype /Image /Width {w} /Height {h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length {} >>\nstream\n", - image.len() - ) - .as_bytes(), - &image, - b"\nendstream", - ] - .concat(), ]; + match smask { + Some((mask_keys, mask_data)) => { + objects.push(stream(&format!("{keys} /SMask 6 0 R"), data)); + objects.push(stream(mask_keys, mask_data)); + } + None => objects.push(stream(keys, data)), + } for (i, o) in objects.iter().enumerate() { offsets.push(out.len()); out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); @@ -828,6 +851,65 @@ mod tests { assert_eq!(info.map(|i| i.pages.len()).unwrap(), 1); } + #[test] + fn a_64_bit_desktop_build_reads_larger_images_and_others_keep_their_limits() { + assert_eq!(image_limits(false), (1 << 30, 1 << 28)); + assert_eq!(image_limits(true), (1 << 32, 1 << 30)); + let (bytes, pixels) = image_limits(LARGE_IMAGES); + assert_eq!(MAX_IMAGE_DECODED as u64, bytes); + let limits = crate::pages::open_options().decode_limits; + assert_eq!((limits.max_decoded_image(), limits.max_image_pixels()), (bytes, pixels)); + // An image declaring more is held to this build's limit, which a refusal of it names. + let d = dict("<< /Subtype /Image /Width 70000 /Height 70000 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode >>"); + assert_eq!(budget(&d), MAX_IMAGE_DECODED); + let most = if LARGE_IMAGES { "4 GB" } else { "1 GB" }; + assert_eq!(crate::pages::decoded_size(MAX_IMAGE_DECODED), most); + } + + /// The only image of `doc`, as stored: its width, height and channel layout. + fn stored_image(doc: &vectorcraft_doc::Document) -> (u32, u32, image::ExtendedColorType) { + use image::ImageDecoder as _; + let blobs: Vec<_> = doc.images.values().collect(); + let [blob] = blobs[..] else { panic!("one image expected, found {}", blobs.len()) }; + let decoder = image::ImageReader::new(std::io::Cursor::new(blob.bytes.as_slice())).with_guessed_format().unwrap().into_decoder().unwrap(); + let (w, h) = decoder.dimensions(); + (w, h, decoder.original_color_type()) + } + + #[test] + fn an_image_past_1_gb_and_2_to_the_28_pixels_opens_on_a_64_bit_desktop_build() { + if !LARGE_IMAGES { + return; + } + // 18919 × 18919 RGB pixels: 358 million pixels, 1.07 GB decoded (#4366). + let side = 18919; + let doc = crate::import(&one_image_pdf(side, side)).unwrap(); + // Opaque: stored as RGB, without an alpha channel. + assert_eq!(stored_image(&doc), (side as u32, side as u32, image::ExtendedColorType::Rgb8)); + } + + #[test] + fn opaque_images_are_stored_without_an_alpha_channel_and_masked_ones_with_one() { + let rgb = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), None); + assert_eq!(stored_image(&crate::import(&rgb).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let gray = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[120; 4], 2), None); + assert_eq!(stored_image(&crate::import(&gray).unwrap()), (4, 2, image::ExtendedColorType::Rgb8)); + let mask = ("/Width 4 /Height 2 /ColorSpace /DeviceGray", &flat(&[0, 85, 170, 255], 2)[..]); + let masked = image_pdf("/Width 4 /Height 2 /ColorSpace /DeviceRGB", &flat(&[200, 180, 150].repeat(4), 2), Some(mask)); + assert_eq!(stored_image(&crate::import(&masked).unwrap()), (4, 2, image::ExtendedColorType::Rgba8)); + } + + #[test] + fn an_image_of_more_pixels_than_the_limit_is_left_out_with_a_warning() { + let (_, pixels) = image_limits(LARGE_IMAGES); + // One more row than a square of the limit's pixels; its data isn't looked at. + let side = 1u64 << (pixels.ilog2() / 2); + let pdf = image_pdf(&format!("/Width {side} /Height {} /ColorSpace /DeviceGray", side + 1), &flat(&[0; 16], 1), None); + let report = crate::import_with_report(&pdf, &crate::ImportOptions::default()).unwrap(); + assert!(report.document.images.is_empty()); + assert!(report.warnings.iter().any(|w| w.contains("an image could not be decoded and was skipped")), "{:?}", report.warnings); + } + #[test] fn object_and_cross_reference_streams_are_looked_at_before_the_file_is_read() { let stream = |dict: &str, data: &[u8]| { diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 2337cc8dee..91c037ad84 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -223,6 +223,60 @@ fn an_instance_whose_art_reaches_the_page_is_written() { assert!(fills.contains(&[255, 0, 0, 255]) && fills.contains(&[0, 0, 255, 255]), "{fills:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), with an instance of +/// "Mark" at (25, 25) and, in a knockout group above a green square, a half-opaque one at (70, 70). +/// With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = doc(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(Rect::new(0.0, 0.0, 1.0, 1.0), Color::BLACK); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(Rect::new(-10.0, -10.0, 10.0, 10.0), color); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + add(&mut d, Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) })); + let green = rect_node(Rect::new(60.0, 60.0, 80.0, 80.0), Color::rgb(0.0, 1.0, 0.0)); + let mut above = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + above.opacity = 0.5; + let mut group = Node::group(NodeId(0), vec![Arc::new(green), Arc::new(above)]); + group.knockout = vectorcraft_doc::Knockout::On; + add(&mut d, group); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same bytes +/// as when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let d = marks("Mark"); + assert!(uncompressed(&d) == uncompressed(&marks("Other")), "the files differ"); + let fills: Vec<[u8; 4]> = leaves(&roundtrip(&d)).iter().filter_map(|n| Some(n.appearance.fill_paint().color()?.to_rgba8(1.0))).collect(); + assert!(fills.contains(&[255, 0, 0, 255]) && !fills.contains(&[0, 0, 255, 255]), "{fills:?}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + add(&mut d, n); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &PdfOptions::default()).expect("export"); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + #[test] fn an_instance_whose_brush_art_reaches_the_page_is_written() { // The symbol's art: a line from (0, 40) to (0, 60) with a 1 pt stroke painted by a 20 pt round diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 61569cc79e..9a4c095650 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -51,3 +51,5 @@ craft-tiff = { workspace = true } craft-psd = { workspace = true } proptest = { workspace = true } serde_json = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/render/src/addons/halftone.rs b/crates/render/src/addons/halftone.rs index 9b1cfe7091..a113e8fab8 100644 --- a/crates/render/src/addons/halftone.rs +++ b/crates/render/src/addons/halftone.rs @@ -57,7 +57,7 @@ pub fn sample(doc: &Document, nodes: Vec<Node>, region: Rect, scale: f64, mono: /// take too many cells: `n` then draws as it is. pub fn art(doc: &Document, n: &Node) -> Option<Node> { let ht = Halftone::of(n)?; - let found = Renderer::new().live_found(doc, &Arc::new(n.clone())); + let found = Renderer::new().live_found(&doc.symbol_boxes(), &Arc::new(n.clone())); let mut cache = CACHE.lock().unwrap_or_else(PoisonError::into_inner); if let Some(at) = cache.iter().position(|(node, was, _)| was.0 == found.0 && node == n) { let kept = cache.remove(at); diff --git a/crates/render/src/bounds.rs b/crates/render/src/bounds.rs index 569e0be64b..fafb1b188f 100644 --- a/crates/render/src/bounds.rs +++ b/crates/render/src/bounds.rs @@ -6,7 +6,13 @@ use super::{BezPath, Document, FillRule, Node, NodeKind, Rect, SymbolBoxes, brus /// geometry effects, and the shadows and glows of it and its members. Symbol instances are /// measured by their art in `doc` ([`Node::visual_bounds_with`]). pub fn painted_bounds(doc: &Document, n: &Node) -> Option<Rect> { - brush_fx::cull_bounds(&doc.symbol_boxes(), n) + painted_bounds_with(&doc.symbol_boxes(), n) +} + +/// [`painted_bounds`] with symbol instances measured by their art in `symbols` (made with +/// [`Document::symbol_boxes`]). +pub fn painted_bounds_with(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { + brush_fx::cull_bounds(symbols, n) } /// [`painted_bounds`] of `n` without the room it leaves for brush art past the brushed strokes of @@ -70,7 +76,7 @@ pub fn rasterize_stage(doc: &Document, n: &Node) -> Option<(Node, Vec<vectorcraf /// The outline, with `n`'s geometry effects applied, that the canvas clips `n`'s Rasterize with /// Create Clipping Mask to. Object › Rasterize's clipping mask follows it. pub fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { - fx::drawn_outline(doc, n) + fx::drawn_outline(&doc.symbol_boxes(), n) } /// The outlines a drag draws for `nodes` with Real-time Drawing off: one for each object in them, diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index a9d86f79e7..dda132308f 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -397,9 +397,7 @@ fn shape_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { // effects in a symbol's art and a live object's content paint past it. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); @@ -466,7 +464,7 @@ fn pieces_within(symbols: &SymbolBoxes, art: &Node, depth: usize, budget: &mut u NodeKind::Path { .. } | NodeKind::Compound { .. } if has_fx(art) => visual_bounds(symbols, art), NodeKind::SymbolInstance { symbol, .. } if depth < vectorcraft_doc::depth::MAX_DEPTH && has_instance_row_effects(art) => { let doc = symbols.document(); - let reshaped = doc.symbols.iter().find(|s| s.name == *symbol).and_then(|s| { + let reshaped = symbols.symbol(symbol).and_then(|s| { let count = s.art.count() as u64; if count > *budget { return None; @@ -501,13 +499,15 @@ pub(crate) fn painted_reach(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> { /// The outline the renderer clips `n`'s Feather, Inner Glow and Rasterize with Create Clipping /// Mask to: a path's or compound path's geometry with its object-level geometry effects applied, /// the outline of the art [`Renderer::fx_art`] makes for an object with object effects, and with -/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. -pub(crate) fn drawn_outline(doc: &Document, n: &Node) -> Option<(BezPath, FillRule)> { +/// Crop Marks the object's own. For other objects it is [`effects::clip_outline`]. The symbols of +/// instances are found in `symbols`. +pub(crate) fn drawn_outline(symbols: &SymbolBoxes, n: &Node) -> Option<(BezPath, FillRule)> { + let doc = symbols.document(); if let Some(art) = effects::crop_marks_art(n) { - return drawn_outline(doc, art.children()?.first()?); + return drawn_outline(symbols, art.children()?.first()?); } if has_object_fx(n) { - let art = Renderer::new().fx_art(doc, &Arc::new(n.clone()), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(n.clone()), false); return effects::clip_outline(&art); } match &n.kind { @@ -545,7 +545,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le if is_container(n) && !makes_art && !effects::has_item_geometry(n) { object.appearance.items.clear(); } - let art = Renderer::new().fx_art(doc, &Arc::new(object), false); + let art = Renderer::new().fx_art(symbols, &Arc::new(object), false); if art.children().is_some() && !has_object_fx(&art) { return evaluated_outlines(doc, symbols, &art, left, out); } @@ -570,7 +570,7 @@ pub(crate) fn drawn_outlines(doc: &Document, symbols: &SymbolBoxes, n: &Node, le NodeKind::SymbolInstance { .. } => { push_outline(n.geometric_bounds_with(symbols).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()), left, out) } - _ => push_outline(drawn_outline(doc, n).map(|(path, _)| path), left, out), + _ => push_outline(drawn_outline(symbols, n).map(|(path, _)| path), left, out), } } @@ -690,9 +690,7 @@ fn cull_bounds_in(symbols: &SymbolBoxes, n: &Node, after_reshape: bool, brush: b // symbol instance's art paint past that art. _ if has_object_fx(n) => { let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, .. } => { - symbols.document().symbols.iter().find(|s| s.name == *symbol).map(|s| dynamic_art(&s.art, n)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| dynamic_art(&s.art, n)), _ => None, }; let reshaped = effects::reshape(Some(symbols.document()), n, symbol.as_ref()); diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 045aeceb39..555a121309 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -481,7 +481,7 @@ impl Renderer { /// What [`Self::draw_object_fx`] draws inside the object's transparency group. fn draw_object_fx_art(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc<Node>, cache: bool) { - if !self.charge_fx_instance(f.doc, a) { + if !self.charge_fx_instance(f.symbols, a) { return; } // A path whose Transform effects after its Rasterize effect hold options that reach its @@ -493,7 +493,7 @@ impl Renderer { { return self.draw_staged(ctx, f, stage, &bp, *rule); } - let art = self.fx_art(f.doc, a, cache); + let art = self.fx_art(f.symbols, a, cache); // Art the cache did not keep is made again in the next frame. let kept = cache && self.fx_arts.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &art)); let outer = self.made_again; @@ -545,9 +545,9 @@ impl Renderer { /// frame's symbol budget as an instance without effects is (`draw_node`): an instance whose /// effects reshape its art draws through here, and nested instances would otherwise expand /// without a limit. True for any other object. - pub(crate) fn charge_fx_instance(&mut self, doc: &vectorcraft_doc::Document, a: &Node) -> bool { + pub(crate) fn charge_fx_instance(&mut self, symbols: &SymbolBoxes, a: &Node) -> bool { let NodeKind::SymbolInstance { symbol, .. } = &a.kind else { return true }; - let count = doc.symbols.iter().find(|s| &s.name == symbol).map_or(0, |s| s.art.count() as u64); + let count = symbols.symbol(symbol).map_or(0, |s| s.art.count() as u64); let mut used = self.symbol_nodes; let room = vectorcraft_doc::charge_symbol_art(&mut used, count, || ((), count)).is_some(); self.symbol_nodes = used; @@ -562,7 +562,7 @@ impl Renderer { /// is made from live objects it evaluated ([`evaluates_live`]), or from type, symbol art or /// colors shaded through the color settings ([`reads_outside`]), is kept only while what it /// reads from outside `a` stays the same ([`Self::live_found`]). - pub(super) fn fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>, cache: bool) -> Arc<Node> { + pub(super) fn fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; let mut kept = None; if cache @@ -574,7 +574,7 @@ impl Renderer { Some(was) => kept = Some((art.clone(), was.0)), } } - let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(doc, a)); + let found = (kept.is_some() || (cache && (evaluates_live(a) || reads_outside(a)))).then(|| self.live_found(symbols, a)); if let Some((art, was)) = kept && found.as_ref().is_some_and(|f| f.0 == was) { @@ -590,11 +590,11 @@ impl Renderer { Some((art, was)) => { let now = match &found { Some(f) => Some(f.0), - None => self.outside_key(doc, a), + None => self.outside_key(symbols, a), }; - if was == now { art } else { self.make_fx_art(doc, a) } + if was == now { art } else { self.make_fx_art(symbols, a) } } - None => self.make_fx_art(doc, a), + None => self.make_fx_art(symbols, a), }; if cache { let bytes = crate::lru::node_bytes(&art); @@ -607,24 +607,24 @@ impl Renderer { /// held until the frame ends ([`Renderer::measured`]), for [`Self::fx_art`] to keep if `a` is /// drawn. What is measured but never drawn (culled, off the view) is let go, and isn't kept in /// place of what is drawn. - pub(crate) fn measured_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + pub(crate) fn measured_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { let key = Arc::as_ptr(a) as usize; if let Some((node, art, found)) = self.fx_arts.get(&key, self.stamp) && Arc::ptr_eq(node, a) { let (art, was) = (art.clone(), found.as_ref().map(|f| f.0)); - if was.is_none_or(|was| self.live_found(doc, a).0 == was) { + if was.is_none_or(|was| self.live_found(symbols, a).0 == was) { return art; } } - let now = self.outside_key(doc, a); + let now = self.outside_key(symbols, a); if let Some((node, art, was)) = self.measured.get(&key) && Arc::ptr_eq(node, a) && *was == now { return art.clone(); } - let art = self.make_fx_art(doc, a); + let art = self.make_fx_art(symbols, a); // Art held for an object before (made from what it read then) gives way. if let Some(old) = self.measured.remove(&key) { self.measured_bytes = self.measured_bytes.saturating_sub(crate::lru::node_bytes(&old.1)); @@ -657,18 +657,17 @@ impl Renderer { /// The key of what `a`'s art reads from outside it ([`Self::live_found`]), `None` when it reads /// nothing. - fn outside_key(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Option<u64> { - (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(doc, a).0) + fn outside_key(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Option<u64> { + (evaluates_live(a) || reads_outside(a)).then(|| self.live_found(symbols, a).0) } /// The art [`Self::fx_art`] draws for `a`, made now. - fn make_fx_art(&mut self, doc: &vectorcraft_doc::Document, a: &Arc<Node>) -> Arc<Node> { + fn make_fx_art(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>) -> Arc<Node> { + let doc = symbols.document(); // Whether the art is a 3D effect's ([`Self::three_d_art_bounds`]). let mut three_d = false; let symbol = match &a.kind { - NodeKind::SymbolInstance { symbol, .. } => { - doc.symbols.iter().find(|s| s.name == *symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)) - } + NodeKind::SymbolInstance { symbol, .. } => symbols.symbol(symbol).map(|s| crate::brush_fx::instance_art(&s.art, a)), _ => None, }; let container = is_container(a); diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 3bbd803cc2..3c2e9ff65a 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -1066,7 +1066,7 @@ fn a_measuring_pass_sweeps_the_bounds_of_held_art_as_they_double() { } let mut r = Renderer::new(); // Held here, as the art kept to draw is. - let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d, n)).collect(); + let held: Vec<_> = d.layers[0].children().unwrap().iter().map(|n| r.measured_fx_art(&d.symbol_boxes(), n)).collect(); assert_eq!((held.len(), r.three_d_bounds.len()), (3000, 3000)); assert!(r.three_d_sweeps <= 2, "{} sweeps", r.three_d_sweeps); } @@ -1193,7 +1193,7 @@ fn drawing_takes_measured_art_out_of_the_budget() { let mut r = Renderer::new(); r.bounds_of(&d.symbol_boxes(), &n); assert!(r.measured_bytes > 0); - r.fx_art(&d, &n, true); + r.fx_art(&d.symbol_boxes(), &n, true); assert_eq!((r.measured_bytes, r.measured.len()), (0, 0), "taken out when drawn"); let mut r = Renderer::new(); r.render(&d, 800, 100, Affine::IDENTITY, &RenderOptions::default()); @@ -1343,11 +1343,11 @@ fn art_measured_again_takes_the_place_of_the_held() { let n = d.layers[0].children().unwrap()[0].clone(); let key = Arc::as_ptr(&n) as usize; let mut r = Renderer::new(); - let art = r.measured_fx_art(&d, &n); + let art = r.measured_fx_art(&d.symbol_boxes(), &n); let bytes = r.measured_bytes; // As if it had read something else then. r.measured.insert(key, (n.clone(), art, Some(7))); - r.measured_fx_art(&d, &n); + r.measured_fx_art(&d.symbol_boxes(), &n); assert_eq!((r.measured_bytes, r.measured.len()), (bytes, 1)); } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5aec78e679..af3a0d4da8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -285,7 +285,7 @@ mod renderer; mod text_geom; mod threads; -pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, rasterize_stage}; +pub use bounds::{drawn_bounds, drawn_outline, drawn_outlines, effect_bounds, painted_bounds, painted_bounds_with, rasterize_stage}; pub use frame::FrameStats; use frame::{ ClipEntry, ClipPaintEntry, Frame, FxArtEntry, GeomEntry, PlacedEntry, PlacedKey, PtrHasher, PtrMap, SliceEntry, StrokeEntry, StrokeKey, diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index e1940bc79c..dfa79a9ad5 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -21,7 +21,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_doc::live::{GradientMesh, MeshQuad}; use vectorcraft_doc::placed_document::ReadDocument; -use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes}; use vectorcraft_geom::{Affine, BezPath, Point, Vec2}; use vello_cpu::RenderContext; use vello_cpu::peniko; @@ -109,10 +109,11 @@ pub fn expand_live(n: &Node) -> Vec<Node> { /// their address). Art is hashed by the addresses of its `Arc`s, which copies of the document /// share: a copy of the document has the same key. It also returns weak references to the reads /// found, and what the walk found ([`Walked`]) when it found no placed file and no such image. -fn resources_key(doc: &Document, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { +/// Symbols are found by name in `symbols`. +fn resources_key(symbols: &SymbolBoxes, cms: usize, names: u64, n: &Node) -> (u64, Vec<Weak<ReadDocument>>, Option<Walked>) { let mut h = DefaultHasher::new(); let mut shown = Shown::default(); - hash_resources(doc, n, &mut shown, &mut h); + hash_resources(symbols, n, &mut shown, &mut h); let walked = Walked { hash: h.finish(), text: shown.text, plugins: shown.plugins }; (walked.key(cms, names), shown.reads, (!shown.placed && !shown.pixels).then_some(walked)) } @@ -175,8 +176,9 @@ struct Shown { /// own fills or strokes follow them ([`crate::effects::follows_image_pixels`]). It walks `n` and /// then, one at a time from a list, the opacity-mask, pattern and symbol art it finds, each pattern /// and each symbol's art once ([`first_seen`]). `shown` records the type, placed files, reads, -/// such images and plug-in effects found. -fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { +/// such images and plug-in effects found. Symbols are found by name in `symbols`. +fn hash_resources<'a>(symbols: &SymbolBoxes<'a>, n: &'a Node, shown: &mut Shown, h: &mut DefaultHasher) { + let doc = symbols.document(); let mut todo = vec![]; let mut next = Some(n); while let Some(art) = next { @@ -198,7 +200,7 @@ fn hash_resources<'a>(doc: &'a Document, n: &'a Node, shown: &mut Shown, h: &mut } match &c.kind { NodeKind::SymbolInstance { symbol, .. } => { - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if let Some(s) = symbols.symbol(symbol) { (Arc::as_ptr(&s.art) as usize).hash(h); if first_seen(&mut shown.seen, Arc::as_ptr(&s.art) as usize) { todo.push(&s.art); @@ -462,14 +464,14 @@ fn spread_to_edges(px: &mut [vello_cpu::color::PremulRgba8], filled: Vec<bool>, } impl Renderer { - /// The [`resources_key`] of `n` in `doc`, with the frame's [`DocInputs`] ([`Found`]): `n` is a - /// live node, or an object with effects whose art ([`Renderer::fx_art`]) can be made from - /// evaluated live objects, type, symbol art or colors shaded through the color settings. The - /// key is made from the [`Walk`] kept for `n` while `doc`'s symbols and patterns are those it - /// read; `n` is walked again when they changed, and in every frame when the walk found a - /// placed file or an image whose own fills or strokes follow its pixels. - pub(crate) fn live_found(&mut self, doc: &Document, n: &Arc<Node>) -> Found { - let inputs = self.doc_inputs(doc); + /// The [`resources_key`] of `n` in the document of `symbols`, with the frame's [`DocInputs`] + /// ([`Found`]): `n` is a live node, or an object with effects whose art ([`Renderer::fx_art`]) + /// can be made from evaluated live objects, type, symbol art or colors shaded through the color + /// settings. The key is made from the [`Walk`] kept for `n` while the document's symbols and + /// patterns are those it read; `n` is walked again when they changed, and in every frame when + /// the walk found a placed file or an image whose own fills or strokes follow its pixels. + pub(crate) fn live_found(&mut self, symbols: &SymbolBoxes, n: &Arc<Node>) -> Found { + let inputs = self.doc_inputs(symbols.document()); let at = Arc::as_ptr(n) as usize; if let Some((node, walked, read)) = self.live.walks.get(&at, self.stamp) && std::ptr::eq(node.as_ptr(), Arc::as_ptr(n)) @@ -481,7 +483,7 @@ impl Renderer { { self.live.walked += 1; } - let (key, reads, walked) = resources_key(doc, inputs.cms, inputs.names, n); + let (key, reads, walked) = resources_key(symbols, inputs.cms, inputs.names, n); if let Some(walked) = walked { // The bytes count the key and the entry, and the node's allocation that the weak // reference keeps. @@ -491,11 +493,12 @@ impl Renderer { (key, inputs, reads) } - fn live_expanded(&mut self, doc: &Document, a: &Arc<Node>, cache: bool) -> Expanded { + fn live_expanded(&mut self, symbols: &SymbolBoxes, a: &Arc<Node>, cache: bool) -> Expanded { + let doc = symbols.document(); let key = Arc::as_ptr(a) as usize; // An evaluation the cache does not keep is made without the key, so the copy that // `draw_live_node` makes is not walked. - let resources = cache.then(|| self.live_found(doc, a)); + let resources = cache.then(|| self.live_found(symbols, a)); if let Some(resources) = &resources && let Some(e) = self.live.expanded.get(&key, self.stamp) && Arc::ptr_eq(&e.0, a) @@ -550,7 +553,7 @@ impl Renderer { let knockout = !f.opts.outline && matches!(a.kind, NodeKind::Blend { .. }) && a.knockout.resolve(self.knockout) - && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.doc, a, true)); + && vectorcraft_doc::live::steps_knockout_shows(&self.live_expanded(f.symbols, a, true)); let enclosing = std::mem::replace(&mut self.knockout, knockout); if !f.opts.outline && (opacity < 1.0 || a.blend != vectorcraft_color::BlendMode::Normal || a.isolate || knockout) { let blends = self.blends_through(a); @@ -575,7 +578,7 @@ impl Renderer { | NodeKind::Intertwine { .. } | NodeKind::Group { .. } | NodeKind::Layer { .. } => { - let items = self.live_expanded(f.doc, a, cache); + let items = self.live_expanded(f.symbols, a, cache); // An evaluation the cache did not keep is made again in the next frame. let kept = cache && self.live.expanded.get(&(Arc::as_ptr(a) as usize), self.stamp).is_some_and(|e| Arc::ptr_eq(&e.1, &items)); let outer = self.made_again; @@ -818,7 +821,12 @@ mod tests { let envelope = Node::new(d.alloc_id(), envelope); let key = |d: &Document| { std::thread::scope(|s| { - std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || resources_key(d, 0, 0, &envelope).0).unwrap().join().unwrap() + std::thread::Builder::new() + .stack_size(256 << 10) + .spawn_scoped(s, || resources_key(&d.symbol_boxes(), 0, 0, &envelope).0) + .unwrap() + .join() + .unwrap() }) }; let before = key(&d); @@ -850,8 +858,8 @@ mod tests { frame: Box::new(Affine::IDENTITY), }; let envelope = Node::new(d.alloc_id(), envelope); - let before = resources_key(&d, 0, 0, &envelope).0; + let before = resources_key(&d.symbol_boxes(), 0, 0, &envelope).0; d.symbols[2].art = y.clone(); - assert_ne!(resources_key(&d, 0, 0, &envelope).0, before, "the art of every instance is hashed"); + assert_ne!(resources_key(&d.symbol_boxes(), 0, 0, &envelope).0, before, "the art of every instance is hashed"); } } diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 8e18b3a045..bd26c851cd 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -36,7 +36,7 @@ impl Renderer { // drawn otherwise, measured as below. _ if measures_three_d(a) && let Some(b) = { - let art = self.measured_fx_art(symbols.document(), a); + let art = self.measured_fx_art(symbols, a); self.three_d_art_bounds(symbols, &art) } => { @@ -578,7 +578,7 @@ impl Renderer { self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) } NodeKind::SymbolInstance { symbol, xf } => { - if let Some(sym) = f.doc.symbols.iter().find(|s| &s.name == symbol) { + if let Some(sym) = f.symbols.symbol(symbol) { // The instance draws when the frame has room for its art's objects; a symbol // with 9-slice guides is placed cell by cell (`Self::sliced_art`). let mut used = self.symbol_nodes; diff --git a/crates/render/src/renderer/text.rs b/crates/render/src/renderer/text.rs index 945ce5303b..01c73918e7 100644 --- a/crates/render/src/renderer/text.rs +++ b/crates/render/src/renderer/text.rs @@ -32,14 +32,14 @@ impl Renderer { return; } for r in t.runs.iter().filter_map(|r| r.inline.as_ref()) { - if !f.doc.symbols.iter().any(|s| s.name == r.symbol) && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { + if f.symbols.symbol(&r.symbol).is_none() && !MISSING_INLINE_LOGGED.swap(true, std::sync::atomic::Ordering::Relaxed) { log::warn!("inline graphic shows symbol {:?}, which the document doesn't have: it draws nothing", r.symbol); } } self.inline_depth += 1; for ig in &g.inlines { let Some(art) = t.runs.get(ig.run).and_then(|r| r.inline.as_ref()) else { continue }; - let Some(sym) = f.doc.symbols.iter().find(|s| s.name == art.symbol) else { continue }; + let Some(sym) = f.symbols.symbol(&art.symbol) else { continue }; // Strokes scale with the art (it is sized to the type, as in the SVG `<use>`). let (node, kept) = self.placed_art(&sym.art, t.xf * ig.xf * f.doc.symbol_natural_xf(&art.symbol), true, None); self.draw_placed_art(ctx, f, &node, kept); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 89e90c31aa..2a0e6c9a93 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -314,6 +314,76 @@ fn past_the_measured_placements_an_instance_is_culled_by_an_estimate_of_its_art_ assert!(img.pixel(3, 20)[3] > 0, "{:?}", img.pixel(3, 20)); } +/// 2,000 symbols, then two named "Mark" (a red square, then a blue one), and an instance of +/// "Mark" at (25, 25) and one with a drop shadow at (70, 70). With `second` the blue square's +/// symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(100.0, 100.0); + for i in 0..2000 { + let art = rect_node(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), Paint::solid(Color::BLACK), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb(1.0, 0.0, 0.0)), (second, Color::rgb(0.0, 0.0, 1.0))] { + let art = rect_node(&mut d, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::solid(color), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let l = d.layers[0].id; + let plain = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((25.0, 25.0)) }); + let mut shadowed = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((70.0, 70.0)) }); + shadowed.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 4, "y": 4, "blur": 0}), + visible: true, + }); + d.insert(Some(l), 0, plain).unwrap(); + d.insert(Some(l), 1, shadowed).unwrap(); + d +} + +/// Instances among many symbols draw the first symbol of their name, the same pixels as when no +/// other symbol has that name. +#[test] +fn instances_draw_the_first_symbol_of_their_name() { + let img = render(&marks("Mark")); + assert_eq!(img.pixel(25, 25), [255, 0, 0, 255]); + assert_eq!(img.pixel(70, 70), [255, 0, 0, 255]); + assert!(img.pixels == render(&marks("Other")).pixels, "the pixels differ"); +} + +/// A frame that draws 300 instances with drop shadows, among 2,000 symbols, and an envelope around +/// instances reads the symbol list once to find their symbols. +#[test] +fn a_frame_reads_the_symbol_list_once() { + let mut d = marks("Other"); + let l = d.layers[0].id; + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 5.0, f64::from(i / 20) * 5.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let content = Arc::new(Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((50.0, 50.0)) })); + let kind = vectorcraft_doc::live::EnvelopeKind::Warp { style: "arc".into(), bend: 30.0, h: 0.0, v: 0.0, horizontal: true, version: 0 }; + let envelope = NodeKind::Envelope { + content: vec![content], + kind: Box::new(kind), + fidelity: 50.0, + editing: false, + options: Default::default(), + frame: Box::new(Affine::IDENTITY), + }; + let envelope = Node::new(d.alloc_id(), envelope); + d.insert(Some(l), usize::MAX, envelope).unwrap(); + let before = vectorcraft_doc::symbols_read(); + render(&d); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// Symbols 0 to 29 each hold two instances of the next, sheared two ways, so that the 2^30 /// instances drawn from the first are all placed differently. Symbol 30 holds a square with a drop /// shadow. An instance of symbol 0 lies far left of the view. With `effect`, every instance has diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 6eb13767d8..5a4fb97b44 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -1241,9 +1241,10 @@ fn symbol_instances_with_effects_are_charged_to_the_symbol_budget() { let inst = d.layers[0].children().unwrap()[0].clone(); let mut r = Renderer::new(); r.symbol_nodes = vectorcraft_doc::MAX_SYMBOL_NODES - 1; - assert!(r.charge_fx_instance(&d, &inst), "one object fits"); + let symbols = d.symbol_boxes(); + assert!(r.charge_fx_instance(&symbols, &inst), "one object fits"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); - assert!(!r.charge_fx_instance(&d, &inst), "the next does not"); + assert!(!r.charge_fx_instance(&symbols, &inst), "the next does not"); assert_eq!(r.symbol_nodes, vectorcraft_doc::MAX_SYMBOL_NODES); } diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 660ef967ad..c1a59d7022 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -47,3 +47,5 @@ vectorcraft-text = { workspace = true, features = ["test-fonts"] } craft-svg = { workspace = true, features = ["tree-render", "tree-text"] } vectorcraft-testkit = { workspace = true } proptest = { workspace = true } +# How many times the symbol list is read to find symbols by name. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } diff --git a/crates/svg/src/export.rs b/crates/svg/src/export.rs index e3acc9f032..ded9a037fe 100644 --- a/crates/svg/src/export.rs +++ b/crates/svg/src/export.rs @@ -117,6 +117,7 @@ fn write(doc: &Document, opts: &ExportOptions, native: Option<&[u8]>, id_prefix: linked: Vec::new(), instance_xf: Affine::IDENTITY, symbols: HashMap::new(), + symbol_lookup: doc.symbol_boxes(), symbol_nest: 0, symbol_nodes: 0, inline_graphic: false, @@ -301,6 +302,9 @@ struct Writer<'a> { instance_xf: Affine, /// What each symbol's instances can share, by symbol name (see [`Writer::symbol_use`]). symbols: HashMap<String, SymbolDef>, + /// The document's symbols, found by name ([`vectorcraft_doc::SymbolBoxes::symbol`]) in time + /// independent of how many symbols the document holds. + symbol_lookup: vectorcraft_doc::SymbolBoxes<'a>, /// Symbols being written inside one another (instances nested deeper are left out: a symbol /// can't contain itself). symbol_nest: u32, diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index b9af2a6c06..6427d048bd 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -51,15 +51,16 @@ fn export_shape_bounds(n: &Node) -> Option<Rect> { impl Reuse { const NONE: Self = Self { moves: false, turns: false, scales: false }; - /// What a def of symbol art `art` stands for. - pub(crate) fn of(doc: &Document, art: &Node) -> Self { + /// What a def of symbol art `art` stands for, in `doc`. `find` finds the symbol of each + /// instance in it by name. + pub(crate) fn of<'d>(doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, art: &Node) -> Self { let mut r = Self { moves: true, turns: true, scales: true }; - r.scan(doc, art, 0); + r.scan(doc, find, art, 0); r } /// Narrow down to what `n` (inside symbols nested `depth` deep) allows. - fn scan(&mut self, doc: &Document, n: &Node, depth: u32) { + fn scan<'d>(&mut self, doc: &'d Document, find: &dyn Fn(&str) -> Option<&'d vectorcraft_doc::Symbol>, n: &Node, depth: u32) { let pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); let text_patterns = matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| pattern(&r.style.fill) || pattern(&r.style.stroke))); let unlinked_mask = n.extras().mask.as_ref().is_some_and(|m| !m.linked); @@ -95,17 +96,17 @@ impl Reuse { if doc.symbol_nine_slice(symbol).is_some() { self.scales = false; } - if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { - self.scan(doc, &s.art, depth + 1); + if let Some(s) = find(symbol) { + self.scan(doc, find, &s.art, depth + 1); } } _ => {} } if let Some(m) = &n.extras().mask { - self.scan(doc, &m.art, depth); + self.scan(doc, find, &m.art, depth); } for c in n.children().into_iter().flatten() { - self.scan(doc, c, depth); + self.scan(doc, find, c, depth); } } @@ -481,7 +482,7 @@ impl Writer<'_> { if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { let custom = !n.extras().symbol_overrides.is_empty(); if symbols.insert((symbol.clone(), custom.then_some(n.id))) - && let Some(s) = self.doc.symbols.iter().find(|s| s.name == *symbol) + && let Some(s) = self.symbol_lookup.symbol(symbol) { stack.push(if custom { std::sync::Arc::new(vectorcraft_brush::instance_art(&s.art, n)) } else { s.art.clone() }); } @@ -518,7 +519,7 @@ impl Writer<'_> { /// its geometry, so the region also covers the geometry's box, placed, grown by the strokes' /// and effects' reach unscaled. fn region_attrs(&mut self, nodes: &[&Node]) -> String { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let region = self.region_of(&symbols, &mut art_reach, nodes); self.region_boxes = Some(symbols); @@ -528,7 +529,7 @@ impl Writer<'_> { /// The box of what each of `nodes` paints, as [`Self::paint_box`] measures it. fn paint_boxes(&mut self, nodes: &[&Node]) -> Vec<Option<Option<Rect>>> { - let symbols = self.region_boxes.take().unwrap_or_else(|| self.doc.symbol_boxes()); + let symbols = self.region_boxes.take().unwrap_or_else(|| self.symbol_lookup.unmeasured()); let mut art_reach = std::mem::take(&mut self.art_reach); let boxes = nodes.iter().map(|n| self.paint_box(&symbols, &mut art_reach, n)).collect(); self.region_boxes = Some(symbols); @@ -615,7 +616,7 @@ impl Writer<'_> { return Some(own + past + self.paint_reach(symbols, art_reach, &g, gb, depth + 1)?); } let symbol = match &n.kind { - NodeKind::SymbolInstance { symbol, xf } => self.doc.symbols.iter().find(|s| s.name == *symbol).map(|s| (s, xf)), + NodeKind::SymbolInstance { symbol, xf } => self.symbol_lookup.symbol(symbol).map(|s| (s, xf)), _ => None, }; if n.children().is_none_or(|c| c.is_empty()) && symbol.is_none() { @@ -1026,7 +1027,7 @@ impl Writer<'_> { let doc = self.doc; // The instances nested in an inline graphic's art are ordinary instances again. let inline = std::mem::take(&mut self.inline_graphic); - let Some(sym) = doc.symbols.iter().find(|s| s.name == *symbol) else { return }; + let Some(sym) = self.symbol_lookup.symbol(symbol) else { return }; if self.symbol_nest > MAX_SYMBOL_NEST { return; } @@ -1113,7 +1114,8 @@ impl Writer<'_> { return None; } if !self.symbols.contains_key(&sym.name) { - let reuse = Reuse::of(self.doc, &sym.art); + let lookup = &self.symbol_lookup; + let reuse = Reuse::of(self.doc, &|name| lookup.symbol(name), &sym.art); self.symbols.insert(sym.name.clone(), SymbolDef { id: None, reuse, nodes: 0 }); } let def = self.symbols.get(&sym.name)?; diff --git a/crates/svg/src/export/paint.rs b/crates/svg/src/export/paint.rs index 234783d029..57e0a6caf4 100644 --- a/crates/svg/src/export/paint.rs +++ b/crates/svg/src/export/paint.rs @@ -680,7 +680,7 @@ impl Writer<'_> { } return 0; } - let bounds = n.visual_bounds_with(&self.doc.symbol_boxes()); + let bounds = n.visual_bounds_with(&self.symbol_lookup.unmeasured()); // An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first. let grow = 18.0 / self.doc.raster_ppi(); let reach: f64 = @@ -705,7 +705,7 @@ impl Writer<'_> { // object's geometry turned into it, grown by what its strokes and other paint add // around it in the document: a square that far to each side, as it measures in // user space along each axis (a miter corner reaches that far along both). - let symbols = self.doc.symbol_boxes(); + let symbols = self.symbol_lookup.unmeasured(); let visual = input.visual_bounds_with(&symbols).unwrap_or_default(); let user_box = if sf.moves_only() { visual - sf.origin() diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 6348b6e141..aaeac31a11 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -202,7 +202,7 @@ pub(crate) fn import_finding( hidden: found.hidden, uses: found.uses, symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: fx::blends(&xml, &scan.markers), @@ -360,8 +360,8 @@ struct Importer { uses: HashMap<String, String>, /// The symbols made so far, by `<symbol>` id. symbols: HashMap<String, SymbolMade>, - /// The names of the symbols made so far. - symbol_names: HashSet<String>, + /// The names of the symbols made so far, each with its index in the document's symbols. + symbol_names: HashMap<String, usize>, /// Where the suffixes of each symbol and pattern name base go on from (`unique_name`). symbol_suffixes: HashMap<String, usize>, pattern_suffixes: HashMap<String, usize>, diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 9badabc601..c1dd856559 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -207,9 +207,11 @@ impl Importer { None => { let base = self.name_of(&sym).to_string(); let names = &self.symbol_names; - let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains(n)); - self.symbol_names.insert(name.clone()); - let reuse = Reuse::of(&self.doc, &art); + let name = unique_name(&base, &mut self.symbol_suffixes, |n| names.contains_key(n)); + let doc = &self.doc; + let find = |n: &str| names.get(n).and_then(|&i| doc.symbols.get(i)).filter(|s| s.name == n); + let reuse = Reuse::of(doc, &find, &art); + self.symbol_names.insert(name.clone(), self.doc.symbols.len()); let made = SymbolMade { name: name.clone(), art: without_ids(&art), reuse }; self.doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); self.symbols.insert(sym, made); @@ -862,7 +864,7 @@ mod tests { hidden: HashSet::new(), uses: HashMap::new(), symbols: HashMap::new(), - symbol_names: HashSet::new(), + symbol_names: HashMap::new(), symbol_suffixes: HashMap::new(), pattern_suffixes: HashMap::new(), blends: HashMap::new(), diff --git a/crates/svg/tests/it/symbols_layers.rs b/crates/svg/tests/it/symbols_layers.rs index b30d367858..1d1b4cc712 100644 --- a/crates/svg/tests/it/symbols_layers.rs +++ b/crates/svg/tests/it/symbols_layers.rs @@ -69,6 +69,64 @@ fn three_instances_give_one_symbol_and_three_uses() { assert!(boxes.iter().any(|b| (b.x0 - 90.0).abs() < 1e-3 && (b.y0 - 30.0).abs() < 1e-3), "{boxes:?}"); } +/// 2,000 symbols, then two named "Mark" (a red square with a black stroke, then a blue one) and +/// "Holder", holding an instance of "Mark". Instances: "Mark" moved, "Mark" stretched (written as +/// its own art) and "Holder". With `second` the blue square's symbol is named that instead. +fn marks(second: &str) -> Document { + let mut d = Document::new(200.0, 120.0); + for i in 0..2000 { + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: format!("Filler {i}"), art: Arc::new(art) }); + } + for (name, color) in [("Mark", Color::rgb8(255, 0, 0)), (second, Color::rgb8(0, 0, 255))] { + let ap = Appearance::basic(Paint::solid(color), Paint::solid(Color::BLACK), 2.0); + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-10.0, -10.0, 10.0, 10.0)), ap); + d.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) }); + } + let held = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf: Affine::translate((5.0, 5.0)) }); + let holder = Node::group(d.alloc_id(), vec![Arc::new(held)]); + d.symbols.push(Symbol { dynamic: false, name: "Holder".into(), art: Arc::new(holder) }); + instance(&mut d, "Mark", Affine::translate((25.0, 25.0))); + instance(&mut d, "Mark", Affine::translate((80.0, 60.0)) * Affine::scale_non_uniform(2.0, 1.0)); + instance(&mut d, "Holder", Affine::translate((150.0, 60.0))); + d +} + +/// Instances among many symbols are written with the first symbol of their name, the same SVG as +/// when no other symbol has that name. +#[test] +fn instances_are_written_with_the_first_symbol_of_their_name() { + let svg = export(&marks("Mark"), &ExportOptions::default()); + assert_eq!(svg, export(&marks("Other"), &ExportOptions::default())); + assert!(svg.contains("#ff0000") && !svg.contains("#0000ff"), "{svg}"); +} + +/// An export of 300 instances with drop shadows, among 2,000 symbols, reads the symbol list once +/// to find their symbols. +#[test] +fn an_export_reads_the_symbol_list_once() { + let mut d = marks("Other"); + for i in 0..300 { + let xf = Affine::translate((f64::from(i % 20) * 10.0, f64::from(i / 20) * 8.0)) * Affine::scale(0.2); + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Mark".into(), xf }); + n.appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + params: serde_json::json!({"x": 1, "y": 1, "blur": 0}), + visible: true, + }); + let l = d.layers[0].id; + d.insert(Some(l), usize::MAX, n).unwrap(); + } + let before = vectorcraft_doc::symbols_read(); + export(&d, &ExportOptions::default()); + let read = vectorcraft_doc::symbols_read() - before; + assert!(read <= d.symbols.len(), "{read} symbols read, {} in the document", d.symbols.len()); +} + /// A scaled instance of a symbol with 9-slice guides is written as the canvas draws it, with no /// `<use>`: at 200 × 150 its 10 × 10 corner square stays 10 × 10 and its center square becomes /// 30 × 20. An instance at the natural size still uses the def. diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 1f8ddc3755..fa88e3f9ef 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -28,6 +28,12 @@ icu_segmenter = "2.3" # Grapheme clusters (a Thai consonant with its vowel and tone marks, an accented letter, an emoji # sequence) for caret movement; MIT OR Apache-2.0, already in the build. unicode-segmentation = "1.13" +# Hyphenation patterns and rules for German, Polish, Portuguese, Italian, Bulgarian, Turkish and +# Russian; MIT OR Apache-2.0, already in the build through the engine's spell checking. +craft-proof = { workspace = true } +# Composes a decomposed Cyrillic word (`и` + U+0306 is `й`) before its script check; MIT OR +# Apache-2.0, already in the build through craft-proof. +unicode-normalization = "0.1.26" # Draws COLR colour glyphs whose paints documents have no form for (sweep gradients, compositing # modes) into images: the canvas's renderer, already in the build. vello_cpu = { workspace = true } diff --git a/crates/text/src/hyphen.rs b/crates/text/src/hyphen.rs index c940ed85a4..435aae7ea9 100644 --- a/crates/text/src/hyphen.rs +++ b/crates/text/src/hyphen.rs @@ -9,8 +9,11 @@ //! [`set_hyphenation_exceptions`]. //! //! Each run hyphenates in its own language ([`vectorcraft_doc::CharStyle::language`]). English -//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns. Other languages -//! only break at user exceptions. Indic breaks always preserve Unicode grapheme boundaries. +//! uses the rules above; eleven Indian languages use bundled hyph-utf8 patterns; German, Polish, +//! Portuguese, Italian, Bulgarian, Turkish and Russian use craft-proof's patterns and rules (German, +//! Polish, Portuguese and Italian only in builds that embed their patterns). Other languages only +//! break at user exceptions. Indic and craft-proof breaks always preserve Unicode grapheme +//! boundaries. use std::collections::HashMap; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -18,22 +21,28 @@ use std::sync::{Mutex, MutexGuard, OnceLock}; use vectorcraft_doc::HyphenationOptions; mod indic; +mod proof; #[derive(Clone, Copy, Debug)] pub(crate) enum Language { None, English, Indic(u8), + /// One of [`proof::TAGS`]. + Proof(u8), } impl Language { /// Select rules by the primary BCP 47 subtag; absent tags retain the English default. pub(crate) fn from_tag(tag: Option<&str>) -> Self { let primary = tag.unwrap_or("en").split('-').next().unwrap_or_default(); + let index = |tags: &[&str]| tags.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()); if primary.eq_ignore_ascii_case("en") { Self::English + } else if let Some(i) = index(&indic::TAGS) { + Self::Indic(i) } else { - indic::TAGS.iter().position(|t| primary.eq_ignore_ascii_case(t)).and_then(|i| u8::try_from(i).ok()).map_or(Self::None, Self::Indic) + index(&proof::TAGS).map_or(Self::None, Self::Proof) } } } @@ -189,11 +198,16 @@ fn onset_pair(a: char, b: char) -> bool { /// Whether text in `language` (a [`vectorcraft_doc::CharStyle::language`]: a BCP 47 tag, `None` for /// the default, English: USA) has break points of its own. pub fn language_has_patterns(language: Option<&str>) -> bool { - !matches!(Language::from_tag(language), Language::None) + match Language::from_tag(language) { + Language::None => false, + Language::Proof(index) => proof::available(usize::from(index)), + Language::English | Language::Indic(_) => true, + } } -/// Language-specific break points as character indices. Indic patterns and exceptions are -/// filtered to whole graphemes; the paragraph's length options count Unicode characters. +/// Language-specific break points as character indices. Indic and craft-proof points and +/// exceptions are filtered to whole graphemes; the paragraph's length options count Unicode +/// characters. pub fn hyphen_points_for_language(word: &str, opts: &HyphenationOptions, language: Option<&str>) -> Vec<usize> { points_for(word, opts, Language::from_tag(language)) } @@ -220,14 +234,15 @@ pub fn hyphen_points_in(word: &str, opts: &HyphenationOptions, patterns: bool) - points_for(word, opts, if patterns { Language::English } else { Language::None }) } -/// Apply exceptions first, then language rules and paragraph limits, protecting Indic clusters. +/// Apply exceptions first, then language rules and paragraph limits, protecting Indic and +/// craft-proof clusters. pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Language) -> Vec<usize> { if let Some(ex) = exception_for(word) { let mut points = match ex { Exception::Never => vec![], Exception::Only(pts) => lowercase_points_to_word(word, &pts), }; - if matches!(language, Language::Indic(_)) { + if matches!(language, Language::Indic(_) | Language::Proof(_)) { indic::retain_boundaries(word, &mut points); } return points; @@ -241,8 +256,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua if n <= longer_than || !c.iter().all(|&ch| is_word_char(ch)) { return vec![]; } - // A capitalised run like "NASA" or a proper name stays whole only when all caps. - if c.iter().all(|c| c.is_uppercase()) { + // A capitalised run like "NASA" or a proper name stays whole only when all caps. Combining + // marks have no case, so a decomposed capital ("O" + U+0308) counts by its letter. + if c.iter().filter(|&&ch| !unicode_normalization::char::is_combining_mark(ch)).all(|c| c.is_uppercase()) { return vec![]; } if !opts.capitalized && c.first().is_some_and(|c| c.is_uppercase()) { @@ -250,8 +266,9 @@ pub(crate) fn points_for(word: &str, opts: &HyphenationOptions, language: Langua } let before = usize::try_from(opts.after_first).unwrap_or(usize::MAX).max(1); let after = usize::try_from(opts.before_last).unwrap_or(usize::MAX).max(1); - if let Language::Indic(index) = language { - let mut points = indic::points(word, usize::from(index)); + if let Language::Indic(index) | Language::Proof(index) = language { + let mut points = + if matches!(language, Language::Indic(_)) { indic::points(word, usize::from(index)) } else { proof::points(word, usize::from(index)) }; points.retain(|p| *p >= before && n.saturating_sub(*p) >= after); indic::retain_boundaries(word, &mut points); return points; @@ -308,6 +325,112 @@ pub(crate) fn with_hyphenation_exceptions_for_test(source: &str, f: impl FnOnce( #[cfg(test)] mod tests { use super::*; + use craft_proof::hyphen::Patterns; + + /// Paragraph options that let every point through: words of any length, one letter each side. + fn open() -> HyphenationOptions { + HyphenationOptions { words_longer_than: 0, after_first: 1, before_last: 1, ..Default::default() } + } + + /// Bulgarian, Turkish and Russian break by their own syllable rules in every build, with + /// regional tags too. + #[test] + fn rule_languages_break_by_their_own_rules() { + for (tags, word, points) in [ + (["bg", "bg-BG"], "планина", vec![3, 5]), + (["tr", "TR-cy"], "öğrenci", vec![2, 5]), + (["tr", "tr-TR"], "kardeş", vec![3]), + (["ru", "ru-RU"], "родина", vec![2, 4]), + (["ru", "RU"], "сестра", vec![3]), + ] { + for tag in tags { + assert_eq!(hyphen_points_for_language(word, &open(), Some(tag)), points, "{tag}: {word}"); + } + } + // Capitals keep their points. + assert_eq!(hyphen_points_for_language("Родина", &open(), Some("ru")), vec![2, 4]); + } + + /// German, Polish, Portuguese and Italian break at their own TeX patterns when craft-proof + /// embeds them, and not at all otherwise (two letters on each side, as TeX's defaults keep). + #[test] + fn pattern_languages_break_at_their_own_patterns() { + let open = || HyphenationOptions { after_first: 2, before_last: 2, ..open() }; + for (tags, patterns, word, points) in [ + (["de", "de-CH"], Patterns::de(), "Silbentrennung", vec![3, 6, 10]), + (["pl", "pl-PL"], Patterns::pl(), "kobieta", vec![2, 5]), + (["pt", "pt-BR"], Patterns::pt(), "computador", vec![3, 5, 7]), + (["it", "it-CH"], Patterns::it(), "montagna", vec![3, 5]), + ] { + for tag in tags { + let got = hyphen_points_for_language(word, &open(), Some(tag)); + if patterns.is_empty() { + assert!(got.is_empty(), "{tag}: {word}: no patterns embedded, no English fallback: {got:?}"); + } else { + assert_eq!(got, points, "{tag}: {word}"); + } + } + } + // A letter outside the language's patterns sends craft-proof to a general syllable + // heuristic, which isn't the language's own: the word stays whole. + for (tag, word) in [("de", "Søndergaard"), ("pl", "Müllerowa"), ("pt", "Łódzkaliano"), ("it", "Łódzkaliano")] { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + } + + /// A word outside its language's script stays whole: craft-proof would hyphenate it as English. + #[test] + fn other_scripts_in_a_language_get_no_english_points() { + for (tag, word) in [("ru", "typography"), ("bg", "typography"), ("ru", "Москваcity"), ("bg", "ёжикова"), ("tr", "родина")] + { + assert!(hyphen_points_for_language(word, &open(), Some(tag)).is_empty(), "{tag}: {word}"); + } + // A combining stress mark in a Russian word, and a joiner in a German one. + assert!(hyphen_points_for_language("моло\u{301}ко", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Silben\u{200d}trennung", &open(), Some("de")).is_empty()); + for tag in ["fr", "es", "hr", "cs", "sr", "nl", "sa", "ur", "x-none", "zz"] { + assert!(hyphen_points_for_language("typography", &open(), Some(tag)).is_empty(), "{tag}"); + assert!(hyphen_points_for_language("родина", &open(), Some(tag)).is_empty(), "{tag}"); + } + } + + /// A decomposed word breaks as its composed spelling does, at the matching characters, and a + /// decomposed all-capitals word stays whole as the composed one does. + #[test] + fn decomposed_words_break_as_composed_ones() { + for tag in ["ru", "bg"] { + let composed = hyphen_points_for_language("чайник", &open(), Some(tag)); + assert!(!composed.is_empty(), "{tag}"); + // `и` + U+0306 is `й`: points after it move one character on. + let shifted: Vec<usize> = composed.iter().map(|&p| if p >= 3 { p + 1 } else { p }).collect(); + assert_eq!(hyphen_points_for_language("чаи\u{306}ник", &open(), Some(tag)), shifted, "{tag}"); + } + assert!(hyphen_points_for_language("ÖĞRENCİ", &open(), Some("tr")).is_empty()); + assert!(hyphen_points_for_language("O\u{308}ĞRENCİ", &open(), Some("tr")).is_empty(), "decomposed capitals"); + assert_eq!(hyphen_points_for_language("o\u{308}ğrenci", &open(), Some("tr")), vec![3, 6]); + } + + /// The paragraph's limits and the Preferences exceptions apply to the new languages as they + /// do to English. + #[test] + fn limits_and_exceptions_apply_in_the_rule_languages() { + let d = HyphenationOptions::default(); + // 3 letters each side by default: "ро-ди-на" keeps neither point, "сес-тра" keeps its one. + assert!(hyphen_points_for_language("родина", &d, Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("сестра", &d, Some("ru")), vec![3]); + assert!(hyphen_points_for_language("сестра", &HyphenationOptions { words_longer_than: 6, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("Сестра", &HyphenationOptions { capitalized: false, ..d.clone() }, Some("ru")).is_empty()); + assert!(hyphen_points_for_language("СЕСТРА", &d, Some("ru")).is_empty(), "all capitals"); + assert!(hyphen_points_for_language("", &open(), Some("ru")).is_empty()); + assert!(hyphen_points_for_language("я", &open(), Some("ru")).is_empty()); + with_exceptions("родина, kar-deş", || { + assert!(hyphen_points_for_language("родина", &open(), Some("ru")).is_empty()); + assert_eq!(hyphen_points_for_language("kardeş", &d, Some("tr")), vec![3], "marked points ignore the limits"); + }); + with_exceptions("ро-дина", || { + assert_eq!(hyphen_points_for_language("родина", &open(), Some("ru")), vec![2]); + }); + } fn with_exceptions(source: &str, f: impl FnOnce()) { with_hyphenation_exceptions_for_test(source, f); @@ -319,9 +442,15 @@ mod tests { for l in [None, Some("en-US"), Some("en-GB"), Some("EN-gb"), Some("en")] { assert!(language_has_patterns(l), "{l:?}"); } - for l in [Some("de"), Some("fr"), Some("pt"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { + for l in [Some("fr"), Some("es"), Some("hr"), Some("cs"), Some("nl"), Some("eng"), Some("x-unknown"), Some(""), Some("é")] { assert!(!language_has_patterns(l), "{l:?}"); } + for l in ["bg", "tr", "ru", "BG-bg", "tr-CY", "ru-RU"] { + assert!(language_has_patterns(Some(l)), "{l}"); + } + for (l, embedded) in [("de", Patterns::de()), ("pl", Patterns::pl()), ("pt", Patterns::pt()), ("it", Patterns::it())] { + assert_eq!(language_has_patterns(Some(l)), !embedded.is_empty(), "{l}"); + } for tag in indic::TAGS { assert!(language_has_patterns(Some(tag))); assert!(language_has_patterns(Some(&format!("{}-IN", tag.to_uppercase())))); diff --git a/crates/text/src/hyphen/proof.rs b/crates/text/src/hyphen/proof.rs new file mode 100644 index 0000000000..05d5f4634b --- /dev/null +++ b/crates/text/src/hyphen/proof.rs @@ -0,0 +1,76 @@ +//! Break points from craft-proof for the languages it has rules or patterns of its own for: +//! German, Polish, Portuguese and Italian (hyph-utf8's TeX patterns, embedded only when craft-proof +//! is built with `CRAFT_I18N_DIR`), Bulgarian and Turkish (syllable rules) and Russian (word-division +//! rules). craft-proof hyphenates any other word as English; those points are dropped here, so a +//! word outside its language's script, or one these rules don't cover, stays whole. + +use craft_proof::hyphen::{Patterns, ProofLang, Source, word_breaks_in}; +use unicode_normalization::UnicodeNormalization; +use unicode_script::{Script, UnicodeScript}; + +pub(super) const TAGS: [&str; 7] = ["de", "pl", "pt", "it", "bg", "tr", "ru"]; + +fn lang(index: usize) -> Option<ProofLang> { + Some(match *TAGS.get(index)? { + "de" => ProofLang::De, + "pl" => ProofLang::Pl, + "pt" => ProofLang::Pt, + "it" => ProofLang::It, + "bg" => ProofLang::Bg, + "tr" => ProofLang::Tr, + "ru" => ProofLang::Ru, + _ => return None, + }) +} + +/// The pattern file of a pattern language, `None` for the languages with rules. +fn patterns(lang: ProofLang) -> Option<&'static Patterns> { + match lang { + ProofLang::De => Some(Patterns::de()), + ProofLang::Pl => Some(Patterns::pl()), + ProofLang::Pt => Some(Patterns::pt()), + ProofLang::It => Some(Patterns::it()), + _ => None, + } +} + +/// Whether the language has break points in this build: the rule languages always, the pattern +/// languages when their patterns are embedded. +pub(super) fn available(index: usize) -> bool { + lang(index).is_some_and(|l| patterns(l).is_none_or(|p| !p.is_empty())) +} + +/// A Latin letter or a combining mark. +fn latin(c: char) -> bool { + matches!(c.script(), Script::Latin | Script::Inherited) && c != '\u{200c}' && c != '\u{200d}' +} + +/// A Cyrillic letter, as craft-proof's Russian rules read them. +fn cyrillic(c: char) -> bool { + matches!(c, '\u{0400}'..='\u{052F}') && c.is_alphabetic() +} + +/// Whether `word` is written in the language's script, and the sources of points that come from +/// the language's own rules or patterns. A Cyrillic word is checked composed, as craft-proof +/// hyphenates it: `и` + U+0306 is `й`, while a stress mark, which composes with nothing, is not a +/// letter. +fn fits(lang: ProofLang, word: &str) -> Option<&'static [Source]> { + let all = |f: fn(char) -> bool| word.chars().all(f); + let composed_cyrillic = || word.nfc().all(cyrillic); + match lang { + ProofLang::De | ProofLang::Pl | ProofLang::Pt | ProofLang::It => all(latin).then_some(&[Source::Patterns, Source::Dictionary]), + ProofLang::Tr => word.chars().all(|c| latin(c) || matches!(c, '\'' | '’')).then_some(&[Source::Rules]), + ProofLang::Bg => composed_cyrillic().then_some(&[Source::Rules]), + ProofLang::Ru => composed_cyrillic().then_some(&[Source::Heuristic]), + _ => None, + } +} + +/// Character-index candidates for one language, before the paragraph's limits; empty when the +/// word isn't in the language's script or the language's own rules give it none. +pub(super) fn points(word: &str, index: usize) -> Vec<usize> { + let Some(lang) = lang(index) else { return vec![] }; + let Some(sources) = fits(lang, word) else { return vec![] }; + let (points, source) = word_breaks_in(word, lang); + if sources.contains(&source) { points } else { vec![] } +} diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 351c698451..80bd7c783a 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1108,18 +1108,49 @@ fn each_run_hyphenates_in_its_own_language() { let saved_without_one = hyphens(None); assert!(saved_without_one > 0, "some words hyphenated"); assert_eq!(hyphens(Some("en-GB")), saved_without_one); - assert_eq!(hyphens(Some("de")), 0, "German has no break points yet"); + assert_eq!(hyphens(Some("fr")), 0, "French has no break points yet"); + assert_eq!(hyphens(Some("ru")), 0, "English words in a Russian run are not hyphenated as English"); assert_eq!(hyphens(Some("x-from-a-file")), 0, "a tag that isn't known has no hyphenation"); - // both in one paragraph: the English run breaks and the German one doesn't + // both in one paragraph: the English run breaks and the French one doesn't let mut t = area(&format!("{text} {text}"), style(14.0), frame, Justify::Left); t.para.hyphenate = true; - edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("de".into())); + edit::style_range(&mut t.runs, text.len(), 2 * text.len() + 1, |s| s.language = Some("fr".into())); let l = layout(db(), &t); let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); assert!(!at.is_empty() && at.iter().all(|b| *b < text.len()), "hyphens only in the English run: {at:?}"); } +/// A justified Russian paragraph in a narrow frame breaks its long words at the Russian rules' +/// points with either composer, and not at all with Hyphenate off. +#[test] +fn a_russian_run_hyphenates_at_russian_break_points() { + let text = "Государственное законодательство регулирует достопримечательности."; + let frame = Rect::new(0.0, 0.0, 120.0, 600.0); + let st = CharStyle { language: Some("ru-RU".into()), ..style(14.0) }; + for composer in [Composer::EveryLine, Composer::SingleLine] { + let mut t = area(text, st.clone(), frame, Justify::JustifyLeft); + t.para.composer = composer; + t.para.hyphenate = true; + let l = layout(db(), &t); + let at: Vec<usize> = l.glyphs.iter().filter(|g| g.len == 0).map(|g| g.byte).collect(); + assert!(!at.is_empty(), "{composer:?}: some words hyphenated"); + for b in at { + // The word the hyphen splits, and where in it the line ends. + let start = text[..b].rfind(' ').map_or(0, |i| i + 1); + let end = text[b..].find([' ', '.']).map_or(text.len(), |i| b + i); + let word = &text[start..end]; + let point = text[start..b].chars().count(); + assert!( + hyphen::hyphen_points_for_language(word, &t.para.hyphenation, Some("ru")).contains(&point), + "{composer:?}: {word} broken after {point} letters" + ); + } + t.para.hyphenate = false; + assert_eq!(layout(db(), &t).glyphs.iter().filter(|g| g.len == 0).count(), 0, "{composer:?}: Hyphenate off"); + } +} + #[test] fn hyphenated_layout_adds_hyphens() { let text = "Extraordinarily comprehensive typographical considerations notwithstanding everything."; diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index f232d265e9..18d371b420 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,8 +12,8 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, inflate, - inflate_each, inflate_together, plane, plane_face_map, + Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, + extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 18ef7d6d1b..cc8881d2d9 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -28,7 +28,7 @@ pub(crate) use build::PLANES; use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; pub use build::{extrude, plane}; -pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; +pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; #[cfg(test)] use inflate::GRID_WORK; pub(crate) use inflate::inflate_faces; diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index d84dcc5ee6..ac99348ba3 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -174,6 +174,95 @@ pub fn plane_face_map(bounds: Rect, view: View) -> Option<FaceMap> { Some(FaceMap::new(&camera, &placing, true)) } +/// A planar face in its solid's mesh ([`crate::Mesh`]): where the points of the art's plane lie +/// before projection, in the mesh's coordinates (y up), and the face's outward normal there. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MeshFace { + /// An art point `p` lies at `x · (p.x - centre.x) + y · (p.y - centre.y) + at`, with the art's + /// center at `at`. + x: V3, + y: V3, + centre: Point, + at: V3, + normal: V3, + /// A plane's mesh turns its normal toward the viewer, so its triangles face either way. + either_side: bool, +} + +/// From the effects' view space (y down) to the mesh's (y up). +fn mesh_space(v: V3) -> V3 { + V3(v.0, -v.1, v.2) +} + +impl MeshFace { + fn new(camera: &Camera, placing: &Placing, centre: Point, side: f64, either_side: bool) -> Self { + let (x, y, _) = placing.frame(); + let at = mesh_space(placing.place(centre)); + let normal = mesh_space(camera.rotate(V3(0.0, 0.0, side))).unit(); + Self { x: mesh_space(x), y: mesh_space(y), centre, at, normal, either_side } + } + + /// The art point that mesh point `m` shows, when `m` lies on the face's plane and a triangle + /// with unit normal `n` there belongs to the face. `None` otherwise, and when the face has no + /// area (a taper of 0 at the back). + pub fn art_point(&self, m: [f64; 3], n: [f64; 3]) -> Option<Point> { + let facing = self.normal.dot(V3(n[0], n[1], n[2])); + let facing = if self.either_side { facing.abs() } else { facing }; + // A NaN normal faces no way. + let faces = facing > 1.0 - 1e-6; + if !faces { + return None; + } + // Measured from the art's center, so the tolerance follows the solid's size and not where + // the art lies on the page. + let d = V3(m[0], m[1], m[2]).sub(self.at); + let (xx, xy, yy) = (self.x.dot(self.x), self.x.dot(self.y), self.y.dot(self.y)); + let det = xx * yy - xy * xy; + let spans = xx > 1e-24 && yy > 1e-24 && det >= 1e-12 * xx * yy; + if !spans { + return None; + } + let (bx, by) = (self.x.dot(d), self.y.dot(d)); + let (px, py) = ((bx * yy - by * xy) / det, (xx * by - xy * bx) / det); + let on = V3(self.x.0 * px + self.y.0 * py, self.x.1 * px + self.y.1 * py, self.x.2 * px + self.y.2 * py); + let off = d.sub(on); + let size = 1.0 + d.dot(d).sqrt(); + let p = Point::new(self.centre.x + px, self.centre.y + py); + (p.x.is_finite() && p.y.is_finite() && off.dot(off).sqrt() <= 1e-6 * size).then_some(p) + } +} + +/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with +/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 +/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, +/// and for invalid bounds. +pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return (face == PlanarFace::Front).then(|| plane_mesh_face(bounds, view)).flatten(); + } + if !o.cap { + return None; + } + let camera = Camera::new(view, bounds, o.depth); + let (t, side) = match face { + PlanarFace::Front => (0.0, 1.0), + PlanarFace::Back => (1.0, -1.0), + }; + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); + Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) +} + +/// The plane [`super::plane`] turns art with `bounds` into, with `view`, in its mesh +/// ([`MeshFace`]). +pub fn plane_mesh_face(bounds: Rect, view: View) -> Option<MeshFace> { + check_bounds(bounds).ok()?; + let camera = Camera::new(view, bounds, 0.0); + let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); + Some(MeshFace::new(&camera, &placing, bounds.center(), 1.0, true)) +} + #[cfg(test)] #[path = "tests_face_map.rs"] mod tests; diff --git a/crates/three-d/src/solid/tests_face_map.rs b/crates/three-d/src/solid/tests_face_map.rs index 31644beda5..ebbe95448a 100644 --- a/crates/three-d/src/solid/tests_face_map.rs +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -1,7 +1,7 @@ use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; use super::super::{Extrude, Facet, PlanarFace, View, extrude, plane}; -use super::{FaceMap, NEAREST, extrude_face_map, plane_face_map}; +use super::{FaceMap, MeshFace, NEAREST, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; fn square() -> (PathData, Rect) { let mut b = BezPath::new(); @@ -143,6 +143,70 @@ fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() { assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for"); } +/// The art point of every corner of each triangle of `mesh` that `face` takes, and how many +/// triangles it takes. +fn mesh_art(mesh: &crate::Mesh, face: &MeshFace) -> (Vec<Point>, usize) { + let (mut points, mut taken) = (vec![], 0); + for t in &mesh.triangles { + let corners: Option<Vec<Point>> = t.iter().map(|&i| face.art_point(mesh.positions[i as usize], mesh.normals[i as usize])).collect(); + if let Some(c) = corners { + points.extend(c); + taken += 1; + } + } + (points, taken) +} + +#[test] +fn a_caps_mesh_corners_go_back_to_the_art_they_were_made_from() { + let (path, bounds) = square(); + let bevel = crate::Bevel { width: 4.0, height: 4.0, ..Default::default() }; + let options = Extrude { twist: 30.0, taper: 0.5, bevel: Some(bevel), ..Extrude::default() }; + let view = turned(40.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + // The bevel's width sets the walls, and the back cap, out from the front's outline. + let outset = bounds.inflate(4.0, 4.0); + for (face, cap) in [(PlanarFace::Front, bounds), (PlanarFace::Back, outset)] { + let mesh_face = extrude_mesh_face(bounds, options, view, face).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // A square cap is two triangles, and none of the bevel's or the walls' triangles are + // taken. The art points undo the back's twist and taper. + assert_eq!(taken, 2, "{face:?}"); + for p in points { + let near = corners(cap).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{face:?}: {p:?} is {near} from the cap's corners"); + } + } + // A hollow solid has no caps, and a plane's mesh has only the front, facing either way. + assert_eq!(extrude_mesh_face(bounds, Extrude { cap: false, ..options }, view, PlanarFace::Front), None); + let plane = crate::plane_mesh(&path, FillRule::NonZero, bounds, view).unwrap(); + let (points, taken) = mesh_art(&plane, &plane_mesh_face(bounds, view).unwrap()); + assert_eq!(taken, plane.triangles.len()); + assert!(points.iter().all(|p| corners(bounds).iter().any(|c| c.distance(*p) < 1e-6)), "{points:?}"); + assert_eq!(extrude_mesh_face(bounds, Extrude { depth: 0.0, ..options }, view, PlanarFace::Back), None); +} + +#[test] +fn a_cap_far_from_the_page_origin_takes_none_of_a_step_bevels_treads() { + let (path, bounds) = square(); + let far = vectorcraft_geom::kurbo::Affine::translate((1e7, 1e7)); + let path = PathData::from_bezpath(&(far * path.to_bezpath())); + let bounds = far.transform_rect_bbox(bounds); + let bevel = crate::Bevel { width: 4.0, height: 4.0, shape: crate::BevelShape::Step, ..Default::default() }; + let options = Extrude { bevel: Some(bevel), ..Extrude::default() }; + let view = turned(0.0); + let mesh = crate::extrude_mesh(&path, FillRule::NonZero, bounds, options, view).unwrap(); + let mesh_face = extrude_mesh_face(bounds, options, view, PlanarFace::Front).unwrap(); + let (points, taken) = mesh_art(&mesh, &mesh_face); + // The treads face the same way as the cap, a few points behind it: only the cap's two + // triangles are taken, wherever the art lies on the page. + assert_eq!(taken, 2); + for p in points { + let near = corners(bounds).iter().map(|c| c.distance(p)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{p:?} is {near} from the cap's corners"); + } +} + #[test] fn the_mapped_part_of_a_rectangle_stops_before_the_eye() { let (_, bounds) = square(); diff --git a/crates/tools/src/addons.rs b/crates/tools/src/addons.rs index c75a73882a..ca8645ffc8 100644 --- a/crates/tools/src/addons.rs +++ b/crates/tools/src/addons.rs @@ -1,8 +1,9 @@ //! The tools of VectorCraft's built-in add-ons. They aren't in the toolbars as they ship: the All //! Tools drawer lists them (under their add-on's heading) so they can be added, and each add-on's -//! submenu selects them. Tool gestures emit engine commands. The Trim at Crossings Tool is the -//! exception: it is in the Scissors tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and -//! the All Tools drawer show it, as well as in Path Precision Tools' submenu. +//! submenu selects them. Tool gestures emit engine commands. Two tools are the exceptions: the Trim +//! at Crossings Tool is in the Scissors tool's group and the Enclosing Lasso Tool is in the Lasso +//! tool's group ([`crate::TOOL_GROUPS`]), where the toolbars and the All Tools drawer show them, as +//! well as in their add-ons' submenus. pub mod anchor_eraser; pub mod box3d; @@ -37,25 +38,17 @@ pub const SMART_PEN: &[ToolInfo] = &[ToolInfo { id: smart_pen::ID, label: "Smart pub const CONTOUR: &[ToolInfo] = &[ToolInfo { id: contour::ID, label: "Contour Tool", shortcut: None, icon: "tool-contour" }]; -pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, label: "Enclosing Lasso Tool", shortcut: None, icon: "tool-lasso" }]; - pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }]; pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the /// heading the All Tools drawer lists it under (its add-on's name). -const HEADED: &[(&[ToolInfo], &str)] = &[ - (PATH_TOOLS, "Path Precision Tools"), - (SMART_PEN, "Smart Pen"), - (ENCLOSING_LASSO, "Enclosing Lasso"), - (CONTOUR, "Contour"), - (BOX_3D, "3D Box"), - (POLYGONAL_LASSO, "Polygonal Lasso"), -]; +const HEADED: &[(&[ToolInfo], &str)] = + &[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (CONTOUR, "Contour"), (BOX_3D, "3D Box"), (POLYGONAL_LASSO, "Polygonal Lasso")]; /// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]). -pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO]; +pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, CONTOUR, BOX_3D, POLYGONAL_LASSO]; /// The heading the All Tools drawer lists tool `id` under: its add-on's name. pub fn heading(id: &str) -> Option<&'static str> { @@ -97,7 +90,6 @@ mod tests { } assert!(PATH_TOOLS.iter().all(|t| heading(t.id) == Some("Path Precision Tools"))); assert_eq!(heading(smart_pen::ID), Some("Smart Pen")); - assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso")); assert_eq!(heading(contour::ID), Some("Contour")); assert_eq!(heading(box3d::ID), Some("3D Box")); assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso")); @@ -122,4 +114,21 @@ mod tests { assert!(!GROUPS.iter().any(|g| g.iter().any(|t| t.id == trim::ID)), "not listed again under the add-on"); assert_eq!(crate::catalog::all_tools().filter(|t| t.id == trim::ID).count(), 1); } + + /// The Enclosing Lasso Tool is in the Lasso tool's group, right after the Lasso, with no + /// default shortcut, listed once, and still made by its add-on. + #[test] + fn enclosing_lasso_is_in_the_lasso_group_once() { + let id = enclosing_lasso::ID; + let groups: Vec<_> = crate::TOOL_GROUPS.iter().filter(|g| g.iter().any(|t| t.id == id)).collect(); + assert_eq!(groups.len(), 1); + let ids: Vec<_> = groups[0].iter().map(|t| t.id).collect(); + assert_eq!(ids, ["lasso", id]); + let info = crate::tool_info(id).expect("catalogued"); + assert_eq!((info.label, info.shortcut, info.icon), ("Enclosing Lasso Tool", None, "tool-lasso")); + assert_eq!(crate::tool_info("lasso").and_then(|t| t.shortcut), Some("Q"), "the Lasso keeps its shortcut"); + assert_eq!(create(id).map(|tool| tool.id()), Some(id)); + assert!(heading(id).is_none(), "not listed again under the add-on"); + assert_eq!(crate::catalog::all_tools().filter(|t| t.id == id).count(), 1); + } } diff --git a/crates/tools/src/addons/polygonal_lasso.rs b/crates/tools/src/addons/polygonal_lasso.rs index 1838293b66..b212943117 100644 --- a/crates/tools/src/addons/polygonal_lasso.rs +++ b/crates/tools/src/addons/polygonal_lasso.rs @@ -167,6 +167,13 @@ impl Tool for PolygonalLassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); let mut line = self.vertices.clone(); diff --git a/crates/tools/src/builder/lookup.rs b/crates/tools/src/builder/lookup.rs index 0d7acd7e67..7dfa249586 100644 --- a/crates/tools/src/builder/lookup.rs +++ b/crates/tools/src/builder/lookup.rs @@ -38,14 +38,20 @@ fn named(n: &Node, name: &str) -> bool { n.name.as_deref() == Some(name) } +/// Is `n` a Live Paint group's part named `name` ([`FACE_NAME`] or [`EDGE_NAME`]): a path with that +/// name? Type, groups and other objects drawn in the group under such a name are not parts. +fn part(n: &Node, name: &str) -> bool { + named(n, name) && n.path_data().is_some() +} + /// Face children of a Live Paint group (paint order). pub fn faces(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, FACE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, FACE_NAME)).collect()).unwrap_or_default() } /// Edge children of a Live Paint group. pub fn edges(group: &Node) -> Vec<&Arc<Node>> { - group.children().map(|c| c.iter().filter(|n| named(n, EDGE_NAME)).collect()).unwrap_or_default() + group.children().map(|c| c.iter().filter(|n| part(n, EDGE_NAME)).collect()).unwrap_or_default() } /// The hidden sources group of a Live Paint group. diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 386dfeb4a5..529aa80d18 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -24,7 +24,11 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("groupSelection", "Group Selection Tool", None, "tool-group-select"), ], &[t("magicWand", "Magic Wand Tool", Some("Y"), "tool-magic-wand")], - &[t("lasso", "Lasso Tool", Some("Q"), "tool-lasso")], + &[ + t("lasso", "Lasso Tool", Some("Q"), "tool-lasso"), + // Enclosing Lasso's tool, kept out of `addons::GROUPS` so that `all_tools` lists it once. + t(crate::addons::enclosing_lasso::ID, "Enclosing Lasso Tool", None, "tool-lasso"), + ], &[ t("pen", "Pen Tool", Some("P"), "tool-pen"), t("addAnchor", "Add Anchor Point Tool", Some("+"), "tool-pen-add"), diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 0082a01a99..6586cb8586 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -762,6 +762,13 @@ impl Tool for DirectSelectionTool { fn options(&self) -> Value { self.mesh.options() } + /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group + /// Selection, which selects whole objects, does not. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" && !self.group { + self.mesh.set_options(value); + } + } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved /// goes back and the tool waits for the next press (#1743). diff --git a/crates/tools/src/meshblend.rs b/crates/tools/src/meshblend.rs index 21ee30eed6..c9ab307028 100644 --- a/crates/tools/src/meshblend.rs +++ b/crates/tools/src/meshblend.rs @@ -360,6 +360,12 @@ impl Tool for MeshTool { fn options(&self) -> serde_json::Value { self.edit.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &serde_json::Value) { + if key == "meshPoints" { + self.edit.set_options(value); + } + } fn busy(&self) -> bool { self.edit.dragging() } diff --git a/crates/tools/src/meshedit.rs b/crates/tools/src/meshedit.rs index 1069c90eb5..71ae329c4c 100644 --- a/crates/tools/src/meshedit.rs +++ b/crates/tools/src/meshedit.rs @@ -34,6 +34,13 @@ pub fn grid_of(n: &Node) -> Option<Cow<'_, GradientMesh>> { } } +/// The `{id, index}` entries of a `meshPoints` option ([`MeshEdit::options`]); malformed entries +/// are left out. +pub fn points_of(value: &Value) -> Vec<(NodeId, usize)> { + let Some(v) = value.as_array() else { return vec![] }; + v.iter().filter_map(|p| Some((NodeId(p.get("id")?.as_u64()?), usize::try_from(p.get("index")?.as_u64()?).ok()?))).collect() +} + /// Can `n` have an editable grid ([`grid_of`])? Its kind alone answers, without building the grid. pub fn may_have_grid(n: &Node) -> bool { match &n.kind { @@ -66,6 +73,16 @@ pub fn part_points(m: &GradientMesh, p: Point, point_tol: f64, line_tol: f64) -> Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) } +/// The points of gradient mesh `m` that a color dropped at `p`, or an Eyedropper click there, +/// recolors: the point within `point_tol`, else the four points around the patch under `p`. +pub fn color_points(m: &GradientMesh, p: Point, point_tol: f64) -> Option<Vec<usize>> { + if let Some(i) = m.point_near(p, point_tol) { + return Some(vec![i]); + } + let (r, c, ..) = m.locate(p)?; + Some(vec![m.idx(r, c), m.idx(r, c + 1), m.idx(r + 1, c), m.idx(r + 1, c + 1)]) +} + /// What a press on a mesh grabs: the mesh, the point and (on the focused point) a handle. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MeshGrab { @@ -307,6 +324,16 @@ impl MeshEdit { json!({"meshPoints": self.picked.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect::<Vec<_>>()}) } + /// Pick the points a `meshPoints` option lists (see [`points_of`]), with none focused: the + /// points the Eyedropper held when the tool switched back. + pub fn set_options(&mut self, value: &Value) { + if self.drag.is_some() { + return; + } + self.picked = points_of(value).into_iter().collect(); + (self.focus, self.click) = (None, None); + } + /// The picked points of the meshes `shown` accepts, filled, and the focused point's handles /// (lines and ends). pub fn overlays(&self, cx: &ToolContext, shown: &dyn Fn(NodeId) -> bool) -> Vec<Overlay> { @@ -637,4 +664,21 @@ mod tests { assert_eq!(out, vec![Action::Exec("select.set".into(), json!({"ids": [m.0]})), Action::Begin("Move Mesh Points".into())]); assert_eq!(picked(&t), set(&[(100.0, 100.0), (150.0, 100.0), (100.0, 150.0), (150.0, 150.0)])); } + + /// The tools that pick mesh points pick again the points a `meshPoints` option lists (those the + /// Eyedropper held), leaving malformed entries out; Group Selection picks none. + #[test] + fn mesh_point_tools_take_back_the_eyedroppers_picks() { + let points = json!([{"id": 7, "index": 2}, {"id": 7}, {"id": 7, "index": 0}]); + for id in ["mesh", "directSelection", "lasso", crate::addons::polygonal_lasso::ID] { + let mut t = crate::create(id); + t.set_option("meshPoints", &points); + assert_eq!(picked(&*t), [0, 2], "{id}"); + t.set_option("meshPoints", &json!([])); + assert!(picked(&*t).is_empty(), "{id}"); + } + let mut t = crate::create("groupSelection"); + t.set_option("meshPoints", &points); + assert!(picked(&*t).is_empty(), "Group Selection"); + } } diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index a83bf1bae6..eb1b8b3895 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -10,10 +10,20 @@ //! blend's steps, an envelope's distorted contents). Clicking an image samples its pixels //! (averaged over the options' raster sample size; a CMYK image gives its ink amounts). //! +//! With a gradient mesh selected, a click on one of its points gives that point the current solid +//! fill color, and a click inside one of its patches gives it to the patch's four points +//! (`object.mesh.setPointColor`). +//! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor //! {stop}`) and switches back to that tool. //! +//! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching +//! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools +//! switched to next. While a selected, editable mesh has picked points, a click or Shift-click on an image or +//! other art samples the color under the cursor into those points alone (`paint.sampleColor +//! {stroke: false, ids}` with those meshes, which recolors the points through `paint.setFill`). +//! //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. //! @@ -41,6 +51,28 @@ pub struct EyedropperTool { text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. brush_key_color: bool, + /// The gradient mesh points the tool switched from had picked, each a mesh and a point index. + mesh_points: Vec<(NodeId, usize)>, +} + +/// The point of each of `points` that a selected, editable gradient mesh in `cx` has. +fn live_points<'a>(cx: &'a ToolContext, points: &'a [(NodeId, usize)]) -> impl Iterator<Item = (NodeId, Point)> + 'a { + let editable = cx.doc.editable(); + points.iter().filter(move |(id, _)| cx.selection.contains(*id) && editable(*id)).filter_map(|(id, index)| { + let Some(NodeKind::Mesh(m)) = cx.doc.node(*id).map(|n| &n.kind) else { return None }; + Some((*id, m.points.get(*index)?.p)) + }) +} + +/// The selected, editable gradient meshes in `cx` with one of `points` picked, in range, each once. +fn picked_meshes(cx: &ToolContext, points: &[(NodeId, usize)]) -> Vec<NodeId> { + let mut ids: Vec<NodeId> = vec![]; + for (id, _) in live_points(cx, points) { + if !ids.contains(&id) { + ids.push(id); + } + } + ids } /// The colour of `paint` at `p` (gradients are sampled along their vector, radial ones honouring @@ -456,6 +488,21 @@ fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option<Color> { Some(Color::rgb(r, g, b)) } +/// The selected, editable gradient mesh and its points that an Eyedropper click at `p` recolors +/// ([`crate::meshedit::color_points`]): the topmost visible object within reach of `p` (locked art +/// included, clipping applied) must be that mesh, and the points are its point within reach of +/// `p`, else the four points around its patch under `p`. +fn selected_mesh_points(cx: &ToolContext, p: Point) -> Option<(NodeId, Vec<usize>)> { + let tol = cx.tol(5.0); + let opt = sample_options(cx); + let leaf = hit_test_visible(cx.doc, p, HitOptions { tol: opt.tol.max(tol), ..opt })?.leaf; + if !cx.selection.contains(leaf) || !cx.doc.editable()(leaf) { + return None; + } + let Some(NodeKind::Mesh(m)) = cx.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, crate::meshedit::color_points(m, p, tol)?)) +} + impl Tool for EyedropperTool { fn id(&self) -> &'static str { "eyedropper" @@ -474,6 +521,17 @@ impl Tool for EyedropperTool { return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; } let stop = self.stop.as_ref().zip(cx.gradient_stop); + // A plain click on a selected gradient mesh gives the fill color to the point there, else + // to the four points of the patch there. + if stop.is_none() + && !ev.mods.alt + && !ev.mods.shift + && let Paint::Solid { color, .. } = &cx.paint.fill + && let Some((id, points)) = selected_mesh_points(cx, ev.pos) + { + let params = json!({ "id": id.0, "points": points, "color": color_json(color), "keepModel": true }); + return vec![Action::Exec("object.mesh.setPointColor".into(), params)]; + } // Reading a source is independent of its editability. Only Alt's reverse operation // writes to the clicked object; Shift+Alt appends its appearance to the selection. let source = if ev.mods.alt && !ev.mods.shift && stop.is_none() { @@ -488,11 +546,20 @@ impl Tool for EyedropperTool { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0, how: true }))]; } let image = matches!(n.kind, NodeKind::Image(_)); - if !(ev.mods.shift || stop.is_some() || image) { + // Picked mesh points take only a color sampled from other art or an image: the sample goes + // to them as a fill, and to nothing else that is selected. A click on a mesh with picked + // points is handled as before. + let meshes = if stop.is_none() { picked_meshes(cx, &self.mesh_points) } else { vec![] }; + let meshes = if meshes.contains(&src) { vec![] } else { meshes }; + if !(ev.mods.shift || stop.is_some() || image || !meshes.is_empty()) { return vec![Action::Exec("appearance.copyFrom".into(), json!({ "source": src.0 }))]; } let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; let color = color_json(&c); + if !meshes.is_empty() { + let ids: Vec<u64> = meshes.iter().map(|id| id.0).collect(); + return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stroke": false, "ids": ids }))]; + } let Some((back, i)) = stop else { return vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color }))] }; let out = vec![Action::Exec("paint.sampleColor".into(), json!({ "color": color, "stop": i })), Action::SwitchTool(back.clone())]; self.stop = None; @@ -506,15 +573,21 @@ impl Tool for EyedropperTool { if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); o.insert("brushKeyColor".into(), json!(self.brush_key_color)); + if !self.mesh_points.is_empty() { + let points: Vec<Value> = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect(); + o.insert("meshPoints".into(), Value::Array(points)); + } } options } - /// Accept a stop target or the selection transferred from the Type tool. + /// Accept a stop target, or the selection or the mesh points picked, transferred from the + /// Type tool or a tool that picks mesh points. fn set_option(&mut self, key: &str, value: &Value) { match key { "stop" => self.stop = value.as_str().map(str::to_string), "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), + "meshPoints" => self.mesh_points = crate::meshedit::points_of(value), "textSelection" => self.text_selection.set_option(key, value), _ => {} } @@ -525,9 +598,13 @@ impl Tool for EyedropperTool { self.text_selection.after_command(cx) } - /// Keep the sampled character range highlighted without activating text input. + /// Keep the sampled character range highlighted without activating text input, and the picked + /// points of selected gradient meshes filled, as the tools that picked them show them. fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { - if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] } + let mut out = + if self.text_selection.options().get("editing").is_some_and(|v| !v.is_null()) { self.text_selection.overlays(cx) } else { vec![] }; + out.extend(live_points(cx, &self.mesh_points).map(|(_, p)| Overlay::Anchor { p, color: crate::draw2::FEEDBACK, filled: true, size: 5.0 })); + out } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { @@ -607,6 +684,82 @@ mod tests { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 400.0)).is_empty()); } + /// With points of a selected gradient mesh picked, a click on other art samples the color under + /// the cursor into those points as a fill, as a Shift-click does. Unselected, or with the picks + /// out of range, on a locked mesh, or on the mesh itself, the click copies the appearance as + /// before; Alt still applies in reverse. + #[test] + fn picked_mesh_points_take_the_color_a_click_samples() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let mesh = d.alloc_id(); + let grid = GradientMesh::from_surface(1, 1, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(mesh, NodeKind::Mesh(grid))).unwrap(); + let red = d.alloc_id(); + let mut art = (*filled_rect(Rect::new(300.0, 100.0, 350.0, 150.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)))).clone(); + art.id = red; + d.insert(Some(l), usize::MAX, art).unwrap(); + let p = paint(); + let mut s = Selection::default(); + s.set([mesh]); + let mut t = EyedropperTool::default(); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 1}, {"id": "x"}, {"id": mesh.0, "index": 3}])); + assert_eq!(t.options()["meshPoints"], json!([{"id": mesh.0, "index": 1}, {"id": mesh.0, "index": 3}]), "malformed entries are left out"); + // The picked points show filled while the mesh is selected. + let anchors: Vec<Point> = t + .overlays(&cx(&d, &s, &p)) + .into_iter() + .filter_map(|o| match o { + Overlay::Anchor { p, filled: true, .. } => Some(p), + _ => None, + }) + .collect(); + assert_eq!(anchors, [Point::new(200.0, 100.0), Point::new(200.0, 200.0)]); + assert!(t.overlays(&cx(&d, &Selection::default(), &p)).is_empty()); + let click = |t: &mut EyedropperTool, s: &Selection, m: Mods| { + t.pointer(&cx(&d, s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0).with_mods(m)) + }; + let sample = vec![Action::Exec( + "paint.sampleColor".into(), + json!({"color": color_json(&Color::rgb(1.0, 0.0, 0.0)), "stroke": false, "ids": [mesh.0]}), + )]; + assert_eq!(click(&mut t, &s, Mods::default()), sample); + assert_eq!(click(&mut t, &s, Mods { shift: true, ..Default::default() }), sample); + // Other selected art does not take the sample. + let mut both = Selection::default(); + both.set([mesh, red]); + assert_eq!(click(&mut t, &both, Mods::default()), sample, "only the picked mesh"); + let alt = click(&mut t, &s, Mods { alt: true, ..Default::default() }); + assert_eq!(alt, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0, "reverse": true}))]); + // The mesh deselected, the picks stand for nothing. + let copy = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": red.0}))]; + assert_eq!(click(&mut t, &Selection::default(), Mods::default()), copy); + // Selected again, as Direct Selection keeps them, the picks take the sample again. + assert_eq!(click(&mut t, &s, Mods::default()), sample, "the mesh selected again"); + // A click on the picked mesh itself (with no solid fill) copies its appearance as before, and + // a Shift-click samples into the active fill as before. + let mut unfilled = paint(); + unfilled.fill = Paint::None; + let on_mesh = + |t: &mut EyedropperTool, m: Mods| t.pointer(&cx(&d, &s, &unfilled), &PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(m)); + let own = vec![Action::Exec("appearance.copyFrom".into(), json!({"source": mesh.0}))]; + assert_eq!(on_mesh(&mut t, Mods::default()), own, "a click on the mesh"); + let shift = on_mesh(&mut t, Mods { shift: true, ..Default::default() }); + assert_eq!(shift, vec![Action::Exec("paint.sampleColor".into(), json!({"color": color_json(&Color::WHITE)}))], "a Shift-click on the mesh"); + // A locked mesh's picks stand for nothing. + let mut locked = d.clone(); + locked.node_mut(mesh).unwrap().locked = true; + let a = t.pointer(&cx(&locked, &s, &p), &PointerEvent::new(PointerKind::Down, 325.0, 125.0)); + assert_eq!(a, copy, "a locked mesh"); + assert!(t.overlays(&cx(&locked, &s, &p)).is_empty()); + t.set_option("meshPoints", &json!([{"id": mesh.0, "index": 4}])); + assert_eq!(click(&mut t, &s, Mods::default()), copy, "a point the mesh does not have"); + t.set_option("meshPoints", &json!([])); + assert!(t.options().get("meshPoints").is_none()); + assert_eq!(click(&mut t, &s, Mods::default()), copy); + } + /// On a clip group's mask edge, where the art it clips lies over it, the eyedropper copies the /// art's appearance, not the unpainted clipping path's (the selection tools take the path there). #[test] @@ -1429,6 +1582,70 @@ mod tests { assert_eq!(sampled_hex(&a), "#404040"); } + /// With a gradient mesh selected, a click on one of its points gives that point the fill color, + /// and a click inside a patch gives it to the patch's four points. Unselected, a click copies + /// the mesh's appearance as before, and Shift still samples. + #[test] + fn a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let red = color_json(&Color::rgb(1.0, 0.0, 0.0)); + let set = |points: Value| { + vec![Action::Exec("object.mesh.setPointColor".into(), json!({"id": id.0, "points": points, "color": red, "keepModel": true}))] + }; + let mut s = Selection::default(); + let click = |s: &Selection, p: &crate::PaintDefaults, x: f64, y: f64, m: Mods| { + EyedropperTool::default().pointer(&cx(&d, s, p), &PointerEvent::new(PointerKind::Down, x, y).with_mods(m)) + }; + let plain = Mods::default(); + let a = click(&s, &p, 125.0, 125.0, plain); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": id.0}))], "an unselected mesh"); + s.set([id]); + assert_eq!(click(&s, &p, 151.0, 149.0, plain), set(json!([4])), "the point near the click"); + assert_eq!(click(&s, &p, 125.0, 125.0, plain), set(json!([0, 1, 3, 4])), "the patch's four points"); + assert_eq!(click(&s, &p, 175.0, 175.0, plain), set(json!([4, 5, 7, 8]))); + let shift = Mods { shift: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, shift)[0], Action::Exec(c, _) if c == "paint.sampleColor")); + let alt = Mods { alt: true, ..Default::default() }; + assert!(matches!(&click(&s, &p, 125.0, 125.0, alt)[0], Action::Exec(c, v) if c == "appearance.copyFrom" && v["reverse"] == true)); + // Off the mesh, or with a fill that is not a solid color, nothing goes to its points. + assert!(click(&s, &p, 400.0, 400.0, plain).is_empty()); + p.fill = Paint::None; + assert!(matches!(&click(&s, &p, 125.0, 125.0, plain)[0], Action::Exec(c, _) if c == "appearance.copyFrom")); + } + + /// An unselected object on top of a selected mesh's point keeps the click: it copies that + /// object's appearance, and the mesh's points keep their colors. + #[test] + fn a_click_on_an_object_over_a_selected_mesh_copies_that_object() { + use vectorcraft_doc::{Document, GradientMesh}; + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mesh = GradientMesh::from_surface(2, 2, &|u, v| Point::new(100.0 + 100.0 * u, 100.0 + 100.0 * v), &|_, _| Color::WHITE); + d.insert(Some(l), 0, Node::new(id, NodeKind::Mesh(mesh))).unwrap(); + let top = d.alloc_id(); + let mut cover = (*filled_rect(vectorcraft_geom::Rect::new(140.0, 140.0, 160.0, 160.0), Paint::solid(Color::BLACK))).clone(); + cover.id = top; + d.insert(Some(l), usize::MAX, cover).unwrap(); + let mut p = paint(); + p.fill = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let mut s = Selection::default(); + s.set([id]); + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))]); + // Locked, it is still what the click samples. + d.node_mut(top).unwrap().locked = true; + let a = EyedropperTool::default().pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 150.0, 150.0)); + assert_eq!(a, vec![Action::Exec("appearance.copyFrom".into(), json!({"source": top.0}))], "a locked object on top"); + } + /// Finding the point in a mesh counts the points it looks at in every patch: a 20 × 20 mesh /// takes more than a thousand units of work. #[test] diff --git a/crates/tools/src/xform/wand.rs b/crates/tools/src/xform/wand.rs index e34630020f..d2074e386e 100644 --- a/crates/tools/src/xform/wand.rs +++ b/crates/tools/src/xform/wand.rs @@ -165,6 +165,13 @@ impl Tool for LassoTool { self.mesh.options() } + /// Pick the gradient mesh points the Eyedropper held (`meshPoints`). + fn set_option(&mut self, key: &str, value: &Value) { + if key == "meshPoints" { + self.mesh.set_options(value); + } + } + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id)); if self.active && self.points.len() >= 2 { diff --git a/crates/trace/src/params.rs b/crates/trace/src/params.rs index 7b850fc344..1fa8aaa2c3 100644 --- a/crates/trace/src/params.rs +++ b/crates/trace/src/params.rs @@ -38,11 +38,12 @@ pub enum Palette { #[serde(alias = "Limited")] Limited, /// As many colours as the image's tones need, up to [`FULL_TONE_MAX`] (photos, gradients): - /// `color_detail` sets how close two colours may be and stay apart. + /// `color_detail` sets how close two colours may be and stay apart. Before merging colors that + /// look alike, it splits to at least one color per step of `color_detail` where the image has that many. #[serde(alias = "Full Tone")] FullTone, /// Flat art (a few colours cover nearly all of it) traces with exactly those colours, anything - /// else as Full Tone. + /// else with as many as its tones need, without Full Tone's least count and merging close RGB colors. #[serde(alias = "Automatic")] Automatic, /// The most used colours of a swatch library ([`TraceParams::swatches`]), at most `colors` of @@ -243,7 +244,10 @@ pub fn preset(name: &str) -> Option<TraceParams> { // many as its tones need where it is not. // (Color detail 85: a colour on a hundredth of the picture is still one of its colours.) "auto color" => TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..color(6, 65.0, 60.0, 16, Method::Abutting) }, - "high fidelity photo" => color(64, 50.0, 50.0, 5, Method::Overlapping), + // A photo's tones: as many colors as they need (Full Tone), split until no color spans more + // than about 21 levels of a channel and into at least 85 (Color detail 85) before colors that + // look alike merge, as abutting shapes. VectorCraft's own values. + "high fidelity photo" => TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..color(64, 50.0, 50.0, 5, Method::Abutting) }, "low fidelity photo" => color(20, 50.0, 50.0, 10, Method::Overlapping), "3 colors" => color(3, 50.0, 50.0, 15, Method::Abutting), "6 colors" => color(6, 50.0, 50.0, 8, Method::Abutting), diff --git a/crates/trace/src/quantize.rs b/crates/trace/src/quantize.rs index ea8fa00ac8..a115cd3ce3 100644 --- a/crates/trace/src/quantize.rs +++ b/crates/trace/src/quantize.rs @@ -93,7 +93,7 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized let g = l.round().clamp(0.0, 255.0) as u8; [g, g, g] }); - let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[]); + let q = merge_mixed(compact(labels, palette.collect()), img.width as usize, img.height as usize, &[], Alike::Rgb); (if settles_wide(params) { settled_wide(q, img, &own, true) } else { settled(q, img, &own) }, vec![]) } // Logo mode traces without quantising; asked directly, it quantises like Color. @@ -175,12 +175,14 @@ pub(crate) fn quantize_keeping(img: &Raster, params: &TraceParams) -> (Quantized img.rgba.as_chunks::<4>().0.iter().map(|p| if p[3] < 128 { TRANSPARENT } else { lut[hk.key(p[0], p[1], p[2])] }).collect(); let palette = centers.iter().map(|c| [c[0].round() as u8, c[1].round() as u8, c[2].round() as u8]).collect(); let q = compact(labels, palette); - // A swatch library's colours are used as they are. + // A swatch library's colours are used as they are. Full Tone's colors merge only when + // they look alike (see `Alike`). if library { return (q, false); } + let alike = if params.palette == Palette::FullTone { Alike::Seen } else { Alike::Rgb }; let before = q.palette.len(); - let q = merge_mixed(q, img.width as usize, img.height as usize, &rare); + let q = merge_mixed(q, img.width as usize, img.height as usize, &rare, alike); let merged = q.palette.len() < before; (q, merged) }; @@ -309,16 +311,38 @@ pub(crate) fn tests_oklab(c: [u8; 3]) -> [f64; 3] { oklab(c.map(f64::from)) } +/// Which colors [`merge_mixed`] takes for one color that noise split. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Alike { + /// Close in RGB: under 30 levels apart and thoroughly mixed, or under 12 and mixed in patches. + /// Used for Grayscale and for every Color palette but Full Tone (Automatic included). + Rgb, + /// Close to the eye: under [`FULL_TONE_ALIKE`] apart in Oklab and thoroughly mixed, or under + /// [`FULL_TONE_PATCHES`] and mixed in patches (compression blocks). Full Tone's neighboring tones + /// of a smooth photo are about as close in RGB as noise makes one color, and mixed along their + /// soft border, so the RGB test would take most of them for one color. + Seen, +} + +/// How far apart (Oklab × 100) two thoroughly mixed Full Tone colors may lie and still be merged +/// as one color that noise split: a little more than the least difference one sees (see [`oklab`]). +const FULL_TONE_ALIKE: f64 = 5.0; + +/// How far apart (Oklab × 100) two Full Tone colors mixed in patches may lie and still be merged: +/// the blocks of one flat color that compression shifted by a few levels each. +const FULL_TONE_PATCHES: f64 = 1.5; + /// `q` with the colours that noise made of one colour merged, largest mix first. /// /// Asked for more colours than a picture has, k-means splits a flat colour along its noise, and -/// the two halves would trace as specks of one all over the other. Such halves are close (under 30 -/// levels apart: noise is about as strong in a dark colour as in a light one, so the distance is -/// taken in RGB) and thoroughly mixed: the pixels of the lesser one have, on average, more than -/// half a neighbour of the other each; or they are closer still (under 12 levels) and mixed in -/// patches (compression blocks). The bands of a gradient are close too, but each keeps to itself -/// and they stay apart. The colours in `keep` merge with none. -fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized { +/// the two halves would trace as specks of one all over the other. Such halves are close and +/// thoroughly mixed: the pixels of the lesser one have, on average, more than half a neighbour of +/// the other each; or they are closer still and mixed in patches (compression blocks). The bands +/// of a gradient are close too, but each keeps to itself and they stay apart. The colours in +/// `keep` merge with none. Close is under 30 RGB levels apart for thoroughly mixed colours and +/// under 12 for patches with [`Alike::Rgb`], and in Oklab under [`FULL_TONE_ALIKE`] and +/// [`FULL_TONE_PATCHES`] with [`Alike::Seen`]. +fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]], alike: Alike) -> Quantized { let k = q.palette.len(); // A rare colour kept on purpose (see `rare_colours`) is distinct by choice: it merges with none. let kept: Vec<bool> = q.palette.iter().map(|c| keep.contains(c)).collect(); @@ -340,6 +364,13 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized } } let mut color: Vec<[f64; 3]> = q.palette.iter().map(|c| c.map(f64::from)).collect(); + // Each colour in Oklab, for `Alike::Seen`, worked out once and again only for a colour that + // takes in another. + let mut lab: Vec<[f64; 3]> = if alike == Alike::Seen { color.iter().map(|&c| oklab(c)).collect() } else { vec![] }; + let seen_apart = |lab: &[[f64; 3]], a: usize, b: usize| match (lab.get(a), lab.get(b)) { + (Some(la), Some(lb)) => (0..3).map(|c| (la[c] - lb[c]).powi(2)).sum::<f64>().sqrt(), + _ => f64::INFINITY, + }; // Which colour each has merged into (itself when none). let mut into: Vec<usize> = (0..k).collect(); loop { @@ -350,14 +381,30 @@ fn merge_mixed(q: Quantized, w: usize, h: usize, keep: &[[u8; 3]]) -> Quantized continue; } let mixed = touch[a * k + b] / count[a].min(count[b]); - let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); - if (mixed > 0.5 && apart < 30.0 || mixed > 0.15 && apart < 12.0) && best.is_none_or(|x| mixed > x.0) { + // Two colours this little mixed merge under neither test. + if mixed <= 0.15 { + continue; + } + let merges = match alike { + Alike::Rgb => { + let apart = (0..3).map(|c| (color[a][c] - color[b][c]).powi(2)).sum::<f64>().sqrt(); + mixed > 0.5 && apart < 30.0 || apart < 12.0 + } + Alike::Seen => { + let apart = seen_apart(&lab, a, b); + mixed > 0.5 && apart < FULL_TONE_ALIKE || apart < FULL_TONE_PATCHES + } + }; + if merges && best.is_none_or(|x| mixed > x.0) { best = Some((mixed, a, b)); } } } let Some((_, a, b)) = best else { break }; color[a] = [0, 1, 2].map(|c| (color[a][c] * count[a] + color[b][c] * count[b]) / (count[a] + count[b])); + if let Some(l) = lab.get_mut(a) { + *l = oklab(color[a]); + } count[a] += count[b]; count[b] = 0.0; into[b] = a; @@ -410,6 +457,33 @@ mod tests { assert!(own.iter().all(|o| *o == own[0])); } + #[test] + fn full_tone_merges_only_mixed_colors_that_look_alike() { + // Two colors in a checkerboard: every pixel has four neighbors of the other color. + let mixed = + |a: [u8; 3], b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 + i / 16) % 2) as u16).collect(), palette: vec![a, b] }; + let colors = |q: Quantized, alike: Alike| merge_mixed(q, 16, 16, &[], alike).palette.len(); + // Gray and a greener gray, 22 levels apart (about 6.4 in Oklab): one color in RGB, two that look different. + let (gray, green) = ([128, 128, 128], [128, 150, 128]); + assert_eq!(colors(mixed(gray, green), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, green), Alike::Seen), 2); + // Two grays 3 levels apart (about 1 in Oklab): one color either way. + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Rgb), 1); + assert_eq!(colors(mixed(gray, [131; 3]), Alike::Seen), 1); + // Side by side, not mixed: two colors either way. + let halves = Quantized { labels: (0..16 * 16).map(|i| u16::from(i % 16 >= 8)).collect(), palette: vec![[128; 3], [131; 3]] }; + assert_eq!(colors(halves.clone(), Alike::Rgb), 2); + assert_eq!(colors(halves, Alike::Seen), 2); + // In 8 × 8 blocks, mixed in patches: grays 3 levels apart merge either way; grays 6 levels + // apart (about 10 in RGB, more than 1.5 in Oklab) merge only in RGB. + let blocks = + |b: [u8; 3]| Quantized { labels: (0..16 * 16).map(|i| ((i % 16 / 8 + i / 16 / 8) % 2) as u16).collect(), palette: vec![gray, b] }; + assert_eq!(colors(blocks([131; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([131; 3]), Alike::Seen), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Rgb), 1); + assert_eq!(colors(blocks([134; 3]), Alike::Seen), 2); + } + #[test] fn a_picture_with_no_pixels_is_not_shared_out() { // No band for each of the rows of a picture with no columns, however many rows it has. diff --git a/crates/trace/src/quantize/palette.rs b/crates/trace/src/quantize/palette.rs index 43a1954cd7..63c8fe9a06 100644 --- a/crates/trace/src/quantize/palette.rs +++ b/crates/trace/src/quantize/palette.rs @@ -138,6 +138,12 @@ pub(super) fn labs(colors: &[[f64; 3]]) -> Vec<[f64; 3]> { /// The most colours Full Tone (and Automatic on continuous-tone images) makes. pub const FULL_TONE_MAX: usize = 256; +/// The fewest colors Palette › Full Tone splits into, before merging, at Color detail `detail` +/// (0–1): one per step of Color detail, 85 at 85. Automatic does not use it. +pub(super) fn full_tone_least(detail: f64) -> usize { + (detail.clamp(0.0, 1.0) * 100.0).round() as usize +} + /// A histogram bin in use: its index, mean colour and pixel count. pub(super) type Used = (usize, [f64; 3], f64); @@ -152,11 +158,14 @@ pub(super) fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3] // Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per // channel, which is one histogram bin. let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail))); + // Palette › Full Tone also splits into at least one color per step of Color detail, where the + // picture has that many (see [`full_tone_least`]). + let full_tone_palette = || refine(used, centers(&median_cut_least(used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); // A Limited palette of 9 to 16 colors keeps a nearly flat dark ground in one color (see [`kmeans_rgb`]). let limited = || kmeans_rgb(used, k, if FEW_COLORS.contains(&k) { LEAST_APART } else { 0.0 }); match params.palette { Palette::Limited => limited(), - Palette::FullTone => full_tone(), + Palette::FullTone => full_tone_palette(), Palette::Automatic => match flat_colors(used, detail) { Some(n) => flat_palette(used, n), None => full_tone(), @@ -285,7 +294,7 @@ const GRAY: f64 = 3.0; /// (see [`median_cut_apart`]). A large, nearly flat dark ground then keeps one color, and the /// color it would have taken goes to another cut. fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { - refine(used, centers(&median_cut_apart(used, k, 0.0, apart))) + refine(used, centers(&median_cut_apart(used, k, 0.0, apart, 0))) } /// Divisive clustering in the manner of median cut, but each box is cut where that leaves its two @@ -295,21 +304,34 @@ fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> { /// and leaves two smaller colours in one box. Boxes are cut while there are fewer than `k` and /// some box spans more than `spread` levels of a channel. pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> { - median_cut_apart(used, k, spread, 0.0) + median_cut_apart(used, k, spread, 0.0, 0) } -/// [`median_cut`], except when both sides of a cut have a dark gray mean color (see [`DARK`] and -/// [`GRAY`]) and the two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain -/// is scaled by (`d` / `apart`)². With `apart` 0 it is [`median_cut`]. -fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<ColorBox> { +/// [`median_cut`], then, while there are fewer than `least` boxes, cutting the boxes no wider than +/// `spread` too, the one whose cut gains most first. +fn median_cut_least(used: &[Used], k: usize, spread: f64, least: usize) -> Vec<ColorBox> { + median_cut_apart(used, k, spread, 0.0, least) +} + +/// [`median_cut`] with at least `least` boxes where the bins allow (see [`median_cut_least`]), +/// except when both sides of a cut have a dark gray mean color (see [`DARK`] and [`GRAY`]) and the +/// two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain is scaled by +/// (`d` / `apart`)². With `apart` 0 and `least` 0 it is [`median_cut`]. +fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64, least: usize) -> Vec<ColorBox> { if used.is_empty() { return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }]; } - /// A box's bins and its best cut: (gain, bins sorted along the cut's channel, bins on the first side). + /// A box's bins, its widest span over the channels, and its best cut: (gain, bins sorted along + /// the cut's channel, bins on the first side). struct Cut { bins: Vec<usize>, + widest: f64, best: Option<(f64, Vec<usize>, usize)>, } + // Boxes no wider than `spread` are cut only while there are fewer than `least` boxes. A box made + // when there are already `least` boxes or more is never cut unless it is wider, so its cut is + // not planned. + let narrowest = |boxes_after: usize| if boxes_after < least { 0.0 } else { spread.max(0.0) }; // How much of a cut's gain counts when its sides' mean colors are `a` and `b`: all of it when // they look different or either is not a dark gray, less as two dark grays look more alike. let dark_gray = |c: [f64; 3]| c[0] < DARK && c[1].hypot(c[2]) < GRAY; @@ -320,7 +342,8 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } ((0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>() / (apart * apart)).min(1.0) }; - let plan = |bins: Vec<usize>| { + let plan = |bins: Vec<usize>, boxes_after: usize| { + let narrowest = narrowest(boxes_after); let mut best: Option<(f64, Vec<usize>, usize)> = None; let widest = (0..3) .map(|ch| { @@ -328,7 +351,7 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col v.clone().fold(f64::NEG_INFINITY, f64::max) - v.fold(f64::INFINITY, f64::min) }) .fold(0.0, f64::max); - if bins.len() >= 2 && widest > spread.max(0.0) { + if bins.len() >= 2 && widest > narrowest { for ch in 0..3 { let mut sorted = bins.clone(); sorted.sort_by(|x, y| used[*x].1[ch].total_cmp(&used[*y].1[ch])); @@ -366,18 +389,26 @@ fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<Col } } } - Cut { bins, best } + Cut { bins, widest, best } }; - let mut boxes = vec![plan((0..used.len()).collect())]; + let mut boxes = vec![plan((0..used.len()).collect(), 1)]; while boxes.len() < k { let gain = |c: &Cut| c.best.as_ref().map_or(f64::NEG_INFINITY, |b| b.0); - let Some(bi) = (0..boxes.len()).filter(|&i| boxes[i].best.is_some()).max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) else { + // The boxes wider than `spread` first; when none is left and there are fewer than `least`, + // any box with a cut. + let most = |wide: bool| { + (0..boxes.len()) + .filter(|&i| boxes[i].best.is_some() && (!wide || boxes[i].widest > spread.max(0.0))) + .max_by(|&a, &b| gain(&boxes[a]).total_cmp(&gain(&boxes[b]))) + }; + let Some(bi) = most(true).or_else(|| if boxes.len() < least { most(false) } else { None }) else { break; }; let Some((_, mut sorted, at)) = boxes.swap_remove(bi).best else { break }; let tail = sorted.split_off(at); - boxes.push(plan(sorted)); - boxes.push(plan(tail)); + let after = boxes.len() + 2; + boxes.push(plan(sorted, after)); + boxes.push(plan(tail, after)); } boxes .iter() @@ -467,7 +498,9 @@ mod tests { assert_eq!(palette(Palette::DocumentLibrary, colors), plain(colors as usize), "{colors} colors"); } let detail = (TraceParams::default().color_detail / 100.0).clamp(0.0, 1.0); - assert_eq!(palette(Palette::FullTone, 16), refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail)))); + // Full Tone's median cut makes at least one color per step of Color detail. + let full_tone = refine(&used, centers(&median_cut_least(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail, full_tone_least(detail)))); + assert_eq!(palette(Palette::FullTone, 16), full_tone); let automatic = match flat_colors(&used, detail) { Some(n) => plain(n), None => refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))), @@ -475,6 +508,32 @@ mod tests { assert_eq!(palette(Palette::Automatic, 16), automatic); } + #[test] + fn full_tone_makes_one_color_per_step_of_color_detail() { + // 256 grays, 1,200 pixels each: the width limit alone gives fewer colors than Color detail. + let ramp = bins((0..256).map(|g| ([f64::from(g); 3], 1200.0))); + let colors = |used: &[Used], color_detail: f64| { + color_palette(used, &TraceParams { palette: Palette::FullTone, color_detail, ..TraceParams::default() }).len() + }; + assert!(median_cut(&ramp, FULL_TONE_MAX, 96.0 - 88.0 * 0.85).len() < 85); + assert_eq!(colors(&ramp, 85.0), 85); + assert_eq!(colors(&ramp, 40.0), 40); + // A picture of three colors keeps three. + let three = bins([([0.0; 3], 100.0), ([128.0; 3], 100.0), ([255.0; 3], 100.0)]); + assert_eq!(colors(&three, 85.0), 3); + // A large, finely shaded area does not take the count from a small pair of reds 40 levels + // apart, wider than one color may be at Color detail 85: the pair keeps two colors. + let shaded = bins((0..128).map(|g| ([f64::from(g); 3], 10_000.0)).chain([([200.0, 0.0, 0.0], 1.0), ([240.0, 0.0, 0.0], 1.0)])); + let reds = color_palette(&shaded, &TraceParams { palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }); + assert!(reds.len() >= 85, "{} colors", reds.len()); + for red in [200.0, 240.0] { + assert!(reds.iter().any(|c| (c[0] - red).abs() < 1.0 && c[1] < 1.0), "no color for red {red}: {reds:?}"); + } + // Automatic's continuous-tone colors are not raised to the count. + let automatic = color_palette(&ramp, &TraceParams { palette: Palette::Automatic, color_detail: 85.0, ..TraceParams::default() }); + assert!(automatic.len() < 85, "{} colors with Automatic", automatic.len()); + } + /// `colors`, each with `n` pixels, as histogram bins. fn bins(colors: impl IntoIterator<Item = ([f64; 3], f64)>) -> Vec<Used> { colors.into_iter().enumerate().map(|(i, (c, n))| (i, c, n)).collect() diff --git a/crates/trace/src/tests.rs b/crates/trace/src/tests.rs index 7e037c8b70..694892a8a6 100644 --- a/crates/trace/src/tests.rs +++ b/crates/trace/src/tests.rs @@ -944,6 +944,16 @@ fn presets_have_their_paths_corners_and_noise() { assert_eq!(colors, [64, 20, 3, 6, 16, 8]); } +#[test] +fn high_fidelity_photo_traces_in_full_tone() { + // As many colors as the tones need, split until no color spans more than about 21 levels, as + // abutting shapes. + let p = preset("High Fidelity Photo").unwrap(); + assert_eq!((p.palette, p.color_detail, p.method), (Palette::FullTone, 85.0, Method::Abutting)); + // Low Fidelity Photo keeps its 20 colors. + assert_eq!(preset("Low Fidelity Photo").unwrap().palette, Palette::Limited); +} + #[test] fn params_json_roundtrip_and_partial() { let p = preset("6 Colors").unwrap(); @@ -1213,12 +1223,14 @@ fn full_tone_follows_the_tones_the_image_has() { } #[test] -fn automatic_traces_flat_art_with_its_colours_and_photos_in_full_tone() { +fn automatic_traces_flat_art_with_its_colours_and_photos_in_continuous_tone() { let flat = palette(&flat_quads(), Palette::Automatic, 2, 50.0); assert_eq!(flat.len(), 4, "the four flat colours, whatever `colors` says: {flat:?}"); assert!(flat.iter().any(|c| c[0] > 200 && c[1] < 60 && c[2] < 60), "red is one of them: {flat:?}"); let tone = palette(&gradient(), Palette::Automatic, 2, 50.0); - assert_eq!(tone.len(), palette(&gradient(), Palette::FullTone, 2, 50.0).len(), "continuous tone: as Full Tone"); + // Continuous tone: as many colors as the tones need, without Full Tone's least count. + let full = palette(&gradient(), Palette::FullTone, 2, 50.0); + assert!(tone.len() > 4 && tone.len() <= full.len(), "{} colors, {} in Full Tone", tone.len(), full.len()); } #[test] @@ -1713,6 +1725,56 @@ fn jitter(x: u32, y: u32, salt: u32) -> f64 { f64::from(v & 0xFFFF) / 32768.0 - 1.0 } +#[test] +fn full_tone_keeps_more_of_a_noisy_ramps_tones() { + // Gray to green with grain: Full Tone's neighboring tones are close in RGB and mixed along + // their borders, and still look different. + let img = Raster::from_fn(256, 96, |x, y| { + let v = |k: u32, base: f64, slope: f64| (base + slope * f64::from(x) + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [v(0, 100.0, 0.0), v(1, 40.0, 0.7), v(2, 100.0, 0.0), 255] + }); + let params = TraceParams { mode: Mode::Color, palette: Palette::FullTone, color_detail: 85.0, ..TraceParams::default() }; + // Median cut gives at least 85 (one per step of Color detail). Merging the ones that look alike + // leaves 6 (one per 30 or so levels of the ramp); merging close RGB colors would leave 4. + let n = quantize(&img, ¶ms).palette.len(); + assert!(n >= 6, "{n} tones"); + // Automatic traces continuous tone without Full Tone's least count and keeps merging close RGB colors. + let automatic = quantize(&img, &TraceParams { palette: Palette::Automatic, ..params }).palette.len(); + assert!(automatic < n, "{automatic} tones with Automatic, {n} with Full Tone"); +} + +#[test] +fn full_tone_traces_a_noisy_dark_ground_like_a_light_one() { + // A gray ground with up to 8 levels of grain a channel. The same grain lies farther apart in + // Oklab in a dark gray than in a light one; the dark ground still takes about as many colors + // and shapes as the light one (32 and 53 against 31 and 52 when measured). + let ground = |gray: f64| { + let img = Raster::from_fn(192, 128, |x, y| { + let c = |k: u32| (gray + 8.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + trace(&img, &preset("High Fidelity Photo").unwrap()) + }; + let (dark, light) = (ground(28.0), ground(200.0)); + assert!(dark.palette.len() <= light.palette.len() + 2, "{} colors dark, {} light", dark.palette.len(), light.palette.len()); + assert!(dark.paths.len() <= light.paths.len() + 6, "{} shapes dark, {} light", dark.paths.len(), light.paths.len()); +} + +#[test] +fn full_tone_merges_a_flat_colors_compression_blocks() { + // Three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, with a + // little grain: the blocks of one color look alike and are mixed in patches, so each flat + // color traces as one shape in Full Tone too, not as squares of near colors. + let bases = [[200.0, 150.0, 120.0], [70.0, 120.0, 190.0], [40.0, 90.0, 40.0]]; + let img = Raster::from_fn(192, 128, |x, y| { + let base: [f64; 3] = bases[(x / 64) as usize]; + let c = |k: u32| (base[k as usize] + 8.0 * jitter(x / 8, y / 8, k) + 1.5 * jitter(x, y, k + 7)).round().clamp(0.0, 255.0) as u8; + [c(0), c(1), c(2), 255] + }); + let res = trace(&img, &preset("High Fidelity Photo").unwrap()); + assert_eq!((res.palette.len(), res.paths.len()), (3, 3), "{:?}", res.palette); +} + /// Three flat colours (a navy field, a yellow disc, a green bar) drawn anti-aliased, with `noise` /// levels of noise per channel. fn three_colour_art(noise: f64) -> Raster { @@ -2013,7 +2075,7 @@ fn a_nearly_flat_dark_ground_keeps_one_color() { #[test] fn a_noisy_gradient_keeps_its_tones_without_specks() { - // Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart. + // Tones 0–255 across with up to 5 levels of noise a channel. let img = Raster::from_fn(256, 96, |x, y| { let c = |k: u32| (f64::from(x) + 5.0 * jitter(x, y, k)).round().clamp(0.0, 255.0) as u8; [c(0), c(1), c(2), 255] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ed2e1aa7ba..70c8834c2d 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -66,8 +66,8 @@ use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; pub use panes::Panes; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; +pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; -pub(crate) use raster::{color_image, color_image_owned, render_job}; pub use selection_marks::SelectionMarks; #[cfg(test)] pub(crate) use task_bar::chip_paints; diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index cd98a214b7..d8cd85d13a 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -50,7 +50,9 @@ pub(super) fn context_menu(app: &mut VectorcraftApp, resp: &egui::Response, xf: /// A panel drag ([`widgets::PanelDrag`]) dropped on art acts on the object under the pointer, /// selected or not: a paint (swatches, a Fill/Stroke proxy, the Gradient panel's thumbnail) goes -/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it), the +/// to its active proxy (`paint.setFill`/`paint.setStroke` with its `ids`; a gradient fits it; a +/// solid fill color on a selected gradient mesh recolors the mesh point under the pointer, else the +/// four points of the patch there, with `object.mesh.setPointColor`), the /// Appearance panel's thumbnail gives the object (the topmost one hit) the appearance it carries /// (`appearance.copyFrom`), a graphic style is applied to it (`graphicStyle.apply`; with Alt, on /// top of its appearance), and a brush is applied to it (`brush.apply`, `brush.addFromLibrary` @@ -89,6 +91,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } + // A solid fill color on a selected gradient mesh: the point under the pointer, else the four + // points around the patch there, take it. The selected meshes are looked at directly, so + // Object Selection by Path Only and the selection tolerance do not stop it. + if let widgets::PanelDrag::Paint { params, paint, .. } = &*d + && !params.is_null() + && let Some(color) = paint.color() + && crate::panels::proxy_cmd(app, false) == "paint.setFill" + && let Some((id, points)) = selected_mesh_drop(app, xf.to_doc(pos), xf.zoom) + { + let params = json!({"id": id.0, "points": points, "color": crate::panels::color_json(&color), "keepModel": true}); + if let Err(e) = app.run("object.mesh.setPointColor", params) { + app.status(e); + } + return; + } let hit = hit_at(app, xf.to_doc(pos), xf.zoom); // A scatter, art or pattern brush from the Brushes panel dropped where there is no art: a copy // of its art, centered where it is dropped, to edit and Alt-drag back onto the brush. @@ -148,3 +165,21 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons app.status(e); } } + +/// The selected, editable gradient mesh and its points that a solid color dropped at document +/// point `p` at `zoom` recolors: the topmost object within 5 screen pixels of `p` must be that mesh +/// (fills count even with Object Selection by Path Only, and clipping applies), and the points are +/// its point within 5 screen pixels, else the four points around its patch under `p`. +fn selected_mesh_drop(app: &VectorcraftApp, p: vectorcraft_geom::Point, zoom: f64) -> Option<(vectorcraft_doc::NodeId, Vec<usize>)> { + let tol = 5.0 / zoom.max(1e-9); + let leaf = hit_with(app, p, zoom, |doc, p, opt| { + vectorcraft_doc::hit::hit_test(doc, p, vectorcraft_doc::hit::HitOptions { path_only: false, tol: opt.tol.max(tol), ..opt }) + })? + .leaf; + let st = app.session.active()?; + if !st.selection.contains(leaf) || !st.doc.editable()(leaf) { + return None; + } + let Some(vectorcraft_doc::NodeKind::Mesh(m)) = st.doc.node(leaf).map(|n| &n.kind) else { return None }; + Some((leaf, vectorcraft_tools::meshedit::color_points(m, p, tol)?)) +} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cc65044dfb..34d0777c51 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2821,10 +2821,20 @@ fn the_art_renders_within_the_largest_texture_side() { assert_eq!(pixel_region(&xf, 1024), None, "more than the display's largest texture"); } +/// Run a test that compares two renders with the color settings that are active when it starts. +/// A test on another thread can change the process's active settings; this thread keeps its own. +fn keeping_color_settings(test: fn()) { + vectorcraft_color::cms::with_active(vectorcraft_color::cms::active(), test); +} + /// A placed document's bitmap made in the background renders the canvas again only where the /// objects showing its file are: both copies of the file are in the part rendered again. #[test] fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { + keeping_color_settings(a_ready_placed_bitmap); +} + +fn a_ready_placed_bitmap() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width":400,"height":300})).unwrap(); app.ui.task_bar = false; @@ -2859,9 +2869,8 @@ fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() { }; let (_, delta) = frame_output(&mut app, &ctx); assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it"); - let t = std::time::Instant::now(); - while vectorcraft_render::placed_document::busy() && t.elapsed().as_secs() < 20 { - std::thread::sleep(std::time::Duration::from_millis(5)); + while vectorcraft_render::placed_document::busy() { + std::thread::yield_now(); } let (_, delta) = frame_output(&mut app, &ctx); let (pos, size) = canvas(&app, delta).expect("the bitmap shows"); @@ -3137,6 +3146,10 @@ fn the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on() /// transparency grid renders the art again, and Outline converts the art alone. #[test] fn translucent_art_over_the_paper_is_blended_before_the_display_profile() { + keeping_color_settings(translucent_art_over_the_paper); +} + +fn translucent_art_over_the_paper() { use crate::display_profile::{Found, Reading}; let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); @@ -3490,12 +3503,42 @@ fn the_first_view_reports_the_plug_in_effects_it_deferred() { } } +/// The render worker's side of a controlled worker: the test thread renders the jobs the canvas +/// queues, with [`crate::render_worker::render`] and the worker's own renderer and last frame. +struct WorkerSide { + jobs: std::sync::mpsc::Receiver<crate::render_worker::Job>, + done: std::sync::mpsc::Sender<crate::render_worker::Done>, + renderer: vectorcraft_render::Renderer, + kept: Option<crate::canvas::KeptFrame>, +} + +impl WorkerSide { + /// A controlled worker for the canvas, and its side. + fn start() -> (crate::render_worker::Worker, Self) { + let (worker, jobs, done) = crate::render_worker::Worker::test_channel(); + (worker, Self { jobs, done, renderer: vectorcraft_render::Renderer::new(), kept: None }) + } + + /// Render the newest job queued, as the worker thread does, and send its frame with a time of + /// 50 ms: the canvas then keeps sending the document's frames to the worker. False when no job + /// is queued. + fn render(&mut self) -> bool { + let Some(job) = self.jobs.try_iter().last() else { return false }; + let done = crate::render_worker::render(&mut self.renderer, &mut self.kept, job); + self.done.send(crate::render_worker::Done { ms: 50.0, ..done }).is_ok() + } +} + /// A drag of an object with raster effects (#1257): the drag's frames render while /// interacting and draw the object's drop shadow and filtered content from the rasters of the /// frame before; the frame after the drag renders without `interacting`, on the render worker, -/// and draws what a fresh renderer draws. +/// and draws what a fresh renderer draws. The worker is a controlled one ([`WorkerSide`]). #[test] fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { + keeping_color_settings(dragging_with_raster_effects); +} + +fn dragging_with_raster_effects() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3528,17 +3571,13 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { } // The frame after the drag runs the effects again: on the worker, while the canvas shows // the drag's last frame. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.session.pointer(&PointerEvent::new(PointerKind::Up, 181.9, 131.3), view).unwrap(); assert!(upload(&mut app).is_none(), "not rendered on this thread"); assert!(app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| !k.interacting), "sent to the worker"); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - let mut after = None; - while after.is_none() && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - after = upload(&mut app); - } - let after = after.expect("the worker's frame arrives"); + assert!(side.render(), "the worker renders the frame"); + let after = upload(&mut app).expect("the worker's frame arrives"); assert!(app.canvas.key.as_ref().is_some_and(|k| !k.interacting)); assert!(!app.canvas.moved); app.canvas.worker = None; @@ -3554,6 +3593,10 @@ fn dragging_an_object_with_raster_effects_draws_its_rasters_moved() { /// without a drag, renders without `dragging` and draws the same. #[test] fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { + keeping_color_settings(a_drag_at_a_lower_resolution); +} + +fn a_drag_at_a_lower_resolution() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3609,9 +3652,13 @@ fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() { /// the blur reaches far past the raster budget, so the still frame keeps the backdrop's raster /// cropped to the view, and each frame of a Selection tool drag draws it from there instead of /// previewing it at the drag's lower resolution: on this thread, and on the worker, where the -/// frames of a heavy document render. +/// frames of a heavy document render. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { + keeping_color_settings(a_drag_over_a_wide_blur); +} + +fn a_drag_over_a_wide_blur() { for on_worker in [false, true] { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 595, "height": 842})).unwrap(); @@ -3623,9 +3670,9 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { app.run("select.set", json!({"ids": [square]})).unwrap(); app.select_tool("selection"); let ctx = egui::Context::default(); - // One headless frame with `events`, then, on the worker, frames until the frame it renders - // for them is shown. - let run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + // One headless frame with `events`, then, with a worker, its frames rendered and shown + // until none is pending. + let run = |app: &mut VectorcraftApp, side: &mut Option<WorkerSide>, events: Vec<egui::Event>| { let frame = |app: &mut VectorcraftApp, events| { let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(1440.0, 870.0))), events, ..Default::default() }; @@ -3633,39 +3680,40 @@ fn a_drag_over_a_wide_blur_draws_the_blur_from_the_still_frame() { out.textures_delta.clear(); }; frame(app, events); - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); + for _ in 0..8 { + if !side.as_mut().is_some_and(WorkerSide::render) { + break; + } frame(app, vec![]); } + assert!(app.canvas.worker.as_ref().is_none_or(|w| w.pending.is_none()), "the worker's frame is shown"); }; let moved = |app: &VectorcraftApp| if on_worker { app.canvas.moved } else { app.canvas.renderer.stats.moved > 0 }; - run(&mut app, vec![]); + let mut side = None; + run(&mut app, &mut side, vec![]); if let Some(vm) = app.view_mut() { (vm.zoom, vm.center) = (2.0, Point::new(290.0, 410.0)); } if on_worker { - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, worker_side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; + side = Some(worker_side); } - run(&mut app, vec![]); + run(&mut app, &mut side, vec![]); assert_eq!(app.canvas.from_worker, on_worker); assert!(!moved(&app), "a still frame, on the worker: {on_worker}"); let at = app.canvas_rect.unwrap().center(); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - run(&mut app, vec![egui::Event::PointerMoved(at)]); - run(&mut app, vec![button(at, true)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at)]); + run(&mut app, &mut side, vec![button(at, true)]); for step in [1.0, 2.0, 3.0] { - run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); + run(&mut app, &mut side, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]); assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}, on the worker: {on_worker}"); assert_eq!(app.canvas.from_worker, on_worker, "step {step}"); - assert!( - !moved(&app), - "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker} ({} ms)", - app.perf.render_ms - ); + assert!(!moved(&app), "the blur drawn from the still frame's raster, step {step}, on the worker: {on_worker}"); } - run(&mut app, vec![button(at + vec2(39.0, 21.0), false)]); + run(&mut app, &mut side, vec![button(at + vec2(39.0, 21.0), false)]); let info = app.run("document.inspect", json!({})).unwrap(); let children = info["layers"][0]["children"].as_array().unwrap().clone(); let x0 = |id: &serde_json::Value| children.iter().find(|c| c["id"] == *id).unwrap()["bounds"]["x"].as_f64().unwrap(); @@ -3706,6 +3754,10 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() { /// leaves the document as it was (#1257): here a drag back to where it started. #[test] fn a_drag_back_to_its_start_renders_again_after_it() { + keeping_color_settings(a_drag_back_to_its_start); +} + +fn a_drag_back_to_its_start() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; // render on this thread @@ -3772,6 +3824,10 @@ fn canvas_render_jobs_use_renderer_limited_dimensions() { /// controlled worker cannot finish early, even if egui repeats a layout pass. #[test] fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { + keeping_color_settings(cached_frames_keep_their_scale); +} + +fn cached_frames_keep_their_scale() { for (old_rot, new_rot, old_ppp, new_ppp, pixel, resize_only) in [ // Isolate the original panel/window resize: zoom, pan, rotation and DPI stay fixed. (0.0, 0.0, 1.0, 1.0, false, true), @@ -3867,9 +3923,13 @@ fn cached_frames_keep_their_scale_during_resize_rotation_and_dpi_changes() { /// a heavy document), the canvas draws the last frame turned until that frame arrives: each /// corner goes where the new view puts the document point that the corner showed. The new frame /// is then drawn unturned. In Pixel Preview the last frame's pixels stay over the document rect -/// they cover. +/// they cover. The worker is a controlled one ([`WorkerSide`]). #[test] fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { + keeping_color_settings(a_turned_view); +} + +fn a_turned_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -3890,7 +3950,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { }) }; // With a worker and a last frame that took 50 ms, the next frame renders on the worker. - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, mut side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.run("view.rotateReset", json!({})).unwrap(); let mesh = art(&mut app).expect("the last frame, turned"); @@ -3908,11 +3969,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { let [a, b, _, d] = [0, 1, 2, 3].map(|i| mesh.vertices[i].pos); assert!((a + (b - a) * uv.x + (d - a) * uv.y - new.to_screen(p)).length() < 0.01, "the rectangle's corner"); // The worker's frame at 0° then covers the canvas unturned. - let until = std::time::Instant::now() + std::time::Duration::from_secs(60); - while app.canvas.key.as_ref().is_some_and(|k| k.rot != 0.0) && std::time::Instant::now() < until { - std::thread::sleep(std::time::Duration::from_millis(5)); - shapes(&mut app, &ctx); - } + assert!(side.render(), "the worker renders the frame at 0°"); + shapes(&mut app, &ctx); assert!(app.canvas.key.as_ref().is_some_and(|k| k.rot == 0.0), "the worker's frame arrives"); let b = art(&mut app).expect("the worker's frame").calc_bounds(); assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}"); @@ -3922,7 +3980,8 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { app.view_mut().unwrap().zoom = 8.0; shapes(&mut app, &ctx); let [x0, y0, ..] = app.canvas.key.as_ref().and_then(|k| k.pixel).expect("the pixels rendered"); - app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone()); + let (worker, _side) = WorkerSide::start(); + app.canvas.worker = Some(worker); app.canvas.last_ms = 50.0; app.view_mut().unwrap().rotation = 30.0; let mesh = art(&mut app).expect("the last frame's pixels"); @@ -3937,6 +3996,10 @@ fn a_turned_view_draws_the_last_frame_turned_until_its_own_arrives() { /// fill is dropped. #[test] fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { + keeping_color_settings(a_pan_fills_the_area); +} + +fn a_pan_fills_the_area() { let ctx = egui::Context::default(); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); @@ -4062,6 +4125,10 @@ fn a_pan_fills_the_area_the_last_frame_leaves_until_the_worker_frame_arrives() { /// before. #[test] fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() { + keeping_color_settings(without_a_worker_a_heavy_canvas); +} + +fn without_a_worker_a_heavy_canvas() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -4172,6 +4239,10 @@ fn the_canvas_waits_only_while_the_view_of_a_slow_frame_changes() { /// worker's pixel copy ask for that. #[test] fn a_bitmap_made_for_another_documents_file_leaves_a_pan_waiting() { + keeping_color_settings(a_bitmap_for_another_documents_file); +} + +fn a_bitmap_for_another_documents_file() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); @@ -9014,6 +9085,86 @@ fn swatches_and_proxy_paints_dropped_on_art_fill_the_object_hit() { assert!(matches!(fill(&app), Paint::Gradient(g) if g.geom.is_none())); } +#[test] +fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{GradientMesh, NodeId, NodeKind}; + use widgets::PanelDrag; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + let id = NodeId(id); + app.session.execute("object.mesh.create", &json!({"ids": [id.0], "rows": 2, "columns": 2})).unwrap(); + app.session.execute("select.none", &json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let drop = |app: &mut VectorcraftApp, d: PanelDrag, at: Point| { + let at = xf.to_screen(at); + egui::DragAndDrop::set_payload(&ctx, d); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]); + }; + let mesh = |app: &VectorcraftApp| -> GradientMesh { + match &app.session.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Mesh(m) => m.clone(), + _ => panic!("not a gradient mesh"), + } + }; + let colors = |app: &VectorcraftApp| mesh(app).points.iter().map(|q| q.color).collect::<Vec<_>>(); + let undo_len = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = colors(&app); + let m = mesh(&app); + let (center, patch) = (m.points[4].p, Point::new((m.points[0].p.x + m.points[4].p.x) / 2.0, (m.points[0].p.y + m.points[4].p.y) / 2.0)); + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // On a mesh point: that point alone. + drop(&mut app, PanelDrag::paint(Paint::solid(red)), center); + let after = colors(&app); + assert_eq!(after[4], red); + assert_eq!((0..9).filter(|i| after[*i] != before[*i]).count(), 1, "only the point under the pointer"); + // Inside a patch: its four points. + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + let after = colors(&app); + assert_eq!([0, 1, 3, 4].map(|i| after[i]), [blue; 4]); + assert_eq!([2, 5, 6, 7, 8].map(|i| after[i]), [2, 5, 6, 7, 8].map(|i| before[i])); + assert!(app.session.active().unwrap().selection.contains(id), "the selection stays"); + // The same color again changes nothing and records no undo step. + let n = undo_len(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(blue)), patch); + assert_eq!(undo_len(&app), n); + // With Object Selection by Path Only, a drop inside a patch still reaches its points, and a + // drop 4 screen pixels outside a corner point still reaches that point. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": true})).unwrap(); + let green = Color::rgb(0.0, 1.0, 0.0); + let far = Point::new((m.points[4].p.x + m.points[8].p.x) / 2.0, (m.points[4].p.y + m.points[8].p.y) / 2.0); + // Art below the patch, with its outline within the selection tolerance, is not taken for it. + let h = 1.0 / xf.zoom; + let below = app.session.execute("shape.rectangle", &json!({"x": far.x - h, "y": far.y - h, "width": 2.0 * h, "height": 2.0 * h})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("object.arrange.sendToBack", &json!({"ids": [below]})).unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), far); + assert_eq!([4, 5, 7, 8].map(|i| colors(&app)[i]), [green; 4]); + assert_ne!(app.session.active().unwrap().doc.node(NodeId(below)).unwrap().appearance.fill_paint(), Paint::solid(green)); + let off = 4.0 / xf.zoom; + drop(&mut app, PanelDrag::paint(Paint::solid(red)), Point::new(m.points[0].p.x - off, m.points[0].p.y)); + assert_eq!(colors(&app)[0], red, "the corner point within reach"); + assert_eq!(colors(&app)[1], blue); + // An unselected object on top of the mesh takes the drop itself. + app.session.execute("prefs.set", &json!({"key": "objectSelectionByPathOnly", "value": false})).unwrap(); + let c = m.points[4].p; + let cover = app.session.execute("shape.rectangle", &json!({"x": c.x - 10.0, "y": c.y - 10.0, "width": 20, "height": 20})).unwrap()["id"] + .as_u64() + .unwrap(); + app.session.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = colors(&app); + drop(&mut app, PanelDrag::paint(Paint::solid(green)), c); + assert_eq!(colors(&app), before, "the mesh under it keeps its colors"); + assert_eq!(app.session.active().unwrap().doc.node(NodeId(cover)).unwrap().appearance.fill_paint(), Paint::solid(green)); +} + #[test] fn dropping_the_appearance_thumbnail_on_art_copies_the_appearance() { use vectorcraft_doc::NodeId; @@ -13076,6 +13227,10 @@ fn pan_doc() -> (std::sync::Arc<vectorcraft_doc::Document>, CacheKey) { /// put in that frame moves with the pan, and the frame matches a whole render where the mark is not. #[test] fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { + keeping_color_settings(a_whole_pixel_pan); +} + +fn a_whole_pixel_pan() { let (doc, key) = pan_doc(); for pan in [(10.0, 0.0), (-10.0, 0.0), (0.0, 7.0), (0.0, -7.0), (-13.0, 5.0)] { let mut r = vectorcraft_render::Renderer::new(); @@ -13103,6 +13258,10 @@ fn a_whole_pixel_pan_copies_the_pixels_that_stay_on_screen() { /// plug-in registry, and the plug-in is removed after. #[test] fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { + keeping_color_settings(a_plug_in_change); +} + +fn a_plug_in_change() { use vectorcraft_plugins::wat as tpl; let id = "test.canvas.redraw"; let module = vectorcraft_format::base64_encode(&wat::parse_str(tpl::module(&tpl::manifest(id, "effect", "{}"), tpl::ECHO, "", 1)).unwrap()); @@ -13145,6 +13304,10 @@ fn a_plug_in_change_draws_the_document_s_plug_in_effects_again() { /// compares such frames with a fresh render pixel by pixel. #[test] fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { + keeping_color_settings(a_frame_renders_whole); +} + +fn a_frame_renders_whole() { let (doc, key) = pan_doc(); let other_opts = |f: &dyn Fn(&mut vectorcraft_render::RenderOptions)| { let mut job = pan_job(&doc, &key, (10.0, 0.0)); @@ -13222,6 +13385,10 @@ fn a_frame_renders_whole_when_anything_but_a_whole_pixel_pan_changed() { /// not kept. A frame that may not copy can still be kept. #[test] fn the_render_worker_keeps_one_frame_up_to_its_limit() { + keeping_color_settings(the_render_worker_keeps_one_frame); +} + +fn the_render_worker_keeps_one_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 256, "height": 128})).unwrap(); let id = app.run("shape.rectangle", json!({"x": 16, "y": 16, "width": 64, "height": 64})).unwrap()["id"].clone(); @@ -13268,6 +13435,10 @@ fn the_render_worker_keeps_one_frame_up_to_its_limit() { /// worker renders whole matches a fresh render, and each copied frame is within one level of it. #[test] fn worker_frames_match_a_fresh_render_through_a_session() { + keeping_color_settings(worker_frames_match_a_fresh_render); +} + +fn worker_frames_match_a_fresh_render() { let (doc, key) = pan_doc(); let mut edited = (*doc).clone(); edited.layers.reverse(); @@ -13353,6 +13524,10 @@ fn worker_frames_match_a_fresh_render_through_a_session() { /// not keep such a frame for the pan to copy from. #[test] fn a_pan_over_art_the_frame_size_decides_renders_whole() { + keeping_color_settings(a_pan_over_art); +} + +fn a_pan_over_art() { let (_, key) = pan_doc(); let effect = |effect: &str, params: serde_json::Value| { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -13408,6 +13583,10 @@ fn a_pan_over_art_the_frame_size_decides_renders_whole() { /// before and only once. #[test] fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { + keeping_color_settings(a_frame_with_copied_pixels); +} + +fn a_frame_with_copied_pixels() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13454,6 +13633,10 @@ fn a_frame_with_copied_pixels_renders_whole_once_the_view_stops() { /// first step of the next pan copies from it. The jobs are the ones the canvas asks for. #[test] fn a_pan_after_the_settling_frame_copies() { + keeping_color_settings(a_pan_after_the_settling_frame); +} + +fn a_pan_after_the_settling_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; @@ -13552,6 +13735,10 @@ fn the_render_worker_thread_copies_a_pan() { /// meanwhile, does not queue the frame again while it renders, and shows it once it lands. #[test] fn a_documents_first_frame_renders_on_the_worker() { + keeping_color_settings(a_documents_first_frame); +} + +fn a_documents_first_frame() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); app.canvas.worker_started = true; diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index ecb6f15ea9..8983199324 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -142,17 +142,52 @@ fn every_tool_is_listed_once_under_a_heading() { assert!(!heads.contains(&"More"), "every tool has a named heading: {heads:?}"); } +/// The Enclosing Lasso Tool is in the Lasso tool's flyout in both toolbars, right after the Lasso, +/// once in the All Tools drawer (under Select) and in Keyboard Shortcuts' list, with no shortcut; +/// Reset Toolbar keeps it there. #[test] -fn enclosing_lasso_is_an_optional_addon_tool() { +fn enclosing_lasso_is_in_the_lasso_flyout() { let mut app = app(); let id = vectorcraft_tools::addons::enclosing_lasso::ID; - assert_eq!(heading(id), "Enclosing Lasso"); - assert!(slot_of(&app, id).is_none()); - app.run("toolbar.addTool", json!({"tool": id})).unwrap(); - assert!(slot_of(&app, id).is_some()); + for advanced in [false, true] { + if advanced { + app.run("window.toolbarAdvanced", json!({})).unwrap(); + } + let s = slots(&app); + let slot = slot_of(&app, "lasso").map(|i| s[i].clone()).expect("a Lasso slot"); + let lasso = slot.iter().position(|t| *t == "lasso").expect("the Lasso"); + assert_eq!(slot.get(lasso + 1), Some(&id), "advanced: {advanced}"); + assert_eq!(s.iter().filter(|ids| ids.contains(&id)).count(), 1, "advanced: {advanced}"); + } + assert_eq!(heading(id), "Select"); + assert_eq!(sections().iter().flat_map(|(_, tools)| tools.iter()).filter(|t| t.id == id).count(), 1, "listed once in the drawer"); + assert_eq!(vectorcraft_tools::catalog::all_tools().filter(|t| t.id == id).count(), 1, "listed once for Keyboard Shortcuts"); + assert_eq!(vectorcraft_tools::tool_info(id).map(|t| (t.label, t.shortcut)), Some(("Enclosing Lasso Tool", None))); app.run("tool.select", json!({"tool": id})).unwrap(); + assert_eq!(app.session.tool_id(), id); + let shown = slot_of(&app, id).map(|i| crate::toolbar::shown_tool(&app, &slots(&app)[i])); + assert_eq!(shown, Some(id), "the slot's button shows the tool once chosen"); + app.run("toolbar.removeTool", json!({"tool": id})).unwrap(); + assert!(slot_of(&app, id).is_none(), "it can be taken out"); app.run("toolbar.reset", json!({})).unwrap(); + let after_reset = slot_of(&app, "lasso").map(|i| slots(&app)[i].contains(&id)); + assert_eq!(after_reset, Some(true), "Reset Toolbar puts it back"); +} + +/// A toolbar edited and saved before the Enclosing Lasso Tool joined the Lasso group keeps its +/// saved layout: the tool stays in the drawer until Reset Toolbar or a drag adds it. +#[test] +fn a_saved_toolbar_without_enclosing_lasso_keeps_its_layout() { + let mut app = app(); + let id = vectorcraft_tools::addons::enclosing_lasso::ID; + let saved = ToolbarCategory { name: Some("Select".into()), slots: vec![["lasso", "magicWand"].iter().map(|t| t.to_string()).collect()] }; + app.ui.toolbar_edits = ToolbarEdits { basic: Some(vec![saved]), advanced: None }; + app.ui = std::mem::take(&mut app.ui).sanitized(); + assert_eq!(slots(&app), [["lasso", "magicWand"]]); assert!(slot_of(&app, id).is_none()); + app.run("toolbar.reset", json!({})).unwrap(); + let slot = slot_of(&app, "lasso").map(|i| slots(&app)[i].clone()); + assert!(slot.is_some_and(|s| s.contains(&id)), "Reset Toolbar adds it"); } #[test] @@ -166,7 +201,7 @@ fn the_commands_add_move_remove_and_reset_tools() { // Before the first slot, moved out of its group. app.run("toolbar.addTool", json!({"tool": "magicWand", "slot": 0})).unwrap(); assert_eq!(&slots(&app)[..3], [&["magicWand"][..], &["selection"], &["directSelection", "groupSelection"]]); - assert_eq!(slots(&app)[3], ["lasso"]); + assert_eq!(slots(&app)[3], ["lasso", "enclosingLasso"]); // After a slot, and into a group (last), moved out of the Rectangle group. app.run("toolbar.addTool", json!({"tool": "slice", "slot": 1, "place": "after"})).unwrap(); assert_eq!(slots(&app)[2], ["slice"]); @@ -359,7 +394,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { // Within the toolbar: Selection onto the divider over the Lasso. let tools = crate::toolbar::tests::widget_rects(&ctx, BUTTON); drag(&mut app, &ctx, 5.0, tools[0].center(), tools[2].center_top() + vec2(0.0, 3.0)); - assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "magicWand"]]); + assert_eq!(&slots(&app)[..3], [&["directSelection", "groupSelection"][..], &["selection"], &["lasso", "enclosingLasso", "magicWand"]]); // The drawer closed, the toolbar is locked: the same drag moves nothing. app.run("window.editToolbar", json!({"open": false})).unwrap(); frame(&mut app, &ctx, 6.0, vec![]); @@ -677,12 +712,11 @@ fn a_saved_toolbar_without_trim_at_crossings_keeps_its_layout() { } /// The add-ons' tools are in neither toolbar as they ship (the Trim at Crossings Tool, in the -/// Scissors tool's group, aside): the drawer lists them under their add-on's heading, and they can -/// be added from there. +/// Scissors tool's group, and the Enclosing Lasso Tool, in the Lasso tool's group, aside): the +/// drawer lists them under their add-on's heading, and they can be added from there. #[test] fn addon_tools_are_in_the_drawer_not_the_toolbars() { let mut app = app(); - let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID; let contour = vectorcraft_tools::addons::contour::ID; let box3d = vectorcraft_tools::addons::box3d::ID; let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID; @@ -698,7 +732,6 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { "slideAnchor", "sharedEdge", "smartPen", - enclosing, contour, box3d, polygonal @@ -715,11 +748,10 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() { }; assert_eq!(listed("extendPath"), Some(("Path Precision Tools", addon[..7].to_vec()))); assert_eq!(listed("smartPen"), Some(("Smart Pen", vec!["smartPen"]))); - assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing]))); assert_eq!(listed(contour), Some(("Contour", vec![contour]))); assert_eq!(listed(box3d), Some(("3D Box", vec![box3d]))); assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal]))); - for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] { + for tool in ["extendPath", "smartPen", contour, box3d, polygonal] { app.run("toolbar.addTool", json!({"tool": tool})).unwrap(); assert!(slot_of(&app, tool).is_some(), "{tool}"); } diff --git a/crates/ui-egui/src/panels/asset_export.rs b/crates/ui-egui/src/panels/asset_export.rs index 3fe249b7e3..3b251ee6cc 100644 --- a/crates/ui-egui/src/panels/asset_export.rs +++ b/crates/ui-egui/src/panels/asset_export.rs @@ -230,6 +230,17 @@ fn collect(app: &mut VectorcraftApp, ctx: &egui::Context, ids: Option<Vec<NodeId } } +/// Does the export of 3D asset `asset` draw a texture for the graphics mapped onto its faces +/// ([`vectorcraft_engine::cmd::fileio::draws_textures`])? Only objects whose 3D effects map graphics +/// are built to find out. +fn writes_textures(doc: &vectorcraft_doc::Document, asset: &ExportAsset) -> bool { + let maps = |e: &vectorcraft_doc::Effect| e.visible && !vectorcraft_render::effects::mapped_graphics(&e.params).is_empty(); + let nodes: Vec<&Node> = asset.nodes.iter().filter_map(|id| doc.node(*id)).collect(); + nodes.iter().any(|n| n.appearance.effects.iter().chain(n.appearance.items.iter().flat_map(|i| i.effects())).any(maps)) + && vectorcraft_render::effects::three_d_meshes_of_in(Some(doc), nodes.iter().copied()) + .is_ok_and(|parts| vectorcraft_engine::cmd::fileio::draws_textures(doc, &parts)) +} + /// Export assets `ids` (`files_each`: the files one asset makes) into a picked folder (without a /// folder picker: the last folder Export for Screens used, else the Desktop); the web downloads /// them, several as one zip. @@ -240,11 +251,20 @@ fn export(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { fn export_now(app: &mut VectorcraftApp, ids: Vec<u64>, files_each: usize) { // 3D assets are written as mesh files (`assets.export3D`), the others as pictures. + let web = io::is_web(app); let Some(st) = app.session.active() else { return }; let format = |id: &u64| st.doc.asset(*id).and_then(|a| a.format_3d.clone()); let (three_d, ids): (Vec<u64>, Vec<u64>) = ids.into_iter().partition(|id| format(id).is_some()); - // An OBJ is two files. - let mesh_files: usize = three_d.iter().map(|id| if format(id).as_deref() == Some("obj") { 2 } else { 1 }).sum(); + // An OBJ is two files, and an OBJ or a USDA whose graphics draw a texture writes it beside + // them. Only the web, which zips several files, needs the count. + let mesh_files: usize = three_d + .iter() + .map(|id| { + let format = format(id); + let textures = web && matches!(format.as_deref(), Some("obj" | "usda")) && st.doc.asset(*id).is_some_and(|a| writes_textures(&st.doc, a)); + usize::from(format.as_deref() == Some("obj")) + 1 + usize::from(textures) + }) + .sum(); // Create Sub-folders as the panel menu checks it: on by default, and remembered folders (per // row, format or item) are used as Export for Screens uses them (a remembered `subfolders` // false beside them would alone put every file in the folder itself). diff --git a/crates/ui-egui/src/render_worker.rs b/crates/ui-egui/src/render_worker.rs index 50d5bc087c..a4a750953f 100644 --- a/crates/ui-egui/src/render_worker.rs +++ b/crates/ui-egui/src/render_worker.rs @@ -52,6 +52,15 @@ pub struct Done { pub reused: bool, } +/// Render `job` as the worker thread does: inside the job's automation roots and deferred +/// effects, with the worker's renderer `r` and its last frame `kept`. +pub(crate) fn render(r: &mut Renderer, kept: &mut Option<crate::canvas::KeptFrame>, job: Job) -> Done { + let t0 = crate::now_ms(); + let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(r, kept, &job))); + let ms = crate::now_ms() - t0; + Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused } +} + pub struct Worker { tx: Sender<Job>, rx: Receiver<Done>, @@ -76,11 +85,7 @@ impl Worker { while let Ok(newer) = jobs.try_recv() { job = newer; } - let t0 = crate::now_ms(); - let frame = job.scope.clone().run(|| job.effects.view(|| crate::canvas::render_job(&mut r, &mut kept, &job))); - let ms = crate::now_ms() - t0; - let done = Done { key: job.key, doc: job.doc, opts: job.opts, img: frame.img, ms, moved: frame.moved, reused: frame.reused }; - if done_tx.send(done).is_err() { + if done_tx.send(render(&mut r, &mut kept, job)).is_err() { break; } ctx.request_repaint(); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 8afa8f571a..56de30acff 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -33,7 +33,7 @@ const STRIP_BUTTON: egui::Vec2 = vec2(32.0, PITCH); /// The Basic toolbar: (category, slots); each slot is a flyout group (first = default). pub const BASIC: &[(&str, &[&[&str]])] = &[ - ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "magicWand"]]), + ("Select", &[&["selection"], &["directSelection", "groupSelection"], &["lasso", "enclosingLasso", "magicWand"]]), ( "Shapes", &[ diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index d13b47a0db..37613c72e8 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -102,7 +102,7 @@ fn the_tool_buttons_are_centred_in_the_panel() { fn saved_flyout_choices_must_still_belong_to_the_slot() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for (saved, shown) in [(vectorcraft_tools::addons::enclosing_lasso::ID, "lasso"), ("magicWand", "magicWand")] { + for (saved, shown) in [(vectorcraft_tools::addons::polygonal_lasso::ID, "lasso"), ("magicWand", "magicWand")] { app.ui.slot_tool.insert("lasso".into(), saved.into()); let tree = tree(|ui| show(&mut app, ui)); assert_eq!(role_and_state(&tree, &tip(tool_info(shown).unwrap())), (Role::Button, Some(Toggled::False))); diff --git a/docs/effects-parity.md b/docs/effects-parity.md index cb857e15cd..b797dcfd45 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -183,7 +183,7 @@ VectorCraft choices; an original approximation, never compared with another appl | Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | Turntable (30.0 beta) | none | -| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | +| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | The `three-d` crate (depends on `geom` and `pathops`, with no UI or GPU dependencies) builds, rotates, projects, shades and depth-sorts the surfaces; the effects crate turns them into art. What's left (materials and shadows, ray-traced rendering, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 6a4d32510b..48250c14e6 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -323,7 +323,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | DXF | open, export | yes | yes (R12–2018) | R13–2018 closed SPLINE flags and control-point closure on import verified (#1299); circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE while non-circular curves keep the existing fallback (`crates/cad/src/tests.rs`); [Autodesk group 70](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-E1F884F8-AA90-4864-A215-3182D47A9C74.htm). DXF 2000–2018 LAYOUT objects write the paper image origin as 148/149 (was a stray 158), the shade plot codes (2004+) and the model type flag, and the plot style placeholder carries no subclass marker (#3085; structure test `r2000_and_later_files_have_the_structure_cad_apps_require`, checked with ezdxf's audit; not yet confirmed in Autodesk Fusion). DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500); VCarve QA remains open | | HP-GL/2 `.plt`, `.hpgl`, `.hgl`, `.hpg` | — | yes (pen moves, pens and widths, line types and attributes, circles, arcs, wedges and Bézier curves, filled and edged rectangles, wedges and polygons, encoded polylines, scaling and rotation; labels, symbol mode, raster images and hatching aren't drawn) | yes (`.plt`: each visible path once along its line, a pen per color or a pen table, type as outlines, clipping applied, HP-GL or HP-GL/2 with pen colors and encoded polylines) | recognized by its first instructions after any printer escapes, under its own extensions or one no other format reads; `crates/cad/src/hpgl/tests.rs`, `crates/cad/src/hpgl/write/tests.rs` (plots read back by the reader), `tests_hpgl.rs`, `import_fuzz.rs` | | DWG | open, export | no | no | no open spec; DXF instead | -| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776) | +| EMF / WMF | open, export | yes | yes | an oversized embedded PNG or JPEG is refused from its header, before any pixels are decoded (#1776); a picture cut short by a reader limit, images and pattern brushes that are not read, clips that are not applied and raster operations other than a plain copy come back as warnings; tests in `crates/metafile/src/tests/import.rs` | | PSD | open, place, export | yes (open: layers as layers, or the merged image with `layers: false`; place: merged image, or the layers embedded as a group of objects with `layers: true`; the merged image comes in clipped by the file's clipping path; every mode and depth; `.psd` and `.pdd`) | yes (layered, max editability, point type as editable type layers with `preserveText`; `tests_psd.rs`) | PSD Import Options on File › Open and on File › Place without Link (Convert Layers to Objects, Flatten Layers to a Single Image, Import Hidden Layers, Import Slices; `tests_psdlayers.rs`, `dialogs/psd_import.rs`); slices (image resource 1050, version 6 and the version 7 and 8 descriptor) open and embed as user slices with `importSlices` (`tests_psdslices.rs`); layer comps aren't read; the embedded ICC profile's tags are 4-byte aligned (#1584) | | PSB | open | yes (layers as layers, or the merged image; the merged image comes in clipped by the file's clipping path) | no | | | PNG / JPEG / GIF / BMP / TIFF / Targa | open, place, export | yes (PNG: `.png` and `.pns`; BMP: `.bmp`, `.dib` and `.rle`; Targa: `.tga`, `.vda`, `.icb` and `.vst`, raw or run-length encoded, with a 16-bit file's one-bit alpha) | yes; TIFF is also selectable in Export for Screens and Asset Export with its existing options | Targa: `tests_tiffbmp.rs`, `tests/links.rs`; TIFF: grayscale with an alpha channel or other extra channels reads (#1466 in part), and so do files that store each channel as its own plane (PlanarConfiguration 2), CMYK ones with their ink amounts, and 1-bit files compressed with CCITT Group 3 (Compression 2 and 3, one- and two-dimensional rows); the ICC profiles embedded in JPEG and TIFF have 4-byte aligned tags (#1584); PNG export marks its colours as sRGB (`embedIcc`, an `sRGB` chunk; no ICC profile is embedded, #2221) | @@ -345,6 +345,15 @@ Gradient meshes in the editing data keep each point's own color where a patch's | Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) | | Clipboard: PDF, SVG, PNG, EMF, text | yes | yes | yes | copied files paste as art; cells copied from a spreadsheet (tab-separated text) paste as a table of point type over gridlines, at most 1000 rows, 256 columns and 20,000 cells (#5296) | +Opaque CMYK PSD/PSB merged images preserve their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, +and clipping path through placement, relinking, updating, and embedding (#8316). VectorCraft stores these images +as CMYK TIFFs up to its native limit of 67,108,864 pixels and within its allocation allowance. Other CMYK composites +use the RGB import path, subject to its allocation limit; importing individual layers keeps its existing behavior. +Synthetic regressions in +`tests_psdread.rs` cover native samples, compression, metadata, and linked-image operations. The +[public PSD specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/index.html) defines +the CMYK planes and profile and resolution resources. + ## PDF form gradients PDF export's linear and radial gradients stay aligned inside transparency groups, opacity masks, diff --git a/docs/gaps.md b/docs/gaps.md index 535e54f295..2822e483b2 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -517,8 +517,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi afterwards opens in a floating window of its own (G7's Float in Window); documents already open stay where they are. Estimate unchanged. - **Done:** Hyphenation › Default Language is the language of new type, unless Document Setup chose one, and each - run hyphenates in its own language (Character panel). English and eleven Indian languages have break - points; other languages stay whole apart from the Exceptions list (#394, #4947). + run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish + and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed + their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Missing:** 2 Preferences options stored but not acted on (#394), each waiting on a subsystem of its own: Plug-ins & Scratch Disks › Primary and Secondary (documents are kept in memory; nothing pages to @@ -703,7 +704,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi Extrude & Bevel, Inflate and Rotate with Position presets ([three-d.md](three-d.md), #1407). Colored Inflate has automatic smooth vector lighting from shared membrane normals. White-light Inflate keeps its polygon shading. Every 3D facet's seam has round joins ([three-d.md](three-d.md#seams)). All four take one to ten colored directional lights, with neutral ambient applied once, a light list and independent previewing controls. Standard, Diffuse, Top Left and Right select original rigs, shared with commands; manual settings show Custom. - **Missing:** materials (base, Substance, graphics), shadows, ray-traced rendering, angular cut caps, exact visibility for intersecting and concave surfaces, the rest of 3D - Classic (Map Art), Turntable, textures, map art and shading in 3D export. + Classic (Map Art), Turntable, and in 3D export the graphics on Revolve's side, materials and shading (graphics on + planes and Extrude & Bevel's caps are exported as textures). - **Impact:** specialist; Materials is the one menu stub left. - **Estimate:** 25–45 h; plan in `plan/` before coding. diff --git a/docs/image-trace-adjustments.md b/docs/image-trace-adjustments.md index 6d2357dbe3..e4830e31b2 100644 --- a/docs/image-trace-adjustments.md +++ b/docs/image-trace-adjustments.md @@ -23,7 +23,10 @@ versions. Among those presets, Corners is 100 in Technical Drawing, 75 in Defaul Logo, Line Art and Outline, and 50 in the other eight. Noise is 1 px in Technical Drawing, 5 in High Fidelity Photo and Black and White Logo, 8 in 6 Colors and 16 Colors, 10 in Low Fidelity Photo, 15 in 3 Colors and Shades of Gray, 20 in Sketched Art, Line Art and Outline, 25 in Default, and 90 in Silhouettes (see -[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). +[image-trace-quality.md](image-trace-quality.md#preset-paths-corners-and-noise)). High Fidelity Photo +traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; see +[image-trace-quality.md](image-trace-quality.md#high-fidelity-photo-in-full-tone)); Low Fidelity Photo +traces with a Limited palette of 20 colors, Overlapping. Sliders apply on release, and their numeric fields can be edited directly. Each committed adjustment re-traces the selected object as one undo step and changes the preset to Custom. @@ -83,9 +86,9 @@ leaves out every white area whatever `ignoreBackground` is. color nearest to it in lightness and hue, with a difference in hue or chroma counted three times as much as one in lightness, so a gray or a muted brown takes a black, white or other neutral library color rather than a saturated color of the same lightness. -**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, 3 Colors, -6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one exact edge. The -canvas smooths the edges of each path on its own, so each of the two paths covers only part of the +**Abutting and Overlapping.** Abutting is the default Method, and the Default, Auto Color, High Fidelity +Photo, 3 Colors, 6 Colors and 16 Colors presets use it. With Abutting, two neighboring colors share one +exact edge. The canvas smooths the edges of each path on its own, so each of the two paths covers only part of the pixels along that edge, and a thin line of the background can show between the colors. Web browsers and PDF viewers usually draw an exported SVG or PDF file the same way and show the same line. Raster exports (PNG, JPEG, TIFF and the other bitmap formats) with None anti-aliasing do not show it at any diff --git a/docs/image-trace-quality.md b/docs/image-trace-quality.md index b111a25fb7..ab8ee313d7 100644 --- a/docs/image-trace-quality.md +++ b/docs/image-trace-quality.md @@ -83,8 +83,9 @@ gradient, texture, sensor noise): Photo trace was 86,000 anchors under the old limit; a noisier scan of the same size would have been refused. At 8,000,000 anchors a trace keeps about 0.7 GB, with a peak of about 0.9 GB while tracing. The preset rows were measured with the earlier preset values: High Fidelity Photo at Paths 90, Corners 25 -and Noise 4, Low Fidelity Photo at Paths 60, Noise 12 and 16 Colors at Paths 70, Corners 55 and Noise 10 -(see [Preset Paths, Corners and Noise](#preset-paths-corners-and-noise)). +and Noise 4 with a Limited palette of 64 colors and Overlapping, Low Fidelity Photo at Paths 60, Noise 12 +and 16 Colors at Paths 70, Corners 55 and Noise 10 (see [Preset Paths, Corners and +Noise](#preset-paths-corners-and-noise) and [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). ## Collapsed loops keep few segments A small closed loop (or a piece that returns to its own junction) whose fit collapsed to a single cubic cannot stay as one, so it kept every positioned point as a straight segment. A looser Paths @@ -250,7 +251,8 @@ Every built-in preset other than Auto Color and Flat Logo traces at Paths 50. Co The palettes, color counts, thresholds and other options of the presets did not change. The enhanced versions of these presets use the same Paths, Corners and Noise. 6 Colors and 16 Colors were at Noise 15 and Black and White Logo at 25 until [Noise joins the nearest color](#noise-joins-the-nearest-color); -the measurements below were made at those values. +the measurements below were made at those values. High Fidelity Photo's palette and Method changed +later (see [High Fidelity Photo in Full Tone](#high-fidelity-photo-in-full-tone)). Measured with the harness below (section 1, each preset on the inputs it is meant for), before and after: anchors fall in 10 of the 12 changed presets, for example 5,494 to 3,136 (High Fidelity Photo), 33 to 27 @@ -271,6 +273,47 @@ the other sections of this file, and in the Image Trace entries of [target-app-parity.md](target-app-parity.md), were measured at the earlier values. Test: `presets_have_their_paths_corners_and_noise` in `crates/trace/src/tests.rs`. +## High Fidelity Photo in Full Tone +High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting. It traced +with a Limited palette of 64 colors, Overlapping, before. Paths, Corners and Noise stay 50, 50 and 5. +These are VectorCraft's own values. Low Fidelity Photo keeps its Limited palette of 20 colors. + +Palette › Full Tone splits its colors until none spans more than its width limit. Then, while it has +fewer colors than Color detail's value (85 at 85), it splits the narrower ones too, where the image has +that many colors. The colors that look alike merge after that, and a merged color can merge again, so a +trace can end with far fewer colors than that count: a gray-to-green ramp 256 px wide with up to 8 levels +of grain a channel ends with 6 colors at Color detail 85, where the RGB test leaves 4. Full Tone's colors +merge when they are thoroughly mixed and less than 5 apart in Oklab × 100, or mixed in patches +(compression blocks) and less than 1.5 apart. The other palettes, Automatic included, keep the RGB test +(under 30 levels and thoroughly mixed, or under 12 and mixed in patches), and Automatic's continuous-tone +colors do not take the least count. These rules apply to every trace with Palette › Full Tone, so an +existing Full Tone trace or saved preset traces differently when it is traced again. + +On 19 photos, cartoons and synthetic shapes of 400 to 4,000 px, the mean pixel difference summed over the +inputs fell from 80.5 to 65.6 levels. It fell by more than 1% on 14 inputs (2.88 to 2.19 and 2.59 to 2.48 +on two photos, the second a JPEG at quality 40; 1.88 to 1.45 on a 4000 × 3000 photo; 12.40 to 7.44 on an +upscaled cartoon) and changed by less than 1% on the other 5. Anchors rose 1.66 times (1.98 million to +3.29 million) and the SVG size 1.31 times. The trace time rose 1.7 times (18.9 to 31.5 s for all 19, with +both builds tracing 3 images at a time in the same run). Flat synthetic art costs the most: 12 to 400 +anchors on a 4000 × 3000 image of two flat colors, and about 3 times the anchors on two images of +synthetic shapes (400 × 300 and 1600 × 1200), with the same pixel difference. A flat gray 192 × 128 with +up to 3 levels of grain a channel traces as 25 colors and 244 anchors, where the Limited palette of 64 +traced 1 color and 4 anchors; with up to 5 or 8 levels both trace it as 25 to 37 colors, on each of the +grays tested (28, 60, 128 and 200). + +In the same run, peak memory fell on 16 of the 19 inputs, for example 906 to 625 MiB on a 1536 × 2048 +cartoon, and rose on 3 small ones (by 5 to 11 MiB). Abutting accounts for the fall: the earlier preset +with Method › Abutting peaked at 523 MiB on the same cartoon, against 924 MiB with Overlapping, in another +run. Low Fidelity Photo, 16 Colors, 6 Colors, Black and White Logo and Auto Color give byte-identical +SVGs. On three flat colors stored in 8 × 8 blocks, each block off by up to 8 levels a channel, High +Fidelity Photo traces 3 colors as 3 paths; without the patch rule it traced 7 colors as 74 paths. + +Tests: `high_fidelity_photo_traces_in_full_tone`, `full_tone_keeps_more_of_a_noisy_ramps_tones`, +`full_tone_traces_a_noisy_dark_ground_like_a_light_one` and +`full_tone_merges_a_flat_colors_compression_blocks` in `crates/trace/src/tests.rs`, +`full_tone_merges_only_mixed_colors_that_look_alike` in `crates/trace/src/quantize.rs`, and +`full_tone_makes_one_color_per_step_of_color_detail` in `crates/trace/src/quantize/palette.rs`. + ## A simpler contour walk `contour::trace_mask` follows each region's outline along the pixel cracks with the inside on the right. It used to build a table of outgoing directions for every pixel corner in a raster pass and diff --git a/docs/mcp.md b/docs/mcp.md index a1fbd84632..ae470340e8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5441,7 +5441,11 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) adds the paths, compound paths and + groups of them drawn in it, shown and unlocked with everything in them, to the group as `livePaint.merge` does, in + one undo step; type, images and other objects stay in it as they are, and with nothing drawn no undo step is + recorded. - **Dialogs and panel state** (control channel and the app's MCP): `ui.layerOptions {ids?}` and `ui.newLayer {sublayer?}` open Layer Options (dialog `layerOptions`: name, color, template, locked, visible, printable, preview, dimImages, dimPercent; OK is one undo step; `ui.dialog.set` of `template` also sets `locked` and `dimImages`, as the @@ -7598,6 +7602,12 @@ they can't be read, as with a PNG cut short by a download or a sync still runnin can't be read" and places nothing; `clipboard.importImage` fails the same way. A JPEG cut short is placed when its pixels still decode. Both keep the decoded pixels (except a CMYK JPEG's) in the image store the renderers share, so the first render that draws the image does not decode the file again. +Opaque CMYK PSD/PSB merged images retain their 8-bit or 16-bit ink samples, CMYK ICC profile, resolution, and +clipping path when placed, linked, relinked, updated, or embedded. `file.place.info`, `image.info`, and `links.info` +report CMYK for these images. VectorCraft's native CMYK limit is 67,108,864 pixels. Composites with transparency, +images beyond that limit, and native samples beyond the allocation allowance use the RGB import path, subject to +its allocation limit. Importing individual layers with `layers: true` retains its existing behavior. + `file.place.info` describes a file without placing it and `image.info` reports a placed image's link, colour mode and effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and @@ -8848,6 +8858,9 @@ starts a new point type object at the position the advance gives, and an underli of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and split as a single line is. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. +Each of these adds one warning, with a count: a file, or a metafile image inside it, cut short by one of the reader's +limits; images and pattern brushes whose bitmap can't be read, which are left out; clips that can't be applied as the +file sets them; and raster operations other than a plain copy, drawn as a plain copy or left out. `clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it (the Windows desktop service doesn't read metafiles yet). @@ -9121,13 +9134,28 @@ default), `usdz`, `gltf` or `obj`; the panel shows a Format row for the 3D asset `assets.set3DFormat {assets, format}` sets it (an undo step only when the format changes). `assets.list` gives each asset's `format3D` (null for a picture asset). -`assets.export3D {assets?, folder?, zip?}` writes each 3D asset (default: all of them) as a mesh file named after it: +`assets.export3D {assets?, folder?, zip?, textureSize?}` writes each 3D asset (default: all of them) as a mesh file named after it: `.usda`, `.usdz`, `.gltf` (glTF 2.0, its buffer embedded) or `.obj` with its `.mtl` (whitespace and `#` in an OBJ's name become `_`). Every solid of the object (the fill's, each stroke's, a group's members') is its own mesh, with a two-sided material in the color it is painted (a gradient's stops averaged, a pattern gray). The mesh holds the solid's faces before they are projected onto the page, those turned away from the viewer included, at the object's 3D rotation, y up, about the point the object turns about: in points (USD's layer gives `metersPerUnit`), in meters in glTF. Files that would share a name get `-2`, `-3` and so on. +Graphics mapped onto a plane or onto Extrude & Bevel's front or back cap (`threeD.mapGraphic`) are exported as a PNG +texture of that face: the face's color with its graphics drawn over it, flat and unlit, on a mesh of the face's own +triangles with texture coordinates and a material that shows the texture. A face that is not opaque keeps its opacity +in the texture's alpha: as on the canvas, the graphics take the opacity of the face's fill or stroke, and the object's +opacity applies to the face and its graphics together. glTF embeds the PNG as a data URI +(`TEXCOORD_0`, `baseColorTexture`), USDZ stores it after the layer, USDA reads it through `primvars:st`, a +`UsdPrimvarReader_float2` and a `UsdUVTexture` connected to the surface's `diffuseColor`, and OBJ gives `vt` coordinates +and an MTL `map_Kd`; OBJ and USDA write the PNG beside them as `<name>-texture-1.png`, `-texture-2.png` and so on +(whitespace, `#` and `@` become `_`). USD reads a face's opacity from the texture's alpha (`outputs:a`), and an OBJ +whose face is not opaque also gets `<name>-texture-1-opacity.png`, the alpha as gray levels, for the MTL's `map_d`. +Faces with the same color, graphics and bounds share one texture. `textureSize` (128 to +4096, default 1024, VectorCraft's own values) is the number of pixels along the longer side of each texture; one export +draws at most 67,108,864 texture pixels in all, and past that it is refused. Graphics on Revolve's side are not +exported yet. The layouts follow glTF 2.0, UsdPreviewSurface (<https://openusd.org/release/spec_usdpreviewsurface.html>) +and OBJ/MTL (<https://www.loc.gov/preservation/digital/formats/fdd/fdd000508.shtml>). With `zip`, the files go into one ZIP named after the document with `-3D` added (`Untitled-1-3D.zip`), or `3D Assets.zip` when the document's title gives no file name. An object whose face has a hole that crosses the face's outline or another hole is refused, by `assets.add3D` and @@ -9815,6 +9843,20 @@ on again. {"name":"run_command","arguments":{"command":"type.convertToAreaType","params":{"ids":[42]}}} ``` +## Insert Special, Whitespace and Break Characters + +`type.insert {char?, text?, code?, unicode?, ids?|id?}` inserts one character (`char` names it, `code` and `unicode` give +its code) or the string `text`. While the Type tool edits text and neither `ids` nor `id` is given, it replaces the +tool's selection, or inserts at its caret, and the caret goes after the insertion; otherwise it appends to the end of each +selected text object. Each call is one undo step; an empty `text` at the Type tool's caret changes nothing and records no undo step. +`char: "forcedLineBreak"` (Type › Insert Break Character › Forced Line Break) inserts U+2028, which starts a new line in +the same paragraph, as Shift+Enter does; `char: "paragraphReturn"` inserts a line feed, which starts a new paragraph. A +`text` that holds U+2028 inserts the same break. + +```json +{"name":"run_command","arguments":{"command":"type.insert","params":{"char":"forcedLineBreak"}}} +``` + ## Smart Punctuation `type.smartPunctuation` replaces keyboard characters in the selected type, or in every text object with `scope: @@ -12247,7 +12289,12 @@ away); its click on a gradient mesh's line picks the line's two ends, and a click inside a patch picks the four points around it. The picked points show filled. Dragging one of them moves them all as one undo step (`object.mesh.movePoints`), a click on one of several picked points picks it alone, and the arrow keys nudge them by the keyboard increment. The active tool lists them in its options -(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). On gradient meshes a solid fill colour (`paint.setFill`, from the +(`tool.setOption {}` returns them as `meshPoints: [{id, index}…]`). Switching to the Eyedropper keeps them picked, its +options list them too, and the Mesh tool, Direct Selection or a Lasso chosen next picks them again. While a selected, editable mesh has +points picked, an Eyedropper click or Shift-click on an image or other art samples the color under the pointer into +those points alone as `paint.sampleColor {color, stroke: false, ids}` with the meshes that have points picked: one undo +step, none when the color is unchanged. Other selected objects keep their paint. A click on one of those meshes, and +Alt-click and Shift+Alt-click anywhere, are unchanged. On gradient meshes a solid fill colour (`paint.setFill`, from the Color panel, Swatches or the Eyedropper) recolours just the picked points, and when every target of `transparency.set` is a gradient mesh with points picked, its `opacity` fades those points instead of the objects (`transparency.info` then shows their opacity, `null` when it differs). Both are one undo step, and neither goes to the @@ -12257,6 +12304,16 @@ picked point's color, and `fillMixed` compares the picked points' colors with ea selected objects. The Transparency panel shows the picked points' opacity (blank when it differs), and the Control bar shows the first picked point's opacity. +A solid color dragged from the Color or Swatches panel or a Fill proxy and dropped on a selected gradient mesh, while the +Fill proxy is active, recolors the mesh point under the pointer (within 5 screen pixels), else the four points around the +patch there, as `object.mesh.setPointColor {id, points, color, keepModel: true}`. With a gradient mesh selected and a +solid fill color set, a plain Eyedropper click does the same with the fill color: on a point of any selected mesh, or +inside a patch of the selected mesh the click hits. A gradient, a pattern, a fill of None, a stroke proxy or a mesh that +is not selected keeps the earlier behavior (the whole object takes the paint, and the Eyedropper copies the appearance), +and so does an unselected object on top of the mesh at that place. +See [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); +the 5-pixel reach is VectorCraft's own. + `object.mesh.movePoints {id, points: [index…], dx, dy}` (or `{items: [{id, points}…], dx, dy}` over several meshes) moves points by (dx, dy), their handles with them; `object.mesh.setPointColor` takes `points` or `items` the same way to colour or fade several points at once. An index out of range, an index that is not a whole number ≥ 0, or a diff --git a/docs/roadmap.md b/docs/roadmap.md index 258b86d04a..4c8cc28361 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -37,8 +37,9 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. M1 selection: Enclosing Lasso selects whole objects enclosed by a freehand loop. It is an add-on -under Object › Plug-ins and has its own heading in All Tools. It has no default shortcut or Basic -toolbar slot. Shift adds and Alt subtracts enclosed objects; Escape cancels the loop. +under Object › Plug-ins, and its tool is also in the Lasso tool's group in both shipped toolbars, +after the Lasso. It has no default shortcut. Shift adds and Alt subtracts enclosed objects; Escape +cancels the loop. This is a VectorCraft addition; milestone estimates and parity scores are unchanged. The shared assessment status line and revision history are current upstream; this dated section records the submission's feature evidence and revisions without rescoring upstream or claiming a new combined build or runtime measurement. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d1a36d3f2..d9114d5d57 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -263,7 +263,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons and Weather Icons are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged) | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, the rest of 3D Classic (Map Art), Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype | 20–28 | estimated; No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -1206,7 +1206,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. With members of a group selected whole (with Group Selection, for example), a Selection-tool press on one of them keeps the selection: the pointer shows Move, a drag moves only the selected members (Shift constrains it), a Shift-click takes the pressed member out of the selection, and Alt over it shows no Distance Guides. A press on a member that is not selected, or only partly selected, still selects the outermost group ([Select objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). Test: `select::tests::a_press_on_a_selected_member_of_a_group_moves_the_selected_members`. The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode. - Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. + Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins. Its tool is also in the Lasso tool's group in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select; a toolbar edited before it joined keeps its saved layout until Reset Toolbar (tests `enclosing_lasso_is_in_the_lasso_flyout` and `a_saved_toolbar_without_enclosing_lasso_keeps_its_layout` in `edit_toolbar::tests`, `enclosing_lasso_is_in_the_lasso_group_once` in `addons::tests`, `headless_backend_methods` in `vectorcraft-mcp`). It has no default shortcut. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged. Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. @@ -1470,6 +1470,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Extrude & Bevel (both kinds) and Rotate keep the art's curves in the faces they draw, export and expand: caps and the edges of walls and bevels where they meet a cap are cubics with smooth anchors where the art's are, fitted within 0.001 pt in perspective and within the sampling tolerance on a bevel's inset. An edge of a twisted wall that is cut into pieces, a piece of curve that does not fit after 8 halvings, and the curves past 1,048,576 for one solid stay straight (VectorCraft's own values; [three-d.md](three-d.md#what-differs-from-the-public-documentation)). Tests `solid::tests::a_cap_keeps_the_curves_of_the_art`, `a_cap_in_perspective_fits_the_projected_curves`, `a_beveled_cap_and_its_walls_share_their_curves`, `twisted_beveled_tiny_and_degenerate_caps_keep_their_curves`. - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. + - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `<name>-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). @@ -1506,6 +1507,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Vertical punctuation:** fullwidth `!` (U+FF01) and `?` (U+FF1F) use their nominal glyph upright when no vertical alternate is present, following the Tu fallback in [Unicode UAX #50 §3.1](https://www.unicode.org/reports/tr50/#vo). Code-built test fonts cover point and area type with and without `vert` alternates, retain the rotated fallback for a bracket and long vowel mark, and leave horizontal type unchanged. Tests: `crates/text/src/tests/vertical.rs`. - Free Distort's dialog (Effect › Distort & Transform › Free Distort…) shows a box in the proportions of the first selected object's bounds with a handle on each corner. Dragging a handle moves that corner. A handle focused by a click or Tab moves 1% of the box with each arrow key, and 10% with Shift. Reset puts the four corners back on the box. The preview and OK run `effect.apply`, or `effect.setParams` when the dialog edits an applied effect, and the Appearance panel's inline editor opens the dialog with Edit…. Behavior reference: Illustrator CC Help (2014, [PDF](https://help.adobe.com/archive/en/illustrator/cc/2014/illustrator_reference.pdf)), page 285 (PDF page 291). - **Kerning at the start of a line:** at the Type tool's caret before the first character of the text, of a paragraph, or after a forced line break, the Kerning field, Alt+←/→ (Alt+↓/↑ in vertical type) and Reset Tracking and Kerning set the space before the character after the caret (`kerningBefore`), as the reporter of #5111 describes the reference; the character moves along its line and the rest of the line follows, as one undo step (#5111). It used to do nothing there, or kern the invisible line break. Inside a line the caret still kerns the character before it. A line that wraps in area type takes no space before its first character, and Touch Type still moves a line's first character only up and down. SVG export starts the line where the character is drawn, and on a path writes the space as the first character's `dx`; vertical type moves the character down its column. A space on the first letter of a ligature keeps the ligature whole. Tests: `tests::caret_kerning` (engine), `tests::kerning_before` (text), `the_space_before_a_lines_first_character_moves_its_tspan` (SVG). +- **Forced Line Break:** Type › Insert Break Character › Forced Line Break starts a new line without starting a new paragraph, as [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/insert-white-space-and-break-characters.html) describes: it inserts U+2028, the character Shift+Enter types, so the paragraph's Space Before does not come between the two lines (`type.insert {char: "forcedLineBreak"}`; `paragraphReturn` still inserts a line feed). Storing the break as U+2028 is VectorCraft's own choice. While the Type tool edits text, this item and the other Insert Special, Whitespace and Break Character items insert at its caret or replace its selection as one undo step, with the caret after them; without a Type tool edit they append to the selected type objects. Tests: `tests::menucmds::insert_forced_line_break_differs_from_paragraph_return`, `tests::menucmds::insert_character_goes_to_the_type_tool_caret`. - **Optical kerning:** Character and Properties offer Optical beside Auto for automatic pair spacing. The side-profile spacing method is VectorCraft's own: each pair moves part of the way toward the font's own stem spacing (the gap of `nn`, else `HH` or `oo`), keeps at least part of that gap where the outlines come closest, and changes by at most 0.12 em tighter or 0.06 em looser, so ordinary text keeps the font's spacing (#5336). Ideographs, kana, hangul, fullwidth and CJK punctuation forms and dashes keep the font's spacing. Optical keeps its mode across cosmetic style runs. Choosing Optical clears manual pair values, as Auto does, and leaves additive tracking intact; a manual value typed afterwards replaces that pair's correction ([Adjust kerning and tracking](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-kerning-and-tracking.html)). Native documents retain the mode and pair overrides; old documents use Auto. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/engine/src/tests/textedit.rs`. - **Kerning across style runs:** characters that differ only in fill, stroke, underline, strikethrough, overprint, character style name, leading, baseline shift, rotation, Character Alignment, kerning, or tracking that keeps or drops ligatures alike are shaped together, so restyling one character keeps the font's kerning pairs with its neighbors. A character with manual kerning that follows one with automatic kerning keeps the font's kerning with it (unless All Caps or Small Caps sets it as two letters, as ß becomes SS), and its value replaces the font's kerning after it. A ligature does not form across a change of style, and a change of font, size or OpenType features still shapes the characters apart. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html) (public documentation). Tests: `crates/text/src/tests/typo.rs`, `crates/text/src/tests/bidi.rs`. - **Manual kerning in right-to-left text:** a manual kerning value on a Hebrew or Arabic character changes the space between it and the next character in reading order, the one drawn to its left, under Auto and Optical kerning. The character before it keeps its place, and the caret between the pair stays beside the next character. The side the space goes on is VectorCraft's own rule. Behavior reference: [Line and character spacing](https://web.archive.org/web/20260916050333/https://helpx.adobe.com/illustrator/using/line-character-spacing.html). Test: `rtl_manual_kerning_spaces_the_character_from_the_next_in_reading_order`. @@ -1582,6 +1584,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Paragraph panel menu's Korean Line Break Anywhere (`text.setFormat {koreanLineBreakAnywhere}`, with the East Asian options, and the East Asian Composition Settings section of Paragraph Style Options) sets for each paragraph whether a line may break between any two Hangul syllables. When it is off, a word that contains Hangul breaks only at its spaces and after punctuation, or where the word is wider than the line, and takes no hyphen. New type has it off; paragraphs saved before the option read as on, so their lines do not move. The Paragraph panel menu's Reset Panel (`text.setStyle`, `text.setFormat` and `text.tabs.clear`) gives the selected type's paragraphs, or the paragraphs the Type tool's selection touches, Auto alignment, no indents or paragraph spacing, Hyphenate off with the default Hyphenation and Justification options, Auto direction, Bottom-to-Bottom Leading, the Line-end Punctuation Half Width Mojikumi Set, Regular burasagari, the Hard kinsoku set, Push Out Only, the Every-line Composer, Bunri-Kinshi, Roman Hanging Punctuation and Korean Line Break Anywhere off, no kashidas and no tab stops, as one undo step. The Paragraph panel menu's Hyphenation… (`ui.hyphenation`, `text.setFormat {wordsLongerThan, afterFirst, beforeLast, hyphenLimit, hyphenationZone, hyphenateCapitalized}`) sets each paragraph's hyphenation limits: the shortest word that breaks, the fewest letters on each side of the hyphen, the most hyphenated lines in a row, a zone at the right edge where the Single-line Composer breaks before a word instead of hyphenating it, and whether capitalized words break. The defaults are words longer than 5 letters, 3 letters on each side, no limit or zone, and capitalized words hyphenated; paragraph styles and the native file keep the options. + Text whose Character panel Language is Bulgarian, Turkish or Russian hyphenates by that language's syllable rules, and German, Polish, Portuguese or Italian text by that language's hyph-utf8 patterns in builds that embed them, within the paragraph's Hyphenation options, in both composers ([Assign languages to text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/assign-languages-to-text.html)). A word written outside its language's script stays whole, and the Preferences exceptions still come first. PDF export with type as text writes the hyphen that ends a line broken inside a word as a hyphen character where the line draws it, and the file opens with the hyphen in the line's text; kashidas are drawn as paths. The Paragraph panel's Insert Kashidas (with the Indic options; `text.setFormat {kashida}`) lengthens each Arabic word of a justified horizontal area type line with a kashida, a tatweel between its last pair of joined letters, before the word spaces widen: Short, Medium and Long kashidas are at most a quarter, half and a whole em long, Stylistic ones are whole tatweels up to an em, and None (the default) leaves the line as before; paragraph styles and the native file keep the setting. The Character panel menu's Kashidas switch (with the Indic options; `text.setFormat` / `text.setRangeStyle {kashidas}`) allows Kashidas on selected characters, on by default for new and old text. A pair of joined letters receives one only when both characters allow it; turning one off leaves other eligible pairs in the word available. Character styles and the native file keep the switch. [Public help](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/justify-text-using-kashida-and-hyphenation.html) documents the menu control and the separate paragraph length choices; the default and pair rule are VectorCraft choices. @@ -1662,6 +1665,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, cut-out edges choose no color:** in Color and Grayscale, the edge pixels that take the color beside them, and the semi-transparent pixels within two pixels of them whose color is also the opaque art's color blended with the background, do not count when the palette or the grays are chosen, so the edge of a cut-out image no longer adds a second shade of a color to Auto Color's palette, takes away an outline's color or takes a gray of its own; beside those pixels, the anti-aliasing between a color and an outline drawn along the edge is no color of Auto Color's own when it lies at least 0.45 of the way from the color to the outline and at least one in 32 of its pixels has both around it (edge pixels that choose no color count when they lie within 2.5 Oklab × 100 of the nearest of those colors): its pixels trace as the outline, so a thin outline stays a ring of few pieces, except beside an outline along the edge with a region of 8 pixels of its own, where each takes the nearer of the two, so a wider outline is not drawn wider; an outline over the edge in the color of other art traces in that color, while an opaque rim drawn along the edge keeps its color, also where other art reaches it; a thin semi-transparent outline of another color still counts, and opaque images trace as before; code-drawn cut-out outline, rim, opaque line and grayscale edge tests in `crates/trace`. - **Image Trace, blurred edges:** in Color with a Limited palette of at most 16 colors (3 Colors, 6 Colors, 16 Colors) and in Grayscale with at most 16 grays (Shades of Gray), by VectorCraft's own rule (RGB distances, 0 to 255 a channel), a blend pixel with no unblended pixel of its own color within 4 pixels takes the nearer side of the pair of colors within 8 pixels that it is best a blend of, of the 8 colors within 8 pixels nearest to its color, when that pair explains it twice as well as its own color, or when it lies between the two and off the line between them by less than 0.15 of their distance apart; it keeps its color when it is one of the pair. Grayscale compares lightness. The in-between tones of an edge blurred over several pixels no longer trace as rings around it. High Fidelity Photo, Low Fidelity Photo and Black and White trace as before, and so do Automatic, Full Tone and Document Library palettes. Noisy and textured images settle more of their pixels. By `crates/trace/tests/quality` (256 px variants), 16 Colors on blurred flat art went from 9.0 paths to 3.0, 158 anchors to 34 and 0.239 px off to 0.069, and 6 Colors from 6.0 paths to 3.0 and 0.226 px off to 0.071; askew shapes take up to 11 px more area in colors the art does not have, and with 16 Colors the largest distance from a thin line's outline to the trace goes from 23.5 px to 45.3 (see [quality notes](image-trace-quality.md#blurred-edges)). Code-drawn blurred-disc and grayscale ramp tests in `crates/trace`. - **Image Trace, preset Paths, Corners and Noise:** every built-in preset but Auto Color and Flat Logo traces at Paths 50, and so do their enhanced versions; among those presets, Corners is 100 in Technical Drawing, 75 in Default, Black and White Logo, Line Art and Outline and 50 in the other eight, and Noise is 1 to 90 px by preset. Palettes and color counts are unchanged. Figures for these presets in the other Image Trace entries were measured at the earlier values. By `crates/trace/tests/quality`, High Fidelity Photo goes from 5,494 anchors to 3,136 and Black and White Logo from 27 to 14, while 16 Colors on flat art goes from 0.100 px off to 0.123 (see [quality notes](image-trace-quality.md#preset-paths-corners-and-noise)). Test `presets_have_their_paths_corners_and_noise` in `crates/trace`. +- **Image Trace, High Fidelity Photo in Full Tone:** High Fidelity Photo traces with Palette › Full Tone at Color detail 85 and Method › Abutting (VectorCraft's own values; it was a Limited palette of 64 colors, Overlapping). Palette › Full Tone splits into at least one color per step of Color detail where the image has that many, and then merges the colors that look alike (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), which can leave far fewer; this applies to every Full Tone trace. On 19 test images the summed mean pixel difference fell from 80.5 to 65.6 levels, with 1.66 times the anchors and 1.7 times the trace time (see [quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)). Tests in `crates/trace`. - **Image Trace, Noise joins the nearest color:** in Color and Grayscale, a region below Noise whose longest-border color is 10 or more apart from its own (Oklab × 100) joins the neighboring color nearest the average of its pixels (leaving out cut-edge pixels that are the color beside them blended with the transparent background), among those sharing at least a tenth of that border, so thin dark lines no longer break into dashes; a single pixel tied between colors joins by border (VectorCraft's own rule and values). 6 Colors and 16 Colors use Noise 8 and Black and White Logo Noise 5. On three illustrations with fine dark lines the mean difference falls 29% to 42% (16 Colors) with 72% to 99% more anchors (see [quality notes](image-trace-quality.md#noise-joins-the-nearest-color)). Tests in `crates/trace/src/quantize/denoise.rs`. Scores and hours unchanged. - **Image Trace, simpler contour walk:** `contour::trace_mask` works out each turn from the pixels during the walk, with no precomputed direction table and no assertion; identical loops to the previous walk on every 4 × 4 mask (see [quality notes](image-trace-quality.md#a-simpler-contour-walk)). - **Image Trace, measured:** `crates/trace/tests/quality` traces drawings made from known vector art with every preset and [`image-trace-quality.md`](image-trace-quality.md) records the numbers against the baseline. Black and White, Grayscale and Color place each edge by the blend of the pixels across it (to a fraction of a pixel on anti-aliased and blurred images; hard-edged images are read as staircases) and fit outlines as Flat Logo does. *Measured* on each preset's own inputs, all sizes and variants: Default's outlines went from 0.31 px off on average to 0.09 (largest 1.51 to 1.02), Black and White Logo's from 0.27 to 0.06 with 0.3 kinks per trace where it had 15, and the gaps between abutting paths from 64 px to 22. On clean curved shapes Black and White Logo is 0.02 px off (the open tracer measured beside it: 0.20). The palette is made of the picture's own colours (blends along edges take none of it, colours that noise made of one colour merge, a blend pixel goes to one of the two colours it lies between; #1504): 16 Colors on flat art, all variants, went from 70 paths to 4.2 and from 5.1 px off to 0.13, with no path left in a colour the art doesn't have (5.9 before). Photos are smoothed within their tones before they are quantised and stacked layers go by lightness (#1516): High Fidelity Photo went from 3,653 paths to 121 with its colour error down from 2.30 to 1.75, and a 16 megapixel photo-like image is traced in 3.5 s where 4 megapixels were refused. Since then, by the same harness: outlines are cut at their junctions and each shared piece is fitted once (#1535: gaps and overlaps between abutting paths 22 to 50 px of area down to under 2); layers are traced within the box of their pixels and a few at a time (#1546: a 16 megapixel photo 3.9 GB to 0.9 GB); black and white are read against the image's own black and the paper near each edge (#1563, for thin lines in blurred and scanned art); Ignore Color and the Auto Color and Outline presets (#1574); Snap Curves To Lines levels lines within 2.5 degrees of level or upright (#1593, the angle our choice); Create: Strokes puts centre lines in the middle of their ink and makes them as wide as it (#1595: Outline 0.295 to 0.052 px from the true centre line, 18.4 to 2.7 anchors a stroke); sharp corners whose pixel is mostly outside the shape stay corners (#1609: Default 69% to 76% kept). Three options, each off unless asked for as the legacy presets have them: Shapes (#1609: 57 to 62% of plain circles, ellipses, rectangles and regular polygons come out as live shapes, rounded rectangles rarely), Auto Grouping (#1618: paths grouped with what lies inside them, the same picture) and Gradients (#1627: linear gradients traced as one gradient-filled path; on gradient inputs 6 Colors' colour error 2.12 to 0.62 with 6.4 to 3.4 paths, none found in flat art). Snap Curves To Lines moves no end of a line by more than 1.6 px, so long lines a degree or two off stay as the image has them (#1647: Technical Drawing's largest distance 4.21 px to 1.46). Flat Logo takes the tones a scan's uneven paper makes of one colour for one colour (#1657: on scans 470 paths and 21 px off to 8.5 paths and 0.09 px). Shapes finds rounded rectangles and shapes in aliased, blurred and scanned art (#1845: 57 to 62% of the plain shapes up to 98 to 100%, no false shape but one line 2 px wide). Stroked lines get square caps where their ink is cut square, and a wide end that turned towards a corner goes back on its line (#1846: Outline's largest distance 2.94 px to 0.88, 14 anchors to 10). Each of the 14 documented presets has an enhanced version with Auto Grouping and, in all but High Fidelity Photo, Shapes (#1847), measured beside its preset: equal or better within 0.005 px and 1% of edge ΔE on every preset's own inputs (Default 0.091 to 0.083 px); Auto Grouping keeps traced order in its groups, which removed a light seam along the counters of letters. Gradients grows a gradient over the pixels noise and soft rims took off it (#1848: blurred and noisy linear gradients 3 to 11 paths beside the gradient down to 0.5 with 6 Colors, 24 to 56 down to 0.5 to 1.5 with High Fidelity Photo). Silhouettes is 0.52 px off because its threshold is 200 (0.11 px at 128). Still weak, by the same numbers: rounded rectangles and other line-and-arc outlines take 12 to 16 anchors (the fitter does not split lines from arcs), blurred and scanned polygons lose corners, hairlines under half a pixel are lost to the threshold, aliased art is about 0.25 px off, a scan's uneven paper splits into tones when more colours are asked for than the art has, stroke junctions stay at their skeleton pixels, a three-stop gradient in a small or scanned disc is not found, radial gradients stay bands (a draft, #1849, traces them; the documented option is for linear ones, so it waits for a decision), near-regular polygons a few dozen pixels across are made regular with Shapes (up to 0.5 px off), and aliased stroked lines are 0.8 px off at worst. @@ -1670,13 +1674,14 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **A point on a mesh's outline is on the mesh:** a point exactly on the outline of a gradient mesh (within a millionth of a point) locates on the edge it lies on, on all four sides alike and with no tolerance, as it already did on the top and left edges, so `object.mesh.addLine` and Create Gradient Mesh `at` a point on the bottom or right edge add their lines there instead of reporting the point outside, and the Eyedropper samples the mesh's color there; a point just outside still needs `tolerance`. Tests: `mesh_locate_takes_a_point_on_any_side_of_the_outline` in `crates/doc/src/live.rs`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Several mesh points at once (#4207, #4208, #4170):** the Mesh tool and Direct Selection pick several points of a gradient mesh or mesh envelope: Shift-click adds a point or takes a picked one away, Direct Selection's marquee picks the points inside it (Shift toggles them) and selects their meshes, and its click on a mesh line picks the line's two ends and one inside a patch the four points around it. The picked points show filled; dragging one moves them all as one undo step and the arrow keys nudge them (`object.mesh.movePoints {id, points, dx, dy}` or `{items, dx, dy}`), and a click on one of several picked points picks it alone. A solid fill colour (`paint.setFill`: Color panel, Swatches, Eyedropper) recolours every picked point, and the Transparency panel's Opacity fades them instead of the object, the panel showing their opacity (blank when it differs); `object.mesh.setPointColor` takes `points` or `items`. Public reference: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (Shift selects multiple mesh points; a fill colour colours the selected point), [Macworld, gradient mesh](https://www.macworld.com/article/202693/gmesh2.html) (Direct Selection: a mesh line selects the points at both ends, a patch the points around it, Shift-click adds or removes points), [Peachpit](https://www.peachpit.com/articles/article.aspx?p=1638270) (each mesh point can have its own colour or transparency). Tests: `shift_clicks_pick_mesh_points_that_drag_and_nudge_together` and `direct_selection_picks_mesh_points_by_marquee_line_and_patch` in `crates/tools/src/meshedit.rs`, `picked_mesh_points_take_the_fill_opacity_and_drag_together` in `crates/engine/src/tests/editcolors.rs`, `mesh_points_move_and_colour_together` in `crates/engine/src/tests/live.rs`. Scores and hours unchanged. - **Picked mesh points in the panels** (VectorCraft's own rule): with points of a gradient mesh picked by the Mesh tool, Direct Selection or the Lasso, the Fill proxy, the Color panel and the Color Wheel show the first picked point's color, so their sliders keep the color a drag sets, and "?" shows when the picked points' colors differ. The Control bar shows the first picked point's opacity. Tests: `the_fill_proxy_shows_the_picked_mesh_points_color`, `the_fill_proxy_follows_where_the_fill_goes_with_an_appearance_row_active` and `the_fill_proxy_counts_picked_mesh_points_beside_other_objects` in `crates/engine/src/tests/xform.rs`, `picked_mesh_points_are_the_color_the_panel_shows_and_edits` in `crates/ui-egui/src/panels/color/tests.rs`, `picking_mesh_points_shows_their_opacity` in `crates/ui-egui/src/panels/transparency.rs`. Scores and hours unchanged. +- **The Eyedropper samples into picked mesh points (#8090):** mesh points picked with the Mesh tool, Direct Selection or the Lasso stay picked after switching to the Eyedropper and go back to one of those tools chosen next, and a click or Shift-click on an image or other art then samples the color under the pointer into every picked point as one undo step, leaving the mesh's other points and its appearance as they were. VectorCraft's own rules: a plain click on vector art samples its color into the points instead of copying its appearance, other selected objects keep their paint, and a click on a mesh with points picked works as before. Public references: [Edit mesh objects](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-meshes/edit-mesh-objects.html) (a mesh point is recolored by selecting it and choosing a fill color), [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Shift-click samples the color from a part of a mesh object or a placed image and applies it to the selected fill). Tests: `picked_mesh_points_take_the_eyedropper_sample` in `crates/engine/src/tests/eyedropper.rs`, `picked_mesh_points_take_the_color_a_click_samples` in `crates/tools/src/xform/eyedropper.rs`, `mesh_point_tools_take_back_the_eyedroppers_picks` in `crates/tools/src/meshedit.rs`. Scores and hours unchanged. - **Image Trace Flat Logo mode:** a fourth mode beside Black and White, Grayscale and Color, for flat-colour logos. Each pixel is read as a blend of the logo's colours (found automatically or named), the blend is interpolated smoothly and every outline is placed where two colours are equally present, so edges are accurate to a fraction of a pixel. Outlines are then cleaned: corners the blur rounded are put back, near-straight runs and near-circular arcs become exact lines and arcs, the rest is fitted with as few Béziers as the tolerance allows, touching colours overlap by a hair so no gap opens, and an outline that strays from the raw contour is fitted plainly instead. Gradients and photos are refused with advice to use Color. Line art whose only solid area is white paper (strokes a pixel or two wide) takes its colours from the strokes' cores, with the lighter shades along a stroke's anti-aliased edge folded into its ink; a page whose ink (a channel at least 48 below white) covers under 1% of it traces to nothing, as blank paper does. *Measured* (a local experiment, not run in CI): a flat-colour logo's vector original was rendered down to a soft 199 × 100 px transparent PNG, traced, and the result compared with the original at 1600 px wide. The built-in colour presets (6 Colors, 16 Colors, High Fidelity Photo, Low Fidelity Photo) had a mean edge error of 2.5 to 3.4 px and region overlap of 0.88 to 0.91; Flat Logo had 0.78 px and 0.966 (0.48 px and 0.975 from a crisp source), in about 0.1 s. Limits: flat-colour art only; needle-thin sharp tips are shortened by about 1.7 source pixels because the blur erases them; it works at no more than 1024 px on the long side (larger images are averaged down first); only one logo family has been scored against a vector original. - **Image Trace, Flat Logo named colors only:** with `logoColors` named, `"logoWhite": false` traces those colors only, so white areas take the nearest of them and no white is added; a named white is kept, and enclosed transparent areas stay holes; code-drawn tests in `crates/trace` and `crates/engine`. - **Image Trace, Flat Logo flat-art check with named colors:** with `logoColors` named, whether the image is flat art is judged by its own colors, as many as are named, with white, or as the Colors setting gives, whichever is more. Named colors 20 levels off a flat badge's colors still trace it, a hatch on a light ground gives the same result with close and far named colors, a gradient's refusal score does not depend on how far the named colors are from it, and areas of colors that were not named are traced in the named colors instead of being refused; code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color between two others:** an anti-aliased edge pixel between black and white is read as a blend of black and white, not of black and a gray that lies between them, when the flat areas around it and the pixels beside it show that edge, so a black disc beside a gray square on white, with sharp edges or edges blurred by up to about half a pixel, traces with one gray path, the square, instead of the square plus 8 to 24 gray slivers around the disc with the colors found or named exactly; on edges blurred by 1 to 3 pixels, the pixel also counts as on that edge when paths of up to 5 steps through pixels that keep getting darker and lighter reach past the gray both ways, and black and white then lie as near as the steps to them, so the same disc and square trace with one gray path at blurs of 1 and 2 pixels and with at most 4 slivers of up to 3 pixels in a light gray at 1.5 pixels, where up to 33 gray paths were traced before (at a blur of 3 pixels with the colors named, a gray of 200 leaves 4 slivers with no area and a light gray of 230 leaves 8 small slivers, where 11 and 14 gray paths were traced before; pixel noise of a level or more can still leave gray slivers); when the first step toward black or white already comes to that color, the path the other way stops at a pixel of the gray, so with edges blurred by 0.6 pixels a gray band 3 to 8 pixels wide along black traces gray at no fewer than 4 of every 5 of its pixel centers; with sharp edges, gray strokes two and three pixels wide beside black stay gray (a soft-edged gray stroke about two pixels wide lying along black traces as black and white, and a short one about three pixels wide can lose most or all of its gray); on edges blurred by a pixel or more, a soft-edged gray band up to 4 pixels wide along black traces as black and white, with gray at no more than 1 of every 16 of its pixel centers, at blurs of 1.5 and 2 pixels, a light gray stroke 2 pixels wide and 2 pixels from black, blurred by 1.5 pixels, traces gray at about 10 of the 34 pixel centers along its middle and one 4 pixels away at about 25, and a soft-edged gray stroke running out of black, blurred by 1 or 1.5 pixels, loses 3 or 4 of the 16 pixel centers along its middle nearest black; a one-pixel gray line of at least 13 touching pixels between black and white stays gray (a shorter one, or one that falls between pixels or is blurred, traces as black and white); code-drawn tests in `crates/trace`. - **Image Trace, Flat Logo with a color beyond both colors of an edge:** an edge pixel between a gray panel and a charcoal disc on a paler gray ground is read as a blend of the panel and the disc, not of the ground and the disc, when the pixels beside it lie on each side of it, none lies past the panel toward the ground, and lighter pixels lead from it to the panel's color or to a flat area of the panel, so the disc traces with three paths, one per color, with the colors found or named, instead of with 28 slivers of the ground around it when its edges are sharp and one sliver when they are blurred by 0.7 pixel (an edge blurred by a pixel or more can still leave slivers of the ground); the pixels of a pale line on the disc, one pixel wide, blurred over three pixels or falling between two pixels, and the edge of a gap of the ground's color between the disc and the panel keep the ground in their blends; code-drawn tests in `crates/trace`. - **Image Trace, Keep Colors:** `"keepColors": ["#rrggbb", …]` traces only the palette colors near a listed color (Abutting: each with the paths the trace of every color gives it; Overlapping: not reaching under the colors left out), in Black and White, Grayscale and Color; code-drawn tests in `crates/trace` and `crates/engine`. -- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More), Automatic (flat art with its own colours, else Full Tone; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). +- **Advanced art:** live Blends (steps/distance/smooth colour, editable spine, anchor-targeted Blend tool, faithful interpolation, knockout), Envelope Distort (warp/mesh/top object, Reset, full Envelope Options, mesh handles, Edit Contents; type, images, symbols, gradients, patterns and appearance distorted everywhere), Liquify tools with options and pen pressure, Puppet Warp with rotating pins, Perspective Grid with presets, movable planes and projected type (choosing a perspective tool shows the grid; Hide Grid hides it with the tool still chosen), Gradient Mesh, Shape Builder (stroke-only open paths and lines cut the regions they cross and enclose regions of their own, and regions they bound merge without seams where the lines cross at rounded coordinates (#893); filled open paths count as closed; erase mode while Alt/Option is held: a minus pointer, red highlights of what will go, a click or drag deletes the regions touched, the pieces of open lines and the edges (outline pieces between the points where paths meet, opening their paths there) it passes over, one undo step, `shapeBuilder.merge {erase}` and `shapeBuilder.regions` edges over MCP), Live Paint (every path an edge, open lines included), Image Trace (12 presets, colour layers traced in parallel; a trace past two million anchor points is refused with advice rather than running out of memory, an image over 64 megapixels is traced scaled down to that size (aspect kept, paths at the image's own size) and one over 192 megapixels is refused, and a selection too large to outline shows its bounds (#525); Object › Image Trace › Make and Make and Expand trace at once with the Default preset, #543; with an image selected the Control bar and the Properties panel show Image Trace, whose arrow traces with any preset, Mask (`object.maskImage`: a clipping path on the image's outline, selected so its handles crop), Crop Image (a crop box on the image, starting on its part over the artboard, dragged by its handles or inside it, the outside dimmed, with X/Y/W/H, Apply and Cancel in the Control bar, Enter and Escape, #734; an image that isn't turned or skewed, isn't CMYK and can be read at its recorded size is cut from its own pixels when the crop edges fall on its pixel grid, copied as they are without resampling; any other image is drawn, #5534; `object.cropImage {rect}` for agents, `{trim: true}` cuts an image to its pixels that aren't fully transparent, pixel for pixel) and Embed or Unembed in place of Fill and Stroke; with an Image Trace object selected, its Preset (choosing another traces again), View, the Image Trace panel and Expand, plus Release in Properties; the five View modes (Tracing Result, with Outlines, Outlines, Outlines with Source Image, Source Image) redraw a trace on screen without tracing again, are saved with it and `imageTrace.setView` sets them, while exports and Expand keep the result; the panel's Advanced section is a header that stays open or closed as it was left (part of #641); Color mode's Palette: Limited, Full Tone (as many colours as the tones need, Less … More, split into at least one color per step of Color detail before colors that look alike merge), Automatic (flat art with its own colours, else as many as the tones need; a heuristic) and Document Library (the most used colours of the document's swatches or a swatch library, filled with the swatch colours as they are), part of #641; Advanced › Create: Fills and/or Strokes, where lines up to the Stroke width trace as stroked centre lines (distance transform, thinning, a skeleton graph with spurs pruned, curve fitting; one width per line; without Fills, wider areas become stroked outlines), part of #641), pattern swatches with pattern editing mode, live Repeat (radial/grid/mirror). A single selected mirror repeat shows a prominent axis with a center move handle and two rotation handles. Drag the line or center to change spacing, or an end to change angle; Shift snaps rotation to 45°. The original artwork stays in place, the reflected copy previews live, Escape cancels and each drag takes one undo step through `object.repeat.options`. Controls follow zoom/view rotation and hide with edges or the bounding box. Engine and headless canvas regressions passed for gestures, history and visibility; native move, rotation and Escape screenshots were reviewed. [Public mirror-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-mirror-repeat-options.html). A single selected grid repeat shows a handle below the grid for rows, one right of it for columns and one past its bottom-right corner for both, and sliders between its first two columns and rows for the horizontal and vertical spacing; the source keeps its size, each drag is one undo step and Escape cancels it ([public grid-repeat reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html), #2691). Object › Expand turns radial, grid and mirror repeats into groups of their instances (#1765, #1756). While Crop Image shows its box, the Control bar also sets the cropped image's resolution (PPI: a list of 72, 96, 150, 200 and 300 ppi with the ones above the image's own disabled, or a typed value; at most the image's own, or 300 ppi for a linked image ([Crop Image](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=352))), a reference point that X and Y name and that W and H resize about, and a link that keeps W and H in proportion; `object.cropImage {ppi}` resamples the cut pixels and refuses a resolution above the limit, and `tool.setOption` sets `ppi`, `reference` and `linked` ([Crop images](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/crop-images-in-illustrator.html)). The list's resolutions and the default (the image's own resolution, the center, unlinked) are VectorCraft's own. Choosing the Blend tool again while it is active (its toolbar button, W or `tool.select`) finishes the blend: the object clicked first is dropped and the next click no longer adds to the blend just made, so the click after it starts a new blend ([Blending objects](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)). Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. @@ -1694,6 +1699,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Create Strokes decides stroke or fill per feature, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) describes the Strokes width: the widest feature of the image that can become a stroke. A shape wider than Stroke somewhere keeps as its area every disc wider than Stroke that fits in it, and each piece outside those discs that reaches out of them at least one and a half times its own width (and 3 px) is traced as a stroked center line, its end at the area carried to the cut so the line's cap closes the join. Corners and edge slivers stay in the area. Which pieces count as features is VectorCraft's own rule. Each line still has one width; without Fills, the area is a 1 px outline as before. Tests: `thin_features_of_a_wide_shape_are_strokes_and_its_body_a_fill`, `wide_shapes_without_thin_features_stay_one_fill` and `distances_to_seeds_equal_brute_force` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. - The ignored centre-lines class measures that split on a mixed-width body scene: one disc with arms of 2, 3 and 5 px, at Stroke 6 px, traces as three stroked paths and one filled path in both the anti-aliased and hard input, with 100.0% of the arms' center samples found and 99.3% (anti-aliased) and 98.3% (hard) of the disc's pixels filled ([quality notes](image-trace-quality.md#centre-lines)). Test: `mixed_width_body_is_one_shape_traced_as_a_fill_and_strokes` in `vectorcraft-trace`. The Image Trace score and estimates are unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. + Paths drawn in an isolated Live Paint group join it when isolation mode ends, as the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html) describes: drawing paths in the isolated group and pressing Esc adds them. `object.exitIsolation` (Esc, the Control bar and isolation bar exits, a double-click outside, the Layers panel and the canvas context menu) adds the shown, unlocked paths, compound paths and groups of them drawn in the group as Merge does, in one undo step, and `object.isolate` on a level outside the group does the same. As VectorCraft's own rules, type, images, hidden and locked objects drawn there, and groups holding one, stay in the group as they are, and Gap Options, Merge and Release keep them; an exit with nothing drawn records no undo step. Evidence: `tests::build::{live_paint_isolation_adds_drawn_paths_on_exit, live_paint_isolation_adds_only_paths_it_takes, live_paint_isolation_leaves_a_group_holding_a_locked_path, live_paint_isolation_adds_drawn_paths_when_isolating_a_level_outside, live_paint_isolation_adds_a_drawn_group_isolated_inside_it, live_paint_isolation_keeps_art_named_like_its_parts, live_paint_keeps_type_drawn_in_it_through_gap_options_merge_and_release}`. With the Live Paint Bucket selected, Alt-click on vector art samples its fill, stroke and stroke weight into the paint defaults ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)). On a placed image it samples the image pixel as a solid fill with no stroke. Alt+Shift-click samples only the color under the pointer, including an intermediate gradient color or image pixels, into the active fill or stroke ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). Neither click paints or changes the selection or selected art, and the next Bucket click paints with the sampled paint. Evidence: `tests_build::live_paint_bucket_alt_sample_paints_next_face_without_changing_selection`. Double-clicking the Live Paint Bucket opens Live Paint Bucket Options ([Paint with the Live Paint Bucket tool](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html)): Paint Fills (on) and Paint Strokes (off) set whether a click paints faces, edges or both, Highlight turns the outline of the face or edge under the pointer on or off, and Color and Width set it (red and 4 px by default). Faces are outlined at the Width and edges at half of it, as the page says faces are highlighted with a thick line and edges with a thin line. With both on, a click paints the edge within 4 px of the pointer, else the face, and Shift switches to Paint Fills only; with one on, Shift switches to the other. The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintBucket"}`). Evidence: `builder::tests::{bucket_options_choose_what_a_click_paints, bucket_options_set_the_highlight, bucket_highlights_an_edge_thinner_than_a_face}`, `dialogs::live_paint_bucket::tests::double_clicking_the_tool_opens_its_options_and_ok_sets_them`. Live Paint Bucket double-click and triple-click, as [the help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) describes them: a double-click on a face fills it and the faces reached across edges that draw no stroke, and on an edge it paints the edges joined to it with the same stroke; a triple-click fills every face of the group that has the face's fill, or paints every edge that draws with the edge's stroke paint, each with the bucket's paint (`livePaint.fill` and `livePaint.strokeEdge` `{scope: "connected" | "samePaint", match?}`; `pointer_gesture` and `ui.pointer` take `tripleclick`). Each click paints as it arrives, as its own undo step when it changes a paint, and the paint compared is the one the face or edge had before the first of its clicks that painted it, including a click whose drag or release crossed it; a first click that made the Live Paint group counts when the face it filled is the clicked face. With Space held for the view tools, a click, double-click or triple-click paints nothing and no face or edge is outlined, and with Cmd/Ctrl held a double-click or triple-click paints nothing. Which faces and edges join and which paints match are VectorCraft's own rules. Evidence: `tests_build::{live_paint_bucket_double_click_floods_across_unstroked_edges, live_paint_bucket_double_click_floods_curved_and_narrow_faces, live_paint_bucket_double_click_floods_across_hidden_edges_and_past_gaps, live_paint_bucket_triple_click_fills_every_face_of_the_same_fill, live_paint_bucket_triple_click_after_a_release_across_an_edge_matches_the_fill_before, live_paint_bucket_triple_click_released_from_another_face_matches_the_fill_before, live_paint_bucket_triple_click_after_making_the_group_across_an_edge_matches_the_made_fill, live_paint_bucket_triple_click_after_making_the_group_under_an_unfilled_path_matches_the_made_fill, live_paint_bucket_triple_click_after_merging_across_an_edge_matches_the_face_fill, live_paint_bucket_triple_click_after_merging_two_groups_matches_the_merged_fill, live_paint_bucket_triple_click_after_a_merge_splits_a_face_matches_the_part_fill, live_paint_bucket_triple_click_after_merging_matches_the_fixed_gradient, live_paint_bucket_triple_click_after_making_the_group_matches_the_made_fill, live_paint_bucket_double_and_triple_click_paint_joined_and_same_stroke_edges, live_paint_bucket_double_click_across_a_junction_paints_the_joined_edges, live_paint_bucket_double_click_released_back_on_the_first_edge_paints_the_joined_edges, live_paint_bucket_edge_double_click_after_filling_a_face_paints_the_joined_edges, live_paint_bucket_triple_click_with_a_cmd_press_between_matches_the_fill_before, live_paint_scope_and_match_are_checked}`, `builder::tests::{bucket_double_and_triple_click_widen_what_a_click_paints, bucket_triple_click_after_making_the_group_on_another_face_matches_its_own_face, bucket_triple_click_with_a_click_on_another_face_between_matches_the_first_fill, bucket_triple_click_with_a_view_tool_press_between_matches_the_first_fill, bucket_highlights_nothing_with_space_held}`, `canvas::tests::bucket_triple_click_with_a_view_tool_press_between_matches_the_fill_before`, `tests::build::{live_paint_scoped_fill_and_stroke_skip_parts_with_the_paint, live_paint_bucket_cmd_double_and_triple_click_paint_nothing}`, `tests::livepaint::{a_triple_click_fills_every_face_of_the_same_fill, clicks_with_space_held_paint_nothing}` (MCP). @@ -2024,6 +2030,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` saved without PDF compatibility (its PDF part only a placeholder page) is placed and pasted from its editing data, as it opens: File › Place places the art of the layers that show on the first artboard (`file.place`'s `page` places another one), and Paste of it as PDF data (`clipboard.importPdf`) takes every object. `document.open` with `pages` naming every page of such a file opens it the same way (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Explicitly requested editing data keeps the full single artboard when its PDF page is capped at 14,400 pt (#6865; `crates/eps/src/import/tests_native.rs`). Scores and estimates unchanged. A `.ai`, or a PDF saved with Illustrator's editing data, whose PDF part can't be read (a stream the import refuses) opens from its editing data, with the PDF part's error as its first warning; File › Place places its first artboard the same way, and Paste of it as PDF data with `editingData: true` takes every object (part of #4366; `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A PDF, or a `.ai` read through its PDF part, opens an image that decodes to up to 4 GiB with up to 2^30 pixels in a 64-bit desktop build (31404 × 31403 RGB pixels are 2.76 GiB), and up to 1 GiB with 2^28 pixels in 32-bit and web builds. A file with an image that would decode to more is refused with the size it would decode past, and an image with more pixels is left out with a warning (#4366). An opaque image is kept as RGB, without an alpha channel (`crates/pdf/src/streams.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part; CCITT Group 3 and planar files with extra channels are not read); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). - JPEG XL (`.jxl`) images open and place, linked or embedded, as their first frame, decoded with jxl-oxide and stored as PNG: 16-bit and floating-point samples become 8 bits, alpha is kept, and an image past the pixel allowance is refused from its header (part of #2306; `crates/engine/src/cmd/fileio/tests_jxlread.rs`). - The Open and Place dialogs list PostScript `.ps` files and `.epsf` files. A `.ps` file opens and places through the EPS reader (its first page), also when its header is only `%!`, as the `ps` format, which exports don't write (Print to PostScript does); an `.epsf` file opens and places as EPS. Copied in a file manager, these files paste as EPS, and `clipboard.importEps` also reads PostScript whose header is only `%!` (`crates/engine/src/cmd/fileio/tests_epsimport.rs`). @@ -2049,6 +2056,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF import warns about what the reader leaves out or does not play as the file asks, with counts: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546). diff --git a/docs/type-parity.md b/docs/type-parity.md index 3a5cdb00ca..5317d1e4cc 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -77,7 +77,7 @@ against Illustrator's public documentation; **estimated** unless noted. | CJK: warichu | done | Character panel menu › Warichu and Warichu Settings… (`text.setFormat` / `text.setRangeStyle {warichu, warichuLines, warichuGap, warichuScale, warichuAlign}`, `ui.warichuSettings`), with Show East Asian Options ([Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)): marked characters set at a percentage of their size and stacked on 1 to 6 lines inside their line, one above the other in horizontal type and side by side in vertical type, with a line gap and eight alignments; a block stays whole on one line. Saved natively, carried by character styles, drawn on the canvas and in every export (SVG, PDF and `.ai` write such type as outlines). Type on a path sets the characters at their own size. Evidence: `tests::warichu`, `dialogs::warichu::tests`, `typecmd::area_tests::warichu_is_a_character_attribute_set_saved_and_exported` | | CJK: composite fonts | partial | Type › Composite Fonts… (`type.compositeFonts.set`), with Show East Asian Options: a font made of a font per class of character (Kanji, Kana, Punctuation, Symbols, Roman, Numerals), each with its own style, size and baseline in percent of the type's size, Kana, Roman and Numerals with horizontal and vertical scale, and Kana with Scale at Center; New, Delete Font, Import… and Export… (`.vccomposite`, `type.compositeFonts.import` and `.export`) ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=347)); custom character sets (Custom: New, Delete Set, characters added by Direct Entry or Unicode code and deleted), each with its own font, style, size, baseline and scales, ahead of the classes, the later set winning a character two list (`custom` in `type.compositeFonts.set`) ([Customize characters in a composite font](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348)). Composite fonts are listed first in the font menus, saved with the document, and their type is laid out per set and class; SVG and legacy `.ai` write it as outlines. Show Sample draws the font picked with lines for its ICF box, em box, baseline, cap height, highest ascent and lowest descent, highest ascender and x-height, each shown or hidden by its button, at the Zoom picked ([Creating composite fonts](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=352)). Not yet: the Units menu. Evidence: `text::composite::tests::characters_fall_in_their_classes`, `text::composite::tests::custom_sets_take_their_characters_before_the_classes`, `tests::composite::composite_type_draws_each_class_in_its_font`, `tests::composite::custom_character_sets_take_their_characters_first`, `compositefonts::tests`, `dialogs::composite_fonts::tests` | | CJK: ruby | partial | ruby (ふりがな) for live text (`type.ruby`): a reading over a byte range, above (right of the column in vertical type) or below, start/centre/end alignment, size, overhang or squeeze; saved natively, laid out with its line growing, drawn on the canvas, in SVG and PDF (as outlines where ruby is present), in EPS, EMF/WMF and legacy `.ai` (legacy `.ai` writes type with ruby as outlines), and kept by Create Outlines, Expand Appearance and flattening, each glyph where the layout puts it (`typecmd::ruby_tests::create_outlines_keeps_the_ruby_where_it_is_laid_out`) | #633 | -| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English and eleven Indian languages hyphenate by run language; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | +| Language per character (Character panel › Language, character styles), text shaped in it | done | `text.setFormat` / `text.setRangeStyle {language}` by name or BCP 47 tag, one of Document Setup's languages (Hindi, Marathi, Gujarati, Bengali, Punjabi, Tamil, Telugu, Kannada, Malayalam, Odia and Urdu added, #4943; Assamese and Sanskrit added, #4947; Nepali, Konkani and Sindhi added, #4943; Serbian: Cyrillic, Serbian: Latin and Croatian; Bulgarian, #5945); the shaper gets the tag, so the font's language forms apply (OpenType `locl`: Turkish keeps `fi` apart and the dot on its i, #4940); new type takes the document's language; saved as the tag only when set, carried by character styles (#4946). English, eleven Indian languages, Bulgarian, Turkish and Russian hyphenate by run language, and German, Polish, Portuguese and Italian do in builds that embed their patterns; a word outside its language's script stays whole; Sanskrit automatic hyphenation awaits allowlisted patterns (#4947). Not yet: `.ai`/PDF import of a text's language, paragraph styles. Evidence: `features::tests::language_picks_the_fonts_forms`, `features::tests::serbian_gets_the_fonts_serbian_forms`, `typecmd::area_tests::language_is_a_character_attribute_saved_only_when_set`, `tests::typo::indic_language_runs_hyphenate_with_both_composers`, `hyphen::tests::sanskrit_without_allowlisted_patterns_uses_only_exceptions`, `hyphen::tests::rule_languages_break_by_their_own_rules`, `hyphen::tests::pattern_languages_break_at_their_own_patterns`, `tests::typo::a_russian_run_hyphenates_at_russian_break_points`, `tests::docsetup::the_further_indian_languages_are_document_and_text_languages`; spelling is checked in each run's Language (`text.spelling.check`, #4936) | | No Break | done | Character panel menu (`text.setFormat` / `text.setRangeStyle {noBreak}`): the marked characters stay on one line, including across a space; a run that does not fit after earlier text moves together, and a run longer than the line stays together. Evidence: `layout::wrapping_tests::no_break_keeps_marked_characters_on_one_line`, `tests::no_break_keeps_marked_words_on_one_line`, `typecmd::no_break_is_a_character_attribute_saved_only_when_on` | | Inline symbols in text | beyond Illustrator | not scored | | Align Stroke (inside, outside) on live type's character stroke | beyond Illustrator | not scored; `stroke.set {align}` and `text.setRangeStyle {strokeOptions: {align}}`; saved natively, drawn around the glyphs on the canvas and in PDF, EPS and SVG (live text, stroke on the glyph outlines); visual bounds grow with it (#2294) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 121841e9d6..4182189c4a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -31,8 +31,10 @@ Window → Help Bar toggles the bottom tool-help strip independently of the stat **Feature evidence last updated:** 2026-11-03. -Enclosing Lasso is an add-on under Object › Plug-ins with its own heading in All Tools. It has -no default shortcut or Basic toolbar slot. It selects whole objects only +Enclosing Lasso is an add-on under Object › Plug-ins. Its tool is also in the Lasso tool's group +in both shipped toolbars, after the Lasso, and All Tools lists it there, under Select. A toolbar +edited before it joined keeps its saved layout until Reset Toolbar. It has no default shortcut; +one can be set in Edit › Keyboard Shortcuts › Tools. It selects whole objects only when their geometry is fully enclosed by the freehand loop. Shift adds, Alt subtracts, and Escape cancels. Ordinary group members can be selected separately; compound paths stay whole. Path checks follow curves, excluding stroke width and effects; other objects use their geometric @@ -328,6 +330,7 @@ tools, never checked side by side) isn't captured row by row. | Cmd/Ctrl: last-used selection tool; Cmd+Alt: Group Selection inside Direct Selection | done | Cmd+Alt lends Group Selection only while Direct Selection is active (Cmd borrow from the Pen keeps Direct Selection so Alt stays copy/subtract); Cmd alone lends Direct Selection the Selection tool: its bounding box shows while Cmd is held over objects selected whole and its handles scale and rotate them, and a Cmd drag moves the whole object while its direct-selected anchors stay selected (#3901; no box over a selection with anchors picked yet); engine pointer and canvas regressions | | Eyedropper copies effective character dimensions between transformed text objects | done | Point/area and grouped text, highlighted ranges, reverse/remembered sampling, opt-outs and atomic invalid-transform rejection; `scaled_type_pick_*` (#6404) | | Eyedropper styles highlighted characters only and preserves ranges across Type switches | done | Font/paint, Shift color-only, Unicode, Undo/Redo and stale-range regression tests; enabled non-neutral source or target object transparency is refused atomically; disable Transparency to sample supported attributes | +| Gradient mesh: a solid color dropped from the Color or Swatches panel or a Fill proxy on a selected mesh recolors the mesh point under the pointer, else the patch's four points; with the mesh selected, an Eyedropper click applies the fill color the same way | done | [Edit mesh objects](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=312); `object.mesh.setPointColor`, one undo step, none when the color is unchanged. The 5-pixel reach for a point is VectorCraft's own. Tests `a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it`, `a_click_on_a_selected_mesh_gives_its_point_or_patch_the_fill_color`, `a_click_on_an_object_over_a_selected_mesh_copies_that_object` | | Eyedropper reads visible sources while their layer/object is locked or outside isolation | done | Ordinary/Shift/Shift+Alt and gradient-stop reads preserve the source and selection; Alt reverse remains editable-only; hidden art stays excluded (`eyedropper_sources.rs`, #1251) | | Add a visible stroke after drawing with inherited None/zero-width paint | done | Paint and Swap Fill/Stroke restore the existing 1 pt default; positive widths and painted zero widths stay as set; Undo/Redo and targeted appearance items tested (`stroke_visibility.rs`, #1253) | | Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) |