mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-17 02:05:42 +00:00
Merge main into fix/fileinfo-control-characters-message
This commit is contained in:
@@ -31,3 +31,8 @@ jobs:
|
||||
require-craft-fonts: true
|
||||
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
|
||||
run-package-check: true
|
||||
# The test builds of this workspace's largest crates (engine, ui-egui) need more than the
|
||||
# VM's 12 GB when two compile at once: the build was killed (exit 137) every night with
|
||||
# four jobs and again with two. One rustc at a time; it still uses every core.
|
||||
cargo-build-extra-args: "-j 1"
|
||||
cargo-test-extra-args: "-j 1"
|
||||
|
||||
Generated
+13
@@ -1043,6 +1043,17 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-metafile"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-pdf"
|
||||
version = "0.1.0"
|
||||
@@ -6681,6 +6692,7 @@ dependencies = [
|
||||
name = "vectorcraft-metafile"
|
||||
version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-metafile",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
"vectorcraft-brush",
|
||||
@@ -6812,6 +6824,7 @@ version = "0.24.1"
|
||||
dependencies = [
|
||||
"craft-docpath",
|
||||
"craft-svg",
|
||||
"data-url",
|
||||
"flate2",
|
||||
"image",
|
||||
"kurbo 0.13.1",
|
||||
|
||||
@@ -31,6 +31,8 @@ craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e
|
||||
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# DXF tags, reader and writer (craft-libs#778, #926, #927).
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
# WMF, EMF and EMF+ reader (craft-libs#778).
|
||||
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
|
||||
# internal
|
||||
vectorcraft-geom = { path = "crates/geom" }
|
||||
|
||||
+4
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: Raster effects 85% → 88%, gallery thumbnails and in-dialog preview in; headline numbers unchanged; Symbols area ~87% → ~88%: dynamic instance parts take opacity, blend, gradient and pattern on the canvas; G5 docs sync for Overlap and Pattern auto corners; previously minor: Tools stays beside the canvas with left-side panels; Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x)
|
||||
|
||||
VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs
|
||||
on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON
|
||||
@@ -125,6 +125,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
## Progress log
|
||||
|
||||
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
|
||||
|
||||
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
|
||||
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
|
||||
@@ -224,6 +225,8 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-15 | minor | Graphic Styles: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); G5 estimate unchanged (3–13 h). |
|
||||
| 2026-11-14 | minor | Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Tidy-up, no content change: the unheaded change bullets at the top of the file and a revision row inside the headline-numbers table move to this table under their commit dates. Scores and estimates unchanged. |
|
||||
| 2026-11-10 | minor | Raster effects: Effect Gallery thumbnails and an in-dialog preview (an original drawing through each filter). Features-table Raster effects 85% → 88%, hours 1–2 → none. Headline numbers unchanged, so the progress log is unchanged. |
|
||||
|
||||
@@ -1008,6 +1008,33 @@ pub fn has_brush(n: &Node) -> bool {
|
||||
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
|
||||
}
|
||||
|
||||
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
|
||||
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
|
||||
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
|
||||
/// the exports leave for brush art when they cull.
|
||||
pub fn reach(n: &Node) -> f64 {
|
||||
let paints = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.visible && s.brush.is_some() && !s.paint.is_none());
|
||||
if !n.appearance.items.iter().any(paints) {
|
||||
return 0.0;
|
||||
}
|
||||
let w = n.appearance.items.iter().filter_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s.width) } else { None }).fold(1.0, f64::max);
|
||||
16.0 * w + 8.0
|
||||
}
|
||||
|
||||
/// The largest [`reach`] of `n` and of the objects in it: the members of its groups, layers and
|
||||
/// live objects. Of a group or layer with a clipping path only the clipping path counts, as the
|
||||
/// clip keeps its members' brush art inside it. A compound path counts its own strokes only, as
|
||||
/// it is painted with its own appearance and not its paths'. Symbol art is not looked into
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::with_brush_art`] measures it).
|
||||
pub fn reach_within(n: &Node) -> f64 {
|
||||
let members = match &n.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => children.get(..1).unwrap_or_default(),
|
||||
NodeKind::Compound { .. } => &[],
|
||||
_ => n.children().map_or(&[][..], |c| &c[..]),
|
||||
};
|
||||
members.iter().map(|c| reach_within(c)).fold(reach(n), f64::max)
|
||||
}
|
||||
|
||||
/// Expand a brushed path: a group of [the path with its fills and unbrushed strokes (if any
|
||||
/// paint remains), the brush art…]. Ids are 0 (the caller re-ids). `None` if not brushed.
|
||||
pub fn expand(doc: &Document, n: &Node) -> Option<Node> {
|
||||
|
||||
@@ -172,6 +172,21 @@ impl IccProfile {
|
||||
Some(dst.map(|x| x.clamp(0.0, 1.0)))
|
||||
}
|
||||
|
||||
/// Device pixels `v` (RGB / CMYK / Gray, 0..1, the profile's channels a pixel, any number of
|
||||
/// pixels) → sRGB in `dst` (three values a pixel), converted with `intent` in one pass of the
|
||||
/// cached transform. `None` when `v` doesn't hold whole pixels, `dst` doesn't hold three values
|
||||
/// for each, or no transform can be built.
|
||||
pub fn to_srgb_pixels(&self, v: &[f32], dst: &mut [f32], intent: Intent) -> Option<()> {
|
||||
let n = self.channels();
|
||||
if !v.len().is_multiple_of(n) || dst.len() != v.len() / n * 3 {
|
||||
return None;
|
||||
}
|
||||
let xf = self.to_xf(intent)?;
|
||||
xf.transform(v, dst).ok()?;
|
||||
dst.iter_mut().for_each(|x| *x = x.clamp(0.0, 1.0));
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// sRGB → device values.
|
||||
pub fn from_srgb(&self, rgb: [f32; 3], intent: Intent) -> Option<Vec<f32>> {
|
||||
let xf = self.inverse_xf(intent)?;
|
||||
|
||||
@@ -48,6 +48,28 @@ fn gray_is_srgb_toned() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_pixels_convert_as_each_one_does() {
|
||||
let p = IccProfile::from_bytes(None, &icc_bytes(DISPLAY_P3).unwrap()).unwrap();
|
||||
let px = [[1.0f32, 0.0, 0.0], [0.2, 0.6, 0.9], [0.5, 0.5, 0.5], [0.0, 1.0, 0.0]];
|
||||
for intent in Intent::ALL {
|
||||
let v: Vec<f32> = px.iter().flatten().copied().collect();
|
||||
let mut dst = vec![0.0; v.len()];
|
||||
p.to_srgb_pixels(&v, &mut dst, intent).unwrap();
|
||||
for (i, rgb) in px.iter().enumerate() {
|
||||
let one = p.to_srgb(rgb, intent).unwrap();
|
||||
assert!(dst[i * 3..i * 3 + 3].iter().zip(one).all(|(a, b)| (a - b).abs() < 1e-5), "{intent:?} {rgb:?}: {dst:?} vs {one:?}");
|
||||
}
|
||||
}
|
||||
// Lengths that aren't whole pixels, or a destination of another size, are refused.
|
||||
assert!(p.to_srgb_pixels(&[0.5; 4], &mut [0.0; 3], Intent::Perceptual).is_none());
|
||||
assert!(p.to_srgb_pixels(&[0.5; 3], &mut [0.0; 6], Intent::Perceptual).is_none());
|
||||
let gray = IccProfile::from_bytes(None, &icc_bytes(GRAY).unwrap()).unwrap();
|
||||
let mut dst = [0.0; 6];
|
||||
gray.to_srgb_pixels(&[0.25, 0.75], &mut dst, Intent::RelativeColorimetric).unwrap();
|
||||
assert!(dst.iter().zip([0.25, 0.25, 0.25, 0.75, 0.75, 0.75]).all(|(a, b)| (a - b).abs() < 0.01), "{dst:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_profiles_are_reproducible() {
|
||||
assert_eq!(icc::builtin_rgb_bytes(DISPLAY_P3).unwrap(), icc::builtin_rgb_bytes(DISPLAY_P3).unwrap());
|
||||
|
||||
+452
-24
@@ -19,11 +19,11 @@
|
||||
use std::f64::consts::PI;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, GradientStop, Paint};
|
||||
use vectorcraft_color::{Color, Gradient, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint};
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveArclen, ParamCurveDeriv};
|
||||
use vectorcraft_geom::{Affine, Anchor, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
|
||||
|
||||
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeLayer, WidthProfile};
|
||||
use crate::appearance::{AngleProfile, Appearance, AppearanceItem, Dash, PressureProfile, StrokeGradientMode, StrokeLayer, WidthProfile};
|
||||
use crate::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use crate::node::{Node, NodeId, NodeKind};
|
||||
use crate::text::TextObject;
|
||||
@@ -79,7 +79,11 @@ fn solid_gradient(c: Color, swatch: Option<&str>, tint: f32, like: &Gradient) ->
|
||||
/// of the two stops around `t` at the tint and plates between theirs (unlinked when they differ),
|
||||
/// as [`Gradient::sample_with`] walks.
|
||||
fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
|
||||
let stops = &g.stops;
|
||||
link_in(&g.stops, t)
|
||||
}
|
||||
|
||||
/// [`link_at`] of a gradient's `stops`.
|
||||
fn link_in(stops: &[GradientStop], t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
|
||||
let link = |s: &GradientStop| (s.swatch.clone(), s.tint, s.plates);
|
||||
let Some(first) = stops.first() else { return (None, 1.0, None) };
|
||||
if t <= first.offset {
|
||||
@@ -103,15 +107,32 @@ fn link_at(g: &Gradient, t: f32) -> (Option<String>, f32, Option<[f32; 4]>) {
|
||||
stops.last().map_or((None, 1.0, None), link)
|
||||
}
|
||||
|
||||
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred).
|
||||
/// How close two places a gradient changes are for [`common_stops`] to give them one stop (two
|
||||
/// where either gradient steps there: two of its stops at the same offset).
|
||||
const STEP: f32 = 1e-4;
|
||||
|
||||
/// `g` with its stops at `offsets`, each painting what `g` paints there (midpoints centred). An
|
||||
/// offset given twice is a step: the second stop paints what `g` steps to there (the last of its
|
||||
/// stops at one offset within [`STEP`] of it), or what it paints there when it does not step.
|
||||
fn resample_stops(g: &Gradient, offsets: &[f32]) -> Gradient {
|
||||
let mut out = g.clone();
|
||||
out.stops = offsets
|
||||
.iter()
|
||||
.map(|&o| {
|
||||
let (color, opacity) = g.sample_keep_model(o);
|
||||
let (swatch, tint, plates) = link_at(g, o);
|
||||
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
|
||||
.enumerate()
|
||||
.map(|(i, &o)| {
|
||||
let after = i.checked_sub(1).and_then(|j| offsets.get(j)) == Some(&o);
|
||||
let stepped =
|
||||
if after { g.stops.windows(2).rfind(|w| w[0].offset == w[1].offset && (w[0].offset - o).abs() < STEP).map(|w| &w[1]) } else { None };
|
||||
match stepped {
|
||||
Some(s) => {
|
||||
GradientStop { opacity: s.opacity, swatch: s.swatch.clone(), tint: s.tint, plates: s.plates, ..GradientStop::new(o, s.color) }
|
||||
}
|
||||
None => {
|
||||
let (color, opacity) = g.sample_keep_model(o);
|
||||
let (swatch, tint, plates) = link_at(g, o);
|
||||
GradientStop { opacity, swatch, tint, plates, ..GradientStop::new(o, color) }
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out
|
||||
@@ -130,7 +151,7 @@ fn gradient_breaks(g: &Gradient, out: &mut Vec<f32>) {
|
||||
}
|
||||
|
||||
/// Two gradients of one kind with the same number of stops: as they are when the counts match,
|
||||
/// else both resampled at every place either changes.
|
||||
/// else both resampled at every place either changes, with two stops where either steps.
|
||||
fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
|
||||
if a.kind != b.kind {
|
||||
return None;
|
||||
@@ -146,8 +167,22 @@ fn common_stops(a: &Gradient, b: &Gradient) -> Option<(Gradient, Gradient)> {
|
||||
gradient_breaks(b, &mut offs);
|
||||
offs.retain(|o| o.is_finite());
|
||||
offs.sort_by(f32::total_cmp);
|
||||
offs.dedup_by(|x, y| (*x - *y).abs() < 1e-4);
|
||||
Some((resample_stops(a, &offs), resample_stops(b, &offs)))
|
||||
offs.dedup_by(|x, y| (*x - *y).abs() < STEP);
|
||||
let mut steps: Vec<f32> =
|
||||
[a, b].into_iter().flat_map(|g| g.stops.windows(2).filter(|w| w[1].offset == w[0].offset).map(|w| w[0].offset)).collect();
|
||||
steps.sort_by(f32::total_cmp);
|
||||
let mut at = Vec::with_capacity(offs.len() + steps.len());
|
||||
let mut k = 0;
|
||||
for o in offs {
|
||||
at.push(o);
|
||||
while steps.get(k).is_some_and(|&s| s <= o - STEP) {
|
||||
k += 1;
|
||||
}
|
||||
if steps.get(k).is_some_and(|&s| (s - o).abs() < STEP) {
|
||||
at.push(o);
|
||||
}
|
||||
}
|
||||
Some((resample_stops(a, &at), resample_stops(b, &at)))
|
||||
}
|
||||
|
||||
fn lerp_gradient(a: &GradientPaint, b: &GradientPaint, t: f32) -> Option<GradientPaint> {
|
||||
@@ -627,12 +662,128 @@ fn reoriented<V: Copy>(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr
|
||||
out
|
||||
}
|
||||
|
||||
/// A stroke read along its subpath turned as `o` says: its width profile (whose sides swap when
|
||||
/// reversed), pen pressure, tilt, bearing and rotation. Its arrowheads stay as they are.
|
||||
fn reorient_stroke(s: &mut StrokeLayer, o: Orient) {
|
||||
/// Gradient `g` laid along a closed subpath that now starts at fraction `s` of its length: the
|
||||
/// part from `s` on runs first, then the part before it, stepping where the old start now falls.
|
||||
/// The stops follow its colors as [`Gradient::span`] reads them, mixed linearly, and run once.
|
||||
/// One of `g`'s own stops keeps its swatch link (each stop of a step its own), and a stop between
|
||||
/// two of them the link [`link_at`] reads there.
|
||||
fn gradient_from(g: &Gradient, s: f32) -> Gradient {
|
||||
// A hue gradient that reflects unrolls through its curve, whose stops have no links: the links
|
||||
// come from its own stops unrolled as a Classic gradient's, which keep them.
|
||||
let hue_reflect = g.is_spread() && g.spread == GradientSpread::Reflect && g.method.is_hue();
|
||||
let classic = hue_reflect.then(|| Gradient { method: GradientMethod::Classic, ..g.clone() });
|
||||
let g = g.unrolled();
|
||||
let mut own = classic.as_ref().map_or_else(|| g.stops.clone(), |c| c.unrolled().stops.clone());
|
||||
own.sort_by(|a, b| a.offset.total_cmp(&b.offset));
|
||||
let mut stops = Vec::new();
|
||||
// The part from `s` to the end runs first, then the part up to `s`.
|
||||
for (from, to, at) in [(s, 1.0, 0.0), (0.0, s, 1.0 - s)] {
|
||||
// The first of `own` not yet matched: the parts' stops run in order, so the links are
|
||||
// found in one pass.
|
||||
let mut j = 0;
|
||||
for (k, st) in g.span(from, to).stops.into_iter().enumerate() {
|
||||
let p = from + (to - from) * st.offset;
|
||||
while own.get(j).is_some_and(|o| o.offset <= p - STEP) {
|
||||
j += 1;
|
||||
}
|
||||
let same = |i: usize| own.get(i).is_some_and(|o| o.color == st.color && o.opacity == st.opacity);
|
||||
let near = (j..own.len()).take_while(|&i| own.get(i).is_some_and(|o| o.offset < p + STEP));
|
||||
let mut hit = near.clone().find(|&i| same(i));
|
||||
// A part starting on a step starts with the color after it, so its first stop takes
|
||||
// the link of the step's last stop of that color.
|
||||
if k == 0
|
||||
&& let Some(at) = hit.and_then(|i| own.get(i)).map(|o| o.offset)
|
||||
{
|
||||
hit = near.filter(|&i| own.get(i).is_some_and(|o| o.offset == at) && same(i)).last().or(hit);
|
||||
}
|
||||
let (swatch, tint, plates) = match hit.and_then(|i| own.get(i).map(|o| (i, o))) {
|
||||
Some((i, o)) => {
|
||||
j = i + 1;
|
||||
(o.swatch.clone(), o.tint, o.plates)
|
||||
}
|
||||
None => link_in(own.get(j.saturating_sub(1)..(j + 1).min(own.len())).unwrap_or_default(), p),
|
||||
};
|
||||
stops.push(GradientStop { offset: at + (to - from) * st.offset, swatch, tint, plates, ..st });
|
||||
}
|
||||
}
|
||||
Gradient { stops, method: GradientMethod::Classic, spread: GradientSpread::Pad, repeats: 1, ..g.into_owned() }
|
||||
}
|
||||
|
||||
/// Dash pattern `d` read along subpaths of lengths `lens` turned as `o` says. Reversed, the
|
||||
/// pattern runs backwards: from the start of a dash, that is the dash and then the other entries
|
||||
/// in reverse order. Exact dashes also start where the turned subpaths now start. The pattern
|
||||
/// restarts on every subpath at the one offset, so the offset moves only when every subpath needs
|
||||
/// the same one (as subpaths whose lengths differ by whole periods do); dashes fitted to corners
|
||||
/// ignore the offset, which stays as it is. A dash pattern starts once per subpath, so on a closed
|
||||
/// subpath started elsewhere the dashes match the key's as far as its own start, and past it run
|
||||
/// on without restarting there.
|
||||
fn reorient_dash(d: &mut Dash, o: Orient, lens: &[f64]) {
|
||||
if !d.is_dashed() || !d.offset.is_finite() {
|
||||
return;
|
||||
}
|
||||
let mut pat = d.pattern.clone();
|
||||
// An odd pattern repeats twice per period (dash, gap, dash / gap, dash, gap).
|
||||
if pat.len() % 2 == 1 {
|
||||
pat.extend_from_within(..);
|
||||
}
|
||||
let period: f64 = pat.iter().sum();
|
||||
// Where along the key's own subpath the turned one starts (a closed one wraps round). A
|
||||
// closed one reversed from its own start runs back from its end.
|
||||
let at = match (o.closed, o.seam()) {
|
||||
(true, s) if s == 0.0 && o.reversed => 1.0,
|
||||
(true, s) => s,
|
||||
(false, _) => o.start,
|
||||
};
|
||||
let first = pat.first().copied().unwrap_or(0.0);
|
||||
let offset = |len: f64| if o.reversed { first - at * len - d.offset } else { d.offset + at * len };
|
||||
let offsets: Vec<f64> = lens.iter().map(|&len| offset(len)).collect();
|
||||
let agree = offsets.first().is_some_and(|&a| {
|
||||
offsets.iter().all(|&b| {
|
||||
let r = (b - a).rem_euclid(period);
|
||||
r.is_finite() && r.min(period - r) <= 1e-6
|
||||
})
|
||||
});
|
||||
if o.reversed {
|
||||
if let Some(rest) = pat.get_mut(1..) {
|
||||
rest.reverse();
|
||||
}
|
||||
d.pattern = pat;
|
||||
}
|
||||
if let Some(&off) = offsets.first().filter(|_| agree && !d.align_corners) {
|
||||
d.offset = off;
|
||||
}
|
||||
}
|
||||
|
||||
/// A key's stroke read along its subpaths turned as `o` says (`lens`: their lengths): its width
|
||||
/// profile (whose sides swap when reversed), pen pressure, tilt, bearing and rotation, its dashes,
|
||||
/// a gradient along the path or across it (whose sides swap when reversed). Its arrowheads stay as
|
||||
/// they are.
|
||||
fn reorient_stroke(s: &mut StrokeLayer, o: Orient, lens: &[f64]) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
}
|
||||
if let Some(d) = &mut s.dash {
|
||||
reorient_dash(d, o, lens);
|
||||
}
|
||||
let along = s.gradient_mode == StrokeGradientMode::Along;
|
||||
if s.path_gradient().is_some()
|
||||
&& let Paint::Gradient(g) = &mut s.paint
|
||||
{
|
||||
let start = along && o.seam() > 0.0;
|
||||
if start {
|
||||
g.gradient = gradient_from(&g.gradient, o.seam() as f32);
|
||||
}
|
||||
// Stops that reflect an even number of times read the same either way.
|
||||
let (spread, runs) = g.gradient.painted_spread();
|
||||
let reverse = o.reversed && !(spread == GradientSpread::Reflect && runs % 2 == 0);
|
||||
if reverse {
|
||||
g.gradient.reverse();
|
||||
}
|
||||
if start || reverse {
|
||||
// The turned gradient is no longer the swatch's.
|
||||
g.swatch = None;
|
||||
}
|
||||
}
|
||||
let same = |v: f64| v;
|
||||
if let Some(p) = &mut s.profile {
|
||||
let mut pts: Vec<(f64, (f64, f64))> = p.points.iter().map(|&(t, l, r)| (t, (l, r))).collect();
|
||||
@@ -676,9 +827,11 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
if o.is_identity() {
|
||||
return;
|
||||
}
|
||||
let lens: Vec<f64> =
|
||||
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
|
||||
for it in n.appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
reorient_stroke(s, o);
|
||||
reorient_stroke(s, o, &lens);
|
||||
if o.reversed && !o.closed {
|
||||
std::mem::swap(&mut s.start_arrow, &mut s.end_arrow);
|
||||
s.arrow_scale = (s.arrow_scale.1, s.arrow_scale.0);
|
||||
@@ -687,15 +840,19 @@ fn reorient_strokes(n: &mut Node, o: Orient) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn the strokes of path `n` for Reverse Path Direction, before its subpaths flagged in
|
||||
/// `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its last
|
||||
/// anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and rotation
|
||||
/// then run the new way, so the stroke draws as it did. A stroke reads one profile along every
|
||||
/// subpath, so it turns only when all of them turn alike. Arrowheads stay at the path's start and
|
||||
/// end.
|
||||
/// Turn the strokes of path or compound path `n` for Reverse Path Direction, before its subpaths
|
||||
/// flagged in `reversed` are reversed with [`SubPath::reverse`] (a closed one then starts at its
|
||||
/// last anchor): each stroke's width profile (sides swapped), pen pressure, tilt, bearing and
|
||||
/// rotation then run the new way, so the stroke draws as it did. A compound path's subpaths are
|
||||
/// its members' subpaths in order. A stroke reads one profile along every subpath, so it turns
|
||||
/// only when all of them turn alike. Arrowheads stay at the path's start and end.
|
||||
pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return };
|
||||
let mut turns = path.subpaths.iter().enumerate().map(|(i, sp)| {
|
||||
let subpaths: Vec<&SubPath> = match &n.kind {
|
||||
NodeKind::Path { path, .. } => path.subpaths.iter().collect(),
|
||||
NodeKind::Compound { children, .. } => children.iter().filter_map(|c| c.path_data()).flat_map(|pd| &pd.subpaths).collect(),
|
||||
_ => return,
|
||||
};
|
||||
let mut turns = subpaths.into_iter().enumerate().map(|(i, sp)| {
|
||||
let mut o = Orient::of(sp);
|
||||
if reversed.get(i).copied().unwrap_or(false) {
|
||||
if sp.closed {
|
||||
@@ -709,9 +866,11 @@ pub fn reverse_stroke_records(n: &mut Node, reversed: &[bool]) {
|
||||
if o.is_identity() || !turns.all(|t| t.same_turn(&o)) {
|
||||
return;
|
||||
}
|
||||
let lens: Vec<f64> =
|
||||
node_path(n).map(|(p, ..)| p.subpaths.iter().map(|sp| PathData::new(vec![sp.clone()]).length()).collect()).unwrap_or_default();
|
||||
for it in n.appearance.items.iter_mut() {
|
||||
if let AppearanceItem::Stroke(s) = it {
|
||||
reorient_stroke(s, o);
|
||||
reorient_stroke(s, o, &lens);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2791,6 +2950,275 @@ mod tests {
|
||||
assert!((rot(0.5, 0.499) - rot(0.5, 0.501)).abs() < 1.0, "no jump where the key started: {:?}", stroke(&blend.at(0.5)).rotation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere() {
|
||||
let keyed = |path: PathData, edit: &dyn Fn(&mut StrokeLayer)| {
|
||||
let mut ap = Appearance::default();
|
||||
ap.set_stroke(Paint::solid(Color::BLACK));
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
edit(s);
|
||||
}
|
||||
Node::path(NodeId(1), path, ap)
|
||||
};
|
||||
let stroke = |n: &Node| n.appearance.stroke().cloned().unwrap_or_else(|| panic!("a stroke"));
|
||||
// How light the stroke's gradient is at `u` (0 black, 3 white).
|
||||
let light = |s: &StrokeLayer, u: f32| match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.sample(u).0.to_rgb().iter().sum::<f32>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
// Whether dash pattern `d` draws a dash `at` this far along its subpath.
|
||||
let dash_at = |d: &Dash, at: f64| {
|
||||
let p = if d.pattern.len() % 2 == 1 { d.pattern.repeat(2) } else { d.pattern.clone() };
|
||||
let mut x = (at + d.offset).rem_euclid(p.iter().sum());
|
||||
for (i, v) in p.iter().enumerate() {
|
||||
if x < *v {
|
||||
return i % 2 == 0;
|
||||
}
|
||||
x -= v;
|
||||
}
|
||||
false
|
||||
};
|
||||
let graded = |mode: StrokeGradientMode| {
|
||||
move |s: &mut StrokeLayer| {
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default())));
|
||||
s.gradient_mode = mode;
|
||||
s.dash = Some(Dash { pattern: vec![1.0, 2.0, 3.0, 1.5], offset: 0.75, align_corners: false });
|
||||
}
|
||||
};
|
||||
// An open key clicked at its last anchor runs the other way: a gradient along it or across
|
||||
// it (whose sides swap) runs the other way too, and its dashes are read from its end.
|
||||
let line = |x: f64| PathData::single(SubPath::polyline(&[Point::new(x, 0.0), Point::new(x + 13.0, 0.0)], false));
|
||||
let plain = keyed(line(0.0), &|_| {});
|
||||
for mode in [StrokeGradientMode::Along, StrokeGradientMode::Across] {
|
||||
let key = keyed(line(100.0), &graded(mode));
|
||||
let s = stroke(&Lerp::new(&plain, &key, (None, Some(1))).at(1.0));
|
||||
assert!(light(&s, 0.0) < 0.01 && light(&s, 1.0) > 2.99, "{mode:?}: {:?}", s.paint);
|
||||
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
|
||||
for k in 1..130 {
|
||||
let u = k as f64 / 10.0 + 0.03;
|
||||
assert_eq!(dash_at(&d, u), dash_at(&own, 13.0 - u), "at {u}: {d:?}");
|
||||
}
|
||||
}
|
||||
// A closed key started half way round starts its gradient along it there too, stepping
|
||||
// where its own start was, and its dashes start there.
|
||||
let square = |x: f64| shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
let key = keyed(square(100.0), &graded(StrokeGradientMode::Along));
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &key, (Some(0), Some(2))).at(1.0));
|
||||
for (u, want) in [(0.0, 1.5), (0.25, 0.75), (0.499, 0.0), (0.501, 3.0), (0.75, 2.25), (1.0, 1.5)] {
|
||||
assert!((light(&s, u) - want).abs() < 0.02, "at {u}: {} for {want}: {:?}", light(&s, u), s.paint);
|
||||
}
|
||||
let (own, d) = (stroke(&key).dash.unwrap_or_default(), s.dash.unwrap_or_default());
|
||||
for k in 1..200 {
|
||||
let u = k as f64 / 10.0 + 0.03;
|
||||
assert_eq!(dash_at(&d, u), dash_at(&own, u + 20.0), "at {u}: {d:?}");
|
||||
}
|
||||
// A closed key that winds the other way runs the other way from the same anchor: its
|
||||
// dashes are read back from the end of its own subpath, which is 40 long and not a whole
|
||||
// number of periods.
|
||||
let wound = |x: f64| {
|
||||
let mut p = square(x);
|
||||
for sp in &mut p.subpaths {
|
||||
sp.reverse();
|
||||
}
|
||||
p
|
||||
};
|
||||
let back = keyed(wound(100.0), &graded(StrokeGradientMode::Along));
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &back, (Some(0), Some(0))).at(1.0));
|
||||
let (own, d) = (stroke(&back).dash.unwrap_or_default(), s.dash.unwrap_or_default());
|
||||
for k in 1..400 {
|
||||
let u = k as f64 / 10.0 + 0.03;
|
||||
assert_eq!(dash_at(&d, u), dash_at(&own, 40.0 - u), "at {u}: {d:?}");
|
||||
}
|
||||
// Stops that reflect twice read the same either way; a link to a swatch stays.
|
||||
let reflected = keyed(line(100.0), &|s| {
|
||||
let mut g = Gradient { spread: GradientSpread::Reflect, repeats: 2, ..Gradient::default() };
|
||||
g.stops[1].swatch = Some("Ink".into());
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
assert_eq!(stroke(&Lerp::new(&plain, &reflected, (None, Some(1))).b).paint, stroke(&reflected).paint);
|
||||
let linked = keyed(square(100.0), &|s| {
|
||||
let mut g = Gradient::default();
|
||||
g.stops[1].swatch = Some("Ink".into());
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &linked, (Some(0), Some(2))).b);
|
||||
let links = match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some("Ink")).map(|st| st.offset).collect::<Vec<_>>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert!(links.contains(&0.5), "the stop the old start ended on keeps its link: {:?}", s.paint);
|
||||
// Each stop of a step keeps its own link.
|
||||
let step = keyed(square(100.0), &|s| {
|
||||
let mut g = Gradient::default();
|
||||
let (mut before, mut after) = (GradientStop::new(0.25, Color::BLACK), GradientStop::new(0.25, Color::WHITE));
|
||||
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
|
||||
g.stops.splice(1..1, [before, after]);
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &step, (Some(0), Some(2))).b);
|
||||
let links = match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.offset == 0.75).map(|st| st.swatch.clone()).collect::<Vec<_>>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert_eq!(links, vec![Some("Ink".into()), Some("Paper".into())], "{:?}", s.paint);
|
||||
// A step of one color between two swatches, where the turned subpath now starts: the
|
||||
// start takes the link after the step and the end the link before it.
|
||||
let seam_step = keyed(square(100.0), &|s| {
|
||||
let mut g = Gradient::default();
|
||||
let gray = Color::rgb8(128, 128, 128);
|
||||
let (mut before, mut after) = (GradientStop::new(0.5, gray), GradientStop::new(0.5, gray));
|
||||
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
|
||||
g.stops.splice(1..1, [before, after]);
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &seam_step, (Some(0), Some(2))).b);
|
||||
let ends = match &s.paint {
|
||||
Paint::Gradient(g) => (g.gradient.stops.first().map(|st| st.swatch.clone()), g.gradient.stops.last().map(|st| st.swatch.clone())),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert_eq!(ends, (Some(Some("Paper".into())), Some(Some("Ink".into()))), "{:?}", s.paint);
|
||||
// A hue gradient that reflects keeps its links on the repeated stops.
|
||||
let hue = keyed(square(100.0), &|s| {
|
||||
let (mut red, mut blue) =
|
||||
(GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }));
|
||||
(red.swatch, blue.swatch) = (Some("Ink".into()), Some("Paper".into()));
|
||||
let g = Gradient {
|
||||
method: GradientMethod::HueClockwise,
|
||||
spread: GradientSpread::Reflect,
|
||||
repeats: 2,
|
||||
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![red, blue])
|
||||
};
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue, (Some(0), Some(2))).b);
|
||||
let linked = |name: &str| match &s.paint {
|
||||
Paint::Gradient(g) => g.gradient.stops.iter().filter(|st| st.swatch.as_deref() == Some(name)).map(|st| st.offset).collect::<Vec<_>>(),
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert!(linked("Paper").contains(&0.0) && linked("Paper").contains(&1.0), "{:?}", s.paint);
|
||||
assert!(linked("Ink").contains(&0.5), "{:?}", s.paint);
|
||||
// Two stops of one color at one place keep their own links, in reverse in a mirrored run.
|
||||
let hue_step = keyed(square(100.0), &|s| {
|
||||
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
|
||||
let (mut before, mut after) = (GradientStop::new(0.5, green), GradientStop::new(0.5, green));
|
||||
(before.swatch, after.swatch) = (Some("Ink".into()), Some("Paper".into()));
|
||||
let stops = vec![
|
||||
GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }),
|
||||
before,
|
||||
after,
|
||||
GradientStop::new(1.0, Color::Rgb { r: 0.0, g: 0.0, b: 1.0 }),
|
||||
];
|
||||
let g = Gradient {
|
||||
method: GradientMethod::HueClockwise,
|
||||
spread: GradientSpread::Reflect,
|
||||
repeats: 2,
|
||||
..Gradient::new(vectorcraft_color::GradientKind::Linear, stops)
|
||||
};
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_step, (Some(0), Some(2))).b);
|
||||
// The links at `u` in order, a link repeated by the next stop listed once.
|
||||
let links_at = |u: f32| match &s.paint {
|
||||
Paint::Gradient(g) => {
|
||||
let mut links =
|
||||
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
|
||||
links.dedup();
|
||||
links
|
||||
}
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert_eq!(links_at(0.25), vec!["Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
|
||||
assert_eq!(links_at(0.75), vec!["Ink".to_string(), "Paper".to_string()], "{:?}", s.paint);
|
||||
// Where two runs meet, each run's stops keep their own links.
|
||||
let hue_end = keyed(square(100.0), &|s| {
|
||||
let green = Color::Rgb { r: 0.0, g: 1.0, b: 0.0 };
|
||||
let (mut a, mut b) = (GradientStop::new(1.0, green), GradientStop::new(1.0, green));
|
||||
(a.swatch, b.swatch) = (Some("Ink".into()), Some("Paper".into()));
|
||||
let g = Gradient {
|
||||
method: GradientMethod::HueClockwise,
|
||||
spread: GradientSpread::Reflect,
|
||||
repeats: 2,
|
||||
..Gradient::new(vectorcraft_color::GradientKind::Linear, vec![GradientStop::new(0.0, Color::Rgb { r: 1.0, g: 0.0, b: 0.0 }), a, b])
|
||||
};
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&keyed(square(0.0), &|_| {}), &hue_end, (Some(0), Some(1))).b);
|
||||
let links_at = |u: f32| match &s.paint {
|
||||
Paint::Gradient(g) => {
|
||||
let mut links =
|
||||
g.gradient.stops.iter().filter(|st| (st.offset - u).abs() < 1e-4).filter_map(|st| st.swatch.clone()).collect::<Vec<_>>();
|
||||
links.dedup();
|
||||
links
|
||||
}
|
||||
p => panic!("a gradient: {p:?}"),
|
||||
};
|
||||
assert_eq!(links_at(0.25), vec!["Ink".to_string(), "Paper".to_string(), "Ink".to_string()], "{:?}", s.paint);
|
||||
// Blended with a gradient of other stops, the steps keep that step.
|
||||
let three = keyed(square(0.0), &|s| {
|
||||
let mut g = Gradient::default();
|
||||
g.stops.insert(1, GradientStop::new(0.5, Color::BLACK));
|
||||
s.paint = Paint::Gradient(Box::new(GradientPaint::new(g)));
|
||||
s.gradient_mode = StrokeGradientMode::Along;
|
||||
});
|
||||
let s = stroke(&Lerp::new(&three, &key, (Some(0), Some(2))).at(0.75));
|
||||
assert!(light(&s, 0.501) - light(&s, 0.499) > 1.5, "{:?}", s.paint);
|
||||
// Subpaths whose lengths call for different dash offsets keep the offset.
|
||||
let rings = |x: f64, turn: usize| {
|
||||
let mut inner = shapes::rectangle(Rect::new(x, 20.0, x + 7.0, 27.0)).subpaths.remove(0);
|
||||
inner.anchors.rotate_left(turn);
|
||||
PathData::new(vec![square(x).subpaths.remove(0), inner])
|
||||
};
|
||||
let key = keyed(rings(100.0, 2), &graded(StrokeGradientMode::Along));
|
||||
let blend = Lerp::new(&keyed(rings(0.0, 0), &|_| {}), &key, (Some(0), Some(2)));
|
||||
let turned = match &blend.shape {
|
||||
Shape::Path { pair, .. } => pair.orient.1,
|
||||
_ => panic!("a path blend"),
|
||||
};
|
||||
assert!((turned.seam() - 0.5).abs() < 1e-9, "both rings turn half way round: {turned:?}");
|
||||
let s = stroke(&blend.at(1.0));
|
||||
assert_eq!(s.dash.map(|d| d.offset), Some(0.75));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradients_of_other_stop_counts_keep_their_steps() {
|
||||
let red = Color::Rgb { r: 1.0, g: 0.0, b: 0.0 };
|
||||
let stepped = Gradient::new(
|
||||
vectorcraft_color::GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop::new(0.0, Color::WHITE),
|
||||
GradientStop::new(0.5, Color::BLACK),
|
||||
GradientStop::new(0.5, Color::WHITE),
|
||||
GradientStop::new(0.50015, red),
|
||||
GradientStop::new(1.0, Color::BLACK),
|
||||
],
|
||||
);
|
||||
let (a, b) = common_stops(&stepped, &Gradient::default()).unwrap_or_else(|| panic!("one kind"));
|
||||
let at = |g: &Gradient| g.stops.iter().map(|s| (s.offset, s.color)).collect::<Vec<_>>();
|
||||
assert_eq!(at(&a), vec![(0.0, Color::WHITE), (0.5, Color::BLACK), (0.5, Color::WHITE), (0.50015, red), (1.0, Color::BLACK)]);
|
||||
assert_eq!(b.stops.len(), 5);
|
||||
assert_eq!(b.stops.get(1).map(|s| s.color), b.stops.get(2).map(|s| s.color), "a gradient without the step paints one color there");
|
||||
// A gradient with two stops close to the other's step, but no step of its own, does not step there.
|
||||
let close = Gradient::new(
|
||||
vectorcraft_color::GradientKind::Linear,
|
||||
vec![
|
||||
GradientStop::new(0.0, Color::WHITE),
|
||||
GradientStop::new(0.5, Color::BLACK),
|
||||
GradientStop::new(0.50005, red),
|
||||
GradientStop::new(1.0, Color::BLACK),
|
||||
],
|
||||
);
|
||||
let (_, b) = common_stops(&stepped, &close).unwrap_or_else(|| panic!("one kind"));
|
||||
assert_eq!(b.stops.get(1).map(|s| s.color), Some(Color::BLACK));
|
||||
assert_eq!(b.stops.get(2).map(|s| s.color), Some(Color::BLACK), "{:?}", b.stops);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn odd_dash_blends_to_solid_with_closed_gaps() {
|
||||
let d = lerp_dash(Some(&Dash { pattern: vec![2.0, 3.0, 4.0], ..Default::default() }), None, 1.0).unwrap();
|
||||
|
||||
+1097
-77
File diff suppressed because it is too large
Load Diff
+54
-27
@@ -379,6 +379,22 @@ pub struct SeriesPaint {
|
||||
/// Object blend mode of each path directly in the series group, as [`Self::opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Object opacity (0..1) of the series group itself, taken from the transparency set on the group. Absent: fully opaque.
|
||||
/// Graph labels keep none.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_opacity: Option<f32>,
|
||||
/// Object blend mode of the series group itself, as [`Self::group_opacity`]. Absent: Normal.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_blend: Option<vectorcraft_color::BlendMode>,
|
||||
/// Isolate Blending of the series group itself, as [`Self::group_opacity`]. Absent: off.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub group_isolate: bool,
|
||||
/// Knockout Group state of the series group itself, as [`Self::group_opacity`]. Absent: neutral.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub group_knockout: Option<crate::Knockout>,
|
||||
/// Knockout Shape of the series group itself, as [`Self::group_opacity`]. Absent: off.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
pub group_knockout_shape: bool,
|
||||
/// A gradient in [`Self::fill`] is placed relative to the unit box (0, 0)–(1, 1), and each mark takes it on its own
|
||||
/// geometric bounds. False: the gradient is in document coordinates, and every mark takes it unchanged.
|
||||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||||
@@ -527,7 +543,7 @@ pub struct GraphSpec {
|
||||
/// Bounds of the art when it was last generated (detects moves/scales of the graph group).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed: Option<Rect>,
|
||||
/// Bounds of the art other than type when it was last generated ([`art_bounds`]). Moves and scales of the graph
|
||||
/// Bounds of the art other than type when it was last generated ([`graph_art_without_type`]). Moves and scales of the graph
|
||||
/// group are measured on these when present; graphs saved without them are measured on [`Self::placed`].
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub placed_art: Option<Rect>,
|
||||
@@ -546,6 +562,43 @@ fn edge_to_edge_before_the_option() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn graph_art_without_type(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| without_type(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether its own geometric bounds depend on that type. A
|
||||
/// group without such type gives its own bounds, and a clipping group whose clip does not depend on type gives the
|
||||
/// bounds of its clip. Objects other than groups, layers and compound paths, blends, envelopes and repeats among them,
|
||||
/// give their own bounds.
|
||||
fn without_type(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
use crate::NodeKind::{Compound, Group, Layer, Text};
|
||||
if matches!(n.kind, Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let children: &[std::sync::Arc<crate::Node>] = match &n.kind {
|
||||
Group { clip: true, children } | Layer { clip: true, children, .. } => children,
|
||||
Group { .. } | Layer { .. } | Compound { .. } => n.editing_children(),
|
||||
_ => return (n.geometric_bounds(), false),
|
||||
};
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
let mut clip_has_type = false;
|
||||
let hidden_layer_member = |c: &crate::Node| !c.visible && matches!(n.kind, Layer { clip: false, .. });
|
||||
for (i, c) in children.iter().enumerate().filter(|(_, c)| !hidden_layer_member(c)) {
|
||||
let (b, t) = without_type(c);
|
||||
had_type |= t;
|
||||
clip_has_type |= i == 0 && t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
let clip = matches!(n.kind, Group { clip: true, .. } | Layer { clip: true, .. });
|
||||
if had_type && (!clip || clip_has_type) { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl GraphSpec {
|
||||
/// The type series `s` is drawn as: its own type when it combines with the graph's, else the graph's.
|
||||
pub fn series_kind(&self, s: usize) -> GraphKind {
|
||||
@@ -614,32 +667,6 @@ impl GraphSpec {
|
||||
}
|
||||
}
|
||||
|
||||
/// The geometric bounds of a graph's art `children` leaving out their type: the plot, axes, tick marks and legend
|
||||
/// swatches without the labels. None when there is nothing else. [`GraphSpec::placed_art`] keeps these.
|
||||
pub fn art_bounds(children: &[std::sync::Arc<crate::Node>]) -> Option<Rect> {
|
||||
children.iter().filter_map(|c| art_bounds_of(c).0).reduce(|a, b| a.union(b))
|
||||
}
|
||||
|
||||
/// The geometric bounds of `n` leaving out the type in it, and whether there was type to leave out. A group without type
|
||||
/// gives its own bounds, so a clipping group gives the bounds of its clip.
|
||||
fn art_bounds_of(n: &crate::Node) -> (Option<Rect>, bool) {
|
||||
if matches!(n.kind, crate::NodeKind::Text(_)) {
|
||||
return (None, true);
|
||||
}
|
||||
let Some(children) = n.children() else { return (n.geometric_bounds(), false) };
|
||||
let mut bounds: Option<Rect> = None;
|
||||
let mut had_type = false;
|
||||
for c in children {
|
||||
let (b, t) = art_bounds_of(c);
|
||||
had_type |= t;
|
||||
bounds = match (bounds, b) {
|
||||
(Some(a), Some(b)) => Some(a.union(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
if had_type { (bounds, true) } else { (n.geometric_bounds(), false) }
|
||||
}
|
||||
|
||||
impl Default for GraphSpec {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
|
||||
+376
-88
@@ -1,7 +1,7 @@
|
||||
//! Hit testing over the document tree.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
@@ -279,13 +279,16 @@ pub fn selected_hidden_at(doc: &Document, p: Point, opt: HitOptions, selected: &
|
||||
return false;
|
||||
}
|
||||
// How a click reaches it, if one does.
|
||||
let start = opt;
|
||||
let Some(opt) = path_options(&nodes, &chain, opt) else { return false };
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`.
|
||||
let masked = nodes
|
||||
.iter()
|
||||
.rev()
|
||||
.skip(1)
|
||||
.any(|n| n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p)));
|
||||
// Hidden by a mask: one of the containers around it clips, and not to `p`. A container
|
||||
// tests its clipping path in outline from the first layer with Preview off down to it, as
|
||||
// a click going down to it does ([`path_options`]).
|
||||
let below = start.scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
let masked = nodes.iter().enumerate().rev().skip(1).any(|(k, n)| {
|
||||
let outline = start.outline || nodes.get(below..=k).is_some_and(|ns| ns.iter().any(|n| previews_off(n)));
|
||||
n.clips() && n.children().and_then(|c| c.first()).is_some_and(|clip| clip.id != id && !clip_contains(clip, p, outline))
|
||||
});
|
||||
// A click may reach it there ([`may_hit`]: not a guide while guides are locked or
|
||||
// hidden, nor a Shaper group's hidden part), and its own art is what a click would hit
|
||||
// in it: a group's hidden, locked or masked contents don't count.
|
||||
@@ -359,6 +362,7 @@ pub fn objects_at(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeI
|
||||
/// measured by their art ([`Node::geometric_bounds_with`]).
|
||||
fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, tops: &mut Vec<NodeId>, seen: &mut HashSet<NodeId>) -> bool {
|
||||
let Some(children) = layer.children() else { return true };
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
if layer.clips()
|
||||
&& let Some(clip) = children.first()
|
||||
{
|
||||
@@ -366,11 +370,10 @@ fn objects_at_layer(layer: &Node, p: Point, opt: HitOptions, symbols: &SymbolBox
|
||||
if clip_outline_hit(layer, clip, p, opt, symbols, true).is_some() && seen.insert(clip.id) {
|
||||
tops.push(clip.id);
|
||||
}
|
||||
if !clip_contains(clip, p) {
|
||||
if !clip_contains(clip, p, opt.outline) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
let opt = if matches!(layer.kind, NodeKind::Layer { preview: false, .. }) { HitOptions { outline: true, ..opt } } else { opt };
|
||||
for (i, c) in children.iter().enumerate().rev() {
|
||||
if !may_hit(layer, i, c, p, opt, symbols, true) || seen.contains(&c.id) {
|
||||
continue;
|
||||
@@ -452,7 +455,7 @@ pub fn locked_objects_at(doc: &Document, p: Point, opt: HitOptions) -> Vec<NodeI
|
||||
/// whole, and an unlocked layer, group, blend or envelope in Edit Contents is searched inside.
|
||||
fn locked_children(parent: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes, out: &mut Vec<NodeId>) {
|
||||
let Some(children) = parent.children() else { return };
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p)) {
|
||||
if parent.clips() && !edits_inside(parent, opt.scope) && children.first().is_some_and(|clip| !clip_contains(clip, p, opt.outline)) {
|
||||
return;
|
||||
}
|
||||
for i in hit_order(parent, children, p) {
|
||||
@@ -561,14 +564,170 @@ fn edits_contents(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Envelope { editing: true, .. })
|
||||
}
|
||||
|
||||
/// Is `p` inside the region `clip` clips to ([`Node::clip_shapes`])? Text counts by its frame:
|
||||
/// glyph outlines need the font engine, above this crate.
|
||||
fn clip_contains(clip: &Node, p: Point) -> bool {
|
||||
clip_regions(clip).iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
/// Is `p` inside the region `clip` clips to ([`clip_areas`])? In outline mode ([`HitOptions::outline`])
|
||||
/// the canvas draws no effects, so the plain shapes of `clip` ([`clip_regions`]) count.
|
||||
fn clip_contains(clip: &Node, p: Point, outline: bool) -> bool {
|
||||
let areas = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
areas.iter().any(|(bp, rule)| fill_contains(bp, *rule, p))
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to ([`Node::clip_shapes`]), text counted by its frame as in
|
||||
/// [`clip_contains`].
|
||||
/// The region of a clip group's clipping path as the canvas clips by it, with the live geometry
|
||||
/// effects of the clipping path and of what it clips by applied, as one path and fill rule
|
||||
/// (`Some(None)` when nothing is left to clip by). `None` when nothing in the clipping path has a
|
||||
/// live geometry effect: its plain shapes ([`clip_regions`]) count then. Effects are evaluated
|
||||
/// above this crate, so the engine registers one with [`set_clip_region`].
|
||||
pub type ClipRegion = fn(&Node) -> Option<Option<(BezPath, FillRule)>>;
|
||||
|
||||
static CLIP_REGION: OnceLock<ClipRegion> = OnceLock::new();
|
||||
|
||||
/// Register how the region of a clipping path with live effects is found (the first registration
|
||||
/// stays).
|
||||
pub fn set_clip_region(f: ClipRegion) {
|
||||
// Already set: the same engine, registered by another session.
|
||||
let _ = CLIP_REGION.set(f);
|
||||
}
|
||||
|
||||
/// Does `clip`, or anything it holds, have a visible effect of its own or on a fill or stroke? Only
|
||||
/// then can the registered [`ClipRegion`] find a geometry effect in it.
|
||||
fn has_effects(clip: &Node) -> bool {
|
||||
let mut found = false;
|
||||
clip.walk(&mut |n| {
|
||||
let visible = |e: &crate::Effect| e.visible;
|
||||
found |= n.appearance.effects.iter().any(visible) || n.appearance.items.iter().any(|i| i.effects().iter().any(visible));
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// A clipping path's region evaluated by [`clip_region`] on this thread: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the region (`None` without geometry effects) and the number of its
|
||||
/// path elements.
|
||||
struct EvaluatedClip {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
region: Option<Rc<Option<(BezPath, FillRule)>>>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many regions [`clip_region`] keeps on each thread: every click and every hover over a clip
|
||||
/// group whose clipping path has live effects asks for its region, and clip groups can be nested.
|
||||
const CLIPS_KEPT: usize = 16;
|
||||
|
||||
thread_local! {
|
||||
/// The regions [`clip_region`] keeps, the latest first.
|
||||
static CLIPS: RefCell<Vec<EvaluatedClip>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many regions [`clip_region`] evaluated on this thread.
|
||||
static CLIPS_EVALUATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The region clipping path `clip` clips to with its live geometry effects applied
|
||||
/// ([`set_clip_region`]), or `None` when it has none or nothing is registered; its plain shapes
|
||||
/// ([`clip_regions`]) are the region then. The region is evaluated again when `clip` or the
|
||||
/// [`LiveInputs`] have changed since.
|
||||
fn clip_region(clip: &Node) -> Option<Rc<Option<(BezPath, FillRule)>>> {
|
||||
let f = CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIPS.with_borrow_mut(|kept| {
|
||||
let i = kept.iter().position(|e| e.inputs == inputs && e.clip == *clip)?;
|
||||
let e = kept.remove(i);
|
||||
let region = e.region.clone();
|
||||
kept.insert(0, e);
|
||||
Some(region)
|
||||
});
|
||||
if let Some(region) = kept {
|
||||
return region;
|
||||
}
|
||||
#[cfg(test)]
|
||||
CLIPS_EVALUATED.with(|c| c.set(c.get() + 1));
|
||||
let region = f(clip).map(Rc::new);
|
||||
let elements = region.as_deref().and_then(Option::as_ref).map_or(0, |(bp, _)| bp.elements().len());
|
||||
let size = elements.saturating_add(art_size(std::slice::from_ref(clip)));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
let e = EvaluatedClip { clip: clip.clone(), inputs, region: region.clone(), size };
|
||||
CLIPS.with_borrow_mut(|kept| {
|
||||
kept.insert(0, e);
|
||||
kept.truncate(CLIPS_KEPT);
|
||||
let mut total = 0usize;
|
||||
kept.retain(|e| {
|
||||
total = total.saturating_add(e.size);
|
||||
total <= LIVE_KEPT_SIZE
|
||||
});
|
||||
});
|
||||
}
|
||||
region
|
||||
}
|
||||
|
||||
/// The box of a clipping path's region found by [`reshaped_clip_box`]: the clipping path and the
|
||||
/// [`LiveInputs`] as they were, the box and the [`art_size`] of the clipping path.
|
||||
struct ClipBox {
|
||||
clip: Node,
|
||||
inputs: u64,
|
||||
rect: Option<Rect>,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
/// How many boxes [`reshaped_clip_box`] keeps on each thread. Every pointer move measures every clip
|
||||
/// group it passes, so the boxes of all of a document's clip groups with live effects are kept, not
|
||||
/// only the latest few as with the regions.
|
||||
const CLIP_BOXES_KEPT: usize = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The boxes [`reshaped_clip_box`] keeps, by clipping path, and the sum of their sizes.
|
||||
static CLIP_BOXES: RefCell<(HashMap<NodeId, ClipBox>, usize)> = RefCell::new((HashMap::new(), 0));
|
||||
}
|
||||
|
||||
/// The box of the region `clip` clips to with its live geometry effects applied ([`clip_region`]),
|
||||
/// `None` when it has none or no region. The box is kept until `clip` or the [`LiveInputs`] change.
|
||||
/// When the boxes kept are full, a new box replaces as many others as it needs room for, so the
|
||||
/// pointer moving over more clip groups than fit still finds most of their boxes.
|
||||
pub(crate) fn reshaped_clip_box(clip: &Node) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
CLIP_REGION.get()?;
|
||||
if !has_effects(clip) {
|
||||
return None;
|
||||
}
|
||||
let inputs = live_inputs();
|
||||
let kept = CLIP_BOXES.with_borrow(|(boxes, _)| boxes.get(&clip.id).filter(|b| b.inputs == inputs && b.clip == *clip).map(|b| b.rect));
|
||||
if let Some(rect) = kept {
|
||||
return rect;
|
||||
}
|
||||
let rect = clip_region(clip).and_then(|r| r.as_ref().as_ref().filter(|(bp, _)| !bp.elements().is_empty()).map(|(bp, _)| bp.bounding_box()));
|
||||
let size = art_size(std::slice::from_ref(clip));
|
||||
if size <= LIVE_KEPT_SIZE {
|
||||
CLIP_BOXES.with_borrow_mut(|(boxes, total)| {
|
||||
if let Some(old) = boxes.remove(&clip.id) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
while boxes.len() >= CLIP_BOXES_KEPT || total.saturating_add(size) > LIVE_KEPT_SIZE {
|
||||
let Some(other) = boxes.keys().next().copied() else { break };
|
||||
if let Some(old) = boxes.remove(&other) {
|
||||
*total = total.saturating_sub(old.size);
|
||||
}
|
||||
}
|
||||
boxes.insert(clip.id, ClipBox { clip: clip.clone(), inputs, rect, size });
|
||||
*total = total.saturating_add(size);
|
||||
});
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
/// The regions a click inside a clip group must fall in: those `clip` clips to with its live
|
||||
/// effects applied, as the canvas clips ([`clip_region`]), else its plain shapes ([`clip_regions`]).
|
||||
fn clip_areas(clip: &Node) -> Vec<(BezPath, FillRule)> {
|
||||
match clip_region(clip) {
|
||||
Some(region) => region.as_ref().iter().cloned().collect(),
|
||||
None => clip_regions(clip),
|
||||
}
|
||||
}
|
||||
|
||||
/// The regions `clip` clips to by its plain shapes ([`Node::clip_shapes`]), without its live
|
||||
/// effects. Text counts by its frame: glyph outlines need the font engine, above this crate.
|
||||
pub fn clip_regions(clip: &Node) -> Vec<(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)> {
|
||||
let frame = |n: &Node| {
|
||||
let b = n.geometric_bounds()?;
|
||||
@@ -698,7 +857,7 @@ fn hit_children(
|
||||
// Elsewhere a clip group (or a layer with a clipping mask) only hits inside it, except for
|
||||
// the selection tools in isolation mode within it.
|
||||
let edited = opt.clip_outlines && editable_only && edits_inside(parent, opt.scope);
|
||||
if !edited && !clip_contains(clip, p) {
|
||||
if !edited && !clip_contains(clip, p, opt.outline) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
@@ -960,7 +1119,7 @@ fn hit_any(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option
|
||||
match &n.kind {
|
||||
// A clip group only hits inside its clipping path.
|
||||
NodeKind::Group { children, clip } => {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p)) {
|
||||
if *clip && children.first().is_some_and(|c| !clip_contains(c, p, opt.outline)) {
|
||||
return None;
|
||||
}
|
||||
children.iter().rev().find_map(|c| hit_any(c, p, opt, symbols))
|
||||
@@ -1048,7 +1207,9 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node {
|
||||
/// group's original shapes, which the canvas does not draw, and guide paths with
|
||||
/// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice
|
||||
/// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not
|
||||
/// draw. `None` when `inst` is not a symbol instance or no editable object of its art is under `p`.
|
||||
/// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a
|
||||
/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or
|
||||
/// no editable object of its art is under `p`.
|
||||
pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option<Vec<u32>> {
|
||||
struct Find<'a> {
|
||||
art: &'a InstanceArt<'a>,
|
||||
@@ -1057,35 +1218,34 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
symbols: &'a SymbolBoxes<'a>,
|
||||
}
|
||||
impl Find<'_> {
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, self.opt, self.symbols).is_some())
|
||||
fn hit(&self, n: &Node, whole: Option<vectorcraft_geom::Affine>, opt: HitOptions) -> bool {
|
||||
self.art.place(n, whole).is_some_and(|n| hit_any(&n, self.p, opt, self.symbols).is_some())
|
||||
}
|
||||
fn skips_guide(&self, n: &Node) -> bool {
|
||||
self.opt.skip_guides && matches!(n.kind, NodeKind::Path { guide: true, .. })
|
||||
}
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>) -> bool {
|
||||
/// `outline`: the view is in Outline, or a layer around `n` has Preview off.
|
||||
fn find(&self, n: &Node, path: &mut Vec<u32>, whole: Option<vectorcraft_geom::Affine>, outline: bool) -> bool {
|
||||
if !n.visible || n.locked || n.is_template() || self.skips_guide(n) {
|
||||
return false;
|
||||
}
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole) };
|
||||
let outline = outline || previews_off(n);
|
||||
let opt = HitOptions { outline, ..self.opt };
|
||||
let (NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }) = &n.kind else { return self.hit(n, whole, opt) };
|
||||
if path.len() >= crate::symbol_overrides::MAX_PATH_DEPTH {
|
||||
return self.hit(n, whole);
|
||||
return self.hit(n, whole, opt);
|
||||
}
|
||||
let whole = self.art.whole(n, whole);
|
||||
if n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
{
|
||||
let Some(clip) = self.art.place_unclipped(first, whole) else { return false };
|
||||
if self.opt.clip_outlines
|
||||
&& first.visible
|
||||
&& !first.locked
|
||||
&& !self.skips_guide(first)
|
||||
&& clip_outline(&clip, self.p, self.opt).is_some()
|
||||
if self.opt.clip_outlines && first.visible && !first.locked && !self.skips_guide(first) && clip_outline(&clip, self.p, opt).is_some()
|
||||
{
|
||||
path.push(0);
|
||||
return true;
|
||||
}
|
||||
if !clip_contains(&clip, self.p) {
|
||||
if !clip_contains(&clip, self.p, outline) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1256,7 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
}
|
||||
let Ok(i) = u32::try_from(i) else { continue };
|
||||
path.push(i);
|
||||
if self.find(c, path, whole) {
|
||||
if self.find(c, path, whole, outline) {
|
||||
return true;
|
||||
}
|
||||
path.pop();
|
||||
@@ -1107,7 +1267,17 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut path = vec![];
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None).then_some(path)
|
||||
let outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
Find { art: &art, p, opt, symbols: &symbols }.find(&art.art, &mut path, None, outline).then_some(path)
|
||||
}
|
||||
|
||||
/// Is `n` below a layer whose Preview is off, so that the canvas draws it in outline? As for clicks
|
||||
/// ([`path_options`]), the Preview of the isolated container `scope` and of the layers around it
|
||||
/// does not count.
|
||||
fn below_preview_off(doc: &Document, n: &Node, scope: Option<NodeId>) -> bool {
|
||||
let Some(chain) = doc.ancestry(n.id) else { return false };
|
||||
let below = scope.and_then(|s| chain.iter().position(|a| *a == s)).map_or(0, |i| i + 1);
|
||||
chain.iter().skip(below).any(|a| doc.node(*a).is_some_and(previews_off))
|
||||
}
|
||||
|
||||
/// The outlines of the object at `path` in symbol instance `inst`'s art (see [`symbol_part_at`]),
|
||||
@@ -1116,11 +1286,23 @@ pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) ->
|
||||
/// group per cell) they are cut to the bounds of the group's clip path, which is not outlined. An
|
||||
/// object inside a clip group or a clipping layer of the art, other than its clipping path, is cut
|
||||
/// to the bounds of that clipping path as well, which contain the region where [`symbol_part_at`]
|
||||
/// picks it.
|
||||
/// picks it: the bounds of the region its live geometry effects give it ([`clip_region`]) when it
|
||||
/// has any.
|
||||
/// `None` for art past the 9-slice object limit that [`symbol_part_at`] applies.
|
||||
pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<BezPath> {
|
||||
symbol_part_outline_in_view(doc, inst, path, HitOptions::default())
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] in the view the canvas shows, for the clicks of `opt`: in Outline view
|
||||
/// ([`HitOptions::outline`]) and below a layer whose Preview is off, in the art or around the
|
||||
/// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the
|
||||
/// outlines are cut to the bounds of the plain clipping paths, without their live effects, as
|
||||
/// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around
|
||||
/// the object leave no region.
|
||||
pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option<BezPath> {
|
||||
let art = InstanceArt::of(doc, inst)?;
|
||||
let part = crate::symbol_overrides::part(&art.art, path)?;
|
||||
let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope);
|
||||
let mut out = BezPath::new();
|
||||
let mut limit = None;
|
||||
let mut whole = None;
|
||||
@@ -1128,24 +1310,40 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option<
|
||||
for &i in path {
|
||||
let children = n.children()?;
|
||||
whole = art.whole(n, whole);
|
||||
outline = outline || previews_off(n);
|
||||
if i != 0
|
||||
&& n.clips()
|
||||
&& let Some(first) = children.first()
|
||||
&& let Some(clip) = art.place_unclipped(first, whole)?.geometric_bounds()
|
||||
{
|
||||
match meet(Some(clip), limit) {
|
||||
Some(r) => limit = Some(r),
|
||||
None => return Some(out),
|
||||
}
|
||||
let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) };
|
||||
limit = within;
|
||||
}
|
||||
n = children.get(usize::try_from(i).ok()?)?;
|
||||
}
|
||||
outline_within(&art.place(part, whole)?, limit, &mut out);
|
||||
outline_within(&art.place(part, whole)?, limit, outline, &mut out);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
/// `limit` cut to the box that the art clipped by `clip` is drawn in: the bounds of the region the
|
||||
/// live geometry effects of `clip` give it ([`clip_region`]), or the bounds of `clip` when it has no
|
||||
/// such effects and with `outline`, where the canvas draws no effects. `None` when none of that art
|
||||
/// is drawn: the effects leave no region, or the box is outside `limit`.
|
||||
fn limit_within(clip: &Node, limit: Option<Rect>, outline: bool) -> Option<Option<Rect>> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let region = if outline { None } else { clip_region(clip) };
|
||||
let bounds = match region.as_deref() {
|
||||
Some(Some((bp, _))) if !bp.elements().is_empty() => Some(bp.bounding_box()),
|
||||
Some(_) => return None,
|
||||
None => clip.geometric_bounds(),
|
||||
};
|
||||
match bounds {
|
||||
Some(b) => meet(Some(b), limit).map(Some),
|
||||
None => Some(limit),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one.
|
||||
fn outline_within(n: &Node, limit: Option<Rect>, outline: bool, out: &mut BezPath) {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
if let Some(pd) = n.path_data() {
|
||||
match limit {
|
||||
@@ -1159,20 +1357,15 @@ fn outline_within(n: &Node, limit: Option<Rect>, out: &mut BezPath) {
|
||||
out.extend(b.to_path(0.1));
|
||||
}
|
||||
let Some(children) = n.children() else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
if n.clips()
|
||||
&& let Some((first, rest)) = children.split_first()
|
||||
{
|
||||
let inner = match first.geometric_bounds() {
|
||||
Some(c) => match meet(Some(c), limit) {
|
||||
Some(r) => Some(r),
|
||||
None => return,
|
||||
},
|
||||
None => limit,
|
||||
};
|
||||
rest.iter().for_each(|c| outline_within(c, inner, out));
|
||||
let Some(inner) = limit_within(first, limit, outline) else { return };
|
||||
rest.iter().for_each(|c| outline_within(c, inner, outline, out));
|
||||
return;
|
||||
}
|
||||
children.iter().for_each(|c| outline_within(c, limit, out));
|
||||
children.iter().for_each(|c| outline_within(c, limit, outline, out));
|
||||
}
|
||||
|
||||
/// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap.
|
||||
@@ -1248,31 +1441,48 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option<NodeId> {
|
||||
/// or of the parent of the single object isolated, does not limit the marquee, as it does not limit
|
||||
/// the selection tools' clicks.
|
||||
pub fn marquee(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false)
|
||||
marquee_with(doc, r, scope, leaves, false, false)
|
||||
}
|
||||
|
||||
/// [`marquee`] in the view the canvas shows: with `outline` (Outline view), and below a layer
|
||||
/// whose Preview is off, a clipping path counts by its plain shapes, without its live effects, as
|
||||
/// the clicks of [`HitOptions::outline`] do.
|
||||
pub fn marquee_in_view(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, leaves, false, outline)
|
||||
}
|
||||
|
||||
/// Candidates for whole-object enclosure by a loop bounded by `r`. Eligibility and group
|
||||
/// traversal follow [`marquee`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true)
|
||||
/// traversal follow [`marquee_in_view`]; compounds contribute the complete path they paint.
|
||||
pub fn enclosure_candidates(doc: &Document, r: Rect, scope: Option<NodeId>, outline: bool) -> Vec<NodeId> {
|
||||
marquee_with(doc, r, scope, true, true, outline)
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool) -> Vec<NodeId> {
|
||||
/// Is `n` a layer whose Preview is off (its art is drawn and clicked in outline)?
|
||||
fn previews_off(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::Layer { preview: false, .. })
|
||||
}
|
||||
|
||||
fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, whole_compounds: bool, outline: bool) -> Vec<NodeId> {
|
||||
let mut out = Vec::new();
|
||||
// `tops` pairs each object with the part of `r` in which the marquee can touch it.
|
||||
let tops: Vec<(&std::sync::Arc<Node>, Rect)> = match scope.and_then(|s| doc.node(s)) {
|
||||
// The objects the marquee may touch ([`Top`]).
|
||||
let tops: Vec<Top> = match scope.and_then(|s| doc.node(s)) {
|
||||
// Isolated art whose layer, or a group around it, was locked or hidden afterwards: the
|
||||
// marquee touches none of it, as clicks don't (#5309).
|
||||
Some(s) if !doc.is_editable(s.id) => vec![],
|
||||
Some(s) => match s.children() {
|
||||
Some(c) => c.iter().enumerate().filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope)).map(|(_, c)| (c, r)).collect(),
|
||||
Some(c) => c
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, c)| !c.is_ruler_guide() && !shaper_hides(s, *i, scope))
|
||||
.map(|(_, c)| (c, Some(r), outline, None))
|
||||
.collect(),
|
||||
// A single object isolated: only it.
|
||||
None => doc
|
||||
.parent_of(s.id)
|
||||
.and_then(|p| doc.node(p))
|
||||
.and_then(|p| p.children())
|
||||
.into_iter()
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, r)))
|
||||
.flat_map(|c| c.iter().filter(|c| c.id == s.id).map(|c| (c, Some(r), outline, None)))
|
||||
.collect(),
|
||||
},
|
||||
// The objects of the layers, looking through sublayers (hidden, locked and template ones
|
||||
@@ -1281,42 +1491,88 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !l.is_template() && doc.pattern_edit.as_ref().is_none_or(|e| e.layer == l.id))
|
||||
.flat_map(|l| layer_objects(l, r))
|
||||
.flat_map(|l| layer_objects(l, r, outline))
|
||||
.collect(),
|
||||
};
|
||||
/// The objects of layer `l`, each with the part of `r` that the clipping masks of `l` and of
|
||||
/// the sublayers it is in leave.
|
||||
fn layer_objects(l: &Node, r: Rect) -> Vec<(&std::sync::Arc<Node>, Rect)> {
|
||||
/// the sublayers it is in leave, whether it is in outline, and for the clipping mask of `l`,
|
||||
/// `r` for its edge test. The clipping mask itself counts by its own geometry within its plain
|
||||
/// shapes ([`mask_marquee`]).
|
||||
fn layer_objects(l: &Node, r: Rect, outline: bool) -> Vec<Top<'_>> {
|
||||
let mut out = vec![];
|
||||
let Some(r) = marquee_in(l, r) else { return out };
|
||||
for c in l.children().into_iter().flatten() {
|
||||
let outline = outline || previews_off(l);
|
||||
let inner = marquee_in_parent(l, r, outline);
|
||||
for (i, c) in l.children().into_iter().flatten().enumerate() {
|
||||
if c.is_layer() {
|
||||
if c.visible && !c.locked && !c.is_template() {
|
||||
out.extend(layer_objects(c, r));
|
||||
if let Some(inner) = inner
|
||||
&& c.visible
|
||||
&& !c.locked
|
||||
&& !c.is_template()
|
||||
{
|
||||
out.extend(layer_objects(c, inner, outline));
|
||||
}
|
||||
} else if !c.is_ruler_guide() {
|
||||
out.push((c, r));
|
||||
if i == 0 && l.clips() {
|
||||
out.push((c, mask_marquee(l, r), outline, Some(r)));
|
||||
} else if inner.is_some() {
|
||||
out.push((c, inner, outline, None));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The part of `r` in which the marquee can touch the clipping path of `parent` by its own
|
||||
/// geometry: within the bounds of its plain shapes ([`marquee_in`]), where clicks find its
|
||||
/// outline too ([`clip_outline_hit`]), whatever its live effects do to the region it clips to.
|
||||
fn mask_marquee(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
/// Does the marquee `r` touch `clip`, the clipping path of a clip group or of a layer with a
|
||||
/// clipping mask, on the edge of the region its live effects give it ([`clip_region`]), where
|
||||
/// the clip shows? Never in outline, nor without live effects: its own geometry counts then.
|
||||
fn clip_edge_touches(clip: &Node, r: Rect, outline: bool) -> bool {
|
||||
if outline {
|
||||
return false;
|
||||
}
|
||||
clip_region(clip).is_some_and(|region| {
|
||||
region.as_ref().as_ref().is_some_and(|(bp, _)| {
|
||||
// The edge of the region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let mut edge = PathData::from_bezpath(bp);
|
||||
edge.subpaths.iter_mut().for_each(|sp| sp.closed = true);
|
||||
vectorcraft_geom::hit::intersects_rect(&edge, r)
|
||||
})
|
||||
})
|
||||
}
|
||||
/// Is `n` collected whole by [`collect_leaves`], not by its members?
|
||||
fn is_leaf(n: &Node) -> bool {
|
||||
!matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Intertwine { .. })
|
||||
}
|
||||
/// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip
|
||||
/// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched
|
||||
/// by the copies it draws, as clicks hit them. Objects of every other kind except paths,
|
||||
/// compound paths, layers and groups are touched by their box.
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool) -> bool {
|
||||
/// compound paths, layers and groups are touched by their box. A clipping path is touched by
|
||||
/// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]).
|
||||
fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool) -> bool {
|
||||
match &n.kind {
|
||||
NodeKind::Path { path, .. } => vectorcraft_geom::hit::intersects_rect(path, r),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
marquee_in(n, r).is_some_and(|r| {
|
||||
children.iter().enumerate().any(|(i, c)| c.visible && !shaper_hides(n, i, scope) && touches(c, s, r, scope, whole_compounds))
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
children.iter().enumerate().any(|(i, c)| {
|
||||
c.visible
|
||||
&& !shaper_hides(n, i, scope)
|
||||
&& if i == 0 && n.clips() {
|
||||
mask_marquee(n, r).is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline)) || clip_edge_touches(c, r, outline)
|
||||
} else {
|
||||
inner.is_some_and(|r| touches(c, s, r, scope, whole_compounds, outline))
|
||||
}
|
||||
})
|
||||
}
|
||||
NodeKind::Compound { children, .. } if whole_compounds => {
|
||||
children.iter().filter_map(|c| c.path_data()).any(|path| vectorcraft_geom::hit::intersects_rect(path, r))
|
||||
}
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds)),
|
||||
NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)),
|
||||
NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)),
|
||||
// A box with no width or no height (an instance of a symbol that draws a straight
|
||||
// line) is touched where the marquee crosses it.
|
||||
_ => n.geometric_bounds_with(s).is_some_and(|b| {
|
||||
@@ -1325,18 +1581,30 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, out: &mut Vec<NodeId>) {
|
||||
fn collect_leaves(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option<NodeId>, whole_compounds: bool, outline: bool, out: &mut Vec<NodeId>) {
|
||||
match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Intertwine { children } => {
|
||||
let Some(r) = marquee_in(n, r) else { return };
|
||||
let outline = outline || previews_off(n);
|
||||
let inner = marquee_in_parent(n, r, outline);
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if c.visible && !c.locked && !shaper_hides(n, i, scope) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, out);
|
||||
if !c.visible || c.locked || shaper_hides(n, i, scope) {
|
||||
continue;
|
||||
}
|
||||
if i == 0 && n.clips() {
|
||||
let before = out.len();
|
||||
if let Some(r) = mask_marquee(n, r) {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
if out.len() == before && is_leaf(c) && clip_edge_touches(c, r, outline) {
|
||||
out.push(c.id);
|
||||
}
|
||||
} else if let Some(r) = inner {
|
||||
collect_leaves(c, s, r, scope, whole_compounds, outline, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if touches(n, s, r, scope, whole_compounds) {
|
||||
if touches(n, s, r, scope, whole_compounds, outline) {
|
||||
out.push(n.id);
|
||||
}
|
||||
}
|
||||
@@ -1344,36 +1612,56 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option<NodeId>, leaves: bool, wh
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let locks = doc.locked_artboards();
|
||||
for (t, r) in tops {
|
||||
for (t, r, outline, edge) in tops {
|
||||
if !t.visible || t.locked || locks.holds_id(t.id) {
|
||||
continue;
|
||||
}
|
||||
if leaves {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, &mut out);
|
||||
} else if touches(t, &symbols, r, scope, whole_compounds) {
|
||||
let before = out.len();
|
||||
if let Some(r) = r {
|
||||
collect_leaves(t, &symbols, r, scope, whole_compounds, outline, &mut out);
|
||||
}
|
||||
if edge.is_some_and(|e| out.len() == before && is_leaf(t) && clip_edge_touches(t, e, outline)) {
|
||||
out.push(t.id);
|
||||
}
|
||||
} else if r.is_some_and(|r| touches(t, &symbols, r, scope, whole_compounds, outline))
|
||||
|| edge.is_some_and(|e| clip_edge_touches(t, e, outline))
|
||||
{
|
||||
out.push(t.id);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An object a marquee may touch ([`marquee_with`]): the object, the part of the marquee in which
|
||||
/// it can be touched (`None` when nowhere), whether it is in outline, and for the clipping mask of a
|
||||
/// layer, the marquee whose edge test it also takes (`clip_edge_touches`).
|
||||
type Top<'a> = (&'a std::sync::Arc<Node>, Option<Rect>, bool, Option<Rect>);
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`. For a clip group or a
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for its clipping path (None
|
||||
/// when the marquee misses it); otherwise it is all of `r`.
|
||||
/// layer with a clipping mask, this is what [`marquee_in_clip`] returns for the plain shapes of its
|
||||
/// clipping path ([`clip_regions`]; None when the marquee misses them); otherwise it is all of `r`.
|
||||
pub fn marquee_in(parent: &Node, r: Rect) -> Option<Rect> {
|
||||
marquee_in_parent(parent, r, true)
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the children of `parent`, by the region its
|
||||
/// clipping path clips to ([`clip_areas`]), or by that path's plain shapes with `outline`
|
||||
/// ([`marquee_in_view`]).
|
||||
fn marquee_in_parent(parent: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
match parent.children().and_then(|c| c.first()) {
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r),
|
||||
Some(clip) if parent.clips() => marquee_in_clip(clip, r, outline),
|
||||
_ => Some(r),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of a marquee `r` in which it can touch the art that `clip` clips (the clipping path of
|
||||
/// a clip group or of a layer with a clipping mask): `r` cut to the bounds of the regions `clip`
|
||||
/// clips to ([`clip_regions`]), or `None` when `r` meets none of those regions. Within those
|
||||
/// bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect) -> Option<Rect> {
|
||||
/// clips to ([`clip_areas`], its plain shapes with `outline`), or `None` when `r` meets none of
|
||||
/// those regions. Within those bounds, art outside a region that is not a rectangle still counts.
|
||||
fn marquee_in_clip(clip: &Node, r: Rect, outline: bool) -> Option<Rect> {
|
||||
use vectorcraft_geom::kurbo::Shape;
|
||||
let regions = clip_regions(clip);
|
||||
let regions = if outline { clip_regions(clip) } else { clip_areas(clip) };
|
||||
// The edge of a region is its outline with each open subpath closed, as `fill_contains` fills it.
|
||||
let meets = |(bp, rule): &(vectorcraft_geom::BezPath, vectorcraft_geom::FillRule)| {
|
||||
let mut edge = vectorcraft_geom::PathData::from_bezpath(bp);
|
||||
|
||||
@@ -110,6 +110,252 @@ fn half_clipped(d: &mut Document) -> (Node, Node) {
|
||||
(mask, art)
|
||||
}
|
||||
|
||||
/// A stand-in for the engine's [`ClipRegion`]: with an effect named `test.move` in the clipping
|
||||
/// path, its first shape moved 100 pt right; with one named `test.empty`, no region left to clip
|
||||
/// by; without either, no geometry effect.
|
||||
fn moved_clip_region(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
let (mut moves, mut empty) = (false, false);
|
||||
clip.walk(&mut |n| {
|
||||
moves |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.move");
|
||||
empty |= n.appearance.effects.iter().any(|e| e.visible && e.id == "test.empty");
|
||||
});
|
||||
if empty {
|
||||
return Some(None);
|
||||
}
|
||||
if !moves {
|
||||
return None;
|
||||
}
|
||||
Some(clip_regions(clip).into_iter().next().map(|(mut bp, rule)| {
|
||||
bp.apply_affine(vectorcraft_geom::Affine::translate((100.0, 0.0)));
|
||||
(bp, rule)
|
||||
}))
|
||||
}
|
||||
|
||||
/// A visible effect named `test.move`, which [`moved_clip_region`] reads as moving the region.
|
||||
fn test_move() -> crate::Effect {
|
||||
crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true }
|
||||
}
|
||||
|
||||
/// Clicks inside a clip group whose clipping path has a live effect fall in the region the
|
||||
/// registered [`ClipRegion`] gives it. The pointer moving over it evaluates the region once, and
|
||||
/// again after the clipping path changes; a clipping path without effects is not evaluated.
|
||||
#[test]
|
||||
fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_changes() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let before = evaluated();
|
||||
let leaf = |d: &Document, x: f64| hit_test(d, Point::new(x, 50.0), HitOptions::default()).map(|h| h.leaf);
|
||||
for x in [148.0, 150.0, 152.0] {
|
||||
assert_eq!(leaf(&d, x), Some(art_id), "in the moved region");
|
||||
}
|
||||
assert_eq!(leaf(&d, 50.0), None, "the clipping path's own place");
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Outline mode draws no effects: the art's edge shows within the clipping path's own shape.
|
||||
let outline = HitOptions { outline: true, ..HitOptions::default() };
|
||||
assert_eq!(hit_test(&d, Point::new(50.0, 0.5), outline).map(|h| h.leaf), Some(art_id), "outline mode");
|
||||
// So with a marquee across the art's left edge: in the view, only in Outline view. The
|
||||
// clipping path's own left edge lies there too, and counts in both.
|
||||
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
|
||||
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
|
||||
// `marquee_in` measures by the plain shapes, as its callers clip by them.
|
||||
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
|
||||
// Hidden, the effect no longer moves the region.
|
||||
d.node_mut(mask_id).unwrap().appearance.effects[0].visible = false;
|
||||
assert_eq!(leaf(&d, 50.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 150.0), None);
|
||||
assert_eq!(evaluated(), before + 1);
|
||||
// Shown again and widened, the region is evaluated again.
|
||||
let mask = d.node_mut(mask_id).unwrap();
|
||||
mask.appearance.effects[0].visible = true;
|
||||
if let NodeKind::Path { path, .. } = &mut mask.kind {
|
||||
*path = shapes::rectangle(Rect::new(0.0, 0.0, 90.0, 100.0));
|
||||
}
|
||||
assert_eq!(leaf(&d, 180.0), Some(art_id));
|
||||
assert_eq!(leaf(&d, 195.0), None);
|
||||
assert_eq!(evaluated(), before + 2);
|
||||
}
|
||||
|
||||
/// A marquee around a clipping path that an effect moved into the middle of large art touches the
|
||||
/// clipping path on the edge of its moved region, in a clip group and in a clipping layer.
|
||||
#[test]
|
||||
fn a_marquee_touches_a_moved_clipping_path_on_its_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let parts = |d: &mut Document| {
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 300.0)), Appearance::default_art());
|
||||
(mask, art)
|
||||
};
|
||||
// Around the moved region (120..160) and the clipping path's own place, inside the art.
|
||||
let around = Rect::new(10.0, 10.0, 170.0, 70.0);
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let (g, mask_id) = (d.alloc_id(), mask.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [g]);
|
||||
assert_eq!(marquee(&d, around, None, true), [mask_id]);
|
||||
// Only over the clipping path's own place, the marquee misses the region but touches the
|
||||
// clipping path's anchors, which a click on its outline also finds.
|
||||
let own = Rect::new(10.0, 10.0, 70.0, 70.0);
|
||||
assert_eq!(marquee(&d, own, None, false), [g]);
|
||||
assert_eq!(marquee(&d, own, None, true), [mask_id]);
|
||||
// Away from both, nothing.
|
||||
assert!(marquee(&d, Rect::new(70.0, 10.0, 110.0, 70.0), None, true).is_empty());
|
||||
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mask, art) = parts(&mut d);
|
||||
let mask_id = mask.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, .. } = &mut sublayer.kind {
|
||||
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
assert_eq!(marquee(&d, around, None, false), [mask_id]);
|
||||
}
|
||||
|
||||
/// A clipping layer whose Preview is off draws its art in outline: clicks, the objects at a point
|
||||
/// and marquees count its clipping path by its plain shape, without the effect that moves it.
|
||||
#[test]
|
||||
fn a_clipping_layer_with_preview_off_counts_its_plain_clipping_path() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, clip, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *clip, *preview) = (vec![Arc::new(mask), Arc::new(art)], true, false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
// The art's top edge, within the clipping path's own shape.
|
||||
let p = Point::new(50.0, 0.5);
|
||||
assert_eq!(hit_test(&d, p, HitOptions::default()).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(objects_at(&d, p, HitOptions::default(), None).first(), Some(&art_id));
|
||||
assert!(marquee(&d, Rect::new(45.0, -5.0, 55.0, 5.0), None, true).contains(&art_id));
|
||||
}
|
||||
|
||||
/// The pointer moving over empty canvas past more clip groups with live effects than the regions
|
||||
/// kept measures each group's box once: the boxes are kept for every clip group.
|
||||
#[test]
|
||||
fn hovers_past_many_clip_groups_evaluate_each_clipping_path_once() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
for i in 0..(2 * CLIPS_KEPT) {
|
||||
let x = 20.0 * i as f64;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default());
|
||||
mask.appearance.effects.push(crate::Effect { id: "test.move".into(), params: serde_json::json!({}), visible: true });
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 20.0, 10.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
d.insert(Some(l), 0, clip).unwrap();
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(500.0, 500.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
for _ in 0..3 {
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
}
|
||||
assert_eq!(evaluated(), first);
|
||||
}
|
||||
|
||||
/// With more clip groups with live effects than the boxes kept, a new box replaces only as many
|
||||
/// others as it needs room for: the next hover finds most of the boxes and evaluates few regions.
|
||||
#[test]
|
||||
fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let mut d = Document::new(1000.0, 1000.0);
|
||||
let l = d.layers[0].id;
|
||||
let groups = CLIP_BOXES_KEPT + 64;
|
||||
let mut members = Vec::with_capacity(groups);
|
||||
for i in 0..groups {
|
||||
let x = (i % 100) as f64 * 5.0;
|
||||
let y = (i / 100) as f64 * 5.0;
|
||||
let mut mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 2.0, y + 2.0)), Appearance::default());
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 4.0, y + 2.0)), Appearance::default_art());
|
||||
let mut clip = Node::group(d.alloc_id(), vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
members.push(Arc::new(clip));
|
||||
}
|
||||
if let Some(children) = d.node_mut(l).and_then(|n| n.children_mut()) {
|
||||
*children = members;
|
||||
}
|
||||
let evaluated = || CLIPS_EVALUATED.with(std::cell::Cell::get);
|
||||
let empty = Point::new(900.0, 900.0);
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let first = evaluated();
|
||||
assert!(hit_test(&d, empty, HitOptions::default()).is_none());
|
||||
let again = evaluated() - first;
|
||||
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
|
||||
}
|
||||
|
||||
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
|
||||
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
|
||||
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
|
||||
/// whose Preview is off, which is clicked in outline while the layer above clips by its region.
|
||||
#[test]
|
||||
fn every_clip_test_follows_the_moved_region() {
|
||||
set_clip_region(moved_clip_region);
|
||||
let (moved, own) = (Point::new(150.0, 50.0), Point::new(50.0, 50.0));
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let (g, art_id) = (d.alloc_id(), art.id);
|
||||
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
|
||||
clip.set_clips(true);
|
||||
let outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
|
||||
d.insert(Some(l), 0, outer.clone()).unwrap();
|
||||
let opt = HitOptions::default();
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id), "hidden at the clipping path's own place");
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None, "shown in the moved region");
|
||||
let symbols = d.symbol_boxes();
|
||||
assert_eq!(hit_any(&outer, moved, opt, &symbols), Some(HitKind::Fill));
|
||||
assert_eq!(hit_any(&outer, own, opt, &symbols), None);
|
||||
d.node_mut(art_id).unwrap().locked = true;
|
||||
assert_eq!(locked_objects_at(&d, moved, opt), [art_id]);
|
||||
assert!(locked_objects_at(&d, own, opt).is_empty());
|
||||
|
||||
// A clipping layer holding the mask and a sublayer whose Preview is off, with the art.
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
let top = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(test_move());
|
||||
let art_id = art.id;
|
||||
let mut sublayer = (*d.layers[0]).clone();
|
||||
sublayer.id = d.alloc_id();
|
||||
if let NodeKind::Layer { children, preview, .. } = &mut sublayer.kind {
|
||||
(*children, *preview) = (vec![Arc::new(art)], false);
|
||||
}
|
||||
d.insert(Some(top), 0, sublayer).unwrap();
|
||||
d.insert(Some(top), 0, mask).unwrap();
|
||||
d.node_mut(top).unwrap().set_clips(true);
|
||||
// The art's top edge, at the clipping path's own place and in the moved region.
|
||||
let (own, moved) = (Point::new(50.0, 0.5), Point::new(150.0, 0.5));
|
||||
assert!(hit_test(&d, own, opt).is_none());
|
||||
assert_eq!(hit_test(&d, moved, opt).map(|h| h.leaf), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, own, opt, &[art_id]), Some(art_id));
|
||||
assert_eq!(selected_hidden_at(&d, moved, opt, &[art_id]), None);
|
||||
}
|
||||
|
||||
/// The art a mask hides counts only for a selected object: there a click hits nothing, and the
|
||||
/// selection tools grab the selection by that art. Not where the art shows (the click hits it),
|
||||
/// beyond the art, for the clip group selected as a whole, nor for art a click can't hit (locked,
|
||||
@@ -1549,6 +1795,63 @@ fn an_object_a_clipping_layer_in_symbol_art_hides_is_not_picked_there() {
|
||||
assert!((b.x1 - 100.0).abs() < 1e-6, "the layer's outline is cut to the mask: {b:?}");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art, an object in a clipping layer whose clipping path has a live effect
|
||||
/// is picked and outlined in the region the effect gives the clipping path. In Outline view, and
|
||||
/// when Preview is off for the layer in the art or for the layer the instance is on, the plain
|
||||
/// clipping path counts, as the canvas draws it. An effect that leaves no region leaves no outline.
|
||||
#[test]
|
||||
fn a_symbol_part_follows_the_region_its_clipping_layers_effects_give_it() {
|
||||
set_clip_region(moved_clip_region);
|
||||
// The instance of a symbol whose art is a clipping layer; `preview` is the Preview of that
|
||||
// layer and of the document layer the instance is on.
|
||||
let instance = |effect: &str, preview: [bool; 2]| {
|
||||
let mut d = Document::new(300.0, 200.0);
|
||||
if let NodeKind::Layer { preview: p, .. } = &mut Arc::make_mut(&mut d.layers[0]).kind {
|
||||
*p = preview[1];
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
let (mut mask, art) = half_clipped(&mut d);
|
||||
mask.appearance.effects.push(crate::Effect { id: effect.into(), ..test_move() });
|
||||
let mut layer = Node::layer(d.alloc_id(), "Masked", crate::LayerColor::Preset(2));
|
||||
if let NodeKind::Layer { children, preview: p, .. } = &mut layer.kind {
|
||||
(*children, *p) = (vec![Arc::new(mask), Arc::new(art)], preview[0]);
|
||||
}
|
||||
layer.set_clips(true);
|
||||
let root = Node::group(d.alloc_id(), vec![Arc::new(layer)]);
|
||||
d.symbols.push(crate::Symbol { dynamic: true, name: "Clipped".into(), art: Arc::new(root) });
|
||||
let inst = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::new(inst, NodeKind::SymbolInstance { symbol: "Clipped".into(), xf: vectorcraft_geom::Affine::IDENTITY })).unwrap();
|
||||
(d, inst)
|
||||
};
|
||||
let outline_box = |d: &Document, inst: NodeId, opt: HitOptions| {
|
||||
let o = symbol_part_outline_in_view(d, d.node(inst).unwrap(), &[0, 1], opt).unwrap();
|
||||
vectorcraft_geom::kurbo::Shape::bounding_box(&o)
|
||||
};
|
||||
let opt = HitOptions::default();
|
||||
let (d, inst) = instance("test.move", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 50.0), opt), Some(vec![0, 1]), "in the moved region");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None, "where the clipping path was");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!((b.x0 - 100.0).abs() < 1e-6 && (b.x1 - 200.0).abs() < 1e-6, "the outline is cut to the moved region: {b:?}");
|
||||
let b = outline_box(&d, inst, HitOptions { outline: true, ..opt });
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "in Outline view, to the plain clipping path: {b:?}");
|
||||
// With Preview off, the art's top edge counts within the plain clipping path.
|
||||
for (preview, what) in [([false, true], "the layer in the art"), ([true, false], "the layer the instance is on")] {
|
||||
let (d, inst) = instance("test.move", preview);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 0.5), opt), Some(vec![0, 1]), "on the edge the canvas draws, Preview off for {what}");
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(150.0, 0.5), opt), None, "past the plain clipping path, Preview off for {what}");
|
||||
let b = outline_box(&d, inst, opt);
|
||||
assert!(b.x0.abs() < 1e-6 && (b.x1 - 100.0).abs() < 1e-6, "Preview off for {what}: the plain clipping path: {b:?}");
|
||||
}
|
||||
// An effect that leaves the clipping path no region hides the art: no pick and no outline.
|
||||
let (d, inst) = instance("test.empty", [true, true]);
|
||||
let n = d.node(inst).unwrap();
|
||||
assert_eq!(symbol_part_at(&d, n, Point::new(50.0, 50.0), opt), None);
|
||||
assert!(symbol_part_outline(&d, n, &[0, 1]).unwrap().elements().is_empty(), "nothing is drawn, so nothing is outlined");
|
||||
}
|
||||
|
||||
/// In a dynamic symbol's art that placing through its 9-slice guides could make more than
|
||||
/// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the
|
||||
/// canvas draws nothing of it. At the art's natural size the same art is picked.
|
||||
|
||||
@@ -119,6 +119,8 @@ pub use slices::{CellAlign, CellVAlign, Slice, SliceArea, SliceKind, SliceOption
|
||||
pub use style_libs::StyleLibrary;
|
||||
pub use text::FontHeightReference;
|
||||
pub use text::GlyphChoice;
|
||||
pub use text::GlyphForm;
|
||||
pub use text::PATH_LEAD_MAX;
|
||||
pub use text::WarichuAlign;
|
||||
pub use text::{
|
||||
AreaFit, AreaOptions, Burasagari, CharAlign, CharPosition, CharStyle, Composer, Digits, FirstBaseline, HyphenationOptions, InlineArt,
|
||||
|
||||
@@ -358,6 +358,34 @@ mod tests {
|
||||
assert!((p.x - 25.0).abs() < 1e-6 && (p.y - 25.0).abs() < 1e-6, "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coons_places_are_where_the_patch_bends() {
|
||||
// A rectangle's sides have 65 evenly spaced points.
|
||||
let [u, v] = Coons::rect(Rect::new(0.0, 0.0, 100.0, 50.0)).places();
|
||||
assert_eq!((u.len(), v.len()), (65, 65));
|
||||
assert!(u.iter().enumerate().all(|(i, x)| (x - i as f64 / 64.0).abs() < 1e-12), "{u:?}");
|
||||
// A top object with a curved top: between two places next to each other the patch is
|
||||
// straight, in `u` and in `v`.
|
||||
let mut path = kurbo::BezPath::new();
|
||||
path.move_to((0.0, 0.0));
|
||||
path.curve_to((30.0, -20.0), (70.0, 10.0), (100.0, 0.0));
|
||||
path.line_to((100.0, 50.0));
|
||||
path.line_to((40.0, 50.0));
|
||||
path.line_to((0.0, 50.0));
|
||||
path.close_path();
|
||||
let c = Coons::from_top_object(&PathData::from_bezpath(&path), Some([0, 1, 2, 4])).unwrap();
|
||||
let [u, v] = c.places();
|
||||
assert!(u.first() == Some(&0.0) && u.last() == Some(&1.0) && u.windows(2).all(|w| w[0] < w[1]), "{u:?}");
|
||||
assert!(v.first() == Some(&0.0) && v.last() == Some(&1.0) && v.windows(2).all(|w| w[0] < w[1]), "{v:?}");
|
||||
for w in u.windows(2) {
|
||||
for y in [0.0, 0.3, 1.0] {
|
||||
let mid = c.eval((w[0] + w[1]) / 2.0, y);
|
||||
let half = c.eval(w[0], y).midpoint(c.eval(w[1], y));
|
||||
assert!(mid.distance(half) < 1e-9, "{w:?} {y}: {mid:?} {half:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_go_on_past_the_content_box() {
|
||||
// A stroke outline reaches past the box: a flat mesh and a rectangle stay the identity there.
|
||||
|
||||
@@ -338,6 +338,31 @@ impl Coons {
|
||||
let end = |side: &[Point]| side.last().copied().unwrap_or_default();
|
||||
[self.top[0], end(&self.top), end(&self.bottom), self.bottom[0]]
|
||||
}
|
||||
|
||||
/// The places in `u` where the top or bottom side has a point, and the places in `v` where the
|
||||
/// left or right side has one, rising from 0 to 1. Between two places next to each other, each
|
||||
/// side runs straight, so [`Self::eval`] changes linearly in `u` and in `v` inside each cell of
|
||||
/// the grid they make.
|
||||
pub fn places(&self) -> [Vec<f64>; 2] {
|
||||
let sides = [&self.top, &self.right, &self.bottom, &self.left];
|
||||
let at = |which: usize| -> Vec<f64> {
|
||||
match self.knots.as_deref().and_then(|k| k.get(which)) {
|
||||
Some(knots) => knots.clone(),
|
||||
None => {
|
||||
let last = sides[which].len().saturating_sub(1).max(1);
|
||||
(0..=last).map(|i| i as f64 / last as f64).collect()
|
||||
}
|
||||
}
|
||||
};
|
||||
let merge = |a: usize, b: usize| {
|
||||
let mut v = at(a);
|
||||
v.extend(at(b));
|
||||
v.sort_by(f64::total_cmp);
|
||||
v.dedup();
|
||||
v
|
||||
};
|
||||
[merge(0, 2), merge(1, 3)]
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points one side of [`Coons::from_top_object`] holds while it adds points between its
|
||||
|
||||
@@ -211,7 +211,9 @@ impl Node {
|
||||
|
||||
/// A quick box round everything the object can paint, for culling clicks: paths and compound
|
||||
/// paths grow their geometric bounds by the farthest their strokes can reach from any path
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in
|
||||
/// ([`Appearance::outset`]) instead of measuring along their shape. A clip group's or a
|
||||
/// clipping layer's box takes in the region that the live geometry effects of its clipping
|
||||
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
|
||||
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
|
||||
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
|
||||
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
|
||||
@@ -261,6 +263,11 @@ impl Node {
|
||||
NodeKind::Blend { children, spec } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), crate::blend::rail_reach(children, spec, symbols))
|
||||
}
|
||||
// The live geometry effects of a clipping path can move or grow the region it clips to
|
||||
// past its plain shape ([`crate::hit::set_clip_region`]).
|
||||
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
|
||||
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
|
||||
}
|
||||
_ => self.visual(symbols),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,6 +173,10 @@ pub struct PatternDef {
|
||||
/// Size Tile to Art: the tile is the art bounds grown by the spacing.
|
||||
#[serde(default)]
|
||||
pub size_tile_to_art: bool,
|
||||
/// Move Tile with Art: in pattern editing mode, a move of all of the tile art moves the tile by
|
||||
/// the same offset.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub move_tile_with_art: bool,
|
||||
#[serde(default)]
|
||||
pub h_spacing: f64,
|
||||
#[serde(default)]
|
||||
@@ -202,6 +206,7 @@ impl PatternDef {
|
||||
art,
|
||||
overlap: Overlap::default(),
|
||||
size_tile_to_art: false,
|
||||
move_tile_with_art: false,
|
||||
h_spacing: 0.0,
|
||||
v_spacing: 0.0,
|
||||
copies: 5,
|
||||
|
||||
@@ -162,6 +162,7 @@ pub const STYLE_LIBRARIES: &[BuiltinStyleLibrary] = &[
|
||||
BuiltinStyleLibrary { id: "blends-transparency", name: "Blends and Transparency", make: blends_transparency },
|
||||
BuiltinStyleLibrary { id: "game-hud", name: "Game HUD", make: game_hud },
|
||||
BuiltinStyleLibrary { id: "status-effects", name: "Status Effects", make: status_effects },
|
||||
BuiltinStyleLibrary { id: "neon-glow", name: "Neon & Glow", make: neon_glow },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -619,6 +620,44 @@ fn status_effects() -> Vec<GraphicStyle> {
|
||||
]
|
||||
}
|
||||
|
||||
/// Neon & Glow: original multi-layer procedural styles with neon tubes, laser beams, and glowing halos.
|
||||
fn neon_glow() -> Vec<GraphicStyle> {
|
||||
vec![
|
||||
style(
|
||||
"Cyan Neon",
|
||||
vec![S(StrokeLayer { opacity: 0.7, ..round("#00e5ff", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.dropShadow", json!({"mode": "screen", "opacity": 85.0, "x": 0.0, "y": 0.0, "blur": 8.0, "color": "#00e5ff"}))],
|
||||
),
|
||||
GraphicStyle {
|
||||
blend: BlendMode::Screen,
|
||||
..style(
|
||||
"Magenta Laser",
|
||||
vec![S(StrokeLayer { blend: BlendMode::Screen, ..round("#ff007f", 5.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#ff007f"}))],
|
||||
)
|
||||
},
|
||||
style(
|
||||
"Amber Tube",
|
||||
vec![S(StrokeLayer { opacity: 0.8, ..round("#ff8c00", 6.0) }), S(round("#ffea00", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#ff8c00"}))],
|
||||
),
|
||||
style(
|
||||
"Electric Lime",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#39ff14", 6.0) }), S(round("#ffffff", 1.5))],
|
||||
vec![fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 90.0, "blur": 8.0, "color": "#39ff14"}))],
|
||||
),
|
||||
style(
|
||||
"Pulse Violet",
|
||||
vec![S(StrokeLayer { opacity: 0.75, ..round("#7b2cbf", 5.0) }), S(round("#e0aaff", 1.5))],
|
||||
vec![
|
||||
fx("stylize.innerGlow", json!({"mode": "screen", "opacity": 75.0, "blur": 6.0, "color": "#c77dff", "source": "edge"})),
|
||||
fx("stylize.outerGlow", json!({"mode": "screen", "opacity": 85.0, "blur": 8.0, "color": "#7b2cbf"})),
|
||||
],
|
||||
),
|
||||
style("Cobalt Phosphor", vec![S(round("#0047ab", 6.0)), S(round("#ffffff", 1.5))], vec![fx("blur.gaussian", json!({"radius": 2.0}))]),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -750,4 +789,36 @@ mod tests {
|
||||
let Paint::Gradient(gp) = g.appearance.fill_paint() else { panic!("a gradient") };
|
||||
assert!(gp.swatch.is_none() && gp.gradient.stops.iter().all(|s| s.swatch.is_none() && s.tint == 1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_and_glow_styles_are_defined_with_multi_strokes_and_effects() {
|
||||
let lib = builtin_style_library("neon-glow").expect("neon-glow library exists");
|
||||
assert_eq!(lib.name, "Neon & Glow");
|
||||
assert_eq!(lib.len(), 6);
|
||||
let names: Vec<&str> = lib.styles.iter().map(|g| g.name.as_str()).collect();
|
||||
assert_eq!(names, ["Cyan Neon", "Magenta Laser", "Amber Tube", "Electric Lime", "Pulse Violet", "Cobalt Phosphor"]);
|
||||
for g in &lib.styles {
|
||||
let strokes = g.appearance.items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count();
|
||||
assert!(strokes >= 2, "{} has {} strokes, expected >= 2", g.name, strokes);
|
||||
assert!(!g.appearance.effects.is_empty(), "{} has effects", g.name);
|
||||
}
|
||||
let cyan = lib.style("Cyan Neon").unwrap();
|
||||
assert_eq!(cyan.appearance.effects[0].id, "stylize.dropShadow");
|
||||
let magenta = lib.style("Magenta Laser").unwrap();
|
||||
assert_eq!(magenta.blend, BlendMode::Screen);
|
||||
let pulse = lib.style("Pulse Violet").unwrap();
|
||||
let pulse_fx: Vec<&str> = pulse.appearance.effects.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(pulse_fx, ["stylize.innerGlow", "stylize.outerGlow"]);
|
||||
let cobalt = lib.style("Cobalt Phosphor").unwrap();
|
||||
assert_eq!(cobalt.appearance.effects[0].id, "blur.gaussian");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neon_glow_round_trips_through_vcstyles() {
|
||||
let lib = builtin_style_library("neon-glow").unwrap();
|
||||
let text = write(&lib);
|
||||
assert!(sniff(&text));
|
||||
let read_back = read(&text, "Fallback").unwrap();
|
||||
assert_eq!(*lib, read_back);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +79,21 @@ fn odd_text_reads_as_nothing_without_panicking() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Text from a command or a file can be any length: a sum of thousands of terms reads as nothing
|
||||
/// instead of exhausting the stack. Up to 128 `+ - * /` signs read; 129 read as nothing.
|
||||
#[test]
|
||||
fn a_very_long_expression_reads_as_nothing() {
|
||||
let sum = |terms: usize| format!("1{}", "+1".repeat(terms - 1));
|
||||
assert_eq!(Unit::Points.parse(&sum(129)), Some(129.0));
|
||||
assert_eq!(Unit::Points.parse(&format!("10{} mm", "*1".repeat(128))), Some(Unit::Millimeters.to_pt(10.0)));
|
||||
// Long text with no signs still reads.
|
||||
assert_eq!(Unit::Points.parse(&format!("{}5", " ".repeat(2_000))), Some(5.0));
|
||||
for text in [sum(200_000), format!("1{}", "*1".repeat(200_000)), sum(130), format!("10{} mm", "*1".repeat(129))] {
|
||||
assert_eq!(Unit::Points.parse(&text), None, "{} bytes", text.len());
|
||||
assert_eq!(crate::parse_number(&text), None, "{} bytes", text.len());
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
|
||||
/// or as nothing and does not panic.
|
||||
|
||||
@@ -18,8 +18,8 @@ mod wrap;
|
||||
pub use area::{AreaFit, AreaOptions, PathAlign, PathEffect, TextFlow, TextWrap, VerticalAlign, WrapShape};
|
||||
use char_style::yes;
|
||||
pub use char_style::{
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics, WARICHU_LINES,
|
||||
WARICHU_SCALE, WarichuAlign,
|
||||
CharAlign, CharPosition, CharStyle, Digits, FontHeightReference, GlyphChoice, GlyphForm, MAX_AKI, MAX_TSUME, MAX_WARICHU_GAP, ScriptMetrics,
|
||||
WARICHU_LINES, WARICHU_SCALE, WarichuAlign,
|
||||
};
|
||||
pub use composite::{
|
||||
COMPOSITE_BASELINE, COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, COMPOSITE_SCALE, COMPOSITE_SIZE, CharClass, CompositeFont, CompositePart,
|
||||
@@ -29,6 +29,7 @@ pub use para_style::{
|
||||
Burasagari, Composer, FirstBaseline, HyphenationOptions, JustificationOptions, Justify, Kashida, Kinsoku, KinsokuShoriType, LeadingModel,
|
||||
Mojikumi, ParaDirection, ParaStyle, SingleWordJustify,
|
||||
};
|
||||
pub use runs::PATH_LEAD_MAX;
|
||||
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
|
||||
pub use tabs_lists::{
|
||||
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
|
||||
|
||||
@@ -205,6 +205,108 @@ pub struct CharStyle {
|
||||
/// default glyph otherwise. Saved only when set.
|
||||
#[serde(default, rename = "glyphAlternate", skip_serializing_if = "Option::is_none")]
|
||||
pub glyph_alternate: Option<GlyphChoice>,
|
||||
/// The East Asian glyph form these characters are drawn in (Glyphs panel menu, with Show East
|
||||
/// Asian Options): one OpenType feature of the font, such as JIS 78 forms (`jp78`), or the
|
||||
/// font's default glyphs. The text keeps its characters. Saved only when set.
|
||||
/// <https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html>
|
||||
#[serde(default, rename = "glyphForm", skip_serializing_if = "crate::skip::is_default")]
|
||||
pub glyph_form: GlyphForm,
|
||||
}
|
||||
|
||||
/// The East Asian glyph form characters are drawn in ([`CharStyle::glyph_form`]): the font's
|
||||
/// default glyphs, or the glyphs one OpenType feature substitutes. One form at a time.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist>
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum GlyphForm {
|
||||
/// The font's default glyphs.
|
||||
#[default]
|
||||
Default,
|
||||
/// Traditional forms (`trad`).
|
||||
Traditional,
|
||||
/// Expert forms (`expt`).
|
||||
Expert,
|
||||
/// JIS 2004 forms (`jp04`).
|
||||
Jis04,
|
||||
/// JIS 90 forms (`jp90`).
|
||||
Jis90,
|
||||
/// JIS 78 forms (`jp78`).
|
||||
Jis78,
|
||||
/// JIS 83 forms (`jp83`).
|
||||
Jis83,
|
||||
/// Monospaced full-width forms (`fwid`).
|
||||
FullWidth,
|
||||
/// Monospaced half-width forms (`hwid`).
|
||||
HalfWidth,
|
||||
/// Monospaced third-width forms (`twid`).
|
||||
ThirdWidth,
|
||||
/// Monospaced quarter-width forms (`qwid`).
|
||||
QuarterWidth,
|
||||
}
|
||||
|
||||
impl GlyphForm {
|
||||
/// Every form, in menu order, the default last.
|
||||
pub const ALL: [GlyphForm; 11] = [
|
||||
GlyphForm::Traditional,
|
||||
GlyphForm::Expert,
|
||||
GlyphForm::Jis04,
|
||||
GlyphForm::Jis90,
|
||||
GlyphForm::Jis78,
|
||||
GlyphForm::Jis83,
|
||||
GlyphForm::FullWidth,
|
||||
GlyphForm::HalfWidth,
|
||||
GlyphForm::ThirdWidth,
|
||||
GlyphForm::QuarterWidth,
|
||||
GlyphForm::Default,
|
||||
];
|
||||
|
||||
/// The name files and commands give this form (as it is saved).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
GlyphForm::Default => "default",
|
||||
GlyphForm::Traditional => "traditional",
|
||||
GlyphForm::Expert => "expert",
|
||||
GlyphForm::Jis04 => "jis04",
|
||||
GlyphForm::Jis90 => "jis90",
|
||||
GlyphForm::Jis78 => "jis78",
|
||||
GlyphForm::Jis83 => "jis83",
|
||||
GlyphForm::FullWidth => "fullWidth",
|
||||
GlyphForm::HalfWidth => "halfWidth",
|
||||
GlyphForm::ThirdWidth => "thirdWidth",
|
||||
GlyphForm::QuarterWidth => "quarterWidth",
|
||||
}
|
||||
}
|
||||
|
||||
/// The form [`GlyphForm::id`] names; `None` for any other name.
|
||||
pub fn from_id(id: &str) -> Option<GlyphForm> {
|
||||
GlyphForm::ALL.into_iter().find(|f| f.id() == id)
|
||||
}
|
||||
|
||||
/// The OpenType feature that draws this form; `None` for the default glyphs.
|
||||
pub fn feature(self) -> Option<&'static [u8; 4]> {
|
||||
Some(match self {
|
||||
GlyphForm::Default => return None,
|
||||
GlyphForm::Traditional => b"trad",
|
||||
GlyphForm::Expert => b"expt",
|
||||
GlyphForm::Jis04 => b"jp04",
|
||||
GlyphForm::Jis90 => b"jp90",
|
||||
GlyphForm::Jis78 => b"jp78",
|
||||
GlyphForm::Jis83 => b"jp83",
|
||||
GlyphForm::FullWidth => b"fwid",
|
||||
GlyphForm::HalfWidth => b"hwid",
|
||||
GlyphForm::ThirdWidth => b"twid",
|
||||
GlyphForm::QuarterWidth => b"qwid",
|
||||
})
|
||||
}
|
||||
|
||||
/// Is this one of the monospaced width forms (`fwid`, `hwid`, `twid`, `qwid`)? A font may
|
||||
/// draw them with other glyphs (`GSUB`) or with other widths for the same glyphs (`GPOS`), and
|
||||
/// they set the characters on a fixed width, so Proportional Metrics (`palt`) is not applied
|
||||
/// with them.
|
||||
/// <https://learn.microsoft.com/en-us/typography/opentype/spec/features_fj#tag-fwid>
|
||||
pub fn is_width(self) -> bool {
|
||||
matches!(self, GlyphForm::FullWidth | GlyphForm::HalfWidth | GlyphForm::ThirdWidth | GlyphForm::QuarterWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// A glyph chosen for one character ([`CharStyle::glyph_alternate`]): the glyph id and the face it
|
||||
@@ -586,6 +688,7 @@ impl Default for CharStyle {
|
||||
no_break: false,
|
||||
language: None,
|
||||
glyph_alternate: None,
|
||||
glyph_form: GlyphForm::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -691,6 +794,15 @@ impl CharStyle {
|
||||
self.position = self.position.in_range();
|
||||
self.small_caps = self.small_caps.map(small_caps_in_range);
|
||||
}
|
||||
/// Sets the East Asian glyph form ([`CharStyle::glyph_form`]). A form other than the default
|
||||
/// also takes away the character's glyph choice ([`CharStyle::glyph_alternate`]), which would
|
||||
/// otherwise keep drawing its own glyph; the default form keeps it.
|
||||
pub fn set_glyph_form(&mut self, form: GlyphForm) {
|
||||
self.glyph_form = form;
|
||||
if form != GlyphForm::Default {
|
||||
self.glyph_alternate = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::Document {
|
||||
|
||||
@@ -352,7 +352,10 @@ impl TextObject {
|
||||
}
|
||||
/// Flip type on a path to the other side of its path (Type on a Path Options › Flip, or its
|
||||
/// centre bracket dragged across the path): the path runs the other way and the brackets swap
|
||||
/// ends, so the type keeps its stretch of the path. False, changing nothing, for other type.
|
||||
/// ends, so the type keeps its stretch of the path. Type that starts before an open path's start
|
||||
/// ([`TextKind::path_text_start`]) starts at its start bracket after the flip: the part of its
|
||||
/// span before the path's start would come after the path's end. False, changing nothing, for
|
||||
/// other type.
|
||||
pub fn flip_on_path(&mut self) -> bool {
|
||||
let Some((s, e)) = self.kind.path_span() else { return false };
|
||||
let TextKind::OnPath { path, start, end } = &mut self.kind else { return false };
|
||||
|
||||
@@ -93,8 +93,10 @@ pub enum TextKind {
|
||||
/// Area type flowed inside `frame` (document coordinates, untransformed by `xf`).
|
||||
Area { frame: PathData },
|
||||
/// Type on a path, flowing from its start bracket `start` to its end bracket `end` (0..1 of the
|
||||
/// path length; no `end`: the end of the path, or once round a closed path). See
|
||||
/// [`TextKind::path_span`].
|
||||
/// path length; no `end`: the end of the path, or once round a closed path). On an open path
|
||||
/// `start` may be below 0: the type starts that far before the path's start, and the characters
|
||||
/// whose middle falls before the path's start are not drawn ([`TextKind::path_text_start`]).
|
||||
/// See [`TextKind::path_span`].
|
||||
OnPath {
|
||||
path: PathData,
|
||||
start: f64,
|
||||
@@ -117,8 +119,22 @@ impl TextKind {
|
||||
(s, end.map_or(1.0, |e| fraction(e).max(s)))
|
||||
})
|
||||
}
|
||||
/// Where type on a path's text starts, as a fraction of its path's length: its start bracket
|
||||
/// ([`Self::path_span`]), or on an open path a start before the path's start (below 0, at most
|
||||
/// [`PATH_LEAD_MAX`] path lengths before it). None for other type.
|
||||
pub fn path_text_start(&self) -> Option<f64> {
|
||||
let TextKind::OnPath { path, start, .. } = self else { return None };
|
||||
if !path.is_closed() && start.is_finite() && *start < 0.0 { Some(start.max(-PATH_LEAD_MAX)) } else { self.path_span().map(|(s, _)| s) }
|
||||
}
|
||||
/// Does type on an open path start before its path's start ([`Self::path_text_start`])?
|
||||
pub fn starts_before_path(&self) -> bool {
|
||||
self.path_text_start().is_some_and(|s| s < 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// How far before its path's start type on an open path may start, in lengths of the path.
|
||||
pub const PATH_LEAD_MAX: f64 = 1e6;
|
||||
|
||||
/// Move anchors `refs` of `path`, in text space, by `d` in document space (`to_text`: the
|
||||
/// document → text map). False when an anchor doesn't exist.
|
||||
pub(super) fn move_anchors(path: &mut PathData, to_text: Affine, refs: &[(usize, usize)], d: Vec2) -> bool {
|
||||
|
||||
@@ -563,6 +563,33 @@ fn area_anchors_move_in_document_space() {
|
||||
assert_eq!(t, before);
|
||||
}
|
||||
|
||||
/// Type on an open path may start before the path's start: the start is kept, saved and read back,
|
||||
/// while the start bracket stays at the path's start. On a closed path, and for a start that is not
|
||||
/// finite, the start is the start bracket as before.
|
||||
#[test]
|
||||
fn type_on_an_open_path_starts_before_the_path() {
|
||||
let pts = [Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0)];
|
||||
let on = |closed: bool, start: f64| TextKind::OnPath {
|
||||
path: PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, closed)]),
|
||||
start,
|
||||
end: None,
|
||||
};
|
||||
let open = on(false, -0.25);
|
||||
assert_eq!(open.path_text_start(), Some(-0.25));
|
||||
assert!(open.starts_before_path());
|
||||
assert_eq!(open.path_span(), Some((0.0, 1.0)));
|
||||
let saved = serde_json::to_value(&open).unwrap();
|
||||
assert_eq!(saved["start"], -0.25);
|
||||
assert_eq!(serde_json::from_value::<TextKind>(saved).unwrap(), open);
|
||||
assert_eq!(on(false, -1e9).path_text_start(), Some(-PATH_LEAD_MAX));
|
||||
assert_eq!(on(false, f64::NEG_INFINITY).path_text_start(), Some(0.0));
|
||||
assert_eq!(on(false, 0.25).path_text_start(), Some(0.25));
|
||||
assert!(!on(false, 0.0).starts_before_path());
|
||||
assert_eq!(on(true, -0.25).path_text_start(), Some(0.0));
|
||||
assert!(!on(true, -0.25).starts_before_path());
|
||||
assert_eq!(TextKind::Point.path_text_start(), None);
|
||||
}
|
||||
|
||||
/// Builds from before [`Justify::Auto`] read new type's alignment as Left or Right (and ignore
|
||||
/// `justify_auto`); this build reads Auto back.
|
||||
#[test]
|
||||
|
||||
@@ -156,7 +156,12 @@ impl Unit {
|
||||
/// before it (`3cm*50%` is 1.5 cm, `3cm/50%` is 6 cm). After `+` or `-`, it adds or takes away
|
||||
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
|
||||
/// percentage on its own (`50%`) reads as nothing.
|
||||
///
|
||||
/// Text with more than 128 `+ - * /` signs reads as nothing.
|
||||
pub fn parse(self, s: &str) -> Option<f64> {
|
||||
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
|
||||
return None;
|
||||
}
|
||||
parse_measure(s, self).filter(|v| v.is_finite())
|
||||
}
|
||||
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
|
||||
@@ -207,6 +212,9 @@ impl Unit {
|
||||
}
|
||||
}
|
||||
|
||||
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
|
||||
const MAX_MEASURE_OPERATORS: usize = 128;
|
||||
|
||||
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
|
||||
|
||||
+62
-16
@@ -27,7 +27,9 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
|
||||
|
||||
use crate::distort::{transform_move, transform_offsets};
|
||||
use crate::group::{has_own_paint, paints};
|
||||
use crate::reshape::{as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves};
|
||||
use crate::reshape::{
|
||||
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
|
||||
};
|
||||
use crate::{
|
||||
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
|
||||
has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape,
|
||||
@@ -199,8 +201,19 @@ fn placed_fits(baked: &Node, spent: u64, dropped: u64) -> Option<u64> {
|
||||
}
|
||||
|
||||
/// The names of the symbols of `d` whose art needs baking ([`needs_bake`]), and of those whose art
|
||||
/// holds an instance of one of them at any depth.
|
||||
/// holds an instance of one of them at any depth, in the art of enabled opacity masks too.
|
||||
fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
fn used(n: &Node, names: &mut Vec<String>) {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
if let Some(m) = n.extras().mask.as_ref().filter(|m| !m.disabled) {
|
||||
used(&m.art, names);
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
used(c, names);
|
||||
}
|
||||
}
|
||||
let mut out: HashSet<String> = d.symbols.iter().filter(|s| needs_bake(&s.art)).map(|s| s.name.clone()).collect();
|
||||
if out.is_empty() {
|
||||
return out;
|
||||
@@ -211,11 +224,7 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
.filter(|s| !out.contains(&s.name))
|
||||
.map(|s| {
|
||||
let mut names = vec![];
|
||||
s.art.walk(&mut |c| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &c.kind {
|
||||
names.push(symbol.clone());
|
||||
}
|
||||
});
|
||||
used(&s.art, &mut names);
|
||||
(s.name.as_str(), names)
|
||||
})
|
||||
.collect();
|
||||
@@ -233,14 +242,22 @@ fn drawn_symbols(d: &Document) -> HashSet<String> {
|
||||
}
|
||||
|
||||
/// Does `n`'s subtree hold an instance of a symbol that [`bake_document_placing_symbols`] replaces
|
||||
/// by its placed art? False outside it, and for objects the export does not write ([`unwritten`]).
|
||||
/// by its placed art, in the art of its enabled opacity masks too? False outside it, and for
|
||||
/// objects the export does not write ([`unwritten`]).
|
||||
fn holds_placed_symbol(n: &Node) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>) -> bool {
|
||||
placed_symbol_in(n, true)
|
||||
}
|
||||
|
||||
/// [`holds_placed_symbol`], with the art of `n`'s own opacity mask left out unless `own_mask`
|
||||
/// (the art of the masks inside `n` is always looked into).
|
||||
fn placed_symbol_in(n: &Node, own_mask: bool) -> bool {
|
||||
fn walk(n: &Node, symbols: &HashSet<String>, own_mask: bool) -> bool {
|
||||
!unwritten(n)
|
||||
&& (matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbols.contains(symbol))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols))))
|
||||
|| (own_mask && !n.is_ruler_guide() && n.extras().mask.as_ref().is_some_and(|m| !m.disabled && walk(&m.art, symbols, true)))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| walk(c, symbols, true))))
|
||||
}
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols)))
|
||||
!UNWRITTEN.with(|c| c.get()) && PLACING.with(|p| p.borrow().as_ref().is_some_and(|p| walk(n, &p.symbols, own_mask)))
|
||||
}
|
||||
|
||||
/// Symbol instance `n`, while [`bake_document_placing_symbols`] bakes and its symbol is one it
|
||||
@@ -278,8 +295,29 @@ fn placed_symbol_art(d: &Document, n: &Node) -> Option<(Node, u64)> {
|
||||
Some((g, most))
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged).
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged), and the art of its enabled opacity
|
||||
/// mask baked one level deeper when it holds instances that [`bake_document_placing_symbols`]
|
||||
/// places ([`holds_placed_symbol`]), so the mask masks with the art the instances draw. The art is
|
||||
/// baked only while the object baked from `n` still carries `n`'s mask art; art already baked
|
||||
/// with `n`'s recolored or placed form is not baked again. A ruler guide's mask stays as it is.
|
||||
fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
let out = bake_object(d, n);
|
||||
let Some(mask) = n.extras().mask.as_ref().filter(|m| !m.disabled && !n.is_ruler_guide() && !unwritten(n) && holds_placed_symbol(&m.art)) else {
|
||||
return out;
|
||||
};
|
||||
let changed = out.is_some();
|
||||
let mut out = out.unwrap_or_else(|| n.clone());
|
||||
let Some(slot) = out.extras_if_any().and_then(|e| e.mask.as_mut()).filter(|s| Arc::ptr_eq(&s.art, &mask.art)) else {
|
||||
return changed.then_some(out);
|
||||
};
|
||||
let Some(art) = one_deeper(|| bake_node(d, &mask.art)) else { return changed.then_some(out) };
|
||||
slot.art = Arc::new(art);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// `n` with its geometry effects evaluated (`None` = unchanged); its opacity mask is left to
|
||||
/// [`bake_node`].
|
||||
fn bake_object(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
// Inside an object the export leaves out, effects are baked but no instance is placed.
|
||||
if !UNWRITTEN.with(|c| c.get()) && unwritten(n) {
|
||||
UNWRITTEN.with(|c| c.set(true));
|
||||
@@ -289,7 +327,8 @@ fn bake_node(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
}
|
||||
// A cancelled export leaves the rest of the document as it is: the caller drops the result.
|
||||
// A ruler guide draws nothing and stays as it is, last in its layer.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || holds_placed_symbol(n)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
// An object whose own mask's art alone holds placed instances stays as it is here.
|
||||
if n.is_ruler_guide() || !(needs_bake(n) || placed_symbol_in(n, false)) || vectorcraft_doc::cancel::is_cancelled() {
|
||||
return None;
|
||||
}
|
||||
// Colour adjustments: the object recoloured (inside it too), then baked as it is.
|
||||
@@ -476,14 +515,18 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
|
||||
|
||||
/// `m`, art evaluated from an object, with its children baked and then given ids of their own (the
|
||||
/// pieces copied from the source keep the source's ids until then). The pieces are baked with the
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id.
|
||||
/// ids the renderer draws them with: Random in a Transform effect takes its seed from the id. When
|
||||
/// `m` clips, its clipping path, unless it is type, first takes the geometry effects in it as the
|
||||
/// canvas clips by it ([`crate::clip::with_clip_effects_applied`]).
|
||||
fn bake_pieces(d: &mut Document, mut m: Node) -> Node {
|
||||
let mut seen = std::collections::HashSet::from([m.id]);
|
||||
let clip = usize::from(m.clips() && !m.children().and_then(|ch| ch.first()).is_some_and(|c| matches!(c.kind, NodeKind::Text(_))));
|
||||
let children = m.children().cloned().unwrap_or_default();
|
||||
let children = children
|
||||
.into_iter()
|
||||
.map(|c| {
|
||||
let c = Arc::unwrap_or_clone(c);
|
||||
.enumerate()
|
||||
.map(|(i, c)| {
|
||||
let c = (i < clip).then(|| crate::clip::with_clip_effects_applied(&c)).flatten().unwrap_or_else(|| Arc::unwrap_or_clone(c));
|
||||
let mut c = one_deeper(|| bake_node(d, &c)).unwrap_or(c);
|
||||
fresh_ids(d, &mut c, &mut seen);
|
||||
Arc::new(c)
|
||||
@@ -648,6 +691,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
|
||||
/// them. `None` when no type stays type.
|
||||
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
|
||||
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
|
||||
if !clipping {
|
||||
paint_type_clip(Some(d), n);
|
||||
}
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
|
||||
@@ -1169,6 +1169,74 @@ fn placing_symbols_reaches_the_art_of_nested_instances() {
|
||||
assert!(near_rect(bounds(&out, 900), Rect::new(110.0, 140.0, 120.0, 150.0)), "{:?}", bounds(&out, 900));
|
||||
}
|
||||
|
||||
/// A 10 pt square with id `id`, masked by `art` (the mask enabled unless `disabled`).
|
||||
fn masked_square(id: u64, art: Node, disabled: bool) -> Node {
|
||||
let mut n = Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
|
||||
let mut mask = vectorcraft_doc::OpacityMask::new(art, false);
|
||||
mask.disabled = disabled;
|
||||
n.extras_mut().mask = Some(Box::new(mask));
|
||||
n
|
||||
}
|
||||
|
||||
/// Whether the art of `n`'s opacity mask is still a symbol instance, and its bounds when it is not.
|
||||
fn mask_art(n: &Node) -> (bool, Option<Rect>) {
|
||||
let art = &n.extras().mask.as_ref().unwrap_or_else(|| panic!("node {:?} has a mask", n.id)).art;
|
||||
(matches!(art.kind, NodeKind::SymbolInstance { .. }), art.geometric_bounds())
|
||||
}
|
||||
|
||||
/// An instance in the art of an enabled opacity mask is placed and baked like any other, so the
|
||||
/// mask masks with the art the instance draws, and the masked object stays as it is (a clipping
|
||||
/// path stays one); one in a disabled mask, in the mask of an object the export leaves out, or in
|
||||
/// a ruler guide's mask, stays as it is.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_opacity_masks() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(masked_square(700, instance(900, "S", Affine::IDENTITY), false));
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 1, masked_square(701, instance(901, "S", Affine::IDENTITY), true)).unwrap();
|
||||
let mut hidden = masked_square(702, instance(902, "S", Affine::IDENTITY), false);
|
||||
hidden.visible = false;
|
||||
d.insert(Some(layer), 2, hidden).unwrap();
|
||||
let mut clipping = masked_square(703, instance(903, "S", Affine::IDENTITY), false);
|
||||
if let NodeKind::Path { clipping: c, .. } = &mut clipping.kind {
|
||||
*c = true;
|
||||
}
|
||||
d.insert(Some(layer), 3, Node::group(NodeId(704), vec![Arc::new(clipping)])).unwrap();
|
||||
let mut guide = Node::new(NodeId(705), NodeKind::RulerGuide { vertical: false, pos: 5.0, artboard: None });
|
||||
guide.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(instance(905, "S", Affine::IDENTITY), false)));
|
||||
d.insert(Some(layer), 4, guide).unwrap();
|
||||
add_symbol(&mut d, "S", moved_square(800));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
for id in [700, 703] {
|
||||
let (still, b) = mask_art(out.node(NodeId(id)).unwrap());
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{id}: {b:?}");
|
||||
}
|
||||
assert!(matches!(out.node(NodeId(703)).unwrap().kind, NodeKind::Path { clipping: true, .. }), "the clipping path stays one");
|
||||
assert!(mask_art(out.node(NodeId(701)).unwrap()).0, "a disabled mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(702)).unwrap()).0, "a hidden object's mask's instance stays");
|
||||
assert!(mask_art(out.node(NodeId(705)).unwrap()).0, "a ruler guide's mask's instance stays");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance only in an opacity mask's art is placed too, and the
|
||||
/// instance in its mask is placed with it.
|
||||
#[test]
|
||||
fn placing_symbols_reaches_instances_in_the_masks_of_symbol_art() {
|
||||
use vectorcraft_geom::Affine;
|
||||
let mut d = doc_with(instance(900, "Outer", Affine::IDENTITY));
|
||||
add_symbol(&mut d, "Inner", moved_square(800));
|
||||
add_symbol(&mut d, "Outer", masked_square(803, instance(802, "Inner", Affine::IDENTITY), false));
|
||||
let out = bake_document_placing_symbols(&d, true, ALL).unwrap();
|
||||
assert!(!is_instance(&out, 900), "the outer instance is placed");
|
||||
let mut found = None;
|
||||
out.node(NodeId(900)).unwrap().walk(&mut |n| {
|
||||
if n.id == NodeId(803) {
|
||||
found = Some(mask_art(n));
|
||||
}
|
||||
});
|
||||
let (still, b) = found.unwrap_or_else(|| panic!("the masked square is in the placed art"));
|
||||
assert!(!still && b.is_some_and(|b| near_rect(b, Rect::new(110.0, 40.0, 120.0, 50.0))), "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol whose art holds an instance of itself is placed until the depth limit, and the export
|
||||
/// ends.
|
||||
#[test]
|
||||
|
||||
@@ -182,29 +182,29 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
REVOLVE,
|
||||
"Revolve…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), 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), segments: integer (8..128, 64), 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), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"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,"cap":true,"expandVisibleOnly":true,"graphics":[]}),
|
||||
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), 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), segments: integer (8..128, 64), 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), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
|
||||
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"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,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
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), 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":[]}),
|
||||
"{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), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. 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":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
INFLATE,
|
||||
"Inflate…",
|
||||
&["Effect", "3D and Materials"],
|
||||
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":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, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), 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), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
|
||||
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":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,"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
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), 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":[]}),
|
||||
"{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), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. 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":[],"render":{"mode":"shaded"}}),
|
||||
),
|
||||
g(
|
||||
CLASSIC_EXTRUDE,
|
||||
@@ -417,7 +417,7 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"artistic.roughPastels",
|
||||
"Rough Pastels…",
|
||||
ARTISTIC,
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\" (\"canvas\"), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
"{strokeLength: 0..40 (6; longer pastel strokes), strokeDetail: 1..20 (10; bristle texture along the strokes), texture: \"brick\"|\"burlap\"|\"canvas\"|\"sandstone\"|\"loaded\" (\"canvas\"; \"loaded\" draws the image in textureImage and draws Canvas when there is none; the others are surfaces made in code), textureImage?: {path} | {name?, dataBase64} | string (Load Texture…: an image file that File › Place reads, within the renderer's pixel allowance, stored as its gray levels in a grayscale PNG in base64; a file sets texture to \"loaded\" unless texture is given, and the stored string, as effect.list gives it, is kept as it is), scaling: % 50..200 (100), relief: 0..50 (4), lightDirection: \"bottom\"|\"bottomLeft\"|\"left\"|\"topLeft\"|\"top\"|\"topRight\"|\"right\"|\"bottomRight\" (\"top\"), invert: bool (false)} repaints the object in soft diagonal pastel strokes over a textured surface, keeping its coverage. A loaded texture lies one image pixel per point at 100 %, centered on the object's center and repeated; each pixel's luma is the surface's height, from 0 for black to 1 pt for white, and a transparent pixel counts as middle gray. Slider ranges follow the documented controls; numeric defaults are chosen for VectorCraft and are not verified against proprietary defaults.",
|
||||
json!({
|
||||
"strokeLength": 6.0,
|
||||
"strokeDetail": 10.0,
|
||||
@@ -468,8 +468,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
|
||||
"blur.radial",
|
||||
"Radial Blur…",
|
||||
BLUR,
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples)} blurs around the object's centre",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good"}),
|
||||
"{amount: 1..100 (10; spin: an arc of `amount`°, zoom: the content scaled by up to about ±amount/2 %), method: \"spin\"|\"zoom\" (\"spin\"), quality: \"draft\"|\"good\"|\"best\" (\"good\"; 16, 64 or 256 samples), centerX: 0..1 (0.5; the Blur Center across the object's bounds, 0 their left edge), centerY: 0..1 (0.5; the Blur Center down the object's bounds, 0 their top edge)} blurs around the Blur Center, which moves and scales with the object. A centerX or centerY outside 0..1 is refused",
|
||||
json!({"amount": 10.0, "method": "spin", "quality": "good", "centerX": 0.5, "centerY": 0.5}),
|
||||
),
|
||||
r(
|
||||
"blur.smart",
|
||||
|
||||
@@ -12,10 +12,14 @@ use vectorcraft_geom::{BezPath, FillRule, PathData};
|
||||
/// fills and strokes: the region is then the union of the paths they give, as an export bakes them.
|
||||
/// `None` when there is nothing to clip by (the clipped art is then hidden).
|
||||
pub fn clip_outline(clip: &Node) -> Option<(BezPath, FillRule)> {
|
||||
match clip_effects_applied(clip, true, || true) {
|
||||
Some(m) => m.clip_outline(Some(&outline_text), &unite),
|
||||
None => clip.clip_outline(Some(&outline_text), &unite),
|
||||
}
|
||||
reshaped_clip_outline(clip).unwrap_or_else(|| clip.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// [`clip_outline`] of a clipping path that a live geometry effect reshapes; `None` when nothing
|
||||
/// `clip` clips by has a geometry effect of its own or on a fill or stroke. A hidden member of a
|
||||
/// group or layer does not clip, so its effects are not counted.
|
||||
pub fn reshaped_clip_outline(clip: &Node) -> Option<Option<(BezPath, FillRule)>> {
|
||||
clip_effects_applied(clip, true, || true).map(|m| m.clip_outline(Some(&outline_text), &unite))
|
||||
}
|
||||
|
||||
/// `n`, the clipping path of a clip group, with the live geometry effects of everything it clips by
|
||||
|
||||
@@ -72,7 +72,7 @@ pub use bake::{
|
||||
StrokeArt, WrittenLayers, bake_appearance, bake_document, bake_document_placing_symbols, bake_type_appearance, expand_art, expand_leaf,
|
||||
fresh_ids, needs_bake,
|
||||
};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, warp_pieces_translucent};
|
||||
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
|
||||
pub use group::{
|
||||
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
|
||||
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, shape_art,
|
||||
@@ -85,18 +85,19 @@ pub use raster::{RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item
|
||||
pub use reshape::{
|
||||
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
|
||||
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
|
||||
outline_text, reshape,
|
||||
outline_text, paint_type_piece, reshape,
|
||||
};
|
||||
pub use revolve::{
|
||||
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
|
||||
};
|
||||
pub use solids::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, 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,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
|
||||
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
|
||||
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
|
||||
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
|
||||
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
|
||||
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
|
||||
with_graphic,
|
||||
};
|
||||
pub use solids::{
|
||||
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
|
||||
|
||||
+22
-16
@@ -30,7 +30,7 @@ mod texture;
|
||||
mod video;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use crate::util::{flag, num, text};
|
||||
|
||||
@@ -155,12 +155,14 @@ pub enum PixelFx {
|
||||
/// `texture_coverage` (0..40) says.
|
||||
Underpainting { brush_size: f64, texture_coverage: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Artistic › Rough Pastels: diagonal pastel strokes `length` (0..40) long, bristle detail
|
||||
/// (1..20), then a [`Texture`] surface scaled by `scaling` (0.5..2), in relief as strong as
|
||||
/// `relief` (0..50) and lit from `light`; `invert` turns the surface's heights over.
|
||||
/// (1..20), then a [`Texture`] surface (a loaded one included) scaled by `scaling` (0.5..2), in
|
||||
/// relief as strong as `relief` (0..50) and lit from `light`; `invert` turns the surface's
|
||||
/// heights over.
|
||||
RoughPastels { length: f64, detail: f64, texture: Texture, scaling: f64, relief: f64, light: Light, invert: bool },
|
||||
/// Blur › Radial Blur around the object's centre: along arcs (spin, an arc of `amount`°) or
|
||||
/// along rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32 },
|
||||
/// Blur › Radial Blur around its Blur Center, `center` (0..1 across and down the object's
|
||||
/// bounds; (0.5, 0.5) the object's centre): along arcs (spin, an arc of `amount`°) or along
|
||||
/// rays (zoom, the content scaled by up to about ±`amount`/2 %), averaging 2^`passes` samples.
|
||||
RadialBlur { amount: f64, zoom: bool, passes: u32, center: [f64; 2] },
|
||||
/// Blur › Smart Blur (Normal mode): each pixel averaged with the neighbours within `radius`
|
||||
/// whose colour differs from its own by no more than `threshold` levels, over a grid of
|
||||
/// `samples` × `samples` neighbours at most.
|
||||
@@ -314,9 +316,12 @@ pub struct PixelSpace {
|
||||
pub to_doc: Affine,
|
||||
/// The size of a pixel in document units.
|
||||
pub px: f64,
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around, and where the
|
||||
/// Pixelate filters' patterns are anchored (so they move with the object).
|
||||
/// The object's centre (document coordinates): where Radial Blur blurs around by default, and
|
||||
/// where the Pixelate filters' patterns are anchored (so they move with the object).
|
||||
pub center: Point,
|
||||
/// The width and height of the object's bounds (document units), centred on `center`: Radial
|
||||
/// Blur's Blur Center lies at a share of them.
|
||||
pub size: Vec2,
|
||||
/// What the colour channels hold.
|
||||
pub channels: Channels,
|
||||
/// The height of a line of the document's raster grid (document units: 72 / Document Raster
|
||||
@@ -381,7 +386,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
"artistic.roughPastels" => PixelFx::RoughPastels {
|
||||
length: num(p, "strokeLength", 6.0).clamp(0.0, 40.0),
|
||||
detail: num(p, "strokeDetail", 10.0).clamp(1.0, 20.0),
|
||||
texture: Texture::parse(text(p, "texture", "canvas")),
|
||||
texture: Texture::parse_with(text(p, "texture", "canvas"), p.get(TEXTURE_IMAGE).and_then(Value::as_str)),
|
||||
scaling: num(p, "scaling", 100.0).clamp(50.0, 200.0) / 100.0,
|
||||
relief: num(p, "relief", 4.0).clamp(0.0, 50.0),
|
||||
light: Light::parse(text(p, "lightDirection", "top")),
|
||||
@@ -421,6 +426,7 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
amount: num(p, "amount", 10.0).clamp(1.0, 100.0),
|
||||
zoom: text(p, "method", "spin").eq_ignore_ascii_case("zoom"),
|
||||
passes: quality([("draft", 4), ("good", 6), ("best", 8)], 6),
|
||||
center: [num(p, "centerX", 0.5).clamp(0.0, 1.0), num(p, "centerY", 0.5).clamp(0.0, 1.0)],
|
||||
},
|
||||
"blur.smart" => PixelFx::SmartBlur {
|
||||
radius: num(p, "radius", 3.0).clamp(0.1, 100.0),
|
||||
@@ -608,13 +614,13 @@ pub(crate) fn parse(id: &str, p: &Value) -> Option<PixelFx> {
|
||||
impl PixelFx {
|
||||
/// How far beyond `bounds` (the content's, document units) the effect can paint.
|
||||
pub fn outset(&self, bounds: Rect) -> f64 {
|
||||
// From the centre to the farthest corner, and to the nearest side.
|
||||
let far = 0.5 * bounds.width().hypot(bounds.height());
|
||||
let near = 0.5 * bounds.width().min(bounds.height());
|
||||
match *self {
|
||||
// A rotated corner reaches the circle through the corners.
|
||||
PixelFx::RadialBlur { zoom: false, .. } => (far - near).max(0.0),
|
||||
PixelFx::RadialBlur { amount, zoom: true, .. } => far * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
// A rotated corner reaches the circle about the Blur Center through the farthest corner.
|
||||
PixelFx::RadialBlur { zoom: false, center, .. } => {
|
||||
let (far, near) = blur::center_reach(bounds, center);
|
||||
(far - near).max(0.0)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom: true, center, .. } => blur::center_reach(bounds, center).0 * (blur::zoom_extent(amount).exp() - 1.0),
|
||||
PixelFx::SmartBlur { radius, .. } => radius,
|
||||
PixelFx::AccentedEdges { .. } => 0.0,
|
||||
// Strokes reach out of the object as far as they reach into it.
|
||||
@@ -786,7 +792,7 @@ impl PixelFx {
|
||||
PixelFx::RoughPastels { length, detail, ref texture, scaling, relief, light, invert } => {
|
||||
artistic::rough_pastels(px, w, h, space, length, detail, texture, scaling, relief, light, invert)
|
||||
}
|
||||
PixelFx::RadialBlur { amount, zoom, passes } => blur::radial(px, w, h, space, amount, zoom, passes),
|
||||
PixelFx::RadialBlur { amount, zoom, passes, center } => blur::radial(px, w, h, space, amount, zoom, passes, center),
|
||||
PixelFx::SmartBlur { radius, threshold, samples, mode: SmartBlurMode::Normal } => {
|
||||
blur::smart(px, w, h, to_px(radius), threshold, samples)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Blur › Radial Blur and Smart Blur (Normal, Edge Only and Overlay Edge).
|
||||
|
||||
use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
|
||||
|
||||
use super::{PixelSpace, Px16, box_blur, pick, to8, to16};
|
||||
|
||||
@@ -29,13 +29,31 @@ fn bilinear(buf: &[Px16], w: usize, h: usize, x: f64, y: f64) -> [f32; 4] {
|
||||
std::array::from_fn(|i| a[i] * wa + b[i] * wb + c[i] * wc + d[i] * wd)
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the centre over
|
||||
/// evenly spaced steps spanning `amount`. Each pass averages the previous result with itself
|
||||
/// turned both ways by half the last step, so `passes` passes average 2^`passes` samples at two
|
||||
/// lookups a pixel each.
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32) {
|
||||
/// How far Radial Blur's Blur Center `center` (0..1 across and down `bounds`) lies from the
|
||||
/// farthest corner of `bounds`, and from its nearest side.
|
||||
pub(super) fn center_reach(bounds: Rect, center: [f64; 2]) -> (f64, f64) {
|
||||
// The share of the width (height) on the far side of the center, doubled: 1 at the middle.
|
||||
let far = |f: f64| 1.0 + (2.0 * f - 1.0).abs();
|
||||
let (w, h) = (bounds.width(), bounds.height());
|
||||
let near = ((2.0 - far(center[0])) * w).min((2.0 - far(center[1])) * h);
|
||||
(0.5 * (far(center[0]) * w).hypot(far(center[1]) * h), 0.5 * near)
|
||||
}
|
||||
|
||||
/// Where Radial Blur's Blur Center `center` (0..1 across and down the object's bounds) lies in the
|
||||
/// document: the object's centre at (0.5, 0.5).
|
||||
pub(super) fn blur_center(space: &PixelSpace, center: [f64; 2]) -> Point {
|
||||
let shift = Vec2::new((center[0] - 0.5) * space.size.x, (center[1] - 0.5) * space.size.y);
|
||||
if shift.x.is_finite() && shift.y.is_finite() { space.center + shift } else { space.center }
|
||||
}
|
||||
|
||||
/// Radial Blur: the average of the content turned (spin) or scaled (zoom) about the Blur Center
|
||||
/// (`center`, [`blur_center`]) over evenly spaced steps spanning `amount`. Each pass averages the
|
||||
/// previous result with itself turned both ways by half the last step, so `passes` passes average
|
||||
/// 2^`passes` samples at two lookups a pixel each.
|
||||
#[allow(clippy::too_many_arguments)] // the effect's four options
|
||||
pub(super) fn radial(px: &mut [[u8; 4]], w: usize, h: usize, space: &PixelSpace, amount: f64, zoom: bool, passes: u32, center: [f64; 2]) {
|
||||
// The centre in pixel index coordinates (pixel centres at whole numbers).
|
||||
let c = space.to_doc.inverse() * space.center - Vec2::new(0.5, 0.5);
|
||||
let c = space.to_doc.inverse() * blur_center(space, center) - Vec2::new(0.5, 0.5);
|
||||
if !(c.x.is_finite() && c.y.is_finite()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
@@ -479,12 +480,16 @@ fn film_grain_leaves_invalid_coordinate_spaces_alone() {
|
||||
|
||||
#[test]
|
||||
fn params_take_defaults_and_stay_in_range() {
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.radial", json!({})), PixelFx::RadialBlur { amount: 10.0, zoom: false, passes: 6, center: [0.5, 0.5] });
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best"})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8 }
|
||||
fx("blur.radial", json!({"amount": 1e308, "method": "ZOOM", "quality": "best", "centerX": 0.25, "centerY": 1})),
|
||||
PixelFx::RadialBlur { amount: 100.0, zoom: true, passes: 8, center: [0.25, 1.0] }
|
||||
);
|
||||
// A saved center outside the bounds (the commands refuse one) draws at the nearest edge.
|
||||
assert_eq!(
|
||||
fx("blur.radial", json!({"amount": -5, "quality": "nonsense", "centerX": -3, "centerY": 7})),
|
||||
PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6, center: [0.0, 1.0] }
|
||||
);
|
||||
assert_eq!(fx("blur.radial", json!({"amount": -5, "quality": "nonsense"})), PixelFx::RadialBlur { amount: 1.0, zoom: false, passes: 6 });
|
||||
assert_eq!(fx("blur.smart", json!({})), PixelFx::SmartBlur { radius: 3.0, threshold: 25.0, samples: 7, mode: SmartBlurMode::Normal });
|
||||
assert_eq!(
|
||||
fx("blur.smart", json!({"radius": "1e999", "threshold": -1, "quality": "low", "blurMode": "EDGEONLY"})),
|
||||
@@ -519,6 +524,11 @@ fn outsets_follow_the_object() {
|
||||
let far = 0.5 * 100f64.hypot(50.0);
|
||||
assert!((spin.outset(b) - (far - 25.0)).abs() < 1e-9);
|
||||
assert!(fx("blur.radial", json!({"method": "zoom", "amount": 100})).outset(b) > 0.4 * far);
|
||||
// About a corner the spin reaches the circle through the opposite corner, the whole diagonal out.
|
||||
let corner = fx("blur.radial", json!({"centerX": 0, "centerY": 0}));
|
||||
assert!((corner.outset(b) - 100f64.hypot(50.0)).abs() < 1e-9, "{}", corner.outset(b));
|
||||
let zoom = |center: f64| fx("blur.radial", json!({"method": "zoom", "amount": 100, "centerX": center, "centerY": center})).outset(b);
|
||||
assert!((zoom(1.0) - 2.0 * zoom(0.5)).abs() < 1e-9, "a zoom about a corner reaches twice as far");
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).outset(b), 4.0);
|
||||
assert_eq!(fx("blur.smart", json!({"radius": 4})).reach(1.0), Some(4.0));
|
||||
// The edge modes also read the copy blurred over a wide radius's samples.
|
||||
@@ -633,6 +643,40 @@ fn spin_blur_smears_along_arcs_and_keeps_the_centre() {
|
||||
assert_eq!(at(&z, w, 32, 16)[3], 0, "not across it");
|
||||
}
|
||||
|
||||
/// The Blur Center moves the point the blur turns about: a dot on it stays sharp, a dot on the
|
||||
/// object's centre then spreads, and the center follows the object when it moves or is scaled.
|
||||
#[test]
|
||||
fn radial_blur_turns_about_its_blur_center() {
|
||||
let (w, h) = (41, 41);
|
||||
// A dot on pixel (10, 30), whose centre (10.5, 30.5) is the Blur Center below, and one on the
|
||||
// object's centre.
|
||||
let src = image(w, h, |x, y| if (x == 10 && y == 30) || (x == 20 && y == 20) { grey(255) } else { [0, 0, 0, 0] });
|
||||
let blur = |p: serde_json::Value, s: &PixelSpace, src: &[u8]| {
|
||||
let mut d = src.to_vec();
|
||||
fx("blur.radial", p).apply(&mut d, w, h, s);
|
||||
d
|
||||
};
|
||||
let off = json!({"amount": 60, "quality": "best", "centerX": 10.5 / 41.0, "centerY": 30.5 / 41.0});
|
||||
let d = blur(off.clone(), &space(w, h), &src);
|
||||
assert!(at(&d, w, 10, 30)[3] > 100, "the dot on the Blur Center barely moves: {:?}", at(&d, w, 10, 30));
|
||||
assert!(at(&d, w, 20, 20)[3] < 100, "the dot on the object's centre spreads: {:?}", at(&d, w, 20, 20));
|
||||
// The default center is the object's centre, the same as no center at all.
|
||||
assert_eq!(blur(json!({"amount": 60, "centerX": 0.5, "centerY": 0.5}), &space(w, h), &src), blur(json!({"amount": 60}), &space(w, h), &src));
|
||||
// Moved 7 pt right and 3 pt down, the object draws the same pixels.
|
||||
let moved =
|
||||
PixelSpace { to_doc: Affine::translate((7.0, 3.0)), center: space(w, h).center + vectorcraft_geom::Vec2::new(7.0, 3.0), ..space(w, h) };
|
||||
assert_eq!(blur(off.clone(), &moved, &src), d, "the center moves with the object");
|
||||
// Drawn at twice the size (two points a pixel), the center lies on the same pixels.
|
||||
let big = PixelSpace {
|
||||
to_doc: Affine::scale(2.0),
|
||||
px: 2.0,
|
||||
center: Point::new(41.0, 41.0),
|
||||
size: vectorcraft_geom::Vec2::new(82.0, 82.0),
|
||||
..space(w, h)
|
||||
};
|
||||
assert_eq!(blur(off, &big, &src), d, "the center scales with the object");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_blur_smooths_noise_and_keeps_edges() {
|
||||
let (w, h) = (40, 20);
|
||||
@@ -862,6 +906,7 @@ fn lengths_are_document_units() {
|
||||
to_doc: Affine::scale(1.0 / scale as f64),
|
||||
px: 1.0 / scale as f64,
|
||||
center: Point::ZERO,
|
||||
size: vectorcraft_geom::Vec2::ZERO,
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
@@ -916,7 +961,15 @@ fn linear_light_blur_mixes_light_not_values() {
|
||||
fn pixel_timings() {
|
||||
let (w, h) = (2000, 2000);
|
||||
let src = image(w, h, |x, y| [(x % 256) as u8, (y % 256) as u8, ((x ^ y) % 256) as u8, 255]);
|
||||
let s = PixelSpace { to_doc: Affine::IDENTITY, px: 1.0, center: Point::new(1000.0, 1000.0), channels: Channels::Rgb, line: 1.0, extent: 0.0 };
|
||||
let s = PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1000.0, 1000.0),
|
||||
size: vectorcraft_geom::Vec2::new(2000.0, 2000.0),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.0,
|
||||
};
|
||||
let cases = [
|
||||
("blur.radial", json!({"quality": "draft"})),
|
||||
("blur.radial", json!({"quality": "good"})),
|
||||
@@ -1494,6 +1547,42 @@ fn texturizer_draws_a_loaded_texture_as_relief() {
|
||||
assert_eq!(fx("texture.texturizer", json!({"texture": "LOADED", "textureImage": "not a texture"})), fx("texture.texturizer", json!({})));
|
||||
}
|
||||
|
||||
/// Rough Pastels draws a loaded texture as its surface, and Scaling, Relief, Light Direction and
|
||||
/// Invert act on it as on the built-in ones.
|
||||
#[test]
|
||||
fn rough_pastels_draws_a_loaded_texture_as_its_surface() {
|
||||
let w = 64;
|
||||
let mid = grey(150);
|
||||
let rings = stored(12, 10, |x, y| {
|
||||
let v = ((x as f64 - 5.5).hypot(y as f64 - 4.5) * 0.9).sin().abs();
|
||||
let g = (v * 255.0).round() as u8;
|
||||
[g, g, g, 255]
|
||||
});
|
||||
let run = |mut p: serde_json::Value| {
|
||||
p["strokeLength"] = json!(0);
|
||||
let mut d = flat(w, mid);
|
||||
fx("artistic.roughPastels", p).apply(&mut d, w, w, &space(w, w));
|
||||
d
|
||||
};
|
||||
let relief = run(json!({"texture": "loaded", "textureImage": rings, "relief": 20}));
|
||||
assert_ne!(relief, flat(w, mid));
|
||||
for (_, builtin) in TEXTURES {
|
||||
assert_ne!(relief, run(json!({"texture": builtin, "relief": 20})), "{builtin}");
|
||||
}
|
||||
for (key, value) in [("invert", json!(true)), ("scaling", json!(200)), ("lightDirection", json!("bottomRight")), ("relief", json!(5))] {
|
||||
let mut p = json!({"texture": "loaded", "textureImage": rings, "relief": 20});
|
||||
p[key] = value;
|
||||
assert_ne!(run(p), relief, "{key}");
|
||||
}
|
||||
assert_eq!(run(json!({"texture": "loaded", "textureImage": rings, "relief": 0})), flat(w, mid));
|
||||
let parsed = fx("artistic.roughPastels", json!({"texture": "Loaded", "textureImage": rings}));
|
||||
assert!(matches!(parsed, PixelFx::RoughPastels { texture: Texture::Loaded(_), .. }), "{parsed:?}");
|
||||
// Without a stored texture, or with one that isn't, Loaded draws Canvas.
|
||||
for p in [json!({"texture": "loaded"}), json!({"texture": "loaded", "textureImage": "not a texture"})] {
|
||||
assert_eq!(fx("artistic.roughPastels", p), fx("artistic.roughPastels", json!({})));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Texture filters' patterns lie in document space around the object's centre: the same at
|
||||
/// twice the resolution, and moving with the object.
|
||||
#[test]
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -14,6 +14,7 @@ fn space(w: usize, h: usize) -> PixelSpace {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(w / 2.0, h / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(w, h),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * w.hypot(h),
|
||||
|
||||
@@ -508,6 +508,20 @@ fn laid_out(t: &vectorcraft_doc::TextObject) -> (Vec<kurbo::BezPath>, kurbo::Bez
|
||||
(runs, all, layout.bounds, colours)
|
||||
}
|
||||
|
||||
/// Paint `piece`, a piece of type's outline in text space (glyphs, ruby glyphs or an underline or
|
||||
/// strikethrough bar), with `style`, the fills and strokes of its run, and place it in the document
|
||||
/// by `xf`, the type's transform, as the renderer paints the run: its unplaced gradients are fixed
|
||||
/// to `bounds`, the layout's bounds in text space, so every piece of the type shows the one
|
||||
/// gradient fitted across the whole layout, and the transform also scales its stroke weights and
|
||||
/// dashes and transforms its pattern tiles. Placed gradients keep their place in text space and
|
||||
/// move with the type.
|
||||
pub fn paint_type_piece(piece: &mut Node, style: &vectorcraft_doc::CharStyle, bounds: Rect, xf: Affine) {
|
||||
let mut ap = style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
piece.appearance = ap.into();
|
||||
piece.transform(xf, vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() });
|
||||
}
|
||||
|
||||
/// Type as glyph outlines in document space: one path per run with the run's fill and stroke,
|
||||
/// over its colour glyphs (images, art), and (when the object has its own fills/strokes) the whole
|
||||
/// outline with the object's items below the characters under them and the others over them, as
|
||||
@@ -520,7 +534,6 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
let NodeKind::Text(t) = &n.kind else { return None };
|
||||
let (runs, all, bounds, colours) = laid_out(t);
|
||||
let path = |bp: &kurbo::BezPath| PathData::from_bezpath(bp).transformed(t.xf);
|
||||
let scaling = vectorcraft_doc::Scaling { strokes: true, patterns: true, ..Default::default() };
|
||||
let mut children: Vec<Arc<Node>> = vec![];
|
||||
for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() {
|
||||
// Colour glyphs paint themselves, under their run's fill, as the renderer paints them.
|
||||
@@ -528,10 +541,8 @@ pub fn outline_text(n: &Node) -> Option<Node> {
|
||||
if bp.elements().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut ap = run.style.appearance();
|
||||
ap.pin_gradients(bounds);
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), ap);
|
||||
piece.transform(t.xf, scaling);
|
||||
let mut piece = Node::path(n.id, PathData::from_bezpath(bp), Appearance::default());
|
||||
paint_type_piece(&mut piece, &run.style, bounds, t.xf);
|
||||
children.push(Arc::new(piece));
|
||||
}
|
||||
if !n.appearance.items.is_empty() && !all.elements().is_empty() {
|
||||
@@ -735,9 +746,13 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option<Node> {
|
||||
|
||||
/// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look
|
||||
/// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes
|
||||
/// its outlines with its visibility and effects ([`clipping_text_outline`]). The swatches and
|
||||
/// patterns that live-effect plug-ins painting their pieces name are looked up in `doc`.
|
||||
/// its outlines with its visibility and effects ([`clipping_text_outline`]), and its fills and
|
||||
/// strokes become art of their own ([`paint_type_clip`]). The swatches and patterns that
|
||||
/// live-effect plug-ins painting their pieces name are looked up in `doc`.
|
||||
pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) {
|
||||
if !clipping {
|
||||
paint_type_clip(doc, n);
|
||||
}
|
||||
let clips = n.clips();
|
||||
let Some(ch) = n.children_mut() else { return };
|
||||
for (i, c) in ch.iter_mut().enumerate() {
|
||||
@@ -755,6 +770,36 @@ pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping
|
||||
}
|
||||
}
|
||||
|
||||
/// When `n` is a clip group or clipping layer whose clipping path is type that paints
|
||||
/// ([`Node::clip_paint`]), make it the art the canvas draws for it: the type's outlines clip
|
||||
/// ([`clipping_text_outline`]), its fills as art ([`as_art`]) paint behind the clipped art inside
|
||||
/// the clip, and its strokes as art paint over it, outside the clip, in a group that `n` becomes
|
||||
/// (keeping its id, name and transparency) with the clip group inside. The other members stay as
|
||||
/// they are. Hidden type paints nothing.
|
||||
pub(crate) fn paint_type_clip(doc: Option<&Document>, n: &mut Node) {
|
||||
let Some((first, rest)) = n.children().and_then(|ch| ch.split_first()) else { return };
|
||||
if !n.clips() || !matches!(first.kind, NodeKind::Text(_)) || !first.visible {
|
||||
return;
|
||||
}
|
||||
let paint = first.clip_paint();
|
||||
if paint.fill.is_none() && paint.stroke.is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(clip) = clipping_text_outline(first) else { return };
|
||||
let art = |part: Option<Node>| part.and_then(|p| as_art(doc, &p, None)).map(Arc::new);
|
||||
let members: Vec<Arc<Node>> = std::iter::once(Arc::new(clip)).chain(art(paint.fill)).chain(rest.iter().cloned()).collect();
|
||||
let stroke = art(paint.stroke);
|
||||
let id = n.id;
|
||||
match (&mut n.kind, stroke) {
|
||||
(NodeKind::Group { children, .. } | NodeKind::Layer { children, .. }, None) => *children = members,
|
||||
(NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. }, Some(stroke)) => {
|
||||
*children = vec![Arc::new(Node::new(id, NodeKind::Group { children: members, clip: true })), stroke];
|
||||
*clip = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` (see [`needs_outline`]) with its object-level geometry effects and its perspective applied:
|
||||
/// its [`outline_art`] reshaped as one piece, or for an image the image clipped by its reshaped
|
||||
/// frame. Type's own fills and strokes keep their effects on its whole outline. An image's own
|
||||
|
||||
+220
-41
@@ -6,9 +6,9 @@ use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2};
|
||||
use vectorcraft_three_d::{Edge, Revolve};
|
||||
use vectorcraft_three_d::{Edge, Revolve, SolidFaces};
|
||||
|
||||
use crate::solids::wireframe::WireFace;
|
||||
use crate::solids::wireframe::{WireFace, wireframe_params};
|
||||
use crate::solids::{
|
||||
Profile, Scope, is_container, members, object_profile, past_effect, profile, reshape_members, resolve_for, solid_paints, union_bounds,
|
||||
};
|
||||
@@ -154,7 +154,12 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let b = union_bounds(&shapes).ok_or(EMPTY)?;
|
||||
let options = shared_options(&shapes, options_of(id, p))?;
|
||||
let mut copies = 0;
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items), &mut copies))?;
|
||||
// In wireframe mode the edges are drawn with no paint copies, graphics or shadow.
|
||||
let wire = wireframe_params(id, p);
|
||||
shapes.iter().try_for_each(|s| check_surface(&s.path, b, options, surface_item(&s.items).filter(|_| !wire), &mut copies))?;
|
||||
if wire {
|
||||
return Ok(());
|
||||
}
|
||||
// Without graphics, or without the document they draw from, no member is measured for them.
|
||||
if let Some(doc) = doc.filter(|_| id == REVOLVE && !crate::solids::mapped_graphics(p).is_empty()) {
|
||||
match graphics_member(&shapes, b, options).and_then(|k| shapes.get(k)) {
|
||||
@@ -176,7 +181,11 @@ pub(crate) fn validate_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
|
||||
let path = geometry(&path, before, &GeomContext::of(n));
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let paints = solid_paints(n);
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints), &mut 0)?;
|
||||
let wire = wireframe_params(id, p);
|
||||
check_surface(&path, b, options_of(id, p), surface_item(&paints).filter(|_| !wire), &mut 0)?;
|
||||
if wire {
|
||||
return Ok(());
|
||||
}
|
||||
check_graphics(doc, id, &path, b, options_of(id, p), p, &mut 0)?;
|
||||
check_shadow(p, [&path], b, options_of(id, p))
|
||||
}
|
||||
@@ -261,7 +270,11 @@ pub(crate) fn validate_item_of(doc: Option<&Document>, n: &Node, id: &str, p: &V
|
||||
let options = options_of(kind, ¶ms);
|
||||
let path = geometry(&path, at.and_then(|at| effects.get(..at)).unwrap_or(effects), &ctx.item(item));
|
||||
let b = path.bounds().ok_or(EMPTY)?;
|
||||
check_surface(&path, b, options, crate::paints(item).then_some(item), &mut copies)?;
|
||||
let wire = wireframe_params(kind, ¶ms);
|
||||
check_surface(&path, b, options, (crate::paints(item) && !wire).then_some(item), &mut copies)?;
|
||||
if wire {
|
||||
continue;
|
||||
}
|
||||
// The graphics of every item add their paints' copies to the graphics' budget, as they
|
||||
// are drawn; only the edited item's graphics are refused here.
|
||||
let graphics = check_graphics(doc, kind, &path, b, options, ¶ms, &mut graphic_copies);
|
||||
@@ -324,6 +337,7 @@ pub(crate) fn validate_revolve_params(p: &Value) -> Result<(), String> {
|
||||
pub(crate) fn validate_params_of(id: &str, p: &Value) -> Result<(), String> {
|
||||
validate_revolve_params(p)?;
|
||||
crate::solids::graphics::validate(id, p)?;
|
||||
crate::solids::wireframe::validate_render(id, p)?;
|
||||
if id == CLASSIC_REVOLVE {
|
||||
classic::validate(p)?;
|
||||
}
|
||||
@@ -338,34 +352,80 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData {
|
||||
/// `b`, revolved with `options`, as dark as `item` is opaque and in its blending mode; `None` with
|
||||
/// the shadow off, when `item` is fully transparent or when it casts nothing, and an error when
|
||||
/// the surface it is cast from is past the limits.
|
||||
fn shadow_of(id: NodeId, fx: &Effect, path: &PathData, item: &AppearanceItem, b: Rect, options: Revolve) -> Result<Option<Node>, String> {
|
||||
///
|
||||
/// `kept` holds the faces the surface drawn kept for its shadow ([`surface`]); without them the
|
||||
/// surface is swept again for its shadow alone.
|
||||
fn shadow_of(
|
||||
id: NodeId,
|
||||
fx: &Effect,
|
||||
path: &PathData,
|
||||
item: &AppearanceItem,
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Option<SolidFaces>,
|
||||
) -> Result<Option<Node>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(None) };
|
||||
let (_, opacity, blend) = paint_of(item);
|
||||
if opacity <= 0.0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)?;
|
||||
cast_surface(&mut caster, path, b, options, kept)?;
|
||||
Ok(crate::solids::shadow::art(id, &caster, settings, crate::solids::shadow::Ink { opacity, blend }))
|
||||
}
|
||||
|
||||
/// Does Revolve `fx` cast a shadow, so a surface in paint as opaque as `opacity` keeps the faces
|
||||
/// its shadow is cast from ([`surface`])?
|
||||
fn casts(fx: &Effect, opacity: f32) -> bool {
|
||||
opacity > 0.0 && crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)).is_some()
|
||||
}
|
||||
|
||||
/// Add the surface of `path` about the axis of `b` to `caster`: the faces it kept when it was
|
||||
/// drawn, or without them, the surface swept for its shadow alone.
|
||||
fn cast_surface(
|
||||
caster: &mut vectorcraft_three_d::ShadowCaster,
|
||||
path: &PathData,
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Option<SolidFaces>,
|
||||
) -> Result<std::ops::Range<usize>, String> {
|
||||
match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.revolve(path, vectorcraft_geom::FillRule::NonZero, b, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shadow of group Revolve `fx` cast by the surfaces of the members `shapes` that have one,
|
||||
/// about the axis of `b`, on one plane; each member's part is as dark as its surface is opaque,
|
||||
/// in its paint's blending mode, and its opacity mask and blending mode apply to that part
|
||||
/// ([`crate::solids::shadow::scoped_art`]). An error when the surfaces it is cast from are past the
|
||||
/// limits.
|
||||
fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: Revolve) -> Result<Vec<Arc<Node>>, String> {
|
||||
/// limits. `kept` holds, member by member, the faces each surface drawn kept for its shadow
|
||||
/// ([`surface`]); a member without them is swept again for its shadow alone.
|
||||
fn group_shadow(
|
||||
id: NodeId,
|
||||
fx: &Effect,
|
||||
shapes: &[Profile],
|
||||
b: Rect,
|
||||
options: Revolve,
|
||||
kept: Vec<Option<SolidFaces>>,
|
||||
) -> Result<Vec<Arc<Node>>, String> {
|
||||
let Some(settings) = crate::solids::shadow::options(&merged_params(&fx.id, &fx.params)) else { return Ok(vec![]) };
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast = vec![];
|
||||
let mut kept = kept.into_iter();
|
||||
for s in shapes {
|
||||
let kept = kept.next().flatten();
|
||||
let Some((_, opacity, blend)) = surface_item(&s.items).map(paint_of) else { continue };
|
||||
// A member whose surface is fully transparent casts nothing.
|
||||
let ink = crate::solids::shadow::Ink { opacity: opacity * s.opacity, blend };
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = caster.revolve(&s.path, vectorcraft_geom::FillRule::NonZero, b, options)?;
|
||||
let faces = cast_surface(&mut caster, &s.path, b, options, kept)?;
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
Ok(crate::solids::shadow::scoped_art(id, &caster, settings, cast, crate::solids::has_masks(shapes)))
|
||||
@@ -377,7 +437,8 @@ fn group_shadow(id: NodeId, fx: &Effect, shapes: &[Profile], b: Rect, options: R
|
||||
/// the bytes of the paint copies of every surface and graphic of the object. Revolve (Classic) draws every face
|
||||
/// with its classic surface, as Extrude & Bevel (Classic) does. Revolve's graphics, with the
|
||||
/// symbols of `doc`, are drawn on the faces of the side ([`crate::solids::graphics::surface_parts`]):
|
||||
/// a face with a part of a graphic is a group of the face and that part.
|
||||
/// a face with a part of a graphic is a group of the face and that part. With `cast`, the sweep
|
||||
/// that draws the surface also keeps the faces its shadow is cast from ([`SolidFaces`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn surface(
|
||||
doc: Option<&Document>,
|
||||
@@ -391,11 +452,18 @@ fn surface(
|
||||
blend: vectorcraft_doc::color::BlendMode,
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
) -> Option<(Vec<Drawn>, Node)> {
|
||||
cast: bool,
|
||||
) -> Option<(Vec<Drawn>, Node, Option<SolidFaces>)> {
|
||||
#[cfg(test)]
|
||||
crate::solids::SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
// A loaded file or a profile edited past the limits keeps drawing its source path instead
|
||||
// of crashing the frame. Commands validate the same evaluator and report its errors.
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options).ok()?;
|
||||
let (facets, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_facets_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve_facets(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(facets.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
@@ -405,10 +473,14 @@ fn surface(
|
||||
let drawn =
|
||||
facets.iter().map(|f| Drawn { depth: f.depth, points: f.contours.first().cloned().unwrap_or_default(), plane: f.plane }).collect();
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p)));
|
||||
return Some((drawn, crate::solids::classic::surface(n, facets, &paint, opacity, blend, &p), kept));
|
||||
}
|
||||
let colored = options.light_color != [1.0; 3] || options.lights.is_some();
|
||||
let faces = vectorcraft_three_d::revolve(path, b, options).ok()?;
|
||||
let (faces, kept) = if cast {
|
||||
vectorcraft_three_d::revolve_shadowed(path, b, options).ok().map(|(f, kept)| (f, Some(kept)))?
|
||||
} else {
|
||||
(vectorcraft_three_d::revolve(path, b, options).ok()?, None)
|
||||
};
|
||||
copies.surfaces = copies.surfaces.saturating_add(paint_copies(faces.len(), &paint));
|
||||
if copies.surfaces > MAX_PAINT_COPIES {
|
||||
return None;
|
||||
@@ -532,7 +604,7 @@ fn surface(
|
||||
let mut group = Node::group(n.id, children);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
Some((keys, group))
|
||||
Some((keys, group, kept))
|
||||
}
|
||||
|
||||
/// A face [`surface`] draws: its depth and, for [`crate::solids::surface_order`], its polygon on the
|
||||
@@ -549,8 +621,9 @@ fn in_order<T>(items: Vec<T>, order: &[usize]) -> Vec<T> {
|
||||
order.iter().filter_map(|&k| slots.get_mut(k).and_then(Option::take)).collect()
|
||||
}
|
||||
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`.
|
||||
/// `copies` is the count [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
/// A surface of one object about the bounds of `path`, built with options derived from `fx`, and
|
||||
/// when `fx` casts a shadow from it, the faces it is cast from ([`surface`]). `copies` is the count
|
||||
/// [`surface`] adds to; its graphics take the symbols of `doc`.
|
||||
fn object_surface(
|
||||
doc: Option<&Document>,
|
||||
n: &Node,
|
||||
@@ -559,10 +632,11 @@ fn object_surface(
|
||||
item: &AppearanceItem,
|
||||
expand: bool,
|
||||
copies: &mut Copies,
|
||||
) -> Option<Node> {
|
||||
) -> Option<(Node, Option<SolidFaces>)> {
|
||||
let b = path.bounds()?;
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies).map(|(_, art)| art)
|
||||
let cast = casts(fx, opacity);
|
||||
surface(doc, n, path, b, fx_options(fx), fx, paint, opacity, blend, expand, copies, cast).map(|(_, art, kept)| (art, kept))
|
||||
}
|
||||
|
||||
/// The paint of a graphic's solid color `c` on `face`, shaded as the face shades a solid fill of
|
||||
@@ -668,14 +742,7 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul
|
||||
/// or stroke's Revolve are looked up in `doc`. Each face carries the width of the stroke the canvas
|
||||
/// draws around it ([`surface`]).
|
||||
pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<crate::solids::wireframe::FacesAndShadow, String> {
|
||||
let faces = |path: &PathData, b: Rect, fx: &Effect, options: Revolve| -> Result<Vec<WireFace>, String> {
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options)?;
|
||||
return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect());
|
||||
}
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
};
|
||||
let faces = wire_faces;
|
||||
if is_container(n) {
|
||||
let index = n
|
||||
.appearance
|
||||
@@ -692,7 +759,9 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) {
|
||||
out.extend(faces(&s.path, b, fx, options)?);
|
||||
}
|
||||
return Ok((out, group_shadow(n.id, fx, &shapes, b, options)?));
|
||||
// In wireframe mode the canvas draws no shadow.
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { vec![] } else { group_shadow(n.id, fx, &shapes, b, options, vec![])? };
|
||||
return Ok((out, shadow));
|
||||
}
|
||||
let (path, _) = object_profile(n, "Revolve")?;
|
||||
let ctx = GeomContext::of(n);
|
||||
@@ -703,7 +772,7 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
let item = surface_item(&paints).ok_or("the revolved object has no fill or stroke")?;
|
||||
let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?;
|
||||
let surface = faces(&path, b, fx, fx_options(fx))?;
|
||||
let shadow = shadow_of(n.id, fx, &path, item, b, fx_options(fx))?;
|
||||
let shadow = if crate::solids::renders_wireframe(fx) { None } else { shadow_of(n.id, fx, &path, item, b, fx_options(fx), None)? };
|
||||
return Ok((surface, shadow.into_iter().map(Arc::new).collect()));
|
||||
}
|
||||
let path = geometry(&path, &n.appearance.effects, &ctx);
|
||||
@@ -721,6 +790,28 @@ pub(crate) fn revolve_face_paths(doc: Option<&Document>, n: &Node) -> Result<cra
|
||||
Ok((out, vec![]))
|
||||
}
|
||||
|
||||
/// The faces Revolve or Revolve (Classic) `fx` sweeps from `path` about the bounds `b` with
|
||||
/// `options`, each with the width of the stroke the canvas draws around it.
|
||||
fn wire_faces(path: &PathData, b: Rect, fx: &Effect, options: Revolve) -> Result<Vec<WireFace>, String> {
|
||||
if fx.id == CLASSIC_REVOLVE {
|
||||
let p = merged_params(&fx.id, &fx.params);
|
||||
let facets = vectorcraft_three_d::revolve_facets(path, b, options)?;
|
||||
return Ok(facets.iter().map(|f| WireFace { path: f.path(), stroke: crate::solids::classic::stroke_width(f, &p) }).collect());
|
||||
}
|
||||
Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(|f| WireFace { path: f.path(), stroke: SEAM_WIDTH }).collect())
|
||||
}
|
||||
|
||||
/// The art Revolve `fx` in wireframe mode draws for object `id` from the profiles `paths`, all swept
|
||||
/// about the bounds `b` with `options`: the edges of their faces ([`crate::solids::wireframe::wire_art`]).
|
||||
/// `None` when a profile can't be swept or past the edge limit, when the canvas draws the source art.
|
||||
fn wire_art<'a>(id: NodeId, paths: impl IntoIterator<Item = &'a PathData>, b: Rect, fx: &Effect, options: Revolve) -> Option<Arc<Node>> {
|
||||
let mut faces = vec![];
|
||||
for path in paths {
|
||||
faces.extend(wire_faces(path, b, fx, options).ok()?.into_iter().map(|f| f.path));
|
||||
}
|
||||
crate::solids::wireframe::wire_art(id, &faces)
|
||||
}
|
||||
|
||||
/// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis.
|
||||
fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result<Vec<crate::SolidMesh>, String> {
|
||||
let index = n
|
||||
@@ -764,13 +855,18 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let paints = solid_paints(n);
|
||||
let item = surface_item(&paints)?;
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let surface = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx)).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of the faces, with no shadow.
|
||||
children.push(wire_art(n.id, [&path], path.bounds()?, fx, fx_options(fx))?);
|
||||
} else {
|
||||
let (surface, kept) = object_surface(doc, n, &path, fx, item, expand, &mut copies)?;
|
||||
if let Some(b) = path.bounds()
|
||||
&& let Some(shadow) = shadow_of(n.id, fx, &path, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
children.push(Arc::new(shadow));
|
||||
}
|
||||
children.push(Arc::new(surface));
|
||||
}
|
||||
children.push(Arc::new(surface));
|
||||
// Later geometry acts on the projected art as a whole through container evaluation.
|
||||
remaining = past_effect(&n.appearance.effects, index);
|
||||
remaining.retain(|e| !is_revolve(&e.id));
|
||||
@@ -790,10 +886,17 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
let fx = item.effects().get(index)?;
|
||||
let p = geometry(&path, item.effects().get(..index)?, &ctx.item(original));
|
||||
let expand = expand && !item.effects().iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut art = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
let mut art = wire_art(n.id, [&p], p.bounds()?, fx, fx_options(fx))?;
|
||||
Arc::make_mut(&mut art).appearance.effects =
|
||||
item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
children.push(art);
|
||||
continue;
|
||||
}
|
||||
let (mut art, kept) = object_surface(doc, n, &p, fx, item, expand, &mut copies)?;
|
||||
art.appearance.effects = item.effects().iter().skip(index + 1).filter(|e| !is_revolve(&e.id)).cloned().collect();
|
||||
if let Some(b) = p.bounds()
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx)).ok()?
|
||||
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, fx_options(fx), kept).ok()?
|
||||
{
|
||||
shadow.appearance.effects = art.appearance.effects.clone();
|
||||
shadows.push(Arc::new(shadow));
|
||||
@@ -939,24 +1042,39 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
reshape_members(n, n.appearance.effects.get(..index)?, &mut shapes);
|
||||
let b = union_bounds(&shapes)?;
|
||||
let options = shared_options(&shapes, fx_options(fx)).ok()?;
|
||||
if crate::solids::renders_wireframe(fx) {
|
||||
// In wireframe mode the edges of every member's faces, with no shadow.
|
||||
let paths = shapes.iter().filter(|s| surface_item(&s.items).is_some()).map(|s| &s.path);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children: vec![wire_art(n.id, paths, b, fx, options)?], clip: false };
|
||||
art.appearance = Appearance { effects: past_effect(&n.appearance.effects, index), ..Default::default() }.into();
|
||||
return Some(art);
|
||||
}
|
||||
let expand = expand && !n.appearance.effects.iter().skip(index + 1).any(|e| e.visible && is_geometry(&e.id));
|
||||
let mut copies = Copies::default();
|
||||
let mut surfaces = vec![];
|
||||
// The faces each member's surface kept for the shadow, member by member.
|
||||
let mut kept = vec![];
|
||||
let mut opaque = true;
|
||||
// The graphics go once, on the side of the member with the longest profile. Without graphics
|
||||
// no member is measured for them.
|
||||
let mapped = fx.id == REVOLVE && !crate::solids::mapped_graphics(&merged_params(&fx.id, &fx.params)).is_empty();
|
||||
let longest = if mapped { graphics_member(&shapes, b, options) } else { None };
|
||||
for (k, s) in shapes.iter().enumerate() {
|
||||
let Some(item) = surface_item(&s.items) else { continue };
|
||||
let Some(item) = surface_item(&s.items) else {
|
||||
kept.push(None);
|
||||
continue;
|
||||
};
|
||||
// The opacity and blending of the member and the groups it is in apply through its scopes.
|
||||
let (paint, opacity, blend) = paint_of(item);
|
||||
opaque &= opacity >= 1.0 && blend == Default::default() && s.scopes.is_empty();
|
||||
// A member with transparency of its own keeps every face, as a transparent object does.
|
||||
let expand = expand && s.scopes.is_empty();
|
||||
let doc = doc.filter(|_| longest == Some(k));
|
||||
let (depths, art) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies)?;
|
||||
let cast = casts(fx, opacity * s.opacity);
|
||||
let (depths, art, faces) = surface(doc, n, &s.path, b, options, fx, paint, opacity, blend, expand, &mut copies, cast)?;
|
||||
surfaces.push((depths, art, s.scopes.as_slice()));
|
||||
kept.push(faces);
|
||||
}
|
||||
if surfaces.is_empty() {
|
||||
return None;
|
||||
@@ -1057,7 +1175,7 @@ fn group_art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
|
||||
};
|
||||
// One shadow for every member's surface, behind them all.
|
||||
let mut children = children;
|
||||
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options).ok()?);
|
||||
children.splice(0..0, group_shadow(n.id, fx, &shapes, b, options, kept).ok()?);
|
||||
let remaining = past_effect(&n.appearance.effects, index);
|
||||
let mut art = n.clone();
|
||||
art.kind = NodeKind::Group { children, clip: false };
|
||||
@@ -1682,6 +1800,67 @@ mod tests {
|
||||
}
|
||||
assert_eq!(expand_revolve_art(&sample), revolve_art(&sample));
|
||||
}
|
||||
|
||||
/// The settings the shadows are compared with: the defaults, a partial sweep turned with
|
||||
/// perspective, and an open surface away from its axis under a colored light.
|
||||
fn shadow_settings() -> [Value; 3] {
|
||||
[
|
||||
json!({"shadow": true}),
|
||||
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "angle": 220, "shadowDistance": 40}),
|
||||
json!({"shadow": true, "shadowDistance": 30, "lightColor": "#ff8040", "offset": 20, "cap": false}),
|
||||
]
|
||||
}
|
||||
|
||||
/// The shadow of the faces Revolve and Revolve (Classic) kept when they swept their surfaces,
|
||||
/// to the bit: the shadow of surfaces swept for the shadow alone, for one object, for an
|
||||
/// object whose fill is half transparent, and for a group of two members, one at half opacity.
|
||||
#[test]
|
||||
fn the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it() {
|
||||
for id in [REVOLVE, CLASSIC_REVOLVE] {
|
||||
for params in shadow_settings() {
|
||||
// Revolve (Classic) takes no shadow settings from commands, but a file can carry them.
|
||||
let mut fx = crate::new_effect(id, &json!({})).unwrap();
|
||||
fx.params = params.clone();
|
||||
let n = profile_node();
|
||||
let (path, _) = profile(&n).unwrap();
|
||||
let b = path.bounds().unwrap();
|
||||
let mut half = n.clone();
|
||||
if let AppearanceItem::Fill(f) = &mut half.appearance.items[0] {
|
||||
f.opacity = 0.5;
|
||||
}
|
||||
for n in [n, half] {
|
||||
let item = surface_item(&n.appearance.items).unwrap();
|
||||
let (_, kept) = object_surface(None, &n, &path, &fx, item, false, &mut Copies::default()).unwrap();
|
||||
let drawn = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), kept).unwrap();
|
||||
let alone = shadow_of(n.id, &fx, &path, item, b, fx_options(&fx), None).unwrap();
|
||||
assert!(alone.is_some() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
let mut other = profile_node();
|
||||
other.id = NodeId(2);
|
||||
other.transform(Affine::translate((120.0, 0.0)), false);
|
||||
other.opacity = 0.5;
|
||||
let mut g = Node::group(NodeId(9), vec![Arc::new(profile_node()), Arc::new(other)]);
|
||||
g.appearance.effects.push(fx.clone());
|
||||
let shapes = members(&g, "").unwrap();
|
||||
let b = union_bounds(&shapes).unwrap();
|
||||
let options = shared_options(&shapes, fx_options(&fx)).unwrap();
|
||||
let kept: Vec<Option<SolidFaces>> = shapes
|
||||
.iter()
|
||||
.map(|s| {
|
||||
let (paint, opacity, blend) = paint_of(surface_item(&s.items).unwrap());
|
||||
let cast = casts(&fx, opacity * s.opacity);
|
||||
surface(None, &g, &s.path, b, options, &fx, paint, opacity, blend, false, &mut Copies::default(), cast).unwrap().2
|
||||
})
|
||||
.collect();
|
||||
assert!(kept.iter().all(Option::is_some), "{id} {params}");
|
||||
let drawn = group_shadow(g.id, &fx, &shapes, b, options, kept).unwrap();
|
||||
let alone = group_shadow(g.id, &fx, &shapes, b, options, vec![]).unwrap();
|
||||
assert!(!alone.is_empty() || id == CLASSIC_REVOLVE, "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+188
-25
@@ -7,7 +7,9 @@ use vectorcraft_doc::color::{BlendMode, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId, NodeKind, OpacityMask};
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
use vectorcraft_three_d::{Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, View};
|
||||
use vectorcraft_three_d::{
|
||||
Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
use vectorcraft_doc::color::Color;
|
||||
@@ -34,7 +36,7 @@ pub use graphics::{
|
||||
pub(crate) mod shadow;
|
||||
|
||||
pub(crate) mod wireframe;
|
||||
pub use wireframe::three_d_wireframe_in;
|
||||
pub use wireframe::{RENDER, RENDER_MODES, renders_wireframe, three_d_wireframe_in};
|
||||
|
||||
pub const EXTRUDE: &str = "threeD.extrude";
|
||||
pub const INFLATE: &str = "threeD.inflate";
|
||||
@@ -236,6 +238,30 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) ->
|
||||
}
|
||||
}
|
||||
|
||||
/// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast
|
||||
/// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the
|
||||
/// classic effects cast no shadow: they keep no faces.
|
||||
fn facets_and_faces(
|
||||
id: &str,
|
||||
path: &PathData,
|
||||
rule: FillRule,
|
||||
bounds: Rect,
|
||||
p: &Value,
|
||||
cast: bool,
|
||||
) -> Result<(Vec<Facet>, Option<SolidFaces>), String> {
|
||||
let view = view_options(p);
|
||||
#[cfg(test)]
|
||||
if cast && id == EXTRUDE {
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
let built = match id {
|
||||
EXTRUDE if cast => vectorcraft_three_d::extrude_shadowed(path, rule, bounds, extrude_options(p), view),
|
||||
ROTATE if cast => vectorcraft_three_d::plane_shadowed(path, rule, bounds, view),
|
||||
_ => return facets(id, path, rule, bounds, p).map(|f| (f, None)),
|
||||
};
|
||||
built.map(|(f, faces)| (f, Some(faces)))
|
||||
}
|
||||
|
||||
/// Check solid `id`'s parameter values `p` alone: the part of [`validate_solid`] that does not
|
||||
/// need the object.
|
||||
fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
@@ -248,6 +274,7 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
crate::lighting::validate(p)?;
|
||||
shadow::validate(p)?;
|
||||
graphics::validate(id, p)?;
|
||||
wireframe::validate_render(id, p)?;
|
||||
if let Some(v) = p.get("bevel")
|
||||
&& !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some())
|
||||
{
|
||||
@@ -298,7 +325,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
return cast_shadow(id, p, &shapes).map(|_| ());
|
||||
return check_cast(id, p, &shapes);
|
||||
}
|
||||
let (path, rule) = object_profile(n, label)?;
|
||||
let anchors = || format!("{label} requires a shape with at least two anchors");
|
||||
@@ -316,7 +343,16 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
|
||||
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
|
||||
check_profiles(id, p, &shapes, b)?;
|
||||
check_solids(id, p, &shapes)?;
|
||||
cast_shadow(id, p, &shapes).map(|_| ())
|
||||
check_cast(id, p, &shapes)
|
||||
}
|
||||
|
||||
/// With the shadow of 3D effect `id` with parameters `p` on, an error when the shadow of `shapes`
|
||||
/// is past the limits ([`cast_shadow`]). In wireframe mode no shadow is drawn, and none is checked.
|
||||
fn check_cast(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
|
||||
if wireframe::wireframe_params(id, p) {
|
||||
return Ok(());
|
||||
}
|
||||
cast_shadow(id, p, shapes).map(|_| ())
|
||||
}
|
||||
|
||||
/// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b`
|
||||
@@ -693,7 +729,9 @@ fn solid_parts(shapes: &[Profile], fallback: Rect) -> (Vec<Part<'_>>, Rect) {
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many solids [`built_solids`] and [`meshes_for`] have built on this thread, for the tests.
|
||||
static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Rotate's planes drawn, the solids built to cast a shadow ([`cast_shadow`]) and Revolve's
|
||||
/// surfaces count too.
|
||||
pub(crate) static SOLIDS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// How many Extrude & Bevel (Classic included) and Inflate solids [`facets`] and
|
||||
/// [`built_solids`] have built on this thread, for the tests.
|
||||
static SOLID_GEOMETRY_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
@@ -712,10 +750,35 @@ fn built_solids<'a>(
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
|
||||
built_solids_cast(id, p, parts, bounds, limit, false).map(|r| r.map(|s| s.map(|(f, _)| f)))
|
||||
}
|
||||
|
||||
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
|
||||
type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
|
||||
|
||||
/// The surfaces of an object's solids, and the faces each solid kept for its shadow
|
||||
/// ([`surfaces_for`]).
|
||||
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
|
||||
|
||||
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
|
||||
/// is cast from, from the same build ([`SolidFaces`]).
|
||||
fn built_solids_cast<'a>(
|
||||
id: &'a str,
|
||||
p: &'a Value,
|
||||
parts: &'a [Part<'a>],
|
||||
bounds: Rect,
|
||||
limit: usize,
|
||||
cast: bool,
|
||||
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
|
||||
// Inflate's eye is placed for every puff together, as far away as the highest needs.
|
||||
let mut inflated = (id == INFLATE).then(|| {
|
||||
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
vectorcraft_three_d::inflate_each(&shapes, bounds, inflate_options(p), view_options(p))
|
||||
let (o, view) = (inflate_options(p), view_options(p));
|
||||
if cast {
|
||||
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
|
||||
} else {
|
||||
Box::new(vectorcraft_three_d::inflate_each(&shapes, bounds, o, view).map(|r| r.map(|f| (f, None))))
|
||||
}
|
||||
});
|
||||
let mut kept = 0usize;
|
||||
let mut ended = false;
|
||||
@@ -729,13 +792,13 @@ fn built_solids<'a>(
|
||||
Some(each) => {
|
||||
#[cfg(test)]
|
||||
SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1));
|
||||
each.next().unwrap_or_else(|| Ok(vec![]))
|
||||
each.next().unwrap_or_else(|| Ok((vec![], None)))
|
||||
}
|
||||
None => facets(id, area, *rule, bounds, p),
|
||||
None => facets_and_faces(id, area, *rule, bounds, p, cast),
|
||||
};
|
||||
let result = match built {
|
||||
Ok(f) => {
|
||||
kept = kept.saturating_add(f.len());
|
||||
kept = kept.saturating_add(f.0.len());
|
||||
if kept > limit { Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()) } else { Ok(Some(f)) }
|
||||
}
|
||||
Err(_) if matches!(item, AppearanceItem::Stroke(_)) => Ok(None),
|
||||
@@ -1364,18 +1427,32 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// otherwise each solid is a surface of its own, in that order. A member's opacity mask and
|
||||
/// 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.
|
||||
/// off), cast from the faces the solids drawn kept ([`cast_built`]), to be drawn behind every
|
||||
/// surface of the object, and the surfaces.
|
||||
fn art_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<ShadowAndSurfaces> {
|
||||
let art = surfaces_for(doc, n, fx, shapes)?;
|
||||
// In wireframe mode the effect draws the edges of the faces it builds, with no shadow.
|
||||
if wireframe::renders_wireframe(fx) {
|
||||
return Some((vec![], wireframe::wire_surfaces(n.id, fx, shapes)?));
|
||||
}
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let cast = !is_classic_three_d(&fx.id) && shadow::options(&p).is_some();
|
||||
let (art, built) = surfaces_for(doc, n, fx, shapes, cast)?;
|
||||
// A shadow past the limits draws the source path, as a solid past them does; commands report
|
||||
// the error ([`validate_solid_in`]).
|
||||
let shadow = shadow_for(n.id, fx, shapes).ok()?;
|
||||
let shadow = if cast { cast_built(&fx.id, &p, shapes, built) } else { Ok(None) };
|
||||
let shadow = match shadow.ok()? {
|
||||
Some((caster, settings, cast)) => shadow::scoped_art(n.id, &caster, settings, cast, has_masks(shapes)),
|
||||
None => vec![],
|
||||
};
|
||||
Some((shadow, art))
|
||||
}
|
||||
|
||||
/// The shadow [`art_for`] draws for effect `fx` on `shapes` behind the surfaces of object `id`:
|
||||
/// none with the shadow off, and an error when it is past the limits.
|
||||
/// none with the shadow off or in wireframe mode, and an error when it is past the limits.
|
||||
pub(crate) fn shadow_for(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Result<Vec<Arc<Node>>, String> {
|
||||
if wireframe::renders_wireframe(fx) {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
Ok(match cast_shadow(&fx.id, &crate::merged_params(&fx.id, &fx.params), shapes)? {
|
||||
Some((caster, settings, cast)) => shadow::scoped_art(id, &caster, settings, cast, has_masks(shapes)),
|
||||
None => vec![],
|
||||
@@ -1408,6 +1485,8 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
for s in shapes {
|
||||
for item in s.items.iter().filter(|i| ink(i, s.opacity).opacity > 0.0) {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let faces = caster.plane(&area, rule, b, view)?;
|
||||
cast.push((s.scopes.as_slice(), ink(item, s.opacity), faces));
|
||||
}
|
||||
@@ -1419,10 +1498,14 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
let added: Vec<Result<std::ops::Range<usize>, String>> = if id == INFLATE {
|
||||
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
|
||||
let casts: Vec<bool> = inks.iter().map(|i| i.opacity > 0.0).collect();
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + shapes.len()));
|
||||
caster.inflate(&shapes, &casts, bounds, inflate_options(p), view)
|
||||
} else {
|
||||
let mut added = vec![];
|
||||
for ((_, _, area, rule, _, _), ink) in parts.iter().zip(&inks) {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + usize::from(ink.opacity > 0.0)));
|
||||
added.push(if ink.opacity > 0.0 { caster.extrude(area, *rule, bounds, extrude_options(p), view) } else { Ok(0..0) });
|
||||
}
|
||||
added
|
||||
@@ -1444,6 +1527,76 @@ fn cast_shadow<'a>(id: &str, p: &Value, shapes: &'a [Profile]) -> Result<Option<
|
||||
Ok(Some((caster, settings, cast)))
|
||||
}
|
||||
|
||||
/// [`cast_shadow`] from `built`, the faces the solids drawn kept ([`surfaces_for`] with its shadow
|
||||
/// cast), one entry for each solid in the order they are built: for Rotate each fill and stroke of
|
||||
/// each shape, otherwise each part ([`solid_parts`]). A stroke's solid left out of the art (past its
|
||||
/// own limits) kept no faces. Its Extrude & Bevel solid is built for the shadow alone, as
|
||||
/// [`cast_shadow`] builds it, and when an Inflate solid of visible art kept no faces the whole
|
||||
/// shadow is cast as [`cast_shadow`] casts it, since Inflate's solids share one eye.
|
||||
fn cast_built<'a>(id: &str, p: &Value, shapes: &'a [Profile], built: Vec<Option<SolidFaces>>) -> Result<Option<Cast<'a>>, String> {
|
||||
if id == CLASSIC_EXTRUDE || id == CLASSIC_ROTATE {
|
||||
return Ok(None);
|
||||
}
|
||||
let (Some(settings), Some(b)) = (shadow::options(p), union_bounds(shapes)) else { return Ok(None) };
|
||||
let view = view_options(p);
|
||||
let mut caster = vectorcraft_three_d::ShadowCaster::new();
|
||||
let mut cast: Vec<shadow::Cast> = vec![];
|
||||
let ink = |item: &AppearanceItem, member: f32| {
|
||||
let (_, opacity, blend) = paint_of(item, member);
|
||||
shadow::Ink { opacity, blend }
|
||||
};
|
||||
if id == ROTATE {
|
||||
let items: Vec<(&Profile, &AppearanceItem)> = shapes.iter().flat_map(|s| s.items.iter().map(move |item| (s, item))).collect();
|
||||
if items.len() != built.len() {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for ((s, item), kept) in items.into_iter().zip(built) {
|
||||
let ink = ink(item, s.opacity);
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept)?,
|
||||
None => {
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.plane(&area, rule, b, view)?
|
||||
}
|
||||
};
|
||||
cast.push((s.scopes.as_slice(), ink, faces));
|
||||
}
|
||||
return Ok(Some((caster, settings, cast)));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let inks: Vec<shadow::Ink> = parts.iter().map(|(item, member, ..)| ink(item, *member)).collect();
|
||||
if parts.len() != built.len() || (id == INFLATE && inks.iter().zip(&built).any(|(ink, kept)| ink.opacity > 0.0 && kept.is_none())) {
|
||||
return cast_shadow(id, p, shapes);
|
||||
}
|
||||
for (((item, _, area, rule, scopes, _), ink), kept) in parts.iter().zip(inks).zip(built) {
|
||||
if ink.opacity <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let faces = match kept {
|
||||
Some(kept) => caster.add_solid(kept),
|
||||
None => {
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
caster.extrude(area, *rule, bounds, extrude_options(p), view)
|
||||
}
|
||||
};
|
||||
// A stroke whose own solid is past the limits is left out; past the shadow's limit for all
|
||||
// the solids together, the shadow is refused.
|
||||
let faces = match faces {
|
||||
Ok(faces) => faces,
|
||||
Err(e) if matches!(item, AppearanceItem::Stroke(_)) && e != vectorcraft_three_d::TOO_COMPLEX_SHADOW => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
cast.push((*scopes, ink, faces));
|
||||
}
|
||||
Ok(Some((caster, settings, cast)))
|
||||
}
|
||||
|
||||
/// The faces a shadow is cast from, its settings, and the faces of each solid of visible art with
|
||||
/// its member's scopes and ink ([`cast_shadow`]).
|
||||
type Cast<'a> = (vectorcraft_three_d::ShadowCaster, vectorcraft_three_d::Shadow, Vec<shadow::Cast<'a>>);
|
||||
@@ -1582,8 +1735,10 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
|
||||
}
|
||||
|
||||
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
|
||||
/// faces drawn right after the last of the solids' surfaces that holds that face.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each
|
||||
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
|
||||
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
|
||||
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
|
||||
let b = union_bounds(shapes)?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
|
||||
@@ -1598,11 +1753,15 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
// the centre of theirs), so they stay together.
|
||||
let mut out = vec![];
|
||||
let mut filled = vec![];
|
||||
let mut built = vec![];
|
||||
for (member, s) in shapes.iter().enumerate() {
|
||||
for item in &s.items {
|
||||
let (paint, opacity, blend) = paint_of(item, s.opacity);
|
||||
let (area, rule) = region(&s.path, s.rule, item);
|
||||
let f = facets(ROTATE, &area, rule, b, &p).ok()?;
|
||||
#[cfg(test)]
|
||||
SOLIDS_BUILT.with(|n| n.set(n.get() + 1));
|
||||
let (f, faces) = facets_and_faces(ROTATE, &area, rule, b, &p, cast).ok()?;
|
||||
built.push(faces);
|
||||
if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, &paint, colored), &paint) {
|
||||
return None;
|
||||
}
|
||||
@@ -1619,19 +1778,23 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
}
|
||||
let arts = placed_graphics(doc, n.id, (ROTATE, &p), b, &filled, masks);
|
||||
let out = with_graphics(out, 0, &arts);
|
||||
return Some(if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() });
|
||||
return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built));
|
||||
}
|
||||
let (parts, bounds) = solid_parts(shapes, b);
|
||||
let mut solids = vec![];
|
||||
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES)) {
|
||||
let mut built = vec![];
|
||||
for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast)) {
|
||||
let item: &AppearanceItem = item;
|
||||
match f {
|
||||
Ok(Some(f)) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => {
|
||||
return None;
|
||||
}
|
||||
Ok(Some(f)) => solids.push((item, *opacity, *scopes, f, *member)),
|
||||
Ok(Some((f, faces))) => {
|
||||
solids.push((item, *opacity, *scopes, f, *member));
|
||||
built.push(faces);
|
||||
}
|
||||
// A stroke's outline past the limits is left out; the fill's solid still draws.
|
||||
Ok(None) => {}
|
||||
Ok(None) => built.push(None),
|
||||
// A loaded file or a shape edited past the limits (its own, or those of the object's
|
||||
// solids together) keeps drawing its source path instead of failing the frame;
|
||||
// commands validate the same evaluator and report its errors.
|
||||
@@ -1760,14 +1923,14 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
out.extend(with_graphics(run.collect(), first, &arts));
|
||||
}
|
||||
}
|
||||
return Some(masked(n.id, out));
|
||||
return Some((masked(n.id, out), built));
|
||||
}
|
||||
if !opaque || !surfaces.iter().all(plain) {
|
||||
let surfaces =
|
||||
surfaces.into_iter().enumerate().map(|(k, (d, s, scopes, e))| (d, underlaid_surface(n.id, s, seal(k..k + 1)), scopes, e)).collect();
|
||||
return Some(whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect());
|
||||
return Some((whole_surfaces(surfaces, &arts).into_iter().map(|(_, s)| s).collect(), built));
|
||||
}
|
||||
Some(vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))])
|
||||
Some((vec![Arc::new(Node::group(n.id, in_one_order(n.id, surfaces, 0, &arts, sealed, &seals)))], built))
|
||||
}
|
||||
|
||||
/// A plain `surface` ([`surface`]: a group of its facets) over an underlay of its facets when
|
||||
|
||||
@@ -1115,6 +1115,44 @@ fn the_check_builds_the_profile_of_a_shape_with_no_fill() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A filled shape is checked about the bounds the effect draws its solid about, which take in the
|
||||
/// strokes beside it. A shape of many small curves is too complex for Extrude & Bevel about the
|
||||
/// shapes' own bounds, where its curves are sampled more finely, and passes about the bounds of a
|
||||
/// wide stroke in its group, as its solid draws there.
|
||||
#[test]
|
||||
fn the_check_builds_a_filled_shape_about_the_bounds_its_solid_draws_about() {
|
||||
// 900 curves about (100, 100), each bulging 1 pt out from a side of a polygon 80 pt across.
|
||||
let corners = 900;
|
||||
let center = Point::new(100.0, 100.0);
|
||||
let corner = |k: usize| {
|
||||
let (s, c) = (k as f64 * std::f64::consts::TAU / corners as f64).sin_cos();
|
||||
Point::new(center.x + 40.0 * c, center.y + 40.0 * s)
|
||||
};
|
||||
let mut b = BezPath::new();
|
||||
b.move_to(corner(0));
|
||||
for k in 0..corners {
|
||||
let (p0, p3) = (corner(k), corner(k + 1));
|
||||
let out = p0.midpoint(p3) - center;
|
||||
let out = out / out.hypot();
|
||||
b.curve_to(p0 + (p3 - p0) / 3.0 + out, p0 + (p3 - p0) * (2.0 / 3.0) + out, p3);
|
||||
}
|
||||
b.close_path();
|
||||
let filled = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
|
||||
let mut line = BezPath::new();
|
||||
line.move_to((80.0, 100.0));
|
||||
line.line_to((120.0, 100.0));
|
||||
let mut wide = Node::path(NodeId(2), PathData::from_bezpath(&line), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2000.0));
|
||||
wide.appearance.items.retain(|i| matches!(i, AppearanceItem::Stroke(_)));
|
||||
let p = json!({"bevel": "rounded", "bevelRepeat": 6});
|
||||
let (path, rule) = profile(&filled).unwrap();
|
||||
let own = path.bounds().unwrap().union(wide.path_data().unwrap().bounds().unwrap());
|
||||
assert_eq!(facets(EXTRUDE, &path, rule, own, &p).map(|_| ()), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()), "about its own bounds");
|
||||
let mut g = Node::group(NodeId(9999), vec![Arc::new(filled), Arc::new(wide)]);
|
||||
assert_eq!(validate_solid(&g, EXTRUDE, &p), Ok(()));
|
||||
g.appearance.effects.push(fx(EXTRUDE, p));
|
||||
assert!(solid_art(&g).is_some(), "the solid draws");
|
||||
}
|
||||
|
||||
/// A convex polygon of `corners` corners about (20,000, 20,000), filled red, with no stroke.
|
||||
fn polygon_node(id: u64, corners: usize) -> Node {
|
||||
let points: Vec<Point> = (0..corners)
|
||||
|
||||
@@ -223,3 +223,92 @@ fn expand_appearance_keeps_the_shadow_as_a_path() {
|
||||
assert!((after.x0 - before.x0 - 40.0).abs() < 1e-6, "{id}: {before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A square filled red and stroked blue, its stroke as opaque as `stroke`.
|
||||
fn stroked_square(id: u64, dx: f64, stroke: f32) -> Node {
|
||||
let mut n = square_node(id, dx);
|
||||
n.appearance = Appearance::basic(Paint::solid(RED), Paint::solid(Color::rgb(0.1, 0.2, 0.9)), 6.0).into();
|
||||
for item in &mut n.appearance.items {
|
||||
if let AppearanceItem::Stroke(s) = item {
|
||||
s.opacity = stroke;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// Objects with 3D effect `id` and its shadow on (`params`): a filled and stroked square, one whose
|
||||
/// stroke is half transparent, one whose stroke is fully transparent, and a group of two members,
|
||||
/// one of them at half opacity.
|
||||
fn shadowed(id: &str, params: &Value) -> Vec<Node> {
|
||||
let with = |mut n: Node| {
|
||||
n.appearance.effects.push(crate::new_effect(id, params).unwrap());
|
||||
n
|
||||
};
|
||||
let mut half = stroked_square(2, 200.0, 1.0);
|
||||
half.opacity = 0.5;
|
||||
let group = Node::group(NodeId(9), vec![Arc::new(stroked_square(1, 0.0, 1.0)), Arc::new(half)]);
|
||||
vec![with(stroked_square(1, 0.0, 1.0)), with(stroked_square(1, 0.0, 0.5)), with(stroked_square(1, 0.0, 0.0)), with(group)]
|
||||
}
|
||||
|
||||
/// The settings the shadows of effect `id` are compared with: the defaults, turned with
|
||||
/// perspective, and under a colored light, below the object for Extrude & Bevel, Inflate and
|
||||
/// Rotate and behind it for Revolve.
|
||||
fn shadow_settings(id: &str) -> [Value; 3] {
|
||||
let position = if id == crate::REVOLVE { "behind" } else { "below" };
|
||||
[
|
||||
json!({"shadow": true}),
|
||||
json!({"shadow": true, "rotationX": -25, "rotationY": 35, "perspective": 50, "shadowDistance": 40}),
|
||||
json!({"shadow": true, "shadowPosition": position, "shadowDistance": 30, "lightColor": "#ff8040", "twist": 30}),
|
||||
]
|
||||
}
|
||||
|
||||
/// How many solids drawing the art of `n` with effect `id` builds.
|
||||
fn solids_built(n: &Node, id: &str) -> usize {
|
||||
let start = SOLIDS_BUILT.with(std::cell::Cell::get);
|
||||
assert!(art(n, id).is_some(), "{id}");
|
||||
SOLIDS_BUILT.with(std::cell::Cell::get) - start
|
||||
}
|
||||
|
||||
/// Drawing a 3D object with its shadow on builds each of its solids once: the shadow is cast from
|
||||
/// the faces the solids drawn kept, so it builds no more solids than the art without a shadow.
|
||||
#[test]
|
||||
fn a_shadowed_3d_object_builds_each_solid_once() {
|
||||
for id in CASTING {
|
||||
for params in shadow_settings(id) {
|
||||
for (lit, mut plain) in shadowed(id, ¶ms).into_iter().zip(shadowed(id, ¶ms)) {
|
||||
plain.appearance.effects.iter_mut().for_each(|e| e.params["shadow"] = json!(false));
|
||||
let mut cast = 0;
|
||||
art(&lit, id).unwrap().walk(&mut |c| cast += usize::from(shadow_opacity(c).is_some()));
|
||||
assert!(cast > 0, "{id} {params}");
|
||||
let built = solids_built(&plain, id);
|
||||
assert!(built > 0, "{id}");
|
||||
assert_eq!(solids_built(&lit, id), built, "{id} {params}: the shadow builds no solid of its own");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The shadow of the faces Extrude & Bevel, Inflate and Rotate kept when they drew their solids,
|
||||
/// to the bit: the shadow [`cast_shadow`] casts from solids built for the shadow alone.
|
||||
#[test]
|
||||
fn the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it() {
|
||||
for id in [EXTRUDE, INFLATE, ROTATE] {
|
||||
for params in shadow_settings(id) {
|
||||
for n in shadowed(id, ¶ms) {
|
||||
let (_, fx) = solid(&n.appearance.effects).unwrap();
|
||||
let shapes = if is_container(&n) {
|
||||
members(&n, "").unwrap()
|
||||
} else {
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
vec![Profile { path, rule, items: solid_paint_sources(&n).1, opacity: 1.0, scopes: vec![] }]
|
||||
};
|
||||
let (drawn, _) = art_for(None, &n, fx, &shapes).unwrap();
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
let (caster, settings, cast) = cast_shadow(&fx.id, &p, &shapes).unwrap().unwrap();
|
||||
let alone = shadow::scoped_art(n.id, &caster, settings, cast, has_masks(&shapes));
|
||||
assert!(!alone.is_empty(), "{id} {params}");
|
||||
assert_eq!(format!("{drawn:?}"), format!("{alone:?}"), "{id} {params}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,91 @@
|
||||
//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that
|
||||
//! can be edited on their own.
|
||||
//! can be edited on their own. Also the 3D and Materials panel's Render Settings › Wireframe, which
|
||||
//! draws those edges in place of the shaded faces while the effect stays live.
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, StrokeLayer};
|
||||
use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath};
|
||||
use vectorcraft_three_d::Facet;
|
||||
|
||||
use super::{
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane, is_three_d, label_of,
|
||||
members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts, union_bounds,
|
||||
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, INFLATE, Profile, ROTATE, built_solids, facets, geometry, has_solid, is_container, is_plane,
|
||||
is_three_d, label_of, members, object_profile, region, reshape_members, resolve, resolve_for, solid, solid_paint_sources, solid_parts,
|
||||
union_bounds,
|
||||
};
|
||||
use crate::{GeomContext, is_geometry};
|
||||
|
||||
/// The most distinct edges one object's wireframe may have.
|
||||
pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000;
|
||||
|
||||
/// The parameter that holds a 3D effect's render settings: an object whose `mode` is one of
|
||||
/// [`RENDER_MODES`].
|
||||
pub const RENDER: &str = "render";
|
||||
|
||||
/// The render modes of a 3D effect: `shaded` draws the lit faces, `wireframe` the edges of every
|
||||
/// face ([`renders_wireframe`]).
|
||||
pub const RENDER_MODES: [&str; 2] = ["shaded", "wireframe"];
|
||||
|
||||
/// The 3D effects that take [`RENDER`]: the 3D and Materials panel's Extrude & Bevel, Revolve,
|
||||
/// Inflate and Rotate. The 3D (Classic) effects have their own Wireframe surface.
|
||||
const TAKES_RENDER: [&str; 4] = [EXTRUDE, crate::REVOLVE, INFLATE, ROTATE];
|
||||
|
||||
/// The weight of a rendered wireframe edge, in points: the weight Expand as Wireframes strokes its
|
||||
/// edges with (VectorCraft's own).
|
||||
pub(crate) const WIRE_WEIGHT: f64 = 0.5;
|
||||
|
||||
/// Does effect `fx` draw as a wireframe: is it one of the effects that take [`RENDER`], with its
|
||||
/// `render.mode` set to `wireframe`?
|
||||
pub fn renders_wireframe(fx: &Effect) -> bool {
|
||||
wireframe_params(&fx.id, &fx.params)
|
||||
}
|
||||
|
||||
/// Do 3D effect `id`'s parameters `p` set it to draw as a wireframe ([`renders_wireframe`])? A
|
||||
/// command that sets them is checked against the art that mode draws: the faces' edges, with no
|
||||
/// shadow, graphics or paint copies.
|
||||
pub(crate) fn wireframe_params(id: &str, p: &Value) -> bool {
|
||||
TAKES_RENDER.contains(&id) && p.get(RENDER).and_then(|r| r.get("mode")).and_then(Value::as_str) == Some("wireframe")
|
||||
}
|
||||
|
||||
/// Check the render settings in 3D effect `id`'s parameters `p`: `render`, when given to one of the
|
||||
/// effects in [`TAKES_RENDER`], is an object that holds only `mode`, one of [`RENDER_MODES`] (a
|
||||
/// missing `mode` is `shaded`). The 3D (Classic) effects refuse it as a parameter they do not take.
|
||||
pub(crate) fn validate_render(id: &str, p: &Value) -> Result<(), String> {
|
||||
let Some(render) = p.get(RENDER).filter(|_| TAKES_RENDER.contains(&id)) else { return Ok(()) };
|
||||
let valid = render
|
||||
.as_object()
|
||||
.is_some_and(|fields| fields.iter().all(|(key, value)| key == "mode" && value.as_str().is_some_and(|m| RENDER_MODES.contains(&m))));
|
||||
if !valid {
|
||||
return Err("`render` must be an object holding only `mode`, set to shaded or wireframe".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The art a 3D effect in wireframe mode draws for object `id` in place of its shaded faces: a group
|
||||
/// of the edges of `faces`, each edge once ([`edges`]), stroked [`WIRE_WEIGHT`] black with round
|
||||
/// joins and no fill, as Expand as Wireframes strokes them. Like Expand as Wireframes and the
|
||||
/// Outline view, the mesh shows every edge whatever the opacity, blending mode or opacity mask of
|
||||
/// the fills, strokes and group members it is built from; the object's own transparency applies to
|
||||
/// the art as a whole. `None` past [`MAX_WIRE_EDGES`] edges, when the canvas draws the source art,
|
||||
/// as it does for a solid past its limits.
|
||||
pub(crate) fn wire_art(id: NodeId, faces: &[PathData]) -> Option<Arc<Node>> {
|
||||
let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT);
|
||||
stroke.join = LineJoin::Round;
|
||||
let appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
|
||||
let children = edges(faces).ok()?.into_iter().map(|path| Arc::new(Node::path(id, path, appearance.clone()))).collect();
|
||||
Some(Arc::new(Node::group(id, children)))
|
||||
}
|
||||
|
||||
/// The art 3D effect `fx` in wireframe mode draws for object `id` from `shapes`: the edges of the
|
||||
/// faces it builds ([`wire_art`]). `None` when a solid can't be built or past the edge limit, when
|
||||
/// the canvas draws the source art.
|
||||
pub(crate) fn wire_surfaces(id: NodeId, fx: &Effect, shapes: &[Profile]) -> Option<Vec<Arc<Node>>> {
|
||||
let faces: Vec<PathData> = facet_paths(fx, shapes).ok()?.into_iter().map(|f| f.path).collect();
|
||||
Some(vec![wire_art(id, &faces)?])
|
||||
}
|
||||
|
||||
/// The grid points are rounded to before edges are compared, in points: two faces that share an
|
||||
/// edge give it once.
|
||||
const GRID: f64 = 1.0 / 1024.0;
|
||||
@@ -171,7 +240,7 @@ fn solid_face_paths(doc: Option<&Document>, n: &Node) -> Result<FacesAndShadow,
|
||||
/// as it is left out of the drawn art; past the limits of the object's solids together, the result
|
||||
/// is an error, as the canvas draws the source art. Each facet carries the width of the stroke the
|
||||
/// canvas draws around it.
|
||||
fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, String> {
|
||||
pub(crate) fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result<Vec<WireFace>, String> {
|
||||
let label = label_of(&fx.id);
|
||||
let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?;
|
||||
let p = crate::merged_params(&fx.id, &fx.params);
|
||||
|
||||
@@ -281,6 +281,210 @@ fn a_clipping_group_with_revolve_and_rotate_expands_the_art_revolve_cuts() {
|
||||
assert_eq!(both, alone);
|
||||
}
|
||||
|
||||
/// The leaves `art` draws: each path with its fill and stroke.
|
||||
fn leaves(art: &Node) -> Vec<(PathData, bool, Option<StrokeLayer>)> {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |c| {
|
||||
if let Some(p) = c.path_data() {
|
||||
out.push((p.clone(), c.appearance.fill().is_some(), c.appearance.stroke().cloned()));
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The art the canvas draws for `n`: Revolve's, else the other 3D effects'.
|
||||
fn drawn(n: &Node) -> Node {
|
||||
crate::revolve_art(n).or_else(|| super::super::solid_art(n)).unwrap_or_else(|| panic!("no art for {n:?}"))
|
||||
}
|
||||
|
||||
const WIRE: [&str; 4] = [super::super::EXTRUDE, crate::REVOLVE, super::super::INFLATE, ROTATE];
|
||||
|
||||
/// Render Settings › Wireframe: each of the panel's four effects draws the edges Expand as
|
||||
/// Wireframes gives, each a 0.5 pt black stroke with round joins and no fill, in place of its
|
||||
/// shaded faces; shaded again, it draws filled faces.
|
||||
#[test]
|
||||
fn wireframe_mode_draws_the_expanded_edges_as_strokes() {
|
||||
for id in WIRE {
|
||||
let n = solid_square(id, json!({"render": {"mode": "wireframe"}}));
|
||||
let art = leaves(&drawn(&n));
|
||||
let wire = three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"));
|
||||
assert_eq!(art.len(), wire.len(), "{id}");
|
||||
for ((path, filled, stroke), edge) in art.iter().zip(&wire) {
|
||||
assert!(!filled, "{id}: an edge has no fill");
|
||||
let stroke = stroke.as_ref().unwrap_or_else(|| panic!("{id}: an edge is stroked"));
|
||||
assert_eq!((stroke.width, stroke.join, &stroke.paint), (WIRE_WEIGHT, LineJoin::Round, &Paint::solid(Color::BLACK)), "{id}");
|
||||
assert_eq!(segments(std::slice::from_ref(path)), segments(std::slice::from_ref(edge)), "{id}");
|
||||
}
|
||||
let shaded = leaves(&drawn(&solid_square(id, json!({"render": {"mode": "shaded"}}))));
|
||||
assert!(shaded.iter().any(|(_, filled, _)| *filled), "{id}: shaded faces are filled");
|
||||
}
|
||||
// The box turned off axis shows the nine edges of its three faces.
|
||||
let n = solid_square(super::super::EXTRUDE, json!({"render": {"mode": "wireframe"}}));
|
||||
let paths: Vec<PathData> = leaves(&drawn(&n)).into_iter().map(|(p, ..)| p).collect();
|
||||
assert_eq!(segments(&paths).len(), 9);
|
||||
}
|
||||
|
||||
/// The wireframe stays live: a deeper extrusion and a turned view redraw the edges.
|
||||
#[test]
|
||||
fn wireframe_mode_follows_the_effects_settings() {
|
||||
let paths = |p: Value| -> Vec<PathData> { leaves(&drawn(&solid_square(super::super::EXTRUDE, p))).into_iter().map(|(p, ..)| p).collect() };
|
||||
let flat = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 10.0})));
|
||||
let deep = bounds(&paths(json!({"render": {"mode": "wireframe"}, "depth": 200.0})));
|
||||
assert!(deep.width() > flat.width() + 1.0 || deep.height() > flat.height() + 1.0, "{flat:?} {deep:?}");
|
||||
let turned = paths(json!({"render": {"mode": "wireframe"}, "rotationY": 60.0}));
|
||||
assert_ne!(segments(&turned), segments(&paths(json!({"render": {"mode": "wireframe"}}))));
|
||||
}
|
||||
|
||||
/// In wireframe mode no shadow and no graphic is drawn: only the edges.
|
||||
#[test]
|
||||
fn wireframe_mode_draws_no_shadow() {
|
||||
for id in WIRE {
|
||||
let n = solid_square(id, json!({"render": {"mode": "wireframe"}, "shadow": true}));
|
||||
let art = leaves(&drawn(&n));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode works where the effect is on a fill and on a group: the fill's solid and every member's
|
||||
/// solid draw as edges, and the geometry effects after a fill's effect still apply to them.
|
||||
#[test]
|
||||
fn wireframe_mode_on_a_fill_and_on_a_group() {
|
||||
for id in WIRE {
|
||||
let mut n = solid_square(id, json!({}));
|
||||
let mut fx = n.appearance.effects.remove(0);
|
||||
fx.params["render"] = json!({"mode": "wireframe"});
|
||||
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
fill.effects_mut().push(fx.clone());
|
||||
fill.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 500.0})).unwrap());
|
||||
let art = leaves(&drawn(&n));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a fill");
|
||||
|
||||
let member = |x: f64, id: u64| {
|
||||
Arc::new(Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)))
|
||||
};
|
||||
let mut g = Node::group(NodeId(1), vec![member(100.0, 2), member(200.0, 3)]);
|
||||
g.appearance.effects.push(fx);
|
||||
let art = leaves(&drawn(&g));
|
||||
assert!(!art.is_empty() && art.iter().all(|(_, filled, stroke)| !filled && stroke.is_some()), "{id} on a group");
|
||||
// Both members' edges are drawn.
|
||||
let paths: Vec<PathData> = art.into_iter().map(|(p, ..)| p).collect();
|
||||
assert!(bounds(&paths).width() > 100.0, "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh shows every edge, as Expand as Wireframes gives them, whatever the opacity of the fill
|
||||
/// and the opacity masks of the group's members; the object's own opacity stays on the art. Two
|
||||
/// members that touch, one at 50% and one masked, draw their shared edge once: seven edges.
|
||||
#[test]
|
||||
fn the_mesh_shows_every_edge_whatever_the_members_transparency() {
|
||||
let member = |x: f64, id: u64, opacity: f32| {
|
||||
let mut n = Node::path(NodeId(id), square(x, 100.0, 50.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.opacity = opacity;
|
||||
}
|
||||
n
|
||||
};
|
||||
let mut masked = member(150.0, 3, 1.0);
|
||||
masked.extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(member(0.0, 900, 1.0), true)));
|
||||
let mut g = Node::group(NodeId(1), vec![Arc::new(member(100.0, 2, 0.5)), Arc::new(masked)]);
|
||||
g.opacity = 0.75;
|
||||
g.appearance.effects.push(crate::new_effect(ROTATE, &json!({"render": {"mode": "wireframe"}})).unwrap());
|
||||
let art = drawn(&g);
|
||||
assert_eq!(art.opacity, 0.75);
|
||||
let paths: Vec<PathData> = leaves(&art).into_iter().map(|(p, ..)| p).collect();
|
||||
assert_eq!(segments(&paths).len(), 7, "{paths:?}");
|
||||
assert_eq!(segments(&paths).len(), segments(&three_d_wireframe_in(None, &g).unwrap()).len());
|
||||
let mut scoped = 0;
|
||||
for c in art.children().into_iter().flatten() {
|
||||
c.walk(&mut |c| scoped += usize::from(c.extras().mask.is_some() || c.opacity < 1.0));
|
||||
}
|
||||
assert_eq!(scoped, 0, "no part of the mesh is masked or faded");
|
||||
// A fill at 0% still shows its mesh.
|
||||
for id in WIRE {
|
||||
let mut n = solid_square(id, json!({"render": {"mode": "wireframe"}}));
|
||||
if let Some(AppearanceItem::Fill(f)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))) {
|
||||
f.opacity = 0.0;
|
||||
}
|
||||
assert!(!leaves(&drawn(&n)).is_empty(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand Appearance of a Revolve in wireframe mode gives the stroked edges, not the shaded faces.
|
||||
#[test]
|
||||
fn expanding_a_revolve_in_wireframe_mode_gives_the_edges() {
|
||||
let n = solid_square(crate::REVOLVE, json!({"render": {"mode": "wireframe"}}));
|
||||
let art = leaves(&crate::revolve::expand_revolve_art(&n).unwrap());
|
||||
assert_eq!(art.len(), three_d_wireframe_in(None, &n).unwrap().len());
|
||||
assert!(art.iter().all(|(_, filled, stroke)| !filled && stroke.as_ref().is_some_and(|s| s.width == WIRE_WEIGHT)));
|
||||
}
|
||||
|
||||
/// `render` is checked before an edit: an object holding only `mode`, `shaded` or `wireframe`, and
|
||||
/// only on the panel's four effects.
|
||||
#[test]
|
||||
fn render_settings_are_validated() {
|
||||
for id in WIRE {
|
||||
for good in [json!({}), json!({"render": {}}), json!({"render": {"mode": "shaded"}}), json!({"render": {"mode": "wireframe"}})] {
|
||||
assert_eq!(crate::validate_three_d_params(id, &good), Ok(()), "{id} {good}");
|
||||
}
|
||||
for bad in [
|
||||
json!({"render": "wireframe"}),
|
||||
json!({"render": null}),
|
||||
json!({"render": {"mode": "raytrace"}}),
|
||||
json!({"render": {"mode": true}}),
|
||||
json!({"render": {"mode": "wireframe", "quality": "high"}}),
|
||||
] {
|
||||
let e = crate::validate_three_d_params(id, &bad).unwrap_err();
|
||||
assert_eq!(e, "`render` must be an object holding only `mode`, set to shaded or wireframe", "{id} {bad}");
|
||||
}
|
||||
// The command check on the object refuses it too.
|
||||
let n = solid_square(id, json!({}));
|
||||
assert!(crate::validate_three_d(&n, id, &json!({"render": {"mode": "x"}})).is_err(), "{id}");
|
||||
}
|
||||
for id in [super::super::CLASSIC_EXTRUDE, crate::CLASSIC_REVOLVE, super::super::CLASSIC_ROTATE] {
|
||||
let e = crate::validate_three_d_params(id, &json!({"render": {"mode": "wireframe"}})).unwrap_err();
|
||||
assert!(e.contains("`render`"), "{id}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Revolve whose shaded surface is past the budget of paint copies (a gradient with many stops) is
|
||||
/// refused shaded, but in wireframe mode, which draws only the black edges, it is accepted and drawn:
|
||||
/// on the object and on a fill.
|
||||
#[test]
|
||||
fn wireframe_mode_is_checked_against_the_edges_it_draws() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
let n = solid_square(crate::REVOLVE, json!({}));
|
||||
let path = n.path_data().unwrap().clone();
|
||||
let faces = vectorcraft_three_d::revolve(&path, path.bounds().unwrap(), crate::revolve::revolve_options(&json!({}))).unwrap().len();
|
||||
let stops = crate::revolve::MAX_PAINT_COPIES / (faces * 4) / std::mem::size_of::<GradientStop>() + 1;
|
||||
let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect();
|
||||
let gradient = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops))));
|
||||
let mut n = n;
|
||||
n.appearance = Appearance::basic(gradient, Paint::None, 0.0).into();
|
||||
let shaded = json!({});
|
||||
let wire = json!({"render": {"mode": "wireframe"}});
|
||||
let refused = crate::validate_revolve(&n, &shaded).unwrap_err();
|
||||
assert!(refused.contains("simplify the gradient"), "{refused}");
|
||||
assert_eq!(crate::validate_revolve(&n, &wire), Ok(()));
|
||||
n.appearance.effects.push(crate::new_effect(crate::REVOLVE, &wire).unwrap());
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
// On the fill.
|
||||
let fx = n.appearance.effects.remove(0);
|
||||
let at = n.appearance.items.iter().position(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
|
||||
assert!(crate::revolve::validate_item_revolve(&n, &shaded, at, 0).is_err());
|
||||
assert_eq!(crate::revolve::validate_item_revolve(&n, &wire, at, 0), Ok(()));
|
||||
n.appearance.items[at].effects_mut().push(fx);
|
||||
assert!(leaves(&drawn(&n)).iter().all(|(_, filled, stroke)| !filled && stroke.is_some()));
|
||||
}
|
||||
|
||||
/// A 3D (Classic) effect ignores a `render` it does not take in a loaded file: it draws as before.
|
||||
#[test]
|
||||
fn a_classic_effect_is_not_drawn_as_a_render_wireframe() {
|
||||
let mut n = solid_square(super::super::CLASSIC_EXTRUDE, json!({}));
|
||||
n.appearance.effects[0].params["render"] = json!({"mode": "wireframe"});
|
||||
assert!(!renders_wireframe(&n.appearance.effects[0]));
|
||||
assert!(leaves(&drawn(&n)).iter().any(|(_, filled, _)| *filled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_without_a_visible_3d_effect_is_an_error() {
|
||||
let mut n = solid_square(super::super::EXTRUDE, json!({}));
|
||||
|
||||
@@ -16,6 +16,7 @@ use vectorcraft_geom::{Affine, Rect, Vec2};
|
||||
use crate::pixel::PixelSpace;
|
||||
use crate::util::{num, text};
|
||||
|
||||
pub mod defaults;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
//! The default SVG filters: the filters Effect › SVG Filters and Apply SVG Filter list in every
|
||||
//! document. The set, the names and the values are VectorCraft's own, written with the filter
|
||||
//! primitives of SVG 1.1 (<https://www.w3.org/TR/SVG11/filters.html>). A default is not part of a
|
||||
//! document until it is applied or edited there: the document then holds a copy under the
|
||||
//! default's name, and that copy stands in the default's place in the lists. Every default computes
|
||||
//! in sRGB (`color-interpolation-filters="sRGB"`), so art a filter passes through keeps its colors.
|
||||
|
||||
use vectorcraft_doc::SvgFilter;
|
||||
|
||||
/// A default SVG filter: its name (the `<filter>` element's `id`) and the element's XML.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct DefaultFilter {
|
||||
pub name: &'static str,
|
||||
pub xml: &'static str,
|
||||
}
|
||||
|
||||
/// The default filters, in the order the lists show them.
|
||||
pub const DEFAULT_FILTERS: [DefaultFilter; 14] = [
|
||||
DefaultFilter {
|
||||
name: "Soft Blur",
|
||||
xml: r#"<filter id="Soft Blur" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="2"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Heavy Blur",
|
||||
xml: r#"<filter id="Heavy Blur" x="-50%" y="-50%" width="200%" height="200%" color-interpolation-filters="sRGB"><feGaussianBlur stdDeviation="6"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Soft Shadow",
|
||||
xml: r#"<filter id="Soft Shadow" x="-30%" y="-30%" width="170%" height="170%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="3"/><feOffset dx="4" dy="4"/><feComponentTransfer><feFuncA type="linear" slope="0.5"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hard Shadow",
|
||||
xml: r#"<filter id="Hard Shadow" x="-20%" y="-20%" width="150%" height="150%" color-interpolation-filters="sRGB"><feOffset in="SourceAlpha" dx="3" dy="3"/><feComponentTransfer><feFuncA type="linear" slope="0.6"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Glow",
|
||||
xml: r##"<filter id="Glow" x="-40%" y="-40%" width="180%" height="180%" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="4" result="spread"/><feFlood flood-color="#ffd24a"/><feComposite in2="spread" operator="in"/><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Bevel",
|
||||
xml: r##"<filter id="Bevel" color-interpolation-filters="sRGB"><feGaussianBlur in="SourceAlpha" stdDeviation="2" result="height"/><feSpecularLighting in="height" surfaceScale="4" specularConstant="0.8" specularExponent="16" lighting-color="#ffffff" result="light"><feDistantLight azimuth="225" elevation="45"/></feSpecularLighting><feComposite in="light" in2="SourceAlpha" operator="in" result="lit"/><feComposite in="SourceGraphic" in2="lit" operator="arithmetic" k1="0" k2="1" k3="1" k4="0"/></filter>"##,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Emboss",
|
||||
xml: r#"<filter id="Emboss" color-interpolation-filters="sRGB"><feConvolveMatrix order="3" kernelMatrix="-2 -1 0 -1 1 1 0 1 2" preserveAlpha="true"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thicken",
|
||||
xml: r#"<filter id="Thicken" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feMorphology operator="dilate" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Thin",
|
||||
xml: r#"<filter id="Thin" color-interpolation-filters="sRGB"><feMorphology operator="erode" radius="1.5"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Rough Edges",
|
||||
xml: r#"<filter id="Rough Edges" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB"><feTurbulence type="turbulence" baseFrequency="0.05" numOctaves="2" result="waves"/><feDisplacementMap in="SourceGraphic" in2="waves" scale="6" xChannelSelector="R" yChannelSelector="G"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grain",
|
||||
xml: r#"<filter id="Grain" color-interpolation-filters="sRGB"><feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.35 0"/><feComposite in2="SourceAlpha" operator="in" result="specks"/><feMerge><feMergeNode in="SourceGraphic"/><feMergeNode in="specks"/></feMerge></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Grayscale",
|
||||
xml: r#"<filter id="Grayscale" color-interpolation-filters="sRGB"><feColorMatrix type="saturate" values="0"/></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Invert",
|
||||
xml: r#"<filter id="Invert" color-interpolation-filters="sRGB"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer></filter>"#,
|
||||
},
|
||||
DefaultFilter {
|
||||
name: "Hue Shift",
|
||||
xml: r#"<filter id="Hue Shift" color-interpolation-filters="sRGB"><feColorMatrix type="hueRotate" values="180"/></filter>"#,
|
||||
},
|
||||
];
|
||||
|
||||
/// The default filter named `name`.
|
||||
pub fn default_filter(name: &str) -> Option<DefaultFilter> {
|
||||
DEFAULT_FILTERS.iter().copied().find(|f| f.name == name)
|
||||
}
|
||||
|
||||
impl DefaultFilter {
|
||||
/// The filter as a document holds it once it is applied or edited there.
|
||||
pub fn to_filter(self) -> SvgFilter {
|
||||
SvgFilter { name: self.name.to_string(), xml: self.xml.to_string() }
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter of the lists ([`listed`]), and whether it is a default the document does not hold.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Listed {
|
||||
pub filter: SvgFilter,
|
||||
/// A default the document has no filter named for: applying or editing it adds a copy.
|
||||
pub default: bool,
|
||||
}
|
||||
|
||||
/// The filters Effect › SVG Filters and Apply SVG Filter list for a document that holds `held`,
|
||||
/// and how many of them come first as the defaults: each default in [`DEFAULT_FILTERS`]' order (the
|
||||
/// document's filter of that name in its place), then the document's other filters in their order.
|
||||
pub fn listed(held: &[SvgFilter]) -> (Vec<Listed>, usize) {
|
||||
let mut out: Vec<Listed> = DEFAULT_FILTERS
|
||||
.iter()
|
||||
.map(|d| match held.iter().find(|f| f.name == d.name) {
|
||||
Some(f) => Listed { filter: f.clone(), default: false },
|
||||
None => Listed { filter: d.to_filter(), default: true },
|
||||
})
|
||||
.collect();
|
||||
let defaults = out.len();
|
||||
out.extend(held.iter().filter(|f| default_filter(&f.name).is_none()).map(|f| Listed { filter: f.clone(), default: false }));
|
||||
(out, defaults)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::*;
|
||||
use crate::pixel::{Channels, PixelSpace};
|
||||
use crate::svg_filter::{SVG_FILTER, SvgFilterFx, check, with_id};
|
||||
use crate::{PixelFx, RasterFx, raster_effects};
|
||||
|
||||
/// A `w` × `w` raster whose pixels are one point wide.
|
||||
fn space(w: usize) -> PixelSpace {
|
||||
let wd = w as f64;
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(1.0),
|
||||
px: 1.0,
|
||||
center: Point::new(wd / 2.0, wd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, wd),
|
||||
channels: Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: 0.5 * wd.hypot(wd),
|
||||
}
|
||||
}
|
||||
|
||||
/// The default named `name` as the renderer reads it.
|
||||
fn fx(name: &str) -> SvgFilterFx {
|
||||
let d = default_filter(name).unwrap_or_else(|| panic!("no default {name}"));
|
||||
let e = Effect { id: SVG_FILTER.into(), params: json!({"name": d.name, "xml": d.xml}), visible: true };
|
||||
match raster_effects(&[e]).first() {
|
||||
Some(RasterFx::Pixel(PixelFx::Svg(f))) => f.clone(),
|
||||
other => panic!("{name}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A 40 × 40 raster with an opaque square of `rgb` from 10 to 30, run through default `name`.
|
||||
fn run(name: &str, rgb: [u8; 3]) -> Vec<u8> {
|
||||
let mut data: Vec<u8> = (0..40usize)
|
||||
.flat_map(|y| (0..40usize).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| if (10..30).contains(&x) && (10..30).contains(&y) { [rgb[0], rgb[1], rgb[2], 255] } else { [0; 4] })
|
||||
.collect();
|
||||
fx(name).apply(&mut data, 40, 40, &space(40));
|
||||
data
|
||||
}
|
||||
|
||||
fn at(d: &[u8], x: usize, y: usize) -> [u8; 4] {
|
||||
let i = (y * 40 + x) * 4;
|
||||
[d[i], d[i + 1], d[i + 2], d[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_is_a_filter_the_check_takes_under_its_own_name() {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_eq!(check(d.xml), Ok(d.name.to_string()), "{}", d.name);
|
||||
assert!(seen.insert(d.name), "{} is listed twice", d.name);
|
||||
assert_eq!(d.name, d.name.trim());
|
||||
// Edit SVG Filter keeps the name by writing it as the id: a default's code comes back as it is.
|
||||
assert_eq!(with_id(d.xml, d.name).as_deref(), Some(d.xml), "{}", d.name);
|
||||
assert_eq!(default_filter(d.name), Some(d));
|
||||
assert!(d.xml.contains(r#" color-interpolation-filters="sRGB""#), "{} computes in sRGB", d.name);
|
||||
}
|
||||
assert!(DEFAULT_FILTERS.len() <= SvgFilter::MAX);
|
||||
assert_eq!(default_filter("soft blur"), None, "names match exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_default_draws_and_is_written_to_svg_as_a_filter() {
|
||||
let plain = {
|
||||
let mut d = vec![0u8; 40 * 40 * 4];
|
||||
for y in 10..30 {
|
||||
for x in 10..30 {
|
||||
d[(y * 40 + x) * 4..(y * 40 + x) * 4 + 4].copy_from_slice(&[200, 60, 20, 255]);
|
||||
}
|
||||
}
|
||||
d
|
||||
};
|
||||
for d in DEFAULT_FILTERS {
|
||||
assert_ne!(run(d.name, [200, 60, 20]), plain, "{} changes what is drawn", d.name);
|
||||
assert!(fx(d.name).writes_as_svg11(), "{} is written as SVG 1.1", d.name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The color defaults against SVG 1.1's own arithmetic, in sRGB as each filter asks.
|
||||
#[test]
|
||||
fn the_color_defaults_compute_what_svg_1_1_defines() {
|
||||
let near = |got: [u8; 4], want: [u8; 4]| got.iter().zip(want).all(|(g, w)| g.abs_diff(w) <= 1);
|
||||
// feComponentTransfer, type="table" with values 1 0: C' = 1 - C (§15.11).
|
||||
let inv = at(&run("Invert", [200, 60, 20]), 20, 20);
|
||||
assert!(near(inv, [55, 195, 235, 255]), "{inv:?}");
|
||||
// feColorMatrix type="saturate" values="0": every channel is 0.213 R + 0.715 G + 0.072 B (§15.10).
|
||||
let grey = at(&run("Grayscale", [200, 60, 20]), 20, 20);
|
||||
let l = (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64).round() as u8;
|
||||
assert!(near(grey, [l, l, l, 255]), "{grey:?} for {l}");
|
||||
// feColorMatrix type="hueRotate" values="180" (§15.10): cos = -1 and sin = 0 leave
|
||||
// R' = (2·0.213 - 1) R + 2·0.715 G + 2·0.072 B, and likewise for G' and B'.
|
||||
let hue = at(&run("Hue Shift", [200, 60, 20]), 20, 20);
|
||||
let lum2 = 2.0 * (0.213 * 200.0 + 0.715 * 60.0 + 0.072 * 20.0f64);
|
||||
let turned = [lum2 - 200.0, lum2 - 60.0, lum2 - 20.0].map(|v| v.round().clamp(0.0, 255.0) as u8);
|
||||
assert!(near(hue, [turned[0], turned[1], turned[2], 255]), "{hue:?} for {turned:?}");
|
||||
}
|
||||
|
||||
/// The shape defaults against what their primitives define: an offset copy of the alpha behind
|
||||
/// the art (feOffset, §15.21), and a shape grown or shrunk by its radius (feMorphology, §15.20).
|
||||
#[test]
|
||||
fn the_shape_defaults_move_and_resize_the_alpha() {
|
||||
let shadow = run("Hard Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&shadow, 20, 20), [200, 60, 20, 255], "the art is on top");
|
||||
// Right of and below the art by up to 3: black at 60% alpha (premultiplied 153).
|
||||
assert_eq!(at(&shadow, 31, 31), [0, 0, 0, 153]);
|
||||
assert_eq!(at(&shadow, 34, 34)[3], 0, "past the offset");
|
||||
assert_eq!(at(&shadow, 8, 8)[3], 0, "nothing up and left");
|
||||
let thick = run("Thicken", [200, 60, 20]);
|
||||
assert_eq!((at(&thick, 9, 20)[3], at(&thick, 7, 20)[3]), (255, 0), "grown by its radius");
|
||||
let thin = run("Thin", [200, 60, 20]);
|
||||
assert_eq!((at(&thin, 10, 20)[3], at(&thin, 13, 20)[3]), (0, 255), "shrunk by its radius");
|
||||
let soft = run("Soft Shadow", [200, 60, 20]);
|
||||
assert_eq!(at(&soft, 20, 20), [200, 60, 20, 255]);
|
||||
let below = at(&soft, 33, 33);
|
||||
assert!(below[3] > 0 && below[3] < 128 && below[0] == 0, "a blurred, half-strength shadow: {below:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_show_the_defaults_first_with_the_documents_copy_in_place() {
|
||||
let (all, defaults) = listed(&[]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len(), DEFAULT_FILTERS.len()));
|
||||
assert!(all.iter().all(|l| l.default));
|
||||
let mine = SvgFilter { name: "Mine".into(), xml: "<filter id=\"Mine\"><feOffset/></filter>".into() };
|
||||
let glow = SvgFilter { name: "Glow".into(), xml: "<filter id=\"Glow\"><feOffset dx=\"1\"/></filter>".into() };
|
||||
let (all, defaults) = listed(&[mine.clone(), glow.clone()]);
|
||||
assert_eq!((all.len(), defaults), (DEFAULT_FILTERS.len() + 1, DEFAULT_FILTERS.len()));
|
||||
let at = DEFAULT_FILTERS.iter().position(|d| d.name == "Glow").unwrap();
|
||||
assert_eq!(all[at], Listed { filter: glow, default: false }, "the document's Glow where the default was");
|
||||
assert_eq!(all.last(), Some(&Listed { filter: mine, default: false }));
|
||||
assert_eq!(all.iter().filter(|l| l.default).count(), DEFAULT_FILTERS.len() - 1);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,15 @@ use crate::{PixelFx, RasterFx, raster_effects};
|
||||
/// resolution whose pixels are `line` points wide.
|
||||
fn space(w: usize, h: usize, px: f64, line: f64) -> PixelSpace {
|
||||
let (wd, hd) = (w as f64 * px, h as f64 * px);
|
||||
PixelSpace { to_doc: Affine::scale(px), px, center: Point::new(wd / 2.0, hd / 2.0), channels: Channels::Rgb, line, extent: 0.5 * wd.hypot(hd) }
|
||||
PixelSpace {
|
||||
to_doc: Affine::scale(px),
|
||||
px,
|
||||
center: Point::new(wd / 2.0, hd / 2.0),
|
||||
size: vectorcraft_geom::Vec2::new(wd, hd),
|
||||
channels: Channels::Rgb,
|
||||
line,
|
||||
extent: 0.5 * wd.hypot(hd),
|
||||
}
|
||||
}
|
||||
|
||||
/// `w` × `h` premultiplied pixels: `f(x, y)` each.
|
||||
|
||||
@@ -1850,6 +1850,7 @@ fn rasterize_compose_leaves_the_raster_alone_when_the_sizes_do_not_fit() {
|
||||
to_doc: Affine::IDENTITY,
|
||||
px: 1.0,
|
||||
center: Point::new(1.0, 1.0),
|
||||
size: vectorcraft_geom::Vec2::new(2.0, 2.0),
|
||||
channels: pixel::Channels::Rgb,
|
||||
line: 1.0,
|
||||
extent: std::f64::consts::SQRT_2,
|
||||
|
||||
@@ -172,6 +172,48 @@ fn the_clipping_paths_effects_apply_before_the_clip_groups() {
|
||||
assert!((b.x0 - want.x0).abs() < 0.5 && (b.x1 - want.x1).abs() < 0.5, "exported: {b:?} against {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clip_group_with_a_fill_or_stroke_of_its_own_clips_as_the_canvas_does() {
|
||||
// A clip group with a fill or a stroke of its own and no effects: the export turns its paint
|
||||
// into art and still clips by the outline the canvas clips by, Transform copies included.
|
||||
let items = [
|
||||
vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))),
|
||||
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 2.0)),
|
||||
];
|
||||
let copies = || fx("distort.transform", json!({"moveH": 60, "copies": 1}));
|
||||
let roughen = fx("distort.roughen", json!({"size": 10, "detail": 10, "relative": false}));
|
||||
// A ring: a compound path of two squares with effects `own`, its hole with effects `hole_fx`.
|
||||
let ring = |hole_fx: Vec<Effect>, own: Vec<Effect>| {
|
||||
let outer = Node::path(NodeId(3), shapes::rectangle(Rect::new(50.0, 50.0, 150.0, 150.0)), Appearance::default());
|
||||
let mut hole = Node::path(NodeId(4), shapes::rectangle(Rect::new(75.0, 75.0, 125.0, 125.0)), Appearance::default());
|
||||
hole.appearance.effects = hole_fx;
|
||||
let mut c =
|
||||
Node::new(NodeId(2), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: vectorcraft_geom::FillRule::EvenOdd });
|
||||
c.appearance.effects = own;
|
||||
c
|
||||
};
|
||||
let clips = [
|
||||
("copies", clipping_path(2, vec![copies()])),
|
||||
("roughen", clipping_path(2, vec![roughen])),
|
||||
("a compound path's copies", ring(vec![], vec![copies()])),
|
||||
("a compound path member's copies", ring(vec![copies()], vec![])),
|
||||
];
|
||||
for item in &items {
|
||||
for (what, clip) in &clips {
|
||||
let mut d = Document::new(400.0, 400.0);
|
||||
let layer = d.layers[0].id;
|
||||
let live = clip_outline(clip).unwrap();
|
||||
let mut group = clip_group(1, clip.clone());
|
||||
group.appearance.items.push(item.clone());
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
let exported = clip_outline(&baked_clip(&d)).unwrap();
|
||||
assert_eq!(live, exported, "{what} with {item:?}: the canvas clips by the outline the export writes");
|
||||
}
|
||||
}
|
||||
let b = bounds(&clips[0].1);
|
||||
assert!((b.x0 - 50.0).abs() < 1e-6 && (b.x1 - 210.0).abs() < 1e-6, "the clip covers both copies: {b:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_effects_apply_before_the_clip_groups() {
|
||||
// The clip group grows its clipping path by 10 (Offset Path). Inside the clipping path a
|
||||
|
||||
@@ -43,6 +43,7 @@ pub(crate) mod graph;
|
||||
mod halftone;
|
||||
pub mod help;
|
||||
pub mod importmatches;
|
||||
mod info;
|
||||
pub(crate) mod inline;
|
||||
mod interactivity;
|
||||
mod intertwine;
|
||||
@@ -344,6 +345,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(docmenu::specs());
|
||||
v.extend(variablecmds::specs());
|
||||
v.extend(docinfo::specs());
|
||||
v.extend(info::specs());
|
||||
v.extend(panelcmds::specs());
|
||||
v.extend(artboardalign::specs());
|
||||
v.extend(buildcmds::specs());
|
||||
@@ -827,7 +829,8 @@ pub use docmenu::guide_indexes;
|
||||
pub(crate) use edit::{settle_interaction, typing_in_progress};
|
||||
pub(crate) use object::bounds_rewrite;
|
||||
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
|
||||
pub use plugin_call::{Location, key_location, location_in, location_keys};
|
||||
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
|
||||
pub use select::SIMILAR;
|
||||
pub(crate) use vectorcraft_doc::range::parse_range;
|
||||
|
||||
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
|
||||
|
||||
@@ -23,7 +23,7 @@ use vectorcraft_render::effects;
|
||||
use super::super::appearance::series_children_in_paint_order;
|
||||
use super::super::colorcmds::edit_if_changed;
|
||||
use super::super::edit::selected_roots;
|
||||
use super::super::graph::capture_series_object_opacity;
|
||||
use super::super::graph::{capture_series_object_opacity, series_groups_among};
|
||||
use super::super::menucmds::whole_or;
|
||||
use super::super::object::{choice, object_bounds_transform, scaling, transform_node, transform_patterns};
|
||||
use super::super::typecmd::refresh_bounds_of;
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Randomize Opacity",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md) → {count}",
|
||||
"{min?: % 0..100 (30), max?: % 0..100 (100; not less than min), seed?: whole number (0; the same seed, objects and range give the same opacities), ids?: [id…] (default: the selection)} give each selected object (the top-level ones) its own opacity, picked at random and evenly from min to max, as one undo step (none when no opacity changes); it is the object's opacity, as the Transparency panel sets it. On paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md) → {count}",
|
||||
has_selection,
|
||||
randomize_opacity
|
||||
),
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Sort Objects",
|
||||
["Object", "Plug-ins", "Arrange Tools"],
|
||||
None,
|
||||
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw (docs/mcp.md). A run that changes nothing makes no step → {count}",
|
||||
"{by?: \"width\" | \"height\" | \"area\" (width × height) | \"x\" (left edge) | \"y\" (top edge) | \"opacity\" (%) | \"stacking\" (stacking order, from the back) (\"area\"), apply?: one of the same (\"stacking\"), order?: \"ascending\" (small to large) | \"descending\" (large to small) | \"random\" (\"ascending\"), distribute?: false (true: the values step evenly from the smallest to the largest; false: the objects trade the values they have), seed?: whole number (0; the order \"random\" picks), scaleStrokes?: the Scale Strokes & Effects preference (width, height and area), ids?: [id…] (default: the selection)} sort the selected objects (the top-level ones, at most 20000) by the attribute `by` and give them the values of `apply` in that order, as one undo step: the first in order gets the smallest value. Sizes and places are measured and set as object.setBounds measures them (Use Preview Bounds), a width, height or area about each object's centre (an area in proportion); stacking order always trades places, and only among the objects in the same layer or group. With apply \"opacity\", on paths directly in a graph series whose opacity changes, the graph stores the opacity and blend mode of the frontmost of them for its next redraw, and on a series group, the group's own (docs/mcp.md). A run that changes nothing makes no step → {count}",
|
||||
has_multi,
|
||||
sort
|
||||
),
|
||||
@@ -418,9 +418,11 @@ fn randomize_opacity(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Store on their graphs the opacity just given to the paths among `changed` (objects whose opacity changed) that are
|
||||
/// directly in a graph series, with their blend mode, so that every path of the series has them when the graph is drawn
|
||||
/// again; the frontmost of them in a series sets them.
|
||||
/// again; the frontmost of them in a series sets them. A series group among `changed` has its own opacity stored for the
|
||||
/// group.
|
||||
fn keep_series_opacity(d: &mut vectorcraft_doc::Document, changed: &[NodeId]) {
|
||||
let marks = series_children_in_paint_order(d, changed);
|
||||
let mut marks = series_children_in_paint_order(d, changed);
|
||||
marks.extend(series_groups_among(d, changed));
|
||||
capture_series_object_opacity(d, &marks);
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Breaks",
|
||||
["Object", "Plug-ins", "Artwork Cleanup"],
|
||||
None,
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
|
||||
"{kind: \"line\"|\"paragraph\", ids?: [id…] (the type they name is taken locked or hidden too)} remove the forced line breaks (line) or paragraph returns (paragraph) in the characters selected with a Type tool (after Select All in a frame of threaded text, in the text of every frame of the story, locked and hidden frames included), else in all the text of the selected type, as one undo step; a break between two words becomes a space, the frames of a threaded story selected all together being read as one text → {ids, removed}",
|
||||
has_selection,
|
||||
remove_breaks
|
||||
),
|
||||
@@ -821,9 +821,9 @@ fn apply_cuts(t: &mut TextObject, cuts: &[(usize, bool)], brk: char) -> usize {
|
||||
}
|
||||
|
||||
/// The breaks `brk` in the text of the frames of `story`, read as one text: a break at the end or
|
||||
/// start of a frame between words of the frames on either side becomes a space. Each editable frame
|
||||
/// (each frame when `all`) comes with its own breaks, at its own bytes.
|
||||
fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(NodeId, Vec<(usize, bool)>)> {
|
||||
/// start of a frame between words of the frames on either side becomes a space. Each frame comes
|
||||
/// with its own breaks, at its own bytes, its locked and hidden frames included.
|
||||
fn story_cuts(d: &Document, story: &[NodeId], brk: char) -> Vec<(NodeId, Vec<(usize, bool)>)> {
|
||||
let texts: Vec<(NodeId, String)> = story.iter().filter_map(|id| Some((*id, text_of(d, *id)?.plain_text()))).collect();
|
||||
let joined: String = texts.iter().map(|(_, t)| t.as_str()).collect();
|
||||
// The breaks in story order, handed to the frames in one pass.
|
||||
@@ -836,9 +836,7 @@ fn story_cuts(d: &Document, story: &[NodeId], brk: char, all: bool) -> Vec<(Node
|
||||
while let Some((at, space)) = cuts.next_if(|(at, _)| *at < end) {
|
||||
own.push((at - start, space));
|
||||
}
|
||||
if all || d.is_editable(id) {
|
||||
out.push((id, own));
|
||||
}
|
||||
out.push((id, own));
|
||||
start = end;
|
||||
}
|
||||
out
|
||||
@@ -859,7 +857,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
// Each type object with the breaks that go from it.
|
||||
let targets: Vec<(NodeId, Vec<(usize, bool)>)> = match editing {
|
||||
Some(_) if !story.is_empty() => story_cuts(d, &story, brk, false),
|
||||
Some(_) if !story.is_empty() => story_cuts(d, &story, brk),
|
||||
Some((id, a, b)) => vec![(id, a.min(b), a.max(b))]
|
||||
.into_iter()
|
||||
.filter(|(id, ..)| d.is_editable(*id))
|
||||
@@ -886,8 +884,7 @@ fn remove_breaks(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
if !story.is_empty() && story.iter().all(|f| named.contains(f)) {
|
||||
done.extend(story.iter().copied());
|
||||
// Every frame is among them, so each one keeps its breaks.
|
||||
out.extend(story_cuts(d, &story, brk, true));
|
||||
out.extend(story_cuts(d, &story, brk));
|
||||
} else if let Some(t) = text_of(d, id) {
|
||||
// `id` is type, so the story of its thread is the same for each of its frames.
|
||||
partial.extend(thread);
|
||||
|
||||
@@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() {
|
||||
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap();
|
||||
assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1));
|
||||
assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays");
|
||||
// Stretched across its own axes (it is turned): skewed, so no longer.
|
||||
// Stretched along its turned bounding box: still the shape, wider along its own axis.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap();
|
||||
let r = shape_of(&s, id).unwrap();
|
||||
assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// Stretched across the page's axes (it is turned): skewed, so no longer.
|
||||
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap();
|
||||
assert_eq!(shape_of(&s, id), None);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(shape_of(&s, id).is_some(), "undo brings it back");
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path (when the type starts before an open path's start, the first character drawn on the path stays where it was drawn and the characters that were not drawn come before it); Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
@@ -229,6 +229,28 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
lay.glyphs.iter().filter(|g| g.origin.x.is_finite() && g.origin.y.is_finite()).min_by_key(|g| (g.byte, g.len != 0)).map(|g| g.origin)
|
||||
}
|
||||
|
||||
/// A glyph of a character: its byte, whether it stands for characters (a list marker does not),
|
||||
/// and its place among the glyphs of that byte and kind (an All Caps ß is two glyphs).
|
||||
type GlyphKey = (usize, bool, usize);
|
||||
|
||||
/// The key and pen position of the first glyph drawn in `lay`, in text order: characters before an
|
||||
/// open path's start are not drawn ([`vectorcraft_text::PositionedGlyph::off_path`]). None without
|
||||
/// a drawn glyph.
|
||||
fn first_drawn_pen(lay: &vectorcraft_text::TextLayout) -> Option<(GlyphKey, Point)> {
|
||||
let (gi, g) = (lay.glyphs.iter().enumerate())
|
||||
.filter(|(_, g)| !g.off_path && g.origin.x.is_finite() && g.origin.y.is_finite())
|
||||
.min_by_key(|(gi, g)| (g.byte, g.len != 0, *gi))?;
|
||||
let kind = g.len != 0;
|
||||
let nth = lay.glyphs.iter().take(gi).filter(|h| h.byte == g.byte && (h.len != 0) == kind).count();
|
||||
Some(((g.byte, kind, nth), g.origin))
|
||||
}
|
||||
|
||||
/// The pen position of the glyph `key` names in `lay`. None without one.
|
||||
fn pen_at(lay: &vectorcraft_text::TextLayout, (byte, kind, nth): GlyphKey) -> Option<Point> {
|
||||
let g = lay.glyphs.iter().filter(|g| g.byte == byte && (g.len != 0) == kind).nth(nth)?;
|
||||
(g.origin.x.is_finite() && g.origin.y.is_finite()).then_some(g.origin)
|
||||
}
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped, and
|
||||
@@ -237,13 +259,14 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
// Where the first character sat. Text that didn't fit on the path has no glyph there: it
|
||||
// starts at the start bracket.
|
||||
let at = first_pen(&vectorcraft_text::layout(db, t)).or_else(|| {
|
||||
// Where the first drawn character sat; characters before an open path's start come before it
|
||||
// on the line. Text that didn't fit on the path has no glyph there: it starts at the start
|
||||
// bracket.
|
||||
let (key, at) = first_drawn_pen(&vectorcraft_text::layout(db, t)).map(|(b, p)| (Some(b), p)).or_else(|| {
|
||||
let ap = ArcPath::new(path);
|
||||
let (from, _) = t.kind.path_span()?;
|
||||
let (p, _) = ap.at(from * ap.len());
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some((None, p))
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
// Point type has no brackets to fit: it keeps the sizes the path drew it at.
|
||||
@@ -254,9 +277,10 @@ fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
out.path_spacing = 0.0;
|
||||
// Point type is in no thread: its first paragraph starts in it.
|
||||
out.first_para_continues = false;
|
||||
// Where the point type puts its own first character; the origin moves so it lands at `at`,
|
||||
// whatever the paragraph's alignment and direction.
|
||||
let own = first_pen(&vectorcraft_text::layout(db, &out)).unwrap_or(Point::ZERO);
|
||||
// Where the point type puts that glyph; the origin moves so it lands at `at`, whatever the
|
||||
// paragraph's alignment and direction.
|
||||
let own_lay = vectorcraft_text::layout(db, &out);
|
||||
let own = key.and_then(|k| pen_at(&own_lay, k)).or_else(|| first_pen(&own_lay)).unwrap_or(Point::ZERO);
|
||||
let shift = at - own;
|
||||
if !(shift.x.is_finite() && shift.y.is_finite()) {
|
||||
return None;
|
||||
|
||||
@@ -482,6 +482,44 @@ mod release {
|
||||
}
|
||||
}
|
||||
|
||||
/// Type that starts before its open path: the first drawn character stays where it was drawn,
|
||||
/// and the characters that were not drawn come before it on the line.
|
||||
#[test]
|
||||
fn type_starting_before_its_open_path_keeps_its_drawn_characters_in_place() {
|
||||
let mut s = session();
|
||||
let id = path_type(&mut s, "M100 300 L500 300", [100.0, 300.0], "Hidden start");
|
||||
s.execute("type.pathOptions", &json!({"start": -0.05})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before);
|
||||
let first = lay.glyphs.iter().filter(|g| !g.off_path).min_by_key(|g| g.byte).unwrap();
|
||||
let (byte, drawn) = (first.byte, before.xf * first.origin);
|
||||
assert!(byte > 0, "some characters are before the path");
|
||||
s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
let after = text(&s, id);
|
||||
assert_eq!(after.kind, TextKind::Point);
|
||||
assert_eq!(after.plain_text(), before.plain_text());
|
||||
let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after);
|
||||
let same = back.glyphs.iter().find(|g| g.byte == byte).unwrap();
|
||||
assert!(close(after.xf * same.origin, drawn), "{:?} vs {drawn:?}", after.xf * same.origin);
|
||||
let lead = back.glyphs.iter().find(|g| g.byte == 0).unwrap();
|
||||
assert!((after.xf * lead.origin).x < drawn.x, "the hidden characters come before it");
|
||||
// An All Caps ß is two glyphs: with the first before the path's start, the second stays
|
||||
// where it was drawn.
|
||||
let id = path_type(&mut s, "M100 400 L500 400", [100.0, 400.0], "ße");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 0, "end": 4, "allCaps": true})).unwrap();
|
||||
let adv = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(&s, id)).glyphs[0].advance;
|
||||
s.execute("type.pathOptions", &json!({"start": -1.2 * adv / 400.0})).unwrap();
|
||||
let before = text(&s, id);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &before);
|
||||
assert!(lay.glyphs[0].byte == 0 && lay.glyphs[1].byte == 0 && lay.glyphs[0].off_path && !lay.glyphs[1].off_path);
|
||||
let drawn = before.xf * lay.glyphs[1].origin;
|
||||
s.execute(C, &json!({"mode": "text"})).unwrap();
|
||||
let after = text(&s, id);
|
||||
let back = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &after);
|
||||
let second = back.glyphs.iter().filter(|g| g.byte == 0).nth(1).unwrap();
|
||||
assert!(close(after.xf * second.origin, drawn), "{:?} vs {drawn:?}", after.xf * second.origin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipped_type_releases_its_path_as_it_runs() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Fill",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+/"),
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, true)
|
||||
),
|
||||
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add New Stroke",
|
||||
["Window", "Appearance"],
|
||||
Some("Cmd+Alt+/"),
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
|s, p| add_item(s, p, false)
|
||||
),
|
||||
@@ -66,7 +66,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} leave each object one empty fill and stroke (None; a group none of its own) and reset its opacity and blend mode. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
clear_appearance
|
||||
),
|
||||
@@ -75,7 +75,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reduce to Basic Appearance",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, target?} keep only one visible fill and stroke (without ids: the Appearance panel's active row in place of the topmost one of its kind; else the topmost), without their own opacity, blend mode or effects (a group keeps no rows it lacked), and drop the object's effects. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
reduce_basic
|
||||
),
|
||||
@@ -84,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index: paint-order item index, ids?|id? (default: the selection), target?: \"object\"|\"contents\", opacity?: 0..100, blend?: name, visible?: bool, weight?: pt (strokes), color?|none?|swatch?|gradient? (as paint.setFill), tint?: 0..100, keepModel?: bool (both as paint.setFill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} edit one fill/stroke of each target object's own appearance stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
set_item
|
||||
),
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Item",
|
||||
[],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} remove those fills/strokes from each target object's own stack. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
remove_item
|
||||
),
|
||||
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Effect",
|
||||
[],
|
||||
None,
|
||||
"{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?} → {ids, index, item}",
|
||||
"{…as effect.apply} same as effect.apply (an alias): {effect: id, params?: {…}, item?: appearance item index|null, ids?, target?, aligned?} → {ids, index, item}",
|
||||
has_doc,
|
||||
super::effectcmd::apply
|
||||
),
|
||||
@@ -111,7 +111,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Item",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
"{index | indices: [..] (paint-order item indices), to?: paint-order index of the copy (with several, of the lowest copy: they land together in their order; default: each right above its item; not with aligned rows of a mixed selection), contents?: count (with `to`: how many items paint below the Contents (Characters) row afterwards; default: it stays between the same items), ids?|id?, target?, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} copy fills/strokes with their effects, as Alt-dragging rows places them. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
duplicate_item
|
||||
),
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reorder Appearance Item",
|
||||
[],
|
||||
None,
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
"{from: paint-order item index | \"contents\", indices?: [..] (several items instead of from: they move as one block in their order, the lowest landing at `to`; a block landing next to the Contents row keeps its lowest item's side), to, contents?: count, ids?|id?, target?, aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} move fill/stroke `from` to paint-order index `to`; on a group, layer or type the Contents (Characters) row stays between the same items (a moved item landing next to it keeps its side) unless `contents` says how many items paint below it afterwards. from \"contents\": move that row so `to` items paint below the members (characters) and the rest above. On a path directly in a graph series (a series group's id stands for those paths, except with from \"contents\", which moves the group's own row), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {index: where the item landed | contents: the row's slot}",
|
||||
has_doc,
|
||||
move_item
|
||||
),
|
||||
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eyedropper",
|
||||
[],
|
||||
None,
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode, and with `append` its topmost visible fill and stroke rows → {ids}",
|
||||
has_doc,
|
||||
copy_from
|
||||
),
|
||||
@@ -147,7 +147,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Show All Hidden Attributes",
|
||||
["Window", "Appearance"],
|
||||
None,
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
"{ids?|id?, target?} make every hidden fill, stroke and effect (the object's and each item's) of each selected object visible again; errors when nothing is hidden. On a path directly in a graph series (a series group's id stands for those paths and the group), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {ids}",
|
||||
has_doc,
|
||||
show_all_hidden
|
||||
),
|
||||
@@ -165,7 +165,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Appearance",
|
||||
[],
|
||||
None,
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
"{source: id, target: id, copy?: bool} give `target` (a layer, group or object) the appearance (fills, strokes, effects) and transparency (opacity, blend mode, isolation, knockout) of `source`, as dragging a target circle onto another in the Layers panel does; the source is left with a cleared appearance (as appearance.clear) unless `copy` (Alt-drag). Opacity masks stay; placed gradients keep their place relative to each object's bounds. On a path directly in a graph series (a series group's id stands for those paths; as `source`, when the group has no effect, opacity, blend mode, isolation, knockout or style link of its own, the topmost one is read and a move clears them all; as `target` each takes the appearance and the group is cleared, a `source` among them keeps its look, and a `source` that is the group's only path is an error), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores that label's topmost visible fill and stroke rows and object opacity and blend mode for every label of its kind → {source, target}",
|
||||
has_doc,
|
||||
transfer
|
||||
),
|
||||
@@ -183,14 +183,21 @@ pub(crate) struct ActiveItem {
|
||||
impl Session {
|
||||
/// The method returns explicit target parameters and the selected appearance effect list.
|
||||
pub fn appearance_effect_target(&self, params: &Value) -> Option<(Value, &[vectorcraft_doc::Effect])> {
|
||||
let mut ids = appearance_targets(self, params).ok()?;
|
||||
let mut ids = drop_design_art(&self.active()?.doc, appearance_targets(self, params).ok()?);
|
||||
let item = item_target(self, params, "effect.apply").ok()?;
|
||||
let anchor = item.anchor(self, &ids);
|
||||
let node = self.active()?.doc.node(*ids.get(anchor)?)?;
|
||||
// Aligned effects given with a graph design's art first are effects of the art's stack, which stays first; the
|
||||
// Appearance panel's active row is a row of the first selected object's.
|
||||
let of = match item {
|
||||
ItemTarget::Item { explicit: false, .. } => None,
|
||||
_ => design_reference(self, params, "effect.apply").ok()?,
|
||||
};
|
||||
let own = *ids.get(anchor)?;
|
||||
let node = self.active()?.doc.node(of.unwrap_or(own))?;
|
||||
let at = item.effects_item(&node.appearance, "effect.apply").ok()?;
|
||||
let effects = node.appearance.effects_at(at)?;
|
||||
ids.swap(0, anchor);
|
||||
let ids: Vec<u64> = ids.into_iter().map(|id| id.0).collect();
|
||||
let ids: Vec<u64> = with_reference(of, &ids).into_iter().map(|id| id.0).collect();
|
||||
let aligned = match item {
|
||||
ItemTarget::Item { aligned, .. } => aligned,
|
||||
ItemTarget::Top => aligned(params, "effect.apply").ok()?,
|
||||
@@ -253,6 +260,10 @@ pub(crate) fn item_target_at(s: &Session, p: &Value, key: &str, cmd: &str) -> Re
|
||||
.ok_or_else(|| bad(cmd, format!("`{key}` must be an appearance item index (paint order) or null"))),
|
||||
// The active item is a row of the first selected object's own stack.
|
||||
None if p.get("ids").is_some() || p.get("id").is_some() || targets_contents(p)? => Ok(ItemTarget::Top),
|
||||
// A row of a graph design's art in a series stands for nothing: the commands leave that art out.
|
||||
None if s.active().and_then(|st| st.selection.subjects().first().map(|id| super::graph::is_design_art(&st.doc, *id))) == Some(true) => {
|
||||
Ok(ItemTarget::Top)
|
||||
}
|
||||
None => Ok(s.appearance_item().map_or(ItemTarget::Top, |index| ItemTarget::Item { index, explicit: false, aligned: true })),
|
||||
}
|
||||
}
|
||||
@@ -300,6 +311,21 @@ impl ItemTarget {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`ItemTarget::per_target`], with an explicit aligned item a row of the stack of `of` (see [`design_reference`]),
|
||||
/// which is not among `ids`, when there is one: each target edits the item equal to it there, and a target without
|
||||
/// an equal item is left out (`None`).
|
||||
pub(crate) fn per_target_of(self, s: &Session, of: Option<NodeId>, ids: &[NodeId]) -> Vec<Option<ItemTarget>> {
|
||||
let ItemTarget::Item { index, explicit: true, aligned: true } = self else { return self.per_target(s, ids) };
|
||||
let Some(d) = s.active().map(|st| &st.doc) else { return self.per_target(s, ids) };
|
||||
let Some(r) = of.and_then(|of| d.node(of)) else { return self.per_target(s, ids) };
|
||||
ids.iter()
|
||||
.map(|id| {
|
||||
let index = SharedStack::of(&[&*r.appearance, &*d.node(*id)?.appearance]).item_in(index, 1)?;
|
||||
Some(ItemTarget::Item { index, explicit: true, aligned: true })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where among `ids` (the targets, in paint order) the object whose stack this item is a row of
|
||||
/// is: the first selected object (or the compound path holding it) for the active item, which
|
||||
/// need not paint first; the first target otherwise, or when that object is not among them.
|
||||
@@ -384,6 +410,41 @@ pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], id
|
||||
}
|
||||
}
|
||||
|
||||
/// The art of a graph design in a graph series whose stack the aligned rows of `p` (`aligned: true`) are rows of: the
|
||||
/// first of the [`appearance_targets`] when it is such art, which the edit leaves out ([`without_design_art`]). A
|
||||
/// command reads it after its own target checks.
|
||||
pub(crate) fn design_reference(s: &Session, p: &Value, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if !aligned(p, cmd)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(ids.first().copied().filter(|id| super::graph::is_design_art(d, *id)))
|
||||
}
|
||||
|
||||
/// The [`design_reference`] of an edit aimed at `item`: none for the Appearance panel's active row, which is a row of the
|
||||
/// first selected object's stack.
|
||||
pub(crate) fn reference_of(s: &Session, p: &Value, item: ItemTarget, cmd: &str) -> Result<Option<NodeId>> {
|
||||
if matches!(item, ItemTarget::Item { explicit: false, .. }) {
|
||||
return Ok(None);
|
||||
}
|
||||
design_reference(s, p, cmd)
|
||||
}
|
||||
|
||||
/// `ids` after `of` (see [`design_reference`]), when there is one.
|
||||
pub(crate) fn with_reference(of: Option<NodeId>, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
of.into_iter().chain(ids.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// [`items_per_target`] of `ids`, with the aligned rows `idx` taken from the stack of `of` (see [`design_reference`])
|
||||
/// when there is one: a row a target has no equal of is left out of that target.
|
||||
pub(crate) fn rows_per_target(d: &Document, of: Option<NodeId>, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec<Vec<usize>> {
|
||||
match of {
|
||||
Some(of) => items_per_target(d, &with_reference(Some(of), ids), idx, true).into_iter().skip(1).collect(),
|
||||
None => items_per_target(d, ids, idx, aligned),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `target` param asks for the contents of groups and layers (see the module docs).
|
||||
fn targets_contents(p: &Value) -> Result<bool> {
|
||||
match p.get("target") {
|
||||
@@ -424,22 +485,44 @@ const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn a
|
||||
|
||||
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
|
||||
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
|
||||
/// are all such art is refused.
|
||||
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
/// are all such art is refused as an error of `cmd`.
|
||||
pub(crate) fn edit_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
without_design_art(&s.doc()?.doc, ids, "appearance")
|
||||
without_design_art(&s.doc()?.doc, ids, cmd)
|
||||
}
|
||||
|
||||
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
|
||||
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn without_design_art(d: &Document, ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let given = ids.len();
|
||||
ids.retain(|id| !super::graph::is_design_art(d, *id));
|
||||
let ids = drop_design_art(d, ids);
|
||||
if given > 0 && ids.is_empty() {
|
||||
return Err(bad(cmd, DESIGN_ART));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// `ids` without the art of graph designs drawn in graph series, for the paint commands, which leave it out without an
|
||||
/// error.
|
||||
pub(crate) fn drop_design_art(d: &Document, mut ids: Vec<NodeId>) -> Vec<NodeId> {
|
||||
ids.retain(|id| !super::graph::is_design_art(d, *id));
|
||||
ids
|
||||
}
|
||||
|
||||
/// The outermost art of graph designs drawn in graph series inside `roots`: the objects directly in a series group that
|
||||
/// [`super::graph::is_design_art`] accepts.
|
||||
pub(crate) fn design_art_in(d: &Document, roots: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in roots {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
n.walk(&mut |m| {
|
||||
if m.extras().series_index.is_some() {
|
||||
out.extend(m.children().into_iter().flatten().map(|c| c.id).filter(|c| super::graph::is_design_art(d, *c)));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
@@ -476,15 +559,15 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
|
||||
|
||||
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
|
||||
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = edit_targets(s, p)?;
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = edit_targets(s, p, cmd)?;
|
||||
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
|
||||
}
|
||||
|
||||
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
|
||||
/// which can hold effects and a graphic style link of its own.
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let own = edit_targets(s, p)?;
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let own = edit_targets(s, p, cmd)?;
|
||||
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
|
||||
let groups = stood_for(&own, &ids);
|
||||
ids.extend(groups);
|
||||
@@ -498,8 +581,9 @@ pub(crate) fn stood_for(own: &[NodeId], ids: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
/// Clear Appearance on each series group a command gave a whole new appearance through its paths, so the group's own
|
||||
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it.
|
||||
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
|
||||
/// opacity, blend mode, isolation, knockout, effects and style link do not stay on top of it. The graph stops keeping the
|
||||
/// groups' opacity, blend mode, isolation and knockout. Returns whether what a graph keeps changed.
|
||||
pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) -> bool {
|
||||
for id in groups {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
@@ -507,11 +591,12 @@ pub(crate) fn clear_stood_for(d: &mut Document, groups: &[NodeId]) {
|
||||
n.extras_mut().graphic_style = None;
|
||||
}
|
||||
}
|
||||
super::graph::capture_series_object_opacity(d, groups)
|
||||
}
|
||||
|
||||
/// [`whole_targets`] of `cmd`, which needs at least one.
|
||||
fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = whole_targets(s, p)?;
|
||||
let ids = whole_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -520,7 +605,7 @@ fn require_whole_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId
|
||||
|
||||
/// [`row_targets`] of `cmd`, which needs at least one.
|
||||
fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let ids = row_targets(s, p)?;
|
||||
let ids = row_targets(s, p, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select objects or give ids"));
|
||||
}
|
||||
@@ -534,16 +619,23 @@ fn require_targets(s: &Session, p: &Value, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
/// ([`capture_series_changes`], [`super::graph::capture_label_changes`]). Nothing targeted is not
|
||||
/// an edit, and when `f` leaves every target as it was, the document and its undo history stay as
|
||||
/// they are.
|
||||
///
|
||||
/// With `of` (see [`reference_of`]), an explicit aligned `item` is a row of the stack of `of`, which
|
||||
/// is not among `ids`: it must be there and of the edited kind, each target edits the row equal to
|
||||
/// it, a target without one is left as it is, and no target with one is an error. Returns the
|
||||
/// targets `f` was aimed at, in the order of `ids`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn edit_items(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
edit_items_then(s, ids, item, cmd, label, fill, f, |before, d, edited| {
|
||||
) -> Result<Vec<NodeId>> {
|
||||
edit_items_then(s, ids, item, of, cmd, label, fill, f, |before, d, edited| {
|
||||
let series = capture_series_changes(before, d, edited);
|
||||
// The rows `f` edited are kept by `edit_items_then`.
|
||||
let labels = super::graph::capture_label_changes(before, d, edited, false);
|
||||
@@ -560,17 +652,29 @@ pub(crate) fn edit_items_then(
|
||||
s: &mut Session,
|
||||
ids: &[NodeId],
|
||||
item: ItemTarget,
|
||||
of: Option<NodeId>,
|
||||
cmd: &str,
|
||||
label: &str,
|
||||
fill: bool,
|
||||
mut f: impl FnMut(&mut Node, Option<usize>) -> Result<()>,
|
||||
mut after: impl FnMut(&vectorcraft_doc::Document, &mut vectorcraft_doc::Document, &[NodeId]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
) -> Result<Vec<NodeId>> {
|
||||
let art = of.and_then(|of| s.doc().ok()?.doc.node(of).map(|n| n.appearance.clone()));
|
||||
let per = match (item, art) {
|
||||
// Checked even when the art is the only object given, which leaves `ids` empty.
|
||||
(ItemTarget::Item { index, explicit: true, aligned: true }, Some(art)) => {
|
||||
item.resolve(&art, fill, cmd)?;
|
||||
let per = item.per_target_of(s, of, ids);
|
||||
if per.iter().all(Option::is_none) {
|
||||
return Err(bad(cmd, format!("no appearance item {index}")));
|
||||
}
|
||||
per
|
||||
}
|
||||
_ if ids.is_empty() => return Ok(Vec::new()),
|
||||
_ => item.per_target(s, ids),
|
||||
};
|
||||
let aimed: Vec<NodeId> = ids.iter().zip(&per).filter(|(_, item)| item.is_some()).map(|(id, _)| *id).collect();
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = item.per_target(s, ids);
|
||||
super::overprint::edit_counted(s, label, |d| {
|
||||
let mut edited = Vec::new();
|
||||
// The objects whose rows `f` edited: on type, no row means its characters.
|
||||
@@ -589,7 +693,13 @@ pub(crate) fn edit_items_then(
|
||||
let labels = super::graph::capture_label_rows(d, &rows);
|
||||
Ok(count_changed(d, &before, &edited) + usize::from(more || labels))
|
||||
})?;
|
||||
Ok(())
|
||||
Ok(aimed)
|
||||
}
|
||||
|
||||
/// The first of `ids` that [`edit_items`] aimed at `item` with `of` changes, and the item it changes there. Read it
|
||||
/// before the edit: once edited, a row that was equal to a row of the art of `of` no longer is.
|
||||
pub(crate) fn first_edited(s: &Session, item: ItemTarget, of: Option<NodeId>, ids: &[NodeId]) -> Option<(NodeId, ItemTarget)> {
|
||||
ids.iter().zip(item.per_target_of(s, of, ids)).find_map(|(id, it)| Some((*id, it?)))
|
||||
}
|
||||
|
||||
/// How many of `ids` differ in `d` from `before`.
|
||||
@@ -598,17 +708,23 @@ pub(crate) fn count_changed(d: &vectorcraft_doc::Document, before: &vectorcraft_
|
||||
}
|
||||
|
||||
/// Whether an edit aimed at `item` changes a stroke: the `stroke` param, else the kind of the
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`]), else `default`. A `stroke` other than true, false or
|
||||
/// null is an error of command `cmd`.
|
||||
/// targeted item (on the object whose row it is, see [`ItemTarget::anchor`] and [`reference_of`]), else `default`. A `stroke` other than
|
||||
/// true, false or null is an error of command `cmd`.
|
||||
pub(crate) fn edits_stroke(s: &Session, p: &Value, item: ItemTarget, default: bool, cmd: &str) -> Result<bool> {
|
||||
check_switches(p, &["stroke"], cmd)?;
|
||||
if let Some(b) = p.get("stroke").and_then(Value::as_bool) {
|
||||
return Ok(b);
|
||||
}
|
||||
let ItemTarget::Item { index, .. } = item else { return Ok(default) };
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
Ok(ids.get(item.anchor(s, &ids)).and_then(|id| d.node(*id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
let holder = match reference_of(s, p, item, cmd)? {
|
||||
Some(of) => Some(of),
|
||||
None => {
|
||||
let ids = drop_design_art(d, appearance_targets(s, p)?);
|
||||
ids.get(item.anchor(s, &ids)).copied()
|
||||
}
|
||||
};
|
||||
Ok(holder.and_then(|id| d.node(id)?.appearance.items.get(index)).map_or(default, |it| !it.is_fill()))
|
||||
}
|
||||
|
||||
/// The whole number of 0 or more that `key` holds, read with [`u64_req`] and [`index`].
|
||||
@@ -943,7 +1059,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(src.opacity, src.blend, src.isolate, src.knockout, src.knockout_shape);
|
||||
super::object::snap_if_aligned(to);
|
||||
}
|
||||
clear_stood_for(d, &group);
|
||||
let forgot = clear_stood_for(d, &group);
|
||||
for id in &cleared {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
clear(n);
|
||||
@@ -961,7 +1077,7 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// The targets last: on two labels of one kind, the target's rows are the ones the kind keeps.
|
||||
let labels = super::graph::capture_label_rows(d, &changed);
|
||||
let all: Vec<NodeId> = from.iter().chain(&targets).chain(&group).copied().collect();
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels))
|
||||
Ok(count_changed(d, &before, &all) + usize::from(kept || painted || object || labels || forgot))
|
||||
})?;
|
||||
s.active_appearance_item = None;
|
||||
Ok(json!({ "source": source.0, "target": target.0 }))
|
||||
@@ -1030,7 +1146,7 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["weight", "opacity"], "appearance.setItem")?;
|
||||
check_switches(p, &["visible"], "appearance.setItem")?;
|
||||
let paint = paint_from(s, p)?;
|
||||
let ids = row_targets(s, p)?;
|
||||
let ids = row_targets(s, p, "appearance.setItem")?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad("appearance.setItem", "select objects or give ids"));
|
||||
}
|
||||
@@ -1038,7 +1154,8 @@ fn set_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When every object comes out as it was (for example, when none has item `index`), the document
|
||||
// and its undo history stay as they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
let of = design_reference(s, p, "appearance.setItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &[idx], aligned(p, "appearance.setItem")?);
|
||||
super::overprint::edit_counted(s, "Appearance", |d| {
|
||||
let mut edited = Vec::new();
|
||||
for (id, at) in ids.iter().zip(&per) {
|
||||
@@ -1125,7 +1242,8 @@ fn remove_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When no object has an item at any of the indices, the document and its undo history stay as
|
||||
// they are.
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
let of = design_reference(s, p, "appearance.removeItem")?;
|
||||
let per = rows_per_target(&before, of, &ids, &idx, aligned(p, "appearance.removeItem")?);
|
||||
super::overprint::edit_counted(s, "Remove Item", |d| {
|
||||
for (id, idx) in ids.iter().zip(&per) {
|
||||
if let Some(n) = d.node_mut(*id) {
|
||||
@@ -1166,12 +1284,19 @@ fn duplicate_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut first_at = None;
|
||||
let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied());
|
||||
let mut active_at = None;
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object.
|
||||
if aligned(p, C)? && to.is_some() && shared_stack(&s.doc()?.doc, &ids).is_some() {
|
||||
// Aligned rows of a mixed selection are copied right above themselves in each object. Rows of a graph design's art,
|
||||
// which is left out, go to `to` in an object whose stack is the same as the art's.
|
||||
let of = design_reference(s, p, C)?;
|
||||
if aligned(p, C)?
|
||||
&& to.is_some()
|
||||
&& (shared_stack(&s.doc()?.doc, &ids).is_some() || (of.is_some() && appearances_differ(&s.doc()?.doc, &with_reference(of, &ids))))
|
||||
{
|
||||
return Err(bad(C, "`to` takes the rows of one object's stack, not aligned rows"));
|
||||
}
|
||||
let before = s.doc()?.doc.clone();
|
||||
let per = items_per_target(&before, &ids, &idx, aligned(p, C)?);
|
||||
// With `to`, the art's stack is the same as the object's, so its rows are the object's, each of which must exist.
|
||||
let per =
|
||||
if to.is_some() { items_per_target(&before, &ids, &idx, aligned(p, C)?) } else { rows_per_target(&before, of, &ids, &idx, aligned(p, C)?) };
|
||||
s.edit("Duplicate Item", |d, _| {
|
||||
let mut any = false;
|
||||
// Copies that became the topmost visible row of their kind: the series stores their paint even when the object
|
||||
@@ -1278,15 +1403,19 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let aligned = aligned(p, C)?;
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
// A graph series group's own Contents row, not its paths, which have none.
|
||||
let ids = edit_targets(s, p)?;
|
||||
let ids = edit_targets(s, p, C)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
}
|
||||
// The Contents row's place counts the rows below it, which isn't one place in several different stacks either.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
return move_contents(s, &ids, to);
|
||||
}
|
||||
let ids = require_targets(s, p, C)?;
|
||||
// Where an aligned row would go in each of several different stacks isn't one place.
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &ids) {
|
||||
if aligned && appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &ids)) {
|
||||
return Err(bad(C, "rows of objects whose appearances differ can't be reordered together"));
|
||||
}
|
||||
if p.get("indices").is_some() {
|
||||
|
||||
@@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
|
||||
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
|
||||
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
@@ -397,6 +398,59 @@ fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brus
|
||||
Brush { name: name.into(), kind }
|
||||
}
|
||||
|
||||
/// Tech Circuit: original conductor geometry, drawn as filled paths so widths and chamfers
|
||||
/// survive brush warping. Pattern tiles meet at x = 0 and 24 with identical lead cross-sections.
|
||||
fn tech_circuit() -> BrushLibrary {
|
||||
let pad = |x: f64| {
|
||||
black(polygon(&[
|
||||
(x - 4.0, -2.0),
|
||||
(x - 2.0, -4.0),
|
||||
(x + 2.0, -4.0),
|
||||
(x + 4.0, -2.0),
|
||||
(x + 4.0, 2.0),
|
||||
(x + 2.0, 4.0),
|
||||
(x - 2.0, 4.0),
|
||||
(x - 4.0, 2.0),
|
||||
]))
|
||||
};
|
||||
// 45-degree jogs lift the conductor to a parallel run and bring it back.
|
||||
let trace = group(vec![
|
||||
black(polygon(&[
|
||||
(4.0, -1.0),
|
||||
(23.0, -1.0),
|
||||
(33.0, -11.0),
|
||||
(61.0, -11.0),
|
||||
(71.0, -1.0),
|
||||
(96.0, -1.0),
|
||||
(96.0, 1.0),
|
||||
(70.0, 1.0),
|
||||
(60.0, -9.0),
|
||||
(34.0, -9.0),
|
||||
(24.0, 1.0),
|
||||
(4.0, 1.0),
|
||||
])),
|
||||
pad(4.0),
|
||||
pad(96.0),
|
||||
]);
|
||||
let bus = group([-4.0, 0.0, 4.0].into_iter().map(|y| black(shapes::rectangle(Rect::new(0.0, y - 0.75, 24.0, y + 0.75)))).collect());
|
||||
let terminals = group(vec![
|
||||
// Overlap the ring's rim without filling the test point's hole.
|
||||
black(shapes::rectangle(Rect::new(0.0, -0.6, 15.5, 0.6))),
|
||||
black(shapes::rectangle(Rect::new(18.5, -0.6, 24.0, 0.6))),
|
||||
pad(6.0),
|
||||
ring(Point::new(17.0, 0.0), 3.0, 1.4),
|
||||
]);
|
||||
built(
|
||||
"Tech Circuit",
|
||||
Document::new(100.0, 100.0),
|
||||
vec![
|
||||
art("Circuit Trace", trace, Colorization::Tints),
|
||||
border("Bus Lines", bus, None, PatternFit::Stretch),
|
||||
border("Terminal Nodes", terminals, None, PatternFit::Stretch),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/// An invisible rectangle that fixes a tile's width.
|
||||
fn spacer(r: Rect) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
|
||||
|
||||
@@ -14,7 +14,7 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::appearance::{AppearanceItem, FillLayer, LineCap, LineJoin, StrokeLayer};
|
||||
use vectorcraft_doc::{Appearance, Document, GapOptions, GapSize, LiveShape, Node, NodeId, NodeKind, Selection, TraceView};
|
||||
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Shape Builder",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
|
||||
"{ids?|id?: [id…] (default: selection), points: [[x,y]…] (drag path; one point = click; may be left out with rect), rect?: [x, y, width, height] (Shift-drag marquee from where the drag started, x and y, to x+width and y+height; width and height may be negative: touches every region whose outline crosses the rectangle or has an anchor inside it and the region holding the whole rectangle, the region under x, y comes first and the one under the opposite corner comes next; with points, it also touches the regions along them; for pickColorFrom, x, y is the drag's first point and the opposite corner is its last), erase?: bool (erase mode, Alt: deletes the regions touched, and the pieces of open paths that cut regions and the edges (outline pieces between the points where paths meet; see shapeBuilder.regions) within tolerance, except that a point in a region no more than twice the tolerance across there touches the region; a deleted edge opens its path there, and edges bounding a deleted region go with it; what is left of each path keeps its look, with gradients fitted to its bounds kept where they were on it, its name, opacity mask and attributes, and its fill rule unless merged regions shaped it), splitStroke?: false (In Merge Mode, Clicking Stroke Splits the Path; not with erase or rect: when the one point of a click is within tolerance of a stroke, the path that stroke is on splits in two instead of a merge: the path keeps the rest of it, and a copy of the path holding the run of it from the anchor or crossing point before the click to the one after it, in the path's direction, goes directly above it; both keep the path's gradients where they were on it; the other objects stay as they are; with pickColorFrom \"swatches\" or fill, the run's stroke takes that paint; a path in a Live Paint group or a Shaper Group does not split, and nor does a path the run is all of, such as a lone line, or all but 0.05 pt or less of (a ten-thousandth of the larger side of a path over 500 pt)), tolerance?: pt (2, erase or splitStroke), gap?: pt (0–72; 0: Gap Detection off), openFilledAsClosed?: true (Consider Open Filled Paths as Closed: a filled open path bounds a region as if an invisible edge closed it, where filled means any fill row is shown, painted and above 0% opacity, whichever row is on top; false: it cuts the regions it crosses like an unfilled one), pickColorFrom?: \"artwork\" (default: the merged shape takes the look of the front-most object under the first point, else under the last point, else of the front-most object) | \"swatches\" (the current fill, with the rest of the look of the front-most object over the first region the drag touches that an object covers, else of the front-most object), fill?: \"#rrggbb\" | {color|swatch|gradient|none} (overrides pickColorFrom)} replaces the paths it uses where they are; other selected objects (type, hidden or locked objects, clipping paths) stay, and a group goes only when it is left empty → {ids (selected after: each selected object still there, or what took its place), merged, regions, lines, edges (counts deleted, merged or split), split?: id (the run split off, after a split)}; after a split, ids are the roots, with the rest and the run in place of the path when it was one",
|
||||
has_selection_or_ids,
|
||||
sb_merge
|
||||
),
|
||||
@@ -72,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Live Paint"],
|
||||
Some("Cmd+Alt+X"),
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with its front-most covering source's fill; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
"{ids?|id?} build a Live Paint group from the selected paths (paths, compound paths and groups of them; type, images and other objects are refused, nothing changes); each covered face starts with the fill rows that draw (shown, with paint and an opacity above 0) of its front-most covering source that has one and an opacity above 0, and each edge with the stroke rows that draw (also a weight above 0) of its source, in order with their settings and with that source's opacity and blending mode (on a path cut into several edges, dashes go on along the path with the lengths set, without the fit of dashes aligned to corners and path ends, arrowheads stay at its own ends, and a width profile or brush stays only on an edge that runs the whole path); a face or edge given no such row has one unpainted row; with a Live Paint group among them, add the others to it as livePaint.merge does; a Live Paint group alone has nothing to add, so it is selected and nothing changes (no undo step) → {id, faces, edges}",
|
||||
has_selection_or_ids,
|
||||
lp_make
|
||||
),
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), scope?: \"one\" (default: the face alone) | \"connected\" (a double-click: also each face reached across edges that are hidden or draw no stroke, as a flood from the face; a stroked edge, a hidden face or a Gap Detection gap stops it) | \"samePaint\" (a triple-click: also every face of the group whose fill is match; \"connected\" and \"samePaint\" are refused with points), match?: paint (as the document stores it, the `fill` of a face's appearance; scope samePaint only; default: the face's fill), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces; when every face it reaches already has the paint, nothing changes (no undo step, and the recent colors stay as they are) → {group, face, count (faces reached)}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket (Stroke)",
|
||||
[],
|
||||
None,
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point; when it already has the paint and the width, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge}",
|
||||
"{group: id, point: [x,y], color?|swatch?|none? (default: current stroke), width?: pt (default: current weight), tolerance?: pt (4), scope?: \"one\" (default: the edge alone) | \"connected\" (a double-click: also each edge joined to it, end to end, through edges that draw with stroke paint match) | \"samePaint\" (a triple-click: also every edge of the group that draws with stroke paint match), match?: paint (as the document stores it; scope connected or samePaint only; default: the stroke paint the edge draws with; an edge draws with the paint of its topmost stroke that is shown, with paint, above 0 pt and not fully transparent, and with none when the edge is fully transparent or has no such stroke), tint?: 0..100, keepModel?: bool (both as paint.setFill)} paint the edge nearest point, skipping hidden edges: each edge reached takes the paint and width in its topmost stroke that is shown, or in a new stroke above the others when it has none; when every edge it reaches already has the paint and the width there, nothing changes (no undo step, and the recent colors stay as they are) → {group, edge, count (edges reached)}",
|
||||
has_doc,
|
||||
lp_stroke_edge
|
||||
),
|
||||
@@ -414,22 +414,274 @@ fn source_nodes(n: &Node) -> Vec<Arc<Node>> {
|
||||
if is_live_paint(n) { b::sources(n).and_then(|g| g.children().cloned()).unwrap_or_default() } else { vec![Arc::new(n.clone())] }
|
||||
}
|
||||
|
||||
/// Does appearance row `i` draw: it is shown, has paint and an opacity above 0, and a stroke also
|
||||
/// has a weight above 0?
|
||||
fn row_draws(i: &AppearanceItem) -> bool {
|
||||
match i {
|
||||
AppearanceItem::Fill(f) => f.visible && !f.paint.is_none() && f.opacity > 0.0,
|
||||
AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none() && s.opacity > 0.0 && s.width > 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a source path gives the faces and edges made from it.
|
||||
struct SourceStyle {
|
||||
/// The fill rows that draw, in paint order (none when the path's opacity is 0).
|
||||
fills: Vec<AppearanceItem>,
|
||||
/// The stroke rows that draw, in paint order (none when the path's opacity is 0).
|
||||
strokes: Vec<AppearanceItem>,
|
||||
/// The top stroke's weight, for an edge given no stroke that draws.
|
||||
width: f64,
|
||||
opacity: f32,
|
||||
blend: BlendMode,
|
||||
}
|
||||
|
||||
impl SourceStyle {
|
||||
/// The style of source path `n`: its rows keep their order and settings, gradients fitted to
|
||||
/// its bounds keep that fit, and the strokes' pen pressure, tilt, bearing and rotation stay
|
||||
/// with the path.
|
||||
fn of(n: &Node) -> Self {
|
||||
let mut a = (*n.appearance).clone().without_pressure();
|
||||
if a.has_unplaced_gradient()
|
||||
&& let Some(bounds) = n.geometric_bounds()
|
||||
{
|
||||
a.pin_gradients(bounds);
|
||||
}
|
||||
let width = a.stroke().map_or(1.0, |s| s.width);
|
||||
let (mut fills, mut strokes) = (vec![], vec![]);
|
||||
if n.opacity > 0.0 {
|
||||
for i in a.items.into_iter().filter(row_draws) {
|
||||
if i.is_fill() { fills.push(i) } else { strokes.push(i) }
|
||||
}
|
||||
}
|
||||
Self { fills, strokes, width, opacity: n.opacity, blend: n.blend }
|
||||
}
|
||||
|
||||
/// Give part `n` the rows `rows` of this source with its opacity and blending mode; with no
|
||||
/// rows, `n` keeps the unpainted row it has.
|
||||
fn paint(&self, n: &mut Node, rows: &[AppearanceItem]) {
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
n.appearance = Appearance { items: rows.to_vec(), ..Default::default() }.into();
|
||||
n.opacity = self.opacity;
|
||||
n.blend = self.blend;
|
||||
}
|
||||
}
|
||||
|
||||
/// How far, in points, a place on an edge may be from its source path and still be on it.
|
||||
const ON_SOURCE: f64 = 0.05;
|
||||
|
||||
/// Does stroke row `i` have settings that depend on where along its path a piece of it lies or
|
||||
/// which way it runs: dashes, arrowheads, a width profile, a brush, or a gradient along or across
|
||||
/// the stroke?
|
||||
fn depends_on_place(i: &AppearanceItem) -> bool {
|
||||
matches!(i, AppearanceItem::Stroke(s) if s.dash.is_some() || s.start_arrow.is_some() || s.end_arrow.is_some() || s.profile.is_some() || s.brush.is_some() || s.gradient_mode != vectorcraft_doc::StrokeGradientMode::Within)
|
||||
}
|
||||
|
||||
/// One subpath's segments with the length along it where each starts, then its whole length, and
|
||||
/// a grid of square cells listing the segments whose bounds, grown by [`ON_SOURCE`], reach into
|
||||
/// each cell, so finding the segments near a point does not look at every segment.
|
||||
struct Track {
|
||||
segs: Vec<kurbo::PathSeg>,
|
||||
at: Vec<f64>,
|
||||
closed: bool,
|
||||
cell: f64,
|
||||
grid: HashMap<(i64, i64), Vec<usize>>,
|
||||
/// Segments that reach into more than [`Track::MAX_CELLS`] cells, or that come after the grid
|
||||
/// holds [`Track::CELLS_PER_SEGMENT`] entries per segment, looked at for every point.
|
||||
wide: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
const ACCURACY: f64 = 1e-4;
|
||||
const MAX_CELLS: i64 = 4096;
|
||||
const CELLS_PER_SEGMENT: usize = 16;
|
||||
|
||||
fn new(sp: &SubPath) -> Self {
|
||||
use kurbo::{ParamCurveArclen, Shape as _};
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
sp.to_bezpath_into(&mut bp);
|
||||
let segs: Vec<kurbo::PathSeg> = bp.segments().collect();
|
||||
let mut at = Vec::with_capacity(segs.len() + 1);
|
||||
let mut len = 0.0;
|
||||
for s in &segs {
|
||||
at.push(len);
|
||||
len += s.arclen(Self::ACCURACY);
|
||||
}
|
||||
at.push(len);
|
||||
let boxes: Vec<kurbo::Rect> = segs.iter().map(|s| s.bounding_box().inflate(ON_SOURCE, ON_SOURCE)).collect();
|
||||
// Cells about as wide as an average segment's bounds.
|
||||
let mean = boxes.iter().map(|b| b.width().max(b.height())).sum::<f64>() / boxes.len().max(1) as f64;
|
||||
let cell = if mean.is_finite() { mean.max(4.0 * ON_SOURCE) } else { 4.0 * ON_SOURCE };
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
|
||||
let mut wide = vec![];
|
||||
// The grid holds at most this many entries in all.
|
||||
let mut budget = boxes.len().saturating_mul(Self::CELLS_PER_SEGMENT);
|
||||
for (k, b) in boxes.iter().enumerate() {
|
||||
let (x0, y0) = Self::cell_of(Point::new(b.x0, b.y0), cell);
|
||||
let (x1, y1) = Self::cell_of(Point::new(b.x1, b.y1), cell);
|
||||
let cells = x1.saturating_sub(x0).saturating_add(1).saturating_mul(y1.saturating_sub(y0).saturating_add(1));
|
||||
let Some(cells) = usize::try_from(cells).ok().filter(|&c| cells <= Self::MAX_CELLS && c <= budget) else {
|
||||
wide.push(k);
|
||||
continue;
|
||||
};
|
||||
budget -= cells;
|
||||
for x in x0..=x1 {
|
||||
for y in y0..=y1 {
|
||||
grid.entry((x, y)).or_default().push(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self { segs, at, closed: sp.closed, cell, grid, wide }
|
||||
}
|
||||
|
||||
fn cell_of(p: Point, cell: f64) -> (i64, i64) {
|
||||
((p.x / cell).floor() as i64, (p.y / cell).floor() as i64)
|
||||
}
|
||||
|
||||
fn len(&self) -> f64 {
|
||||
self.at.last().copied().unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// The lengths along the subpath to each of its segments' places nearest `p` that are within
|
||||
/// [`ON_SOURCE`] of it (more than one where the subpath passes `p` again).
|
||||
fn places(&self, p: Point) -> Vec<f64> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
|
||||
let near = self.grid.get(&Self::cell_of(p, self.cell)).map(Vec::as_slice).unwrap_or_default();
|
||||
let mut out = vec![];
|
||||
for &k in near.iter().chain(&self.wide) {
|
||||
let Some(s) = self.segs.get(k) else { continue };
|
||||
let n = s.nearest(p, 1e-9);
|
||||
if n.distance_sq <= ON_SOURCE * ON_SOURCE {
|
||||
out.push(self.at.get(k).copied().unwrap_or(0.0) + s.subsegment(0.0..n.t).arclen(Self::ACCURACY));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The signed length from `a` to `b` along the subpath (the shorter way round a closed one).
|
||||
fn step(&self, a: f64, b: f64) -> f64 {
|
||||
let (d, len) = (b - a, self.len());
|
||||
if self.closed && len > 0.0 { d - len * (d / len).round() } else { d }
|
||||
}
|
||||
|
||||
/// Of `places`, the one nearest along the subpath to `target`.
|
||||
fn nearest(&self, places: &[f64], target: f64) -> Option<f64> {
|
||||
places.iter().copied().min_by(|x, y| self.step(*x, target).abs().total_cmp(&self.step(*y, target).abs()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where edge `edge` runs along its source path, whose subpaths' tracks are `tracks`: the length
|
||||
/// along the source subpath to the edge's start, whether the edge starts at that subpath's start and
|
||||
/// ends at its end (an open subpath), and whether it runs the whole subpath. The middle of the
|
||||
/// edge's first segment places it, and its ends are taken where they lie that far along the source,
|
||||
/// so a path that passes a point twice is told apart. An edge that runs against the direction of its
|
||||
/// source is reversed first, and a closed edge as long as its closed source is started at the anchor
|
||||
/// where its source starts (one with no anchor there, or a shorter loop cut from a source that
|
||||
/// crosses itself, does not count as running the whole subpath). `None` when the edge is
|
||||
/// not a single piece found on the source.
|
||||
fn edge_run(tracks: &[Track], edge: &mut PathData) -> Option<(f64, bool, bool, bool)> {
|
||||
use kurbo::{ParamCurve, ParamCurveArclen};
|
||||
let [sp] = edge.subpaths.as_slice() else { return None };
|
||||
if sp.segment_count() == 0 {
|
||||
return None;
|
||||
}
|
||||
let (a, z) = (sp.anchors.first()?.p, if sp.closed { sp.anchors.first()?.p } else { sp.anchors.last()?.p });
|
||||
let first = sp.segment(0);
|
||||
let mid = first.eval(0.5);
|
||||
let half = first.subsegment(0.0..0.5).arclen(Track::ACCURACY);
|
||||
let length = sp.anchor_arc_positions().last().copied().unwrap_or(0.0);
|
||||
let edge_closed = sp.closed;
|
||||
// (how far off the fit is, track, start, end, runs forward) for the subpath that fits best.
|
||||
let mut found: Option<(f64, &Track, f64, f64, bool)> = None;
|
||||
for track in tracks {
|
||||
// The start lies half the first segment before its middle along the source, or after it
|
||||
// when the edge runs the other way: take the place and way that fit best.
|
||||
let starts_at = track.places(a);
|
||||
let mut best: Option<(f64, f64, bool)> = None;
|
||||
for pm in track.places(mid) {
|
||||
for forward in [true, false] {
|
||||
let Some(pa) = track.nearest(&starts_at, if forward { pm - half } else { pm + half }) else { continue };
|
||||
let miss = (if forward { track.step(pa, pm) } else { track.step(pm, pa) } - half).abs();
|
||||
if best.is_none_or(|(m, _, _)| miss < m) {
|
||||
best = Some((miss, pa, forward));
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some((miss, pa, forward)) = best else { continue };
|
||||
let target = if forward { pa + length } else { pa - length };
|
||||
let Some(pz) = track.nearest(&track.places(z), target) else { continue };
|
||||
let miss = miss + track.step(pz, target).abs();
|
||||
if found.is_none_or(|(m, ..)| miss < m) {
|
||||
found = Some((miss, track, pa, pz, forward));
|
||||
}
|
||||
}
|
||||
let (_, track, pa, pz, forward) = found?;
|
||||
let (from, to) = if forward { (pa, pz) } else { (pz, pa) };
|
||||
if !forward {
|
||||
edge.reverse();
|
||||
}
|
||||
let open = !track.closed;
|
||||
let starts = open && from <= ON_SOURCE;
|
||||
let ends = open && to >= track.len() - ON_SOURCE;
|
||||
if open {
|
||||
return Some((from, starts, ends, starts && ends));
|
||||
}
|
||||
// A closed edge runs the whole closed subpath, from the anchor the planar map starts it at.
|
||||
// Start it at the anchor where the source starts, so settings that follow the path begin there.
|
||||
let start = track.segs.first().map(|s| s.start())?;
|
||||
let moved = edge_closed
|
||||
&& (length - track.len()).abs() <= ON_SOURCE.max(track.len() * 1e-4)
|
||||
&& edge.subpaths.first_mut().is_some_and(|sp| match sp.anchors.iter().position(|a| a.p.distance(start) <= ON_SOURCE) {
|
||||
Some(k) => {
|
||||
sp.anchors.rotate_left(k);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
});
|
||||
Some((if moved { 0.0 } else { from }, false, false, moved))
|
||||
}
|
||||
|
||||
/// Fit stroke row `row` of a source path to an edge cut from it, which runs as [`edge_run`] says
|
||||
/// (`None`: not known): its dashes go on from where the edge starts along the source, with the
|
||||
/// lengths set and without the fit of dashes aligned to corners and path ends, its arrowheads stay only at the source's own ends, and its width profile and brush, which spread
|
||||
/// over the whole path, stay only on an edge that runs the whole path.
|
||||
fn fit_to_edge(row: &mut AppearanceItem, run: Option<(f64, bool, bool, bool)>) {
|
||||
let AppearanceItem::Stroke(s) = row else { return };
|
||||
let (from, starts, ends, whole) = run.unwrap_or((0.0, false, false, false));
|
||||
if !whole {
|
||||
if let Some(d) = &mut s.dash
|
||||
&& run.is_some()
|
||||
{
|
||||
d.offset += from;
|
||||
d.align_corners = false;
|
||||
}
|
||||
s.profile = None;
|
||||
s.brush = None;
|
||||
}
|
||||
if !starts {
|
||||
s.start_arrow = None;
|
||||
}
|
||||
if !ends {
|
||||
s.end_arrow = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The planar map's inputs from `sources` (paths and compound paths, back → front), with the
|
||||
/// fill, stroke and stroke width of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<(Paint, Paint, f64)>) {
|
||||
/// style of each.
|
||||
fn source_shapes(sources: &[Arc<Node>]) -> (Vec<po::Shape>, Vec<SourceStyle>) {
|
||||
let mut lv = vec![];
|
||||
for n in sources {
|
||||
b::leaf_shapes(n, &mut lv);
|
||||
}
|
||||
let mut shapes = vec![];
|
||||
let mut styles: Vec<(Paint, Paint, f64)> = vec![];
|
||||
let mut styles: Vec<SourceStyle> = vec![];
|
||||
for l in lv {
|
||||
if let Some((path, rule)) = b::node_outline(l)
|
||||
&& !path.is_empty()
|
||||
{
|
||||
shapes.push(po::Shape::new(path, rule, styles.len() as u64));
|
||||
let a = &l.appearance;
|
||||
styles.push((a.fill_paint(), a.stroke_paint(), a.stroke().map(|s| s.width).unwrap_or(1.0)));
|
||||
styles.push(SourceStyle::of(l));
|
||||
}
|
||||
}
|
||||
(shapes, styles)
|
||||
@@ -462,17 +714,35 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
let nfaces = regs.len();
|
||||
for r in regs {
|
||||
let id = d.alloc_id();
|
||||
let fill = r.top().and_then(|t| styles.get(t)).map_or(Paint::None, |s| s.0.clone());
|
||||
let mut n = Node::path(id, r.path, fill_only(fill));
|
||||
let mut n = Node::path(id, r.path, fill_only(Paint::None));
|
||||
n.name = Some(FACE_NAME.into());
|
||||
// The front-most covering source with a fill that draws gives the face its fill rows.
|
||||
if let Some(s) = r.sources.iter().rev().filter_map(|&t| styles.get(t)).find(|s| !s.fills.is_empty()) {
|
||||
s.paint(&mut n, &s.fills);
|
||||
}
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
let nedges = edges.len();
|
||||
// The tracks of the sources whose edges need them, measured once each.
|
||||
let mut tracks: HashMap<usize, Vec<Track>> = HashMap::new();
|
||||
for e in edges {
|
||||
let Some((_, stroke, w)) = styles.get(e.key as usize) else { continue };
|
||||
let key = e.key as usize;
|
||||
let Some(s) = styles.get(key) else { continue };
|
||||
let mut path = e.path;
|
||||
let mut rows = s.strokes.clone();
|
||||
if rows.iter().any(depends_on_place) {
|
||||
let source = tracks
|
||||
.entry(key)
|
||||
.or_insert_with(|| shapes.get(key).map(|src| src.path.subpaths.iter().map(Track::new).collect()).unwrap_or_default());
|
||||
let run = edge_run(source, &mut path);
|
||||
for r in &mut rows {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, e.path, stroke_only(stroke.clone(), *w));
|
||||
let mut n = Node::path(id, path, stroke_only(Paint::None, s.width));
|
||||
n.name = Some(EDGE_NAME.into());
|
||||
s.paint(&mut n, &rows);
|
||||
children.push(Arc::new(n));
|
||||
}
|
||||
Ok((children, nfaces, nedges))
|
||||
@@ -481,8 +751,9 @@ fn build_children(d: &mut Document, sources: Vec<Arc<Node>>, max_gap: Option<f64
|
||||
/// Give the faces and edges of `g`, a Live Paint group made again from the sources of `old`, the
|
||||
/// look of `old`'s face or edge where they lie: each face takes everything but the outline (its
|
||||
/// appearance, none included, its transparency and the rest) of the old face its inside point is
|
||||
/// in, and each edge that of the old edge its middle lies on. Faces and edges where `old` had none
|
||||
/// keep the paint of their sources.
|
||||
/// in, and each edge that of the old edge its middle lies on, with the old edge's stroke rows fitted
|
||||
/// to the part of it the new edge runs, as [`fit_to_edge`] fits a source's rows. Faces and edges
|
||||
/// where `old` had none keep the paint of their sources.
|
||||
fn repaint_from(g: &mut Node, old: &Node) {
|
||||
/// How far an edge's middle may be from the old edge it lies on.
|
||||
const ON_EDGE: f64 = 1e-3;
|
||||
@@ -505,7 +776,30 @@ fn repaint_from(g: &mut Node, old: &Node) {
|
||||
n.id = c.id;
|
||||
n.kind = c.kind.clone();
|
||||
n.bbox_angle = c.bbox_angle;
|
||||
// An edge cut from the old one takes the old edge's dashes, arrowheads, width profile
|
||||
// and brush as they fall on its part of the old edge.
|
||||
if c.name.as_deref() == Some(EDGE_NAME)
|
||||
&& let Some(old_path) = was.path_data()
|
||||
{
|
||||
fit_to_old_edge(&mut n, old_path);
|
||||
}
|
||||
*c = Arc::new(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fit the stroke rows of edge `n`, which it took from an old edge whose outline is `old`, to the
|
||||
/// part of the old edge that `n` runs, as [`fit_to_edge`] fits a source's rows to an edge cut from
|
||||
/// it; `n` is reversed when it runs against the old edge.
|
||||
fn fit_to_old_edge(n: &mut Node, old: &PathData) {
|
||||
if !n.appearance.items.iter().any(depends_on_place) {
|
||||
return;
|
||||
}
|
||||
let tracks: Vec<Track> = old.subpaths.iter().map(Track::new).collect();
|
||||
let run = n.path_data_mut().and_then(|path| edge_run(&tracks, path));
|
||||
let mut a = (*n.appearance).clone();
|
||||
for r in &mut a.items {
|
||||
fit_to_edge(r, run);
|
||||
}
|
||||
n.appearance = a.into();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::{
|
||||
Appearance, AppearanceItem, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json,
|
||||
is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes,
|
||||
switch_or,
|
||||
PathData, Point, Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite,
|
||||
fit_to_old_edge, ids_json, is_live_paint, json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids,
|
||||
source_nodes, source_shapes, switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -85,6 +85,9 @@ pub(super) fn lp_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "id": id.0, "faces": faces, "edges": edges }))
|
||||
}
|
||||
|
||||
/// How far, in points, the middle of an edge Merge makes may be from the old edge it lies on.
|
||||
const ON_OLD_EDGE: f64 = 1e-3;
|
||||
|
||||
/// What Merge carries from a face or edge to the part it makes again in its place, another path:
|
||||
/// the appearance, visibility, opacity and blending mode. Gradients fitted to the old outline keep
|
||||
/// that fit, and the strokes' pen pressure, tilt, bearing and rotation stay behind.
|
||||
@@ -125,18 +128,11 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
.ok_or_else(|| EngineError::Other("Live Paint Merge: select a Live Paint group and the paths to add".into()))?;
|
||||
check_live_paint_takes(d, roots)?;
|
||||
let old = d.node(target).cloned().ok_or(EngineError::NoNode(target))?;
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw, and (point on edge,
|
||||
// paint) for every edge.
|
||||
// Paint to carry over: (point inside face, paint) for faces that draw; edges are matched to the
|
||||
// old edges below.
|
||||
let keep_faces: Vec<(Point, Carried)> =
|
||||
b::faces(&old).iter().filter(|f| draws(f)).filter_map(|f| Some((po::interior_point(f.path_data()?)?, Carried::of(f)))).collect();
|
||||
let keep_edges: Vec<(Point, Carried)> = b::edges(&old)
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let pd = e.path_data()?;
|
||||
let sp = pd.subpaths.first().filter(|sp| sp.segment_count() > 0)?;
|
||||
Some((kurbo::ParamCurve::eval(&sp.segment(0), 0.5), Carried::of(e)))
|
||||
})
|
||||
.collect();
|
||||
let old_parts = old.clone();
|
||||
let mut sources = source_nodes(&old);
|
||||
for r in roots {
|
||||
if *r != target {
|
||||
@@ -162,12 +158,24 @@ fn merge_live(d: &mut Document, sel: &mut Selection, roots: &[NodeId]) -> Result
|
||||
carried.onto(Arc::make_mut(f));
|
||||
}
|
||||
}
|
||||
for (pt, carried) in keep_edges {
|
||||
if let Some(eid) = edge_near(&g, pt, 0.5).map(|e| e.id)
|
||||
&& let Some(ch) = g.children_mut()
|
||||
&& let Some(e) = ch.iter_mut().find(|c| c.id == eid)
|
||||
{
|
||||
carried.onto(Arc::make_mut(e));
|
||||
// Each edge whose middle lies on an old edge, every piece of an edge an added path cuts
|
||||
// included, takes the old edge's paint, with its rows fitted to its part of the old edge.
|
||||
if let Some(ch) = g.children_mut() {
|
||||
for c in ch.iter_mut().filter(|c| c.name.as_deref() == Some(EDGE_NAME)) {
|
||||
let Some(mid) = c
|
||||
.path_data()
|
||||
.and_then(|pd| pd.subpaths.first())
|
||||
.filter(|sp| sp.segment_count() > 0)
|
||||
.map(|sp| kurbo::ParamCurve::eval(&sp.segment(0), 0.5))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(was) = edge_near(&old_parts, mid, ON_OLD_EDGE) else { continue };
|
||||
let e = Arc::make_mut(c);
|
||||
Carried::of(was).onto(e);
|
||||
if let Some(outline) = was.path_data() {
|
||||
fit_to_old_edge(e, outline);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut merged = Beside::replacing(d, roots);
|
||||
@@ -363,9 +371,52 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "ids": ids_json(&targets), "faces": faces, "gaps": gaps_json(&gaps), "closed": closed }))
|
||||
}
|
||||
|
||||
/// Which parts a Live Paint Bucket click paints besides the one under the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum LpScope {
|
||||
/// The part under the pointer alone (a click).
|
||||
One,
|
||||
/// A face and the faces reached from it across edges that draw no stroke ([`b::flood_faces`]),
|
||||
/// or an edge and the edges joined to it end to end that draw with the same stroke paint
|
||||
/// ([`b::connected_edges`], [`b::lp_stroke_paint`]) (a double-click).
|
||||
Connected,
|
||||
/// Every face with the same fill, or every edge that draws with the same stroke paint, in the
|
||||
/// group (a triple-click).
|
||||
SamePaint,
|
||||
}
|
||||
|
||||
/// The `scope` of `livePaint.fill` and `livePaint.strokeEdge`: `one` when left out or null.
|
||||
fn scope_param(p: &Value, c: &str) -> Result<LpScope> {
|
||||
match p.get("scope").filter(|v| !v.is_null()) {
|
||||
None => Ok(LpScope::One),
|
||||
Some(v) => match v.as_str() {
|
||||
Some("one") => Ok(LpScope::One),
|
||||
Some("connected") => Ok(LpScope::Connected),
|
||||
Some("samePaint") => Ok(LpScope::SamePaint),
|
||||
_ => Err(bad(c, "scope must be \"one\", \"connected\" or \"samePaint\"")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The `match` of `livePaint.fill` and `livePaint.strokeEdge`: a paint as the document stores it,
|
||||
/// None when left out or null. With `allowed` false (a scope that compares no paints) a `match` is
|
||||
/// an error naming `scopes`, the scopes it applies to.
|
||||
fn match_param(p: &Value, c: &str, allowed: bool, scopes: &str) -> Result<Option<super::Paint>> {
|
||||
let Some(v) = p.get("match").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
if !allowed {
|
||||
return Err(bad(c, format!("match applies only with scope {scopes}")));
|
||||
}
|
||||
serde_json::from_value::<super::Paint>(v.clone()).map(Some).map_err(|_| bad(c, "match must be a paint as the document stores it"))
|
||||
}
|
||||
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope == LpScope::SamePaint, "\"samePaint\"")?;
|
||||
if scope != LpScope::One && p.get("points").is_some() {
|
||||
return Err(bad(C, "scope applies to a click: leave out points"));
|
||||
}
|
||||
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
|
||||
let values = input
|
||||
.as_array()
|
||||
@@ -400,7 +451,8 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let group = object_param(p, "group", C)?;
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
// The faces the click or drag paints in Live Paint group `gid`: the visible face at the point,
|
||||
// and every visible face the drag crosses; → (the face at the point, the faces).
|
||||
// the faces its scope adds, and every visible face the drag crosses; → (the face at the point,
|
||||
// the faces).
|
||||
let targets_in = |d: &Document, gid: NodeId| -> Result<(NodeId, std::collections::BTreeSet<NodeId>)> {
|
||||
let fid = d
|
||||
.node(gid)
|
||||
@@ -408,6 +460,18 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(|f| f.id)
|
||||
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
let mut targets = std::collections::BTreeSet::from([fid]);
|
||||
if scope != LpScope::One {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
if scope == LpScope::Connected {
|
||||
targets.extend(b::flood_faces(n, fid));
|
||||
} else {
|
||||
let like = match &like {
|
||||
Some(m) => m.clone(),
|
||||
None => d.node(fid).ok_or(EngineError::NoNode(fid))?.appearance.fill_paint(),
|
||||
};
|
||||
targets.extend(b::faces(n).into_iter().filter(|f| f.visible && f.appearance.fill_paint() == like).map(|f| f.id));
|
||||
}
|
||||
}
|
||||
if let Some(points) = points {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
// Use the existing region-crossing probes, so even a face narrower than the distance
|
||||
@@ -457,34 +521,36 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let (g, face) = match live {
|
||||
let (g, face, count) = match live {
|
||||
Some(gid) => {
|
||||
let (fid, targets) = targets_in(&s.doc()?.doc, gid)?;
|
||||
let count = targets.len();
|
||||
// Faces that already have the paint stay as they are: when every face has it, nothing
|
||||
// changes and no undo step is recorded.
|
||||
let d = &s.doc()?.doc;
|
||||
let unpainted: Vec<NodeId> = targets.into_iter().filter(|t| d.node(*t).is_none_or(|f| f.appearance.fill_paint() != paint)).collect();
|
||||
if unpainted.is_empty() {
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0 }));
|
||||
return Ok(json!({ "group": gid.0, "face": fid.0, "count": count }));
|
||||
}
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in unpainted {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?
|
||||
}
|
||||
None => s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = make_live(d, sel, &roots)?.0;
|
||||
let (fid, targets) = targets_in(d, gid)?;
|
||||
let count = targets.len();
|
||||
for target in targets {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
}
|
||||
Ok((gid, fid))
|
||||
Ok((gid, fid, count))
|
||||
})?,
|
||||
};
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "face": face.0 }))
|
||||
Ok(json!({ "group": g.0, "face": face.0, "count": count }))
|
||||
}
|
||||
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -498,31 +564,72 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "width out of range"));
|
||||
}
|
||||
let tol = number_or(p, "tolerance", 4.0, C)?.clamp(0.0, 1000.0);
|
||||
let (eid, unchanged) = {
|
||||
let scope = scope_param(p, C)?;
|
||||
let like = match_param(p, C, scope != LpScope::One, "\"connected\" or \"samePaint\"")?;
|
||||
let (eid, count, changed) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad(C, format!("{g} is not a Live Paint group")))?;
|
||||
let e = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
// An edge that already has the paint and the width (or has no stroke and gets none) stays as
|
||||
// it is, and no undo step is recorded.
|
||||
let unchanged = match e.appearance.stroke() {
|
||||
Some(st) => st.paint == paint && st.width == width,
|
||||
None => paint.is_none(),
|
||||
let start = b::visible_edge_near(n, pt, tol).ok_or_else(|| EngineError::Other("no Live Paint edge near that point".into()))?;
|
||||
let eid = start.id;
|
||||
let like = like.unwrap_or_else(|| b::lp_stroke_paint(start));
|
||||
let targets = match scope {
|
||||
LpScope::One => vec![eid],
|
||||
LpScope::Connected => b::connected_edges(n, eid, &like),
|
||||
LpScope::SamePaint => std::iter::once(eid)
|
||||
.chain(b::edges(n).into_iter().filter(|e| e.visible && e.id != eid && b::lp_stroke_paint(e) == like).map(|e| e.id))
|
||||
.collect(),
|
||||
};
|
||||
(e.id, unchanged)
|
||||
let count = targets.len();
|
||||
// An edge whose shown stroke already has the paint and the width (or that has no shown stroke
|
||||
// and gets none) stays as it is; when every edge does, nothing changes and no undo step is
|
||||
// recorded.
|
||||
let changed: Vec<NodeId> = targets
|
||||
.into_iter()
|
||||
.filter(|t| {
|
||||
d.node(*t).is_none_or(|e| match shown_stroke(e) {
|
||||
Some(st) => !(st.paint == paint && st.width == width),
|
||||
None => !paint.is_none(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
(eid, count, changed)
|
||||
};
|
||||
if unchanged {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0 }));
|
||||
if changed.is_empty() {
|
||||
return Ok(json!({ "group": g.0, "edge": eid.0, "count": count }));
|
||||
}
|
||||
let edge = s.edit("Live Paint Bucket", |d, _| {
|
||||
let e = d.node_mut(eid).ok_or(EngineError::NoNode(eid))?;
|
||||
e.appearance.set_stroke(paint.clone());
|
||||
if let Some(st) = e.appearance.stroke_mut() {
|
||||
st.width = width;
|
||||
s.edit("Live Paint Bucket", |d, _| {
|
||||
for target in &changed {
|
||||
let e = d.node_mut(*target).ok_or(EngineError::NoNode(*target))?;
|
||||
match shown_stroke_mut(e) {
|
||||
Some(st) => {
|
||||
st.paint = paint.clone();
|
||||
st.width = width;
|
||||
}
|
||||
None => e.appearance.items.push(super::AppearanceItem::Stroke(super::StrokeLayer::new(paint.clone(), width))),
|
||||
}
|
||||
}
|
||||
Ok(eid)
|
||||
Ok(())
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
Ok(json!({ "group": g.0, "edge": edge.0 }))
|
||||
Ok(json!({ "group": g.0, "edge": eid.0, "count": count }))
|
||||
}
|
||||
|
||||
/// The stroke `livePaint.strokeEdge` paints on Live Paint edge `e`: its topmost stroke that is
|
||||
/// shown. None when it has no stroke or every stroke is hidden; the command then adds a stroke
|
||||
/// above the others.
|
||||
fn shown_stroke(e: &Node) -> Option<&super::StrokeLayer> {
|
||||
e.appearance.items.iter().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`shown_stroke`], to change.
|
||||
fn shown_stroke_mut(e: &mut Node) -> Option<&mut super::StrokeLayer> {
|
||||
e.appearance.items.iter_mut().rev().find_map(|i| match i {
|
||||
super::AppearanceItem::Stroke(s) if s.visible => Some(s),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every fill and stroke row of face or edge `n`, bottom first, as `livePaint.info` lists them. A
|
||||
|
||||
@@ -63,7 +63,7 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some(&q) = pts.first()
|
||||
&& let Some((i, run)) = map.stroke_at(&outlines, q, tol)
|
||||
&& let (Some(leaf), Some(drawn)) = (leaves.get(i), outlines.get(i))
|
||||
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && !leaf.appearance.fill_paint().is_none(), b::outline_snap(drawn))
|
||||
&& let Some(rest) = po::cut_out(drawn, &run, open_filled_as_closed && leaf.appearance.has_drawn_fill(), b::outline_snap(drawn))
|
||||
&& rest.length() > b::outline_snap(drawn)
|
||||
{
|
||||
// The path keeps the rest of it, and a copy of it with the run under the click goes
|
||||
|
||||
@@ -288,9 +288,10 @@ fn trace_library(c: &str, s: &Session, params: &mut tr::TraceParams) -> Result<V
|
||||
/// The most anchor points an Image Trace may make, a guard for memory: a trace past it is refused
|
||||
/// with advice instead (#525). A trace keeps about 90 bytes an anchor in the document (measured on
|
||||
/// code-drawn photos of 2000 × 2000 to 6000 × 4000 pixels), so 8,000,000 anchors are about
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at High Fidelity Photo
|
||||
/// makes about 1.9 million, and even at Paths 100, Noise 1 and every tone about 7.9 million. On the
|
||||
/// web, where a page has at most 4 GB of memory, the limit stays at 2,000,000.
|
||||
/// 0.7 GB, with a peak of about 1 GB while tracing: a 4000 × 3000 photo at Limited 64 colors,
|
||||
/// Paths 90, Corners 25 and Noise 4 makes about 1.9 million, and even at Paths 100, Noise 1 and
|
||||
/// every tone about 7.9 million. On the web, where a page has at most 4 GB of memory, the limit
|
||||
/// stays at 2,000,000.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub const MAX_TRACE_ANCHORS: usize = 8_000_000;
|
||||
|
||||
@@ -1139,7 +1140,7 @@ mod trace_limit_tests {
|
||||
assert_eq!(w, ["Flat Logo traced the image at 946 × 710 pixels, averaged down from 16000 × 12000."]);
|
||||
}
|
||||
|
||||
// A 4000 × 3000 photo at High Fidelity Photo makes about 1.9 million anchors, which must fit;
|
||||
// the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
// A 4000 × 3000 photo at Limited 64 colors, Paths 90, Corners 25 and Noise 4 makes about
|
||||
// 1.9 million anchors, which must fit; the limit still guards memory (about 90 bytes an anchor). Checked when the tests build.
|
||||
const _: () = assert!(MAX_TRACE_ANCHORS >= 2_000_000 && MAX_TRACE_ANCHORS <= 16_000_000);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ use crate::DocState;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = vec![
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty)", always, export_svg),
|
||||
cmd!(query "clipboard.exportSvg", "Clipboard as SVG", [], None, "{} → {svg} the copied objects as standalone SVG (null when the clipboard is empty). Under automation read roots it is refused while the SVG would name a linked image's file outside them (an image whose pixels the clipboard doesn't hold; a relative path is followed from the document the objects came from while it is open)", always, export_svg),
|
||||
cmd!(
|
||||
query "clipboard.importSvg",
|
||||
"Load SVG into Clipboard",
|
||||
@@ -435,14 +435,37 @@ impl Clipboard {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty).
|
||||
/// The internal clipboard as standalone SVG (`None` when it is empty, and when the SVG would name
|
||||
/// a linked image's file the caller asking now may not be shown: [`Self::clipboard_svg_refused`]).
|
||||
pub fn clipboard_svg(&self) -> Option<String> {
|
||||
if self.clipboard_svg_refused() {
|
||||
return None;
|
||||
}
|
||||
self.clipboard.svg()
|
||||
}
|
||||
|
||||
/// Would the internal clipboard's SVG name a linked image's file outside the read roots in
|
||||
/// force? It names the file of an image whose pixels the clipboard doesn't hold. A relative
|
||||
/// path is followed from the document the objects came from while it is open; otherwise it
|
||||
/// counts as outside.
|
||||
pub fn clipboard_svg_refused(&self) -> bool {
|
||||
self.check_clipboard_svg("clipboard.exportSvg").is_err()
|
||||
}
|
||||
|
||||
/// [`Self::clipboard_svg_refused`] as `cmd`'s error, which names no file or folder.
|
||||
fn check_clipboard_svg(&self, cmd: &str) -> Result<()> {
|
||||
if crate::file_access::current().is_none() || !self.clipboard.has_art() {
|
||||
return Ok(());
|
||||
}
|
||||
let from = self.docs.iter().find(|d| Some(d.uid) == self.clipboard.source_doc);
|
||||
let base = from.map_or_else(super::links::LinkBase::default, super::links::LinkBase::of);
|
||||
super::fileio::check_images_in(cmd, "svg", &self.clipboard.to_document(), base, &json!({}))
|
||||
}
|
||||
}
|
||||
|
||||
fn export_svg(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "svg": s.clipboard_svg() }))
|
||||
s.check_clipboard_svg("clipboard.exportSvg")?;
|
||||
Ok(json!({ "svg": s.clipboard.svg() }))
|
||||
}
|
||||
|
||||
fn import_svg(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -64,7 +64,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Assign Profile…",
|
||||
["Edit"],
|
||||
None,
|
||||
"{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}",
|
||||
"{rgb?: profile|null, cmyk?: profile|null} tag the document with profiles (color numbers are kept; null: no profile, Don't Color Manage This Document, so colors show through the working space; the working space's name: that profile stays assigned when the working space changes). Colors then show and convert through the profiles assigned; the working spaces stay as edit.colorSettings set them → {rgb, cmyk}",
|
||||
has_doc,
|
||||
assign_profile
|
||||
),
|
||||
|
||||
@@ -70,13 +70,26 @@ pub(super) fn grid_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None | Some(Value::Null) => None,
|
||||
Some(_) => Some(switch_or(p, "visible", false, C)?),
|
||||
};
|
||||
let g = silent(s, |g| g.visible = want.unwrap_or(!g.visible))?;
|
||||
// A hidden grid holds no plane for Automatic Plane Positioning.
|
||||
let g = silent(s, |g| {
|
||||
g.visible = want.unwrap_or(!g.visible);
|
||||
if !g.visible {
|
||||
g.inferred = None;
|
||||
}
|
||||
})?;
|
||||
Ok(json!({ "visible": g.visible }))
|
||||
}
|
||||
|
||||
pub(super) fn plane_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let plane = str_param(p, "plane").and_then(Plane::parse).ok_or_else(|| bad("perspective.plane.set", "plane must be left|right|ground|none"))?;
|
||||
silent(s, |g| g.plane = plane)?;
|
||||
// The new active plane passes through the point Automatic Plane Positioning holds, unless no
|
||||
// plane is active or that would put the plane behind the viewer.
|
||||
silent(s, |g| {
|
||||
g.plane = plane;
|
||||
if g.inferred.is_some() && (plane == Plane::None || g.validate().is_err()) {
|
||||
g.inferred = None;
|
||||
}
|
||||
})?;
|
||||
Ok(json!({ "plane": plane.id() }))
|
||||
}
|
||||
|
||||
@@ -91,9 +104,14 @@ fn plane_param(g: &PerspectiveGrid, p: &Value, cmd: &str) -> Result<Plane> {
|
||||
Ok(plane)
|
||||
}
|
||||
|
||||
/// The objects a perspective command acts on: the outermost of `ids` (each once, in the order first
|
||||
/// given), else the selection's roots.
|
||||
pub(super) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match named_ids(p)? {
|
||||
Some(v) => Ok(outermost(&s.doc()?.doc, v)),
|
||||
Some(v) => {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
Ok(outermost(&s.doc()?.doc, v.into_iter().filter(|id| seen.insert(*id)).collect()))
|
||||
}
|
||||
None => selected_roots(s),
|
||||
}
|
||||
}
|
||||
@@ -138,6 +156,9 @@ pub(super) fn attach(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
store_grid(d, &g);
|
||||
Ok(())
|
||||
})?;
|
||||
if !ids.is_empty() {
|
||||
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
|
||||
}
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "plane": plane.id() }))
|
||||
}
|
||||
|
||||
@@ -205,8 +226,13 @@ fn persp_edit(
|
||||
return Err(EngineError::Other("select the objects to transform in perspective".into()));
|
||||
}
|
||||
let mut g = grid_of(&s.doc()?.doc);
|
||||
// An object not in perspective yet attaches to `fallback` where that plane is now.
|
||||
let attaches = {
|
||||
let d = &s.doc()?.doc;
|
||||
fallback.filter(|_| ids.iter().any(|id| g.attachment_of(d, *id).is_none()))
|
||||
};
|
||||
let kept = if copy && !stores_attachments(&s.doc()?.doc) { crate::cmd::object::preview_copies(s, ids, false)? } else { None };
|
||||
s.edit(label, |d, sel| {
|
||||
let edited = s.edit(label, |d, sel| {
|
||||
g.adopt_stored_attachments(d);
|
||||
let targets = match &kept {
|
||||
// The document becomes the snapshot with the kept copies, not yet mapped, and the loop
|
||||
@@ -236,7 +262,11 @@ fn persp_edit(
|
||||
}
|
||||
store_grid(d, &g);
|
||||
Ok((targets, first))
|
||||
})
|
||||
})?;
|
||||
if let Some(plane) = attaches {
|
||||
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
|
||||
}
|
||||
Ok(edited)
|
||||
}
|
||||
|
||||
/// Where the first of `ids` is in perspective (its plane and depth) when `ids` is not empty, every one
|
||||
@@ -430,6 +460,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["offset", "by"], C)?;
|
||||
let old = grid_of(&s.doc()?.doc);
|
||||
let plane = plane_param(&old, p, C)?;
|
||||
// A plane that Automatic Plane Positioning holds moves from where it is held, and the move
|
||||
// places it there for good: the moved grid holds no plane (undoing the move holds it again).
|
||||
let held = old.inferred;
|
||||
let from = old.offset(plane);
|
||||
let to = match (p.get("offset").and_then(Value::as_f64), p.get("by").and_then(Value::as_f64)) {
|
||||
(Some(o), _) => o,
|
||||
@@ -440,7 +473,7 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(objects, "none" | "move" | "copy") {
|
||||
return Err(bad(C, "objects must be none, move or copy"));
|
||||
}
|
||||
let mut g = old.clone();
|
||||
let mut g = PerspectiveGrid { inferred: None, ..old.clone() };
|
||||
g.set_offset(plane, to);
|
||||
g.validate().map_err(|e| bad(C, e))?;
|
||||
let label = match objects {
|
||||
@@ -458,8 +491,9 @@ pub(super) fn plane_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.collect()
|
||||
};
|
||||
// A plane moved to where it is, with its objects or without them, moves nothing: when the
|
||||
// document holds the grid already, the document and its undo history stay as they are.
|
||||
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &g) {
|
||||
// document holds the grid already, the document and its undo history stay as they are (a
|
||||
// plane held where it was placed stays held).
|
||||
if to == from && objects != "copy" && grid_kept(&s.doc()?.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) {
|
||||
let ids = if objects == "move" { on_plane(&s.doc()?.doc) } else { vec![] };
|
||||
return Ok(json!({ "plane": plane.id(), "offset": to, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }));
|
||||
}
|
||||
@@ -507,12 +541,19 @@ pub(super) fn plane_match(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
named_id(p)?.or_else(|| st.selection.objects.first().copied()).ok_or_else(|| EngineError::Other("select an object in perspective".into()))?;
|
||||
let mut g = grid_of(&st.doc);
|
||||
let (plane, depth) = g.attachment_of(&st.doc, id).ok_or_else(|| EngineError::Other("the object isn't in perspective".into()))?;
|
||||
// The moved grid holds no plane for Automatic Plane Positioning (undoing the move holds it
|
||||
// again).
|
||||
let held = g.inferred.take();
|
||||
g.set_offset(plane, depth);
|
||||
g.plane = plane;
|
||||
g.validate().map_err(|e| bad("perspective.plane.matchObject", e))?;
|
||||
// When the plane is at the object and active already, and the document holds that grid, the
|
||||
// document and its undo history stay as they are.
|
||||
if grid_kept(&st.doc, &g) {
|
||||
// document and its undo history stay as they are; a plane held elsewhere goes back to that
|
||||
// place as view state.
|
||||
if grid_kept(&st.doc, &PerspectiveGrid { inferred: held, ..g.clone() }) {
|
||||
if held.is_some() {
|
||||
silent(s, |g| g.inferred = None)?;
|
||||
}
|
||||
return Ok(json!({ "plane": plane.id(), "offset": depth }));
|
||||
}
|
||||
s.edit("Move Plane to Match Object", |d, _| {
|
||||
@@ -573,6 +614,7 @@ pub(super) fn persp_draw(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.history.recost_last(&st.doc);
|
||||
}
|
||||
res?;
|
||||
crate::cmd::perspgrid::plane_positioning_used(s, plane)?;
|
||||
Ok(json!({ "id": id.0, "plane": plane.id() }))
|
||||
}
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Eraser",
|
||||
[],
|
||||
None,
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] (pen pressure 0..1), size?: pt (10), sizeMode?: \"fixed\" (default) | \"pressure\" (Eraser Tool Options' Size set to Pressure: the tip is size − sizeVariation across where the pen presses lightest and size + sizeVariation where it presses hardest, as path.blob), sizeVariation?: pt (0), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one",
|
||||
"{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1, tilt −90..90°, barrel rotation ° clockwise, as path.freehand), size?: pt (10), angle?: ° (0: the tip's long axis counter-clockwise from level), roundness?: % (100, kept within 1–100), angleMode?, roundnessMode?, sizeMode?: \"fixed\" (default) | \"random\" | \"pressure\" | \"tilt\" | \"bearing\" | \"rotation\" (Eraser Tool Options' variation menus; a varied angle turns either way, clockwise or counter-clockwise), angleVariation?: ° (0–180, default 0, either way: clockwise or counter-clockwise), roundnessVariation?: % (0–100, default 0), sizeVariation?: pt (0 or more, default 0)} erase the stroke of an elliptical tip from paths (selected, or all) → {ids}. The tip is `size` across its long axis, which runs at `angle` counter-clockwise from horizontal; its short axis is `roundness` percent of the long one. A value whose mode is not fixed varies by up to its variation either way: random draws one value for the drag; pressure goes from the value less the variation where the pen presses lightest to the value plus it where it presses hardest (size on pressure as path.blob); tilt from less with the pen lying flat to more with it upright; bearing and rotation from less at −180° to more at 180° of the pen's lean direction or barrel turn. A drag without that pen reading (a mouse) erases at the value itself. An unknown mode, or a variation below 0 or past its range, is an error and erases nothing",
|
||||
has_doc,
|
||||
erase_region
|
||||
),
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
use super::common::{
|
||||
dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces, samples_param,
|
||||
sibling_with, size_pressure, target_paths, usize_opt,
|
||||
PenRecord, Sample, dist_to_polyline, fill_targets, ids_json, path_mut, path_of, points_param, poly_bounds, pressure_region, replace_with_pieces,
|
||||
samples_param, sibling_with, size_pressure, target_paths, usize_opt,
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, Paint, ParamCurve, PathData, Point, Result, Session,
|
||||
SubPath, Value, Vec2, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Variation};
|
||||
use vectorcraft_doc::StrokeLayer;
|
||||
use vectorcraft_tools::draw2::MIN_BRUSH_SIZE;
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
pub(in super::super) fn components(pd: &PathData) -> Vec<PathData> {
|
||||
@@ -278,7 +281,11 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let angle = number_or(p, "angle", 0.0, C)?;
|
||||
let roundness = number_or(p, "roundness", 100.0, C)?;
|
||||
let pressure = size_pressure(p, &samples, C)?;
|
||||
let vary = eraser_variations(p, C)?;
|
||||
if varies_beyond_size_pressure(&vary) {
|
||||
return erase_varied(s, &samples, [angle, roundness, size], vary);
|
||||
}
|
||||
let pressure = if vary[2].0 == Variation::Pressure { size_pressure(p, &samples, C)? } else { None };
|
||||
let pts: Vec<Point> = samples.into_iter().map(|s| s.pt).collect();
|
||||
let r = size / 2.0;
|
||||
// The tip's short axis (its narrowest with Pressure): an open path is sampled at least every half of it.
|
||||
@@ -318,6 +325,101 @@ pub(super) fn erase_region(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
/// The variation modes `path.eraseRegion` takes for each of `angleMode`, `roundnessMode` and
|
||||
/// `sizeMode`.
|
||||
const ERASER_MODES: &str = "\"fixed\", \"random\", \"pressure\", \"tilt\", \"bearing\" or \"rotation\"";
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variations: for each of angle (`angleMode` with
|
||||
/// `angleVariation` in degrees, at most 180), roundness (`roundnessMode` with `roundnessVariation`
|
||||
/// in percent, at most 100) and size (`sizeMode` with `sizeVariation` in points), its mode and how
|
||||
/// far it varies either way. A mode left out or null is Fixed, and a variation left out or null
|
||||
/// is 0; any other mode, or a variation that is negative or past its most, is refused.
|
||||
fn eraser_variations(p: &Value, cmd: &str) -> Result<[(Variation, f64); 3]> {
|
||||
const KEYS: [(&str, &str, f64); 3] =
|
||||
[("angleMode", "angleVariation", 180.0), ("roundnessMode", "roundnessVariation", 100.0), ("sizeMode", "sizeVariation", f64::INFINITY)];
|
||||
let mut out = [(Variation::Fixed, 0.0); 3];
|
||||
for (slot, (mode_key, var_key, most)) in out.iter_mut().zip(KEYS) {
|
||||
let mode = match p.get(mode_key).filter(|v| !v.is_null()) {
|
||||
None => Variation::Fixed,
|
||||
Some(Value::String(id)) => Variation::parse(id).ok_or_else(|| bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not `{id}`")))?,
|
||||
Some(other) => return Err(bad(cmd, format!("{mode_key} is one of {ERASER_MODES}, not {other}"))),
|
||||
};
|
||||
let variation = number_or(p, var_key, 0.0, cmd)?;
|
||||
if !(variation.is_finite() && variation >= 0.0) {
|
||||
return Err(bad(cmd, format!("{var_key} must be 0 or more")));
|
||||
}
|
||||
if variation > most {
|
||||
return Err(bad(cmd, format!("{var_key} must be at most {most}")));
|
||||
}
|
||||
*slot = (mode, variation);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Does any of the Eraser's Angle, Roundness and Size vary with something other than Size on
|
||||
/// Pressure? A mode whose variation is 0 does not vary.
|
||||
fn varies_beyond_size_pressure(vary: &[(Variation, f64); 3]) -> bool {
|
||||
vary.iter().enumerate().any(|(i, (mode, v))| *v > 0.0 && *mode != Variation::Fixed && !(i == 2 && *mode == Variation::Pressure))
|
||||
}
|
||||
|
||||
/// `path.eraseRegion` with its tip varying along the drag ([`eraser_variations`]): the area the
|
||||
/// tip covers is swept as a Calligraphic brush nib of the same angle, roundness, size, modes and
|
||||
/// variations, with what the pen recorded along the drag. Random draws one value for the drag
|
||||
/// and the pen modes follow the pen at each point; a drag without that recording (a mouse) takes
|
||||
/// the value itself. `tip`: the angle, roundness and size.
|
||||
fn erase_varied(s: &mut Session, samples: &[Sample], tip: [f64; 3], vary: [(Variation, f64); 3]) -> Result<Value> {
|
||||
let [angle, roundness, size] = tip;
|
||||
let mut pts: Vec<Point> = samples.iter().map(|s| s.pt).collect();
|
||||
// A press without a drag is a dab: a sweep needs some length.
|
||||
if let [only] = pts[..] {
|
||||
pts.push(only + Vec2::new(0.01, 0.0));
|
||||
}
|
||||
// A nib's size is kept within 1296 pt and the stroke's width scales it: a larger tip is swept
|
||||
// at a fraction of its size on a stroke as many times wider.
|
||||
let [(am, av), (rm, rv), (sm, sv)] = vary;
|
||||
let sv = if sm == Variation::Fixed { 0.0 } else { sv };
|
||||
let scale = ((size + sv) / Calligraphic::RANGES[2].1).max(1.0);
|
||||
let nib = Calligraphic {
|
||||
angle,
|
||||
roundness: roundness.clamp(1.0, 100.0),
|
||||
size: size / scale,
|
||||
variation: [av, rv, sv / scale],
|
||||
modes: Some([am, rm, sm]),
|
||||
};
|
||||
let brush = Brush { name: "Eraser".into(), kind: BrushKind::Calligraphic(nib) };
|
||||
let mut stroke = StrokeLayer::new(Paint::None, scale);
|
||||
PenRecord::of_samples(samples).write(&mut stroke);
|
||||
let spine = SubPath::polyline(&pts, false);
|
||||
let st = s.doc()?;
|
||||
let pieces = vectorcraft_brush::stroke_pieces(&st.doc, &brush, &PathData::single(spine).to_bezpath(), &stroke);
|
||||
let areas: Vec<PathData> = pieces.iter().filter_map(|n| n.path_data().cloned()).collect();
|
||||
if areas.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
}
|
||||
let region =
|
||||
po::try_unite_all(&areas.iter().map(|a| (a, FillRule::NonZero)).collect::<Vec<_>>()).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let bp = region.to_bezpath();
|
||||
// The narrowest the tip gets across: an open path is sampled at least every half of it.
|
||||
let low = |i: usize| match vary[i] {
|
||||
(Variation::Fixed, _) => tip[i],
|
||||
(_, v) => tip[i] - v,
|
||||
};
|
||||
let short = low(2).max(MIN_BRUSH_SIZE) * low(1).clamp(1.0, 100.0) / 100.0;
|
||||
let reach = (size + sv) / 2.0;
|
||||
let mut plan: Vec<(NodeId, Vec<PathData>)> = vec![];
|
||||
for (id, pd, rule) in fill_targets(&st.doc, &st.selection, poly_bounds(&pts, reach))? {
|
||||
if pd.is_closed() {
|
||||
if po::area(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Intersect), FillRule::NonZero) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
plan.push((id, components(&po::boolean(&pd, rule, ®ion, FillRule::NonZero, BoolOp::Difference))));
|
||||
} else if let Some(pieces) = erase_outline(&pd, short / 2.0, &|q| fill_contains(&bp, FillRule::NonZero, q)) {
|
||||
plan.push((id, pieces));
|
||||
}
|
||||
}
|
||||
apply_plan(s, "Eraser", plan)
|
||||
}
|
||||
|
||||
fn apply_plan(s: &mut Session, label: &str, plan: Vec<(NodeId, Vec<PathData>)>) -> Result<Value> {
|
||||
if plan.is_empty() {
|
||||
return Ok(json!({ "ids": [] }));
|
||||
|
||||
@@ -13,7 +13,10 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at};
|
||||
use super::appearance::{
|
||||
ItemTarget, aligned, appearance_targets, design_reference, edit_targets, index_param, item_indices, item_target, item_target_at, reference_of,
|
||||
with_reference,
|
||||
};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
|
||||
@@ -49,7 +52,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Apply Effect",
|
||||
[],
|
||||
None,
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -67,7 +70,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Remove Effect",
|
||||
[],
|
||||
None,
|
||||
"{index: int (position in the effect list), indices?: [int] (several positions in the same list instead of index, removed in one undo step; every one must exist), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
"{index: int (position in the effect list), indices?: [int] (several positions in the same list instead of index, removed in one undo step; every one must exist), item?: appearance item index|null (that fill/stroke's effects; omitted: the active item, else the object's), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}",
|
||||
has_doc,
|
||||
remove
|
||||
),
|
||||
@@ -76,7 +79,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Effect Options",
|
||||
[],
|
||||
None,
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} → {ids}",
|
||||
"{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}",
|
||||
has_doc,
|
||||
set_params
|
||||
),
|
||||
@@ -85,7 +88,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"3D Lighting Preset",
|
||||
[],
|
||||
None,
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}",
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}",
|
||||
has_doc,
|
||||
lighting_preset
|
||||
),
|
||||
@@ -103,7 +106,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Duplicate Effect",
|
||||
[],
|
||||
None,
|
||||
"{index: int, indices?: [int] (several positions in the same list instead of index; every one must exist), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} insert a copy of each effect right after it, in one undo step → {ids}",
|
||||
"{index: int, indices?: [int] (several positions in the same list instead of index; every one must exist), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} insert a copy of each effect right after it, in one undo step → {ids}",
|
||||
has_doc,
|
||||
duplicate
|
||||
),
|
||||
@@ -112,7 +115,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Move Effect",
|
||||
[],
|
||||
None,
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
|
||||
has_doc,
|
||||
move_effect
|
||||
),
|
||||
@@ -296,14 +299,20 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
/// effects it edits (`None`: the object's own) and the effect's index there. With `aligned` (see
|
||||
/// [`ItemTarget::per_target`]) `item` and `index` are the first target's, and each other target
|
||||
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
|
||||
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
|
||||
/// the other targets have; in a target without them, `item` and `index` stand for themselves. When the first object
|
||||
/// given is the art of a graph design in a series ([`design_reference`]), which is left out, they are rows of its stack,
|
||||
/// and a target without them is left out.
|
||||
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
|
||||
let roots = edit_targets(s, p)?;
|
||||
let roots = edit_targets(s, p, cmd)?;
|
||||
let of = reference_of(s, p, item, cmd)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let per = item.per_target(s, &roots);
|
||||
let first = roots.first().and_then(|f| d.node(*f));
|
||||
let per = item.per_target_of(s, of, &roots);
|
||||
let first = of.or_else(|| roots.first().copied()).and_then(|f| d.node(f));
|
||||
// Whether `item` names an item in the stack it is a row of (else the edit is object-level there).
|
||||
let anchor = roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a));
|
||||
let anchor = match of {
|
||||
Some(of) => d.node(of),
|
||||
None => roots.get(item.anchor(s, &roots)).and_then(|a| d.node(*a)),
|
||||
};
|
||||
let anchor_level = anchor.map(|a| item.effects_item(&a.appearance, cmd)).transpose()?.flatten();
|
||||
let aligned = aligned(p, cmd)?;
|
||||
let mut out = Vec::with_capacity(roots.len());
|
||||
@@ -312,7 +321,11 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
|
||||
let at = item.effects_item(&n.appearance, cmd)?;
|
||||
// An object-level effect this target shares with the first is where it is in this target.
|
||||
let index = match (first.filter(|_| aligned), at, anchor_level) {
|
||||
(Some(f), None, None) => SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1).unwrap_or(index),
|
||||
(Some(f), None, None) => match SharedStack::of(&[&*f.appearance, &*n.appearance]).effect_in(index, 1) {
|
||||
Some(i) => i,
|
||||
None if of.is_some() && index != APPENDED => continue,
|
||||
None => index,
|
||||
},
|
||||
_ => index,
|
||||
};
|
||||
out.push((*id, at, index));
|
||||
@@ -320,6 +333,10 @@ pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: us
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The effect index `effect.apply` gives [`effect_targets`] for the effect it appends, which names no effect the targets
|
||||
/// have.
|
||||
const APPENDED: usize = usize::MAX;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn edit_effects(
|
||||
s: &mut Session,
|
||||
@@ -362,6 +379,20 @@ fn edit_effects_at(
|
||||
indices: &[usize],
|
||||
mut f: impl FnMut(&mut Vec<Effect>, &[usize]) -> bool,
|
||||
) -> Result<Vec<NodeId>> {
|
||||
// With a graph design's art given first, the indices are effects of its list: one it doesn't have names no effect,
|
||||
// and the edit is refused as a whole, as it is in a list that lacks one of them.
|
||||
if let Some(of) = reference_of(s, p, item, cmd)?
|
||||
&& let Some(n) = s.doc()?.doc.node(of)
|
||||
{
|
||||
let ap = &n.appearance;
|
||||
let len = match item.effects_item(ap, cmd)? {
|
||||
None => ap.effects.len(),
|
||||
Some(i) => ap.items.get(i).map_or(0, |it| it.effects().len()),
|
||||
};
|
||||
if indices.iter().any(|i| *i >= len) {
|
||||
return Err(EngineError::Other(none.into()));
|
||||
}
|
||||
}
|
||||
// Each target's list and the positions in it, in the order the targets first come up.
|
||||
let mut targets: Vec<(NodeId, Option<usize>, Vec<usize>)> = vec![];
|
||||
for &index in indices {
|
||||
@@ -427,6 +458,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
super::params::check_effect_color(C, id, ¶ms)?;
|
||||
super::params::check_effect_channel(C, id, ¶ms)?;
|
||||
super::params::check_effect_center(C, id, ¶ms)?;
|
||||
// Crop Marks take their style from the preferences when applied.
|
||||
if id == effects::CROP_MARKS && params.get("style").is_none() {
|
||||
params["style"] = json!(s.crop_mark_style().id());
|
||||
@@ -452,13 +484,18 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "ids": [gid.0], "index": 0, "item": null, "grouped": true }));
|
||||
}
|
||||
let item = item_target(s, p, C)?;
|
||||
// The item as each target has it, read before the effect changes their rows: a row of a graph design's art, which is
|
||||
// left out of the targets, is the row equal to it there, and a target without one is left out.
|
||||
let targets = edit_targets(s, p, C)?;
|
||||
let of = reference_of(s, p, item, C)?;
|
||||
let per: Vec<(NodeId, Option<ItemTarget>)> = targets.iter().copied().zip(item.per_target_of(s, of, &targets)).collect();
|
||||
if effects::is_three_d(id) {
|
||||
let targets = edit_targets(s, p)?;
|
||||
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
|
||||
for &(target, at) in &per {
|
||||
let Some(at) = at else { continue };
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
|
||||
// A new effect goes after the item's (or the object's) others.
|
||||
let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten();
|
||||
let on = at.effects_item(&n.appearance, C).ok().flatten();
|
||||
let on = on.and_then(|i| Some((Some(i), n.appearance.items.get(i)?.effects().len())));
|
||||
let on = on.unwrap_or((None, n.appearance.effects.len()));
|
||||
effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?;
|
||||
@@ -473,14 +510,19 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", 0, |fx, _| {
|
||||
let ids = edit_effects(s, p, item, C, &label, "Apply Effect: select objects", APPENDED, |fx, _| {
|
||||
fx.push(effect.clone());
|
||||
true
|
||||
})?;
|
||||
// The item the effect landed on in the object whose row the item is (the first selected object
|
||||
// for the active item, which applies where it fits), and the effect's index in that object.
|
||||
let first = ids.get(item.anchor(s, &ids)).and_then(|id| s.doc().ok()?.doc.node(*id));
|
||||
let landed = first.and_then(|n| item.effects_item(&n.appearance, C).ok().flatten());
|
||||
let k = item.anchor(s, &ids);
|
||||
let first = ids.get(k).and_then(|id| s.doc().ok()?.doc.node(*id));
|
||||
let at = match of {
|
||||
Some(_) => ids.get(k).and_then(|id| per.iter().find(|(t, _)| t == id)).and_then(|(_, at)| *at).unwrap_or(item),
|
||||
None => item,
|
||||
};
|
||||
let landed = first.and_then(|n| at.effects_item(&n.appearance, C).ok().flatten());
|
||||
let index = first.and_then(|n| n.appearance.effects_at(landed)).map_or(0, |fx| fx.len().saturating_sub(1));
|
||||
Ok(json!({ "ids": ids_json(&ids), "index": index, "item": landed }))
|
||||
}
|
||||
@@ -494,7 +536,7 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
// The art of a graph design in a series stays where the graph draws it.
|
||||
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "appearance")?;
|
||||
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "effect.apply")?;
|
||||
let grouped = roots.iter().any(|r| d.node(*r).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })));
|
||||
Ok((roots.len() >= 2 && !grouped).then_some(roots))
|
||||
}
|
||||
@@ -607,9 +649,9 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src = item_target_at(s, p, "fromItem", C)?;
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let roots = edit_targets(s, p)?;
|
||||
let roots = edit_targets(s, p, C)?;
|
||||
// Where an aligned effect would go in each of several different stacks isn't one place.
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
}
|
||||
// Where the effect landed in each object it moved in, in the order of `ids`.
|
||||
@@ -718,7 +760,7 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// sets its Warp style (`warpStyle`), its 3D type (`threeDType`) or visibility (`visible`), as one
|
||||
/// undo step. They are checked as `effect.apply` checks them, and a visible 3D effect must still
|
||||
/// fit; a hidden one has its given values checked. → `{ids}`.
|
||||
fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "effect.setParams";
|
||||
let index = index_param(p, "index", C)?;
|
||||
let mut params = p.get("params").cloned().unwrap_or(Value::Null);
|
||||
@@ -740,6 +782,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for effect in &edited {
|
||||
super::params::check_effect_color(C, effect, ¶ms)?;
|
||||
super::params::check_effect_channel(C, effect, ¶ms)?;
|
||||
super::params::check_effect_center(C, effect, ¶ms)?;
|
||||
}
|
||||
if edited.iter().any(|e| texture_load_effect(e)) {
|
||||
load_texture(&mut params, C)?;
|
||||
@@ -833,11 +876,13 @@ fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const GLASS: &str = "distort.glass";
|
||||
/// Effect › Texture › Texturizer.
|
||||
const TEXTURIZER: &str = "texture.texturizer";
|
||||
/// Effect › Artistic › Rough Pastels.
|
||||
const ROUGH_PASTELS: &str = "artistic.roughPastels";
|
||||
|
||||
/// Does effect `id` have Load Texture: a `textureImage` that `effect.apply` reads from an image
|
||||
/// file (Glass, Texturizer)?
|
||||
/// file (Glass, Texturizer, Rough Pastels)?
|
||||
pub(crate) fn texture_load_effect(id: &str) -> bool {
|
||||
id == GLASS || id == TEXTURIZER
|
||||
id == GLASS || id == TEXTURIZER || id == ROUGH_PASTELS
|
||||
}
|
||||
|
||||
/// Glass's `textureImage` in `params` as Glass stores it: an image file (`{path}`, or `{name?,
|
||||
@@ -894,8 +939,11 @@ fn can_expand(s: &Session) -> std::result::Result<(), String> {
|
||||
has_doc(s)?;
|
||||
let ids = appearance_targets(s, &Value::Null).map_err(|e| e.to_string())?;
|
||||
let d = &s.doc().map_err(|e| e.to_string())?.doc;
|
||||
// The art of a graph design in a series, selected or inside a selected graph, is drawn again from the design.
|
||||
let ids = super::appearance::drop_design_art(d, ids);
|
||||
// A dimension selected with the art it measures is left as it is.
|
||||
let kept = super::dimension::with_their_art(d, &ids);
|
||||
let mut kept = super::dimension::with_their_art(d, &ids);
|
||||
kept.extend(super::appearance::design_art_in(d, &ids));
|
||||
if ids.iter().filter_map(|id| d.node(*id)).any(|n| expandable_except(n, &kept)) {
|
||||
Ok(())
|
||||
} else {
|
||||
@@ -1221,12 +1269,22 @@ fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::col
|
||||
}
|
||||
|
||||
fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let roots = appearance_targets(s, p)?;
|
||||
let roots = edit_targets(s, p, "effect.expandAppearance")?;
|
||||
// In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the
|
||||
// geometry it hasn't changed.
|
||||
if vectorcraft_plugins::safe_mode::active() {
|
||||
// A dimension selected with the art it measures is left as it is.
|
||||
let d = &*super::dimension::without_kept(&s.doc()?.doc, &roots);
|
||||
// A dimension selected with the art it measures is left as it is, and so is the art of a graph design in a
|
||||
// series.
|
||||
let mut d = super::dimension::without_kept(&s.doc()?.doc, &roots);
|
||||
let designs = super::appearance::design_art_in(&d, &roots);
|
||||
if !designs.is_empty() {
|
||||
let view = d.to_mut();
|
||||
for id in designs {
|
||||
// Art already gone (inside other art removed) needs nothing more.
|
||||
let _ = view.remove(id);
|
||||
}
|
||||
}
|
||||
let d = &*d;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
if roots.iter().filter_map(|id| d.node(*id)).any(|n| holds_plugin_effect(d, n, false, &mut seen)) {
|
||||
return Err(EngineError::Other("Expand Appearance: a plug-in effect in the selection can't be expanded in Safe Mode".into()));
|
||||
@@ -1236,6 +1294,10 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
|
||||
let ids = s.edit("Expand Appearance", |d, _| {
|
||||
let before = d.clone();
|
||||
// The art of graph designs in the graphs and series among the roots stays as the graph draws it. A group whose
|
||||
// own effect turns it into other art as a whole (a blur, feather or inner glow makes it an image) takes its
|
||||
// art into that art, which draws it, so that art has no place to go back to.
|
||||
let designs = super::appearance::design_art_in(d, &roots);
|
||||
// A dimension selected with the art it measures keeps its own lines and label: it is out
|
||||
// of the document while the art expands.
|
||||
let lifted = super::dimension::lift(d, &roots);
|
||||
@@ -1247,6 +1309,15 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
for id in &roots {
|
||||
expand_node(d, *id, &brushes, &mut out);
|
||||
}
|
||||
for id in &designs {
|
||||
if let (Some(was), Some(slot)) = (before.node(*id), d.node_mut(*id)) {
|
||||
*slot = was.clone();
|
||||
}
|
||||
}
|
||||
if !designs.is_empty() {
|
||||
// A mark that expands into a group stays listed: only what lies in the restored art is left out.
|
||||
out.retain(|id| d.node(*id).is_some() && !d.ancestry(*id).is_some_and(|up| up.iter().any(|a| designs.contains(a))));
|
||||
}
|
||||
super::dimension::put_back(d, lifted);
|
||||
// A dimension whose source was replaced stays where it was, no longer linked.
|
||||
super::dimension::restore_unchanged(&before, d, ended);
|
||||
|
||||
@@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
effect_targets(s, p, item, index, C)?
|
||||
} else {
|
||||
let mut out = vec![];
|
||||
for id in edit_targets(s, p)? {
|
||||
for id in edit_targets(s, p, C)? {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -1016,3 +1016,69 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
|
||||
});
|
||||
assert_eq!(shadows, 1);
|
||||
}
|
||||
|
||||
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
|
||||
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
|
||||
#[test]
|
||||
fn radial_blur_center_is_stored_drawn_and_checked() {
|
||||
let (mut s, id) = session_with_rect();
|
||||
let draw = |s: &Session| {
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
s.execute("effect.apply", &json!({"effect": "blur.radial", "params": {"amount": 40}})).unwrap();
|
||||
assert_eq!(node(&s, id).appearance.effects[0].params["centerX"], json!(0.5), "the default center is stored");
|
||||
let middle = draw(&s);
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0.5, "centerY": 0.5}})).unwrap();
|
||||
assert_eq!(draw(&s), middle, "the default center draws as before");
|
||||
s.execute("effect.setParams", &json!({"index": 0, "params": {"centerX": 0, "centerY": 1}})).unwrap();
|
||||
let params = node(&s, id).appearance.effects[0].params.clone();
|
||||
assert_eq!((params["centerX"].clone(), params["centerY"].clone()), (json!(0), json!(1)));
|
||||
let corner = draw(&s);
|
||||
assert_ne!(corner, middle, "the blur turns about the bottom-left corner");
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (cmd, params) in [
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerX": 1.5}})),
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerY": -0.01}})),
|
||||
("effect.setParams", json!({"index": 0, "params": {"centerX": "0.5"}})),
|
||||
("effect.apply", json!({"effect": "blur.radial", "params": {"centerY": 2}})),
|
||||
] {
|
||||
let e = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(e.contains("must be a number"), "{cmd} {params}: {e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{cmd} {params}");
|
||||
assert_eq!(node(&s, id).appearance.effects.len(), 1, "{cmd} {params}");
|
||||
assert_eq!(draw(&s), corner, "{cmd} {params}");
|
||||
}
|
||||
// A replayed journal is checked too: the refusal is the command's own.
|
||||
let e = s.replay("effect.setParams", &json!({"index": 0, "params": {"centerX": 7}})).unwrap_err().to_string();
|
||||
assert!(e.contains("`centerX` must be a number from 0 to 1"), "{e}");
|
||||
// Moving the object moves the blur with it.
|
||||
s.execute("object.move", &json!({"ids": [id.0], "dx": 40, "dy": 20})).unwrap();
|
||||
let moved = draw(&s);
|
||||
let at = |px: &[u8], x: usize, y: usize| px[(y * 300 + x) * 4..][..4].to_vec();
|
||||
for (x, y) in [(95, 150), (150, 205), (205, 95), (120, 120)] {
|
||||
assert_eq!(at(&moved, x + 40, y + 20), at(&corner, x, y), "({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Rasterize with transparent room around the art, before another Rasterize, splits the stack,
|
||||
/// and the part after the split paints around content the room spreads. The Blur Center still
|
||||
/// lies in the object's own bounds, so the blur draws as it does without the room.
|
||||
#[test]
|
||||
fn radial_blur_center_stays_in_the_object_when_the_stack_splits() {
|
||||
let draw = |room: bool| {
|
||||
let (mut s, _) = session_with_rect();
|
||||
let mut stack = vec![("rasterize", json!({})), ("blur.radial", json!({"amount": 60, "centerX": 0, "centerY": 0}))];
|
||||
if room {
|
||||
stack.insert(0, ("rasterize", json!({"addAround": 40})));
|
||||
}
|
||||
for (effect, params) in stack {
|
||||
s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap();
|
||||
}
|
||||
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
|
||||
};
|
||||
let (plain, split) = (draw(false), draw(true));
|
||||
let alpha = |px: &[u8]| px.iter().skip(3).step_by(4).map(|a| u64::from(*a)).sum::<u64>();
|
||||
assert!(alpha(&plain) > 0, "the blurred art draws");
|
||||
let differ = (0..300 * 300).filter(|i| plain[i * 4 + 3].abs_diff(split[i * 4 + 3]) > 8).count();
|
||||
assert!(differ < 50, "{differ} pixels' coverage moved with the room around the art");
|
||||
}
|
||||
|
||||
@@ -265,25 +265,27 @@ fn gradient_expands(d: &Document, l: &Node) -> bool {
|
||||
|
||||
/// Whether type `t` has a gradient fill that Fill expands once Object has outlined it: one of the
|
||||
/// paths `type.createOutlines` makes of its glyphs, ruby glyphs and underline and strikethrough
|
||||
/// bars, each painted as its run, has one ([`gradient_expands`] on that path's own box). Inline
|
||||
/// graphics and color glyphs become other art. Leaves the document as it is and stops at the
|
||||
/// first such path.
|
||||
/// bars, each painted as its run with its unplaced gradients fitted to the layout's bounds, has one
|
||||
/// ([`gradient_expands`] on that path). Inline graphics and color glyphs become other art. Leaves
|
||||
/// the document as it is and stops at the first such path.
|
||||
fn text_gradient_expands(d: &Document, t: &TextObject) -> bool {
|
||||
if !t.runs.iter().any(|r| matches!(r.style.fill, Paint::Gradient(_))) {
|
||||
return false;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let first = t.first_style();
|
||||
let expands = |run: usize, outline: &BezPath| {
|
||||
let style = t.runs.get(run).map(|r| &r.style);
|
||||
if !matches!(style.map_or_else(|| t.first_style().fill, |s| s.fill.clone()), Paint::Gradient(_)) {
|
||||
let style = t.runs.get(run).map_or(&first, |r| &r.style);
|
||||
if !matches!(style.fill, Paint::Gradient(_)) {
|
||||
return false;
|
||||
}
|
||||
let path = PathData::from_bezpath(outline).transformed(t.xf);
|
||||
let path = PathData::from_bezpath(outline);
|
||||
if path.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let appearance = style.map_or_else(|| t.first_style().appearance(), |s| s.appearance());
|
||||
gradient_expands(d, &Node::path(NodeId(u64::MAX), path, appearance))
|
||||
let mut piece = Node::path(NodeId(u64::MAX), path, Appearance::default());
|
||||
vectorcraft_render::effects::paint_type_piece(&mut piece, style, lay.bounds, t.xf);
|
||||
gradient_expands(d, &piece)
|
||||
};
|
||||
let inline = |gi: usize| lay.inlines.iter().find(|i| i.glyph == gi).is_some_and(|i| t.runs.get(i.run).is_some_and(|r| r.inline.is_some()));
|
||||
lay.glyphs.iter().enumerate().any(|(gi, g)| !inline(gi) && g.image.is_none() && g.colour.is_none() && expands(g.run, &g.outline))
|
||||
|
||||
@@ -39,7 +39,7 @@ pub mod jxlread;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, file_clipped, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
@@ -91,6 +91,7 @@ pub(crate) use mesh3d::{mesh_file_names, mesh_files};
|
||||
pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, render as render_file_name};
|
||||
pub(crate) use native::preview_png;
|
||||
pub use native::with_compression_pref;
|
||||
pub(crate) use pdfimport::opened_page_document;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
@@ -124,9 +125,10 @@ mod commands;
|
||||
mod export_names;
|
||||
mod formats;
|
||||
|
||||
pub(crate) use access::check_images_in;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
|
||||
@@ -139,6 +139,49 @@ pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Re
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The error for an SVG that would name a linked image's file outside the read roots.
|
||||
pub(crate) const IMAGE_OUTSIDE: &str = "a linked image file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `d`, the document an output of `st` writes (all of it, or the objects it
|
||||
/// exports), in format `format` (a format id) with options `p`: any format but SVG and SVGZ, and
|
||||
/// those too unless read roots are in force and the file would name a linked image's file outside
|
||||
/// them (a relative path taken from `st`'s folder; a URL is not checked). An `<image>` names the
|
||||
/// file with SVG Options › Images set to Link, and with Embed when the document holds no pixels for
|
||||
/// the image, for the images of the art each file draws (with chosen artboards, the art over each
|
||||
/// one; hidden layers and objects only with `hiddenLayers`, template layers and the opacity-mask
|
||||
/// and symbol editing layers never) and of the symbols, patterns and brushes that art uses; with
|
||||
/// Preserve Editing Capabilities, the native document the file carries names every linked file, the relative paths kept of them
|
||||
/// and each data set's image. The error names no file or folder.
|
||||
pub fn check_linked_images(cmd: &str, format: &str, st: &crate::DocState, d: &vectorcraft_doc::Document, p: &Value) -> Result<()> {
|
||||
check_images_in(cmd, format, d, crate::cmd::links::LinkBase::of(st), p)
|
||||
}
|
||||
|
||||
/// [`check_linked_images`] for `d`, a document whose links are looked for from `base` (the
|
||||
/// objects on the clipboard, looked for from the document they came from).
|
||||
pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Document, base: crate::cmd::links::LinkBase, p: &Value) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
// Options that don't read as the encoder's choices count as Link, Preserve Editing and hidden
|
||||
// layers kept: the encoder refuses them anyway.
|
||||
let (link, preserve, hidden) = match super::svg::options_map(p) {
|
||||
Ok(m) => {
|
||||
let on = |k: &str| m.get(k).is_some_and(|v| v.as_bool() != Some(false));
|
||||
(m.get("images").is_some_and(|v| v.as_str() != Some("embed")), on("preserveEditing"), on("hiddenLayers"))
|
||||
}
|
||||
Err(_) => (true, true, true),
|
||||
};
|
||||
// The opacity-mask and symbol editing layers are never written.
|
||||
let d = &*d.without_edit_modes();
|
||||
let names = |d: &vectorcraft_doc::Document| crate::cmd::links::svg_names_hidden_image(d, base, link, hidden);
|
||||
if preserve && crate::cmd::links::names_hidden_file(d, base)
|
||||
|| names(d) && super::svg::drawn(d, p).is_none_or(|files| files.iter().any(|f| names(f)))
|
||||
{
|
||||
return Err(bad(cmd, IMAGE_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,13 +2,13 @@
|
||||
//! (unknown keys are ignored, so one params object can carry the options of several formats).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind};
|
||||
use vectorcraft_doc::{Artboard, Document, Node, NodeKind, SYMBOL_SIZES, SymbolOverride};
|
||||
use vectorcraft_geom::Rect;
|
||||
use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, JpegOptions};
|
||||
@@ -450,31 +450,107 @@ pub fn export_art_bounds(doc: &Document, format: &str) -> Option<Rect> {
|
||||
/// The bounds of the visible art of `doc` with the objects that `left_out` picks hidden
|
||||
/// ([`hidden_nodes`]) and the ones in the art of the symbols that instances show taken out
|
||||
/// ([`without_nodes`]: symbol art is measured with its hidden objects). An instance of a symbol
|
||||
/// whose art is all picked or hidden is hidden too. The art of a dynamic symbol is measured whole:
|
||||
/// an instance can paint its objects, and finds them by their places in the art.
|
||||
/// whose art is all picked or hidden is hidden too. The drawn instances of a dynamic symbol that
|
||||
/// make the same appearance changes to its art are measured on a copy of the symbol of their own,
|
||||
/// in which each object is judged with those changes ([`as_drawn`]); the objects taken out of
|
||||
/// a dynamic symbol's art leave empty groups in their places, by which instances find the objects
|
||||
/// they change. Each copy keeps its symbol's 9-slice guides and natural size. An instance whose art
|
||||
/// goes through 9-slice guides at any depth is measured as its art placed through them
|
||||
/// ([`placed_instances`]), with the objects `left_out` picks hidden after placing: the guides cut
|
||||
/// the box of the whole art. Where an instance stays one, the art of a symbol with 9-slice guides,
|
||||
/// and of the symbols whose instances are in that art at any depth ([`sliced_art`]), is measured
|
||||
/// whole.
|
||||
fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Rect> {
|
||||
// The symbols instances show (the first of each name) that aren't dynamic.
|
||||
// The symbols instances show (the first of each name).
|
||||
let mut names = HashSet::new();
|
||||
let shown: Vec<(usize, &vectorcraft_doc::Symbol)> =
|
||||
doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).filter(|(_, s)| !s.dynamic).collect();
|
||||
let shown: Vec<usize> = doc.symbols.iter().enumerate().filter(|(_, s)| names.insert(s.name.as_str())).map(|(i, _)| i).collect();
|
||||
// The sets of appearance changes the drawn instances of each dynamic symbol make to its art;
|
||||
// `None` for a symbol with more than `MAX_ART_COPIES`, which is measured whole.
|
||||
let mut sets: HashMap<&str, Option<Vec<Vec<&SymbolOverride>>>> =
|
||||
shown.iter().filter_map(|i| doc.symbols.get(*i)).filter(|s| s.dynamic).map(|s| (s.name.as_str(), Some(Vec::new()))).collect();
|
||||
if !sets.is_empty() {
|
||||
let mut walked = HashSet::new();
|
||||
for l in &doc.layers {
|
||||
drawn_changes(doc, l, left_out, true, &mut walked, &mut sets);
|
||||
}
|
||||
}
|
||||
// Each set of changes gets a copy of its symbol, appended after the symbols, which the instances
|
||||
// that make those changes show instead.
|
||||
let variant = |symbol: &str, n: &Node| -> Option<String> {
|
||||
let k = sets.get(symbol)?.as_ref()?.iter().position(|c| *c == own_changes(n))?;
|
||||
Some(format!("{symbol}\u{0}{k}"))
|
||||
};
|
||||
let mut copies: Vec<(usize, &[&SymbolOverride])> = Vec::new();
|
||||
let remapped_doc = sets.values().flatten().any(|v| !v.is_empty()).then(|| {
|
||||
let mut d = doc.clone();
|
||||
for l in &mut d.layers {
|
||||
if let Some(n) = remapped(l, &variant) {
|
||||
*l = n;
|
||||
}
|
||||
}
|
||||
for s in &mut d.symbols {
|
||||
if let Some(n) = remapped(&s.art, &variant) {
|
||||
s.art = n;
|
||||
}
|
||||
}
|
||||
for i in &shown {
|
||||
let Some(s) = d.symbols.get(*i).cloned() else { continue };
|
||||
for (k, c) in sets.get(s.name.as_str()).into_iter().flatten().flatten().enumerate() {
|
||||
copies.push((d.symbols.len(), c.as_slice()));
|
||||
let name = format!("{}\u{0}{k}", s.name);
|
||||
copy_placement(&mut d, &s.name, &name);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name, ..s.clone() });
|
||||
}
|
||||
}
|
||||
d
|
||||
});
|
||||
let src = remapped_doc.as_ref().unwrap_or(doc);
|
||||
let whole = sliced_art(src);
|
||||
// The symbols to measure with the changes their instances make (`None` for a static symbol),
|
||||
// without the dynamic symbols measured whole.
|
||||
let entries: Vec<(usize, Option<&[&SymbolOverride]>)> = shown
|
||||
.iter()
|
||||
.filter_map(|i| src.symbols.get(*i).map(|s| (*i, s)))
|
||||
.filter(|(_, s)| !s.dynamic || sets.get(s.name.as_str()).is_some_and(Option::is_some))
|
||||
.map(|(i, s)| (i, s.dynamic.then_some(&[][..])))
|
||||
.chain(copies.iter().map(|(i, c)| (*i, Some(*c))))
|
||||
.collect();
|
||||
// The symbols whose art `left_out` leaves nothing of, those that only hold instances of such
|
||||
// symbols included.
|
||||
let mut empty: HashSet<&str> = HashSet::new();
|
||||
while let Some((_, s)) = shown.iter().find(|(_, s)| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty)) {
|
||||
while let Some(s) = entries.iter().find_map(|(i, c)| {
|
||||
src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && all_left_out(&s.art, left_out, &empty, *c, &mut Vec::new()))
|
||||
}) {
|
||||
empty.insert(&s.name);
|
||||
}
|
||||
let left_out =
|
||||
&|n: &Node| left_out(n) || matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if empty.contains(symbol.as_str()) && !has_effects(n));
|
||||
let layers = hidden_nodes(&doc.layers, left_out);
|
||||
let symbols: Vec<(usize, Arc<Node>)> = shown
|
||||
// The instances whose art goes through 9-slice guides, at any depth, are measured as their art
|
||||
// placed by those guides without the objects `left_out` picks, and without a clip group that
|
||||
// holds only such objects.
|
||||
let layers = hidden_nodes(&src.layers, left_out);
|
||||
let placing = holding(src, &whole);
|
||||
let layers = if placing.is_empty() {
|
||||
layers
|
||||
} else {
|
||||
let picked = &|n: &Node| {
|
||||
left_out(n) || matches!(n.kind, NodeKind::Group { clip: true, .. }) && all_left_out(n, left_out, &empty, None, &mut Vec::new())
|
||||
};
|
||||
let mut budget = 0;
|
||||
let from = layers.as_deref().unwrap_or(&src.layers);
|
||||
Some(from.iter().map(|l| placed_instances(src, l, &placing, picked, &mut budget, 0).unwrap_or_else(|| l.clone())).collect())
|
||||
};
|
||||
let symbols: Vec<(usize, Arc<Node>)> = entries
|
||||
.iter()
|
||||
.filter(|(_, s)| !empty.contains(s.name.as_str()))
|
||||
.filter_map(|(i, s)| without_nodes(&s.art, left_out).map(|art| (*i, art)))
|
||||
.filter_map(|(i, c)| {
|
||||
let s = src.symbols.get(*i).filter(|s| !empty.contains(s.name.as_str()) && !whole.contains(s.name.as_str()))?;
|
||||
without_nodes(&s.art, left_out, *c, &mut Vec::new()).map(|art| (*i, art))
|
||||
})
|
||||
.collect();
|
||||
if layers.is_none() && symbols.is_empty() {
|
||||
return vectorcraft_render::encode::art_bounds(doc);
|
||||
return vectorcraft_render::encode::art_bounds(src);
|
||||
}
|
||||
let mut d = doc.clone();
|
||||
let mut d = remapped_doc.unwrap_or_else(|| doc.clone());
|
||||
if let Some(layers) = layers {
|
||||
d.layers = layers;
|
||||
}
|
||||
@@ -486,22 +562,256 @@ fn bounds_without(doc: &Document, left_out: &dyn Fn(&Node) -> bool) -> Option<Re
|
||||
vectorcraft_render::encode::art_bounds(&d)
|
||||
}
|
||||
|
||||
/// Give symbol `to` of `d` the 9-slice guides and the natural size that symbol `from` has.
|
||||
fn copy_placement(d: &mut Document, from: &str, to: &str) {
|
||||
if let Some(guides) = d.symbol_nine_slice(from) {
|
||||
d.set_symbol_nine_slice(to, Some(guides));
|
||||
}
|
||||
if let Some(size) = d.unknown.get(SYMBOL_SIZES).and_then(|m| m.get(from)).cloned()
|
||||
&& let Some(sizes) = d.unknown.get_mut(SYMBOL_SIZES).and_then(Value::as_object_mut)
|
||||
{
|
||||
sizes.insert(to.to_string(), size);
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` with 9-slice guides, and of the symbols whose instances are in
|
||||
/// the art of those at any depth.
|
||||
fn sliced_art(doc: &Document) -> HashSet<&str> {
|
||||
let mut arts: HashMap<&str, &Arc<Node>> = HashMap::new();
|
||||
for s in &doc.symbols {
|
||||
arts.entry(s.name.as_str()).or_insert(&s.art);
|
||||
}
|
||||
let mut todo: Vec<&str> = arts.keys().copied().filter(|name| doc.symbol_nine_slice(name).is_some()).collect();
|
||||
let mut found = HashSet::new();
|
||||
while let Some(name) = todo.pop() {
|
||||
if !found.insert(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(&art) = arts.get(name) {
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
todo.push(symbol.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The names of the symbols of `doc` in `sliced`, and of the symbols whose art holds an instance of
|
||||
/// one of those at any depth.
|
||||
fn holding<'a>(doc: &'a Document, sliced: &HashSet<&'a str>) -> HashSet<&'a str> {
|
||||
let mut held_by: HashMap<&str, Vec<&str>> = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
for s in doc.symbols.iter().filter(|s| seen.insert(s.name.as_str())) {
|
||||
s.art.walk(&mut |n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
held_by.entry(symbol.as_str()).or_default().push(s.name.as_str());
|
||||
}
|
||||
});
|
||||
}
|
||||
let mut found = HashSet::new();
|
||||
let mut todo: Vec<&str> = sliced.iter().copied().collect();
|
||||
while let Some(name) = todo.pop() {
|
||||
if found.insert(name) {
|
||||
todo.extend(held_by.get(name).into_iter().flatten().copied());
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The most instances deep [`placed_instances`] places symbol art.
|
||||
const MAX_PLACED_DEPTH: usize = 32;
|
||||
|
||||
/// `n` with each instance of the `placing` symbols in it, and in its layers and groups at any depth,
|
||||
/// made a group with the instance's appearance that holds the instance's art (with its changes and
|
||||
/// stain) as `doc` places it, through the symbol's 9-slice guides when it has them, without the
|
||||
/// objects `picked` picks ([`without_nodes`]; hidden when it picks the whole art); `None` when `n`
|
||||
/// holds no such instance, or is hidden. An instance on a perspective grid, one
|
||||
/// [`MAX_PLACED_DEPTH`] instances deep, one in another kind of object (a blend, for example), and
|
||||
/// one whose art would take the objects placed in all (`budget`) past
|
||||
/// [`vectorcraft_doc::MAX_SYMBOL_NODES`] stay instances.
|
||||
/// Their symbols' art is measured whole, as taking objects out of it would change the box the
|
||||
/// guides cut, and the page can come out larger than the plot.
|
||||
fn placed_instances(
|
||||
doc: &Document,
|
||||
n: &Arc<Node>,
|
||||
placing: &HashSet<&str>,
|
||||
picked: &dyn Fn(&Node) -> bool,
|
||||
budget: &mut u64,
|
||||
depth: usize,
|
||||
) -> Option<Arc<Node>> {
|
||||
// Hidden art is not plotted, and placing it would take from the budget of the art that is.
|
||||
if !n.visible {
|
||||
return None;
|
||||
}
|
||||
match &n.kind {
|
||||
NodeKind::SymbolInstance { symbol, xf } => {
|
||||
if !placing.contains(symbol.as_str()) || depth >= MAX_PLACED_DEPTH || n.projection().is_some() {
|
||||
return None;
|
||||
}
|
||||
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
|
||||
let art = vectorcraft_doc::symbol_overrides::instance_art(&sym.art, n);
|
||||
let most = doc.symbol_slice_map(symbol, *xf).map_or(art.count_with_masks() as u64, |m| m.most_placed(&art, doc));
|
||||
if budget.saturating_add(most) > vectorcraft_doc::MAX_SYMBOL_NODES {
|
||||
return None;
|
||||
}
|
||||
let art = Arc::new(doc.place_symbol_art(symbol, &art, *xf)?);
|
||||
*budget = budget.saturating_add(art.count_with_masks() as u64);
|
||||
let art = placed_instances(doc, &art, placing, picked, budget, depth + 1).unwrap_or(art);
|
||||
let art = if picked(&art) {
|
||||
let mut hidden = (*art).clone();
|
||||
hidden.visible = false;
|
||||
Arc::new(hidden)
|
||||
} else {
|
||||
without_nodes(&art, picked, None, &mut Vec::new()).unwrap_or(art)
|
||||
};
|
||||
let mut g = (**n).clone();
|
||||
g.kind = NodeKind::Group { children: vec![art], clip: false };
|
||||
Some(Arc::new(g))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = placed_instances(doc, c, placing, picked, budget, depth)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The appearance changes instance `n` makes to its symbol's art, without those that change nothing.
|
||||
fn own_changes(n: &Node) -> Vec<&SymbolOverride> {
|
||||
n.extras().symbol_overrides.iter().filter(|o| !o.is_empty()).collect()
|
||||
}
|
||||
|
||||
/// `n` with each instance at any depth that `variant` gives another symbol (from the instance's
|
||||
/// symbol and the instance) made an instance of that symbol; `None` when none is.
|
||||
fn remapped(n: &Arc<Node>, variant: &dyn Fn(&str, &Node) -> Option<String>) -> Option<Arc<Node>> {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let name = variant(symbol, n)?;
|
||||
let mut m = (**n).clone();
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &mut m.kind {
|
||||
*symbol = name;
|
||||
}
|
||||
return Some(Arc::new(m));
|
||||
}
|
||||
let children = n.children()?;
|
||||
let mut out: Option<Vec<Arc<Node>>> = None;
|
||||
for (i, c) in children.iter().enumerate() {
|
||||
if let Some(new) = remapped(c, variant)
|
||||
&& let Some(slot) = out.get_or_insert_with(|| children.clone()).get_mut(i)
|
||||
{
|
||||
*slot = new;
|
||||
}
|
||||
}
|
||||
out.map(|c| {
|
||||
let mut m = (**n).clone();
|
||||
if let Some(children) = m.children_mut() {
|
||||
*children = c;
|
||||
}
|
||||
Arc::new(m)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `n` is hidden, picked by `left_out`, an instance of one of the `empty` symbols, or a
|
||||
/// layer or a group holding only such objects (its clipping path among them when it clips). A
|
||||
/// Shaper group, or a layer, group or instance with effects, fills or strokes of its own, is none
|
||||
/// of these unless it is hidden or picked.
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>) -> bool {
|
||||
/// of these unless it is hidden or picked. In the art of a dynamic symbol (`changed`, the changes
|
||||
/// an instance makes to it; `n` is at place `at`), each object is judged with those changes
|
||||
/// ([`as_drawn`]).
|
||||
fn all_left_out(n: &Node, left_out: &dyn Fn(&Node) -> bool, empty: &HashSet<&str>, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> bool {
|
||||
let m = as_drawn(n, changed, at);
|
||||
!n.visible
|
||||
|| left_out(n)
|
||||
|| !has_effects(n)
|
||||
|| left_out(&m)
|
||||
|| !has_effects(&m)
|
||||
&& n.extras().shaper.is_none()
|
||||
&& match &n.kind {
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().all(|c| all_left_out(c, left_out, empty)),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().enumerate().all(|(i, c)| {
|
||||
at.push(i as u32);
|
||||
let out = all_left_out(c, left_out, empty, changed, at);
|
||||
at.pop();
|
||||
out
|
||||
}),
|
||||
NodeKind::SymbolInstance { symbol, .. } => empty.contains(symbol.as_str()),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Add the sets of appearance changes that the instances in `n` and its subtree make to the art of
|
||||
/// the symbols `sets` names, each set once, and those of the instances in the art of the symbols the
|
||||
/// instances show (`walked`, the symbols already looked in). With `hidden` (in a layer), the
|
||||
/// instances that are hidden or that `left_out` picks, and those in such an object, are left out.
|
||||
/// In symbol art every instance counts, since an instance of the symbol can change the objects
|
||||
/// that hold it. A symbol with more than [`MAX_ART_COPIES`] sets gets `None`.
|
||||
fn drawn_changes<'a>(
|
||||
doc: &'a Document,
|
||||
n: &'a Node,
|
||||
left_out: &dyn Fn(&Node) -> bool,
|
||||
hidden: bool,
|
||||
walked: &mut HashSet<&'a str>,
|
||||
sets: &mut HashMap<&'a str, Option<Vec<Vec<&'a SymbolOverride>>>>,
|
||||
) {
|
||||
if hidden && (!n.visible || left_out(n)) {
|
||||
return;
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
let changes = own_changes(n);
|
||||
if let Some(entry) = sets.get_mut(symbol.as_str())
|
||||
&& !changes.is_empty()
|
||||
{
|
||||
let full = match entry {
|
||||
Some(list) if !list.contains(&changes) && list.len() < MAX_ART_COPIES => {
|
||||
list.push(changes);
|
||||
false
|
||||
}
|
||||
Some(list) => !list.contains(&changes),
|
||||
None => false,
|
||||
};
|
||||
if full {
|
||||
*entry = None;
|
||||
}
|
||||
}
|
||||
if walked.insert(symbol.as_str())
|
||||
&& let Some(s) = doc.symbols.iter().find(|s| s.name == *symbol)
|
||||
{
|
||||
drawn_changes(doc, &s.art, left_out, false, walked, sets);
|
||||
}
|
||||
}
|
||||
for c in n.children().into_iter().flatten() {
|
||||
drawn_changes(doc, c, left_out, hidden, walked, sets);
|
||||
}
|
||||
}
|
||||
|
||||
/// The most copies of one dynamic symbol's art [`bounds_without`] measures, one for each set of
|
||||
/// appearance changes its instances make; a symbol whose instances make more sets is measured whole.
|
||||
const MAX_ART_COPIES: usize = 64;
|
||||
|
||||
/// `n`, the object at place `at` of a symbol's art, with the appearance changes `changed` that an
|
||||
/// instance makes to it applied in their order; `n` itself for the art of a symbol that is not
|
||||
/// dynamic (`changed` is `None`) and when no change names `at`.
|
||||
fn as_drawn<'a>(n: &'a Node, changed: Option<&[&SymbolOverride]>, at: &[u32]) -> Cow<'a, Node> {
|
||||
let here: Vec<SymbolOverride> =
|
||||
changed.into_iter().flatten().filter(|o| o.path == at).map(|o| SymbolOverride { path: Vec::new(), ..(*o).clone() }).collect();
|
||||
if here.is_empty() {
|
||||
return Cow::Borrowed(n);
|
||||
}
|
||||
let mut m = n.clone();
|
||||
vectorcraft_doc::symbol_overrides::apply(&mut m, &here);
|
||||
Cow::Owned(m)
|
||||
}
|
||||
|
||||
/// Whether `n` has a visible effect, fill or stroke of its own, which the objects it holds can
|
||||
/// take part in.
|
||||
fn has_effects(n: &Node) -> bool {
|
||||
@@ -511,25 +821,32 @@ fn has_effects(n: &Node) -> bool {
|
||||
/// `n` without the objects that `left_out` picks in it, when it is a layer or a group, and in the
|
||||
/// layers and groups in it at any depth; `None` when it picks none of them. A clipping layer or
|
||||
/// group keeps its clipping path, its first object, and a Shaper group and a layer or group with
|
||||
/// effects, fills or strokes of its own keep all they hold.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool) -> Option<Arc<Node>> {
|
||||
/// effects, fills or strokes of its own keep all they hold. In the art of a dynamic symbol
|
||||
/// (`changed`, the changes an instance makes to it, as for [`all_left_out`]; `n` is at place
|
||||
/// `at`), each object is judged with those changes ([`as_drawn`]), and an object taken out leaves
|
||||
/// an empty group in its place.
|
||||
fn without_nodes(n: &Arc<Node>, left_out: &dyn Fn(&Node) -> bool, changed: Option<&[&SymbolOverride]>, at: &mut Vec<u32>) -> Option<Arc<Node>> {
|
||||
let (NodeKind::Layer { children, clip, .. } | NodeKind::Group { children, clip }) = &n.kind else { return None };
|
||||
if has_effects(n) || n.extras().shaper.is_some() {
|
||||
if has_effects(&as_drawn(n, changed, at)) || n.extras().shaper.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut changed = false;
|
||||
let mut taken = false;
|
||||
let kept: Vec<Arc<Node>> = children
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| {
|
||||
if left_out(c) && !(*clip && i == 0) {
|
||||
changed = true;
|
||||
return None;
|
||||
}
|
||||
Some(without_nodes(c, left_out).inspect(|_| changed = true).unwrap_or_else(|| c.clone()))
|
||||
at.push(i as u32);
|
||||
let out = if left_out(&as_drawn(c, changed, at)) && !(*clip && i == 0) {
|
||||
taken = true;
|
||||
changed.map(|_| Arc::new(Node::group(c.id, Vec::new())))
|
||||
} else {
|
||||
Some(without_nodes(c, left_out, changed, at).inspect(|_| taken = true).unwrap_or_else(|| c.clone()))
|
||||
};
|
||||
at.pop();
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
changed.then(|| {
|
||||
taken.then(|| {
|
||||
let mut new = (**n).clone();
|
||||
if let NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } = &mut new.kind {
|
||||
*children = kept;
|
||||
|
||||
@@ -12,8 +12,8 @@ use crate::DocState;
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
|
||||
write_or_return,
|
||||
ARTBOARD_PARAMS, Format, check_images_in, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output,
|
||||
writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
@@ -287,6 +287,8 @@ fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(C
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let doc = export_doc(st, f, p)?;
|
||||
// The objects written (all, or with selectedOnly the selected ones) are checked.
|
||||
check_images_in(cmd, f.id, &doc, crate::cmd::links::LinkBase::of(st), p)?;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
Ok((super::titled_for_export(&doc, st.path.as_deref(), f.id).map_or(doc, Cow::Owned), display_doc_title))
|
||||
}
|
||||
@@ -372,6 +374,8 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
// The selected objects' links are looked for from the document they are in.
|
||||
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
|
||||
// The encoder's warnings (options accepted but not applied, features approximated or left
|
||||
// out), as document.export reports them.
|
||||
let (bytes, mut warnings) = encode_with_warnings(&d, f.id, &without_artboards(&p))?;
|
||||
|
||||
@@ -393,8 +393,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
return Err(err(format!("can't open `{}`: {}", file_name(name), crate::cmd::place::dcs::LINK_ONLY)));
|
||||
}
|
||||
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
|
||||
// A `.ai` keeps the artboard its header gives; an EPS comes in on its page.
|
||||
let import = if matches!(format.id, "ai" | "ait") { vectorcraft_eps::import_ai } else { vectorcraft_eps::import_names };
|
||||
restore_or_import(editing, || {
|
||||
let r = vectorcraft_eps::import_names(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
|
||||
let r = import(bytes, opts.editing_data, opts.trust_editing_data, opts.legacy_names)
|
||||
.map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
|
||||
Ok((r.document, r.warnings))
|
||||
})?
|
||||
@@ -678,15 +680,28 @@ impl ReadFile {
|
||||
/// ([`super::importer`]).
|
||||
pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value, update_links: bool, low_res_proxy_eps: bool) -> Result<ReadFile> {
|
||||
let opts = LoadOptions::from_params("document.open", p)?;
|
||||
let mut loaded = match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
|
||||
None => load_with(name, bytes, &opts)?,
|
||||
let mut loaded = if opts.link_pages {
|
||||
linked_pages(name, bytes, path.as_deref(), &opts)?
|
||||
} else {
|
||||
match super::importer::pick(name, bytes, p)? {
|
||||
Some(plugin) => super::importer::load(name, bytes, &plugin, p)?,
|
||||
None => load_with(name, bytes, &opts)?,
|
||||
}
|
||||
};
|
||||
let links = crate::cmd::links::resolve(&mut loaded.doc, crate::cmd::links::LinkBase::file(path.as_deref()), update_links, low_res_proxy_eps);
|
||||
Session::refresh_text_bounds(&mut loaded.doc);
|
||||
Ok(ReadFile { loaded, opts, path, links })
|
||||
}
|
||||
|
||||
/// The PDF `name` (`bytes`, read from `path`) opened with `linkPages`: its pages as placed documents
|
||||
/// linked to them ([`super::pdfimport::linked_pages`]), named after the file.
|
||||
fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, opts: &LoadOptions) -> Result<Loaded> {
|
||||
let (mut doc, warnings) = super::pdfimport::linked_pages(name, bytes, path, opts)?;
|
||||
doc.title = file_name(name);
|
||||
let format = detect(name, bytes).ok_or_else(|| err(format!("can't open `{}`: not a PDF", file_name(name))))?;
|
||||
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
|
||||
}
|
||||
|
||||
/// The second half of [`open_bytes_with`]: open a file [`read_for_open`] read as the new active
|
||||
/// document → `document.open`'s result.
|
||||
pub fn open_read(s: &mut Session, file: ReadFile) -> Result<Value> {
|
||||
@@ -851,7 +866,9 @@ pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
/// CMYK TIFFs with an alpha channel, which the decoder can't read, become RGBA in the active color
|
||||
/// settings' CMYK, as do CMYK Photoshop documents, whose merged image is read ([`psdread`]).
|
||||
/// settings' CMYK, whichever of their extra channels is the alpha
|
||||
/// ([`vectorcraft_doc::cmyk::extra_samples_tiff_rgba`]), as do CMYK Photoshop documents, whose
|
||||
/// merged image is read ([`psdread`]).
|
||||
/// 1-bit TIFFs compressed with CCITT Group 3, which the decoder can't read either, become RGBA
|
||||
/// too ([`vectorcraft_doc::cmyk::group3_tiff_rgba`]).
|
||||
/// Grayscale TIFFs with an alpha channel or other extra channels, which the decoder can't read
|
||||
@@ -1059,16 +1076,32 @@ pub(super) fn raster_doc(name: &str, bytes: &[u8]) -> Result<Document> {
|
||||
let layer = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let xf = Affine::scale_non_uniform(sx, sy);
|
||||
let mut n = Node::new(
|
||||
let n = Node::new(
|
||||
id,
|
||||
NodeKind::Image(Box::new(ImageObject { key: key.clone(), width, height, xf, link: None, placement: Default::default(), pixels: None })),
|
||||
);
|
||||
let mut n = file_clipped(&mut d, n, psdread::clipping_path(bytes));
|
||||
n.name = Some(name.to_string());
|
||||
d.images.insert(key, blob);
|
||||
d.insert(Some(layer), 0, n).map_err(err)?;
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// Image `image` of `d` clipped by `clip`, the clipping path its file names in the image's pixel
|
||||
/// space (a PSD or PSB file's, [`psdread::clipping_path`]): a clip group of that path (even-odd,
|
||||
/// with no paint) and the image. Without one the image stays as it is.
|
||||
pub(crate) fn file_clipped(d: &mut Document, image: Node, clip: Option<vectorcraft_geom::PathData>) -> Node {
|
||||
let (Some(mut path), NodeKind::Image(im)) = (clip, &image.kind) else { return image };
|
||||
path.transform(im.xf);
|
||||
let none = vectorcraft_color::Paint::None;
|
||||
let mut clip = Node::path(d.alloc_id(), path, vectorcraft_doc::Appearance::basic(none.clone(), none, 0.0));
|
||||
if let NodeKind::Path { clipping, rule, .. } = &mut clip.kind {
|
||||
*clipping = true;
|
||||
*rule = vectorcraft_geom::FillRule::EvenOdd;
|
||||
}
|
||||
Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(clip), std::sync::Arc::new(image)], clip: true })
|
||||
}
|
||||
|
||||
/// Does this import note say that the file has something the document doesn't?
|
||||
fn is_loss(note: &str) -> bool {
|
||||
note == vectorcraft_pdf::OFF_ARTBOARD_NOTE || vectorcraft_eps::is_loss(note)
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -2,11 +2,15 @@
|
||||
//! and `file.place` read ([`LoadOptions`]), the pages they import and `document.pdfInfo` (pages,
|
||||
//! boxes, a thumbnail; one page for a PostScript file) for the Import PDF dialog.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{ColorMode, Document};
|
||||
use vectorcraft_doc::{Artboard, ColorMode, Document, LayerColor, LinkInfo, Node, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
use vectorcraft_pdf::{Choice, CropTo, ImportOptions, PdfError, TextAs};
|
||||
|
||||
use super::super::colormgmt::Grays;
|
||||
use super::super::place::document;
|
||||
use super::super::{Result, Session, bad, check_numbers, number_or, parse_range, text_param};
|
||||
use super::{err, source};
|
||||
|
||||
@@ -47,6 +51,9 @@ pub struct LoadOptions {
|
||||
/// A PDF or `.ai` saved with Preserve Editing opens from the VectorCraft document it carries;
|
||||
/// off, it opens as another app would open it, from the editing copy of its art or its pages.
|
||||
pub native: bool,
|
||||
/// Each page of a PDF opens as a placed document linked to that page of its file, on an
|
||||
/// artboard of its own, instead of as editable art (`linkPages`; see [`linked_pages`]).
|
||||
pub link_pages: bool,
|
||||
}
|
||||
|
||||
impl Default for LoadOptions {
|
||||
@@ -65,6 +72,7 @@ impl Default for LoadOptions {
|
||||
trust_editing_data: false,
|
||||
legacy_names: vectorcraft_eps::NameEncoding::default(),
|
||||
native: true,
|
||||
link_pages: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,8 +82,8 @@ impl LoadOptions {
|
||||
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
|
||||
/// `textAs` (`text` | `outlines`), `layers` (true | false), `hiddenLayers` (true | false),
|
||||
/// `editingData` (true | false | `always`),
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]) and `dxf` (the DXF
|
||||
/// import options).
|
||||
/// `legacyNameEncoding` (one of [`vectorcraft_eps::NameEncoding::LABELS`]), `linkPages` (true |
|
||||
/// false) and `dxf` (the DXF import options).
|
||||
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
|
||||
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
|
||||
None => None,
|
||||
@@ -115,6 +123,10 @@ impl LoadOptions {
|
||||
.and_then(vectorcraft_eps::NameEncoding::from_label)
|
||||
.ok_or_else(|| bad(cmd, format!("legacyNameEncoding must be one of {}", vectorcraft_eps::NameEncoding::LABELS.join(", "))))?,
|
||||
};
|
||||
let link_pages = match p.get("linkPages").filter(|v| !v.is_null()) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "linkPages must be true or false"))?,
|
||||
};
|
||||
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
|
||||
Ok(Self {
|
||||
pages,
|
||||
@@ -130,14 +142,15 @@ impl LoadOptions {
|
||||
trust_editing_data,
|
||||
legacy_names,
|
||||
native: true,
|
||||
link_pages,
|
||||
})
|
||||
}
|
||||
|
||||
/// Does the document read only part of the file, or read it differently (a page range, another
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries)?
|
||||
/// Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
|
||||
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
|
||||
pub fn is_partial(&self) -> bool {
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native
|
||||
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
|
||||
}
|
||||
|
||||
/// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible
|
||||
@@ -192,7 +205,7 @@ pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Docu
|
||||
}
|
||||
|
||||
/// [`page_document`] of `opened`, the PDF `bytes` already read.
|
||||
fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
pub(crate) fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err)
|
||||
}
|
||||
|
||||
@@ -201,6 +214,125 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions {
|
||||
ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() }
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or
|
||||
/// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to
|
||||
/// that page of the file as File › Place with Link places one ([`document::source`]). Each page
|
||||
/// gets an artboard of its `o.crop` box (its art's bounds for `bounding`, a blank page's crop box;
|
||||
/// a PDF-compatible `.ai` asked for its crop box gets its trim box, as it opens), in a row from the
|
||||
/// left with the gap a PDF's artboards open with, and a layer named after the page. On its trim box,
|
||||
/// a page shows its bleed box round the artboard, and the document's bleed is the pages' bleed (the
|
||||
/// widest on each side); the artboards are then the gap apart plus the bleed on both sides. The document opens
|
||||
/// in CMYK when most of the pages read in CMYK, unless `o.color_mode` names a mode. Refused without a
|
||||
/// path, for any other file, with a password (a linked page is read again without one), with
|
||||
/// `textAs: outlines` (a linked page shows the file's own type) and for a file over
|
||||
/// [`document::MAX_FILE`] → the document and the notes of reading its pages.
|
||||
pub(super) fn linked_pages(name: &str, bytes: &[u8], path: Option<&str>, o: &LoadOptions) -> Result<(Document, Vec<String>)> {
|
||||
const C: &str = "document.open";
|
||||
let file = super::file_name(name);
|
||||
if !document::is_pdf(name, bytes) {
|
||||
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
|
||||
}
|
||||
let path = path.ok_or_else(|| bad(C, "linkPages needs the file's path: linked pages are read from it"))?;
|
||||
if o.password.is_some() {
|
||||
return Err(bad(C, "linkPages can't open a file with a password: linked pages are read again without it"));
|
||||
}
|
||||
if o.text_as != TextAs::Text {
|
||||
return Err(bad(C, "linkPages can't be used with textAs: outlines: linked pages show the file's own type"));
|
||||
}
|
||||
if bytes.len() > document::MAX_FILE {
|
||||
return Err(bad(C, format!("linkPages: `{file}` is over {} MB", document::MAX_FILE >> 20)));
|
||||
}
|
||||
// The file is read once: every page is read from it.
|
||||
let opened = vectorcraft_pdf::open_pdf(bytes, None).map_err(err)?;
|
||||
let count = opened.page_count();
|
||||
let picked = match &o.pages {
|
||||
None => (0..count).collect(),
|
||||
Some(range) => parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?,
|
||||
};
|
||||
let bounding = o.crop == CropTo::Bounding;
|
||||
// A PDF-compatible `.ai` asked for its crop box opens on its trim boxes ([`LoadOptions::import_options`]).
|
||||
let crop = if o.crop == CropTo::Crop && opened.has_illustrator_data() { CropTo::Trim } else { o.crop };
|
||||
let mut doc = Document::new(1.0, 1.0);
|
||||
let board = doc.artboards.first().cloned().ok_or_else(|| err("a new document has no artboard"))?;
|
||||
doc.artboards.clear();
|
||||
doc.layers.clear();
|
||||
let link = crate::cmd::links::link_info(path, bytes);
|
||||
let gap = ImportOptions::default().artboard_gap;
|
||||
// Every page's object keeps the same one copy of the file.
|
||||
let shared = Arc::new(bytes.to_vec());
|
||||
// The file is hashed once for all its pages.
|
||||
let hash = link.hash.clone().unwrap_or_else(|| vectorcraft_doc::links::hash_bytes(bytes));
|
||||
let (mut warnings, mut cmyk_pages) = (Vec::<String>::new(), 0);
|
||||
// Each page as read, with its bleed (top, bottom, left, right). The pages are laid out once
|
||||
// the document's bleed is known.
|
||||
let mut read_pages = Vec::with_capacity(picked.len());
|
||||
for &index in &picked {
|
||||
let page = index as u32 + 1;
|
||||
let file_once = document::SharedFile { bytes: &shared, hash: &hash, opened: &opened };
|
||||
// On its trim box, a page shows its bleed box, the artboard on the trim box inside it, so
|
||||
// the art in the bleed shows and prints as bleed.
|
||||
let bleed = if crop == CropTo::Trim { opened.page_bleed(index) } else { None };
|
||||
let page_box = if bleed.is_some() { vectorcraft_doc::PageBox::Bleed } else { document::page_box(crop) };
|
||||
let read = |bounding| document::shared_source(name, file_once, Some(path), page, bounding, page_box, C);
|
||||
// A blank page has no art's bounds: it keeps its crop box, as opening it as art does.
|
||||
let (mut s, bounding) = match read(bounding) {
|
||||
Err(e) if bounding && e.to_string().contains("has no art to place") => (read(false)?, false),
|
||||
s => (s?, bounding),
|
||||
};
|
||||
// A page that is only a placeholder (a `.ai` saved without PDF compatibility) shows the
|
||||
// file's editing data, not a page of the file.
|
||||
if s.editing_data {
|
||||
return Err(bad(C, format!("linkPages: `{file}` isn't a PDF or a PDF-compatible .ai file")));
|
||||
}
|
||||
cmyk_pages += usize::from(s.color_mode == ColorMode::Cmyk);
|
||||
// The document's bleed is the widest of the pages' on each side.
|
||||
let sides = bleed.unwrap_or_default();
|
||||
for (side, b) in doc.setup.bleed.iter_mut().zip(sides) {
|
||||
*side = side.max(b.min(vectorcraft_doc::setup::MAX_BLEED));
|
||||
}
|
||||
for w in std::mem::take(&mut s.warnings) {
|
||||
if !warnings.contains(&w) {
|
||||
warnings.push(w);
|
||||
}
|
||||
}
|
||||
read_pages.push((page, s, bounding, sides));
|
||||
}
|
||||
// Each artboard is the gap from the one before plus the bleed on both sides of it: the
|
||||
// document's bleed, which export adds round every artboard, or a page's own bleed box where it
|
||||
// reaches farther. Neither page then shows or exports the other's art.
|
||||
let [_, _, doc_left, doc_right] = doc.setup.bleed;
|
||||
let mut x = 0.0;
|
||||
for (i, (page, s, bounding, [top, bottom, left, right])) in read_pages.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
x += doc_left.max(left);
|
||||
}
|
||||
let mut node = document::node(&mut doc, &s, LinkInfo { page: Some(page), ..link.clone() }, bounding);
|
||||
if let NodeKind::PlacedDocument(p) = &mut node.kind {
|
||||
p.xf = Affine::translate((x - left, -top));
|
||||
}
|
||||
node.name = Some(file.clone());
|
||||
let mut layer = Node::layer(doc.alloc_id(), &format!("Page {page}"), LayerColor::Preset((i % 27) as u8));
|
||||
if let NodeKind::Layer { children, .. } = &mut layer.kind {
|
||||
children.push(Arc::new(node));
|
||||
}
|
||||
doc.layers.push(Arc::new(layer));
|
||||
let rect = Rect::new(x, 0.0, x + s.frame.width() - left - right, s.frame.height() - top - bottom);
|
||||
doc.artboards.push(Artboard { id: i as u32 + 1, name: format!("Artboard {}", i + 1), rect, ..board.clone() });
|
||||
x = rect.x1 + doc_right.max(right) + gap;
|
||||
}
|
||||
// Pages painted mostly in CMYK read as CMYK documents, as opening them as art does: the
|
||||
// document opens in CMYK (with the CMYK default swatches) when most of its pages do.
|
||||
if cmyk_pages * 2 > picked.len() {
|
||||
doc.color_mode = ColorMode::Cmyk;
|
||||
let (swatches, groups) = vectorcraft_color::default_swatches(ColorMode::Cmyk.model());
|
||||
(doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into());
|
||||
}
|
||||
if let Some(mode) = o.color_mode.filter(|m| *m != doc.color_mode) {
|
||||
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, o.grays);
|
||||
}
|
||||
Ok((doc, warnings))
|
||||
}
|
||||
|
||||
const INFO: &str = "document.pdfInfo";
|
||||
|
||||
/// `document.pdfInfo`.
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
//! File › Place (#918): the merged image, the flattened picture every PSD carries after its layers,
|
||||
//! as a linked PSD shows. Written from Adobe's public "Photoshop File Formats Specification"
|
||||
//! (<https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/>). File › Open reads the
|
||||
//! layers with [`super::psdlayers`], which shares this reader.
|
||||
//! layers with [`super::psdlayers`], which shares this reader. The clipping path a document names
|
||||
//! ([`clipping_path`]) clips its merged image where it opens or is placed.
|
||||
//!
|
||||
//! Every mode Photoshop saves a merged image in is read: Bitmap, Grayscale, Duotone (as its
|
||||
//! grayscale data), Indexed, RGB, CMYK and Lab, at 1, 8, 16 and 32 bits per channel, stored raw,
|
||||
@@ -14,6 +15,7 @@
|
||||
use std::io::Read;
|
||||
|
||||
use vectorcraft_color::cms::{Lab, lab::lab_to_srgb};
|
||||
use vectorcraft_geom::{Anchor, AnchorKind, PathData, Point, SubPath};
|
||||
|
||||
/// Photoshop's colour modes (the header's numbers), as far as the merged image is concerned.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -154,30 +156,113 @@ pub(super) fn header<'a>(r: &mut Reader<'a>) -> Result<Header<'a>, String> {
|
||||
pub fn resolution(bytes: &[u8]) -> Option<(f64, f64)> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r).ok()?;
|
||||
let mut r = Reader::new(h.resources);
|
||||
while !r.rest().is_empty() {
|
||||
r.take(4).ok()?;
|
||||
let (_, _, data) = resources(h.resources, false).find(|(id, _, _)| *id == 0x03ed)?;
|
||||
let mut d = Reader::new(data);
|
||||
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the unit the
|
||||
// size is shown in.
|
||||
let mut axis = || -> Option<f64> {
|
||||
let v = f64::from(d.u32().ok()?) / 65536.0;
|
||||
let unit = d.u16().ok()?;
|
||||
d.u16().ok()?;
|
||||
Some(if unit == 2 { v * 2.54 } else { v })
|
||||
};
|
||||
Some((axis()?, axis()?))
|
||||
}
|
||||
|
||||
/// The image resource blocks of `resources`, in file order: each one's id, name (the bytes of its
|
||||
/// Pascal string) and data. Stops at the first block that is cut short. With `signed`, only the
|
||||
/// blocks whose signature is `8BIM` are given.
|
||||
fn resources(resources: &[u8], signed: bool) -> impl Iterator<Item = (u16, &[u8], &[u8])> {
|
||||
let mut r = Reader::new(resources);
|
||||
std::iter::from_fn(move || {
|
||||
if r.rest().is_empty() {
|
||||
return None;
|
||||
}
|
||||
let ours = r.take(4).ok()? == b"8BIM";
|
||||
let id = r.u16().ok()?;
|
||||
// A Pascal string padded to an even size, length byte included.
|
||||
let name = usize::from(r.u8().ok()?);
|
||||
r.take(name + (name + 1) % 2).ok()?;
|
||||
let len = usize::from(r.u8().ok()?);
|
||||
let name = r.take(len).ok()?;
|
||||
r.take((len + 1) % 2).ok()?;
|
||||
let size = usize::try_from(r.u32().ok()?).ok()?;
|
||||
let data = r.take(size).ok()?;
|
||||
r.take(size % 2).ok()?;
|
||||
if id == 0x03ed {
|
||||
let mut d = Reader::new(data);
|
||||
// Fixed 16.16 values, each with its unit (1: per inch, 2: per centimetre) and the
|
||||
// unit the size is shown in.
|
||||
let mut axis = || -> Option<f64> {
|
||||
let v = f64::from(d.u32().ok()?) / 65536.0;
|
||||
let unit = d.u16().ok()?;
|
||||
d.u16().ok()?;
|
||||
Some(if unit == 2 { v * 2.54 } else { v })
|
||||
};
|
||||
return Some((axis()?, axis()?));
|
||||
Some((ours, id, name, data))
|
||||
})
|
||||
.filter(move |(ours, ..)| *ours || !signed)
|
||||
.map(|(_, id, name, data)| (id, name, data))
|
||||
}
|
||||
|
||||
/// The resource naming the document's clipping path.
|
||||
const CLIPPING_PATH_NAME: u16 = 2999;
|
||||
|
||||
/// The saved paths' resource ids.
|
||||
const SAVED_PATHS: std::ops::RangeInclusive<u16> = 2000..=2997;
|
||||
|
||||
/// The clipping path a PSD or PSB file names, in its pixel space (x across its width, y down
|
||||
/// its height): the saved path (resources 2000 to 2997) whose name the clipping path resource
|
||||
/// (2999) gives, both `8BIM` resources. `None` when the document names none, names a path it doesn't have, or that path
|
||||
/// has no anchors or more records than [`vectorcraft_geom::path::MAX_READ_ANCHORS`]. Saved paths
|
||||
/// use the even-odd rule. A path whose initial fill record says the fill starts with all pixels
|
||||
/// begins with a subpath around the whole image, so its subpaths cut holes in it.
|
||||
pub fn clipping_path(bytes: &[u8]) -> Option<PathData> {
|
||||
let mut r = Reader::new(bytes);
|
||||
let h = header(&mut r).ok()?;
|
||||
let (_, _, named) = resources(h.resources, true).find(|(id, _, _)| *id == CLIPPING_PATH_NAME)?;
|
||||
// A Pascal string, then the flatness and a fill rule, which the specification says is ignored.
|
||||
let len = usize::from(*named.first()?);
|
||||
let name = named.get(1..1 + len)?;
|
||||
let (_, _, data) = resources(h.resources, true).find(|(id, n, _)| SAVED_PATHS.contains(id) && *n == name)?;
|
||||
// A path of more records than a document may hold anchors is left out before it is built.
|
||||
if data.len() / PATH_RECORD > vectorcraft_geom::path::MAX_READ_ANCHORS {
|
||||
return None;
|
||||
}
|
||||
let path = saved_path(data, f64::from(h.width), f64::from(h.height));
|
||||
(!path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
/// One record of a saved path: a selector, then 24 bytes.
|
||||
const PATH_RECORD: usize = 26;
|
||||
|
||||
/// The saved path of path records `data`, scaled to an image `width` × `height` pixels. Knot
|
||||
/// records come after their subpath's length record; one that comes before any, or past the knots
|
||||
/// a length record counts, is left out, as is a last record cut short.
|
||||
fn saved_path(data: &[u8], width: f64, height: f64) -> PathData {
|
||||
// A path point: a vertical, then a horizontal signed 8.24 fixed-point fraction of the image's
|
||||
// height and width.
|
||||
let fixed = |b: [u8; 4]| f64::from(i32::from_be_bytes(b)) / f64::from(1 << 24);
|
||||
let point = |[v0, v1, v2, v3, h0, h1, h2, h3]: [u8; 8]| Point::new(fixed([h0, h1, h2, h3]) * width, fixed([v0, v1, v2, v3]) * height);
|
||||
let mut subpaths: Vec<SubPath> = vec![];
|
||||
let mut all_pixels = false;
|
||||
// The knots the current subpath still takes.
|
||||
let mut left = 0usize;
|
||||
let (records, _) = data.as_chunks::<PATH_RECORD>();
|
||||
for &[s0, s1, ref body @ ..] in records {
|
||||
let [c0, c1, ..] = *body;
|
||||
let (points, _) = body.as_chunks::<8>();
|
||||
let [a, b, c] = [0, 1, 2].map(|i| points.get(i).copied().map_or(Point::ZERO, point));
|
||||
match u16::from_be_bytes([s0, s1]) {
|
||||
sel @ (0 | 3) => {
|
||||
left = usize::from(u16::from_be_bytes([c0, c1]));
|
||||
// Anchors are added as knots come: a count can claim more than follow.
|
||||
subpaths.push(SubPath::new(vec![], sel == 0));
|
||||
}
|
||||
sel @ (1 | 2 | 4 | 5) if left > 0 => {
|
||||
let Some(sp) = subpaths.last_mut() else { continue };
|
||||
left -= 1;
|
||||
let kind = if matches!(sel, 1 | 4) { AnchorKind::Smooth } else { AnchorKind::Corner };
|
||||
sp.anchors.push(Anchor { h_in: a, p: b, h_out: c, kind });
|
||||
}
|
||||
8 => all_pixels = [c0, c1] == [0, 1],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
subpaths.retain(|s| !s.anchors.is_empty());
|
||||
if all_pixels && !subpaths.is_empty() {
|
||||
let all = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, width, height));
|
||||
subpaths.splice(0..0, all.subpaths);
|
||||
}
|
||||
PathData::new(subpaths)
|
||||
}
|
||||
|
||||
/// Does the merged image keep its transparency in the first extra channel? Yes when the layer
|
||||
|
||||
@@ -891,6 +891,13 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let params = Value::Object(params);
|
||||
super::check_linked_images(cmd, plan.format.id, st, &own, ¶ms)?;
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
if let Some(d) = super::titled_for_export(&own, file, plan.format.id) {
|
||||
@@ -905,12 +912,7 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
|
||||
let base = crate::cmd::links::LinkBase::of(st);
|
||||
let relative = plan.path.as_deref().filter(|_| is_native(plan.format)).and_then(|p| crate::cmd::links::with_relative_paths(&own, base, p));
|
||||
let doc = relative.map_or(own, Arc::new);
|
||||
let mut params = plan.options.clone();
|
||||
if is_svg(plan.format) {
|
||||
// A save keeps hidden layers (not displayed) unless told otherwise; exports leave them out.
|
||||
params.entry("hiddenLayers").or_insert(Value::Bool(true));
|
||||
}
|
||||
let mut params = Value::Object(params);
|
||||
let mut params = params;
|
||||
if matches!(plan.format.id, "vectorcraft" | "template") {
|
||||
// Not remembered with the options: the preference decides each time it isn't given.
|
||||
params = with_compression_pref(&s.prefs, ¶ms);
|
||||
@@ -1307,7 +1309,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -1125,6 +1125,13 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
|
||||
};
|
||||
let crop = rows.iter().any(|r| r.format.id != "pdf");
|
||||
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
|
||||
// The file each item writes for each SVG row, before the folder is made or any row is written.
|
||||
let base = crate::cmd::links::LinkBase::of(s.doc()?);
|
||||
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
|
||||
for item in &items {
|
||||
super::check_images_in(C, r.format.id, &item.doc, base, &r.options_for(item.region, item.artboard)?)?;
|
||||
}
|
||||
}
|
||||
// Appearance of Black › Printing / Exporting for RGB raster rows.
|
||||
// Include Artboard Fill off: the encoders leave the background colors out.
|
||||
let fill = if o.include_artboard_fill == Some(false) { json!({ "includeArtboardFill": false }) } else { json!({}) };
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! params' top level or from an `svg` object (which wins), and the files an SVG export writes
|
||||
//! (one per artboard, plus the images it links to).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use vectorcraft_doc::Document;
|
||||
@@ -155,6 +157,18 @@ fn plan(doc: &Document, p: &Value) -> Result<(ExportOptions, Vec<Option<usize>>,
|
||||
Ok((opts, named.unwrap_or_else(|| vec![0]).into_iter().map(Some).collect(), chosen))
|
||||
}
|
||||
|
||||
/// The art the SVG files of `doc` with options `p` draw, as [`encode`] picks it: with chosen
|
||||
/// artboards, the art over each one; else all of `doc`. `None` when the options don't read.
|
||||
pub(super) fn drawn<'a>(doc: &'a Document, p: &Value) -> Option<Vec<Cow<'a, Document>>> {
|
||||
let (_, boards, chosen) = plan(doc, p).ok()?;
|
||||
if !chosen {
|
||||
return Some(vec![Cow::Borrowed(doc)]);
|
||||
}
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let rects: Vec<_> = boards.iter().flatten().filter_map(|b| doc.artboards.get(*b)).map(|a| a.rect).collect();
|
||||
Some(rects.into_iter().map(|r| Cow::Owned(super::export::art_over(doc, r, &mut renderer))).collect())
|
||||
}
|
||||
|
||||
/// What a save of `doc` as SVG (format `label`) with options `p` loses of several artboards: the
|
||||
/// file is one artboard and reopens as one, unless it carries the native document (Preserve
|
||||
/// Editing Capabilities).
|
||||
|
||||
@@ -202,6 +202,41 @@ fn a_16_bit_cmyk_tiff_with_alpha_places_at_16_bits() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK or grayscale TIFF whose alpha follows another extra sample opens and places with that
|
||||
/// alpha, at 8 and 16 bits, chunky and planar; a CMYK one is not kept as inks. A CMYK one with two
|
||||
/// more samples than its ExtraSamples values count does too.
|
||||
#[test]
|
||||
fn a_tiff_with_alpha_after_another_extra_sample_places_with_its_alpha() {
|
||||
let none = vec![0u16; 6];
|
||||
let full = vec![255u16; 6];
|
||||
let other = vec![9u16, 8, 7, 6, 5, 4];
|
||||
let alpha = vec![255u16, 128, 0, 255, 64, 1];
|
||||
let inks = [full.clone(), none.clone(), none.clone(), none.clone()];
|
||||
let cases = [
|
||||
("CMYK", 5, vec![full.clone(), none.clone(), none.clone(), none.clone(), other.clone(), alpha.clone()]),
|
||||
("CMYK, two more samples", 5, [&inks[..], &[other.clone(), alpha.clone(), other.clone(), full.clone()]].concat()),
|
||||
("gray", 1, vec![full.clone(), other.clone(), alpha.clone()]),
|
||||
];
|
||||
for (what, photometric, channels) in cases {
|
||||
for bits in [8, 16] {
|
||||
let wide: Vec<Vec<u16>> = channels.iter().map(|ch| ch.iter().map(|v| if bits == 16 { v * 257 } else { *v }).collect()).collect();
|
||||
for planar in [false, true] {
|
||||
let what = format!("{what}, {bits} bits, planar {planar}");
|
||||
let file = hand_tiff(photometric, bits, &[0, 2], planar, &wide);
|
||||
let (inks, rgba) = kept(&what, &file);
|
||||
assert_eq!(inks, None, "{what}: shown as RGB with its alpha");
|
||||
let alphas: Vec<u8> = rgba.iter().skip(3).step_by(4).copied().collect();
|
||||
assert_eq!(alphas, [255, 128, 0, 255, 64, 1], "{what}: the alpha is the second extra sample");
|
||||
let mut s = session(100.0, 100.0, 1);
|
||||
s.execute("file.place", &json!({"name": "a.tif", "dataBase64": vectorcraft_format::base64_encode(&file)})).unwrap();
|
||||
let blob = &s.doc().unwrap().doc.images[&image_of(&s).key];
|
||||
let placed = image::load_from_memory(&blob.bytes).unwrap().to_rgba8().into_raw();
|
||||
assert_eq!(placed, rgba, "{what}: Place reads it as Open does");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A planar TIFF whose header claims more strips than the decoder can count (here 2^31 + 1 rows
|
||||
/// a strip each, times 5 planes) is refused as too large to draw, without a panic.
|
||||
#[test]
|
||||
|
||||
@@ -1160,6 +1160,91 @@ fn an_ai_file_saved_without_its_pdf_part_places_from_its_editing_data() {
|
||||
assert!(e.contains("placeholder"), "{e}");
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` refuses a `.ai` saved without PDF compatibility, whose page is
|
||||
/// only a placeholder, and opens a PDF-compatible one.
|
||||
#[test]
|
||||
fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpages-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let file = |name: &str, page: &str| {
|
||||
let path = d.join(name);
|
||||
std::fs::write(&path, ai::ai(&compressed(&ai::sample_data()), page)).unwrap();
|
||||
path.to_string_lossy().to_string()
|
||||
};
|
||||
let (plain, compatible) = (file("plain.ai", PLACEHOLDER), file("compatible.ai", "0 g 10 10 40 40 re f"));
|
||||
let mut s = Session::new();
|
||||
let e = s.execute("document.open", &json!({"path": plain, "linkPages": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("isn't a PDF or a PDF-compatible .ai file"), "{e}");
|
||||
assert!(s.documents().is_empty(), "nothing opened");
|
||||
s.execute("document.open", &json!({"path": compatible, "linkPages": true})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.has_placed());
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
|
||||
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
|
||||
#[test]
|
||||
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("trimmed.ai");
|
||||
let boxes = "/TrimBox [10 10 190 90] /BleedBox [4 2 196 98]";
|
||||
std::fs::write(&path, ai::ai_with(&compressed(&ai::sample_data()), "0 g 10 10 40 40 re f", boxes)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let board = doc.artboards[0].rect;
|
||||
assert_eq!((board.width(), board.height()), (180.0, 80.0), "the trim box");
|
||||
assert_eq!(doc.setup.bleed, [8.0, 8.0, 6.0, 6.0], "top, bottom, left, right");
|
||||
// The page shows its bleed box, so the art in the bleed is kept.
|
||||
let placed = doc.layers[0].children().unwrap()[0].clone();
|
||||
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
|
||||
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
|
||||
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_pages_on_their_trim_boxes_keep_the_bleed_between_the_artboards() {
|
||||
// Two 100 pt trim boxes: the first with 60 pt of bleed on each side, the second with 80 pt on
|
||||
// its left, more than the largest document bleed (72 pt).
|
||||
let entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
|
||||
let first = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 220.0, 220.0]),
|
||||
trim: Some([60.0, 60.0, 160.0, 160.0]),
|
||||
entries,
|
||||
..PdfPage::new(220.0, 220.0, "0 g 0 0 220 220 re f")
|
||||
};
|
||||
let second = PdfPage {
|
||||
bleed: Some([0.0, 0.0, 240.0, 220.0]),
|
||||
trim: Some([80.0, 60.0, 180.0, 160.0]),
|
||||
..PdfPage::new(240.0, 220.0, "0 g 0 0 240 220 re f")
|
||||
};
|
||||
let d = std::env::temp_dir().join(format!("vc-ailinkpagesgap-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
let path = d.join("pages.ai");
|
||||
std::fs::write(&path, pdf_with(&[first, second], &["<< /Length 4 >>\nstream\ndata\nendstream"], None)).unwrap();
|
||||
let path = path.to_string_lossy().to_string();
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"path": path, "linkPages": true})).unwrap();
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
assert_eq!(doc.setup.bleed, [60.0, 60.0, 72.0, 60.0], "top, bottom, left, right");
|
||||
// The first page's bleed ends at 160; the second's starts 36 pt later, 80 pt left of its trim box.
|
||||
let boards: Vec<(f64, f64)> = doc.artboards.iter().map(|a| (a.rect.x0, a.rect.x1)).collect();
|
||||
assert_eq!(boards, [(0.0, 100.0), (276.0, 376.0)]);
|
||||
let shown: Vec<f64> = doc
|
||||
.layers
|
||||
.iter()
|
||||
.map(|l| match &l.children().unwrap()[0].kind {
|
||||
NodeKind::PlacedDocument(p) => p.xf.translation().x,
|
||||
k => panic!("{k:?}"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(shown, [-60.0, 196.0], "each page's bleed box round its artboard");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
/// A page of text alone, as text-only art has in its PDF part: no path is painted.
|
||||
const TEXT_ART: &str = "BT /F1 36 Tf 10 40 Td (Text only) Tj ET";
|
||||
|
||||
|
||||
@@ -277,3 +277,17 @@ fn ps_and_epsf_files_open_and_place() {
|
||||
let e = writable_format(None, Some("out.ps")).unwrap_err();
|
||||
assert_eq!(e, "PostScript files can be opened but not written (see document.formats)");
|
||||
}
|
||||
|
||||
/// A program in the legacy `.ai` format with a template box and no art size (version 3) opens as a
|
||||
/// `.ai` or `.ait` on a US Letter artboard around the box's center, and as an EPS on its bounding
|
||||
/// box.
|
||||
#[test]
|
||||
fn a_legacy_ai_program_opens_on_its_artboard_and_an_eps_on_its_page() {
|
||||
let program = b"%!PS-Adobe-2.0 EPSF-1.2\n%%Creator: a script\n%%BoundingBox: 10 10 30 30\n%AI3_TemplateBox: 100 100 100 100\n\
|
||||
%%EndComments\n%%BeginProlog\n/m {moveto} def /L {lineto} def /f {closepath fill} def /k {setcmykcolor} def\n\
|
||||
%%EndProlog\n%%BeginSetup\n%%EndSetup\n0 0 0 1 k\n10 10 m\n30 10 L\n30 30 L\n10 30 L\nf\n%%PageTrailer\nshowpage\n%%Trailer\n%%EOF\n";
|
||||
for (name, size) in [("old.ai", (612.0, 792.0)), ("old.ait", (612.0, 792.0)), ("old.eps", (20.0, 20.0))] {
|
||||
let r = load(name, program).unwrap_or_else(|e| panic!("{name}: {e}"));
|
||||
assert_eq!(r.doc.artboards[0].rect.size(), vectorcraft_geom::Size::new(size.0, size.1), "{name}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,6 +254,236 @@ fn a_plot_of_the_arts_bounds_leaves_out_images_in_symbol_art() {
|
||||
}
|
||||
}
|
||||
|
||||
/// In the art of a dynamic symbol a placed image and a path that paints nothing are left out as
|
||||
/// well, until an instance paints the path, and a document whose only other visible art is an
|
||||
/// instance of a dynamic symbol of an image is refused.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_images_in_dynamic_symbol_art() {
|
||||
let mut s = two_boards();
|
||||
let plot = |s: &mut Session| s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).map(|v| bytes(&v));
|
||||
let bounds = |s: &Session| super::export_art_bounds(&s.doc().unwrap().doc, "hpgl").unwrap();
|
||||
let same = |a: vectorcraft_geom::Rect, b: vectorcraft_geom::Rect| {
|
||||
[(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-6)
|
||||
};
|
||||
let printing = s.doc().unwrap().doc.layers[0].id;
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let mut png = vec![];
|
||||
image::DynamicImage::new_rgb8(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let square = s.execute("shape.rectangle", &json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
let bare = s.execute("shape.rectangle", &json!({"x": 500, "y": -400, "width": 20, "height": 20})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [bare], "none": true})).unwrap();
|
||||
let before = bounds(&s);
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Mixed", "ids": [image, square, bare], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let after = bounds(&s);
|
||||
assert!(same(before, after), "{before:?} {after:?}");
|
||||
|
||||
// A change of the path's blending mode leaves it painting nothing; once the instance paints the
|
||||
// path, the path is measured.
|
||||
let art = s.doc().unwrap().doc.symbols[0].art.clone();
|
||||
let x0 = |c: &std::sync::Arc<vectorcraft_doc::Node>| c.visual_bounds().map_or(f64::MIN, |b| b.x0);
|
||||
let at = (0..art.children().unwrap().len()).max_by(|a, b| x0(&art.children().unwrap()[*a]).total_cmp(&x0(&art.children().unwrap()[*b]))).unwrap();
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "blend": "multiply"})).unwrap();
|
||||
let blended = bounds(&s);
|
||||
assert!(same(before, blended), "{before:?} {blended:?}");
|
||||
s.execute("symbol.instance.setAppearance", &json!({"id": inst, "path": [at], "stroke": "#000000"})).unwrap();
|
||||
let painted = bounds(&s);
|
||||
assert!(painted.x1 > 500.0 && painted.y0 < -390.0, "{painted:?}");
|
||||
// A later change to the same object, as a file can hold, takes the paint off again.
|
||||
{
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let mut overrides = n.extras().symbol_overrides.clone();
|
||||
overrides.push(vectorcraft_doc::SymbolOverride { path: vec![at as u32], opacity: Some(0.0), ..Default::default() });
|
||||
n.extras_mut().symbol_overrides = overrides.clone();
|
||||
let taken_off = bounds(&s);
|
||||
assert!(same(before, taken_off), "{before:?} {taken_off:?}");
|
||||
overrides.pop();
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides = overrides;
|
||||
}
|
||||
// Another instance, far above, that doesn't paint the path is measured without it, whether or
|
||||
// not the first one paints it.
|
||||
let other = s.execute("symbol.place", &json!({"name": "Mixed", "x": 0, "y": -5000})).unwrap()["id"].clone();
|
||||
let with_paint = bounds(&s);
|
||||
s.execute("symbol.instance.reset", &json!({"ids": [inst]})).unwrap();
|
||||
let without_paint = bounds(&s);
|
||||
assert!((with_paint.y0 - without_paint.y0).abs() < 1e-6, "{with_paint:?} {without_paint:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let undone = bounds(&s);
|
||||
assert!(same(undone, with_paint), "{undone:?} {with_paint:?}");
|
||||
s.execute("select.set", &json!({"ids": [other]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
|
||||
s.execute("select.set", &json!({"ids": [inst]})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": printing, "visible": false})).unwrap();
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
s.execute("symbol.new", &json!({"name": "Image", "ids": [image], "type": "dynamic"})).unwrap();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
|
||||
// An instance that brings a group at 0% opacity back to full opacity still draws nothing when
|
||||
// the group holds only an image.
|
||||
let image = s.execute("file.place", &json!({"name": "far.png", "dataBase64": b64(&png), "at": [-600, 800]})).unwrap()["ids"][0].clone();
|
||||
let group = s.execute("object.group", &json!({"ids": [image]})).unwrap()["id"].clone();
|
||||
s.execute("transparency.set", &json!({"ids": [group], "opacity": 0})).unwrap();
|
||||
let inst = s.execute("symbol.new", &json!({"name": "Clear", "ids": [group], "type": "dynamic"})).unwrap()["id"].clone();
|
||||
let id = vectorcraft_doc::NodeId(inst.as_u64().unwrap());
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
d.node_mut(id).unwrap().extras_mut().symbol_overrides =
|
||||
[vec![], vec![0]].into_iter().map(|path| vectorcraft_doc::SymbolOverride { path, opacity: Some(1.0), ..Default::default() }).collect();
|
||||
let e = plot(&mut s).unwrap_err().to_string();
|
||||
assert!(e.contains("no visible art"), "{e}");
|
||||
}
|
||||
|
||||
/// A rectangle filled black, or one that paints nothing.
|
||||
fn plot_rect(d: &mut vectorcraft_doc::Document, r: vectorcraft_geom::Rect, painted: bool) -> std::sync::Arc<vectorcraft_doc::Node> {
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
let fill = if painted { Paint::solid(Color::BLACK) } else { Paint::None };
|
||||
let appearance = vectorcraft_doc::Appearance::basic(fill, Paint::None, 0.0);
|
||||
std::sync::Arc::new(vectorcraft_doc::Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), appearance))
|
||||
}
|
||||
|
||||
/// An instance of symbol `symbol` placed by `xf`.
|
||||
fn plot_instance(d: &mut vectorcraft_doc::Document, symbol: &str, xf: vectorcraft_geom::Affine) -> vectorcraft_doc::Node {
|
||||
vectorcraft_doc::Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf })
|
||||
}
|
||||
|
||||
/// Symbol `name` holding `art` in a group.
|
||||
fn plot_symbol(d: &mut vectorcraft_doc::Document, name: &str, art: Vec<std::sync::Arc<vectorcraft_doc::Node>>, dynamic: bool) {
|
||||
let group = vectorcraft_doc::Node::group(d.alloc_id(), art);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { dynamic, name: name.into(), art: std::sync::Arc::new(group) });
|
||||
}
|
||||
|
||||
/// Puts `n` on the first layer of `d`.
|
||||
fn plot_on_layer(d: &mut vectorcraft_doc::Document, n: vectorcraft_doc::Node) {
|
||||
std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().push(std::sync::Arc::new(n));
|
||||
}
|
||||
|
||||
/// The art of a symbol with 9-slice guides, static or dynamic, is placed whole and measured
|
||||
/// without what the plot leaves out: a frame that paints nothing sets where the guides place the
|
||||
/// painted art inside it, and is not measured itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_places_9_slice_symbol_art_by_all_of_it() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
// Static and dynamic, and with the instance's fill staining the art.
|
||||
for (dynamic, stained) in [(false, false), (true, false), (false, true)] {
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let square = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Panel", vec![frame, square], dynamic);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
if stained {
|
||||
let red = vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0));
|
||||
wide.appearance = vectorcraft_doc::Appearance::basic(red, vectorcraft_color::Paint::None, 0.0).into();
|
||||
}
|
||||
plot_on_layer(&mut d, wide);
|
||||
// Scaled 2 times across, the middle column maps x to 3x - 50: the square draws from x 70
|
||||
// to 130.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "dynamic: {dynamic}, stained: {stained}, {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// In art placed through 9-slice guides, a group with a fill of its own keeps the path it paints,
|
||||
/// which paints nothing by itself.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_keeps_what_a_group_paints_in_9_slice_symbol_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let bare = plot_rect(&mut d, Rect::new(40.0, 40.0, 60.0, 60.0), false);
|
||||
let mut group = vectorcraft_doc::Node::group(d.alloc_id(), vec![bare]);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
group.appearance = vectorcraft_doc::Appearance::basic(black, vectorcraft_color::Paint::None, 0.0).into();
|
||||
plot_symbol(&mut d, "Panel", vec![frame, std::sync::Arc::new(group)], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the group's path is plotted");
|
||||
let exact = [(b.x0, 70.0), (b.y0, 40.0), (b.x1, 130.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact, "{b:?}");
|
||||
}
|
||||
|
||||
/// A symbol without guides in the art of a symbol with 9-slice guides is measured without what the
|
||||
/// plot leaves out, in the placed art and in an instance of its own.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_leaves_out_unplotted_art_of_symbols_in_9_slice_art() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let far = plot_rect(&mut d, Rect::new(45.0, -500.0, 55.0, -480.0), false);
|
||||
let dot = plot_rect(&mut d, Rect::new(45.0, 45.0, 55.0, 55.0), true);
|
||||
plot_symbol(&mut d, "Dot", vec![far, dot], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Dot", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], false);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
plot_on_layer(&mut d, wide);
|
||||
let near = |b: Rect, e: [f64; 4]| [b.x0, b.y0, b.x1, b.y1].iter().zip(e).all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
// The dot's box is in the middle column, which maps x to 3x - 50.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 115.0, 55.0]), "{b:?}");
|
||||
let own = plot_instance(&mut d, "Dot", Affine::translate((200.0, 0.0)));
|
||||
plot_on_layer(&mut d, own);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(near(b, [85.0, 45.0, 255.0, 55.0]), "{b:?}");
|
||||
}
|
||||
|
||||
/// The copy of a dynamic symbol that an instance's changes are measured on keeps the symbol's
|
||||
/// 9-slice guides.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_changed_9_slice_instances_by_their_guides() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bar = plot_rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), true);
|
||||
plot_symbol(&mut d, "Bar", vec![bar], false);
|
||||
let frame = plot_rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), false);
|
||||
let inner = std::sync::Arc::new(plot_instance(&mut d, "Bar", Affine::IDENTITY));
|
||||
plot_symbol(&mut d, "Panel", vec![frame, inner], true);
|
||||
d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default()));
|
||||
let mut wide = plot_instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
|
||||
wide.extras_mut().symbol_overrides =
|
||||
vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(vectorcraft_color::Paint::None), ..Default::default() }];
|
||||
plot_on_layer(&mut d, wide);
|
||||
// The bar crosses the left guide and is placed by the middle column's map, x to 3x - 50: it
|
||||
// draws from x -20 to 160.
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
let exact = |b: Rect| [(b.x0, -20.0), (b.y0, 40.0), (b.x1, 160.0), (b.y1, 60.0)].iter().all(|(a, e)| (a - e).abs() < 1e-6);
|
||||
assert!(exact(b), "{b:?}");
|
||||
// The same instance in the art of a symbol without guides.
|
||||
let wide = std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().unwrap().pop().unwrap();
|
||||
plot_symbol(&mut d, "Holder", vec![wide], false);
|
||||
let holder = plot_instance(&mut d, "Holder", Affine::IDENTITY);
|
||||
plot_on_layer(&mut d, holder);
|
||||
let b = super::export_art_bounds(&d, "hpgl").unwrap();
|
||||
assert!(exact(b), "{b:?}");
|
||||
}
|
||||
|
||||
/// An instance in a dynamic symbol's art, in a group at 0% opacity that an instance of the symbol
|
||||
/// brings back to full opacity, is measured with the paint it gives its own symbol's art.
|
||||
#[test]
|
||||
fn a_plot_of_the_arts_bounds_measures_instances_that_an_instance_brings_back() {
|
||||
use vectorcraft_geom::{Affine, Rect};
|
||||
let mut d = vectorcraft_doc::Document::new(400.0, 400.0);
|
||||
let bare = plot_rect(&mut d, Rect::new(300.0, 300.0, 320.0, 320.0), false);
|
||||
plot_symbol(&mut d, "Inner", vec![bare], true);
|
||||
let mut inner = plot_instance(&mut d, "Inner", Affine::IDENTITY);
|
||||
let black = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
|
||||
inner.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![0], fill: Some(black), ..Default::default() }];
|
||||
plot_symbol(&mut d, "Outer", vec![std::sync::Arc::new(inner)], true);
|
||||
std::sync::Arc::make_mut(&mut d.symbols[1].art).opacity = 0.0;
|
||||
let mut outer = plot_instance(&mut d, "Outer", Affine::IDENTITY);
|
||||
outer.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { path: vec![], opacity: Some(1.0), ..Default::default() }];
|
||||
plot_on_layer(&mut d, outer);
|
||||
let b = super::export_art_bounds(&d, "hpgl").expect("the painted rectangle is plotted");
|
||||
assert!((b.x0 - 300.0).abs() < 1e-6 && (b.x1 - 320.0).abs() < 1e-6, "{b:?}");
|
||||
}
|
||||
|
||||
/// A placed image with a Vector Halftone effect is measured when the effect makes dots, and left
|
||||
/// out when it would take more cells than the effect makes.
|
||||
#[test]
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
//! Reading Photoshop documents (#918): the merged image of every colour mode, depth and
|
||||
//! compression, PSB files, transparency, the resolution, and damaged files refused without a panic.
|
||||
//! compression, PSB files, transparency, the resolution, the clipping path, and damaged files
|
||||
//! refused without a panic.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind};
|
||||
|
||||
use super::psdread::{decode, is_psd, resolution};
|
||||
use super::psdread::{clipping_path, decode, is_psd, resolution};
|
||||
use super::*;
|
||||
|
||||
/// A Photoshop document built from its parts: `version` 1 (PSD) or 2 (PSB), the header's fields,
|
||||
@@ -260,6 +262,221 @@ fn pdd_files_open_and_place() {
|
||||
assert!(format_for_name("x.pdd").is_none() && writable_format(None, Some("x.pdd")).is_err(), "an export to .pdd is refused as before");
|
||||
}
|
||||
|
||||
/// An image resource block: `8BIM`, `id`, `name` as a Pascal string padded to an even size, then
|
||||
/// `data` padded to an even size.
|
||||
fn resource(id: u16, name: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
let mut r = b"8BIM".to_vec();
|
||||
r.extend(id.to_be_bytes());
|
||||
r.push(name.len() as u8);
|
||||
r.extend(name);
|
||||
if name.len().is_multiple_of(2) {
|
||||
r.push(0);
|
||||
}
|
||||
r.extend((data.len() as u32).to_be_bytes());
|
||||
r.extend(data);
|
||||
if !data.len().is_multiple_of(2) {
|
||||
r.push(0);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// A path point record's 8 bytes: `[x, y]` as fractions of the image's width and height, stored
|
||||
/// vertical first as signed 8.24 fixed-point numbers.
|
||||
fn point([x, y]: [f64; 2]) -> Vec<u8> {
|
||||
[y, x].iter().flat_map(|v| ((v * f64::from(1 << 24)).round() as i32).to_be_bytes()).collect()
|
||||
}
|
||||
|
||||
/// A saved path's records: the fill rule record, an initial fill record saying whether the fill
|
||||
/// starts with all pixels, then each subpath (closed or not) of corner knots without handles.
|
||||
fn saved_path(all_pixels: bool, subpaths: &[(bool, &[[f64; 2]])]) -> Vec<u8> {
|
||||
let record = |selector: u16, body: Vec<u8>| {
|
||||
let mut r = selector.to_be_bytes().to_vec();
|
||||
r.extend(body);
|
||||
r.resize(26, 0);
|
||||
r
|
||||
};
|
||||
let mut d = record(6, vec![]);
|
||||
d.extend(record(8, vec![0, u8::from(all_pixels)]));
|
||||
for (closed, knots) in subpaths {
|
||||
d.extend(record(if *closed { 0 } else { 3 }, (knots.len() as u16).to_be_bytes().to_vec()));
|
||||
for k in *knots {
|
||||
d.extend(record(if *closed { 2 } else { 5 }, [point(*k), point(*k), point(*k)].concat()));
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The clipping path resource (2999) naming the saved path `name`, with a flatness of 0 and the
|
||||
/// fill rule left as it is.
|
||||
fn clipping_name(name: &[u8]) -> Vec<u8> {
|
||||
let mut d = vec![name.len() as u8];
|
||||
d.extend(name);
|
||||
d.extend([0; 6]);
|
||||
resource(2999, b"", &d)
|
||||
}
|
||||
|
||||
/// A 100 × 50 pixel red RGB document with `resources`, flat or with a layer count of 0.
|
||||
fn red_psd(resources: &[u8]) -> Vec<u8> {
|
||||
psd(1, 3, (100, 50), 8, 3, &[], resources, &[], &raw(&[&[255; 5000], &[0; 5000], &[0; 5000]]))
|
||||
}
|
||||
|
||||
/// The triangle saved as "Outline", another path saved as "Other", and the clipping path naming
|
||||
/// "Outline".
|
||||
fn triangle_resources() -> Vec<u8> {
|
||||
let other = saved_path(false, &[(true, &[[0.0, 0.0], [0.1, 0.0], [0.1, 0.1]])]);
|
||||
let outline = saved_path(false, &[(true, &[[0.5, 0.0], [1.0, 1.0], [0.0, 1.0]])]);
|
||||
[resource(2000, b"Other", &other), resource(2001, b"Outline", &outline), clipping_name(b"Outline")].concat()
|
||||
}
|
||||
|
||||
/// The clip group a PSD file comes in as: its clipping path's anchors (pt), whether that path
|
||||
/// uses the even-odd rule, and the image it clips.
|
||||
fn clip_group(d: &Document, id: NodeId) -> (Vec<[f64; 2]>, bool, NodeId) {
|
||||
let Some(NodeKind::Group { children, clip: true }) = d.node(id).map(|n| &n.kind) else { panic!("not a clip group: {:?}", d.node(id)) };
|
||||
let [path, image] = &children[..] else { panic!("{} children", children.len()) };
|
||||
let NodeKind::Path { path: p, rule, clipping: true, .. } = &path.kind else { panic!("not a clipping path") };
|
||||
assert!(matches!(image.kind, NodeKind::Image(_)));
|
||||
let anchors = p.anchors().map(|(_, _, a)| [a.p.x, a.p.y]).collect();
|
||||
(anchors, *rule == vectorcraft_geom::FillRule::EvenOdd, image.id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_path_clips_the_merged_image_on_place_and_open() {
|
||||
let f = red_psd(&triangle_resources());
|
||||
let triangle = vec![[50.0, 0.0], [100.0, 50.0], [0.0, 50.0]];
|
||||
let data = vectorcraft_format::base64_encode(&f);
|
||||
// Place: one clip group of the named path, not the other, at 100 % (72 ppi: a pixel a point).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [50, 25]})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
let (anchors, even_odd, image) = clip_group(&s.doc().unwrap().doc, id);
|
||||
assert_eq!((anchors, even_odd), (triangle.clone(), true));
|
||||
assert_eq!(r["image"], image.0, "{r}");
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(100.0), Some(50.0)));
|
||||
// Open with layers off, and a flat file opened with layers on, as its merged image.
|
||||
for params in [json!({"layers": false}), json!({})] {
|
||||
s.execute("document.open", &merge(json!({"name": "cut.psd", "dataBase64": data}), params.clone())).unwrap();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let top = d.layers[0].children().unwrap();
|
||||
assert_eq!(top.len(), 1, "{params}");
|
||||
assert_eq!(top[0].name.as_deref(), Some("cut.psd"), "{params}");
|
||||
let group = top[0].id;
|
||||
let (anchors, even_odd, _) = clip_group(d, group);
|
||||
assert_eq!((anchors, even_odd), (triangle.clone(), true), "{params}");
|
||||
// The corner outside the triangle draws nothing; its middle draws red.
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!((png.get_pixel(2, 2).0[3], png.get_pixel(50, 40).0), (0, [255, 0, 0, 255]), "{params}");
|
||||
// The clipping path is an ordinary path: releasing the clipping mask leaves the image whole.
|
||||
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
|
||||
s.execute("object.clippingMask.release", &json!({})).unwrap();
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!(png.get_pixel(2, 2).0, [255, 0, 0, 255], "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace keeps a clipped PSD file's scale, as it keeps an image's.
|
||||
#[test]
|
||||
fn replacing_a_clipped_psd_keeps_its_scale() {
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [200, 200]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "replace": true})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
let (anchors, _, _) = clip_group(&s.doc().unwrap().doc, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert_eq!(anchors, [[200.0, 150.0], [300.0, 250.0], [100.0, 250.0]]);
|
||||
// A plain image replacing the clip group keeps its scale too.
|
||||
let plain = vectorcraft_format::base64_encode(&red_psd(&[]));
|
||||
let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap();
|
||||
assert_eq!((r["width"].as_f64(), r["height"].as_f64()), (Some(200.0), Some(100.0)), "{r}");
|
||||
}
|
||||
|
||||
/// A plain image replacing a clipped PSD file takes the clipped image's scale and rotation.
|
||||
#[test]
|
||||
fn a_plain_image_replacing_a_clipped_psd_keeps_its_rotation() {
|
||||
let data = vectorcraft_format::base64_encode(&red_psd(&triangle_resources()));
|
||||
let plain = vectorcraft_format::base64_encode(&red_psd(&[]));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "cut.psd", "dataBase64": data, "at": [200, 200]})).unwrap();
|
||||
let group = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 150})).unwrap();
|
||||
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
|
||||
let xf = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Image(im)) => im.xf.as_coeffs(),
|
||||
other => panic!("not an image: {other:?}"),
|
||||
};
|
||||
let (_, _, image) = clip_group(&s.doc().unwrap().doc, group);
|
||||
let before = xf(&s, image);
|
||||
let r = s.execute("file.place", &json!({"name": "plain.psd", "dataBase64": plain, "replace": true})).unwrap();
|
||||
let after = xf(&s, NodeId(r["ids"][0].as_u64().unwrap()));
|
||||
assert!(after.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-9), "{after:?} != {before:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_that_starts_with_all_pixels_puts_the_image_around_the_path() {
|
||||
let hole = saved_path(true, &[(true, &[[0.25, 0.25], [0.75, 0.25], [0.75, 0.75], [0.25, 0.75]])]);
|
||||
let f = red_psd(&[resource(2000, b"Hole", &hole), clipping_name(b"Hole")].concat());
|
||||
let path = clipping_path(&f).unwrap();
|
||||
let starts: Vec<_> = path.subpaths.iter().map(|s| (s.anchors[0].p.x, s.anchors[0].p.y, s.closed)).collect();
|
||||
assert_eq!(starts, [(0.0, 0.0, true), (25.0, 12.5, true)], "the image's edges, then the hole");
|
||||
let mut s = Session::new();
|
||||
s.execute("document.open", &json!({"name": "hole.psd", "dataBase64": vectorcraft_format::base64_encode(&f), "layers": false})).unwrap();
|
||||
let png = image::load_from_memory(&exported(&mut s, json!({"format": "png"}))).unwrap().to_rgba8();
|
||||
assert_eq!((png.get_pixel(2, 2).0, png.get_pixel(50, 25).0[3]), ([255, 0, 0, 255], 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_naming_no_clipping_path_or_a_missing_one_place_a_plain_image() {
|
||||
let other = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]);
|
||||
let empty = saved_path(false, &[]);
|
||||
for (resources, what) in [
|
||||
(resource(2000, b"Other", &other), "saved paths, none named"),
|
||||
([resource(2000, b"Other", &other), clipping_name(b"Gone")].concat(), "a name no path has"),
|
||||
([resource(2000, b"Empty", &empty), clipping_name(b"Empty")].concat(), "a path with no knots"),
|
||||
([resource(3000, b"Other", &other), clipping_name(b"Other")].concat(), "a resource outside the saved paths"),
|
||||
([resource(2000, b"Other", &other), [&b"MeSa"[..], &clipping_name(b"Other")[4..]].concat()].concat(), "a block not signed 8BIM"),
|
||||
(vec![], "no resources"),
|
||||
] {
|
||||
let f = red_psd(&resources);
|
||||
assert!(clipping_path(&f).is_none(), "{what}");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let r = s.execute("file.place", &json!({"name": "a.psd", "dataBase64": vectorcraft_format::base64_encode(&f)})).unwrap();
|
||||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||||
assert!(matches!(s.doc().unwrap().doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(_))), "{what}");
|
||||
assert!(r.get("image").is_none(), "{what}: {r}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_clipping_paths_are_read_without_a_panic() {
|
||||
let good = red_psd(&triangle_resources());
|
||||
assert!(clipping_path(&good).is_some());
|
||||
// The header, the empty colour mode data, then the resources' length and the resources.
|
||||
let start = 26 + 4;
|
||||
let end = start + 4 + triangle_resources().len();
|
||||
for n in 0..end + 2 {
|
||||
let _ = clipping_path(&good[..n]);
|
||||
}
|
||||
for i in start..end {
|
||||
for v in [0, 1, 0x7f, 0x80, 0xff] {
|
||||
let mut f = good.clone();
|
||||
f[i] = v;
|
||||
let _ = clipping_path(&f);
|
||||
}
|
||||
}
|
||||
// Knots before any length record, and more knots than a length record counts, are left out.
|
||||
let mut extra = saved_path(false, &[(true, &[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]])]);
|
||||
extra[26 * 2 + 3] = 2;
|
||||
let mut stray = 2u16.to_be_bytes().to_vec();
|
||||
stray.resize(26, 0);
|
||||
extra.splice(26..26, stray);
|
||||
let path = clipping_path(&red_psd(&[resource(2000, b"P", &extra), clipping_name(b"P")].concat())).unwrap();
|
||||
assert_eq!(path.subpaths.iter().map(|s| s.anchors.len()).collect::<Vec<_>>(), [2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_and_unsupported_files_are_refused_without_a_panic() {
|
||||
let good = psd(2, 4, (3, 2), 8, 3, &[], &[], &layer_count(-1, true), &raw(&[&[1; 6], &[2; 6], &[3; 6], &[4; 6]]));
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
"{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind; the points on a label's characters are not stored → {index}",
|
||||
has_doc,
|
||||
add_point
|
||||
),
|
||||
@@ -28,7 +28,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
"{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
|
||||
has_doc,
|
||||
set_point
|
||||
),
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Freeform Point",
|
||||
[],
|
||||
None,
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
"{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
|
||||
has_doc,
|
||||
delete_point
|
||||
),
|
||||
@@ -46,7 +46,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
"{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
|
||||
has_doc,
|
||||
add_line
|
||||
),
|
||||
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Split Freeform Line",
|
||||
[],
|
||||
None,
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
"{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
|
||||
has_doc,
|
||||
split_line
|
||||
),
|
||||
@@ -182,7 +182,8 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
let item = item_target(s, p, cmd)?;
|
||||
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let ids = item.targets(s, p)?;
|
||||
// The art of a graph design in a series keeps the design's gradient.
|
||||
let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(cmd, "select an object with a freeform gradient"));
|
||||
}
|
||||
@@ -200,7 +201,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
first.get_or_insert(r);
|
||||
Ok(())
|
||||
};
|
||||
edit_items(s, &ids, item, cmd, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, cmd)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
edit_items(s, &ids, item, of, cmd, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -221,7 +224,9 @@ fn edit<R>(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
|
||||
})?;
|
||||
let r = first.ok_or_else(|| bad(cmd, NOT_FREEFORM))?;
|
||||
// The edited gradient is the last one used (`paint.lastGradient`).
|
||||
let shown = s.doc()?.doc.node(ids[0]).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()));
|
||||
let shown = shown_at.and_then(|(id, item)| {
|
||||
s.doc().ok()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, cmd).ok().flatten()))
|
||||
});
|
||||
if let Some(p) = shown {
|
||||
s.remember_paint(&p);
|
||||
}
|
||||
|
||||
@@ -865,7 +865,8 @@ pub(crate) fn propagate(before: &Document, d: &mut Document, ge: &GlobalEdit, se
|
||||
}
|
||||
|
||||
/// Store on their graphs what the members `edited`, and the objects in them, took on the paths directly in a graph
|
||||
/// series, for the graph's next redraw. The edited member is left to the edit's own command.
|
||||
/// series, and the transparency a series group among them took, for the graph's next redraw. The edited member is left to
|
||||
/// the edit's own command.
|
||||
fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
|
||||
let mut taken = vec![];
|
||||
for id in edited {
|
||||
@@ -874,6 +875,8 @@ fn keep_series_changes(before: &Document, d: &mut Document, edited: &[NodeId]) {
|
||||
}
|
||||
}
|
||||
super::appearance::capture_series_changes(before, d, &taken);
|
||||
let groups = super::graph::series_groups_among(d, &taken);
|
||||
super::graph::capture_series_object_opacity(d, &groups);
|
||||
}
|
||||
|
||||
/// The outlines of the members of the active document's Global Edit that are not selected, hold
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without its placement, fitted to each label",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (docs/mcp.md); on a graph label's row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters their gradient without the placement this command sets, fitted to each label",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
@@ -531,6 +531,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["angle"], C)?;
|
||||
let item = item.of_kind(s, !stroke);
|
||||
let ids = item.targets(s, p)?;
|
||||
// Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
|
||||
// not one for new art.
|
||||
let selected = !ids.is_empty();
|
||||
let ids = super::appearance::drop_design_art(&s.doc()?.doc, ids);
|
||||
// How the gradient lies on a stroke (the panel's Stroke buttons).
|
||||
let mode = match str_param(p, "strokeMode") {
|
||||
None => None,
|
||||
@@ -576,7 +580,10 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
let shown_at = super::appearance::first_edited(s, item, of, &ids);
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let edited = edit_items(s, &ids, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
@@ -605,16 +612,19 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(m) = mode
|
||||
&& ids.is_empty()
|
||||
&& !selected
|
||||
&& p.get("ids").is_none()
|
||||
&& let Some(st) = s.new_art_stroke_mut()
|
||||
{
|
||||
st.gradient_mode = m;
|
||||
}
|
||||
// The last gradient is the one the first object now shows (the defaults' without objects).
|
||||
let shown = match ids.first() {
|
||||
Some(id) => s.doc()?.doc.node(*id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten())),
|
||||
None => Some(new_default.clone()),
|
||||
let shown = match shown_at {
|
||||
Some((id, item)) => {
|
||||
s.doc()?.doc.node(id).map(|n| super::paint::proxy_paint(n, stroke, item.resolve(&n.appearance, !stroke, C).ok().flatten()))
|
||||
}
|
||||
None if ids.is_empty() => Some(new_default.clone()),
|
||||
None => None,
|
||||
};
|
||||
if let Some(shown) = shown {
|
||||
s.remember_paint(&shown);
|
||||
@@ -624,7 +634,7 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
s.paint.fill = new_default;
|
||||
}
|
||||
Ok(json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
Ok(json!({"ids": edited.iter().map(|i| i.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
/// A painted stroke on a type run without a weight gets 1 pt.
|
||||
@@ -760,8 +770,11 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if targets.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
}
|
||||
let targets = super::appearance::drop_design_art(&s.doc()?.doc, targets);
|
||||
let model = super::paint::new_color_model(s, &Value::Null);
|
||||
edit_items(s, &targets, item, C, "Gradient", !stroke, |n, index| {
|
||||
let of = super::appearance::reference_of(s, p, item, C)?;
|
||||
// The objects returned: with a design's art, those with a row equal to the art's.
|
||||
let targets = edit_items(s, &targets, item, of, C, "Gradient", !stroke, |n, index| {
|
||||
if index.is_none()
|
||||
&& let NodeKind::Text(t) = &mut n.kind
|
||||
{
|
||||
|
||||
@@ -37,9 +37,9 @@ use axis::{nice_axis, tick_values};
|
||||
#[cfg(test)]
|
||||
use columns::{fill_totals, total_text};
|
||||
pub use commands::specs;
|
||||
pub(crate) use data::apply_csv;
|
||||
pub(crate) use data::{apply_csv, parse_csv};
|
||||
#[cfg(test)]
|
||||
use data::{fmt_value, parse_csv, to_csv};
|
||||
use data::{fmt_value, to_csv};
|
||||
pub(crate) use edit::{graphs_holding, keep_placed};
|
||||
#[cfg(test)]
|
||||
use generate::generate;
|
||||
@@ -48,7 +48,7 @@ use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_changes, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows,
|
||||
capture_label_styles, capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_marks_in,
|
||||
label_object_opacity_differs, labels_in, paint_targets, series_group_marks, series_group_marks_where, series_groups_among, series_marks_in,
|
||||
series_object_opacity_differs, shown_paint,
|
||||
};
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ fn cell(c: &str) -> Cell {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
pub(crate) fn parse_csv(csv: &str) -> (Vec<String>, Vec<String>, Vec<Vec<Option<f64>>>) {
|
||||
let csv = csv.strip_prefix('\u{feff}').unwrap_or(csv);
|
||||
// Records end at line breaks outside quotes; a record is tab-separated if it has a tab outside quotes.
|
||||
let rows: Vec<Vec<Cell>> = split_unquoted(csv, '\n')
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use vectorcraft_doc::graph::art_bounds;
|
||||
use vectorcraft_doc::graph::graph_art_without_type as art_bounds;
|
||||
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
@@ -21,12 +21,16 @@ fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
|
||||
/// The bounds a redraw of graph `n` measures a move or scale on, as kept at the last generation and as they are now:
|
||||
/// those of its art without type ([`GraphSpec::placed_art`]), or those of all its art when the graph keeps no such
|
||||
/// bounds with a width and a height, or has no art without type now.
|
||||
/// bounds with a width and a height. `None` when the art measured has no width or no height now, or the graph keeps
|
||||
/// bounds of its art without type and has no such art now.
|
||||
fn measured(n: &Node) -> Option<(Rect, Rect)> {
|
||||
let kept = n.extras().graph.as_deref()?;
|
||||
let c = n.children()?;
|
||||
let art = kept.placed_art.filter(|p| p.width() > 1e-9 && p.height() > 1e-9).zip(art_bounds(c));
|
||||
art.or_else(|| kept.placed.zip(children_bounds(c)))
|
||||
let solid = |r: &Rect| r.width() > 1e-9 && r.height() > 1e-9;
|
||||
match kept.placed_art.filter(solid) {
|
||||
Some(placed) => art_bounds(c).filter(solid).map(|now| (placed, now)),
|
||||
None => kept.placed.zip(children_bounds(c).filter(solid)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `r` carried by the change from bounds `from` to bounds `to`: each edge stays at the same place relative to them.
|
||||
@@ -39,14 +43,28 @@ fn carried(r: Rect, from: Rect, to: Rect) -> Option<Rect> {
|
||||
Some(Rect::new(to.x0 + (r.x0 - from.x0) * sx, to.y0 + (r.y0 - from.y0) * sy, to.x0 + (r.x1 - from.x0) * sx, to.y0 + (r.y1 - from.y0) * sy))
|
||||
}
|
||||
|
||||
/// The graphs holding objects `ids`, each with the bounds of its art without type and of all its art. Give them to
|
||||
/// [`keep_placed`] after an edit that changes a graph's art without moving the graph.
|
||||
/// The graphs holding objects `ids`, that are among them or that are inside them, each with the bounds of its art
|
||||
/// without type and of all its art. Give them to [`keep_placed`] after an edit that changes a graph's art without
|
||||
/// moving the graph.
|
||||
pub(crate) fn graphs_holding(d: &Document, ids: &[NodeId]) -> Vec<(NodeId, Option<Rect>, Option<Rect>)> {
|
||||
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
|
||||
let is_graph = |n: &Node| n.extras().graph.is_some();
|
||||
let mut found: Vec<NodeId> = vec![];
|
||||
for id in ids {
|
||||
let Some(chain) = d.ancestry(*id) else { continue };
|
||||
let holder = chain.iter().rev().skip(1).copied().find(|a| d.node(*a).is_some_and(|n| n.extras().graph.is_some()));
|
||||
let Some(gid) = holder.filter(|g| !out.iter().any(|(o, ..)| o == g)) else { continue };
|
||||
found.extend(chain.iter().rev().copied().find(|a| d.node(*a).is_some_and(is_graph)));
|
||||
if let Some(n) = d.node(*id) {
|
||||
n.walk(&mut |c| {
|
||||
if is_graph(c) {
|
||||
found.push(c.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut out: Vec<(NodeId, Option<Rect>, Option<Rect>)> = vec![];
|
||||
for gid in found {
|
||||
if out.iter().any(|(o, ..)| *o == gid) {
|
||||
continue;
|
||||
}
|
||||
let children = d.node(gid).and_then(Node::children);
|
||||
out.push((gid, children.and_then(|c| art_bounds(c)), children.and_then(|c| children_bounds(c))));
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use super::labels::{
|
||||
recolour_text, runs, shadow_of,
|
||||
};
|
||||
use super::markers::{MARKER_BUDGET, marker_cost, marker_designs};
|
||||
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_opacity};
|
||||
use super::series::{picks_legend_fill, series_marks, with_series_gradients, with_series_group_opacity, with_series_opacity};
|
||||
use super::{
|
||||
Arc, BezPath, Color, Document, GraphKind, GraphSpec, Justify, Node, NodeKind, Paint, PathData, Point, Rect, TickLength, ValueAxisSide, shapes,
|
||||
};
|
||||
@@ -1005,7 +1005,7 @@ impl<'a> Plot<'a> {
|
||||
}
|
||||
}
|
||||
let name = g.series.get(s).cloned().filter(|n| !n.is_empty()).unwrap_or_else(|| format!("Series {}", s + 1));
|
||||
let grp = self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items)));
|
||||
let grp = with_series_group_opacity(g, s, self.b.series(&name, s, with_series_opacity(g, s, with_series_gradients(g, s, items))));
|
||||
self.b.out.push(grp);
|
||||
}
|
||||
self.b.out.append(&mut self.on_top);
|
||||
|
||||
@@ -149,20 +149,22 @@ impl Gen<'_> {
|
||||
refresh_bounds(&mut t);
|
||||
t
|
||||
}
|
||||
/// A category or series label: a `|` in it starts a new line (Add graph labels). `middle`: the lines are centred
|
||||
/// on `at` (labels beside an axis or in a wedge) instead of running down from it.
|
||||
/// A category or series label: a `|` in it starts a new line (Add graph labels), as does a line break a quoted CSV
|
||||
/// cell keeps. `middle`: the lines are centred on `at` (labels beside an axis or in a wedge) instead of running down
|
||||
/// from it.
|
||||
pub(super) fn label(&mut self, role: Role, at: Point, s: &str, justify: Justify, middle: bool) -> Arc<Node> {
|
||||
let lines = s.split('|').count();
|
||||
let text = s.replace('|', "\n");
|
||||
let lines = text.split('\n').count();
|
||||
// Default leading puts the first and last baselines this far above and below `at`.
|
||||
let half = (lines - 1) as f64 * label_size(self.styles, role) * 1.2 / 2.0;
|
||||
let start = if middle { Point::new(at.x, at.y - half) } else { at };
|
||||
let mut t = self.text_object(role, start, &s.replace('|', "\n"), justify);
|
||||
let mut t = self.text_object(role, start, &text, justify);
|
||||
// Kept leading or paragraph spacing moves the lines: put the middle of the first and last baselines on `at`. An
|
||||
// empty line has no baseline: an empty first or last line leaves the label where the default leading puts it.
|
||||
if middle && kept_para(self.styles, role).is_some() {
|
||||
let ys: Vec<f64> = t.baselines().map(|(a, _)| a.y).collect();
|
||||
let ends_set = s.split('|').next().is_some_and(|l| !l.is_empty()) && s.split('|').next_back().is_some_and(|l| !l.is_empty());
|
||||
let set = s.split('|').filter(|l| !l.is_empty()).count();
|
||||
let ends_set = text.split('\n').next().is_some_and(|l| !l.is_empty()) && text.split('\n').next_back().is_some_and(|l| !l.is_empty());
|
||||
let set = text.split('\n').filter(|l| !l.is_empty()).count();
|
||||
if let (Some(first), Some(last), true) = (ys.first(), ys.last(), ends_set && ys.len() == set) {
|
||||
t.xf = Affine::translate((0.0, half - (first + last) / 2.0)) * t.xf;
|
||||
}
|
||||
|
||||
@@ -475,15 +475,16 @@ pub(crate) fn capture_series_opacity(doc: &mut Document, edited: &[(NodeId, bool
|
||||
settle_series_paints(doc, before)
|
||||
}
|
||||
|
||||
/// Copy the object opacity and blend mode of generated series art just edited (`edited`) into that series' object opacity
|
||||
/// and blend mode. Called inside the same document edit, so both undo together. Returns whether a series' kept object
|
||||
/// opacity or blend mode changed.
|
||||
/// Copy the object transparency of generated series art just edited (`edited`) into what that series keeps: a path
|
||||
/// directly in a series group sets the paths' object opacity and blend mode, and the series group itself sets the
|
||||
/// group's opacity, blend mode, isolation, knockout and knockout shape. Called inside the same document edit, so both undo
|
||||
/// together. Returns whether what a series keeps changed.
|
||||
pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId]) -> bool {
|
||||
let mut before = SeriesPaintsBefore::new();
|
||||
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
|
||||
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
|
||||
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
|
||||
// A fully opaque Normal object on a series the graph keeps nothing for leaves the graph as it is.
|
||||
if opacity.is_none() && blend.is_none() && spec.series_paints.len() <= index {
|
||||
if look == ObjectOpacity::default() && spec.series_paints.len() <= index {
|
||||
continue;
|
||||
}
|
||||
before.entry(graph).or_insert_with(|| spec.series_paints.clone());
|
||||
@@ -492,7 +493,12 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
|
||||
spec.series_paints.resize(index + 1, vectorcraft_doc::SeriesPaint::default());
|
||||
}
|
||||
let Some(slot) = spec.series_paints.get_mut(index) else { continue };
|
||||
(slot.opacity, slot.blend) = (opacity, blend);
|
||||
if group {
|
||||
(slot.group_opacity, slot.group_blend) = (look.opacity, look.blend);
|
||||
(slot.group_isolate, slot.group_knockout, slot.group_knockout_shape) = (look.isolate, look.knockout, look.knockout_shape);
|
||||
} else {
|
||||
(slot.opacity, slot.blend) = (look.opacity, look.blend);
|
||||
}
|
||||
}
|
||||
settle_series_paints(doc, before)
|
||||
}
|
||||
@@ -500,20 +506,50 @@ pub(crate) fn capture_series_object_opacity(doc: &mut Document, edited: &[NodeId
|
||||
/// Would [`capture_series_object_opacity`] change what the graph stores for `edited`? Reads the document without copying
|
||||
/// it.
|
||||
pub(crate) fn series_object_opacity_differs(doc: &Document, edited: &[NodeId]) -> bool {
|
||||
let mut after: HashMap<(NodeId, usize), (Option<f32>, Option<BlendMode>)> = HashMap::new();
|
||||
let stored = |graph: NodeId, index: usize| {
|
||||
let mut after: HashMap<(NodeId, usize, bool), ObjectOpacity> = HashMap::new();
|
||||
let stored = |graph: NodeId, index: usize, group: bool| {
|
||||
let spec = doc.node(graph).and_then(|n| n.extras().graph.as_deref());
|
||||
spec.and_then(|g| g.series_paints.get(index)).map_or((None, None), |slot| (slot.opacity, slot.blend))
|
||||
let slot = spec.and_then(|g| g.series_paints.get(index));
|
||||
slot.map_or_else(ObjectOpacity::default, |slot| {
|
||||
if group {
|
||||
ObjectOpacity {
|
||||
opacity: slot.group_opacity,
|
||||
blend: slot.group_blend,
|
||||
isolate: slot.group_isolate,
|
||||
knockout: slot.group_knockout,
|
||||
knockout_shape: slot.group_knockout_shape,
|
||||
}
|
||||
} else {
|
||||
ObjectOpacity { opacity: slot.opacity, blend: slot.blend, ..ObjectOpacity::default() }
|
||||
}
|
||||
})
|
||||
};
|
||||
for (graph, index, opacity, blend) in object_opacity_captures(doc, edited) {
|
||||
after.insert((graph, index), (opacity, blend));
|
||||
for (graph, index, group, look) in object_opacity_captures(doc, edited) {
|
||||
after.insert((graph, index, group), look);
|
||||
}
|
||||
after.into_iter().any(|((graph, index), pair)| stored(graph, index) != pair)
|
||||
after.into_iter().any(|((graph, index, group), look)| stored(graph, index, group) != look)
|
||||
}
|
||||
|
||||
/// The series and object opacity and blend mode (None for 100% and Normal) of each of `edited` that is a path directly in a
|
||||
/// series group, in order.
|
||||
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, Option<f32>, Option<BlendMode>)> {
|
||||
/// The series groups among `ids`, for an edit that changes only what a group's transparency has beyond its opacity and
|
||||
/// blend mode (isolation, knockout and knockout shape), which the graph keeps for series groups alone.
|
||||
pub(crate) fn series_groups_among(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
ids.iter().copied().filter(|id| doc.node(*id).is_some_and(|n| n.extras().series_index.is_some())).collect()
|
||||
}
|
||||
|
||||
/// An object's transparency as a graph keeps it: the object opacity and blend mode (None for 100% and Normal), and for a
|
||||
/// series group its isolation, knockout (None for neutral) and knockout shape. Paths keep the first two only.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct ObjectOpacity {
|
||||
opacity: Option<f32>,
|
||||
blend: Option<BlendMode>,
|
||||
isolate: bool,
|
||||
knockout: Option<vectorcraft_doc::Knockout>,
|
||||
knockout_shape: bool,
|
||||
}
|
||||
|
||||
/// The graph, series, whether it is the series group itself (`true`) or a path directly in it, and the object
|
||||
/// transparency of each of `edited` that is one of those, in order.
|
||||
fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, usize, bool, ObjectOpacity)> {
|
||||
if edited.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -524,14 +560,48 @@ fn object_opacity_captures(doc: &Document, edited: &[NodeId]) -> Vec<(NodeId, us
|
||||
edited
|
||||
.iter()
|
||||
.filter_map(|id| {
|
||||
// Only the paths the graph draws again, not the copy of a graph design.
|
||||
let r = members.get(id).filter(|r| doc.parent_of(*id) == Some(r.group))?;
|
||||
let node = doc.node(*id).filter(|n| matches!(n.kind, NodeKind::Path { .. }))?;
|
||||
Some((r.graph, r.index, (node.opacity < 1.0).then_some(node.opacity), (node.blend != BlendMode::Normal).then_some(node.blend)))
|
||||
let r = members.get(id)?;
|
||||
let group = r.group == *id;
|
||||
// Only the series group and the paths the graph draws again, not the copy of a graph design.
|
||||
let node = doc.node(*id).filter(|n| group || (doc.parent_of(*id) == Some(r.group) && matches!(n.kind, NodeKind::Path { .. })))?;
|
||||
let mut look = ObjectOpacity {
|
||||
opacity: (node.opacity < 1.0).then_some(node.opacity),
|
||||
blend: (node.blend != BlendMode::Normal).then_some(node.blend),
|
||||
..ObjectOpacity::default()
|
||||
};
|
||||
if group {
|
||||
look.isolate = node.isolate;
|
||||
look.knockout = (node.knockout != vectorcraft_doc::Knockout::Neutral).then_some(node.knockout);
|
||||
look.knockout_shape = node.knockout_shape;
|
||||
}
|
||||
Some((r.graph, r.index, group, look))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Series `i`'s group (`group`) with the object opacity, blend mode, isolation, knockout and knockout shape the graph
|
||||
/// keeps for it. An opacity read from a file is held to 0..1, and one that is not a number is left out.
|
||||
pub(super) fn with_series_group_opacity(g: &GraphSpec, i: usize, mut group: Arc<Node>) -> Arc<Node> {
|
||||
let Some(slot) = g.series_paints.get(i) else { return group };
|
||||
let opacity = slot.group_opacity.filter(|o| o.is_finite()).map(|o| o.clamp(0.0, 1.0));
|
||||
if opacity.is_none() && slot.group_blend.is_none() && !slot.group_isolate && slot.group_knockout.is_none() && !slot.group_knockout_shape {
|
||||
return group;
|
||||
}
|
||||
let n = Arc::make_mut(&mut group);
|
||||
if let Some(o) = opacity {
|
||||
n.opacity = o;
|
||||
}
|
||||
if let Some(b) = slot.group_blend {
|
||||
n.blend = b;
|
||||
}
|
||||
if let Some(k) = slot.group_knockout {
|
||||
n.knockout = k;
|
||||
}
|
||||
n.isolate |= slot.group_isolate;
|
||||
n.knockout_shape |= slot.group_knockout_shape;
|
||||
group
|
||||
}
|
||||
|
||||
/// Graph Data › Transpose row/column: categories become series and series categories.
|
||||
pub(super) fn transpose(g: &mut GraphSpec) {
|
||||
let cells = g.cells();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
//! Window › Info (`info.readout`): the selection's size and the active tool's readout, as the Info
|
||||
//! panel shows them.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::{CommandSpec, Result, Session, always, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
query "info.readout",
|
||||
"Info",
|
||||
[],
|
||||
None,
|
||||
"{} → {tool: the active tool's id, width?, height?: the sides of the selection's bounding box in pt (the box around the anchors selected with Direct Selection, when there are some), measured as prefs usePreviewBounds says; left out with nothing selected, readout?: what the Info panel shows for the tool in use: {kind: \"drag\", dx, dy, distance, angle} while the Selection, Direct Selection or Group Selection tool moves the selection or the Gradient tool draws a gradient vector on the art; {kind: \"scale\", width, height} (percent) during a Scale tool drag; {kind: \"rotate\", center: [x, y], angle: deg counter-clockwise, as object.rotate takes it} and {kind: \"reflect\", center, angle: the axis in deg counter-clockwise from horizontal, as object.reflect takes it} during a Rotate or Reflect tool drag; {kind: \"shear\", center, axis: 0 for a horizontal shear and 90 for a vertical one, angle: deg, as object.shear takes it} during a Shear tool drag; {kind: \"brush\", brush: name|null} while the Paintbrush is the tool; left out for any other tool and between drags. Lengths are in pt, a drag's angle is in deg counter-clockwise from the x axis, and center is the center of the selection's bounding box as the drag has carried it, in document coordinates}",
|
||||
always,
|
||||
readout
|
||||
)]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The sides of the selection's bounding box as the Info panel shows them: of the box around
|
||||
/// the anchors selected with Direct Selection when there are some, else of the bounding box
|
||||
/// rotated with rotated objects ([`Session::transform_box`]), measured as Use Preview Bounds
|
||||
/// says. None with nothing selected.
|
||||
pub fn info_size(&self) -> Option<(f64, f64)> {
|
||||
let st = self.active()?;
|
||||
let anchors = effects::preview::anchor_bounds_with(&st.selection, &st.doc, self.bounds_measure());
|
||||
let r = anchors.or_else(|| self.transform_box(&st.selection.objects).map(|b| b.rect))?;
|
||||
Some((r.width(), r.height()))
|
||||
}
|
||||
}
|
||||
|
||||
fn readout(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let mut out = json!({ "tool": s.tool_id() });
|
||||
if let Some((w, h)) = s.info_size() {
|
||||
out["width"] = json!(w);
|
||||
out["height"] = json!(h);
|
||||
}
|
||||
if let Some(r) = s.tool_readout() {
|
||||
out["readout"] = r.to_json();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use vectorcraft_tools::{PointerEvent, PointerKind};
|
||||
|
||||
use crate::{Session, ViewInfo};
|
||||
|
||||
fn view() -> ViewInfo {
|
||||
ViewInfo { smart_guides: false, snap_to_point: false, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A 100 by 60 rectangle at (50, 50), selected, with a 10 pt stroke.
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 60})).unwrap()["id"].clone();
|
||||
s.execute("select.set", &json!({ "ids": [id] })).unwrap();
|
||||
s.execute("stroke.set", &json!({"weight": 10})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn tool(s: &mut Session, id: &str) {
|
||||
s.select_tool(id, view()).unwrap();
|
||||
}
|
||||
|
||||
fn pointer(s: &mut Session, kind: PointerKind, x: f64, y: f64) {
|
||||
s.pointer(&PointerEvent::new(kind, x, y), view()).unwrap();
|
||||
}
|
||||
|
||||
fn info(s: &mut Session) -> serde_json::Value {
|
||||
s.execute("info.readout", &json!({})).unwrap()
|
||||
}
|
||||
|
||||
fn near(v: &serde_json::Value, want: f64) -> bool {
|
||||
v.as_f64().is_some_and(|v| (v - want).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_size_follows_use_preview_bounds() {
|
||||
let mut s = session();
|
||||
let i = info(&mut s);
|
||||
assert!(near(&i["width"], 100.0) && near(&i["height"], 60.0), "{i}");
|
||||
assert!(i.get("readout").is_none(), "{i}");
|
||||
s.execute("prefs.set", &json!({"key": "usePreviewBounds", "value": true})).unwrap();
|
||||
let i = info(&mut s);
|
||||
assert!(near(&i["width"], 110.0) && near(&i["height"], 70.0), "{i}");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let i = info(&mut s);
|
||||
assert!(i.get("width").is_none() && i.get("height").is_none(), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_reads_how_far_it_has_gone_until_the_release() {
|
||||
let mut s = session();
|
||||
tool(&mut s, "selection");
|
||||
pointer(&mut s, PointerKind::Down, 100.0, 80.0);
|
||||
assert!(info(&mut s).get("readout").is_none());
|
||||
pointer(&mut s, PointerKind::Drag, 130.0, 40.0);
|
||||
let i = info(&mut s);
|
||||
let r = &i["readout"];
|
||||
assert_eq!(r["kind"], "drag", "{i}");
|
||||
assert!(near(&r["dx"], 30.0) && near(&r["dy"], -40.0) && near(&r["distance"], 50.0), "{i}");
|
||||
assert!(near(&r["angle"], 53.13010235415598), "{i}");
|
||||
pointer(&mut s, PointerKind::Up, 130.0, 40.0);
|
||||
let i = info(&mut s);
|
||||
assert!(i.get("readout").is_none(), "{i}");
|
||||
assert!(near(&i["width"], 100.0), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_transform_tool_reads_its_drag() {
|
||||
for (id, check) in [
|
||||
("scale", (|r| r["kind"] == "scale" && near(&r["width"], 200.0) && near(&r["height"], 200.0)) as fn(&serde_json::Value) -> bool),
|
||||
("rotate", |r| r["kind"] == "rotate" && near(&r["center"][0], 100.0) && near(&r["center"][1], 80.0) && near(&r["angle"], -90.0)),
|
||||
("reflect", |r| r["kind"] == "reflect" && near(&r["center"][0], 100.0) && near(&r["angle"], 0.0)),
|
||||
("shear", |r| {
|
||||
r["kind"] == "shear"
|
||||
&& near(&r["center"][0], 100.0)
|
||||
&& near(&r["center"][1], 80.0)
|
||||
&& near(&r["axis"], 0.0)
|
||||
&& near(&r["angle"], 45.0)
|
||||
}),
|
||||
] {
|
||||
let mut s = session();
|
||||
tool(&mut s, id);
|
||||
// The reference point is the box's center (100, 80).
|
||||
let from = if id == "shear" { (100.0, 60.0) } else { (120.0, 100.0) };
|
||||
pointer(&mut s, PointerKind::Down, from.0, from.1);
|
||||
let to = match id {
|
||||
"scale" => (140.0, 120.0),
|
||||
"rotate" => (80.0, 100.0),
|
||||
"reflect" => (160.0, 80.0),
|
||||
_ => (120.0, 60.0),
|
||||
};
|
||||
pointer(&mut s, PointerKind::Drag, to.0, to.1);
|
||||
let i = info(&mut s);
|
||||
assert_eq!(i["tool"], id);
|
||||
assert!(check(&i["readout"]), "{id}: {i}");
|
||||
pointer(&mut s, PointerKind::Up, to.0, to.1);
|
||||
assert!(info(&mut s).get("readout").is_none(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paintbrush_reads_its_brush() {
|
||||
let mut s = session();
|
||||
tool(&mut s, "paintbrush");
|
||||
let i = info(&mut s);
|
||||
assert_eq!(i["readout"], json!({"kind": "brush", "brush": null}), "{i}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_parameter_is_refused() {
|
||||
let mut s = session();
|
||||
let e = s.execute("info.readout", &json!({"tool": "scale"})).unwrap_err().to_string();
|
||||
assert!(e.contains("tool"), "{e}");
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded)|size (the linked file's size in bytes as Link Info shows it, smallest first; rows without one, embedded images and missing files whose size is not kept, last; equal sizes by name); default: stacking order; top first, dcsTransparency?: false (Show DCS Transparency Interactions: mark the images placed from DCS files that are transparent, themselves or a group or layer holding them, or that overlap a visible object with its own transparency; it looks at every object, so it takes longer)} every image object and placed document the document stores, as the Links panel lists them: those in the layers, then those in opacity-mask art and in the art of symbols, graph designs, patterns and stored brushes (one row per stored object, never one per symbol instance, pattern tile or brushed stroke) → {links: [{id, name, linked, status: ok|modified|missing|embedded, format (DCS for an image placed from a DCS file), pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels), dcsTransparency?: true (with dcsTransparency), owner?: {kind: layers|symbol|graphDesign|pattern|brush, name? (of the symbol, graph design, pattern or brush), index? (a brush's place in the Brushes panel, from 0), tile?: side|outerCorner|innerCorner|start|end (a pattern brush's tile), maskOf?: id (in the opacity-mask art of that object)} (an object outside the layer tree)}], missing, modified, embedded}; under automation read roots, path and found are left out when the file they name is outside the roots",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -1298,7 +1298,112 @@ pub(crate) fn path_shown(path: &str, doc_path: Option<&str>) -> bool {
|
||||
/// alone in a reply to the caller asking now? Only a path [`path_shown`] does not allow; a URL is
|
||||
/// always shown as it is.
|
||||
pub(crate) fn script_hidden(f: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(f, doc_path) && !matches!(fileio::document_path(f, doc_path), Err(craft_docpath::Refused::Url))
|
||||
file_hidden(f, doc_path)
|
||||
}
|
||||
|
||||
/// Is the file `path` (a link of the document saved at `doc_path`) one the caller asking now may
|
||||
/// not be shown? Only a path [`path_shown`] does not allow; a URL is not a file and is shown as it is.
|
||||
pub(crate) fn file_hidden(path: &str, doc_path: Option<&str>) -> bool {
|
||||
!path_shown(path, doc_path) && !matches!(fileio::document_path(path, doc_path), Err(craft_docpath::Refused::Url))
|
||||
}
|
||||
|
||||
/// Does an SVG of `d` (a document whose links are looked for from `base`) written for the caller
|
||||
/// asking now name the file of a linked image that [`file_hidden`] keeps from it? An `<image>`
|
||||
/// names its image's file with SVG Options › Images set to Link (`link`), and with Embed when the
|
||||
/// document holds no pixels for the image. An image with a solid colorize paint whose pixels are
|
||||
/// gray or missing names none: the SVG writes gray pixels colorized and leaves out an image
|
||||
/// without pixels. The images of the art the SVG writes (opacity masks included) and of the
|
||||
/// symbols, patterns and brushes that art uses, as Copy follows them, are checked: the SVG writes
|
||||
/// no other resource. Hidden layers and objects are written only with
|
||||
/// SVG Options › hidden layers kept (`hidden`), and template layers never ([`svg_written`]).
|
||||
/// Always `false` without read roots in force.
|
||||
pub(crate) fn svg_names_hidden_image(d: &Document, base: LinkBase, link: bool, hidden: bool) -> bool {
|
||||
if crate::file_access::current().is_none() || !names_hidden_image(d, base, link) {
|
||||
return false;
|
||||
}
|
||||
let art = d.layers.iter().filter_map(|l| svg_written(l, hidden)).collect();
|
||||
names_hidden_image(&super::clipboard::Clipboard::gather(d, art).to_document(), base, link)
|
||||
}
|
||||
|
||||
/// `n` as the SVG writer writes it, or `None` when it writes none of it: a hidden layer or object
|
||||
/// is left out unless `hidden`, a template layer's art always, and a disabled opacity mask's art.
|
||||
/// Only layers and groups lose members; other objects keep theirs as they are.
|
||||
fn svg_written(n: &Node, hidden: bool) -> Option<Node> {
|
||||
if !(n.visible || hidden) {
|
||||
return None;
|
||||
}
|
||||
let mut n = n.clone();
|
||||
let mask = n.extras().mask.as_deref().filter(|m| !m.disabled).and_then(|m| {
|
||||
let art = svg_written(&m.art, hidden)?;
|
||||
Some(Box::new(vectorcraft_doc::OpacityMask { art: std::sync::Arc::new(art), ..m.clone() }))
|
||||
});
|
||||
if n.extras().mask.is_some() {
|
||||
n.extras_mut().mask = mask;
|
||||
}
|
||||
match &mut n.kind {
|
||||
NodeKind::Layer { template: true, children, .. } => children.clear(),
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => {
|
||||
*children = children.iter().filter_map(|c| svg_written(c, hidden)).map(std::sync::Arc::new).collect();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Some(n)
|
||||
}
|
||||
|
||||
/// [`svg_names_hidden_image`] for every image of `d`: in the layers, symbols, graph designs,
|
||||
/// patterns, opacity masks and the art of the stored brushes, used or not.
|
||||
fn names_hidden_image(d: &Document, base: LinkBase, link: bool) -> bool {
|
||||
let d = with_brush_art(d);
|
||||
let mut hidden = false;
|
||||
d.visit_images(|n, im| {
|
||||
if hidden {
|
||||
return;
|
||||
}
|
||||
let shown = d.shown_image(n, im);
|
||||
let Some(l) = &shown.link else { return };
|
||||
let blob = d.image_blob(&shown).filter(|b| !b.bytes.is_empty());
|
||||
// The SVG writes an image with a solid colorize paint as colorized pixels when they are
|
||||
// gray, and leaves it out when the document holds none of them.
|
||||
if matches!(n.extras().colorize.as_deref(), Some(vectorcraft_color::Paint::Solid { .. })) && blob.is_none_or(|b| b.gray_source().is_some()) {
|
||||
return;
|
||||
}
|
||||
let named = link || blob.is_none();
|
||||
hidden = named && file_hidden(&l.path, base.doc);
|
||||
});
|
||||
hidden
|
||||
}
|
||||
|
||||
/// Does the native document an SVG of `d` (a document whose links are looked for from `base`)
|
||||
/// carries with Preserve Editing Capabilities name a file that the caller asking now may not be
|
||||
/// shown: the file of a linked image or placed document ([`file_hidden`]), the relative path kept
|
||||
/// of one, which is followed from the file the document was read from and from the document's own
|
||||
/// folder, or a data set's image? Links in the layers, symbols, graph designs, patterns, the pattern
|
||||
/// being edited as it was before, opacity masks and the art of the stored brushes are all checked,
|
||||
/// as [`with_hidden_paths_named`] checks them. A stored brush library that is not a list, or holds
|
||||
/// an entry that does not read as a brush, counts as naming one: the native document carries it as
|
||||
/// it is, and its links cannot be checked. Always `false` without read roots in force.
|
||||
pub(crate) fn names_hidden_file(d: &Document, base: LinkBase) -> bool {
|
||||
if crate::file_access::current().is_none() {
|
||||
return false;
|
||||
}
|
||||
let unread = |list: &Vec<Value>| list.iter().any(|raw| vectorcraft_brush::Brush::from_json(raw.clone()).is_err());
|
||||
if d.unknown.get(vectorcraft_brush::DOC_KEY).is_some_and(|v| v.as_array().is_none_or(unread)) {
|
||||
return true;
|
||||
}
|
||||
let relative_hidden = |r: &str| [base.relative, base.doc].into_iter().any(|from| !path_shown(r, from));
|
||||
let hidden = |l: &LinkInfo| file_hidden(&l.path, base.doc) || l.relative.as_deref().is_some_and(relative_hidden);
|
||||
let image_hidden = |v: &DataValue| matches!(v, DataValue::Image(path) if file_hidden(path, base.doc));
|
||||
if d.variables.datasets.iter().any(|set| set.values.values().any(image_hidden)) {
|
||||
return true;
|
||||
}
|
||||
let mut d = with_brush_art(d);
|
||||
if let Some(original) = d.pattern_edit.as_ref().and_then(|e| e.original.clone()) {
|
||||
d.to_mut().patterns.push(original);
|
||||
}
|
||||
let mut found = false;
|
||||
d.visit_images(|_, im| found |= im.link.as_ref().is_some_and(hidden));
|
||||
d.visit_placed(|_, p| found |= hidden(&p.link));
|
||||
found
|
||||
}
|
||||
|
||||
/// The linked JavaScript file `f` of the open document `st` as a reply to the caller asking now
|
||||
@@ -2211,6 +2316,16 @@ fn document_row(p: &PlacedDocument) -> Value {
|
||||
json!({ "format": pdf.map_or("VectorCraft", |f| f.label), "document": true, "pageWidth": p.width, "pageHeight": p.height })
|
||||
}
|
||||
|
||||
/// The size in bytes of the file that link `l` (of `st`) names, as Link Info shows it: the file's
|
||||
/// size now, else the size the document keeps of it when the caller may see its path.
|
||||
fn link_file_size(st: &crate::DocState, l: &LinkInfo) -> Option<u64> {
|
||||
let doc_path = LinkBase::of(st).doc;
|
||||
let kept = l.size.filter(|_| path_shown(&l.path, doc_path));
|
||||
let roots = crate::file_access::current().or_else(|| st.opened_by.clone());
|
||||
let now = crate::file_access::confine(roots.as_ref(), || fileio::document_path(&l.path, doc_path).ok().as_deref().and_then(file_stamp));
|
||||
now.map(|s| s.0).or(kept)
|
||||
}
|
||||
|
||||
/// Sort rank of a `links.list` status: missing, modified, ok, embedded.
|
||||
fn status_rank(status: &str) -> usize {
|
||||
["missing", "modified", "ok", "embedded"].iter().position(|s| *s == status).unwrap_or(4)
|
||||
@@ -2277,8 +2392,14 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !matches!(show, "all" | "missing" | "modified" | "embedded") {
|
||||
return Err(bad(C, format!("show `{show}`: all, missing, modified or embedded")));
|
||||
}
|
||||
let sort = str_param(p, "sort");
|
||||
if let Some(x) = sort.filter(|x| !matches!(*x, "name" | "kind" | "status" | "size")) {
|
||||
return Err(bad(C, format!("sort `{x}`: name, kind, status or size")));
|
||||
}
|
||||
let interactions = if switch_or(p, "dcsTransparency", false, C)? { dcs_transparency(&st.doc) } else { BTreeSet::new() };
|
||||
let statuses = statuses(st);
|
||||
// The file size of each listed row's link, read only to sort by size.
|
||||
let mut sizes: BTreeMap<u64, u64> = BTreeMap::new();
|
||||
// The layer tree's objects, top first as the Layers panel lists them, then the others in the
|
||||
// order they are stored (opacity-mask art, symbols, graph designs, patterns, the art of the
|
||||
// stored brushes), each once.
|
||||
@@ -2326,6 +2447,11 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let doc_path = LinkBase::of(st).doc;
|
||||
if let Some(l) = link {
|
||||
if sort == Some("size")
|
||||
&& let Some(size) = link_file_size(st, l)
|
||||
{
|
||||
sizes.insert(n.id.0, size);
|
||||
}
|
||||
note_path(&mut row, "path", &l.path, doc_path);
|
||||
if let Some(page) = l.page {
|
||||
row["page"] = json!(page);
|
||||
@@ -2346,12 +2472,17 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
rows.push(row);
|
||||
}
|
||||
let text = |r: &Value, k: &str| r[k].as_str().unwrap_or_default().to_lowercase();
|
||||
match str_param(p, "sort") {
|
||||
None => {}
|
||||
match sort {
|
||||
Some("name") => rows.sort_by_cached_key(|r| text(r, "name")),
|
||||
Some("kind") => rows.sort_by_cached_key(|r| (text(r, "format"), text(r, "name"))),
|
||||
Some("status") => rows.sort_by_cached_key(|r| (status_rank(r["status"].as_str().unwrap_or_default()), text(r, "name"))),
|
||||
Some(x) => return Err(bad(C, format!("sort `{x}`: name, kind or status"))),
|
||||
// Smallest file first; rows without a file size (embedded images, a missing file whose
|
||||
// size the document does not keep) come last; equal sizes by name.
|
||||
Some("size") => rows.sort_by_cached_key(|r| {
|
||||
let size = r["id"].as_u64().and_then(|id| sizes.get(&id).copied());
|
||||
(size.is_none(), size.unwrap_or(0), text(r, "name"))
|
||||
}),
|
||||
_ => {}
|
||||
}
|
||||
let count = |k: &str| counts.get(k).copied().unwrap_or(0);
|
||||
Ok(json!({ "links": rows, "missing": count("missing"), "modified": count("modified"), "embedded": count("embedded") }))
|
||||
|
||||
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Scale…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), sx: %, sy?: %, origin?: [x,y], copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), sx: % (along the bounding box's width), sy?: % (along its height), origin?: [x,y] (a page point), basis?: \"box\"|\"page\" (box, the default: sx and sy follow the bounding box, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)} (strokes/corners default to the preferences). With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
scale
|
||||
),
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reflect…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical; vertical and horizontal are the bounding box's own axes, deg a line on the page), origin?, basis?: \"box\"|\"page\" (for a named axis; box, the default: the bounding box's axes, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
reflect
|
||||
),
|
||||
@@ -251,7 +251,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
|
||||
@@ -68,8 +68,14 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
|
||||
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
|
||||
let transparency = opacity.is_some() || blend.is_some();
|
||||
let stores =
|
||||
|| transparency && (crate::cmd::graph::series_object_opacity_differs(d, &ids) || crate::cmd::graph::label_object_opacity_differs(d, &ids));
|
||||
// A series group's isolation, knockout and knockout shape are kept for the group alone.
|
||||
let group_only = !transparency && ["isolate", "knockout", "knockoutShape"].iter().any(|k| p.get(*k).is_some());
|
||||
let kept = if group_only { crate::cmd::graph::series_groups_among(d, &ids) } else { ids.clone() };
|
||||
let stores = || {
|
||||
(transparency || group_only)
|
||||
&& (crate::cmd::graph::series_object_opacity_differs(d, &kept)
|
||||
|| transparency && crate::cmd::graph::label_object_opacity_differs(d, &ids))
|
||||
};
|
||||
if ids.iter().all(|id| d.node(*id).is_some_and(has_values)) && !stores() {
|
||||
// Hidden or locked objects can't stay selected.
|
||||
if hides {
|
||||
@@ -123,8 +129,10 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
});
|
||||
}
|
||||
}
|
||||
if transparency || group_only {
|
||||
crate::cmd::graph::capture_series_object_opacity(d, &kept);
|
||||
}
|
||||
if transparency {
|
||||
crate::cmd::graph::capture_series_object_opacity(d, &ids);
|
||||
crate::cmd::graph::capture_label_object_opacity(d, &ids);
|
||||
}
|
||||
// Hidden or locked objects can't stay selected.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::align::choice;
|
||||
use super::{
|
||||
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, Point, Result, Scaling, Session, Value, Vec2, bad, bool_or,
|
||||
check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad,
|
||||
bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
|
||||
selected_roots_to_transform,
|
||||
};
|
||||
|
||||
@@ -158,6 +158,9 @@ fn apply_transform_moving_guides(
|
||||
}
|
||||
None => ids.clone(),
|
||||
};
|
||||
// Pattern editing with Move Tile with Art: the tile art's bounds before a move.
|
||||
let moves_only = c[0] == 1.0 && c[1] == 0.0 && c[2] == 0.0 && c[3] == 1.0;
|
||||
let tile_art = if objects && !copy && moves_only { crate::cmd::patterncmds::tile_art_bounds(d) } else { None };
|
||||
// Transforms don't move nodes in the tree, so reuse the paths found for the no-copy
|
||||
// case; copies and a settled typing session need paths from the edited document.
|
||||
let paths = if reindex { d.index_paths(targets.iter().copied()) } else { paths };
|
||||
@@ -172,6 +175,10 @@ fn apply_transform_moving_guides(
|
||||
for id in &targets {
|
||||
super::pixelgrid::keep_compound_aligned(d, *id, sc);
|
||||
}
|
||||
// Moving all of the tile art moves the tile as far.
|
||||
if let Some(before) = tile_art {
|
||||
crate::cmd::patterncmds::move_tile_with_art(d, &targets, before);
|
||||
}
|
||||
}
|
||||
if with_guides && (delta.x != 0.0 || delta.y != 0.0) {
|
||||
for i in sel.guides.clone() {
|
||||
@@ -358,26 +365,52 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(bad("object.scale", "scale must be non-zero"));
|
||||
}
|
||||
apply_transform(s, "Scale", ids, about(o, Affine::scale_non_uniform(sx, sy)), p, true)
|
||||
let frame = basis_frame(s, p, "object.scale", &ids)?;
|
||||
apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true)
|
||||
}
|
||||
|
||||
/// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param:
|
||||
/// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset
|
||||
/// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with
|
||||
/// Direct Selection (with no copy and Transform Objects on) transform along the page's axes, as
|
||||
/// their own box does. The basis joins the journal entry, so a replay acts in the same frame. A
|
||||
/// saved step without `basis` ([`Session::replay`]) was recorded before Scale and Reflect followed
|
||||
/// the box, so it acts along the page's axes, as it did when it was recorded.
|
||||
fn basis_frame(s: &mut Session, p: &Value, cmd: &str, ids: &[NodeId]) -> Result<OrientedBox> {
|
||||
let basis = choice(p, cmd, "basis", &["box", "page"])?;
|
||||
let page = basis == Some("page") || (basis.is_none() && s.replaying());
|
||||
let st = s.doc()?;
|
||||
let anchors = !bool_or(p, "copy", false)
|
||||
&& transforms_objects(p)
|
||||
&& effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure()).is_some();
|
||||
let angle = if page || anchors { 0.0 } else { st.doc.bbox_angle(ids) };
|
||||
s.note_journal("basis", json!(if page { "page" } else { "box" }));
|
||||
Ok(OrientedBox { angle, rect: Rect::ZERO })
|
||||
}
|
||||
|
||||
pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.reflect")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
let o = origin_of(s, p, &ids)?;
|
||||
let m = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Affine::scale_non_uniform(1.0, -1.0),
|
||||
Some(Value::Number(n)) => {
|
||||
let t = -n.as_f64().unwrap_or(90.0).to_radians();
|
||||
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
|
||||
}
|
||||
None | Some(Value::Null) => Affine::scale_non_uniform(-1.0, 1.0),
|
||||
Some(Value::String(a)) if a == "vertical" => Affine::scale_non_uniform(-1.0, 1.0),
|
||||
// A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page.
|
||||
let named = match p.get("axis") {
|
||||
Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)),
|
||||
Some(Value::Number(_)) => None,
|
||||
None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)),
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")));
|
||||
}
|
||||
};
|
||||
let m = match named {
|
||||
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
|
||||
None => {
|
||||
choice(p, "object.reflect", "basis", &["box", "page"])?;
|
||||
let t = -p.get("axis").and_then(Value::as_f64).unwrap_or(90.0).to_radians();
|
||||
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
|
||||
}
|
||||
};
|
||||
apply_transform(s, "Reflect", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user