diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 8c4c4fffa2..0d4deca36f 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,9 +238,11 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index f59d195cd5..c2b40e37e6 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -478,6 +478,7 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index b4c0a41103..11afcfe121 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have File › New start each category's documents from its profile in the `New Document +/// Profiles` folder, which `file.newProfiles.edit` makes. +pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("New Document Profiles") { + session.attach_new_doc_profiles(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index f2a705857e..46dcdb52ba 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -6,8 +6,9 @@ //! * **CMYK spaces:** [`GENERIC_CMYK`] is our own documented parametric press model //! ([`generic`]); [`DEVICE_CMYK`] is the old profile-free formula (kept for exact legacy numbers); //! any CMYK `.icc` the user loads goes through `moxcms` (LUT-based profiles). -//! * The **active settings** (Edit → Color Settings) are process-wide; [`crate::Color::to_rgb`] -//! uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`]. +//! * The **active settings** are process-wide: the working settings (Edit → Color Settings), with +//! the profiles [`use_document_profiles`] last put in place of the working spaces; +//! [`crate::Color::to_rgb`] uses them. Code that needs deterministic numbers builds its own [`Cms`] with [`Cms::new`]. pub mod generic; pub mod icc; @@ -320,6 +321,9 @@ pub struct Cms { settings: ColorSettings, rgb: RgbSpace, cmyk: CmykSpace, + /// The working settings, when a document's assigned profiles take the place of their spaces + /// ([`use_document_profiles`]): a [`ProofTarget::WorkingCmyk`] proof simulates their CMYK space. + working: Option>, } impl std::fmt::Debug for Cms { @@ -330,7 +334,7 @@ impl std::fmt::Debug for Cms { impl Default for Cms { fn default() -> Self { - Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()) } + Self { settings: ColorSettings::default(), rgb: RgbSpace::Srgb, cmyk: CmykSpace::Generic(generic()), working: None } } } @@ -338,7 +342,7 @@ impl Cms { /// Profiles named by a legacy name are stored under their current name. pub fn new(settings: &ColorSettings) -> Result { let settings = ColorSettings { rgb: canonical_name(&settings.rgb).into(), cmyk: canonical_name(&settings.cmyk).into(), ..settings.clone() }; - Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings }) + Ok(Self { rgb: rgb_space(&settings.rgb)?, cmyk: cmyk_space(&settings.cmyk)?, settings, working: None }) } pub fn settings(&self) -> &ColorSettings { &self.settings @@ -542,8 +546,9 @@ impl Cms { ProofTarget::Deuteranopia => simulate_cvd(srgb, &DEUTERANOPIA), ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb), ProofTarget::WorkingCmyk => { - let cmyk = self.srgb_to_cmyk(srgb, proof.intent); - self.cmyk_to_srgb(cmyk, proof.simulate_paper) + let working = self.working_cms(); + let cmyk = working.srgb_to_cmyk(srgb, proof.intent); + working.cmyk_to_srgb(cmyk, proof.simulate_paper) } ProofTarget::Cmyk(name) => match cmyk_space(name) { Ok(sp) => { @@ -555,20 +560,29 @@ impl Cms { } } - /// Display sRGB of CMYK inks in the proof's CMYK space (the working space for RGB targets). + /// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB + /// targets). pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] { match &proof.target { ProofTarget::Cmyk(name) => match cmyk_space(name) { Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc), Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper), }, + ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper), _ => self.cmyk_to_srgb(cmyk, proof.simulate_paper), } } + /// The context of the working settings: the one [`use_document_profiles`] put a document's + /// profiles in place of, else this one. + fn working_cms(&self) -> &Cms { + self.working.as_deref().unwrap_or(self) + } + /// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels. pub fn proof_lut(&self, proof: &ProofSetup) -> Arc { - let key = format!("{:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper); + let working = self.working.as_ref().map(|w| &w.settings); + let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper); let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) { return l.clone(); @@ -890,10 +904,12 @@ impl CmykLut { // ---------- the active (process-wide) settings ---------- static ACTIVE: RwLock>> = RwLock::new(None); +static WORKING: RwLock>> = RwLock::new(None); static RGB_IS_SRGB: AtomicBool = AtomicBool::new(true); static CMYK_IS_DEVICE: AtomicBool = AtomicBool::new(false); -/// The active colour-management context (Edit → Color Settings). +/// The active color-management context: the working settings, with the profiles +/// [`use_document_profiles`] last put in place of the working spaces. pub fn active() -> Arc { if let Some(c) = ACTIVE.read().unwrap_or_else(|e| e.into_inner()).as_ref() { return c.clone(); @@ -906,13 +922,62 @@ pub fn active_settings() -> ColorSettings { active().settings.clone() } -/// Replace the active settings (fails, leaving them unchanged, if a profile is unknown). +/// The color-management context of Edit → Color Settings (the working spaces, intent and black +/// point compensation), as [`set_active`] last set them, whatever profiles a document is assigned. +pub fn working() -> Arc { + if let Some(c) = WORKING.read().unwrap_or_else(|e| e.into_inner()).as_ref() { + return c.clone(); + } + let mut w = WORKING.write().unwrap_or_else(|e| e.into_inner()); + w.get_or_insert_with(|| Arc::new(Cms::default())).clone() +} + +/// The settings of [`working`]. +pub fn working_settings() -> ColorSettings { + working().settings.clone() +} + +/// Replace the working settings (Edit → Color Settings) and make them the active settings (fails, +/// leaving both unchanged, if a profile is unknown). pub fn set_active(settings: &ColorSettings) -> Result<(), CmsError> { - let cms = Cms::new(settings)?; + let cms = Arc::new(Cms::new(settings)?); + *WORKING.write().unwrap_or_else(|e| e.into_inner()) = Some(cms.clone()); + install(cms); + Ok(()) +} + +/// Make the working settings the active settings, with the profiles a document is assigned +/// (`None`: none) in place of the working spaces. An assigned profile that is not available, or +/// is not of its model, leaves the working space. The working settings stay as they are. True when +/// the active settings changed. +pub fn use_document_profiles(rgb: Option<&str>, cmyk: Option<&str>) -> bool { + let working = working(); + let mut st = working.settings.clone(); + if let Some(p) = rgb.and_then(profile).filter(|p| p.kind == ProfileKind::Rgb) { + st.rgb = p.name; + } + if let Some(p) = cmyk.and_then(profile).filter(|p| p.kind == ProfileKind::Cmyk) { + st.cmyk = p.name; + } + if st == active().settings { + return false; + } + if st == working.settings { + install(working); + return true; + } + // The working settings were checked when they were set; a working profile removed since then + // leaves the active settings as they are. + let Ok(mut cms) = Cms::new(&st) else { return false }; + cms.working = Some(working); + install(Arc::new(cms)); + true +} + +fn install(cms: Arc) { RGB_IS_SRGB.store(cms.rgb_is_srgb(), Ordering::Relaxed); CMYK_IS_DEVICE.store(matches!(cms.cmyk, CmykSpace::Device), Ordering::Relaxed); - *ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(cms)); - Ok(()) + *ACTIVE.write().unwrap_or_else(|e| e.into_inner()) = Some(cms); } /// Fast path for [`Color::to_rgb`]: RGB colours need no conversion while the working space is sRGB. diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 24f3d68af6..55a904d02c 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -440,6 +440,8 @@ fn leaf_base(n: &Node) -> Option<(PathData, FillRule, GeomContext<'_>, Node)> { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } + // The raster effects of its fills and strokes follow its Transform effects, as on the canvas. + crate::raster::follow_items(&mut m); m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); Some((g, rule, ctx, m)) } diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 031d3e1d98..602e2d7fe9 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -189,8 +189,8 @@ pub fn effect_catalog() -> Vec { EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", - json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}), ), g( INFLATE, @@ -203,8 +203,8 @@ pub fn effect_catalog() -> Vec { ROTATE, "Rotate…", &["Effect", "3D and Materials"], - "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", - json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0}), + "{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.", + json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[]}), ), g( CLASSIC_EXTRUDE, @@ -267,7 +267,7 @@ pub fn effect_catalog() -> Vec { "distort.transform", "Transform…", DT, - "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", + "{scaleH: % (100), scaleV: % (100), moveH: pt (0; right = +), moveV: pt (0; down = +), rotate: deg (0; counter-clockwise; when the effect turns, reflects or scales the object unevenly, a gradient fitted to the object is fixed to its fit and turns with the object and with each copy), copies: 0..1000 (0; each copy transforms the last again and is painted below it, the object on top; a group's copies each hold all its members, and a group with a member that carries a geometry, Pathfinder or 3D effect copies each member in its place; placed gradients transform with the object and with each copy), reflectX: bool (false; flips left to right), reflectY: bool (false; flips top to bottom), reference: 0..8 (4; the point of the bounds' 9-point grid it scales, rotates and reflects about: 0 top left, 4 centre, 8 bottom right), random: bool (false; each scale goes a random share of the way from 100 % to its value, each move and the angle a random share of theirs, differently for each object and the same on every redraw), objects: bool (true; Transform Objects: off, the geometry stays where it is and makes no copies, and only the two options below apply, once; on, without copies or random, the raster effects listed before this effect (Rasterize and SVG filters excepted) transform with the art whatever strokes says: their sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, while the angles and light directions of pixel filters stay as they are; so do the raster effects of the object's fills and strokes and, on a group, those of its members, of their fills and strokes and of their linked opacity masks' art, after their own Transform effects, including those that a member's own Transform effect with copies or random holds back), patterns: bool (false; Transform Patterns: pattern fills and strokes transform along; with copies the original keeps its pattern and copy k takes the transformation k times), strokes: bool (false; Scale Strokes & Effects: stroke weights and dashes, and the distances of the effects on the fills and strokes, scale by the mean scale √|scaleH·scaleV|, copy k by its k-th power; raster effects that transform with the art are not scaled again; on a fill or stroke, the effects listed after this effect in that fill's or stroke's own list keep their distances and apply to the transformed art, and with objects off so do the effects before it)}", json!({"scaleH": 100.0, "scaleV": 100.0, "moveH": 0.0, "moveV": 0.0, "rotate": 0.0, "copies": 0, "reflectX": false, "reflectY": false, "reference": 4, "random": false, "objects": true, "patterns": false, "strokes": false}), ), g( diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 015490a74d..0f61fda674 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -257,6 +257,9 @@ fn reshaped(src: &Node, n: &Node, doc: Option<&Document>) -> Node { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } + // So do the raster effects of its fills and strokes, by `n`'s Transform effects + // ([`crate::follow_items`]). + crate::raster::follow_items_of(&mut m, &n.appearance.effects); } without_geometry_effects(&mut m); m diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index a7fb05b2a6..c169c807b2 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -1281,6 +1281,23 @@ fn compound_shape(mode: ShapeMode) -> Node { g } +/// A compound shape's Transform effect turns its fill's drop shadow with the area it turns. +#[test] +fn a_compound_shapes_transform_turns_its_fills_shadow() { + let mut shape = compound_shape(ShapeMode::Add); + if let Some(item) = shape.appearance.items.first_mut() { + *item.effects_mut() = + vec![Effect { id: "stylize.dropShadow".into(), params: serde_json::json!({"x": 10, "y": 0, "blur": 0}), visible: true }]; + } + shape.appearance.effects.push(Effect { id: "distort.transform".into(), params: serde_json::json!({"rotate": 90}), visible: true }); + let art = shape_art(None, &shape, None).unwrap(); + let item = art.appearance.items.first().unwrap(); + match crate::raster_effects(item.effects()).first() { + Some(crate::RasterFx::DropShadow { dx, dy, .. }) => assert!(dx.abs() < 1e-9 && (dy + 10.0).abs() < 1e-9, "{dx} {dy}"), + other => panic!("expected a drop shadow, got {other:?}"), + } +} + /// A compound shape draws the area its members' modes make, one unpainted path that its own /// appearance paints; evaluated, it is plain art painted with that appearance. #[test] diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 080098ad24..89b41df9e7 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -78,7 +78,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; -pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, outset, raster_effects, without_geometry}; +pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, without_geometry}; pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, @@ -87,15 +87,21 @@ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; pub use solids::{ - CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, - classic_extrude_options, classic_shading, extrude_options, has_solid, inflate_options, is_classic_three_d, is_three_d, solid_art, solid_art_in, - three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, 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, + CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, ROTATE, ROTATE_SURFACES, + ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options, graphic_bounds, + graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol, + names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, solid_art, solid_art_in, takes_graphics, three_d_meshes, + three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, + validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, +}; +pub use solids::{ + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; pub use vectorcraft_three_d::Mesh; +pub use vectorcraft_three_d::PlanarFace; pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index 07140e2bc9..b59d61beb2 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use serde_json::{Map, Value, json}; use vectorcraft_doc::color::{BlendMode, Color}; use vectorcraft_doc::rastersettings::MAX_ADD_AROUND; -use vectorcraft_doc::{Effect, RasterColorModel, RasterEffectsSettings}; +use vectorcraft_doc::{AppearanceItem, Effect, Node, RasterColorModel, RasterEffectsSettings}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; @@ -478,6 +478,104 @@ pub(crate) fn follow_one(effects: &mut [Effect], t: &Effect) -> bool { changed } +/// The linear part of the visible Transform effects of `owner`, an object's or a container's own +/// effects, in order: what they do to the raster effects of everything the object paints (its +/// fills and strokes, and a container's members and theirs), which those effects transform with +/// the rest of the art. `None` when they leave them as they are: no Transform effect moves the +/// art, or one of them makes copies or moves at random ([`followed`]). +pub(crate) fn contents_step(owner: &[Effect]) -> Option { + let a = owner.iter().filter(|e| e.visible && e.id == "distort.transform").try_fold(Affine::IDENTITY, |a, e| transform_step(e).map(|s| s * a))?; + (a != Affine::IDENTITY).then_some(a) +} + +/// Make the raster effects of `effects`, the own effects of something inside an object (a fill's +/// or stroke's, or a member's), follow `a`, the linear part of the object's Transform effects +/// ([`contents_step`]), which apply after all of them. `outer` is what the Transform effects +/// between them and `a` do to them (those of the fill's or stroke's object and of the groups that +/// hold it inside the object). A raster effect that the Transform effects after it in `effects` +/// move ([`followed`]) is set so that it draws as those effects, then `outer` and then `a` +/// transform it, whichever of them is applied first. One that a Transform effect after it in +/// `effects` holds back keeps its value through those effects, so it is set to draw as `outer` and +/// then `a` transform it. `false` when nothing changed. +pub(crate) fn follow_contents(effects: &mut [Effect], a: Affine, outer: Affine) -> bool { + if a == Affine::IDENTITY || !effects.iter().any(|e| follows(&e.id)) { + return false; + } + let mut changed = false; + // The linear part of the Transform effects after the effect at hand, as `followed` reads it; + // `None` once one of them holds the effect back, which they then leave as it is. + let mut after = Some(Affine::IDENTITY); + for e in effects.iter_mut().rev() { + if e.id == "distort.transform" { + after = after.and_then(|b| transform_step(e).map(|s| b * s)); + continue; + } + if !follows(&e.id) { + continue; + } + let b = outer * after.unwrap_or(Affine::IDENTITY); + // The effect is still to be mapped by `b` when it is drawn, so it takes b⁻¹·a·b now: + // drawn, it is a·b of what it was. A `b` that flattens the art takes `a` alone. + let det = b.determinant(); + let c = if b == Affine::IDENTITY || !(det.is_finite() && det.abs() > 1e-12) { a } else { b.inverse() * a * b }; + if c.is_finite() { + follow_transform(e, c); + changed = true; + } + } + changed +} + +/// Make the raster effects of the fills and strokes of `n` follow the Transform effects of its own +/// effect list ([`contents_step`]), as they do while the object is drawn with them: for art that +/// applies those effects and keeps the fills and strokes. `false` when nothing changed. +pub fn follow_items(n: &mut Node) -> bool { + let Some(a) = contents_step(&n.appearance.effects) else { return false }; + follow_items_by(n, a) +} + +/// [`follow_items`] for `n` holding the fills and strokes of an object whose own effects are +/// `owner` (the area of a compound shape, which carries none of the shape's effects). +pub(crate) fn follow_items_of(n: &mut Node, owner: &[Effect]) -> bool { + let Some(a) = contents_step(owner) else { return false }; + follow_items_by(n, a) +} + +/// Make the raster effects of the fills and strokes of `n` follow `a` ([`follow_contents`]). +fn follow_items_by(n: &mut Node, a: Affine) -> bool { + if !n.appearance.items.iter().any(|i| i.effects().iter().any(|e| follows(&e.id))) { + return false; + } + let mut changed = false; + for item in &mut n.appearance.items { + changed |= follow_contents(item.effects_mut(), a, Affine::IDENTITY); + } + changed +} + +/// Make the raster effects of `items`, the fills and strokes of an object whose own effects are +/// `owner`, follow the Transform effects of `owner` ([`follow_contents`]): for art that applies +/// those effects to the object's path and draws each fill and stroke on it as a node of its own. +pub(crate) fn follow_paints(items: &mut [AppearanceItem], owner: &[Effect]) { + let Some(a) = contents_step(owner) else { return }; + for item in items { + follow_contents(item.effects_mut(), a, Affine::IDENTITY); + } +} + +/// `effects`, those of a fill or stroke of an object whose own effects are `owner`, with each +/// raster effect following the Transform effects of `owner` as well ([`follow_contents`]): the +/// list to draw that fill's or stroke's raster effects from ([`raster_effects`]). Borrowed when +/// nothing changes. +pub fn item_effects_in<'a>(owner: &[Effect], effects: &'a [Effect]) -> Cow<'a, [Effect]> { + let Some(a) = contents_step(owner) else { return Cow::Borrowed(effects) }; + if !effects.iter().any(|e| follows(&e.id)) { + return Cow::Borrowed(effects); + } + let mut out = effects.to_vec(); + if follow_contents(&mut out, a, Affine::IDENTITY) { Cow::Owned(out) } else { Cow::Borrowed(effects) } +} + /// How many of the effects of `effects` that [`without_geometry`] keeps no longer follow the /// Transform effects listed after `effects` ([`followed`]): those before the last visible Transform /// effect among them that makes copies or moves at random. @@ -511,7 +609,7 @@ fn transform_step(e: &Effect) -> Option { /// Does raster effect `id` follow the Transform effects listed after it ([`followed`])? An SVG /// filter does not, and neither does Rasterize, whose image keeps its own pixel grid and room /// around the art. -fn follows(id: &str) -> bool { +pub(crate) fn follows(id: &str) -> bool { crate::is_raster(id) && id != crate::SVG_FILTER && id != RASTERIZE } diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 8822548c29..16c271dca0 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -740,12 +740,16 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget wholes.entry(id).or_insert_with(|| copies_whole(m)); }); let mut warped = WarpedImages::new(); + // The raster effects of what the art holds follow each Transform effect that moves it once, + // whatever its options, unless one of the effects makes copies or moves at random + // ([`crate::raster::contents_step`], [`follow_art`]). + let held = listed.iter().any(|e| crate::raster::holds_back(e)); for e in fx { let Some(bounds) = warped.bounds(art) else { break }; let params = merged_params(&e.id, &e.params); // Where a live-effect plug-in sits, which it is listed by when it is deferred. let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e))); - let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes }; + let step = Step { e, params: ¶ms, bounds, seed, effect, apart, doc, wholes: &wholes, held }; // Art with linked masks keeps its shape under an effect that a mask in it could not take // as the art it masks did, so no mask is left apart from its art. let before = masked.then(|| (art.clone(), used)); @@ -768,8 +772,10 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget /// One geometry effect of an object run over its art ([`reshape_leaves_apart`]): the effect, its /// merged params, the reference box and seed of the object's art, where a deferred live-effect /// plug-in is listed, whether each Transform copy becomes an object, the document that the -/// swatches and patterns of painted pieces are looked up in, and [`copies_whole`] of the art of -/// each linked mask before the first effect, by the id of the object it masks. +/// swatches and patterns of painted pieces are looked up in, [`copies_whole`] of the art of +/// each linked mask before the first effect, by the id of the object it masks, and whether one of +/// the object's effects holds the raster effects in its art back from its Transform effects +/// ([`follow_art`]). struct Step<'a> { e: &'a Effect, params: &'a serde_json::Value, @@ -779,6 +785,7 @@ struct Step<'a> { apart: bool, doc: Option<&'a Document>, wholes: &'a HashMap, + held: bool, } /// What [`Step::run`] did to a piece of art. @@ -885,6 +892,8 @@ impl Step<'_> { let options = crate::distort::TransformOptions::of(params); (m, copies, options, crate::distort::transform_affine(bounds, params, seed)) }); + // What the effect does to the raster effects in the art, when they follow it. + let raster_map = if self.held { None } else { crate::raster::contents_step(std::slice::from_ref(e)) }; // In a mask's art, images and symbol instances take only a Transform effect // ([`transform_placed`]): a mask's art that holds one can't take another effect as the art // it masks does. @@ -944,7 +953,7 @@ impl Step<'_> { // The copies of a path replace it by a group of them, the path included. let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len); if options.reach_appearance() { - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, None); + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None); *used = used.minus(before).plus(made); if moved { // With Transform Objects off the path stays, and its mask takes the @@ -1014,12 +1023,22 @@ impl Step<'_> { *art = Node::group(id, vec![Arc::new(one)]); } let placed = if watch { masked_placed(art, own) } else { 0 }; - transform_placed(art, m, copies, copy_scaling(options)); + // Scale Strokes & Effects leaves the raster effects that follow the effect to + // [`follow_art`]. + let mut scaling = copy_scaling(options); + if raster_map.is_some() { + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + } + transform_placed(art, m, copies, scaling); short |= watch && masked_placed(art, own) < placed.saturating_mul(copies.saturating_add(1)); if root && let Some([one]) = art.children().map(Vec::as_slice) { *art = (**one).clone(); } } + // A mask's art takes them as a group inside the art: its own raster effects follow too. + if let Some(a) = raster_map { + follow_art(art, a, &kept_ids, Some(&moved_ids), own.then_some(Affine::IDENTITY), depth); + } if outlines.iter().any(Option::is_some) { rebase_type_outlines(art, &mut outlines.into_iter()); } @@ -1239,15 +1258,94 @@ fn copy_scaling(options: crate::distort::TransformOptions) -> vectorcraft_doc::S } } +/// [`crate::scale_effect`] for the effects that do not follow a Transform effect as raster effects +/// do ([`crate::raster::follows`]): Scale Strokes & Effects scales them, and [`follow_art`] moves +/// the others. +fn scale_unfollowed(e: &mut Effect, s: f64) { + if !crate::raster::follows(&e.id) { + crate::scale_effect(e, s); + } +} + +/// Make the raster effects under `art` follow `a`, the linear part of a Transform effect that moved +/// it ([`crate::raster::follow_contents`]): those of every object in it (its own and its fills' and +/// strokes'), the art's own effects excepted (`up` is `None` for the art itself). A path that kept +/// its shape (in `kept`), and a group with such a path under it, keep their own and their fills' +/// and strokes'. `up` is what the Transform effects of the groups between an object and the art do +/// to the object's effects. A Transform effect of an object's own that makes copies or moves at +/// random leaves the effects it holds back as they are, so those follow `a` and the groups' maps +/// alone. The linked opacity mask of an object that took the effect as an object (in `moved`, and +/// every image and symbol instance) moved with it, so the raster effects in the mask's art follow +/// `a` as those of a mask that takes the effect as art do ([`Step::reshape_masks`]); `moved` is +/// `None` inside such a mask's art, where every linked mask moved. The walk reaches the groups and +/// layers that [`for_each_leaf`] made the art's own, so it copies nothing. Returns whether a path in +/// `kept` is under `n`. +fn follow_art(n: &mut Node, a: Affine, kept: &HashSet, moved: Option<&HashSet>, up: Option, depth: usize) -> bool { + if n.is_guide() { + return false; + } + if moved.is_none_or(|moved| moved.contains(&n.id)) || is_placed(n) { + follow_moved_mask(n, a, depth); + } + // What the object's own Transform effects then do to its fills' and strokes' effects and its + // members' (nothing when one of them holds those back); the art's own effects are the ones + // being applied. + let below = up.map_or(Affine::IDENTITY, |up| crate::raster::contents_step(&n.appearance.effects).map_or(up, |s| up * s)); + let keeps = match &mut n.kind { + NodeKind::Path { .. } | NodeKind::Compound { .. } => kept.contains(&n.id), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + let mut keeps = false; + for c in children.iter_mut() { + keeps |= follow_art(Arc::make_mut(c), a, kept, moved, Some(below), depth); + } + keeps + } + _ => false, + }; + if !keeps { + if let Some(up) = up + && contents_raster(&n.appearance.effects) + { + crate::raster::follow_contents(&mut n.appearance.effects, a, up); + } + if n.appearance.items.iter().any(|i| contents_raster(i.effects())) { + for item in &mut n.appearance.items { + crate::raster::follow_contents(item.effects_mut(), a, below); + } + } + } + keeps +} + +/// Make the raster effects in the art of the linked opacity mask of `n`, which moved with `n`, +/// follow `a` ([`follow_art`]), with those of the linked masks inside that art, which moved too. A +/// mask past [`vectorcraft_doc::depth::MAX_DEPTH`] masks inside masks stays as it is. +fn follow_moved_mask(n: &mut Node, a: Affine, depth: usize) { + if depth >= vectorcraft_doc::depth::MAX_DEPTH { + return; + } + let Some(m) = n.extras_if_any().and_then(|x| x.mask.as_mut()).filter(|m| m.linked) else { return }; + follow_art(Arc::make_mut(&mut m.art), a, &HashSet::new(), None, Some(Affine::IDENTITY), depth + 1); +} + +/// Does any of `effects` follow a Transform effect as a raster effect ([`crate::raster::follows`])? +fn contents_raster(effects: &[Effect]) -> bool { + effects.iter().any(|e| crate::raster::follows(&e.id)) +} + /// A Transform effect whose Transform Patterns or Scale Strokes & Effects is on (`options`), with /// map `m` and `copies`, applied to `leaf` (a path or compound path with geometry `path`) as Object /// › Transform with those options transforms an object (#885): the strokes' weights and dashes /// and the distances of the effects on its fills and strokes scale by `m`'s mean scale, and its /// pattern paints transform by `m`. With copies, the original keeps them and copy `k` takes them /// `k` times, each copy an object of its own ([`copy_leaf`], within `budget`). With Transform -/// Objects off the geometry stays and the options apply once. The effects `kept` names keep their -/// values on the leaf and on each copy ([`keep_listed`]). Returns what the leaf costs after, and -/// `false` when the path kept its shape because the moved path would pass `budget`. +/// Objects off the geometry stays and the options apply once. With `follows`, Scale Strokes & +/// Effects leaves the raster effects that follow the Transform effect ([`follow_art`]) to the +/// caller. The effects `kept` names keep their values on the leaf and on each copy +/// ([`keep_listed`]), whether Scale Strokes & Effects scaled them or left them to the caller. +/// Returns what the leaf costs after, and `false` when the path kept its shape because the moved +/// path would pass `budget`. +#[allow(clippy::too_many_arguments)] fn transform_leaf( leaf: &mut Node, path: &PathData, @@ -1255,9 +1353,13 @@ fn transform_leaf( copies: usize, options: crate::distort::TransformOptions, budget: Budget, + follows: bool, kept: Kept, ) -> (Budget, bool) { - let scaling = copy_scaling(options); + let mut scaling = copy_scaling(options); + if follows && copies == 0 { + scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64)); + } if !options.objects { if options.strokes && let Some(k) = vectorcraft_doc::Scaling::factor(m).filter(|k| k.is_finite() && *k > 0.0) @@ -1716,7 +1818,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt set_geometry(&mut p, g.clone(), rule); let after = kept_before.len(); let keep = |k: usize| k >= after || !options.objects; - let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, Some((&rest, &keep))); + let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep))); *used = used.plus(made); let from = crate::raster::held_back(before); if moved && !held_later { @@ -1795,7 +1897,7 @@ fn transform_piece(p: &mut Node, (seed, source, kept): (u64, usize, &[usize]), h let options = crate::distort::TransformOptions::of(¶ms); let map = crate::distort::transform_affine(bounds, ¶ms, seed); let keep = |k: usize| k > j || (k < j && !options.objects); - let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, Some((item.effects(), &keep))); + let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep))); *used = used.minus(before).plus(made); if moved { follow_piece(leaf, was, from, &e); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index d82e4e8818..0006e5362f 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -619,9 +619,13 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { } else { let path = geometry(&path, &n.appearance.effects, &ctx); remaining = crate::without_geometry(&remaining); + // The object's Transform effects, applied to the path above, transform the items' raster + // effects too. + let mut items: Vec = n.appearance.items.iter().filter(|i| crate::paints(i)).cloned().collect(); + crate::raster::follow_paints(&mut items, &n.appearance.effects); // Every item's shadow goes behind every item's art. let mut shadows = vec![]; - for item in n.appearance.items.iter().filter(|i| crate::paints(i)) { + for item in &items { if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) { let fx = item.effects().get(index)?; let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 9e7578d6d7..e4fb218604 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -6,7 +6,7 @@ use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; -use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View}; +use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, PlanarFace, View}; #[cfg(test)] use vectorcraft_doc::color::Color; @@ -20,6 +20,15 @@ pub use classic::{CLASSIC_EXTRUDE, CLASSIC_ROTATE, ROTATE_SURFACES, SHADING_COLO mod source; pub(crate) use source::{resolve, resolve_for}; +mod graphics; +pub use graphics::{ + GRAPHICS, GraphicFrame, MAX_GRAPHICS, MappedGraphic, graphic_symbols, mapped_graphics, missing_symbol, names_graphic_symbol, + rename_graphic_symbol, rename_graphic_symbol_in, takes_graphics, with_graphic, +}; +pub use graphics::{ + MAX_OFFSET as GRAPHIC_MAX_OFFSET, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, rename_appearance_graphic_symbol, +}; + pub(crate) mod shadow; pub(crate) mod wireframe; @@ -70,6 +79,12 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } } + // A plane has only a front, so graphics on the back cap are dropped. + if to == ROTATE + && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) + { + list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + } Value::Object(out) } @@ -212,6 +227,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { } crate::lighting::validate(p)?; shadow::validate(p)?; + graphics::validate(id, p)?; if let Some(v) = p.get("bevel") && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) { @@ -241,6 +257,9 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) /// `item`, whose shadow is cast by that item's solid alone. fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, item: Option) -> Result<(), String> { validate_solid_params(id, p)?; + if let Some(doc) = doc { + graphics::validate_symbols(doc, p)?; + } let label = label_of(id); let n = &*source::resolve_for(doc, n, label, is_plane(id))?; if is_container(n) { @@ -434,6 +453,7 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]). pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + graphics::validate(id, p)?; if crate::revolve::is_revolve(id) { crate::revolve::validate_in(doc, n, id, p) } else { validate_solid_in(doc, n, id, p) } } @@ -449,6 +469,7 @@ pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usi /// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a /// blend and a clipping group take a 3D effect as groups do: on the object itself. pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { + graphics::validate(id, p)?; match at { Some(_) if is_container(n) || source::resolves(n) => { Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) @@ -463,6 +484,7 @@ pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Va /// build the art, for an edit that hides the effect: hidden, it draws nothing, so its object does /// not need to fit. pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> { + graphics::validate(id, p)?; if crate::revolve::is_revolve(id) { crate::revolve::validate_params_of(id, p) } else { validate_solid_params(id, p) } } @@ -712,8 +734,8 @@ type ShadowAndSurfaces = (Vec>, Vec>); /// blending mode, and those of a group it is in, apply to the surfaces of the members it holds /// ([`masked`]). The art comes in two parts: the effect's shadow ([`cast_shadow`], none with it /// off), to be drawn behind every surface of the object, and the surfaces. -fn art_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { - let art = surfaces_for(n, fx, shapes)?; +fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option { + let art = surfaces_for(doc, n, fx, shapes)?; // A shadow past the limits draws the source path, as a solid past them does; commands report // the error ([`validate_solid_in`]). let shadow = match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes).ok()? { @@ -789,8 +811,139 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec>); -/// [`art_for`] without the shadow: the solids' surfaces. -fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { +/// The graphics of a 3D effect with parameters `p`, drawn on its faces ([`graphics::face_art`]): +/// for each planar face with a graphic, the art and the face. `caps` are the faces the viewer sees +/// of the ends of the object's solids, each with its end; `bounds` are the bounds the solids were +/// built with; `opacity` is the opacity of the fill or stroke those solids are painted with, which +/// the graphics take too. `elements` is the effect's count of drawn path elements, shared by every +/// call for one effect ([`graphics::face_art`]). +fn graphic_art( + doc: Option<&Document>, + id: NodeId, + (effect, p): (&str, &Value), + bounds: Rect, + caps: &[&Facet], + opacity: f32, + elements: &mut usize, +) -> Vec<(PlanarFace, Arc)> { + let list = graphics::mapped_graphics(p); + if list.is_empty() || !takes_graphics(effect) { + return vec![]; + } + let view = view_options(p); + PlanarFace::ALL + .into_iter() + .filter_map(|face| { + let on: Vec<&Facet> = caps.iter().copied().filter(|f| f.end == Some(face)).collect(); + let map = if effect == ROTATE { + vectorcraft_three_d::plane_face_map(bounds, view) + } else { + vectorcraft_three_d::extrude_face_map(bounds, extrude_options(p), view, face) + }?; + graphics::face_art(doc, id, &list, (face, &map), bounds.center(), &on, elements).map(|mut art| { + art.opacity *= opacity; + (face, Arc::new(art)) + }) + }) + .collect() +} + +/// A solid (a fill's or a stroke's) with ends the viewer sees: the index of its surface, its +/// member, the ends, the opacity and blending mode of its fill or stroke, and whether its surface +/// carries an opacity mask (a gradient's transparency under a colored light, [`surface`]). +struct Filled { + at: usize, + member: usize, + caps: Vec, + opacity: f32, + blend: BlendMode, + masked: bool, +} + +/// Does a surface in `paint` carry an opacity mask ([`surface`])? +fn masks_surface(paint: &Paint, colored: bool) -> bool { + colored && crate::lighting::opaque_paint(paint).1.is_some() +} + +/// The graphics of the solids `filled` ([`graphic_art`]), each with the index of the surface it is +/// drawn right after (the last of those solids holding its face) and its face. With `per_member` +/// (a member's opacity mask or blending mode applies to its surfaces) each member's solids get +/// graphics of their own, clipped to that member's caps, so they stay in that member's scopes. +/// All the groups share one limit on the path elements drawn: once it is reached, later groups +/// draw no graphics. +fn placed_graphics( + doc: Option<&Document>, + id: NodeId, + effect: (&str, &Value), + bounds: Rect, + filled: &[Filled], + per_member: bool, +) -> Vec<(usize, PlanarFace, Arc)> { + let mut groups: Vec> = vec![]; + for f in filled { + // Solids whose fills or strokes differ in opacity or blending mode get graphics of their + // own, each drawn as its fill or stroke is. A solid whose surface carries an opacity mask + // gets its own too, which takes that mask ([`with_graphics`]). + let joins = |first: &Filled| { + (!per_member || first.member == f.member) && first.opacity == f.opacity && first.blend == f.blend && !first.masked && !f.masked + }; + match groups.iter_mut().find(|g| g.first().is_some_and(|first| joins(first))) { + Some(g) => g.push(f), + None => groups.push(vec![f]), + } + } + let mut out = vec![]; + let mut elements = 0usize; + for group in groups { + let caps: Vec<&Facet> = group.iter().flat_map(|f| &f.caps).collect(); + let opacity = group.first().map_or(1.0, |f| f.opacity); + let blend = group.first().map_or(BlendMode::Normal, |f| f.blend); + for (face, mut art) in graphic_art(doc, id, effect, bounds, &caps, opacity, &mut elements) { + if let Some(f) = group.iter().rev().find(|f| f.caps.iter().any(|c| c.end == Some(face))) { + Arc::make_mut(&mut art).blend = blend; + out.push((f.at, face, art)); + } + } + } + out +} + +/// One solid's surface as [`surfaces_for`] builds it: its faces' depths, its art, its member's +/// scopes, and for each face the end of a solid it is, when the viewer sees it. +type BuiltSurface<'s> = (Vec, Node, &'s [Scope], Vec>); + +/// [`with_graphics`] of built surfaces, each drawn whole. +fn whole_surfaces<'s>(surfaces: Vec>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { + with_graphics(surfaces.into_iter().map(|(_, s, scopes, _)| (scopes, Arc::new(s))).collect(), arts) +} + +/// `surfaces` drawn whole, each with its scopes, and the graphics `arts` ([`placed_graphics`]) each +/// right after its surface, with that surface's scopes and its opacity mask (a gradient's +/// transparency), so a graphic is hidden where its cap is. +fn with_graphics<'s>(surfaces: Vec<(&'s [Scope], Arc)>, arts: &[(usize, PlanarFace, Arc)]) -> Vec<(&'s [Scope], Arc)> { + let mut out = Vec::with_capacity(surfaces.len() + arts.len()); + for (k, (scopes, s)) in surfaces.into_iter().enumerate() { + let mask = s.extras().mask.clone(); + out.push((scopes, s)); + out.extend(arts.iter().filter(|(at, ..)| *at == k).map(|(.., art)| { + let mut art = art.clone(); + if let Some(mask) = &mask { + Arc::make_mut(&mut art).extras_mut().mask = Some(mask.clone()); + } + (scopes, art) + })); + } + out +} + +/// The ends of `f` the viewer sees, for a fill's solid or a stroke's: where its graphics go. +fn seen_ends(f: &[Facet]) -> impl Iterator { + f.iter().filter(|f| f.end.is_some() && !f.away) +} + +/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar +/// faces drawn right after the last of the solids' surfaces that holds that face. +fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option>> { let b = union_bounds(shapes)?; let p = crate::merged_params(&fx.id, &fx.params); let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE; @@ -798,11 +951,14 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option Option = seen_ends(&f).cloned().collect(); + if !caps.is_empty() { + filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) }); + } + } let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; out.push((s.scopes.as_slice(), Arc::new(art))); } } + let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks); + let out = with_graphics(out, &arts); return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }); } let (parts, bounds) = solid_parts(shapes, b); @@ -845,36 +1009,56 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option= 1.0 && blend == BlendMode::Normal }); - let surfaces: Vec<(Vec, Node, &[Scope])> = solids + let arts = if !graphics_on { + vec![] + } else { + let filled: Vec = solids + .iter() + .enumerate() + .filter_map(|(at, (item, member, _, f, shape))| { + let caps: Vec = seen_ends(f).cloned().collect(); + let (paint, opacity, blend) = paint_of(item, *member); + let masked = masks_surface(&paint, colored); + (!caps.is_empty()).then_some(Filled { at, member: *shape, caps, opacity, blend, masked }) + }) + .collect(); + placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks) + }; + let surfaces: Vec = solids .into_iter() .map(|(item, member, scopes, f, shape)| { let closed = shapes.get(shape).is_some_and(|s| s.path.subpaths.iter().all(|p| p.closed)); let paints = Paints::of(item, closed); let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); + let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) }; - (depths, art, scopes) + (depths, art, scopes, ends) }) .collect(); if masks { - return Some(masked(n.id, surfaces.into_iter().map(|(_, s, scopes)| (scopes, Arc::new(s))).collect())); + return Some(masked(n.id, whole_surfaces(surfaces, &arts))); } // One order takes a plain group of faces from each solid, one face for each facet. With // colored lights a surface can instead be one clipped composite of all its facets. A composite // has no faces to order, so when any surface is one, every surface of the solid, masked ones // included, draws whole in member order. - let plain = surfaces.iter().all(|(depths, s, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); - if !opaque || !plain { - return Some(surfaces.into_iter().map(|(_, s, _)| Arc::new(s)).collect()); - } + let plain = + surfaces.iter().all(|(depths, s, _, _)| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len())); // A surface in a gradient with transparent stops carries an opacity mask: its faces go in runs - // ([`in_runs`]), and each run carries the mask. - let masks: Vec>> = surfaces.iter().map(|(_, s, _)| s.extras().mask.clone()).collect(); - let (mut placed, mut faces) = (vec![], vec![]); - for (surface, (depths, s, _)) in surfaces.into_iter().enumerate() { + // ([`in_runs`]), and each run carries the mask. With graphics as well, the surfaces draw whole, + // each graphic right after its surface. + let masks: Vec>> = surfaces.iter().map(|(_, s, _, _)| s.extras().mask.clone()).collect(); + let masked_faces = masks.iter().any(Option::is_some); + if !opaque || !plain || (masked_faces && !arts.is_empty()) { + return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect()); + } + let (mut placed, mut faces, mut ends) = (vec![], vec![], vec![]); + for (surface, (depths, s, _, e)) in surfaces.into_iter().enumerate() { if let NodeKind::Group { children, .. } = s.kind { placed.extend(depths); faces.extend(children.into_iter().map(|face| Some((surface, face)))); + ends.extend(e); } } let sealed = match fx.id.as_str() { @@ -883,8 +1067,18 @@ fn surfaces_for(n: &Node, fx: &Effect, shapes: &[Profile]) -> Option extrude_options(&p).cap, }; let order = draw_order(&placed, sealed); - let faces: Vec<(usize, Arc)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect(); - let children = if masks.iter().all(Option::is_none) { faces.into_iter().map(|(_, face)| face).collect() } else { in_runs(n.id, faces, &masks) }; + if masked_faces { + let faces: Vec<(usize, Arc)> = order.into_iter().filter_map(|k| faces.get_mut(k).and_then(Option::take)).collect(); + return Some(vec![Arc::new(Node::group(n.id, in_runs(n.id, faces, &masks)))]); + } + // Each face's graphics go right after the last of the faces they are drawn on. + let last: Vec> = + arts.iter().map(|(_, face, _)| order.iter().rposition(|k| ends.get(*k).copied().flatten() == Some(*face))).collect(); + let mut children = Vec::with_capacity(order.len() + arts.len()); + for (at, k) in order.into_iter().enumerate() { + children.extend(faces.get_mut(k).and_then(Option::take).map(|(_, face)| face)); + children.extend(last.iter().zip(&arts).filter(|(l, _)| **l == Some(at)).map(|(_, (.., art))| art.clone())); + } Some(vec![Arc::new(Node::group(n.id, children))]) } @@ -969,7 +1163,7 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { } let n = &*resolve(doc, n, "").ok()?; if is_container(n) { - return group_solid_art(n); + return group_solid_art(doc, n); } let (path, rule) = profile(n)?; let ctx = GeomContext::of(n); @@ -978,19 +1172,23 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { let remaining: Vec; if let Some((index, fx)) = solid(&n.appearance.effects) { let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); - let (shadow, surfaces) = art_for(n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }])?; children.extend(shadow.into_iter().chain(surfaces)); // Later geometry effects act on the projected art as a whole. remaining = past_effect(&n.appearance.effects, index); } else { let path = geometry(&path, &n.appearance.effects, &ctx); remaining = crate::without_geometry(&n.appearance.effects); + // The object's Transform effects, applied to the path above, transform the items' raster + // effects too. + let mut paints = paints; + crate::raster::follow_paints(&mut paints, &n.appearance.effects); // Every item's shadow goes behind every item's art. let mut shadows = vec![]; for item in &paints { if let Some((index, fx)) = solid(item.effects()) { let p = geometry(&path, item.effects().get(..index)?, &ctx.item(item)); - let (shadow, surfaces) = art_for(n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + let (shadow, surfaces) = art_for(doc, n, fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; let later: Vec = item.effects().iter().skip(index + 1).filter(|e| !is_three_d(&e.id)).cloned().collect(); let with_later = |mut art: Arc| { Arc::make_mut(&mut art).appearance.effects = later.clone(); @@ -1014,11 +1212,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { /// geometry effects before it reshape the members, those after it bend the result as a whole; the /// group's own fills and strokes are not drawn. `None` when the effect is only on one of the /// group's own fills or strokes, or when its members can't become solids. -fn group_solid_art(n: &Node) -> Option { +fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option { let (index, fx) = solid(&n.appearance.effects)?; let mut shapes = members(n, "").ok()?; reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); - let (shadow, surfaces) = art_for(n, fx, &shapes)?; + let (shadow, surfaces) = art_for(doc, n, fx, &shapes)?; let children = shadow.into_iter().chain(surfaces).collect(); let remaining = past_effect(&n.appearance.effects, index); let mut art = n.clone(); @@ -1027,6 +1225,77 @@ fn group_solid_art(n: &Node) -> Option { Some(art) } +/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its +/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their +/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or +/// Rotate there, or its art can't be built. +pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option) -> Option { + frame_of(doc, n, item, &solid) +} + +/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude & +/// Bevel or Rotate. +pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option { + frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && SOLIDS.contains(&e.id.as_str())).map(|e| (index, e))) +} + +/// Does a visible geometry effect come after the 3D effect at `index` in the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`)? Such an effect moves or +/// bends the drawn art, graphics included, while [`graphic_frame_at`] places the graphics on the +/// art before it. +pub fn graphics_reshaped_after(n: &Node, item: Option, index: usize) -> bool { + n.appearance.effects_at(item).and_then(|fx| fx.get(index + 1..)).is_some_and(crate::has_geometry) +} + +/// Finds a 3D effect in a list of effects, with its index there. +type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { + let n = &*resolve(doc, n, "").ok()?; + let (fx, shapes) = if is_container(n) { + let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; + let mut shapes = members(n, "").ok()?; + reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes); + (fx, shapes) + } else { + let (path, rule) = profile(n)?; + let ctx = GeomContext::of(n); + match item { + None => { + let (index, fx) = pick(&n.appearance.effects)?; + let path = geometry(&path, n.appearance.effects.get(..index)?, &ctx); + (fx, vec![Profile { path, rule, items: solid_paints(n), opacity: 1.0, scopes: vec![] }]) + } + Some(k) => { + let it = n.appearance.items.get(k)?; + let (index, fx) = pick(it.effects())?; + let path = geometry(&geometry(&path, &n.appearance.effects, &ctx), it.effects().get(..index)?, &ctx.item(it)); + (fx, vec![Profile { path, rule, items: vec![it.clone()], opacity: 1.0, scopes: vec![] }]) + } + } + }; + if !takes_graphics(&fx.id) { + return None; + } + let p = crate::merged_params(&fx.id, &fx.params); + let b = union_bounds(&shapes)?; + let view = view_options(&p); + if fx.id == ROTATE { + let plane = vectorcraft_three_d::plane_face_map(b, view); + return Some(graphics::GraphicFrame::new(b, plane, None)); + } + let (_, bounds) = solid_parts(&shapes, b); + let options = extrude_options(&p); + let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); + Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) +} + +/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. +pub fn graphic_bounds(doc: &Document, name: &str) -> Option { + graphics::art_bounds(doc, name) +} + /// `effects` without the 3D effect at `index` and the geometry effects before it, which shape the /// art it projects. Each raster effect before it follows the Transform effects among those /// ([`crate::without_geometry`]), unless a Transform effect after it makes copies or moves at diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs new file mode 100644 index 0000000000..6c5d8686a7 --- /dev/null +++ b/crates/effects/src/solids/graphics.rs @@ -0,0 +1,631 @@ +//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a +//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! +//! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, +//! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of +//! the object's bounds in the face's own plane (points, x to the right and y down as the face is +//! seen from the front of that face), its size as a share of the symbol's own, and its turn +//! (degrees, counterclockwise). On the back cap, x runs to the right as the back is seen from +//! behind, so the graphic reads the right way round there. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::color::{BlendMode, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol}; +use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape}; +use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath}; +use vectorcraft_three_d::{FaceMap, Facet, PlanarFace}; + +/// The effect parameter that holds the graphics. +pub const GRAPHICS: &str = "graphics"; + +/// The most graphics one 3D effect maps. +pub const MAX_GRAPHICS: usize = 64; + +/// The most fills and stroke outlines the art of one symbol draws as a graphic. +const MAX_PIECES: usize = 4096; + +/// The most path elements the graphics of one 3D effect draw together, after a perspective cuts +/// their curves. +const MAX_ELEMENTS: usize = 400_000; + +/// The pieces each curve of a graphic is cut into under a perspective map, which bends it. +const PERSPECTIVE_PIECES: usize = 8; + +/// How deep symbol instances in a graphic's art may nest. +const MAX_NESTING: usize = 8; + +/// How deep the objects of a graphic's art may be, counting groups and the art of the symbols it +/// places: as deep as an object may be drawn. +const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH; + +/// The size range of a graphic, as a percentage of its symbol's own size. +pub const SCALE_RANGE: (f64, f64) = (1.0, 10_000.0); + +/// How far a graphic's center may be from the center of its object, in points. +pub const MAX_OFFSET: f64 = 1e6; + +/// One graphic mapped onto a face of a 3D object. +#[derive(Clone, Debug, PartialEq)] +pub struct MappedGraphic { + pub symbol: String, + pub face: PlanarFace, + pub x: f64, + pub y: f64, + /// Percent of the symbol's own size. + pub scale: f64, + /// Degrees, counterclockwise. + pub rotation: f64, +} + +impl MappedGraphic { + pub fn to_value(&self) -> Value { + json!({"symbol": self.symbol, "face": self.face.id(), "x": self.x, "y": self.y, "scale": self.scale, "rotation": self.rotation}) + } + + /// The graphic `v` describes. Only `symbol` is required: `face` defaults to front, the offsets + /// and the rotation to 0 and the scale to 100. + pub fn from_value(v: &Value) -> Result { + let Value::Object(m) = v else { return Err(format!("each of `{GRAPHICS}` must be an object")) }; + if let Some(k) = m.keys().find(|k| !matches!(k.as_str(), "symbol" | "face" | "x" | "y" | "scale" | "rotation")) { + return Err(format!("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`")); + } + let symbol = match m.get("symbol") { + Some(Value::String(s)) if !s.trim().is_empty() => s.clone(), + _ => return Err(format!("each of `{GRAPHICS}` needs `symbol`, the name of a symbol")), + }; + let face = match m.get("face") { + None => PlanarFace::Front, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + }; + let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { + match m.get(key) { + None => Ok(default), + Some(v) => v + .as_f64() + .filter(|n| n.is_finite() && (lo..=hi).contains(n)) + .ok_or_else(|| format!("`{GRAPHICS}` {key} must be a number from {lo} to {hi}")), + } + }; + Ok(Self { + symbol, + face, + x: number("x", 0.0, (-MAX_OFFSET, MAX_OFFSET))?, + y: number("y", 0.0, (-MAX_OFFSET, MAX_OFFSET))?, + scale: number("scale", 100.0, SCALE_RANGE)?, + rotation: number("rotation", 0.0, (-360.0, 360.0))?, + }) + } + + /// Where the graphic's art goes in the face's plane, for symbol art whose bounds are `art` on an + /// object whose bounds have center `center`. + fn placement(&self, art: Rect, center: Point) -> Affine { + let place = Affine::translate((center.x + self.x, center.y + self.y)) + * Affine::rotate(-self.rotation.to_radians()) + * Affine::scale(self.scale / 100.0) + * Affine::translate(-art.center().to_vec2()); + match self.face { + PlanarFace::Front => place, + // Seen from behind, the back's right is the front's left. + PlanarFace::Back => { + Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place + } + } + } +} + +/// The 3D effects that take graphics: Extrude & Bevel (its caps) and Rotate (the plane), the two +/// object types of the 3D and Materials panel with planar faces. +pub fn takes_graphics(id: &str) -> bool { + id == super::EXTRUDE || id == super::ROTATE +} + +/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold +/// anything; commands check every entry with [`validate`]). +pub fn mapped_graphics(p: &Value) -> Vec { + match p.get(GRAPHICS) { + Some(Value::Array(list)) => list.iter().take(MAX_GRAPHICS).filter_map(|v| MappedGraphic::from_value(v).ok()).collect(), + _ => vec![], + } +} + +/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel and Rotate take +/// graphics, and a plane has only a front. +pub fn validate(id: &str, p: &Value) -> Result<(), String> { + let list = match p.get(GRAPHICS) { + None => return Ok(()), + Some(Value::Array(list)) => list, + Some(_) => return Err(format!("`{GRAPHICS}` must be an array")), + }; + if list.is_empty() { + return Ok(()); + } + if !takes_graphics(id) { + return Err("Graphics map onto planar faces: use the Extrude or Plane object type".into()); + } + if list.len() > MAX_GRAPHICS { + return Err(format!("`{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics")); + } + for v in list { + let g = MappedGraphic::from_value(v)?; + if id == super::ROTATE && g.face == PlanarFace::Back { + return Err("A plane has one face: map its graphics onto the front".into()); + } + } + Ok(()) +} + +/// The first symbol the graphics in `p` name that `doc` does not have, leaving out the symbols the +/// graphics in `old` (the effect's parameters before an edit) already name: a graphic whose symbol +/// was deleted may stay. +pub fn missing_symbol(doc: &Document, p: &Value, old: Option<&Value>) -> Option { + let kept = old.map(mapped_graphics).unwrap_or_default(); + mapped_graphics(p) + .into_iter() + .map(|g| g.symbol) + .find(|name| !doc.symbols.iter().any(|s| s.name == *name) && !kept.iter().any(|g| g.symbol == *name)) +} + +/// Does the art of the symbols the graphics in `p` name fit the limits? A graphic whose symbol +/// `doc` does not have draws nothing and is not counted. With a perspective, each curve counts as +/// the [`PERSPECTIVE_PIECES`] pieces it is cut into; without one, it counts once. +pub fn validate_symbols(doc: &Document, p: &Value) -> Result<(), String> { + let curve = if super::view_options(p).perspective > 0.0 { PERSPECTIVE_PIECES } else { 1 }; + let mut elements = 0usize; + for g in mapped_graphics(p) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + let pieces = pieces_of(doc, symbol)?; + elements = elements.saturating_add(pieces.iter().map(|p| drawn_elements(&p.path, curve)).sum()); + if elements > MAX_ELEMENTS { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + } + Ok(()) +} + +/// The path elements `path` draws when each curve draws `curve` elements, before curves near the +/// eye are split further: one for each straight line, move and close. +fn drawn_elements(path: &PathData, curve: usize) -> usize { + let segments = |s: &SubPath| (0..s.segment_count()).map(|i| if s.segment_is_line(i) { 1 } else { curve }).sum::(); + path.subpaths.iter().map(|s| 1 + usize::from(s.closed) + segments(s)).sum() +} + +/// One area of a graphic's art, drawn with one paint: a fill, or a stroke's outline. +struct Piece { + path: PathData, + rule: FillRule, + paint: Paint, + opacity: f32, + blend: BlendMode, +} + +/// The areas the art of `symbol` paints, back to front, at the symbol's natural size: the fills of +/// its paths, compound paths and type (as outlines), and its strokes' outlines, through the symbol +/// instances it holds (with their changes to dynamic symbols, and through 9-slice guides). Hidden objects, guides, clipping paths and images are left out, and clipping +/// groups draw their art unclipped. +fn pieces_of(doc: &Document, symbol: &Symbol) -> Result, String> { + fn walk(doc: &Document, n: &Node, outer: f32, xf: Affine, (depth, level): (usize, usize), out: &mut Vec) -> Result<(), String> { + if !n.visible || n.is_guide() { + return Ok(()); + } + if level > MAX_LEVELS { + return Err(format!("A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art")); + } + let opacity = outer * n.opacity; + let shape = match &n.kind { + NodeKind::Path { path, rule, clipping: false, .. } => Some((path.clone(), *rule)), + NodeKind::Compound { children, rule } => { + Some((PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule)) + } + NodeKind::Text(_) => { + if let Some(mut outlined) = crate::outline_text(n) { + // The outlines take the type's place, with its opacity. + outlined.visible = true; + outlined.opacity = n.opacity; + walk(doc, &outlined, outer, xf, (depth, level + 1), out)?; + } + None + } + NodeKind::SymbolInstance { symbol, xf: at } => { + if let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol) { + if depth >= MAX_NESTING { + return Err(format!("A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art")); + } + // The instance shows its own changes to a dynamic symbol's art, and a symbol + // with 9-slice guides is placed through them, as the canvas draws it. The + // pieces are not clipped, so paths that cross a guide are cut at it. + let art = vectorcraft_doc::symbol_overrides::dynamic_art(&s.art, n); + if doc.symbol_slice_map(symbol, *at).is_some() { + let Some(placed) = doc.place_symbol_art_unclipped(symbol, &art, *at) else { + return Err("A graphic's art holds too many objects: simplify the symbol's art".into()); + }; + walk(doc, &placed, opacity, xf, (depth + 1, level + 1), out)?; + } else { + walk(doc, &art, opacity, xf * *at, (depth + 1, level + 1), out)?; + } + } + None + } + _ => { + for c in n.children().into_iter().flatten() { + walk(doc, c, opacity, xf, (depth, level + 1), out)?; + } + None + } + }; + let Some((path, rule)) = shape else { return Ok(()) }; + // Symbol art keeps its strokes' widths as drawn while its geometry is scaled to the + // symbol's square, so a stroke is outlined after the art takes its size. + let path = path.transformed(xf); + for item in n.appearance.items.iter().filter(|i| i.visible()) { + let (area, rule, paint, item_opacity, blend) = match item { + AppearanceItem::Fill(f) => (path.clone(), rule, f.paint.clone(), f.opacity, f.blend), + AppearanceItem::Stroke(s) if s.width > 0.0 && s.width.is_finite() => { + (crate::stroke::outline_region(&path, rule, s), FillRule::EvenOdd, s.paint.clone(), s.opacity, s.blend) + } + AppearanceItem::Stroke(_) => continue, + }; + if matches!(paint, Paint::None) || area.bounds().is_none() { + continue; + } + if out.len() >= MAX_PIECES { + return Err(format!("A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art")); + } + // A placed gradient or pattern takes the same size and place as its path. + let mut paint = paint; + match &mut paint { + Paint::Gradient(g) => g.transform(xf), + Paint::Pattern { xf: placed, .. } => *placed = xf * *placed, + Paint::None | Paint::Solid { .. } => {} + } + out.push(Piece { path: area, rule, paint, opacity: opacity * item_opacity, blend }); + } + Ok(()) + } + let mut out = vec![]; + walk(doc, &symbol.art, 1.0, doc.symbol_natural_xf(&symbol.name), (0, 1), &mut out)?; + Ok(out) +} + +/// `path` through `map`: exactly for an affine map, otherwise with each curve cut into +/// [`PERSPECTIVE_PIECES`] pieces whose control points go through it (straight lines stay straight +/// under a perspective). Fails when part of it has no page point, or when it takes more than `room` +/// elements. +fn map_path(path: &PathData, map: &FaceMap, affine: Option, room: usize) -> Result { + let bp = path.to_bezpath(); + if let Some(a) = affine { + return if bp.elements().len() <= room { Ok(a * bp) } else { Err(NotMapped::Full) }; + } + let to = |p: Point| map.to_page(p).ok_or(NotMapped::Behind); + let mut out = BezPath::new(); + let mut at = Point::ZERO; + for el in bp.elements() { + if out.elements().len() > room { + return Err(NotMapped::Full); + } + match *el { + PathEl::MoveTo(p) => { + out.move_to(to(p)?); + at = p; + } + PathEl::LineTo(p) => { + out.line_to(to(p)?); + at = p; + } + PathEl::QuadTo(c, p) => { + cubic_to(&mut out, vectorcraft_geom::kurbo::QuadBez::new(at, c, p).raise(), map).ok_or(NotMapped::Behind)?; + at = p; + } + PathEl::CurveTo(c1, c2, p) => { + cubic_to(&mut out, CubicBez::new(at, c1, c2, p), map).ok_or(NotMapped::Behind)?; + at = p; + } + PathEl::ClosePath => out.close_path(), + } + } + if out.elements().len() <= room { Ok(out) } else { Err(NotMapped::Full) } +} + +/// Why [`map_path`] drew nothing. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum NotMapped { + /// Part of the path has no page point: it is at or behind the eye. + Behind, + /// The path takes more elements than it has room for. + Full, +} + +/// Curve `c` through `map`, cut into [`PERSPECTIVE_PIECES`] pieces. A piece that lies in front of +/// the eye while a control point does not is split further ([`piece_to`]). `None` when part of a +/// piece has no page point. +fn cubic_to(out: &mut BezPath, c: CubicBez, map: &FaceMap) -> Option<()> { + for k in 0..PERSPECTIVE_PIECES { + let (t0, t1) = (k as f64 / PERSPECTIVE_PIECES as f64, (k + 1) as f64 / PERSPECTIVE_PIECES as f64); + let s = c.subsegment(t0..t1); + if !map.maps_curve([s.p0, s.p1, s.p2, s.p3]) { + return None; + } + piece_to(out, s, map, MAX_SPLITS)?; + } + Some(()) +} + +/// How many times [`piece_to`] halves a piece whose control points are behind the eye. +const MAX_SPLITS: usize = 4; + +/// Piece `s`, which lies in front of the eye, through `map`: halved until the control points of +/// each half have page points, at most `splits` times, and drawn straight past that. +fn piece_to(out: &mut BezPath, s: CubicBez, map: &FaceMap, splits: usize) -> Option<()> { + let end = map.to_page(s.p3)?; + match (map.to_page(s.p1), map.to_page(s.p2)) { + (Some(c1), Some(c2)) => out.curve_to(c1, c2, end), + _ if splits == 0 => out.line_to(end), + _ => { + let (a, b) = s.subdivide(); + piece_to(out, a, map, splits - 1)?; + piece_to(out, b, map, splits - 1)?; + } + } + Some(()) +} + +/// The graphics `graphics` lists for `face`, drawn on caps `caps` (the faces of that end of the +/// object's solids that the viewer sees) through `map`, for an object whose bounds have +/// center `center`: one clipping group of every such graphic, shaded with the first cap's light. +/// Pattern tiles keep their colors: the document's pattern draws them. A graphic whose symbol +/// `doc` does not have draws nothing. `elements` counts the path elements +/// the effect's graphics have drawn so far, after a perspective cuts their curves, and is shared by +/// every call for one effect. `None` when there is nothing to draw or that count passes +/// [`MAX_ELEMENTS`]. +pub(super) fn face_art( + doc: Option<&Document>, + id: NodeId, + graphics: &[MappedGraphic], + (face, map): (PlanarFace, &FaceMap), + center: Point, + caps: &[&Facet], + elements: &mut usize, +) -> Option { + let doc = doc?; + let light = caps.first()?.illumination; + let affine = map.local_affine(center).filter(|_| map.is_affine()); + let mut children = vec![]; + for g in graphics.iter().filter(|g| g.face == face) { + let Some(symbol) = doc.symbols.iter().find(|s| s.name == g.symbol) else { continue }; + // A symbol past the limits is left out; the other graphics still draw. + let Ok(pieces) = pieces_of(doc, symbol) else { continue }; + let Some(bounds) = pieces.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) else { continue }; + let place = g.placement(bounds, center); + // Gradients follow the face's map as it is near the graphic's center. + let middle = place * bounds.center(); + // When the center is at or behind the eye, they follow it near the middle of the part that + // is in front; a graphic with no part in front is left out. + let local = map.local_affine(middle).or_else(|| { + let part = map.mapped_part(place.transform_rect_bbox(bounds))?; + let sum = part.iter().fold(Point::ZERO, |s, p| s + p.to_vec2()); + map.local_affine(Point::new(sum.x / part.len() as f64, sum.y / part.len() as f64)) + }); + let Some(local) = local else { continue }; + let gradient_map = local * place; + for piece in pieces { + let placed = piece.path.transformed(place); + // Each anchor draws at least one element. A perspective cuts curves into more, and + // straight lines stay one each: the path may take what is left of the limit, and is + // counted as it is drawn. Past the limit, the face draws nothing. + let least: usize = placed.subpaths.iter().map(|s| s.anchors.len()).sum(); + let before = *elements; + if before.saturating_add(least) > MAX_ELEMENTS { + return None; + } + let room = MAX_ELEMENTS - before; + let mut rule = piece.rule; + let mapped = match map_path(&placed, map, affine, room) { + Err(NotMapped::Behind) => { + // Part of it is at or behind the eye: the part in front is drawn. + let Some(part) = placed.bounds().and_then(|b| map.mapped_part(b)) else { continue }; + let Some(&first) = part.first() else { continue }; + let mut front = BezPath::new(); + front.move_to(first); + part.iter().skip(1).for_each(|p| front.line_to(*p)); + front.close_path(); + let cut = vectorcraft_pathops::boolean( + &placed, + piece.rule, + &PathData::from_bezpath(&front), + FillRule::NonZero, + vectorcraft_pathops::BoolOp::Intersect, + ); + rule = FillRule::NonZero; + map_path(&cut, map, affine, room) + } + done => done, + }; + let mapped = match mapped { + Ok(mapped) => mapped, + Err(NotMapped::Full) => return None, + Err(NotMapped::Behind) => continue, + }; + *elements = before.saturating_add(mapped.elements().len()); + let mut paint = piece.paint; + vectorcraft_doc::recolor::map_paint(&mut paint, &|c| crate::lighting::shade(c, light)); + // A pattern's tiles follow the graphic onto the face, as its gradients do below. + if let Paint::Pattern { xf, .. } = &mut paint { + *xf = gradient_map * *xf; + } + let mut fill = FillLayer::new(paint); + fill.opacity = piece.opacity; + fill.blend = piece.blend; + let mut appearance = Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }; + appearance.transform_gradients(gradient_map); + let mut node = Node::path(id, PathData::from_bezpath(&mapped), appearance); + if let NodeKind::Path { rule: r, .. } = &mut node.kind { + *r = rule; + } + children.push(Arc::new(node)); + } + } + if children.is_empty() { + return None; + } + let mut clip = BezPath::new(); + for cap in caps { + // A cap's holes are contours of the same path wound against its outline, so turning the + // whole path keeps them holes under the nonzero rule. + let mut outline = cap.path().to_bezpath(); + if outline.area() < 0.0 { + outline = outline.reverse_subpaths(); + } + clip.extend(outline.iter()); + } + let clip = Node::path(id, PathData::from_bezpath(&clip), Appearance::default()); + Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, children))], clip: true })) +} + +/// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. +pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { + let symbol = doc.symbols.iter().find(|s| s.name == name)?; + pieces_of(doc, symbol).ok()?.iter().filter_map(|p| p.path.bounds()).reduce(|a, b| a.union(b)) +} + +/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' +/// offsets are from their center) and the maps of its front and back faces, when it has them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GraphicFrame { + pub bounds: Rect, + front: Option, + back: Option, +} + +impl GraphicFrame { + pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { + Self { bounds, front, back } + } + + pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { + match face { + PlanarFace::Front => self.front.as_ref(), + PlanarFace::Back => self.back.as_ref(), + } + } + + /// The point of `face`'s plane that offset `(x, y)` names, as [`MappedGraphic`] places a + /// graphic's center. + fn art_point(&self, face: PlanarFace, (x, y): (f64, f64)) -> Point { + let c = self.bounds.center(); + match face { + PlanarFace::Front => Point::new(c.x + x, c.y + y), + PlanarFace::Back => Point::new(c.x - x, c.y + y), + } + } + + /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the + /// viewer. `None` when the object has no such face or the point has no page point. + pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + let map = self.map(g.face)?; + Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) + } + + /// The offset of a graphic on `face` whose center lands on page point `page`. + pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { + let art = self.map(face)?.to_art(page)?; + let c = self.bounds.center(); + let (x, y) = match face { + PlanarFace::Front => (art.x - c.x, art.y - c.y), + PlanarFace::Back => (c.x - art.x, art.y - c.y), + }; + (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) + } + + /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most + /// 100: where a newly mapped graphic starts. + pub fn fitting_scale(&self, art: Rect) -> f64 { + let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + } +} + +/// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). +pub fn graphic_symbols(n: &Node) -> Vec { + appearance_graphic_symbols(&n.appearance) +} + +/// The symbols the graphics of the 3D effects in `appearance` name, as [`graphic_symbols`]: for a +/// graphic style's appearance. +pub fn appearance_graphic_symbols(appearance: &Appearance) -> Vec { + std::iter::once(&appearance.effects) + .chain(appearance.items.iter().map(AppearanceItem::effects)) + .flatten() + .filter(|e| takes_graphics(&e.id)) + .flat_map(|e| mapped_graphics(&e.params)) + .map(|g| g.symbol) + .collect() +} + +/// Makes the graphics of `n`'s 3D effects that name symbol `from` name `to` instead. Returns +/// whether any changed. +pub fn rename_graphic_symbol(n: &mut Node, from: &str, to: &str) -> bool { + // Checked first, so an appearance that names another symbol is not copied. + graphic_symbols(n).iter().any(|s| s == from) && rename_appearance_graphic_symbol(&mut n.appearance, from, to) +} + +/// [`rename_graphic_symbol`] for the 3D effects in `appearance`: for a graphic style's appearance. +pub fn rename_appearance_graphic_symbol(appearance: &mut Appearance, from: &str, to: &str) -> bool { + if !appearance_graphic_symbols(appearance).iter().any(|s| s == from) { + return false; + } + let mut lists: Vec<&mut Vec> = vec![]; + let (effects, items) = (&mut appearance.effects, &mut appearance.items); + lists.push(effects); + lists.extend(items.iter_mut().map(AppearanceItem::effects_mut)); + for e in lists.into_iter().flatten().filter(|e| takes_graphics(&e.id)) { + if let Some(Value::Array(list)) = e.params.get_mut(GRAPHICS) { + for g in list.iter_mut() { + if g.get("symbol").and_then(Value::as_str) == Some(from) { + g["symbol"] = json!(to); + } + } + } + } + true +} + +/// Does `n` or any object in it, opacity masks included, have a graphic that names symbol `from`? +pub fn names_graphic_symbol(n: &Node, from: &str) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| found |= graphic_symbols(c).iter().any(|s| s == from)); + found +} + +/// [`rename_graphic_symbol`] for `n` and every object in it, at any depth, opacity masks included. +/// Only the parts that name `from` are copied. Returns whether any changed. +pub fn rename_graphic_symbol_in(n: &mut Node, from: &str, to: &str) -> bool { + let names = names_graphic_symbol; + let mut changed = rename_graphic_symbol(n, from, to); + if let Some(mask) = n.extras_if_any().and_then(|x| x.mask.as_deref_mut()).filter(|m| names(&m.art, from)) { + changed |= rename_graphic_symbol_in(Arc::make_mut(&mut mask.art), from, to); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| names(c, from)) { + changed |= rename_graphic_symbol_in(Arc::make_mut(c), from, to); + } + } + changed +} + +/// `p` with graphic `g` added at the end of its list. +pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { + let mut out = p.as_object().cloned().unwrap_or_else(Map::new); + let mut list = match out.get(GRAPHICS) { + Some(Value::Array(list)) => list.clone(), + _ => vec![], + }; + list.push(g.to_value()); + out.insert(GRAPHICS.into(), Value::Array(list)); + Value::Object(out) +} + +#[cfg(test)] +#[path = "tests_graphics.rs"] +mod tests; diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs new file mode 100644 index 0000000000..64c947a9df --- /dev/null +++ b/crates/effects/src/solids/tests_graphics.rs @@ -0,0 +1,659 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, INFLATE, ROTATE, graphic_frame, solid_art_in, three_d_params_as, validate_three_d_in, validate_three_d_params}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0) with effect `id`, its parameters `params` over a view +/// straight on. +fn object(id: &str, params: Value) -> Node { + let mut p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(id, &p).unwrap()); + n +} + +/// The graphics clip groups in `art`, in drawing order: each one's mapped paths. +fn graphics_in(art: &Node) -> Vec> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let [_, inner] = children.as_slice() + && let NodeKind::Group { children: paths, clip: false } = &inner.kind + { + let paths: Vec<(PathData, Paint)> = paths + .iter() + .filter_map(|p| { + let fill = p.appearance.items.iter().find_map(|i| match i { + AppearanceItem::Fill(f) => Some(f.paint.clone()), + AppearanceItem::Stroke(_) => None, + })?; + Some((p.path_data()?.clone(), fill)) + }) + .collect(); + if paths.iter().any(|(_, p)| p.color().is_some_and(|c| c.to_rgb()[1] < 0.1 && c.to_rgb()[0] > 0.3)) { + out.push(paths); + } + } + }); + out +} + +fn bounds_of(paths: &[(PathData, Paint)]) -> Rect { + paths.iter().filter_map(|(p, _)| p.bounds()).reduce(|a, b| a.union(b)).unwrap() +} + +fn close(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +#[test] +fn a_graphic_is_drawn_on_the_front_cap_at_its_offset_size_and_turn() { + let d = document(); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = graphics_in(&art); + assert_eq!(found.len(), 1); + // Straight on, the front cap is the art: a 20 × 20 square centered 20 right of and 10 above (50, 50). + assert!(close(bounds_of(&found[0]), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds_of(&found[0])); + // Turned 45°, the square's corners reach out to its half diagonal. + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "rotation": 45.0}]})); + let b = bounds_of(&graphics_in(&solid_art_in(Some(&d), &n).unwrap())[0]); + assert!((b.width() - 10.0 * 2f64.sqrt()).abs() < 1e-6); +} + +#[test] +fn without_the_document_or_its_symbol_nothing_is_drawn() { + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark"}]})); + let art = solid_art_in(None, &n).unwrap(); + assert!(graphics_in(&art).is_empty()); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Gone"}]})); + assert!(graphics_in(&solid_art_in(Some(&document()), &n).unwrap()).is_empty()); + // Without graphics, the art is the same as before they existed. + let plain = object(EXTRUDE, json!({})); + assert_eq!(solid_art_in(Some(&document()), &plain), solid_art_in(None, &plain)); +} + +#[test] +fn the_graphic_is_shaded_with_its_face() { + let d = document(); + let n = object(EXTRUDE, json!({"shade": true, "lightIntensity": 0.0, "ambient": 50.0, "graphics": [{"symbol": "Mark"}]})); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + let c = found[0][0].1.color().unwrap().to_rgb(); + assert!((c[0] - 0.5).abs() < 1e-3 && c[1].abs() < 1e-6 && c[2].abs() < 1e-6, "{c:?}"); +} + +#[test] +fn the_graphic_goes_right_after_its_cap_and_is_clipped_to_it() { + let d = document(); + let n = object(EXTRUDE, json!({"rotationX": -20.0, "rotationY": 25.0, "graphics": [{"symbol": "Mark", "scale": 2000.0}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let NodeKind::Group { children, .. } = &art.kind else { panic!("a group") }; + let NodeKind::Group { children: faces, .. } = &children.last().unwrap().kind else { panic!("the ordered faces") }; + let last = faces.last().unwrap(); + assert!(matches!(&last.kind, NodeKind::Group { clip: true, .. }), "the graphic is drawn last, over the front cap"); + let NodeKind::Group { children: parts, .. } = &last.kind else { panic!() }; + let clip = parts[0].path_data().unwrap().bounds().unwrap(); + let cap = faces[faces.len() - 2].path_data().unwrap().bounds().unwrap(); + assert!(close(clip, cap), "clipped to the cap: {clip:?} against {cap:?}"); +} + +#[test] +fn the_back_cap_reads_the_right_way_round_from_behind() { + let d = document(); + let behind = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0}]}); + let n = object(EXTRUDE, behind); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + assert_eq!(found.len(), 1); + let b = bounds_of(&found[0]); + // Seen from behind, x runs to the right on the page too. + assert!((b.center().x - 70.0).abs() < 1e-6, "{b:?}"); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 20.0})).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && (at.x - 70.0).abs() < 1e-6); + let (x, y) = frame.offset_at(PlanarFace::Back, Point::new(40.0, 55.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6); + // From the front the back cap is hidden, and so is its graphic. + let front = object(EXTRUDE, json!({"graphics": [{"symbol": "Mark", "face": "back"}]})); + assert!(graphics_in(&solid_art_in(Some(&d), &front).unwrap()).is_empty()); +} + +#[test] +fn a_perspective_foreshortens_the_graphic_with_its_face() { + let d = document(); + let params = json!({"rotationX": -30.0, "rotationY": 35.0, "perspectiveAngle": 100.0, "graphics": [{"symbol": "Mark", "scale": 400.0}]}); + let n = object(EXTRUDE, params); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let map = frame.map(PlanarFace::Front).unwrap(); + // The corners of the 40 × 40 square centered on the object land where the face's map takes them. + let path = &found[0][0].0; + let corners: Vec = [(30.0, 30.0), (70.0, 30.0), (70.0, 70.0), (30.0, 70.0)].map(|(x, y)| map.to_page(Point::new(x, y)).unwrap()).into(); + for c in corners { + let near = path.subpaths.iter().flat_map(|s| &s.anchors).map(|a| a.p.distance(c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "{c:?} is {near} from the drawn graphic"); + } +} + +#[test] +fn a_graphic_behind_the_eye_leaves_the_others_drawn() { + let d = document(); + let view = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0}); + let n = object(EXTRUDE, view.clone()); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let map = frame.map(PlanarFace::Front).unwrap(); + let c = frame.bounds.center(); + // An offset whose point of the front's plane is at or behind the eye. + let y = [1.0, -1.0] + .into_iter() + .flat_map(|s| (1..60).map(move |k| s * 10f64.powf(f64::from(k) / 10.0))) + .find(|y| map.local_affine(Point::new(c.x, c.y + y)).is_none()) + .expect("an offset behind the eye"); + let mut params = view; + params["graphics"] = json!([{"symbol": "Mark"}, {"symbol": "Mark", "y": y}]); + let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap()); + assert_eq!(found.len(), 1, "the graphic that projects is still drawn"); + // A graphic centered there but large enough to reach over the cap draws the part in front. + let mut params = json!({"rotationX": -60.0, "rotationY": 0.0, "perspectiveAngle": 160.0}); + params["graphics"] = json!([{"symbol": "Mark", "y": y, "scale": (20.0 * (y.abs() + 50.0)).clamp(1.0, 10_000.0)}]); + let found = graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, params)).unwrap()); + assert_eq!(found.len(), 1, "the part in front is drawn (offset {y})"); + assert!(!found[0].is_empty()); +} + +#[test] +fn the_graphic_takes_the_opacity_of_its_fill() { + let d = document(); + for id in [EXTRUDE, ROTATE] { + let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.25; + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut opacities = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + opacities.push(c.opacity); + } + }); + assert_eq!(opacities, vec![0.25], "{id}"); + } +} + +#[test] +fn the_graphic_takes_the_blending_mode_of_its_fill() { + let d = document(); + for id in [EXTRUDE, ROTATE] { + let mut n = object(id, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.blend = BlendMode::Multiply; + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut blends = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + blends.push(c.blend); + } + }); + assert_eq!(blends, vec![BlendMode::Multiply], "{id}"); + } +} + +#[test] +fn each_fill_of_a_plane_gives_its_graphic_its_own_opacity() { + let d = document(); + let mut n = object(ROTATE, json!({"graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.opacity = 0.25; + } + let mut second = FillLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2))); + second.opacity = 0.75; + n.appearance.items.push(AppearanceItem::Fill(second)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut opacities = vec![]; + art.walk(&mut |c| { + if matches!(c.kind, NodeKind::Group { clip: true, .. }) { + opacities.push(c.opacity); + } + }); + opacities.sort_by(f32::total_cmp); + assert_eq!(opacities, vec![0.25, 0.75]); +} + +#[test] +fn a_symbols_gradient_takes_the_size_of_its_art() { + use vectorcraft_doc::color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let mut d = document(); + // Symbol art kept in its 20 × 20 square, drawn 40 × 20. + let mut g = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), GradientStop::new(1.0, Color::BLACK)])); + g.geom = Some(GradientGeom { start: Point::new(-10.0, 0.0), end: Point::new(10.0, 0.0), aspect: 1.0, focal: None }); + let art = square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), Paint::Gradient(Box::new(g))); + d.symbols.push(Symbol { dynamic: false, name: "Ramp".into(), art: Arc::new(art) }); + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({"Ramp": [40.0, 20.0]})); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ramp"}]})); + let out = solid_art_in(Some(&d), &n).unwrap(); + let mut found = None; + out.walk(&mut |c| { + if let (Some(p), Some(AppearanceItem::Fill(f))) = (c.path_data(), c.appearance.items.first()) + && let Paint::Gradient(g) = &f.paint + { + found = Some((p.bounds().unwrap(), g.geom.unwrap())); + } + }); + let (bounds, geom) = found.unwrap(); + assert!(close(bounds, Rect::new(30.0, 40.0, 70.0, 60.0)), "{bounds:?}"); + assert!(geom.start.distance(Point::new(30.0, 50.0)) < 1e-6 && geom.end.distance(Point::new(70.0, 50.0)) < 1e-6, "{geom:?}"); +} + +#[test] +fn a_symbols_pattern_follows_the_graphic() { + let mut d = document(); + let tiles = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + d.symbols.push(Symbol { dynamic: false, name: "Tiles".into(), art: Arc::new(square(0, Rect::new(-10.0, -10.0, 10.0, 10.0), tiles)) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Tiles", "scale": 200.0}]})); + let out = solid_art_in(Some(&d), &n).unwrap(); + let mut found = None; + out.walk(&mut |c| { + if let Some(AppearanceItem::Fill(f)) = c.appearance.items.first() + && let Paint::Pattern { xf, .. } = &f.paint + { + found = Some((c.path_data().unwrap().bounds().unwrap(), *xf)); + } + }); + let (bounds, xf) = found.unwrap(); + // The 20 × 20 art drawn 40 × 40 on the middle of the front: its tiles go with it. + assert!(close(bounds, Rect::new(30.0, 30.0, 70.0, 70.0)), "{bounds:?}"); + assert!((xf * Point::new(-10.0, -10.0)).distance(Point::new(30.0, 30.0)) < 1e-6, "{xf:?}"); + assert!((xf * Point::new(10.0, 10.0)).distance(Point::new(70.0, 70.0)) < 1e-6, "{xf:?}"); +} + +#[test] +fn a_curve_in_front_of_the_eye_maps_though_its_control_points_do_not() { + let bounds = Rect::new(10.0, 20.0, 70.0, 60.0); + let view = vectorcraft_three_d::View { rotation_x: -89.0, rotation_y: 40.0, rotation_z: 10.0, perspective: 160.0, ..Default::default() }; + let map = vectorcraft_three_d::plane_face_map(bounds, view).unwrap(); + // Where the page map stops along the line x = `x`, between the center and a point it does not map. + let edge = |x: f64| { + let inside = Point::new(x, bounds.center().y); + let far = [Point::new(x, -1e6), Point::new(x, 1e6)].into_iter().find(|p| map.to_page(*p).is_none()).unwrap(); + let (mut a, mut b) = (inside, far); + for _ in 0..200 { + let m = a.midpoint(b); + if map.to_page(m).is_some() { a = m } else { b = m } + } + a + }; + let (b1, b2) = (edge(40.0), edge(60.0)); + let u = (b2 - b1).normalize(); + let mut n = vectorcraft_geom::Vec2::new(-u.y, u.x); + if map.to_page(b1 + n * 10.0).is_none() { + n = -n; + } + // Ends 219.17 in front of that line and control points 100 and 42 past it: the curve stays + // about 1 in front, while a control point of one of the pieces it is cut into falls behind. + let at = |s: f64, t: f64| b1 + n * s + u * t; + let mut curve = BezPath::new(); + curve.move_to(at(219.17, 0.0)); + curve.curve_to(at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0)); + let c = CubicBez::new(at(219.17, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(219.17, 20.0)); + assert!((0..=1000).all(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_some()), "the curve itself is in front"); + let pieces = (0..PERSPECTIVE_PIECES).map(|k| c.subsegment(k as f64 / 8.0..(k + 1) as f64 / 8.0)); + assert!(pieces.flat_map(|s| [s.p1, s.p2]).any(|p| map.to_page(p).is_none()), "a piece's control point is behind"); + let mapped = map_path(&PathData::from_bezpath(&curve), &map, None, usize::MAX).expect("the curve maps"); + // The split pieces count toward the room the path is given: without room, the path is full, + // not behind the eye, so it is not clipped. + assert!(mapped.elements().len() > 1 + PERSPECTIVE_PIECES); + assert_eq!(map_path(&PathData::from_bezpath(&curve), &map, None, PERSPECTIVE_PIECES + 1).err(), Some(NotMapped::Full)); + assert!(mapped.elements().iter().all(|e| e.end_point().is_none_or(|p| p.x.is_finite() && p.y.is_finite()))); + // That piece is split until its halves' control points map, so it stays a curve. + assert!(mapped.elements().iter().all(|e| !matches!(e, PathEl::LineTo(_))), "{mapped:?}"); + // With its ends at 214.25 instead, the curve dips about 0.24 behind the line between the ends + // of two pieces, which still map: it has no page point there, and is left to the clipping. + let c = CubicBez::new(at(214.25, 0.0), at(-100.0, 5.0), at(-42.0, 15.0), at(214.25, 20.0)); + assert!((0..=PERSPECTIVE_PIECES).all(|k| map.to_page(c.eval(k as f64 / 8.0)).is_some())); + assert!((0..=1000).any(|k| map.to_page(c.eval(k as f64 / 1000.0)).is_none())); + let mut dips = BezPath::new(); + dips.move_to(c.p0); + dips.curve_to(c.p1, c.p2, c.p3); + assert_eq!(map_path(&PathData::from_bezpath(&dips), &map, None, usize::MAX).err(), Some(NotMapped::Behind)); +} + +#[test] +fn members_with_their_own_blending_get_graphics_of_their_own() { + let d = document(); + let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + b.blend = BlendMode::Multiply; + let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &group).unwrap(); + let found = graphics_in(&art); + // One graphic clipped to each member's cap: the second stays inside the member's Multiply group. + assert_eq!(found.len(), 2); + let mut blended = 0; + art.walk(&mut |c| { + if c.blend == BlendMode::Multiply { + blended += graphics_in(c).len(); + } + }); + assert_eq!(blended, 1); +} + +/// [`document`] with symbol "Dense" too: a red polygon of 30,000 sides, straight or `curved`. +fn dense_document(curved: bool) -> Document { + let mut d = document(); + let mut poly = BezPath::new(); + let mut last = Point::ZERO; + for k in 0..30_000 { + let a = k as f64 / 30_000.0 * std::f64::consts::TAU; + let p = Point::new(5.0 + 5.0 * a.cos(), 5.0 + 5.0 * a.sin()); + if k == 0 { + poly.move_to(p); + } else if curved { + poly.curve_to(last.lerp(p, 1.0 / 3.0), last.lerp(p, 2.0 / 3.0), p); + } else { + poly.line_to(p); + } + last = p; + } + poly.close_path(); + let art = Node::path(NodeId(0), PathData::from_bezpath(&poly), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Dense".into(), art: Arc::new(art) }); + d +} + +/// The graphics drawn on a group of two members, each with its own graphic of symbol "Dense" +/// ([`dense_document`]), seen under a perspective. +fn dense_graphics_drawn(curved: bool) -> usize { + let d = dense_document(curved); + let a = square(1, Rect::new(0.0, 0.0, 50.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + let mut b = square(2, Rect::new(50.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + b.blend = BlendMode::Multiply; + let mut group = Node::group(NodeId(3), vec![Arc::new(a), Arc::new(b)]); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "perspectiveAngle": 60.0, "shade": false, "graphics": [{"symbol": "Dense", "scale": 1000.0}]}); + group.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + graphics_in(&solid_art_in(Some(&d), &group).unwrap()).len() +} + +#[test] +fn members_with_graphics_of_their_own_share_one_element_limit() { + // A perspective cuts each of the 30,000 curves into 8: one copy fits the limit, two do not. + // The first member's graphic is drawn; the second would pass the limit, so it draws none. + assert_eq!(dense_graphics_drawn(true), 1); +} + +#[test] +fn straight_sides_count_once_under_a_perspective() { + // A perspective keeps each of the 30,000 straight sides one element: both copies fit the limit. + assert_eq!(dense_graphics_drawn(false), 2); +} + +#[test] +fn the_symbol_check_counts_what_the_view_draws() { + // Two graphics of the 30,000-sided polygon under a perspective: straight, they fit the limit; + // curved, they do not. + let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]}); + let n = object(EXTRUDE, two.clone()); + assert!(validate_three_d_in(Some(&dense_document(false)), &n, EXTRUDE, &two).is_ok()); + let e = validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &two).unwrap_err(); + assert!(e.contains("too complex"), "{e}"); + // Without a perspective each curve draws once: curved, they fit too. + let flat = json!({"perspectiveAngle": 0.0, "graphics": two["graphics"].clone()}); + assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok()); +} + +#[test] +fn a_plane_and_a_hollow_solid() { + let d = document(); + let plane = object(ROTATE, json!({"rotationY": 30.0, "graphics": [{"symbol": "Mark"}]})); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &plane).unwrap()).len(), 1); + let hollow = object(EXTRUDE, json!({"cap": false, "graphics": [{"symbol": "Mark"}]})); + assert!(graphics_in(&solid_art_in(Some(&d), &hollow).unwrap()).is_empty()); +} + +#[test] +fn a_stroked_graphic_draws_its_stroke_as_an_outline() { + let mut d = document(); + let mut ring = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::None); + ring.appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(red()), 2.0))], ..Default::default() }.into(); + d.symbols.push(Symbol { dynamic: false, name: "Ring".into(), art: Arc::new(ring) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Ring"}]})); + let found = graphics_in(&solid_art_in(Some(&d), &n).unwrap()); + // The 10 × 10 square's 2 pt stroke reaches 1 pt outside it. + assert!(close(bounds_of(&found[0]), Rect::new(44.0, 44.0, 56.0, 56.0)), "{:?}", bounds_of(&found[0])); +} + +#[test] +fn graphics_are_checked() { + let n = object(EXTRUDE, json!({})); + let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([])).is_ok()); + for bad in [ + json!("Mark"), + json!([{"face": "front"}]), + json!([{"symbol": ""}]), + json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "scale": 0.0}]), + json!([{"symbol": "Mark", "rotation": 400.0}]), + json!([{"symbol": "Mark", "x": "1"}]), + json!([{"symbol": "Mark", "repeat": true}]), + json!(vec![json!({"symbol": "Mark"}); MAX_GRAPHICS + 1]), + ] { + assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); + } + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); + assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); + // A loaded file's invalid entries are left out when drawn. + assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); +} + +#[test] +fn the_frame_at_an_index_is_that_effects() { + let d = document(); + let mut n = object(EXTRUDE, json!({})); + n.appearance.effects.push(crate::new_effect(ROTATE, &json!({})).unwrap()); + // The first 3D effect is the Extrude & Bevel, with a back cap; the second is a plane, without. + assert!(graphic_frame(Some(&d), &n, None).unwrap().map(PlanarFace::Back).is_some()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 0).unwrap().map(PlanarFace::Back).is_some()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 1).unwrap().map(PlanarFace::Back).is_none()); + assert!(super::super::graphic_frame_at(Some(&d), &n, None, 2).is_none()); +} + +#[test] +fn a_change_to_a_plane_drops_the_back_caps_graphics() { + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let plane = three_d_params_as(EXTRUDE, &p, ROTATE); + assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Back to Extrude & Bevel, the front's graphic stays. + assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); +} + +#[test] +fn a_stroked_solid_carries_its_graphic_too() { + let d = document(); + let mut n = Node::path( + NodeId(7), + shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), + Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 20.0), + ); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).len(), 1); +} + +#[test] +fn art_nested_too_deep_is_refused_and_not_drawn() { + let mut d = document(); + let mut art = square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red())); + for k in 0..=MAX_LEVELS { + art = Node::group(NodeId(k as u64 + 1), vec![Arc::new(art)]); + } + d.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(art) }); + let n = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}]})); + let e = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Deep"}]})).unwrap_err(); + assert!(e.contains("nested"), "{e}"); + assert!(graphics_in(&solid_art_in(Some(&d), &n).unwrap()).is_empty()); + // A loaded file draws its other graphics. + let both = object(EXTRUDE, json!({"graphics": [{"symbol": "Deep"}, {"symbol": "Mark"}]})); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &both).unwrap()).len(), 1); +} + +#[test] +fn symbols_nested_too_deep_are_refused_and_not_drawn() { + let mut d = document(); + // Symbol `N{k}` holds an instance of `N{k-1}`, and `N0` is a square. + d.symbols.push(Symbol { dynamic: false, name: "N0".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) }); + for k in 1..=MAX_NESTING + 1 { + let instance = Node::new(NodeId(k as u64), NodeKind::SymbolInstance { symbol: format!("N{}", k - 1), xf: Affine::IDENTITY }); + d.symbols.push(Symbol { dynamic: false, name: format!("N{k}"), art: Arc::new(instance) }); + } + let deepest = format!("N{MAX_NESTING}"); + let p = json!({"graphics": [{"symbol": deepest}]}); + assert!(validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).is_ok()); + assert_eq!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).len(), 1); + let past = format!("N{}", MAX_NESTING + 1); + let p = json!({"graphics": [{"symbol": past}]}); + let e = validate_three_d_in(Some(&d), &object(EXTRUDE, p.clone()), EXTRUDE, &p).unwrap_err(); + assert!(e.contains("nest"), "{e}"); + assert!(graphics_in(&solid_art_in(Some(&d), &object(EXTRUDE, p)).unwrap()).is_empty()); +} + +#[test] +fn a_solid_in_a_transparent_gradient_keeps_its_graphic() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let d = document(); + let mut stop = GradientStop::new(1.0, red()); + stop.opacity = 0.25; + let gradient = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red()), stop])); + // Under a colored light the faces are drawn opaque and masked by the gradient's transparency. + let mut n = object(EXTRUDE, json!({"shade": true, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark"}]})); + if let Some(AppearanceItem::Fill(f)) = n.appearance.items.first_mut() { + f.paint = Paint::Gradient(Box::new(gradient)); + } + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut masked = false; + art.walk(&mut |c| masked |= c.extras().mask.is_some()); + assert!(masked); + assert_eq!(graphics_in(&art).len(), 1); + // Each graphic clip group in `art`, in drawing order: whether it carries an opacity mask. + let masks = |art: &Node| { + let mut out = vec![]; + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind + && let [_, inner] = children.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: false, .. }) + { + out.push(c.extras().mask.is_some()); + } + }); + out + }; + // The graphic carries the cap's mask, so it is hidden where the gradient is transparent. + assert_eq!(masks(&art), vec![true]); + // With an opaque stroke drawn after the fill, the fill's cap keeps a masked graphic of its own + // and the stroke's outline gets an unmasked one. + n.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))); + assert_eq!(masks(&solid_art_in(Some(&d), &n).unwrap()), vec![true, false]); +} + +#[test] +fn a_cap_with_a_hole_keeps_the_hole_out_of_the_graphic() { + let d = document(); + let outer = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)).to_bezpath(); + let hole = shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)).to_bezpath().reverse_subpaths(); + let mut ring = outer; + ring.extend(hole.iter()); + for flip in [false, true] { + let ring = if flip { ring.reverse_subpaths() } else { ring.clone() }; + let mut n = + Node::path(NodeId(7), PathData::from_bezpath(&ring), Appearance::basic(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), Paint::None, 0.0)); + let p = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false, "graphics": [{"symbol": "Mark", "scale": 2000.0}]}); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + let art = solid_art_in(Some(&d), &n).unwrap(); + let mut clips = vec![]; + art.walk(&mut |c| { + if let NodeKind::Group { children, clip: true } = &c.kind { + clips.push(children[0].path_data().unwrap().to_bezpath()); + } + }); + assert_eq!(clips.len(), 1, "flip {flip}"); + assert_ne!(clips[0].winding(Point::new(10.0, 10.0)), 0, "flip {flip}: the ring is inside the clip"); + assert_eq!(clips[0].winding(Point::new(50.0, 50.0)), 0, "flip {flip}: the hole is outside it"); + } +} + +#[test] +fn a_graphic_starts_inside_its_object() { + let d = document(); + let frame = graphic_frame(Some(&d), &object(EXTRUDE, json!({})), None).unwrap(); + assert_eq!(frame.fitting_scale(Rect::new(0.0, 0.0, 10.0, 10.0)), 100.0); + assert!((frame.fitting_scale(Rect::new(0.0, 0.0, 400.0, 200.0)) - 25.0).abs() < 1e-9); + assert_eq!(super::super::graphic_bounds(&d, "Mark"), Some(Rect::new(500.0, 500.0, 510.0, 510.0))); +} + +#[test] +fn a_symbol_instance_in_a_graphic_draws_as_the_canvas_shows_it() { + let mut d = document(); + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + // A dynamic symbol whose instance in "Changed" fills its square blue instead of red. + d.symbols.push(Symbol { dynamic: true, name: "Dynamic".into(), art: Arc::new(square(0, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red()))) }); + let mut changed = Node::new(NodeId(1), NodeKind::SymbolInstance { symbol: "Dynamic".into(), xf: Affine::IDENTITY }); + changed.extras_mut().symbol_overrides = + vec![vectorcraft_doc::symbol_overrides::SymbolOverride { fill: Some(blue.clone()), ..Default::default() }]; + d.symbols.push(Symbol { dynamic: false, name: "Changed".into(), art: Arc::new(changed) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Changed").unwrap()).unwrap(); + assert_eq!(pieces.iter().map(|p| p.paint.clone()).collect::>(), [blue]); + // A symbol with 9-slice guides, a 100 × 100 square with a 10 × 10 one in its corner, placed + // three times as wide: the corner keeps its width while the rest stretches. + let corner = square(2, Rect::new(0.0, 0.0, 10.0, 10.0), Paint::solid(red())); + let whole = square(3, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(red())); + d.symbols.push(Symbol { dynamic: false, name: "Sliced".into(), art: Arc::new(Node::group(NodeId(4), vec![Arc::new(whole), Arc::new(corner)])) }); + d.set_symbol_nine_slice("Sliced", Some(vectorcraft_doc::SymbolNineSlice::default())); + let wide = Node::new(NodeId(5), NodeKind::SymbolInstance { symbol: "Sliced".into(), xf: Affine::scale_non_uniform(3.0, 1.0) }); + d.symbols.push(Symbol { dynamic: false, name: "Wide".into(), art: Arc::new(wide) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "Wide").unwrap()).unwrap(); + let widths: Vec = pieces.iter().map(|p| p.path.bounds().unwrap().width()).collect(); + assert_eq!(widths.len(), 2); + assert!((widths[1] / widths[0] - 1.0 / 30.0).abs() < 1e-6, "{widths:?}"); + // With a gradient, the square crossing the guides is cut at them: its pieces cover the + // placed 300 × 100 once, not one whole copy for each cell. + use vectorcraft_doc::color::{Gradient, GradientPaint}; + let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + let shaded = square(6, Rect::new(0.0, 0.0, 100.0, 100.0), gradient); + d.symbols.push(Symbol { dynamic: false, name: "Shaded".into(), art: Arc::new(Node::group(NodeId(7), vec![Arc::new(shaded)])) }); + d.set_symbol_nine_slice("Shaded", Some(vectorcraft_doc::SymbolNineSlice::default())); + let wide = Node::new(NodeId(8), NodeKind::SymbolInstance { symbol: "Shaded".into(), xf: Affine::scale_non_uniform(3.0, 1.0) }); + d.symbols.push(Symbol { dynamic: false, name: "WideShaded".into(), art: Arc::new(wide) }); + let pieces = pieces_of(&d, d.symbols.iter().find(|s| s.name == "WideShaded").unwrap()).unwrap(); + let area: f64 = pieces.iter().map(|p| p.path.to_bezpath().area().abs()).sum(); + assert!((area - 30_000.0).abs() < 1e-3, "{area}"); +} diff --git a/crates/effects/src/tests/rasterfollow.rs b/crates/effects/src/tests/rasterfollow.rs index c674cf5041..e0c7bc5130 100644 --- a/crates/effects/src/tests/rasterfollow.rs +++ b/crates/effects/src/tests/rasterfollow.rs @@ -325,6 +325,23 @@ fn a_shadow_before_a_transform_follows_it_into_3d_art() { } } +/// An object's Transform effect transforms the raster effects of its fills when only a fill has a +/// 3D effect: the shadow after that fill's 3D effect and another fill's shadow, as it does without +/// the 3D effect. +#[test] +fn an_objects_transform_moves_its_fills_shadows_beside_a_fills_3d_effect() { + for three_d in [crate::EXTRUDE, crate::REVOLVE] { + let art = |n: &Node| if three_d == crate::EXTRUDE { crate::solid_art(n) } else { crate::revolve_art(n) }; + let mut n = fill_square(18, vec![fx(three_d, json!({})), shadow(10.0, 10.0, 0.0)]); + let mut other = n.appearance.items[0].clone(); + *other.effects_mut() = vec![shadow(10.0, 10.0, 0.0)]; + n.appearance.items.push(other); + n.appearance.effects = vec![transform(json!({"scaleH": 200, "scaleV": 100}))]; + let drawn = shadows_in(&art(&n).unwrap()); + assert!(drawn.len() > 1 && near(&drawn, &vec![(20.0, 10.0); drawn.len()]), "{three_d}: {drawn:?}"); + } +} + #[test] fn glows_blurs_and_feathers_scale_with_the_transform_after_them() { let effects = [ @@ -419,3 +436,217 @@ fn expanded_and_exported_objects_keep_the_shadow_the_canvas_draws() { assert!(close(drawn_shadow(&b.appearance.effects), (20.0, 20.0, 8.0)), "{id}: {:?}", b.appearance.effects); } } + +/// A group of `members` with `effects` of its own. +fn group(id: u64, members: Vec, effects: Vec) -> Node { + let mut g = Node::group(NodeId(id), members.into_iter().map(std::sync::Arc::new).collect()); + g.appearance.effects = effects; + g +} + +/// The node with `id` under `n`. +fn node_in(n: &Node, id: u64) -> Node { + let mut found = None; + n.walk(&mut |m| { + if m.id == NodeId(id) && found.is_none() { + found = Some(m.clone()); + } + }); + found.unwrap_or_else(|| panic!("no node {id}")) +} + +/// The offset of the Drop Shadow that the first fill of `n` draws, its own effects and `n`'s +/// Transform effects applied ([`crate::item_effects_in`]). +fn fill_shadow(n: &Node) -> (f64, f64) { + let item = n.appearance.items.first().unwrap(); + match raster_effects(&crate::item_effects_in(&n.appearance.effects, item.effects())).first() { + Some(RasterFx::DropShadow { dx, dy, .. }) => (*dx, *dy), + other => panic!("expected a drop shadow, got {other:?}"), + } +} + +/// A group's Transform effect transforms the raster effects of what the group holds with the art, +/// whatever its options: a member's own shadow, a member's fill's shadow and a nested group's own +/// shadow, drawn (the group's art) and baked. +#[test] +fn a_groups_transform_moves_its_members_shadows() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 200}), (20.0, 20.0)), + (json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)), + (json!({"rotate": 90, "patterns": true}), (10.0, -10.0)), + (json!({"rotate": 90, "strokes": true}), (10.0, -10.0)), + ]; + for (params, want) in cases { + let members = vec![ + square(21, vec![shadow(10.0, 10.0, 0.0)]), + fill_square(22, vec![shadow(10.0, 10.0, 0.0)]), + group(23, vec![square(24, vec![])], vec![shadow(10.0, 10.0, 0.0)]), + ]; + let g = group(20, members, vec![transform(params.clone())]); + let art = crate::evaluate_container(None, &g).unwrap(); + assert!(near(&shadows_in(&art), &[want; 3]), "{params}: drawn {:?}", shadows_in(&art)); + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, g).unwrap(); + let baked = bake_document(&d).unwrap(); + for id in [21, 22, 23] { + let b = baked.node(NodeId(id)).unwrap(); + assert!(near(&shadows_in(b), &[want]), "{params}: {id} baked {:?}", shadows_in(b)); + } + } +} + +/// A group's Transform effect that makes copies or moves at random leaves its members' shadows as +/// they are, as it leaves the shadows listed before it in its own effects. +#[test] +fn a_groups_copying_transform_leaves_its_members_shadows() { + for params in [json!({"scaleH": 200, "scaleV": 200, "copies": 1}), json!({"scaleH": 200, "scaleV": 200, "random": true})] { + let g = group(25, vec![square(26, vec![shadow(10.0, 10.0, 0.0)]), square(27, vec![])], vec![transform(params.clone())]); + let art = crate::evaluate_container(None, &g).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![(10.0, 10.0); drawn.len()]), "{params}: {drawn:?}"); + } +} + +/// The Transform effects inside a group apply before the group's: a member's own turn of 90° +/// applies to its shadow before the group's uneven scale does, for the member's own shadow, its +/// fill's shadow, and the shadow of a member of a nested group that has the turn. +#[test] +fn a_groups_transform_applies_after_its_members_own() { + let turn = || transform(json!({"rotate": 90})); + let uneven = || transform(json!({"scaleH": 200, "scaleV": 100})); + // Turned first, (10, 0) goes to (0, -10), which the scale leaves; scaled first, it would be (0, -20). + let want = (0.0, -10.0); + let own = group(30, vec![square(31, vec![shadow(10.0, 0.0, 0.0), turn()])], vec![uneven()]); + let art = crate::evaluate_container(None, &own).unwrap(); + assert!(near(&shadows_in(&art), &[want]), "own: {:?}", shadows_in(&art)); + let mut on_fill = fill_square(33, vec![shadow(10.0, 0.0, 0.0)]); + on_fill.appearance.effects = vec![turn()]; + let art = crate::evaluate_container(None, &group(32, vec![on_fill], vec![uneven()])).unwrap(); + assert!(near(&[fill_shadow(&node_in(&art, 33))], &[want]), "fill: {:?}", fill_shadow(&node_in(&art, 33))); + let nested = group(34, vec![group(35, vec![square(36, vec![shadow(10.0, 0.0, 0.0)])], vec![turn()])], vec![uneven()]); + let art = crate::evaluate_container(None, &nested).unwrap(); + let inner = crate::evaluate_container(None, &node_in(&art, 35)).unwrap(); + assert!(near(&shadows_in(&inner), &[want]), "nested: {:?}", shadows_in(&inner)); +} + +/// An object's Transform effect transforms the raster effects of its fills and strokes with the +/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that +/// makes copies leaves them. +#[test] +fn an_objects_transform_moves_its_fills_shadows() { + let cases = [ + (json!({"scaleH": 200, "scaleV": 100}), (20.0, 10.0)), + (json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)), + (json!({"rotate": 90, "patterns": true}), (10.0, -10.0)), + (json!({"rotate": 90, "strokes": true}), (10.0, -10.0)), + (json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)), + ]; + for (params, want) in cases { + let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]); + n.appearance.effects = vec![transform(params.clone())]; + if crate::has_transform_art(&n) { + let art = crate::reshape(None, &n, None).unwrap(); + let drawn = shadows_in(&art); + assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: drawn {drawn:?}"); + } else { + assert!(near(&[fill_shadow(&n)], &[want]), "{params}: drawn {:?}", fill_shadow(&n)); + } + let mut d = Document::new(800.0, 800.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, n).unwrap(); + let baked = bake_document(&d).unwrap(); + let drawn = shadows_in(baked.node(NodeId(40)).unwrap()); + assert!(!drawn.is_empty() && near(&drawn, &vec![want; drawn.len()]), "{params}: baked {drawn:?}"); + } +} + +/// A 10 pt image at the origin with `effects`. +fn image(id: u64, effects: Vec) -> Node { + let mut n = Node::new( + NodeId(id), + vectorcraft_doc::NodeKind::Image(Box::new(vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: vectorcraft_geom::Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + n.appearance.effects = effects; + n +} + +/// A group's Transform effect transforms, with Scale Strokes & Effects off or on, the raster +/// effects that a member's own Transform effect with copies holds back: they keep their value +/// through the member's effect and transform with the group's. That holds for a shadow listed +/// before the member's copying effect, one listed after it, a fill's shadow under it, the shadow +/// of a member of a nested group with such an effect, and an image's shadow. +#[test] +fn a_groups_transform_moves_the_shadows_its_members_copies_hold_back() { + let copies = || transform(json!({"moveH": 60, "copies": 1})); + // Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5). + let want = (5.0, -5.0); + for strokes in [false, true] { + let mut on_fill = fill_square(73, vec![shadow(10.0, 10.0, 0.0)]); + on_fill.appearance.effects = vec![copies()]; + let members = vec![ + square(71, vec![shadow(10.0, 10.0, 0.0), copies()]), + square(72, vec![copies(), shadow(10.0, 10.0, 0.0)]), + on_fill, + group(74, vec![square(75, vec![shadow(10.0, 10.0, 0.0)])], vec![copies()]), + image(76, vec![shadow(10.0, 10.0, 0.0)]), + ]; + let g = group(70, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + for id in [71, 72, 73, 75, 76] { + let drawn = shadows_in(&node_in(&art, id)); + assert!(near(&drawn, &[want]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + } + } +} + +/// A group's Transform effect transforms the raster effects in the art of a member's linked opacity +/// mask with the member, a path's or an image's, with Scale Strokes & Effects off or on. +#[test] +fn a_groups_transform_moves_the_shadow_in_a_members_mask() { + let masked = |mut n: Node, id: u64| { + n.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(square(id, vec![shadow(10.0, 10.0, 0.0)]), true))); + n + }; + for strokes in [false, true] { + let params = json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}); + let g = group(80, vec![masked(square(81, vec![]), 82), masked(image(83, vec![]), 84)], vec![transform(params)]); + let art = crate::evaluate_container(None, &g).unwrap(); + for id in [81, 83] { + let member = node_in(&art, id); + let mask = member.extras().mask.as_deref().unwrap(); + assert!(near(&shadows_in(&mask.art), &[(5.0, -5.0)]), "Scale Strokes & Effects {strokes}: {id} {:?}", shadows_in(&mask.art)); + } + } +} + +/// A group's Transform effect transforms the shadows of its members' fills that carry a Transform +/// effect of their own with Scale Strokes & Effects on, with the group's Scale Strokes & Effects off +/// or on: a shadow listed after the fill's Transform effect keeps its value through that effect and +/// transforms with the group's, and one listed before it follows the fill's Transform effect and +/// then the group's. Drawn through each member's art. +#[test] +fn a_groups_transform_moves_its_members_fills_shadows_beside_their_own_transform() { + let scaled = || transform(json!({"scaleH": 200, "scaleV": 200, "strokes": true})); + // Halved and turned 90° counterclockwise on screen, (10, 10) goes to (5, -5); doubled first by + // the fill's own Transform effect, it goes to (10, -10). + let cases = [(91, vec![scaled(), shadow(10.0, 10.0, 0.0)], (5.0, -5.0)), (92, vec![shadow(10.0, 10.0, 0.0), scaled()], (10.0, -10.0))]; + for strokes in [false, true] { + let members = cases.iter().map(|(id, effects, _)| fill_square(*id, effects.clone())).collect(); + let g = group(90, members, vec![transform(json!({"scaleH": 50, "scaleV": 50, "rotate": 90, "strokes": strokes}))]); + let art = crate::evaluate_container(None, &g).unwrap(); + for (id, _, want) in &cases { + let member = node_in(&art, *id); + let drawn = shadows_in(&crate::reshape(None, &member, None).unwrap()); + assert!(!drawn.is_empty() && near(&drawn, &vec![*want; drawn.len()]), "Scale Strokes & Effects {strokes}: {id} {drawn:?}"); + } + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 509279a3ae..66eb2104d1 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -5,6 +5,7 @@ mod addons; mod apiref; pub(crate) mod appearance; pub mod arrowheads; +mod artboardalign; mod assets; mod attributes; pub mod brushlib; @@ -338,6 +339,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(variablecmds::specs()); v.extend(docinfo::specs()); v.extend(panelcmds::specs()); + v.extend(artboardalign::specs()); v.extend(buildcmds::specs()); v.extend(shaper::specs()); v.extend(brushsym::specs()); diff --git a/crates/engine/src/cmd/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs new file mode 100644 index 0000000000..9832133729 --- /dev/null +++ b/crates/engine/src/cmd/artboardalign.rs @@ -0,0 +1,262 @@ +//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool +//! is chosen. + +use serde_json::{Value, json}; +use vectorcraft_doc::Scaling; +use vectorcraft_geom::{Rect, Vec2}; + +use super::object::choice; +use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or}; +use crate::EngineError; + +pub fn specs() -> Vec { + vec![ + cmd!( + "artboard.align", + "Align", + [], + None, + "{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}", + has_doc, + align + ), + cmd!( + "artboard.distribute", + "Distribute", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute + ), + cmd!( + "artboard.distributeSpacing", + "Distribute Spacing", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute_spacing + ), + ] +} + +/// What an artboard Align or Distribute command acts on, read from its params. +struct Boards { + /// The artboards named, in artboard order, each with its rectangle. + items: Vec<(usize, Rect)>, + /// With `to: "artboard"`, the artboard to align to and its rectangle. + reference: Option<(usize, Rect)>, + /// Whether the art inside each artboard moves with it. + move_art: bool, + /// Whether locked and hidden art moves too. + locked_art: bool, +} + +/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing` +/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The +/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the +/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails +/// when every artboard named is locked. +fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { + check_switches(p, &["patterns"], cmd)?; + let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard"); + let indices = named_or_selected(s, p, cmd)?; + let given = |key: &str| -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some), + None => Ok(None), + } + }; + let (named, recorded) = (given("artboard")?, given("activeArtboard")?); + let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?; + let locked_art = locked_and_hidden(s, p, move_art, cmd)?; + note_artboards(s, p, &indices); + s.note_journal("moveArt", json!(move_art)); + let reference = match (to_artboard, named.or(recorded)) { + (false, _) => None, + (true, Some(i)) => Some(i), + (true, None) => { + let active = s.tool_options_of("artboard")["active"].clone(); + Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?) + } + }; + if let Some(i) = reference.filter(|_| named.is_none()) { + s.note_journal("activeArtboard", json!(i)); + } + let d = &s.doc()?.doc; + let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into())); + let items = indices.iter().map(|i| rect(*i)).collect::>>()?; + if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) { + return Err(EngineError::Other("the artboard is locked".into())); + } + Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art }) +} + +/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null. +fn spacing(p: &Value, cmd: &str) -> Result> { + p.get("spacing") + .filter(|v| !v.is_null()) + .map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number"))) + .transpose() +} + +/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it +/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error +/// (`no such artboard`), since the gap is measured from it. +fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option) -> Result> { + let Some((reference, _)) = b.reference else { return Ok(None) }; + match items.iter().position(|(i, _)| *i == reference) { + None if gap.is_some() => Err(EngineError::Other("no such artboard".into())), + at => Ok(at), + } +} + +/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when +/// `b` says so, the art inside it. Locked artboards stay where they are. When no artboard moves +/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit +/// fails with nothing changed when an artboard would end up past the canvas, as every edit does. +fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result { + let d = &s.doc()?.doc; + let moves: Vec<(usize, Vec2)> = + moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect(); + let moved: Vec = moves.iter().map(|(i, _)| *i).collect(); + if moves.is_empty() { + return Ok(json!({ "moved": moved })); + } + let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?; + let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; + s.edit(label, |d, _| { + for ((i, dv), (_, art)) in moves.iter().zip(&arts) { + let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + a.rect = a.rect + *dv; + let id = a.id; + d.move_artboard_guides(id, *dv); + for id in art { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*dv), sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + Ok(()) + })?; + Ok(json!({ "moved": moved })) +} + +fn align(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.align"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + if h.is_none() && v.is_none() { + return Err(bad(C, "give horizontal or vertical")); + } + let b = boards(s, p, C)?; + let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else { + return Ok(json!({ "moved": [] })); + }; + let moves: Vec<(usize, Vec2)> = b + .items + .iter() + .map(|(i, a)| { + let dx = match h { + Some("left") => r.x0 - a.x0, + Some("center") => r.center().x - a.center().x, + Some("right") => r.x1 - a.x1, + _ => 0.0, + }; + let dy = match v { + Some("top") => r.y0 - a.y0, + Some("center") => r.center().y - a.center().y, + Some("bottom") => r.y1 - a.y1, + _ => 0.0, + }; + (*i, Vec2::new(dx, dy)) + }) + .collect(); + apply(s, "Align", p, &b, &moves) +} + +fn distribute(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.distribute"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) { + (Some("left"), _) => (true, |r| r.x0), + (Some("right"), _) => (true, |r| r.x1), + (Some(_), _) => (true, |r| r.center().x), + (None, Some("top")) => (false, |r| r.y0), + (None, Some("bottom")) => (false, |r| r.y1), + (None, Some(_)) => (false, |r| r.center().y), + (None, None) => return Err(bad(C, "give horizontal or vertical")), + }; + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let mut items = b.items.clone(); + items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1))); + let kept = kept(&b, &items, gap)?; + // With a spacing: the place in the order and the line of the artboard it is measured from. + let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r)))); + let n = items.len(); + // Two artboards are the ends already; with a spacing the second is placed from the first. + if n < if from.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (first, last) = (line(first), line(last)); + let deltas: Vec = items + .iter() + .enumerate() + .map(|(k, (_, r))| { + let target = match from { + Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64), + None => first + (last - first) * k as f64 / (n - 1) as f64, + }; + target - line(r) + }) + .collect(); + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0); + let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect(); + apply(s, "Distribute", p, &b, &moves) +} + +fn distribute_spacing(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.distributeSpacing"; + let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical"); + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let start = |r: &Rect| if horiz { r.x0 } else { r.y0 }; + let size = |r: &Rect| if horiz { r.width() } else { r.height() }; + let mut items = b.items.clone(); + items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1))); + let kept = kept(&b, &items, gap)?; + let gap = gap.filter(|_| kept.is_some()); + let n = items.len(); + if n < if gap.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (lo, hi) = (start(first), start(last) + size(last)); + let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::()) / (n - 1) as f64); + let mut pos = lo; + let mut deltas = Vec::with_capacity(n); + for (i, r) in &items { + deltas.push((*i, pos - start(r))); + pos += size(r) + gap; + } + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1); + let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect(); + apply(s, "Distribute Spacing", p, &b, &moves) +} + +/// An offset of `d` along the axis: x when `horiz`, else y. +fn along(horiz: bool, d: f64) -> Vec2 { + if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/artboardalign/tests.rs b/crates/engine/src/cmd/artboardalign/tests.rs new file mode 100644 index 0000000000..94733b099e --- /dev/null +++ b/crates/engine/src/cmd/artboardalign/tests.rs @@ -0,0 +1,277 @@ +//! Align and Distribute for artboards. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; +use crate::tooling::ViewInfo; + +/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner: +/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids. +fn three_boards() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let ids = [sq(5, 5), sq(155, 45), sq(405, 15)]; + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +/// The top-left corner of each artboard. +fn corners(s: &Session) -> Vec<(f64, f64)> { + s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect() +} + +/// The top-left corner of object `id`. +fn corner(s: &Session, id: u64) -> (f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +const ALL: [u64; 3] = [0, 1, 2]; + +/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside +/// it, in one undo step. +#[test] +fn align_moves_the_artboards_to_their_common_edge_with_their_art() { + let (mut s, [a, b, c]) = three_boards(); + let before = corners(&s); + let steps = undo_steps(&s); + let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + assert_eq!(out, json!({"moved": [1, 2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]); + assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard"); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step"); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap(); + assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250"); + assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art"); +} + +/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not +/// be one of the artboards aligned. +#[test] +fn align_to_an_artboard_keeps_that_artboard_in_place() { + let (mut s, _) = three_boards(); + let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap(); + assert_eq!(out, json!({"moved": [0, 1]})); + assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap(); + assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80"); +} + +/// With no artboard named, the commands act on the artboards the Artboard tool has selected and +/// align to its active one; the journal records both for a replay, and an action leaves them out. +#[test] +fn the_artboard_tools_selection_is_the_default_and_is_recorded() { + let (mut s, [_, _, c]) = three_boards(); + s.select_tool("artboard", ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([1, 2])); + let start = s.journal.len(); + assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]); + assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on"); + let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false}); + assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded)); + assert_eq!( + s.journal_for_action(start), + [("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))] + ); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1"); + assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1)); + assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one"); + let action = s.journal_for_action(start); + let entry = &action.last().unwrap().1; + assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + s.set_tool_option("moveArt", &json!(false)); + s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays"); +} + +/// A command that moves no artboard leaves the document and its undo history as they are. +#[test] +fn nothing_to_move_records_no_undo_step() { + let (mut s, _) = three_boards(); + s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"indices": ALL, "vertical": "top"})), + ("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})), + ("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})), + ("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})), + ("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})), + ("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})), + ] { + assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}"); + } +} + +/// A locked artboard stays where it is and still counts in the bounds and in the order. When every +/// artboard named is locked, the command fails. +#[test] +fn a_locked_artboard_stays_where_it_is() { + let (mut s, _) = three_boards(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked"); + let out = + s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap(); + assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200"); + s.execute("edit.undo", &json!({})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})), + ("artboard.distribute", json!({"index": 1, "horizontal": "left"})), + ("artboard.distributeSpacing", json!({"indices": [1]})), + ] { + assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}"); + } +} + +/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards; +/// with a spacing and an artboard to align to, it places them that far apart from that artboard. +#[test] +fn distribute_spaces_the_edges_or_centers() { + let (mut s, [_, b, _]) = three_boards(); + assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450"); + assert_eq!(corner(&s, b), (225.0, 45.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100}); + assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place"); + s.execute("edit.undo", &json!({})).unwrap(); + let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150}); + assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]})); + assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place"); +} + +/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard +/// to align to, the gaps are that wide and that artboard stays. +#[test] +fn distribute_spacing_makes_the_gaps_equal() { + let (mut s, _) = three_boards(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap(); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20}); + assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap(); + assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place"); +} + +/// A value outside what a param takes is an error, and nothing changes. +#[test] +fn bad_params_are_errors() { + let (mut s, _) = three_boards(); + let (steps, before) = (undo_steps(&s), corners(&s)); + let with = |extra: Value| { + let mut p = json!({"indices": ALL, "horizontal": "left"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let shared = [ + json!({"horizontal": "middle"}), + json!({"horizontal": 1}), + json!({"to": "key"}), + json!({"to": "artboard", "artboard": 9}), + json!({"artboard": "1"}), + json!({"artboard": -1}), + json!({"moveArt": "yes"}), + json!({"patterns": 1}), + json!({"lockedAndHidden": "no"}), + json!({"indices": [9]}), + json!({"indices": []}), + json!({"indices": "0"}), + ]; + for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] { + let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) }; + for extra in &shared { + let mut p = with(axis.clone()); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() { + p = json!({"indices": ALL, "axis": extra["horizontal"]}); + } + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + } + for (id, p) in [ + ("artboard.align", json!({"indices": ALL})), + ("artboard.align", json!({"indices": ALL, "vertical": "middle"})), + ("artboard.distribute", json!({"indices": ALL})), + ("artboard.distribute", with(json!({"spacing": "10"}))), + ("artboard.distribute", with(json!({"spacing": true}))), + ("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})), + ("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + // Spacings that would put an artboard past the canvas, or overflow to infinity. + for (id, p) in [ + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))), + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})), + ] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("exceed the canvas"), "{id} {p}: {e}"); + } + assert_eq!((undo_steps(&s), corners(&s)), (steps, before)); +} + +/// An artboard's own guides move with it. +#[test] +fn an_artboards_guides_move_with_it() { + let (mut s, _) = three_boards(); + s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap(); + s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap(); + let d = &s.doc().unwrap().doc; + let positions: Vec = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1"); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 76b4e1a715..347968b2c5 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -208,7 +208,7 @@ pub fn specs() -> Vec { "Symbol Options…", [], None, - "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", + "{name?, newName?, registration?: 0..8, exportType?: movieClip|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static|dynamic} rename a symbol (its instances and the graphics mapped onto 3D objects follow the new name) and/or set Symbol Options › Registration, Export Type, 9-slice guides (nineSliceGuides [left, top, right, bottom] fractions 0..1) and Symbol Type (a dynamic symbol's instances may change the appearance of objects in its art and stay linked; making it static drops those changes); default name: current → {name, registration, exportType, nineSlice, type}", has_doc, symbol_options ), @@ -326,7 +326,7 @@ pub fn specs() -> Vec { "Select All Unused", [], None, - "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", + "{} → {names: [the symbols nothing places, in panel order]} (the Symbols panel selects them): instances in the art (opacity masks included), graphics mapped onto 3D objects (threeD.mapGraphic), graph designs, pattern tiles (with the tiles that pattern editing's Cancel puts back) and brush art count, and so do instances in the art of a symbol that is used", has_doc, symbol_unused ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index b789f600b4..edd2335f6a 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -115,6 +115,8 @@ fn art_symbols(n: &Node, out: &mut Vec) { if let NodeKind::SymbolInstance { symbol, .. } = &m.kind { out.push(symbol.clone()); } + // A graphic on a 3D object draws its symbol's art too. + out.extend(vectorcraft_render::effects::graphic_symbols(m)); }); } @@ -129,6 +131,8 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result { let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref())); let trees = d.layers.iter().map(|l| &**l).chain(d.graph_designs.iter().map(|g| &*g.art)); trees.chain(patterns.flat_map(|p| p.art.iter().map(|n| &**n))).chain(lib.iter().flat_map(|b| b.art())).for_each(|n| art_symbols(n, &mut todo)); + // A graphic in a graphic style draws its symbol's art wherever the style is applied. + todo.extend(d.graphic_styles.iter().flat_map(|g| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance))); let mut used = std::collections::BTreeSet::new(); while let Some(name) = todo.pop() { if !used.contains(&name) { @@ -290,6 +294,33 @@ pub(super) fn symbol_options(s: &mut Session, p: &Value) -> Result { *symbol = n.clone(); } } + // The graphics mapped onto 3D objects follow the new name: in the layers, the art of + // symbols, patterns, graph designs and brushes, their opacity masks, and graphic styles. + let patterns = d.patterns.iter_mut().chain(d.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut())); + let trees = d + .layers + .iter_mut() + .chain(d.symbols.iter_mut().map(|sym| &mut sym.art)) + .chain(d.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(patterns.flat_map(|p| p.art.iter_mut())); + for art in trees.filter(|art| vectorcraft_render::effects::names_graphic_symbol(art, &name)) { + vectorcraft_render::effects::rename_graphic_symbol_in(Arc::make_mut(art), &name, n); + } + let styled = |g: &vectorcraft_doc::GraphicStyle| vectorcraft_render::effects::appearance_graphic_symbols(&g.appearance).contains(&name); + if d.graphic_styles.iter().any(styled) { + for style in d.graphic_styles.iter_mut() { + vectorcraft_render::effects::rename_appearance_graphic_symbol(&mut style.appearance, &name, n); + } + } + // The brush library is stored again only when a brush's art changed. + let mut lib = brush::library(d); + let mut brushes = false; + for art in lib.iter_mut().flat_map(|b| b.art_mut()) { + brushes |= vectorcraft_render::effects::rename_graphic_symbol_in(art, &name, n); + } + if brushes { + brush::store(d, &lib); + } rename_natural_size(d, &name, n); d.rename_symbol_registration(&name, n); d.rename_symbol_export_type(&name, n); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index b1377d2fef..243c69f671 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -86,6 +86,10 @@ fn paint_refs(p: &Paint, f: Visit) { } fn appearance_refs(a: &Appearance, f: Visit) { + // The graphics mapped onto the faces of its 3D effects name symbols. + for s in vectorcraft_render::effects::appearance_graphic_symbols(a) { + f(Ref::Name(Res::Symbol, &s)); + } for it in &a.items { paint_refs(it.paint(), f); if let AppearanceItem::Stroke(l) = it @@ -620,6 +624,17 @@ impl Relink { } } } + // A 3D effect's mapped graphics follow their symbols' names in the document. Each name is + // looked up once, so renames that chain (A to B, B to C) do not apply twice. + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items).filter(|e| vectorcraft_render::effects::takes_graphics(&e.id)) { + let list = e.params.get_mut(vectorcraft_render::effects::GRAPHICS).and_then(Value::as_array_mut); + for g in list.into_iter().flatten() { + if let Some(Value::String(s)) = g.get_mut("symbol") { + self.name(Res::Symbol, s); + } + } + } for it in &mut a.items { self.paint(it.paint_mut()); if let AppearanceItem::Stroke(l) = it diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1046c4a948..18d4e26704 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -5,7 +5,9 @@ //! Colour settings and the proof view are process-wide (`vectorcraft_color::cms::active`, //! `vectorcraft_render::proof::view`). A document's assigned profiles are stored in //! `Document::color_profiles` (files before format v3: `Document.unknown["colorProfiles"]`) and -//! become active when assigned. +//! take the place of the working spaces in the active settings when assigned, and when the working +//! settings change while the document is in front ([`use_front_profiles`]); the working spaces stay +//! as Edit → Color Settings set them. use std::collections::BTreeMap; use std::sync::Arc; @@ -59,7 +61,7 @@ pub fn specs() -> Vec { "Assign Profile…", ["Edit"], None, - "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (colour numbers are kept) → {rgb, cmyk}", + "{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: the working space). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}", has_doc, assign_profile ), @@ -176,9 +178,19 @@ fn touch_all(s: &mut Session) { } } +/// Make the active settings the working settings with the profiles the front document is assigned +/// in place of the working spaces (none, or no document open: the working spaces). The open +/// documents redraw when the active settings change. +fn use_front_profiles(s: &mut Session) { + let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); + if cms::use_document_profiles(rgb.as_deref(), cmyk.as_deref()) { + touch_all(s); + } +} + fn color_settings(s: &mut Session, p: &Value) -> Result { const C: &str = "edit.colorSettings"; - let mut st = cms::active_settings(); + let mut st = cms::working_settings(); let before = st.clone(); if let Some(v) = text_param(p, "rgb", C)? { st.rgb = cms::canonical_name(v).to_string(); @@ -194,6 +206,7 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; // Saved for the next start when the app attached a settings file (#6335). s.store_color_settings(&st); + use_front_profiles(s); touch_all(s); } Ok(settings_json(&st)) @@ -208,14 +221,18 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { let info = cms::register_icc(&bytes, None).map_err(|e| bad(C, e.to_string()))?; // The bytes are kept, not the path: the file may move or go away. let remembered = s.store_profile(&info.name, &bytes); - // A new file of a working space: the active settings still hold the old one. - let working = cms::active_settings(); - let is_working = working.rgb == info.name || working.cmyk == info.name; - if is_working { + // A new file of a working space or of an assigned profile in use: the active settings still + // hold the old one. A profile the front document is assigned, loaded after it was removed, is + // in use again. + let (working, active) = (cms::working_settings(), cms::active_settings()); + let (rgb, cmyk) = s.active().map(|d| doc_profiles(&d.doc)).unwrap_or_default(); + let front = [rgb, cmyk].iter().any(|n| n.as_deref() == Some(info.name.as_str())); + if front || [&working.rgb, &working.cmyk, &active.rgb, &active.cmyk].contains(&&info.name) { cms::set_active(&working).map_err(|e| bad(C, e.to_string()))?; - } - // A new file of a working space, or of the CMYK profile View → Proof Setup targets: redraw. - if is_working || proof_targets(&info.name) { + use_front_profiles(s); + touch_all(s); + } else if proof_targets(&info.name) { + // A new file of the CMYK profile View → Proof Setup targets: redraw. touch_all(s); } Ok(json!({"name": info.name, "kind": info.kind, "remembered": remembered})) @@ -229,14 +246,21 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result { if info.builtin { return Err(bad(C, format!("`{name}` is a built-in profile and stays"))); } - let working = cms::active_settings(); + let working = cms::working_settings(); if working.rgb == name || working.cmyk == name { return Err(bad(C, format!("`{name}` is a working space: choose another with edit.colorSettings first"))); } + let active = cms::active_settings(); if !cms::unregister_icc(&info.name) { return Err(bad(C, format!("no profile named `{name}`"))); } s.unstore_profile(&info.name); + // An assigned profile in use: the working space takes its place, as for any document assigned + // a profile that is not available. + if active.rgb == name || active.cmyk == name { + use_front_profiles(s); + } + // The CMYK profile View → Proof Setup targets: redraw. if proof_targets(&info.name) { touch_all(s); } @@ -284,18 +308,9 @@ fn assign_profile(s: &mut Session, p: &Value) -> Result { d.color_profiles = profiles; Ok(()) })?; - let mut st = cms::active_settings(); - let before = st.clone(); - if let Some(r) = &rgb { - st.rgb = r.clone(); - } - if let Some(c) = &cmyk { - st.cmyk = c.clone(); - } - if st != before { - cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; - touch_all(s); - } + // The document draws through its profiles now, and a Document Color Mode later in the same + // batch converts through them. The working spaces stay as they are. + use_front_profiles(s); } Ok(json!({"rgb": rgb, "cmyk": cmyk})) } diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index ac79d0acc7..942b5a0087 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -629,14 +629,15 @@ fn info(s: &mut Session, p: &Value) -> Result { } let font_names: Vec = fonts.iter().map(super::fonts::font_label).collect(); // Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the last of two - // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. + // brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type + // as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them. let kinds: HashMap<&str, &vectorcraft_brush::BrushKind> = library.iter().map(|b| (b.name.as_str(), &b.kind)).collect(); let brush_entries: Vec = brushes.iter().map(|name| json!({ "name": name, "type": kinds.get(name.as_str()).map(|k| k.type_id()) })).collect(); let brush_rows: Vec<(String, String)> = brushes .iter() .map(|name| { - (name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} brush", k.label()))) + (name.clone(), kinds.get(name.as_str()).map_or_else(|| "missing from the Brushes panel".to_string(), |k| format!("{} Brush", k.label()))) }) .collect(); let mut out = json!({ @@ -805,10 +806,10 @@ mod tests { let i = brushes(&mut s, json!({"category": "brushes"})); assert_eq!(i["brushNames"], json!(["Charcoal", "Dots"])); assert_eq!(i["brushes"], json!([{"name": "Charcoal", "type": "art"}, {"name": "Dots", "type": "scatter"}])); - assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art brush"], ["Dots", "Scatter brush"]])); + assert_eq!(i["sections"][0]["rows"], json!([["Charcoal", "Art Brush"], ["Dots", "Scatter Brush"]])); assert!(panel.contains(&json!("3 pt. Round")) && i["panelBrushNames"] == json!(panel)); let text = brushes(&mut s, json!({"category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string(); - assert!(text.contains("\nBRUSHES\nCharcoal: Art brush\nDots: Scatter brush\n") && !text.contains("3 pt. Round"), "{text}"); + assert!(text.contains("\nBRUSHES\nCharcoal: Art Brush\nDots: Scatter Brush\n") && !text.contains("3 pt. Round"), "{text}"); assert!(!text.contains("OBJECTS"), "{text}"); // Selection Only: the brushes the selected objects' strokes use. let selected = |s: &mut Session| brushes(s, json!({"selectionOnly": true, "category": "brushes"})); @@ -818,10 +819,10 @@ mod tests { let i = selected(&mut s); assert_eq!( (i["brushes"].clone(), i["sections"][0]["rows"].clone()), - (json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter brush"]])) + (json!([{"name": "Dots", "type": "scatter"}]), json!([["Dots", "Scatter Brush"]])) ); let text = brushes(&mut s, json!({"selectionOnly": true, "category": "brushes", "format": "text"}))["text"].as_str().unwrap().to_string(); - assert!(text.contains("\nBRUSHES\nDots: Scatter brush\n") && !text.contains("Charcoal"), "{text}"); + assert!(text.contains("\nBRUSHES\nDots: Scatter Brush\n") && !text.contains("Charcoal"), "{text}"); // A stroke without a brush lists none. let plain = s.execute("shape.rectangle", &json!({"x": 60, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); s.execute("select.set", &json!({"ids": [plain]})).unwrap(); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 41949ddeb9..985d54fa50 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index b570ce332a..8040b0016c 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -34,8 +34,15 @@ fn svg_filter_name(s: &Session, xml: &str, cmd: &str) -> Result { Ok(name) } -/// The effect commands of the Effect menu and the Appearance panel. +/// The effect commands of the Effect menu and the Appearance panel, and the 3D and Materials +/// panel's Graphics. pub fn specs() -> Vec { + let mut specs = effect_specs(); + specs.extend(graphics::specs()); + specs +} + +fn effect_specs() -> Vec { vec![ cmd!( "effect.apply", @@ -454,6 +461,9 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; + if let Some(name) = effects::missing_symbol(d, &effect.params, None) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } if id == effects::REVOLVE && effects::has_revolve(n) { return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); } @@ -758,6 +768,9 @@ fn set_params(s: &mut Session, p: &Value) -> Result { if let (Some(cur), Value::Object(new)) = (prospective.as_object_mut(), effects::upgrade_params(to, ¶ms)) { cur.extend(new); } + if let Some(name) = effects::missing_symbol(d, &prospective, Some(&e.params)) { + return Err(bad(C, format!("no symbol named `{name}`"))); + } if visible != Some(false) { effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; } else { @@ -1201,6 +1214,8 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { Ok(out) } +mod graphics; + #[cfg(test)] mod lighting_presets_tests; diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs new file mode 100644 index 0000000000..1801c83492 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -0,0 +1,153 @@ +//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single +//! Graphic) and mapped onto the planar faces of 3D objects (Extrude & Bevel's caps, a plane). The +//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams` +//! also edits. + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{Effect, Node}; +use vectorcraft_render::effects; + +use super::super::appearance::{appearance_targets, index_param, item_target}; +use super::super::brushsym::{normalize, selection_art, store_symbol}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param}; +use super::{effect_targets, ids_json}; + +pub(super) fn specs() -> Vec { + vec![ + cmd!( + "threeD.addGraphic", + "Add as Single Graphic", + [], + None, + "{name?: string (default Graphic; made unique), ids?|id?} keep the selection's art as a new document symbol, listed among the 3D and Materials panel's Graphics; the selection stays as it is → {name}", + has_selection, + add_graphic + ), + cmd!( + "threeD.mapGraphic", + "Map Graphic", + [], + None, + "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane), scale?: % (1..10000; default 100, or less so the graphic fits inside the object), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it; every object's 3D effect must be Extrude & Bevel (on a solid cap) or Rotate (the Plane type); one undo step → {ids, graphic}", + has_doc, + map_graphic + ), + ] +} + +/// `threeD.addGraphic`: stores the selection's art as a symbol without replacing it with an +/// instance. +fn add_graphic(s: &mut Session, p: &Value) -> Result { + const C: &str = "threeD.addGraphic"; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !["name", "ids", "id"].contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + if p.get("name").is_some_and(|v| v.as_str().is_none_or(|n| n.trim().is_empty())) { + return Err(bad(C, "`name` must be a name that is not empty")); + } + let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); + let (art, size, _) = normalize(art)?; + let name = s.doc()?.doc.unique_symbol_name(str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Graphic")); + s.edit("Add as Single Graphic", |d, _| { + store_symbol(d, &art, &name, size); + Ok(()) + })?; + Ok(json!({ "name": name })) +} + +/// The 3D effect of `n` that a graphic goes on when none is named: its own first, then its fills' +/// and strokes', as the 3D and Materials panel finds it. +fn first_three_d(n: &Node) -> Option<(Option, usize)> { + let at = |fx: &[Effect]| fx.iter().position(|e| effects::is_three_d(&e.id)); + at(&n.appearance.effects) + .map(|i| (None, i)) + .or_else(|| n.appearance.items.iter().enumerate().find_map(|(k, item)| at(item.effects()).map(|i| (Some(k), i)))) +} + +/// `threeD.mapGraphic`: appends a graphic to the 3D effect of each target, after checking that every +/// target takes it. +fn map_graphic(s: &mut Session, p: &Value) -> Result { + const C: &str = "threeD.mapGraphic"; + const KEYS: [&str; 10] = ["symbol", "face", "x", "y", "scale", "rotation", "index", "item", "ids", "id"]; + if let Some(key) = p.as_object().and_then(|m| m.keys().find(|k| !KEYS.contains(&k.as_str()))) { + return Err(bad(C, format!("unknown parameter `{key}`"))); + } + // An item names where the effect is in that item's list, so it takes an index too. + if p.get("item").is_some() && p.get("index").is_none() { + return Err(bad(C, "`item` needs `index`")); + } + // The graphic's own settings, checked as the effect checks them. + let mut given = Map::new(); + for key in ["symbol", "face", "x", "y", "scale", "rotation"] { + if let Some(v) = p.get(key) { + given.insert(key.into(), v.clone()); + } + } + let base = effects::MappedGraphic::from_value(&Value::Object(given)).map_err(|e| bad(C, e))?; + let d = &s.doc()?.doc; + if !d.symbols.iter().any(|sym| sym.name == base.symbol) { + return Err(bad(C, format!("no symbol named `{}`", base.symbol))); + } + let targets: Vec<(NodeId, Option, usize)> = if p.get("index").is_some() { + let index = index_param(p, "index", C)?; + let item = item_target(s, p, C)?; + effect_targets(s, p, item, index, C)? + } else { + let mut out = vec![]; + for id in appearance_targets(s, p)? { + let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?; + out.push((id, item, index)); + } + out + }; + if targets.is_empty() { + return Err(bad(C, "select an object with a 3D effect")); + } + let mut edits = Vec::with_capacity(targets.len()); + for &(id, item, index) in &targets { + let n = d.node(id).ok_or(EngineError::NoNode(id))?; + let Some(effect) = n.appearance.effects_at(item).and_then(|fx| fx.get(index)).filter(|e| effects::is_three_d(&e.id)) else { + return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0))); + }; + if !effects::takes_graphics(&effect.id) { + return Err(bad(C, format!("object {}: Graphics map onto planar faces: use the Extrude or Plane object type", id.0))); + } + // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, + // but has no cap to show a new one on. + let merged = effects::merged_params(&effect.id, &effect.params); + let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); + if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); + } + // With a depth of 0 the art is a plane, which has only a front. + if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); + } + let mut graphic = base.clone(); + if p.get("scale").is_none() + && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + { + graphic.scale = frame.fitting_scale(art); + } + let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); + effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, item.map(|i| (i, index))).map_err(|e| bad(C, e))?; + edits.push((id, item, index, graphic)); + } + let first = edits.first().map(|(.., g)| g.to_value()); + let ids = s.edit("Map Graphic", |d, _| { + let mut done = vec![]; + for (id, item, index, graphic) in &edits { + let Some(e) = d.node_mut(*id).and_then(|n| n.appearance.effects_mut(*item)).and_then(|fx| fx.get_mut(*index)) else { continue }; + let current = effects::upgrade_params(&e.id, &e.params); + e.params = effects::with_graphic(¤t, graphic); + done.push(*id); + } + Ok(done) + })?; + Ok(json!({ "ids": ids_json(&ids), "graphic": first })) +} + +#[cfg(test)] +#[path = "graphics_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs new file mode 100644 index 0000000000..125ba82514 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -0,0 +1,289 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; + +/// A 100 × 100 square with `effect`, and a 10 × 20 red rectangle beside it kept as graphic "Mark". +fn setup(effect: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let mark = s.execute("path.create", &json!({"d":"M300 300L310 300L310 320L300 320Z"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"color":"#ff0000"})).unwrap(); + let made = s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [mark]})).unwrap(); + assert_eq!(made["name"], "Mark"); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{"rotationX":0.0,"rotationY":0.0,"rotationZ":0.0}})).unwrap(); + (s, id) +} + +fn graphics(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params["graphics"].clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +#[test] +fn add_as_single_graphic_keeps_the_art_and_makes_a_symbol() { + let (s, _) = setup("threeD.extrude"); + let d = &s.doc().unwrap().doc; + assert!(d.symbols.iter().any(|sym| sym.name == "Mark")); + // The art stays a plain path: no instance replaced it. + let mut instances = 0; + for l in &d.layers { + l.walk(&mut |n| instances += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::SymbolInstance { .. }))); + } + assert_eq!(instances, 0); + // The 10 × 20 rectangle and its 1 pt stroke. + assert_eq!(vectorcraft_render::effects::graphic_bounds(d, "Mark").map(|r| (r.width(), r.height())), Some((11.0, 21.0))); +} + +#[test] +fn map_graphic_adds_to_the_selected_object_in_one_undo_step_and_undoes() { + let (mut s, id) = setup("threeD.extrude"); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let r = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "x": 5.0, "rotation": 30.0})).unwrap(); + assert_eq!(r["ids"], json!([id.0])); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 5.0, "y": 0.0, "scale": 100.0, "rotation": 30.0}])); + assert_eq!(undo_len(&s), history + 1); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back"})).unwrap(); + assert_eq!(graphics(&s, id).as_array().unwrap().len(), 2); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.layers, before.layers); +} + +#[test] +fn a_large_graphic_starts_inside_its_object() { + let (mut s, id) = setup("threeD.rotate"); + let big = s.execute("path.create", &json!({"d":"M0 0L400 0L400 200L0 200Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Big", "ids": [big]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Big", "ids": [id.0]})).unwrap(); + // 401 pt wide with its stroke, in a 100 pt square. + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * 100.0 / 401.0).abs() < 1e-9, "{scale}"); +} + +#[test] +fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { + let (mut s, id) = setup("threeD.inflate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("Extrude or Plane"), "{e}"); + let (mut s, id) = setup("threeD.rotate"); + for (p, says) in [ + (json!({"symbol": "Gone"}), "no symbol named"), + (json!({"face": "front"}), "needs `symbol`"), + (json!({"symbol": "Mark", "face": "back"}), "one face"), + (json!({"symbol": "Mark", "scale": 0.0}), "scale"), + (json!({"symbol": "Mark", "tile": true}), "`tile`"), + (json!({"symbol": "Mark", "item": 0}), "`item` needs `index`"), + (json!({"symbol": "Mark", "item": null}), "`item` needs `index`"), + ] { + let mut p = p; + p["ids"] = json!([id.0]); + let e = s.execute("threeD.mapGraphic", &p).unwrap_err().to_string(); + assert!(e.contains(says), "{p}: {e}"); + } + assert_eq!(undo_len(&s), history); + // An object without a 3D effect. + let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone(); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [plain]})).unwrap_err().to_string(); + assert!(e.contains("3D effect"), "{e}"); + // A hollow Extrude & Bevel has no cap to show a new graphic on. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("turn on Cap"), "{e}"); + assert_eq!(undo_len(&s), history); + // With a depth of 0 there is no back. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": true, "depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); +} + +#[test] +fn set_params_edits_graphics_and_checks_them() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let moved = json!([{"symbol": "Mark", "face": "front", "x": -12.0, "y": 8.0, "scale": 150.0, "rotation": 0.0}]); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": moved}})).unwrap(); + assert_eq!(graphics(&s, id), moved); + let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": [{"symbol": "Mark", "face": "top"}]}}); + assert!(s.execute("effect.setParams", &bad).is_err()); + let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}}); + assert!(s.execute("effect.setParams", &null).is_err()); + assert_eq!(graphics(&s, id), moved); + // Extrude to Plane keeps the graphics; to Inflate drops them. + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap(); + assert_eq!(graphics(&s, id), moved); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap(); + assert_eq!(graphics(&s, id), Value::Null); +} + +#[test] +fn effect_commands_refuse_an_unknown_symbol_but_keep_a_deleted_ones_graphic() { + let (mut s, id) = setup("threeD.extrude"); + let unknown = json!([{"symbol": "Nowhere"}]); + let history = undo_len(&s); + assert!(s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": unknown}})).is_err()); + s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap(); + let created = undo_len(&s); + assert!(s.execute("effect.apply", &json!({"effect": "threeD.extrude", "item": null, "params": {"graphics": unknown}})).is_err()); + assert_eq!((history + 1, undo_len(&s)), (created, created)); + // A graphic whose symbol was deleted stays while the effect's other settings change. + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).symbols.retain(|sym| sym.name != "Mark"); + s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"depth": 30.0}})).unwrap(); + assert_eq!(graphics(&s, id)[0]["symbol"], "Mark"); +} + +#[test] +fn a_symbol_a_graphic_uses_is_used_and_follows_a_rename() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let unused = s.execute("symbol.unused", &json!({})).unwrap(); + assert!(!unused["names"].as_array().unwrap().iter().any(|n| n == "Mark"), "{unused}"); + // A 3D object with the graphic kept in another symbol's art follows the rename too. + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + s.execute("symbol.new", &json!({"name": "Holder"})).unwrap(); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap(); + assert_eq!(graphics(&s, id)[0]["symbol"], "Label"); + let d = &s.doc().unwrap().doc; + let holder = d.symbols.iter().find(|sym| sym.name == "Holder").unwrap(); + let mut held = vec![]; + holder.art.walk(&mut |n| held.extend(vectorcraft_render::effects::graphic_symbols(n))); + assert_eq!(held, vec!["Label".to_string()]); +} + +#[test] +fn a_rename_reaches_graphics_in_graph_designs_and_opacity_masks() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let held = d.node(id).unwrap().clone(); + d.graph_designs.push(vectorcraft_doc::GraphDesign { name: "Bars".into(), art: std::sync::Arc::new(held.clone()) }); + d.graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", (*held.appearance).clone())); + let mut lib = vectorcraft_brush::library(d); + let scatter = lib.iter_mut().find(|b| !b.art().is_empty()).unwrap(); + *scatter.art_mut()[0] = held.clone(); + vectorcraft_brush::store(d, &lib); + d.node_mut(id).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(held, true))); + s.execute("symbol.options", &json!({"name": "Mark", "newName": "Label"})).unwrap(); + let d = &s.doc().unwrap().doc; + let style = d.graphic_styles.iter().find(|g| g.name == "Boxed").unwrap(); + assert_eq!(vectorcraft_render::effects::appearance_graphic_symbols(&style.appearance), vec!["Label".to_string()]); + let brush: Vec = + vectorcraft_brush::library(d).iter().flat_map(|b| b.art()).flat_map(vectorcraft_render::effects::graphic_symbols).collect(); + assert_eq!(brush, vec!["Label".to_string()]); + let names = |n: &vectorcraft_doc::Node| { + let mut out = vec![]; + n.walk(&mut |c| out.extend(vectorcraft_render::effects::graphic_symbols(c))); + out + }; + assert_eq!(names(&d.graph_designs[0].art), vec!["Label".to_string()]); + let mask = d.node(id).unwrap().extras().mask.as_deref().map(|m| names(&m.art)); + assert_eq!(mask, Some(vec!["Label".to_string()])); +} + +#[test] +fn pasted_into_another_document_a_graphic_brings_its_symbol() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // The symbol the pasted object's graphic names, and the size of that symbol's art. + let pasted = |s: &mut Session| { + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let n = st.doc.node(st.selection.objects[0]).unwrap(); + let name = n.appearance.effects[0].params["graphics"][0]["symbol"].as_str().unwrap().to_string(); + let size = vectorcraft_render::effects::graphic_bounds(&st.doc, &name).map(|r| (r.width(), r.height())); + (name, size) + }; + // A document without the symbol gets it. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + assert_eq!(pasted(&mut s), ("Mark".to_string(), Some((11.0, 21.0)))); + // A document whose symbol "Mark" is other art gets the copied symbol under a free name. + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let other = s.execute("path.create", &json!({"d":"M0 0L50 0L50 50L0 50Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [other]})).unwrap(); + let (name, size) = pasted(&mut s); + assert_ne!(name, "Mark"); + assert_eq!(size, Some((11.0, 21.0))); +} + +#[test] +fn a_symbol_only_a_graphic_style_uses_is_used() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let appearance = (*s.doc().unwrap().doc.node(id).unwrap().appearance).clone(); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"graphics": []}})).unwrap(); + let unused = |s: &mut Session| s.execute("symbol.unused", &json!({})).unwrap()["names"].clone(); + assert!(unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).graphic_styles.push(vectorcraft_doc::GraphicStyle::new("Boxed", appearance)); + assert!(!unused(&mut s).as_array().unwrap().iter().any(|n| n == "Mark")); +} + +#[test] +fn add_graphic_refuses_bad_parameters_and_changes_nothing() { + let (mut s, _) = setup("threeD.extrude"); + let art = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].clone(); + let (symbols, history) = (s.doc().unwrap().doc.symbols.len(), undo_len(&s)); + for p in [ + json!({"name": 5, "ids": [art]}), + json!({"name": null, "ids": [art]}), + json!({"name": "", "ids": [art]}), + json!({"name": " ", "ids": [art]}), + json!({"tile": true, "ids": [art]}), + ] { + assert!(s.execute("threeD.addGraphic", &p).is_err(), "{p}"); + } + assert_eq!((s.doc().unwrap().doc.symbols.len(), undo_len(&s)), (symbols, history)); +} + +#[test] +fn map_graphic_refuses_a_selection_with_an_object_without_a_3d_effect() { + let (mut s, id) = setup("threeD.extrude"); + let plain = s.execute("path.create", &json!({"d":"M0 0L10 0L10 10Z"})).unwrap()["id"].as_u64().unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0, plain]})).unwrap_err().to_string(); + assert!(e.contains(&format!("object {plain} needs a 3D effect")), "{e}"); + assert_eq!(undo_len(&s), history); + assert_eq!(graphics(&s, id).as_array().map_or(0, Vec::len), 0); +} + +#[test] +fn the_graphic_is_drawn_on_the_object() { + let (mut s, id) = setup("threeD.extrude"); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()).unwrap(); + let mut red = None; + art.walk(&mut |n| { + if let (Some(p), Some(vectorcraft_doc::AppearanceItem::Fill(f))) = (n.path_data(), n.appearance.items.first()) + && f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) + { + red = p.bounds(); + } + }); + // Seen straight on, the 10 × 20 graphic sits at the center of the square. + let r = red.unwrap(); + assert!( + (r.center().x - 150.0).abs() < 1e-6 + && (r.center().y - 150.0).abs() < 1e-6 + && (r.width() - 10.0).abs() < 1e-6 + && (r.height() - 20.0).abs() < 1e-6, + "{r:?}" + ); +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 6d4bcd54d9..40b8e26060 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -588,7 +588,9 @@ fn expand_piece_leaves( /// Path `l` as the canvas paints its fills and strokes: its visible geometry effects applied to its /// path (a plain path then), and every geometry effect of its own removed, with each raster effect /// following the Transform effects after it -/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)). `None` when it has no +/// ([`without_geometry`](vectorcraft_render::effects::without_geometry)) and those of its fills and +/// strokes following its Transform effects +/// ([`follow_items`](vectorcraft_render::effects::follow_items)). `None` when it has no /// visible geometry effect. The swatches and patterns that live-effect plug-ins painting their /// pieces name are looked up in `doc`. This merges the pieces of such a plug-in into one path, so a /// path that one paints goes through [`expand_pieces`] instead. @@ -604,6 +606,8 @@ pub(crate) fn reshaped(doc: &Document, l: &Node) -> Option { if carry.moves(&m.appearance) { carry.apply(&mut m.appearance); } + // So do the raster effects of its fills and strokes. + vectorcraft_render::effects::follow_items(&mut m); m.appearance.effects = without_geometry(&m.appearance.effects); Some(m) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 58c7974460..f4aaa841ca 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -1,10 +1,21 @@ //! File → New: the settings `file.new` takes, the New Document presets (generated in code, by //! category), the user's saved presets and the recently used sizes (both kept in the //! preferences), and the artboard grid layout shared with Rearrange All Artboards. +//! +//! New Document profiles: each built-in category has a profile, a native document in the +//! `New Document Profiles` folder next to the preferences ([`Session::attach_new_doc_profiles`]). +//! `file.new` starts a document of that category with the profile's swatches, graphic styles, +//! brushes, symbols, character and paragraph styles, rulers, document setup and print settings +//! ([`DocSettings::document_from_profile`]). The grid stays that of Preferences › Guides & Grid, +//! which applies to every open document. A category without a profile file starts with the +//! defaults, and a profile that can't be read leaves them in place and is reported in `file.new`'s +//! result. + +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; @@ -38,6 +49,33 @@ pub fn specs() -> Vec { |s| if s.prefs.new_doc_presets.is_empty() { Err("no saved presets".into()) } else { Ok(()) }, delete ), + cmd!( + query "file.newProfiles", + "New Document Profiles", + [], + None, + "{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}", + always, + list_profiles + ), + cmd!( + "file.newProfiles.edit", + "Edit Profile", + [], + None, + "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result", + always, + edit_profile + ), + cmd!( + "file.newProfiles.reset", + "Reset Profile", + [], + None, + "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}", + always, + reset_profile + ), ] } @@ -148,6 +186,11 @@ pub struct DocSettings { /// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from /// before it. pub align_new_objects_to_pixel_grid: bool, + /// The New Document profile the document starts from (a built-in category's name): the + /// category of a built-in preset, kept by the saved and Recent presets made from it; `None`: + /// the defaults. + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, } impl Default for DocSettings { @@ -168,6 +211,7 @@ impl Default for DocSettings { raster_effects_ppi: 72.0, preview_mode: PreviewMode::Default, align_new_objects_to_pixel_grid: false, + profile: None, } } } @@ -217,6 +261,7 @@ impl DocSettings { "rasterEffectsPpi": self.raster_effects_ppi, "previewMode": self.preview_mode.id(), "alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid, + "profile": self.profile, }) } @@ -280,6 +325,11 @@ impl DocSettings { self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?; } self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?; + match p.get("profile") { + None => {} + Some(Value::Null) => self.profile = None, + Some(v) => self.profile = Some(profile_name(v, cmd)?.to_string()), + } let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r)); if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD { return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size")); @@ -357,6 +407,101 @@ impl DocSettings { .collect(); d } + + /// The new document started from New Document profile `profile`: [`Self::document`] with the + /// profile's swatches, swatch groups, graphic styles, brushes, symbols, patterns and the images + /// they use, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler + /// origin and mode, transparency grid, document setup (bleed, background and Align New Objects + /// to Pixel Grid stay these settings'), assigned color profiles, raster effects settings (the + /// resolution stays these settings') and print settings, in these settings' color mode (the + /// profile's colors converted as Document Color Mode converts them). The profile's art, + /// layers and artboards are left out: the document has one empty layer. + pub fn document_from_profile(&self, mut profile: Document) -> Document { + if profile.color_mode != self.color_mode { + super::colormgmt::set_color_mode(&mut profile, self.color_mode, true, None, super::colormgmt::Grays::Profile); + } + let profile_next_id = profile.peek_next_id(); + let mut d = self.document(); + d.swatches = profile.swatches; + d.swatch_groups = profile.swatch_groups; + d.graphic_styles = profile.graphic_styles; + d.char_styles = profile.char_styles; + d.para_styles = profile.para_styles; + d.composite_fonts = profile.composite_fonts; + d.symbols = profile.symbols; + d.graph_designs = profile.graph_designs; + d.patterns = profile.patterns; + d.images = profile.images; + d.svg_filters = profile.svg_filters; + d.spot_use_lab = profile.spot_use_lab; + d.ruler_origin = profile.ruler_origin; + d.rulers = profile.rulers; + d.artboard_ruler_origins = profile.artboard_ruler_origins.into_iter().filter(|(id, _)| d.artboards.iter().any(|a| a.id == *id)).collect(); + d.transparency_grid = profile.transparency_grid; + d.print_setup = profile.print_setup; + d.color_profiles = profile.color_profiles; + // The resolution stays the preset's (raster_effects_ppi); the other raster effects settings + // are the profile's. + d.raster_effects = profile.raster_effects; + let setup = std::mem::replace(&mut d.setup, profile.setup); + d.setup.bleed = setup.bleed; + d.setup.background = setup.background; + d.setup.align_new_objects_to_pixel_grid = setup.align_new_objects_to_pixel_grid; + if let Some(brushes) = profile.unknown.get("brushes") { + d.unknown.insert("brushes".into(), brushes.clone()); + } + // Symbol, pattern and graph design art keeps the profile's ids, which a damaged file can + // have above its counter: the counter goes past all of them, as it does for a loaded + // document's layers, before the new layer takes an id. + d.raise_next_id(profile_next_id); + d.layers = d + .symbols + .iter() + .map(|s| s.art.clone()) + .chain(d.graph_designs.iter().map(|g| g.art.clone())) + .chain(d.patterns.iter().flat_map(|p| p.art.iter().cloned())) + .collect(); + d.fix_next_id(); + let layer = d.alloc_id(); + d.layers = vec![Arc::new(Node::layer(layer, "Layer 1", LayerColor::Preset(0)))]; + // Images only the profile's art used stay behind: an image is kept when an object of the new + // document names it in its `key`, as a native save keeps only the images its objects name. + let images = std::mem::take(&mut d.images); + if !images.is_empty() { + d.images = match serde_json::to_value(&d) { + Ok(v) => { + let used = image_keys(&v); + images.into_iter().filter(|(k, _)| used.contains(k.as_str())).collect() + } + Err(_) => images, + }; + } + d + } +} + +/// The string values of every `key` member at any depth of `v`, which name the images a document's +/// objects use, collected in one pass. +fn image_keys(v: &Value) -> std::collections::HashSet<&str> { + let mut keys = std::collections::HashSet::new(); + let mut stack = vec![v]; + while let Some(v) = stack.pop() { + match v { + Value::Object(m) => { + for (k, v) in m { + match v.as_str() { + Some(s) if k == "key" => { + keys.insert(s); + } + _ => stack.push(v), + } + } + } + Value::Array(a) => stack.extend(a), + _ => {} + } + } + keys } /// Largest artboard side `file.new` and `artboard.new` accept, points: the span of the canvas @@ -594,6 +739,7 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator + ' color_mode, raster_effects_ppi: ppi, align_new_objects_to_pixel_grid: align, + profile: Some(category.into()), ..DocSettings::default() }) } @@ -644,7 +790,18 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } - let mut d = settings.document(); + let (profile, profile_error) = match settings.profile.as_deref() { + Some(name) => match s.read_profile(name) { + Ok(p) => (p, None), + Err(e) => (None, Some(e)), + }, + None => (None, None), + }; + let applied = profile.is_some(); + let mut d = match profile { + Some(p) => settings.document_from_profile(p), + None => settings.document(), + }; d.grid = s.prefs.grid(); d.title = match str_param(p, "name").or(str_param(p, "title")).map(str::trim).filter(|t| !t.is_empty()) { // New Document offers the next untitled name: taking it uses it up. @@ -660,7 +817,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { s.execute("view.overprintPreview", &json!({ "on": true }))?; } remember(s, &settings); - Ok(json!({ "index": i, "previewMode": settings.preview_mode.id() })) + let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() }); + if applied { + out["profile"] = json!(settings.profile); + } + if let Some(e) = profile_error { + out["profileError"] = json!({ "profile": settings.profile, "reason": e }); + } + Ok(out) } /// Put `settings` first in Recent (one entry per size and units). @@ -714,3 +878,136 @@ fn delete(s: &mut Session, p: &Value) -> Result { let i = saved.iter().position(|q| q.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(C, format!("no saved preset called `{name}`")))?; Ok(json!({ "deleted": saved.remove(i).name })) } + +/// The largest New Document profile file `file.new` reads, bytes (VectorCraft's own limit); a +/// larger one is reported and the document starts with the defaults. +pub const MAX_PROFILE_BYTES: u64 = 64 << 20; + +/// The New Document profiles' names: the built-in categories, in tab order. +pub fn profile_names() -> impl Iterator { + CATEGORIES.iter().map(|c| c.0) +} + +/// The profile `v` names (a built-in category, any case). +fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> { + let name = v.as_str().map(str::trim).unwrap_or_default(); + profile_names().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| { + let shown = v.as_str().map_or_else(|| v.to_string(), str::to_string); + bad(cmd, format!("no New Document profile called `{shown}` ({})", profile_names().collect::>().join(", "))) + }) +} + +impl Session { + /// Keep the New Document profiles in the folder `dir` (`New Document Profiles` next to the + /// preferences). The folder is made when a profile is first edited. + pub fn attach_new_doc_profiles(&mut self, dir: std::path::PathBuf) { + self.new_doc_profile_dir = Some(dir); + } + + /// The New Document profiles' folder ([`Session::attach_new_doc_profiles`]); none on the web. + pub fn new_doc_profile_dir(&self) -> Option<&std::path::Path> { + self.new_doc_profile_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// The file of profile `name`, whether or not it exists. + fn profile_path(&self, name: &str) -> Option { + Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION))) + } + + /// Whether profile `name` has a file, which `file.newProfiles.reset` deletes. + pub fn new_doc_profile_customized(&self, name: &str) -> bool { + self.profile_path(name).is_some_and(|p| p.is_file()) + } + + /// Profile `name`'s document: `None` when it has no file (the shipped profile, the defaults), + /// the reason when the request being served may not read it, or its file can't be read, is + /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + fn read_profile(&self, name: &str) -> std::result::Result, String> { + let Some(path) = self.profile_path(name) else { return Ok(None) }; + // Checked before the file is looked for, so a request that may not read the folder learns + // nothing of its files. + crate::file_access::check_read(&path.to_string_lossy())?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&path.to_string_lossy())?; + let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let mut doc = vectorcraft_format::load(&bytes).map_err(|e| e.to_string())?; + // Linked images in its symbols, patterns and brushes are read from their files, as placing + // a document reads them. + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&path.to_string_lossy())), false, false); + Ok(Some(doc)) + } +} + +/// The shipped profile of category `name`: the defaults, as a document of the category's first +/// preset. +fn shipped_profile(s: &Session, name: &str) -> Document { + let first = CATEGORIES.iter().find(|c| c.0 == name).and_then(|c| builtin(c, s.default_units()).next()); + let mut d = first.unwrap_or_default().document(); + d.title = name.to_string(); + d +} + +/// `path` when the request being served may read it. +fn shown(path: &std::path::Path) -> Option { + let path = path.to_string_lossy().to_string(); + crate::file_access::check_read(&path).is_ok().then_some(path) +} + +fn list_profiles(s: &mut Session, _: &Value) -> Result { + let profiles: Vec = profile_names() + .map(|name| { + let mut v = json!({ "name": name }); + match s.profile_path(name) { + // A request that may not read the folder learns nothing of its files. + Some(path) => { + if let Some(p) = shown(&path) { + v["customized"] = json!(path.is_file()); + v["path"] = json!(p); + } + } + None => v["customized"] = json!(false), + } + v + }) + .collect(); + Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) })) +} + +/// The file of profile `name` for `cmd` to change, checked against the request's write access. +fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result { + let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?; + crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?; + Ok(path) +} + +fn edit_profile(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.edit"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + // document.open reads it next: a profile it can't open is not written either. + crate::file_access::check_read(&path).map_err(super::EngineError::Other)?; + if !file.exists() { + let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); + file.parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::write(&file, bytes)) + .map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?; + } + s.execute("document.open", &json!({ "path": path })) +} + +fn reset_profile(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.reset"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + let reset = match std::fs::remove_file(&file) { + Ok(()) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))), + }; + Ok(json!({ "name": name, "reset": reset })) +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index d541e8c05d..9b37bfaa6f 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -122,7 +122,7 @@ pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Res /// Add `selectedArtboards` to the running command's journal entry when `p` names no artboard, so a /// replay acts on the artboards the Artboard tool had selected. An action leaves it out /// (`REPLAY_ONLY`) and keeps an `index` or `indices` the call gave. -fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { +pub(crate) fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { if p.get("index").is_none() && p.get("indices").is_none() { s.note_journal("selectedArtboards", json!(indices)); } @@ -130,7 +130,7 @@ fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { /// The artboards `cmd` acts on: `index` or `indices`, else `selectedArtboards` (a replay of the /// journal), else those the Artboard tool has selected, else its active one. -fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result> { +pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result> { let t = s.tool_options_of("artboard"); let d = &s.doc()?.doc; if p.get("index").is_some() || p.get("indices").is_some() { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index f25dfd4a35..0f5ada29fe 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -86,9 +86,12 @@ pub(super) const ALLOWED: &[&str] = &[ "appearance.showAllHidden", "appearance.targetContents", "appearance.transfer", + "artboard.align", "artboard.convertToArtboards", "artboard.delete", "artboard.deleteEmpty", + "artboard.distribute", + "artboard.distributeSpacing", "artboard.duplicate", "artboard.fitToArt", "artboard.fitToSelection", @@ -624,6 +627,8 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.releaseSelection", "text.thread.remove", "text.touchType", + "threeD.addGraphic", + "threeD.mapGraphic", "transparency.disableOpacityMask", "transparency.editOpacityMask", "transparency.enableOpacityMask", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index c9de286514..a17fbaf3f8 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -28,7 +28,7 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 29] = [ +const REPLAY_ONLY: [(&str, &str); 35] = [ ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -50,6 +50,12 @@ const REPLAY_ONLY: [(&str, &str); 29] = [ ("artboard.cut", "selectedArtboards"), ("artboard.rename", "selectedArtboards"), ("artboard.switchOrientation", "selectedArtboards"), + ("artboard.align", "selectedArtboards"), + ("artboard.align", "activeArtboard"), + ("artboard.distribute", "selectedArtboards"), + ("artboard.distribute", "activeArtboard"), + ("artboard.distributeSpacing", "selectedArtboards"), + ("artboard.distributeSpacing", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b211c3d727..a891fb9599 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -176,6 +176,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, + /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). + new_doc_profile_dir: Option, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1eed4a083c..3e9ae56423 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -89,6 +89,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index d2e5f1b115..247a037e45 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -512,3 +512,173 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(s.execute("artboard.rearrange", &p).unwrap(), json!({"artboards": 0, "rows": 1, "columns": 1})); assert_eq!(history(&s), before); } + +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). +fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + (s, dir) +} + +fn swatch_names(s: &Session) -> Vec { + s.doc().unwrap().doc.swatches.iter().map(|w| w.name.clone()).collect() +} + +/// Edit the Print profile: Brand Red, the Brand Box style, the Badge and Logo symbols (Logo's art an +/// embedded image) and an image left on its layer, saved. +fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { + // Edit writes the shipped profile and opens it. + s.execute("file.newProfiles.edit", &json!({"name": "print"})).unwrap(); + assert!(dir.join("Print.vectorcraft").is_file()); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + s.execute("swatch.new", &json!({"name": "Brand Red", "color": "#cc2200"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Brand Box"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Badge"})).unwrap(); + // One embedded image becomes a symbol's art, another stays on the profile's layer. + let png = |rgb: [u8; 3]| { + let mut out = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + vectorcraft_format::base64_encode(&out) + }; + s.execute("file.place", &json!({"name": "red.png", "dataBase64": png([255, 0, 0]), "link": false})).unwrap(); + s.execute("symbol.new", &json!({"name": "Logo"})).unwrap(); + s.execute("file.place", &json!({"name": "blue.png", "dataBase64": png([0, 0, 255]), "link": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.images.len(), 2); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(s.execute("file.newProfiles", &json!({})).unwrap()["profiles"][2]["customized"], true); +} + +#[test] +fn an_edited_profile_starts_the_documents_of_its_category() { + let (mut s, dir) = with_profiles("edited"); + let listed = s.execute("file.newProfiles", &json!({})).unwrap(); + let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p["customized"] == false), "{listed}"); + edit_print_profile(&mut s, &dir); + + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert_eq!(r["profile"], "Print", "{r}"); + assert!(swatch_names(&s).contains(&"Brand Red".to_string())); + let d = &s.doc().unwrap().doc; + assert!(d.graphic_styles.iter().any(|g| g.name == "Brand Box")); + let badge = d.symbols.iter().find(|y| y.name == "Badge").expect("the profile's symbol"); + assert!(d.symbols.iter().any(|y| y.name == "Logo")); + assert_eq!(d.images.len(), 1, "only the symbol's image comes along"); + // The profile's art stays behind: one empty layer, with an id the symbol's art doesn't use. + assert_eq!(d.layers.len(), 1); + assert!(d.layers[0].children().is_none_or(Vec::is_empty)); + let mut symbol_ids = vec![]; + badge.art.walk(&mut |n| symbol_ids.push(n.id)); + assert!(!symbol_ids.contains(&d.layers[0].id), "{symbol_ids:?}"); + assert_eq!(d.artboards[0].rect.width().round(), 595.0); + let red = d.swatches.iter().find(|w| w.name == "Brand Red").cloned().unwrap(); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }), "{:?}", red.paint); + // In RGB the profile's colors are converted, as Document Color Mode converts them. + s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); + let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_profile_follows_the_preset_access_and_reset() { + let (mut s, dir) = with_profiles("choice"); + edit_print_profile(&mut s, &dir); + // A request that may not read the folder gets the defaults, and the reason; edit is refused + // before anything is written. + let elsewhere = dir.with_extension("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "A4"}))).unwrap(); + assert!(r.get("profile").is_none() && r["profileError"]["profile"] == "Print", "{r}"); + assert!(!swatch_names(&s).contains(&"Brand Red".to_string())); + // Nothing tells such a request which profiles have files. + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "Web 1920×1080"}))).unwrap(); + assert_eq!(r["profileError"]["profile"], "Web", "{r}"); + let listed = crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles", &json!({}))).unwrap(); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p.get("customized").is_none() && p.get("path").is_none()), "{listed}"); + assert!(crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles.edit", &json!({"name": "Web"}))).is_err()); + assert!(!dir.join("Web.vectorcraft").exists()); + let _ = std::fs::remove_dir_all(&elsewhere); + // A saved preset made from a Print preset keeps the profile. + s.execute("file.newPresets.save", &json!({"name": "Zine", "preset": "A5"})).unwrap(); + assert_eq!(presets(&mut s, "Saved")[0]["profile"], "Print"); + assert_eq!(s.execute("file.new", &json!({"preset": "Zine"})).unwrap()["profile"], "Print"); + + // Other categories, no preset and `profile: null` start with the defaults. + for p in [json!({"preset": "Web 1920×1080"}), json!({}), json!({"preset": "A4", "profile": null})] { + let r = s.execute("file.new", &p).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{p}: {r}"); + } + // `profile` picks one for any settings. + assert_eq!(s.execute("file.new", &json!({"width": 300, "height": 300, "profile": "PRINT"})).unwrap()["profile"], "Print"); + + // Reset deletes the file, once; the shipped profile applies again. + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": true})); + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { + let (mut s, dir) = with_profiles("damaged"); + s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); + let defaults = swatch_names(&s); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + assert!(!r["profileError"]["reason"].as_str().unwrap_or("").is_empty(), "{r}"); + assert!(r.get("profile").is_none()); + assert_eq!(swatch_names(&s), defaults); + // Past the limit the file is not read at all (a sparse file of that length). + let big = std::fs::File::create(dir.join("Web.vectorcraft")).unwrap(); + big.set_len(crate::cmd::newdoc::MAX_PROFILE_BYTES + 1).unwrap(); + drop(big); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn profile_names_are_checked_and_editing_needs_the_folder() { + let mut s = Session::new(); + for p in [json!({"profile": "Posters"}), json!({"profile": 5}), json!({"profile": ""})] { + let e = s.execute("file.new", &p).unwrap_err().to_string(); + assert!(e.contains("no New Document profile called") && e.contains("Film & Video"), "{p}: {e}"); + } + assert!(s.execute("file.newProfiles.edit", &json!({"name": "Posters"})).is_err()); + for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] { + let e = s.execute(cmd, &json!({"name": "Print"})).unwrap_err().to_string(); + assert!(e.contains("preferences folder"), "{cmd}: {e}"); + } + // Without a folder every profile is the shipped one and documents start with the defaults. + let r = s.execute("file.newProfiles", &json!({})).unwrap(); + assert!(r["folder"].is_null() && r["profiles"][0].get("path").is_none(), "{r}"); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && r.get("profileError").is_none(), "{r}"); +} + +#[test] +fn the_new_layer_takes_an_id_no_profile_art_has() { + // A damaged profile whose symbol art has the id the new layer would otherwise take. + let settings = crate::cmd::newdoc::DocSettings::default(); + let mut profile = settings.document(); + let next = settings.document().peek_next_id().max(profile.peek_next_id()); + let art = std::sync::Arc::new(vectorcraft_doc::Node::group(vectorcraft_doc::NodeId(next), vec![])); + profile.symbols.push(vectorcraft_doc::Symbol { name: "Badge".into(), art, dynamic: false }); + let d = settings.document_from_profile(profile); + assert_eq!(d.layers.len(), 1); + assert_ne!(d.layers[0].id, vectorcraft_doc::NodeId(next)); + // Ids given out later skip the symbol's art too. + assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next); +} diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index 07589a2f4a..38918cf2c4 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -212,6 +212,51 @@ fn a_shadow_before_a_transform_expands_as_the_canvas_draws_it() { } } +/// The object's Transform effect scales and turns the drop shadow of its gradient fill on the +/// canvas; Object › Expand of the fill keeps the shadow the canvas drew. +#[test] +fn a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it() { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(80.0, 80.0, 120.0, 120.0), white_black(), false); + for (effect, params, item) in [ + ("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}), json!(0)), + ("distort.transform", json!({"scaleH": 200, "scaleV": 100, "rotate": 90}), json!(null)), + ] { + run(&mut s, "effect.apply", json!({"effect": effect, "params": params, "ids": [id.0], "item": item})); + } + let before = render(&s); + run(&mut s, "object.expand", json!({"object": false, "stroke": false, "steps": 64})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "{diff} pixels differ"); +} + +/// A group's Transform effect scales and turns its member's drop shadow on the canvas, and an +/// object's scales and turns its fill's, with Scale Strokes & Effects off or on; Expand Appearance +/// keeps the shadows the canvas drew. +#[test] +fn shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them() { + let shadow = json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}); + for strokes in [false, true] { + let transform = json!({"scaleH": 200, "scaleV": 100, "rotate": 90, "strokes": strokes}); + for group in [false, true] { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(80.0, 80.0, 120.0, 120.0), white_black(), false); + let item = if group { json!(null) } else { json!(0) }; + run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "ids": [id.0], "item": item})); + if group { + run(&mut s, "object.group", json!({})); + } + run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": transform})); + let before = render(&s); + run(&mut s, "effect.expandAppearance", json!({})); + let after = render(&s); + let diff = differing(&before, &after, 64); + assert_eq!(diff, 0, "group {group}, Scale Strokes & Effects {strokes}: {diff} pixels differ"); + } + } +} + #[test] fn a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it() { // The object's own effect, and the fill's (the first appearance item). diff --git a/crates/engine/src/tests/outlinestroke.rs b/crates/engine/src/tests/outlinestroke.rs index a92ca10416..16b57a628c 100644 --- a/crates/engine/src/tests/outlinestroke.rs +++ b/crates/engine/src/tests/outlinestroke.rs @@ -332,6 +332,30 @@ fn a_shadow_before_a_transform_outlines_as_the_canvas_draws_it() { } } +/// The object's Transform effect turns and scales the drop shadow of its stroke (brushed or not) +/// on the canvas; outlining the stroke keeps the shadow the canvas drew. +#[test] +fn a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it() { + for brush in [false, true] { + for (command, p) in outlining().into_iter().filter(|(command, _)| !(brush && *command == "object.flattenTransparency")) { + let mut s = session(); + square_with( + &mut s, + json!({"color": "#ff0000"}), + json!(1), + &[("stylize.dropShadow", json!({"x": 10, "y": 0, "blur": 0, "opacity": 100}))], + ); + s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"scaleH": 50, "scaleV": 100, "rotate": 90}})).unwrap(); + if brush { + s.execute("brush.apply", &json!({"name": "Tapered Stroke"})).unwrap(); + } + let before = render(&s); + outlined_by(&mut s, command, &p); + assert_eq!(differing(&before, &render(&s), 64), 0, "{command}, brush {brush}"); + } + } +} + /// The brush art of a brushed stroke with a geometry effect follows the path the effect makes. #[test] fn a_brush_draws_along_the_path_the_stroke_effects_make() { diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index c3d6df771b..6c7e90a188 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -75,6 +75,140 @@ fn assigning_another_profile_replaces_the_active_color_settings() { cms::set_active(&before).unwrap(); } +/// Assign Profile tags the document and leaves the working spaces: Color Settings shows the +/// working spaces, a later change to it saves them and not the assigned profile, and taking the +/// profile off the document brings the working spaces back. +#[test] +fn assign_profile_leaves_the_working_spaces() { + let _g = settings(); + let dir = fresh_dir("assign-profile"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + let mut s = session(); + s.attach_color_settings(file.clone()); + let working = cms::working_settings(); + assert_ne!(working.cmyk, cms::DEVICE_CMYK); + exec(&mut s, "edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document draws through its profile"); + assert_eq!(cms::working_settings(), working); + assert!(!file.exists(), "Assign Profile saves no Color Settings"); + let r = exec(&mut s, "edit.colorSettings", json!({})); + assert_eq!(r["cmyk"], working.cmyk.as_str(), "Color Settings shows the working CMYK space"); + exec(&mut s, "edit.colorSettings", json!({"intent": "perceptual"})); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!((saved.cmyk.as_str(), saved.intent), (working.cmyk.as_str(), cms::Intent::Perceptual)); + assert_eq!(cms::active_settings().cmyk, cms::DEVICE_CMYK, "the document still draws through its profile"); + exec(&mut s, "edit.assignProfile", json!({"cmyk": null})); + assert_eq!(cms::active_settings(), cms::working_settings(), "no profile: the working spaces"); +} + +/// A loaded profile that is assigned but is not a working space can be removed: the working space +/// takes its place in the active settings, and the working spaces stay as they are. +#[test] +fn removing_an_assigned_profile_puts_the_working_space_back() { + const NAME: &str = "Assigned CMYK"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some(NAME.into())).unwrap(); + let mut s = session(); + let working = cms::working_settings(); + exec(&mut s, "edit.assignProfile", json!({"cmyk": NAME})); + assert_eq!(cms::active_settings().cmyk, NAME); + let revision = s.doc().unwrap().revision; + let r = exec(&mut s, "color.removeProfile", json!({"name": NAME})); + assert_eq!(r["removed"], NAME); + assert_eq!(cms::active_settings(), working, "the working CMYK space is in use again"); + assert_eq!(cms::working_settings(), working); + assert!(s.doc().unwrap().revision > revision, "the canvas redraws"); +} + +/// Loading the file of an assigned profile in use again keeps it in use, loading it after it was +/// removed puts it back in use, and the working spaces stay as they are. +#[test] +fn loading_an_assigned_profile_again_keeps_it_in_use() { + const NAME: &str = "Assigned P"; + let _g = settings(); + let dir = fresh_dir("reload-assigned"); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![dir.clone()] }; + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("assigned.icc"); + std::fs::write(&path, icc_named(NAME)).unwrap(); + let mut s = session(); + let working = cms::working_settings(); + let load = |s: &mut Session| assert_eq!(exec(s, "color.loadProfile", json!({"path": path.to_str().unwrap()}))["name"], NAME); + load(&mut s); + exec(&mut s, "edit.assignProfile", json!({"rgb": NAME})); + let before = cms::active(); + load(&mut s); + assert_eq!(cms::active_settings().rgb, NAME, "the assigned profile stays in use"); + assert!(!std::sync::Arc::ptr_eq(&before, &cms::active()), "the new file is in use"); + exec(&mut s, "color.removeProfile", json!({"name": NAME})); + assert_eq!(cms::active_settings(), working); + load(&mut s); + assert_eq!(cms::active_settings().rgb, NAME, "loaded again, the assigned profile is in use"); + assert_eq!(cms::working_settings(), working); +} + +/// A batch that assigns a profile and then changes the color mode, as Document Setup's OK does, +/// converts the colors through the profile it assigns. +#[test] +fn a_batch_converts_through_the_profile_it_assigns() { + let _g = settings(); + let _reset = ColorSettingsReset { profile: None, paths: vec![] }; + let blue = |s: &mut Session| { + let id = rect(s, 10.0, 10.0, 50.0, 50.0); + exec(s, "paint.setFill", json!({"ids": [id.0], "color": "#3366cc"})); + id + }; + let fill = |s: &Session, id| s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color(); + let mut working = session(); + let w = blue(&mut working); + exec(&mut working, "file.documentColorMode", json!({"mode": "cmyk"})); + let mut tagged = session(); + let a = blue(&mut tagged); + let steps = json!([ + {"command": "edit.assignProfile", "params": {"cmyk": cms::DEVICE_CMYK}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + ]); + exec(&mut tagged, "command.batch", json!({"commands": steps})); + let converted = fill(&tagged, a); + assert_ne!(converted, fill(&working, w), "converted through the working CMYK space"); + let mut device = session(); + let b = blue(&mut device); + exec(&mut device, "edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})); + exec(&mut device, "file.documentColorMode", json!({"mode": "cmyk"})); + assert_eq!(converted, fill(&device, b)); +} + +/// View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in a +/// document assigned another CMYK profile, in Proof Colors and in Separations Preview, and a change +/// of the working CMYK space shows in the next proof while the document keeps its profile. +#[test] +fn working_cmyk_proofs_a_tagged_document_through_the_working_space() { + const NAME: &str = "Tagged CMYK"; + let _g = settings(); + let _reset = ColorSettingsReset { profile: Some(NAME), paths: vec![] }; + cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some(NAME.into())).unwrap(); + let proof = cms::ProofSetup::default(); + assert_eq!(proof.target, cms::ProofTarget::WorkingCmyk); + let (blue, inks) = ([0.2, 0.4, 0.8], [0.6, 0.3, 0.0, 0.1]); + let mut s = session(); + exec(&mut s, "edit.assignProfile", json!({"cmyk": NAME})); + let (active, working) = (cms::active(), cms::working()); + assert_eq!(active.settings().cmyk, NAME); + assert_eq!(active.proof_srgb(blue, &proof), working.proof_srgb(blue, &proof), "Proof Colors"); + assert_eq!(active.proof_cmyk_to_srgb(inks, &proof), working.proof_cmyk_to_srgb(inks, &proof), "Separations Preview"); + let _ = active.proof_lut(&proof); + exec(&mut s, "edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})); + let (active, working) = (cms::active(), cms::working()); + assert_eq!(active.settings().cmyk, NAME, "the document keeps its profile"); + let lut = active.proof_lut(&proof); + let fresh = cms::ProofLut::build(|rgb| working.proof_srgb(rgb, &proof)); + for px in [[51, 102, 204], [230, 30, 30], [20, 160, 40], [128, 128, 128]] { + assert_eq!(lut.apply8(px), fresh.apply8(px), "the proof of {px:?} through the new working CMYK space"); + } +} + /// Separations Preview follows the Color Settings and the profiles loaded: a renderer draws a gray /// square on the Black plate through the new working CMYK profile, and the four process plates /// through a proof profile loaded again under the same name, as a new renderer draws them. diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index ccf66c9b21..43d93cec25 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7126,6 +7126,81 @@ fn a_linked_object_past_the_object_limit_warns_that_its_link_is_left_out() { } } +/// A link to a graphic style with Twist is kept where the reader reads Twist: on a curve, a curved +/// compound path or a group with nothing stroked up to a quarter turn, and on a path with straight +/// segments at any angle. A stroked curve, a group with a stroked member or a guide, or a curve, +/// compound path or group twisted further, is written without the link and warns. +#[test] +fn a_link_to_a_twist_style_is_kept_where_the_reader_reads_it() { + // A document with the object `make` builds from its appearance, `ap` with Twist at `angle`, + // linked to a graphic style of that appearance. + fn twisted(angle: f64, ap: Appearance, make: impl FnOnce(&mut Document, Appearance) -> Node) -> Document { + let mut doc = Document::new(200.0, 100.0); + let ap = Appearance { effects: vec![fx("distort.twist", serde_json::json!({"angle": angle}))], ..ap }; + let mut g = vectorcraft_doc::GraphicStyle::new("Twisted", ap.clone()); + g.id = 9; + doc.graphic_styles.push(g); + let mut n = make(&mut doc, ap); + n.extras_mut().graphic_style = Some(9); + put(&mut doc, n); + doc + } + let oval = || shapes::ellipse(Rect::new(10.0, 10.0, 90.0, 60.0)); + let square = || shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 60.0)); + let red = solid(Color::rgb(1.0, 0.0, 0.0)); + let filled = || Appearance::basic(black_fill(), Paint::None, 0.0); + let path = |p: PathData| move |doc: &mut Document, ap: Appearance| Node::path(doc.alloc_id(), p, ap); + let ring = |doc: &mut Document, ap: Appearance| { + let outer = Node::path(doc.alloc_id(), oval(), Appearance::default()); + let inner = Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(30.0, 20.0, 70.0, 50.0)), Appearance::default()); + let mut n = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::NonZero }); + n.appearance = ap.into(); + n + }; + // A group of a filled square and `second`. + let group = |second: fn(&mut Document) -> Node| { + move |doc: &mut Document, ap: Appearance| { + let first = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 40.0, 40.0)), filled()); + let second = second(doc); + let mut n = Node::group(doc.alloc_id(), vec![Arc::new(first), Arc::new(second)]); + n.appearance = ap.into(); + n + } + }; + let curve = |doc: &mut Document| { + Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(50.0, 10.0, 90.0, 60.0)), Appearance::basic(black_fill(), Paint::None, 0.0)) + }; + let stroked_curve = |doc: &mut Document| { + let ap = Appearance::basic(black_fill(), solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + Node::path(doc.alloc_id(), shapes::ellipse(Rect::new(50.0, 10.0, 90.0, 60.0)), ap) + }; + let guide = |doc: &mut Document| { + let path = shapes::rectangle(Rect::new(50.0, 10.0, 90.0, 60.0)); + Node::new(doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: false, guide: true }) + }; + for (what, doc, kept) in [ + ("a twisted curve", twisted(45.0, filled(), path(oval())), true), + ("a curve twisted a quarter turn back", twisted(-90.0, filled(), path(oval())), true), + ("a square twisted three quarters of a turn", twisted(270.0, filled(), path(square())), true), + ("a curve twisted past a quarter turn", twisted(120.0, filled(), path(oval())), false), + ("a stroked curve", twisted(45.0, Appearance::basic(black_fill(), red.clone(), 2.0), path(oval())), false), + ("a curved compound path", twisted(-60.0, filled(), ring), true), + ("a curved compound path twisted past a quarter turn", twisted(120.0, filled(), ring), false), + ("a twisted group", twisted(90.0, Appearance::default(), group(curve)), true), + ("a group twisted past a quarter turn", twisted(135.0, Appearance::default(), group(curve)), false), + ("a group with a stroked member", twisted(45.0, Appearance::default(), group(stroked_curve)), false), + ("a group with a guide", twisted(45.0, Appearance::default(), group(guide)), false), + ] { + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings.iter().any(|w| w == writer::STYLE_LINKS), !kept, "{what}: {:?}", out.warnings); + let back = read_back(&doc); + let n = &back.layers[0].children().unwrap()[0]; + let style = n.extras().graphic_style.and_then(|id| back.graphic_style_by_id(id)).map(|g| g.name.as_str()); + assert_eq!(style, kept.then_some("Twisted"), "{what}: {n:?}"); + assert_eq!(n.appearance.effects.iter().any(|e| e.id == "distort.twist"), kept, "{what}: {n:?}"); + } +} + /// Twist and Transform on an object that isn't linked to a graphic style are not written as a style /// of its own: the object reads back without live effects. #[test] diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 3a93af7419..bc58858b91 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1067,7 +1067,8 @@ fn strokes(n: &Node, depth: usize) -> bool { || n.children().into_iter().flatten().any(|c| strokes(c, depth + 1)) } -/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? +/// Are all of path or compound path `n`'s segments straight, each anchor's handles on it? Any other +/// object, a group included, counts as no. fn straight(n: &Node) -> bool { match &n.kind { NodeKind::Path { path, .. } => path.subpaths.iter().flat_map(|s| &s.anchors).all(|a| a.h_in == a.p && a.h_out == a.p), @@ -1076,10 +1077,21 @@ fn straight(n: &Node) -> bool { } } +/// Is neither `n` nor anything in it a guide? Deeper than [`MAX_DEPTH`] counts as no. +fn no_guides(n: &Node, depth: usize) -> bool { + depth <= MAX_DEPTH && !n.is_guide() && n.children().into_iter().flatten().all(|c| no_guides(c, depth + 1)) +} + +/// The largest Twist angle, in degrees either way, read as a live effect on an object that isn't a +/// path or compound path with straight segments: VectorCraft's own limit. An object with a larger +/// Twist keeps the file's drawn look. +const MAX_TWIST: f64 = 90.0; + /// Is `object` one that style `st`, whose effect moves the outline, is read on? It and everything -/// in it [`moves_alike`], and the style paints no gradient. Twist is read only on an unstroked path -/// or compound path with straight segments, and Transform that scales, turns or reflects only when -/// nothing is stroked (its reference point lies on the bounds without strokes). +/// in it [`moves_alike`], and the style paints no gradient. Twist is read only when nothing is +/// stroked: on a path or compound path with straight segments at any angle, or up to [`MAX_TWIST`] +/// degrees either way on another object with no guide in it. Transform that scales, turns or reflects +/// is read only when nothing is stroked (its reference point lies on the bounds without strokes). fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { use crate::import::ai::style::StyleItem; let stroked = st.items.iter().any(|i| matches!(i, StyleItem::Stroke { paint, .. } if !paint.is_none())) @@ -1088,7 +1100,9 @@ fn moves_with(object: &Node, st: &crate::import::ai::style::ArtStyle) -> bool { && outlines_only(object) && object.children().into_iter().flatten().all(|c| moves_alike(c, 1)) && st.effects.iter().all(|e| match e.id.as_str() { - "distort.twist" => !stroked && matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && straight(object), + "distort.twist" => { + !stroked && (straight(object) || (no_guides(object, 0) && e.params["angle"].as_f64().is_some_and(|a| a.abs() <= MAX_TWIST))) + } "distort.transform" => { let p = &e.params; !stroked diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 8fa0a58346..c6a6041212 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -7092,13 +7092,12 @@ fn with_red_stroke(styles: &str) -> String { #[test] fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { - // GUARDS: Twist was read on curves, strokes and groups, and Transform scaling a stroked object, - // where the outline VectorCraft draws hasn't been checked. + // GUARDS: Twist was read on strokes, and Transform scaling a stroked object, where the outline + // VectorCraft draws hasn't been checked. let object = |hidden: &str| { format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}f\n%_0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) }; let square = object(&rect_path(20.0, 20.0, 60.0, 50.0)); - let curved = object("20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"); let twist = distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", BLUE_FILL); let scale = "0.5 /Real (scaleH_Factor) ,\n0 /Bool (scaleLines) ,\n0 /Bool (transformPatterns) ,\n"; let corner = distort_styles("Adobe Transform", &format!("0 /Int (pinPoint) ,\n{scale}"), BLUE_FILL); @@ -7106,9 +7105,7 @@ fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { let moved = distort_styles("Adobe Transform", "0 /Int (pinPoint) ,\n5 /Real (moveH_Pts) ,\n0 /Bool (transformPatterns) ,\n", BLUE_FILL); let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); for (what, r) in [ - ("a twisted curve", read(&twist, &curved)), ("a twisted stroke", read(&with_red_stroke(&twist), &square)), - ("a twisted group", read(&distort_styles("Adobe Twirl", "45 /Real (angle) ,\n", None), &distort_group())), ("a stroke scaled from a corner", read(&with_red_stroke(&corner), &square)), ("a stroke scaled from the center", read(&with_red_stroke(¢er), &square)), ] { @@ -7133,6 +7130,67 @@ fn twist_and_a_scaling_transform_are_read_only_where_their_outline_is_known() { assert_eq!((e.id.as_str(), e.params["angle"].as_f64()), ("distort.twist", Some(45.0))); } +#[test] +fn twist_is_read_on_curves_compound_paths_and_groups_with_nothing_stroked_up_to_a_quarter_turn() { + // GUARDS: Twist was read only on paths and compound paths with straight segments. + // The object, `hidden` painted with its style, under its drawn look. + let object = |hidden: &str| { + format!("0 Ae\nu\n{RED}{}f\nU\n%_Bb\n%_{}0 BB\n1 (Bent) XW\n", rect_path(16.0, 16.0, 64.0, 54.0), hidden.replace('\n', "\n%_")) + }; + let square = object(&format!("{}f\n", rect_path(20.0, 20.0, 60.0, 50.0))); + let oval = "20 35 m\n20 45 60 45 60 35 c\n60 25 20 25 20 35 c\n"; + let curved = object(&format!("{oval}f\n")); + let ring = object(&format!("*u\n{oval}f\n30 35 m\n30 40 50 40 50 35 c\n50 30 30 30 30 35 c\nf\n*U\n")); + let twist = |angle: f64, paint| distort_styles("Adobe Twirl", &format!("{angle} /Real (angle) ,\n"), paint); + let read = |styles: &str, art_: &str| read_ok(&format!("{styles}{}", layer(art_))); + // The first member of a group, and a second one. + let group = |second: &str| { + let member = |s: String| s.replace('\n', "\n%_"); + format!( + "0 Ae\nu\n{RED}{}f\nU\n%_0 Ae\n%_u\n%_{}{}U\n1 (Bent) XW\n", + rect_path(-1.0, -1.0, 16.0, 11.0), + member(format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))), + member(second.to_string()) + ) + }; + let hidden_member = group(&format!("1 Xw\n{RED}{}f\n0 Xw\n", rect_path(5.0, 0.0, 15.0, 10.0))); + // A compound path, its first subpath `first` and a guide. + let with_guide = |first: &str| object(&format!("*u\n{first}f\n5 0 m\n15 10 L\n(N) *\n*U\n")); + for (what, r, members) in [ + ("a twisted curve", read(&twist(45.0, BLUE_FILL), &curved), 0), + ("a curved compound path", read(&twist(-60.0, BLUE_FILL), &ring), 2), + ("a twisted group", read(&twist(90.0, None), &distort_group()), 2), + ("a group with a hidden member", read(&twist(45.0, None), &hidden_member), 2), + ("a curve twisted a quarter turn back", read(&twist(-90.0, BLUE_FILL), &curved), 0), + ("a square twisted three quarters of a turn, as before", read(&twist(270.0, BLUE_FILL), &square), 0), + ("a straight compound path with a guide, as before", read(&twist(45.0, BLUE_FILL), &with_guide(&rect_path(20.0, 20.0, 60.0, 50.0))), 2), + ] { + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert_eq!(a[0].children().map_or(0, |c| c.len()), members, "{what}: the object, not its look: {a:#?}"); + let [e] = a[0].appearance.effects.as_slice() else { panic!("{what}: {:?}", a[0].appearance) }; + assert_eq!(e.id, "distort.twist", "{what}"); + } + // A group with a stroked member or a guide, a curved compound path with a guide, and curves and + // groups twisted past a quarter turn, keep the drawn look. + let stroked_member = group(&format!("0 1 1 0 1 0 0 XA\n2 w\n{}S\n", rect_path(5.0, 0.0, 15.0, 10.0))); + let guide_member = group("5 0 m\n15 10 L\n(N) *\n"); + for (what, r) in [ + ("a group with a stroked member", read(&twist(45.0, None), &stroked_member)), + ("a group with a guide", read(&twist(45.0, None), &guide_member)), + ("a curved compound path with a guide", read(&twist(45.0, BLUE_FILL), &with_guide(oval))), + ("a curve twisted past a quarter turn", read(&twist(91.0, BLUE_FILL), &curved)), + ("a curve twisted half a turn back", read(&twist(-180.0, BLUE_FILL), &curved)), + ("a group twisted past a quarter turn", read(&twist(135.0, None), &distort_group())), + ] { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{what}: {a:#?}"); + assert!(a[0].appearance.effects.is_empty(), "{what}: the drawn look: {a:#?}"); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{what}: {:?}", r.warnings); + } +} + #[test] fn a_bare_comment_line_in_a_prolog_leaves_its_end_alone() { // GUARDS: a bare `%` line's empty marker matched the empty begin marker of a section that has none. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 5c137347c0..14c11c1932 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,91 +261,91 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.horizontalLeft", "Horizontal Align Left", "", - "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalCenter", "Horizontal Align Center", "", - "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalRight", "Horizontal Align Right", "", - "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalVerticalCenter", "Horizontal & Vertical Align Center", "", - "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalTop", "Vertical Align Top", "", - "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalCenter", "Vertical Align Center", "", - "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalBottom", "Vertical Align Bottom", "", - "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalTop", "Vertical Distribute Top", "", - "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalCenter", "Vertical Distribute Center", "", - "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalBottom", "Vertical Distribute Bottom", "", - "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalLeft", "Horizontal Distribute Left", "", - "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalCenter", "Horizontal Distribute Center", "", - "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalRight", "Horizontal Distribute Right", "", - "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalSpace", "Vertical Distribute Space", "", - "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalSpace", "Horizontal Distribute Space", "", - "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "type.bold", diff --git a/crates/pathops/src/offset.rs b/crates/pathops/src/offset.rs index bf533476be..f9579f1bf3 100644 --- a/crates/pathops/src/offset.rs +++ b/crates/pathops/src/offset.rs @@ -126,21 +126,49 @@ fn path_is_finite(path: &PathData) -> bool { /// Fallible [`offset_path`] that returns an error when the input is non-finite or exceeds /// the complexity bound ([`MAX_OFFSET_SEGMENT_PAIRS`]), or when planar arrangement fails. pub fn try_offset_path(path: &PathData, delta: f64, join: Join, miter_limit: f64) -> Result { - let src = std::cell::LazyCell::new(|| SegmentTree::new(boxed_segments(&path.to_bezpath()))); - offset_with_check(path, delta, join, miter_limit, |p, r| any_within(&src, p, r)) + offset_with_check(path, delta, join, miter_limit, |part| { + let bp = part.to_bezpath(); + let src = std::cell::LazyCell::new(move || SegmentTree::new(boxed_segments(&bp))); + move |p, r| any_within(&src, p, r) + }) } -/// [`try_offset_path`] with the test of whether some segment of `path` lies closer than a radius to a point. -fn offset_with_check( +/// [`try_offset_path`] with `within_of(part)`, the test of whether some segment of `part` lies +/// closer than a radius to a point. +fn offset_with_check bool>( + path: &PathData, + delta: f64, + join: Join, + miter_limit: f64, + within_of: impl Fn(&PathData) -> W, +) -> Result { + if !delta.is_finite() || !path_is_finite(path) { + return Err(PathOpsError::NonFinite); + } + // An inset keeps only faces inside the closed fill, so it would drop the outline of every + // open subpath (#6427). Inset the closed subpaths, outline the open ones as a positive offset + // does, and unite the two. + if delta < 0.0 && path.subpaths.iter().any(|s| s.anchors.len() > 1 && !close_if_ends_meet(s).closed) { + let (closed, open): (Vec, Vec) = path.subpaths.iter().cloned().partition(|s| close_if_ends_meet(s).closed); + let (closed, open) = (PathData::new(closed), PathData::new(open)); + let inset = offset_region(&closed, delta, join, miter_limit, within_of(&closed))?; + let outline = offset_region(&open, -delta, join, miter_limit, within_of(&open))?; + if inset.is_empty() { + return Ok(outline); + } + return crate::boolean::try_unite_all(&[(&inset, FillRule::NonZero), (&outline, FillRule::NonZero)]); + } + offset_region(path, delta, join, miter_limit, within_of(path)) +} + +/// [`offset_with_check`] of a finite `path` with the `within` test of its own segments. +fn offset_region( path: &PathData, delta: f64, join: Join, miter_limit: f64, within: impl Fn(kurbo::Point, f64) -> bool, ) -> Result { - if !delta.is_finite() || !path_is_finite(path) { - return Err(PathOpsError::NonFinite); - } if path.is_empty() { return Ok(PathData::default()); } @@ -630,14 +658,17 @@ mod tests { fn offsets_with_the_tree_are_identical_to_offsets_with_the_scan() { let (mut checks, mut hits, mut misses) = (0, 0, 0); for path in offset_inputs() { - let segs = boxed_segments(&path.to_bezpath()); for delta in [0.0, 0.05, 1.0, 5.0, 60.0, -0.05, -1.0, -5.0, -60.0] { for join in [Join::Round, Join::Miter, Join::Bevel] { let found = std::cell::Cell::new((0, 0)); - let by_scan = offset_with_check(&path, delta, join, 4.0, |p, r| { - let v = any_within_by_scan(&segs, p, r); - found.set((found.get().0 + usize::from(v), found.get().1 + usize::from(!v))); - v + let by_scan = offset_with_check(&path, delta, join, 4.0, |part| { + let segs = boxed_segments(&part.to_bezpath()); + let found = &found; + move |p, r| { + let v = any_within_by_scan(&segs, p, r); + found.set((found.get().0 + usize::from(v), found.get().1 + usize::from(!v))); + v + } }); checks += 1; hits += found.get().0; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 81e7f83ce7..492aaf56f1 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -316,6 +316,24 @@ fn offset_of_an_open_path_whose_ends_meet_is_the_closed_shape_offset() { assert_eq!(o.subpaths.len(), 1); } +#[test] +fn a_negative_offset_outlines_an_open_path_as_a_positive_one_does() { + // Issue #6427 (A4): an inset of an open path was empty. Open subpaths are outlined with a + // stroke of width 2|delta| whichever way the offset goes. + let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false)); + for delta in [2.0, -2.0] { + let o = offset_path(&line, delta, Join::Miter, 4.0); + assert!(close(ar(&o), 400.0, 1e-6), "delta {delta}: {}", ar(&o)); + assert_eq!(o.subpaths.len(), 1, "delta {delta}"); + } + // With a closed shape beside it, the shape is inset and the line still outlined. + let mut both = rect(0.0, 0.0, 20.0, 10.0); + both.subpaths.push(SubPath::polyline(&[Point::new(100.0, 0.0), Point::new(150.0, 0.0)], false)); + let o = offset_path(&both, -2.0, Join::Miter, 4.0); + assert!(close(ar(&o), 16.0 * 6.0 + 50.0 * 4.0, 1e-6), "{}", ar(&o)); + assert_eq!(o.subpaths.len(), 2); +} + #[test] fn outline_stroke_of_line() { let l = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(30.0, 40.0)], false)); diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 4b5055e67f..58c8714306 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -54,6 +54,12 @@ pub(super) fn item_effects(item: &AppearanceItem) -> &[Effect] { } } +/// The effects of `item`, a fill or stroke of `n`, that its raster effects are drawn from: each +/// one following `n`'s Transform effects as well ([`effects::item_effects_in`]). +pub(super) fn item_raster<'a>(n: &Node, item: &'a AppearanceItem) -> std::borrow::Cow<'a, [Effect]> { + effects::item_effects_in(&n.appearance.effects, item_effects(item)) +} + /// Visual bounds including geometry effects, stroke outsets and shadows/glows (symbol instances /// measured by their art from `symbols`). pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { @@ -81,7 +87,7 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { /// `r`, the art of `n` with its strokes, grown by how far the raster effects of `n`'s fills and /// strokes and then `n`'s own paint past it. fn with_raster_reach(symbols: &SymbolBoxes, n: &Node, r: Rect) -> Rect { - let r = n.appearance.items.iter().filter(|i| paints(i)).map(|i| spread(symbols, item_effects(i), r)).fold(r, |acc, b| acc.union(b)); + let r = n.appearance.items.iter().filter(|i| paints(i)).map(|i| spread(symbols, &item_raster(n, i), r)).fold(r, |acc, b| acc.union(b)); let o = outset(symbols, &n.appearance.effects, r); r.inflate(o, o) } @@ -109,7 +115,7 @@ pub(crate) fn drawn_bounds(symbols: &SymbolBoxes, n: &Node) -> Option { } let b = art_bounds(symbols, n)?; let items = n.appearance.items.iter().filter(|i| paints(i) && !effects::raster_effects(item_effects(i)).is_empty()); - Some(items.map(|i| spread(symbols, item_effects(i), item_bounds(symbols.document(), n, i).unwrap_or(b))).fold(b, |acc, r| acc.union(r))) + Some(items.map(|i| spread(symbols, &item_raster(n, i), item_bounds(symbols.document(), n, i).unwrap_or(b))).fold(b, |acc, r| acc.union(r))) } /// The bounds of what `item`, a fill or stroke of the path or compound path `n`, paints: the path diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 1169877dc7..052a8401a4 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -1,4 +1,4 @@ -use super::bounds::{apply_carrying, item_effects}; +use super::bounds::{apply_carrying, item_effects, item_raster}; use super::entries::{Content, DocInputs, Drawn, FX_RASTER_BUDGET, Inputs, ItemGeom, KeptImage, Made, Reads, feather_outline}; #[cfg(test)] use super::raster::RASTERIZED; @@ -677,7 +677,7 @@ impl Renderer { }); let item = carried.as_ref().and_then(Option::as_ref).unwrap_or(item); let ib = if effects::has_geometry(item_effects(item)) && !ig.elements().is_empty() { ig.bounding_box() } else { bounds }; - let rfx = effects::raster_effects(item_effects(item)); + let rfx = effects::raster_effects(&item_raster(n, item)); if rfx.is_empty() { self.paint_item(ctx, f, n, item, ig, rule, ib); continue; diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 96bddc17f1..50d0245c12 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -337,6 +337,45 @@ fn a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art() { } } +/// An object's or a group's Transform effect transforms the raster effects of what it holds with +/// the art: halving a 40 pt square about its center halves the 10 pt offset of its fill's shadow, +/// and of a group member's own shadow, with Scale Strokes & Effects off or on. +#[test] +fn a_transform_scales_the_shadows_of_fills_and_members_with_the_art() { + let r = Rect::new(20.0, 20.0, 60.0, 60.0); + let shadow = + Effect { id: "stylize.dropShadow".into(), params: json!({"x": 10, "y": 10, "blur": 0, "opacity": 100, "mode": "normal"}), visible: true }; + for strokes in [false, true] { + let transform = ("distort.transform", json!({"scaleH": 50, "scaleV": 50, "strokes": strokes})); + let mut fill = doc_with(r, Color::rgb(1.0, 0.0, 0.0), vec![transform.clone()]); + let l = fill.layers[0].id; + let mut square = (*fill.layers[0].children().and_then(|c| c.first()).cloned().unwrap()).clone(); + fill.remove(square.id).unwrap(); + if let Some(item) = square.appearance.items.first_mut() { + *item.effects_mut() = vec![shadow.clone()]; + } + fill.insert(Some(l), 0, square.clone()).unwrap(); + let mut member = doc_with(r, Color::rgb(1.0, 0.0, 0.0), vec![]); + let l = member.layers[0].id; + let mut square = (*member.layers[0].children().and_then(|c| c.first()).cloned().unwrap()).clone(); + member.remove(square.id).unwrap(); + square.appearance.effects = vec![shadow.clone()]; + let mut g = Node::group(member.alloc_id(), vec![Arc::new(square)]); + g.appearance.effects = [transform].into_iter().map(|(id, p)| Effect { id: id.into(), params: p, visible: true }).collect(); + member.insert(Some(l), 0, g).unwrap(); + for (what, d) in [("fill", fill), ("member", member)] { + let img = render(&d); + // The square now covers 30..50 and its shadow 35..55. + assert_eq!(img.pixel(40, 40), [255, 0, 0, 255], "{what}, Scale Strokes & Effects {strokes}"); + assert!(lum(img.pixel(53, 37)) < 100, "{what}, {strokes}: the shadow reaches up to 35: {:?}", img.pixel(53, 37)); + assert_eq!(lum(img.pixel(57, 57)), WHITE, "{what}, {strokes}: the shadow ends at 55"); + // The area redrawn for it takes in the 5 pt shadow around the 30..50 square. + let b = super::cull_bounds(&d.symbol_boxes(), &d.layers[0].children().unwrap()[0]).unwrap(); + assert!((b.x0 - 25.0).abs() < 1e-9 && (b.x1 - 55.0).abs() < 1e-9, "{what}, {strokes}: {b:?}"); + } + } +} + /// A red square's drop shadow at Darkness `darkness` (%), opaque and sharp, 10 pt down and /// right; `shade` "color" or "darkness". fn shaded_doc(mode: vectorcraft_doc::ColorMode, fill: Color, shade: &str, darkness: f64) -> Document { diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 2d945c1439..a807cbb8fa 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -8,7 +8,10 @@ mod solid; mod visibility; -pub use solid::{Bevel, BevelShape, Extrude, Facet, Inflate, View, extrude, inflate, inflate_together, plane}; +pub use solid::{ + Bevel, BevelShape, Extrude, FaceMap, Facet, Inflate, PlanarFace, View, extrude, extrude_face_map, inflate, inflate_together, plane, + plane_face_map, +}; pub use visibility::{VisibleFace, visible_faces}; mod shading; pub use shading::{ClassicShading, ClassicSurface, LightGradient, RgbGradient, ShadeGradient}; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 18c9959b19..bfd3149e6e 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -14,6 +14,7 @@ use vectorcraft_geom::{BezPath, FillRule, ParamCurve, PathData, Point, Rect, Vec use crate::{MAX_FACES, MAX_SOLID_FACES, Revolve, V3, eye_distance, perspective_scale}; mod build; +mod face_map; mod inflate; mod membrane; mod outline; @@ -23,6 +24,7 @@ mod rings; use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, extrude_faces, plane_faces}; pub use build::{extrude, plane}; +pub use face_map::{FaceMap, extrude_face_map, plane_face_map}; #[cfg(test)] use inflate::GRID_WORK; #[cfg(test)] @@ -242,6 +244,29 @@ impl Default for Inflate { } } +/// A planar face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the +/// art itself, or a plane's only face) or its back cap. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PlanarFace { + Front, + Back, +} + +impl PlanarFace { + pub const ALL: [PlanarFace; 2] = [Self::Front, Self::Back]; + + pub fn id(self) -> &'static str { + match self { + Self::Front => "front", + Self::Back => "back", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|f| f.id() == s) + } +} + /// One projected polygon. Holes are contours of their own (nonzero winding). #[derive(Clone, Debug, PartialEq)] pub struct Facet { @@ -263,6 +288,9 @@ pub struct Facet { /// The facet is turned away from the viewer: a closed solid keeps it (seen edge-on, or with /// Draw Hidden Faces) and draws it behind the facets turned toward the viewer. pub away: bool, + /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane + /// (its front). `None` for every other facet. + pub end: Option, /// The contours in view space, before projection, for tests that measure depths. #[cfg(test)] view: Vec>, @@ -307,6 +335,8 @@ impl Facet { rgb_gradient: None, outline: face.outline, side: !face.cap, + // A revolved cap is not one of the planar faces graphics map onto. + end: None, away: false, #[cfg(test)] view: vec![], diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 0b429409c7..bd4030dfc4 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -6,7 +6,7 @@ use super::rings::{ solid_rings_traced, }; use super::{ - Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, Point, Rect, Revolve, V3, View, eye_distance, + Bevel, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale, }; use crate::shadow::Projection; @@ -49,6 +49,11 @@ impl Camera { pub(super) fn brightness(&self, n: V3) -> f64 { crate::brightness(&self.view, n, self.light) } + /// The document point the view's center projects to, and the eye's distance in front of it + /// (`None` without perspective). + pub(super) fn center_and_eye(&self) -> (Point, Option) { + (self.origin, self.eye) + } /// The rotation and projection this camera draws with, for a shadow cast from its faces. pub(super) fn projection(&self) -> Projection { Projection { view: self.view, origin: self.origin, eye: self.eye } @@ -150,6 +155,7 @@ impl Builder<'_> { outline: None, side: false, away: behind, + end: None, #[cfg(test)] view, }); @@ -255,6 +261,17 @@ impl Builder<'_> { } } + /// Mark the facet that [`Builder::face`] added, when it added one after `before` facets, as the + /// planar end `end` of the solid. + pub(super) fn end(&mut self, before: usize, end: PlanarFace) { + if self.mesh.is_some() || self.facets.len() <= before { + return; + } + if let Some(f) = self.facets.last_mut() { + f.end = Some(end); + } + } + /// How many faces the builder holds: facets, or faces kept for a mesh. pub(super) fn len(&self) -> usize { self.mesh.as_ref().map_or(self.facets.len(), Vec::len) @@ -301,6 +318,10 @@ impl Placing { self.at_centre.2 + self.x.2 * dx + self.y.2 * dy, ) } + /// The map as `(x, y, c)`: an art point `p` goes to `x · p.x + y · p.y + c` in view space. + pub(super) fn frame(&self) -> (V3, V3, V3) { + (self.x, self.y, self.place(Point::ZERO)) + } } /// The point `w` points to the left of `span`'s curve at `t`, as the ring runs along it (toward @@ -598,11 +619,12 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio if o.cap { // A cap turned toward the viewer covers the walls it overlaps, even those nearer than its // center: twisted walls, and the walls of a fill inside the solid of its stroke. - let caps = [(steps.first(), along.first(), 1.0), (steps.last(), along.last(), -1.0)]; - for (s, along, n) in caps { + let caps = [(steps.first(), along.first(), 1.0, PlanarFace::Front), (steps.last(), along.last(), -1.0, PlanarFace::Back)]; + for (s, along, n, end) in caps { let Some(s) = s else { continue }; let before = b.len(); b.face(rings.iter().map(|r| ring_at(r, s)).collect(), camera.rotate(V3(0.0, 0.0, n)), Order::Last)?; + b.end(before, end); if let Some(along) = along { let traced: Vec<&Ring> = traced.iter().collect(); b.outline(before, |c| outline::face(&traced, c, along, &mut budget)); @@ -630,6 +652,7 @@ pub(crate) fn plane_faces(path: &PathData, rule: FillRule, bounds: Rect, view: V let up = camera.rotate(V3(0.0, 0.0, 1.0)); let n = if camera.facing(V3::default(), up) < 0.0 { V3(-up.0, -up.1, -up.2) } else { up }; b.face(contours, n, Order::Last)?; + b.end(0, PlanarFace::Front); let m = Placing::new(&camera, bounds.center(), Turn::new(bounds, 0.0, 1.0, 0.0), 0.0); let at = |span: &Span, t: f64| camera.project(m.place(span.curve.eval(t))); let map = |p: Point| camera.project(m.place(p)); diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs new file mode 100644 index 0000000000..d84dcc5ee6 --- /dev/null +++ b/crates/three-d/src/solid/face_map.rs @@ -0,0 +1,179 @@ +//! Where the points of a planar face's own plane land on the page: the map a graphic drawn on +//! Extrude & Bevel's caps or on a plane goes through, with the same rotation, twist, taper and +//! perspective as the face itself. + +use vectorcraft_geom::{Affine, Point, Rect}; + +use super::build::{Camera, Placing, Turn, check_bounds}; +use super::{Extrude, PlanarFace, V3, View}; + +/// A planar face's map from the art's plane (document coordinates before the 3D effect) to the +/// page: a projective map, affine without perspective. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FaceMap { + /// Rows of the map in homogeneous coordinates: a point `p` goes to `origin + (r0 · q, r1 · q) / + /// (r2 · q)` with `q = (p.x, p.y, 1)`. + rows: [[f64; 3]; 3], + origin: Point, + /// The eye's distance in front of the view's center; `None` without perspective. + eye: Option, + /// The face is turned toward the viewer. A plane, seen from either side, always is. + pub visible: bool, +} + +/// The smallest share of the eye's distance a point of the face may lie in front of the eye at: +/// the same limit [`crate::perspective_scale`] holds parts reaching past the eye to. +const NEAREST: f64 = 1e-3; + +impl FaceMap { + fn new(camera: &Camera, placing: &Placing, visible: bool) -> Self { + let (x, y, c) = placing.frame(); + let (origin, eye) = camera.center_and_eye(); + let rows = match eye { + Some(e) => [[e * x.0, e * y.0, e * c.0], [e * x.1, e * y.1, e * c.1], [-x.2, -y.2, e - c.2]], + None => [[x.0, y.0, c.0], [x.1, y.1, c.1], [0.0, 0.0, 1.0]], + }; + Self { rows, origin, eye, visible } + } + + fn homogeneous(&self, p: Point) -> [f64; 3] { + self.rows.map(|r| r[0] * p.x + r[1] * p.y + r[2]) + } + + /// The homogeneous depth a mapped point must lie beyond: the eye's distance times [`NEAREST`] + /// with perspective, 0 without. + fn nearest(&self) -> f64 { + self.eye.map_or(0.0, |e| e * NEAREST) + } + + /// Where art point `p` lands on the page. `None` when it lies at or behind the eye, or the + /// result is not finite. + pub fn to_page(&self, p: Point) -> Option { + let [u, v, w] = self.homogeneous(p); + if w.is_nan() || w <= self.nearest() { + return None; + } + let q = Point::new(self.origin.x + u / w, self.origin.y + v / w); + (q.x.is_finite() && q.y.is_finite()).then_some(q) + } + + /// The art point that lands on page point `q`. `None` when the face is seen edge-on there, the + /// point lies beyond the face's horizon, or it lies nearer the eye than [`FaceMap::to_page`] + /// maps. + pub fn to_art(&self, q: Point) -> Option { + let (u, v) = (q.x - self.origin.x, q.y - self.origin.y); + let [r0, r1, r2] = self.rows; + let (a, b, c) = (r0[0] - u * r2[0], r0[1] - u * r2[1], -(r0[2] - u * r2[2])); + let (d, e, f) = (r1[0] - v * r2[0], r1[1] - v * r2[1], -(r1[2] - v * r2[2])); + let det = a * e - b * d; + let scale = (a.abs() + b.abs()).max(d.abs() + e.abs()); + if det.is_nan() || det.abs() <= 1e-12 * scale * scale { + return None; + } + let p = Point::new((c * e - b * f) / det, (a * f - c * d) / det); + // A point of the plane behind the eye projects to the same page point as one in front, and + // `to_page` maps no point nearer the eye than its limit. + (p.x.is_finite() && p.y.is_finite() && self.homogeneous(p)[2] > self.nearest()).then_some(p) + } + + /// Does every point of the cubic Bézier curve with control points `c` lie far enough in front + /// of the eye for [`FaceMap::to_page`] to map it? Its control points need not. + pub fn maps_curve(&self, c: [Point; 4]) -> bool { + let [w0, w1, w2, w3] = c.map(|p| self.homogeneous(p)[2]); + let depth = |t: f64| { + let s = 1.0 - t; + s * s * s * w0 + 3.0 * s * s * t * w1 + 3.0 * s * t * t * w2 + t * t * t * w3 + }; + // The depth is least at an end or where its derivative, a t² + b t + k (times 3), is 0. + let (a, b, k) = (w3 - 3.0 * w2 + 3.0 * w1 - w0, 2.0 * (w2 - 2.0 * w1 + w0), w1 - w0); + // A missing root is NaN, which the range check leaves out. + let mut at = [0.0, 1.0, f64::NAN, f64::NAN]; + if a.abs() > 1e-12 { + let root = (b * b - 4.0 * a * k).sqrt(); + at[2] = (-b + root) / (2.0 * a); + at[3] = (-b - root) / (2.0 * a); + } else if b.abs() > 1e-12 { + at[2] = -k / b; + } + let limit = self.nearest(); + at.into_iter().filter(|t| (0.0..=1.0).contains(t)).all(|t| depth(t) > limit) + } + + /// The part of rectangle `r` of the face's plane whose points [`FaceMap::to_page`] maps, kept + /// back from the eye by twice its nearest distance, as a convex polygon: all of `r` without + /// perspective. `None` when no part of `r` maps. + pub fn mapped_part(&self, r: Rect) -> Option> { + let corners = vec![Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]; + let Some(e) = self.eye else { return Some(corners) }; + let [a, b, c] = self.rows[2]; + let limit = 2.0 * e * NEAREST; + let side = |p: Point| a * p.x + b * p.y + c - limit; + // The polygon cut by the line where `side` is 0 (one step of Sutherland and Hodgman's clip). + let mut out = vec![]; + for (k, &p) in corners.iter().enumerate() { + let q = corners[(k + 1) % corners.len()]; + let (sp, sq) = (side(p), side(q)); + if sp >= 0.0 { + out.push(p); + } + if (sp >= 0.0) != (sq >= 0.0) { + out.push(p.lerp(q, sp / (sp - sq))); + } + } + (out.len() >= 3 && out.iter().all(|p| p.x.is_finite() && p.y.is_finite())).then_some(out) + } + + /// Without perspective, the map is affine. + pub fn is_affine(&self) -> bool { + self.eye.is_none() + } + + /// The affine map nearest the face's map around art point `p` (exact without perspective): + /// what a gradient or a stroke on a graphic is drawn with. `None` where [`FaceMap::to_page`] + /// has no point. + pub fn local_affine(&self, p: Point) -> Option { + let at = self.to_page(p)?; + let [u, v, w] = self.homogeneous(p); + let [r0, r1, r2] = self.rows; + // The derivatives of u / w and v / w along x and y. + let d = |r: [f64; 3], n: f64, k: usize| (r[k] * w - n * r2[k]) / (w * w); + let (a, b, c, e) = (d(r0, u, 0), d(r1, v, 0), d(r0, u, 1), d(r1, v, 1)); + let m = Affine::new([a, b, c, e, at.x - a * p.x - c * p.y, at.y - b * p.x - e * p.y]); + m.as_coeffs().iter().all(|v| v.is_finite()).then_some(m) + } +} + +/// The map of Extrude & Bevel's cap `face` for a solid built with `bounds`, `options` and `view`, +/// as [`super::extrude`] builds it. With a depth of 0 the art is a plane, whose only face is the +/// front. `None` for a hollow solid (no caps), for the back of a plane, and for invalid bounds. +pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return (face == PlanarFace::Front).then(|| plane_face_map(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); + let at = placing.place(bounds.center()); + let visible = camera.facing(at, camera.rotate(V3(0.0, 0.0, side))) > 0.0; + Some(FaceMap::new(&camera, &placing, visible)) +} + +/// The map of the plane [`super::plane`] turns art with `bounds` into, with `view`. +pub fn plane_face_map(bounds: Rect, view: View) -> Option { + 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(FaceMap::new(&camera, &placing, 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 new file mode 100644 index 0000000000..31644beda5 --- /dev/null +++ b/crates/three-d/src/solid/tests_face_map.rs @@ -0,0 +1,160 @@ +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}; + +fn square() -> (PathData, Rect) { + let mut b = BezPath::new(); + b.move_to((10.0, 20.0)); + b.line_to((70.0, 20.0)); + b.line_to((70.0, 60.0)); + b.line_to((10.0, 60.0)); + b.close_path(); + let p = PathData::from_bezpath(&b); + let r = p.bounds().unwrap(); + (p, r) +} + +fn turned(perspective: f64) -> View { + View { rotation_x: -30.0, rotation_y: 40.0, rotation_z: 10.0, perspective, ..View::default() } +} + +fn corners(r: Rect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// Every corner of `face` is where the map takes one of the art's corners. +fn lands_on(face: &Facet, map: &FaceMap, art: [Point; 4]) { + for c in face.contours.iter().flatten() { + let near = art.iter().filter_map(|p| map.to_page(*p)).map(|q| q.distance(*c)).fold(f64::INFINITY, f64::min); + assert!(near < 1e-6, "facet corner {c:?} is {near} from every mapped corner"); + } +} + +fn end(facets: &[Facet], end: PlanarFace) -> Option<&Facet> { + facets.iter().find(|f| f.end == Some(end)) +} + +#[test] +fn the_front_cap_is_where_the_map_takes_the_art() { + let (path, bounds) = square(); + for perspective in [0.0, 60.0, 140.0] { + let view = turned(perspective); + let facets = extrude(&path, FillRule::NonZero, bounds, Extrude::default(), view).unwrap(); + let map = extrude_face_map(bounds, Extrude::default(), view, PlanarFace::Front).unwrap(); + let front = end(&facets, PlanarFace::Front).unwrap(); + assert!(map.visible && !front.away); + lands_on(front, &map, corners(bounds)); + assert_eq!(map.is_affine(), perspective == 0.0); + } +} + +#[test] +fn the_back_cap_follows_the_twist_and_taper() { + let (path, bounds) = square(); + let options = Extrude { twist: 35.0, taper: 0.5, ..Extrude::default() }; + // Seen from behind, the back cap faces the viewer and the front does not. + let view = View { rotation_y: 160.0, perspective: 50.0, ..turned(0.0) }; + let facets = extrude(&path, FillRule::NonZero, bounds, options, view).unwrap(); + let back = end(&facets, PlanarFace::Back).unwrap(); + let map = extrude_face_map(bounds, options, view, PlanarFace::Back).unwrap(); + assert!(map.visible); + assert!(!extrude_face_map(bounds, options, view, PlanarFace::Front).unwrap().visible); + assert!(end(&facets, PlanarFace::Front).is_none_or(|f| f.away)); + lands_on(back, &map, corners(bounds)); +} + +#[test] +fn a_plane_has_only_a_front_and_a_hollow_solid_none() { + let (path, bounds) = square(); + let view = turned(80.0); + let facets = plane(&path, FillRule::NonZero, bounds, view).unwrap(); + let map = plane_face_map(bounds, view).unwrap(); + lands_on(end(&facets, PlanarFace::Front).unwrap(), &map, corners(bounds)); + let flat = Extrude { depth: 0.0, ..Extrude::default() }; + assert_eq!(extrude_face_map(bounds, flat, view, PlanarFace::Front), Some(map)); + assert_eq!(extrude_face_map(bounds, flat, view, PlanarFace::Back), None); + let hollow = Extrude { cap: false, ..Extrude::default() }; + assert_eq!(extrude_face_map(bounds, hollow, view, PlanarFace::Front), None); + let facets = extrude(&path, FillRule::NonZero, bounds, hollow, view).unwrap(); + assert!(facets.iter().all(|f| f.end.is_none())); +} + +#[test] +fn page_points_map_back_to_the_art() { + let (_, bounds) = square(); + for perspective in [0.0, 120.0] { + let map = extrude_face_map(bounds, Extrude::default(), turned(perspective), PlanarFace::Front).unwrap(); + for p in [Point::new(10.0, 20.0), Point::new(45.0, 33.0), Point::new(-200.0, 400.0)] { + let q = map.to_page(p).unwrap(); + let back = map.to_art(q).unwrap(); + assert!(back.distance(p) < 1e-6, "{p:?} came back as {back:?}"); + } + } +} + +#[test] +fn the_local_affine_map_matches_the_face_near_its_point() { + let (_, bounds) = square(); + let flat = extrude_face_map(bounds, Extrude::default(), turned(0.0), PlanarFace::Front).unwrap(); + let m = flat.local_affine(Point::new(40.0, 40.0)).unwrap(); + for p in corners(bounds) { + assert!((m * p).distance(flat.to_page(p).unwrap()) < 1e-9); + } + let deep = extrude_face_map(bounds, Extrude::default(), turned(120.0), PlanarFace::Front).unwrap(); + let at = Point::new(40.0, 40.0); + let [a, b, c, d, ..] = deep.local_affine(at).unwrap().as_coeffs(); + let h = 1e-4; + let slope = |dx: f64, dy: f64| { + let (p, q) = (deep.to_page(Point::new(at.x + dx, at.y + dy)).unwrap(), deep.to_page(Point::new(at.x - dx, at.y - dy)).unwrap()); + ((p.x - q.x) / (2.0 * h), (p.y - q.y) / (2.0 * h)) + }; + let ((ax, bx), (cy, dy)) = (slope(h, 0.0), slope(0.0, h)); + for (got, want) in [(a, ax), (b, bx), (c, cy), (d, dy)] { + assert!((got - want).abs() < 1e-6, "{got} against {want}"); + } + assert!((deep.local_affine(at).unwrap() * at).distance(deep.to_page(at).unwrap()) < 1e-9); +} + +#[test] +fn a_point_behind_the_eye_has_no_page_point() { + let (_, bounds) = square(); + // Seen almost edge-on at the widest perspective, far points of the plane pass behind the eye. + let view = View { rotation_x: -89.0, perspective: 160.0, ..turned(0.0) }; + let map = plane_face_map(bounds, view).unwrap(); + assert!(map.to_page(Point::new(40.0, -1e6)).is_none() || map.to_page(Point::new(40.0, 1e6)).is_none()); +} + +#[test] +fn a_page_point_nearer_the_eye_than_the_page_map_allows_has_no_art_point() { + let (_, bounds) = square(); + let view = View { rotation_x: -89.0, perspective: 160.0, ..turned(0.0) }; + let map = plane_face_map(bounds, view).unwrap(); + let limit = map.eye.unwrap() * NEAREST; + // An art point in front of the eye, but at half the nearest depth `to_page` maps. + let [a, b, c] = map.rows[2]; + let p0 = bounds.center(); + let t = (limit / 2.0 - (a * p0.x + b * p0.y + c)) / (a * a + b * b); + let p = Point::new(p0.x + t * a, p0.y + t * b); + let [u, v, w] = map.homogeneous(p); + assert!(w > 0.0 && w < limit, "{w}"); + assert_eq!(map.to_page(p), None); + let q = Point::new(map.origin.x + u / w, map.origin.y + v / w); + assert_eq!(map.to_art(q), None, "the inverse map takes {q:?} back to an art point the page map has no point for"); +} + +#[test] +fn the_mapped_part_of_a_rectangle_stops_before_the_eye() { + let (_, bounds) = square(); + let view = View { rotation_x: -89.0, perspective: 160.0, ..turned(0.0) }; + let map = plane_face_map(bounds, view).unwrap(); + let r = Rect::new(-1e6, -1e6, 1e6, 1e6); + let part = map.mapped_part(r).unwrap(); + // Some of the rectangle passes behind the eye, and every corner of what is left maps. + assert!((3..=5).contains(&part.len())); + assert!(part.iter().all(|p| map.to_page(*p).is_some()), "{part:?}"); + assert!(corners(r).iter().any(|p| !part.contains(p))); + // Without perspective, all of it maps. + let flat = plane_face_map(bounds, View { perspective: 0.0, ..view }).unwrap(); + assert_eq!(flat.mapped_part(r).map(|p| p.len()), Some(4)); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f68fbee17f..d75eae537f 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -410,6 +410,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { draw_overlays(&painter, &xf, &overlays, &t, HandleLook::of(&app.session.prefs)); if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); + crate::panels::three_d::paint_graphic_handles(app, &painter, &xf); } } ime_geometry(app, ui.ctx(), &xf); @@ -444,14 +445,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press. -fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { - // A press on the canvas while the context menu is open only closes it (a drag too, which egui - // alone would leave open); the tool doesn't get it. +pub(crate) fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) { // The artboard's 3D gizmo owns these gestures while its options are open. // Do not let a ring drag also move or deselect the editable source path. } else if resp.context_menu_opened() && resp.hovered() && ui.input(|i| i.pointer.any_pressed()) { + // A press on the canvas while the context menu is open only closes it (a drag too, which + // egui alone would leave open); neither the tool nor a graphic's handle gets it. egui::Popup::close_all(ui.ctx()); + } else if crate::panels::three_d::graphic_handles_input(app, ui, resp, rect) { + // A mapped graphic's handle, shown while the 3D and Materials panel's Materials tab is + // open, has the press: the drag moves the graphic, not the object. } else { handle_input(app, ui, resp, rect); // `hover_doc` is the document point under the pointer in the view `handle_input` left. The diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 53bfb98c1c..e7c4145397 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -282,6 +282,26 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize transform } +/// Draws the Control bar's Align group after the artboard controls, with the Artboard tool in use: +/// the Align buttons, the Align To menu and, for two or more selected artboards, the Distribute +/// buttons. They align and distribute the selected artboards +/// ([`crate::panels::align::run_button`]). Each shows only while the bar has room for it, and none +/// while the panel menu has the group off. +fn artboard_align_group(app: &mut VectorcraftApp, ui: &mut Ui) { + if !group_on(app, "alignDistribute") || app.session.active().is_none() || ui.available_width() < separator_width(ui) + buttons_width(ui, 7) { + return; + } + separator(ui); + crate::panels::align::align_buttons(app, ui, BUTTON); + if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x { + crate::panels::align::align_to_menu(app, ui, BUTTON); + if crate::panels::align::artboards_selected(app) > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) { + ui.add_space(GROUP_GAP); + crate::panels::align::distribute_buttons(app, ui, BUTTON); + } + } +} + /// The edges of the window the Control bar docks to (`window.control.dock {edge}`): the top, then /// the bottom. pub const CONTROL_BAR_EDGES: [&str; 2] = ["top", "bottom"]; @@ -516,6 +536,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // of the object controls. let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); if crate::panels::artboards::control_bar(app, ui, artboard_options, transform) { + artboard_align_group(app, ui); return; } if anchors != AnchorControls::None && group_on(app, "anchors") { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index d7620e8d03..9350180586 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2669,6 +2669,49 @@ fn menus_stop_above_a_control_bar_docked_at_the_bottom() { assert!(f < bar_top - 1.0, "the status and hint bars show above the Control bar: menus stop above them, {f}"); } +/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard +/// controls while it has room, and the Distribute buttons for two or more selected artboards. A +/// click aligns the selected artboards as the Align panel's button does. The group is left out +/// while the panel menu has it off. +#[test] +fn the_control_bar_aligns_the_selected_artboards_with_the_artboard_tool() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2400.0, 300.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = |app: &mut crate::VectorcraftApp, name: &str| { + frame(app, vec![]); + let nodes = frame(app, vec![]); + let n = nodes.iter().find(|(_, n)| n.label() == Some(name)).map(|(_, n)| n)?; + n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + }; + app.session.set_tool_option("selected", &json!([1])); + assert!(button(&mut app, "Vertical Align Top").is_some(), "one artboard: the Align buttons"); + assert!(button(&mut app, "Horizontal Distribute Left").is_none(), "one artboard: no Distribute buttons"); + app.session.set_tool_option("selected", &json!([1, 0])); + assert!(button(&mut app, "Horizontal Distribute Left").is_some(), "two artboards: the Distribute buttons"); + let r = button(&mut app, "Vertical Align Top").expect("Vertical Align Top"); + let press = + |pressed| egui::Event::PointerButton { pos: r.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![egui::Event::PointerMoved(r.center()), press(true)], vec![press(false)]] { + frame(&mut app, events); + } + let tops: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.y0).collect(); + assert_eq!(tops, [0.0, 0.0], "{}", app.ui.status); + app.run("window.control.options", json!({"group": "alignDistribute", "visible": false})).unwrap(); + assert!(button(&mut app, "Vertical Align Top").is_none(), "the group is off"); +} + /// Two or more selected objects show all six Distribute Objects buttons in the Control bar; /// a single object keeps the bar as it was. A click distributes as the Align panel's button does. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 0f27de4ead..89ab7e37b4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -652,7 +652,10 @@ fn occurrences(text: &str, needle: &str, fold: bool) -> Vec { /// changed. fn replace_text(s: &str, r: &Rewrite) -> Option { let decoded = if has_percent_escape(s) { decoded_with_spans(s).filter(|(decoded, _)| decoded != s) } else { None }; - let mut found = Found::default(); + let mut found = Found { kept: readable_ids_in(s, None, r), ..Found::default() }; + if let Some((text, spans)) = &decoded { + found.kept.extend(readable_ids_in(text, Some(spans.as_slice()), r)); + } for group in &r.pairs { for fold in [false, true].into_iter().take(if r.fold { 2 } else { 1 }) { for (from, to) in group { @@ -679,24 +682,28 @@ fn replace_text(s: &str, r: &Rewrite) -> Option { Some(out) } -/// The spans of a text that [`replace_text`] replaces, each with its replacement, and every span it has -/// taken: the ones it replaces and the loaded library ids it keeps. +/// The spans of a text that [`replace_text`] replaces, each with its replacement, every span it has +/// taken (the ones it replaces and the loaded library ids it keeps), and the whole readable library ids +/// the text holds ([`readable_ids_in`]). #[derive(Default)] struct Found<'a> { cuts: Vec<(usize, usize, &'a str)>, taken: Vec<(usize, usize)>, + kept: Vec<(usize, usize)>, } impl<'a> Found<'a> { - /// Takes each occurrence of `from` in `text` that overlaps no span taken: as a span to write as `to`, - /// or, where it begins a loaded library's id ([`begins_known_id`]), that id's span, kept. `spans` - /// gives the range of the original text each byte of a decoded `text` was read from. + /// Takes each occurrence of `from` in `text` that overlaps no span taken and lies inside no whole + /// readable library id: as a span to write as `to`, or, where it begins a loaded library's id + /// ([`begins_known_id`]), that id's span, kept. `spans` gives the range of the original text each + /// byte of a decoded `text` was read from. fn claim(&mut self, text: &str, spans: Option<&[(usize, usize)]>, from: &str, to: &'a str, fold: bool, r: &Rewrite) { let span = |at: usize, end: usize| spans.map_or((at, end), |s| (s[at].0, s[end - 1].1)); for at in occurrences(text, from, fold) { let end = at + from.len(); let (start, stop) = span(at, end); - if self.taken.iter().any(|&(a, b)| start < b && a < stop) || ends_a_longer_path(text, at, from) { + let inside_readable = self.kept.iter().any(|&(a, b)| a <= start && stop <= b); + if inside_readable || self.taken.iter().any(|&(a, b)| start < b && a < stop) || ends_a_longer_path(text, at, from) { continue; } match begins_known_id(text, at, end, r) { @@ -825,6 +832,47 @@ fn begins_known_id(text: &str, at: usize, end: usize, r: &Rewrite) -> Option