From cb1796185e1c3af13ffa02bacb85bddb4711165c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:31:39 -0800 Subject: [PATCH 01/10] Symbols: Symbolism Tools Options gain Method, pen pressure and the Sprayer and Sizer options The Symbolism Tools Options dialog adds Use Pressure Pen, Method (User Defined, Average, Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density. A Tool row switches which tool's options show. symbol.adjust takes method, usePressure with [x, y, pressure] points, proportional and affectsDensity; symbol.spray takes attributes. The new symbol.setDensity gives the selected symbol sets a new Symbol Set Density, from the density each set was created at or last given, as one undo step. A symbolism stroke that changes no instance adds no undo step. --- crates/engine/src/cmd.rs | 4 + crates/engine/src/cmd/brushsym.rs | 18 +- crates/engine/src/cmd/brushsym/symbolism.rs | 369 ++++++++++++ crates/engine/src/cmd/brushsym/symbols.rs | 240 ++++++-- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/symbolism_options.rs | 559 ++++++++++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/settings.rs | 22 +- crates/tools/src/symbolism.rs | 238 +++++++- .../ui-egui/src/dialogs/symbolism_options.rs | 209 ++++++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 45 +- docs/target-app-parity.md | 1 + 14 files changed, 1637 insertions(+), 74 deletions(-) create mode 100644 crates/engine/src/cmd/brushsym/symbolism.rs create mode 100644 crates/engine/src/tests/symbolism_options.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 19695fd4ff..a56bcdbff8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -892,6 +892,10 @@ pub use buildcmds::live_paint_gaps; /// Control bar enable it when it changes one). pub use brushsym::reset_transformation_changes; +/// Whether an object is a symbol set (the Symbolism Tools Options' Symbol Set Density applies to +/// the selected ones). +pub use brushsym::is_symbol_set; + /// Command ids kept only so older scripts keep working: `(alias, the command it duplicates)`. /// They run as before but the command palette leaves them out (it lists the command once). pub const ALIASES: &[(&str, &str)] = &[("object.convertDocumentColorMode", "file.documentColorMode")]; diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 1046cada1c..3a31281f30 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -27,8 +27,12 @@ use crate::EngineError; /// Whether Reset Transformation changes a symbol instance. pub use symbols::reset_transformation_changes; +/// Whether an object is a symbol set. +pub use symbols::is_symbol_set; + mod brushes; mod dynamic; +mod symbolism; mod symbols; pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint}; @@ -38,6 +42,7 @@ use brushes::{ }; pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part}; use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance}; +use symbolism::symbol_set_density; use symbols::selected_instances; pub(crate) use symbols::{ expand_instances_under, expandable_instances, instance_in_place, natural_size, normalize, place_xf, set_natural_size, store_symbol, @@ -345,16 +350,25 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances)} spray instances into a symbol set → {id, count}", + "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), + cmd!( + "symbol.setDensity", + "Symbol Set Density", + [], + None, + "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and the sets moved then have density `to`; a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves (a set already at `to`, or sets of one instance). A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", + has_doc, + symbol_set_density + ), cmd!( "symbol.adjust", "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. No undo step is added when no instance changes (none under the brush, or average with each already at the mean). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs new file mode 100644 index 0000000000..f5df078745 --- /dev/null +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -0,0 +1,369 @@ +//! What the symbolism commands share: the Method and the Symbol Sprayer options of the Symbolism +//! Tools Options, what an instance shows of the values the tools change ([`Look`]), the mean of +//! those values under the brush ([`mean`]), and `symbol.setDensity`. + +use std::collections::HashMap; + +use super::symbols::{instance_center, is_symbol_set}; +use super::{Affine, Document, EngineError, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids}; + +/// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Method { + /// Gradually, in relation to the position of the pointer. + UserDefined, + /// Toward the mean of the instances under the brush. + Average, + /// By an amount that differs from instance to instance. + Random, +} + +/// The `method` of `symbol.adjust` (User Defined when left out or null). +pub(super) fn method_param(p: &Value, cmd: &str) -> Result { + match p.get("method") { + None | Some(Value::Null) => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "userDefined" => Ok(Method::UserDefined), + Some(Value::String(s)) if s == "average" => Ok(Method::Average), + Some(Value::String(s)) if s == "random" => Ok(Method::Random), + Some(v) => Err(bad(cmd, format!("`method` must be userDefined, average or random, not {v}"))), + } +} + +/// The Symbol Sprayer options: whether each value of a new instance is the average of the +/// instances under the brush (true) or the User Defined value (false). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct SprayModes { + pub scrunch: bool, + pub size: bool, + pub spin: bool, + pub screen: bool, + pub stain: bool, + pub style: bool, +} + +impl SprayModes { + /// Whether any value is an average. + pub fn any_average(self) -> bool { + self.scrunch || self.size || self.spin || self.screen || self.stain || self.style + } +} + +/// The `attributes` of `symbol.spray`: `{scrunch?, size?, spin?, screen?, stain?, style?}`, each +/// `average` (also when left out or null) or `userDefined`. Another key or value is an error. +pub(super) fn spray_modes(p: &Value, cmd: &str) -> Result { + let mut m = SprayModes { scrunch: true, size: true, spin: true, screen: true, stain: true, style: true }; + let map = match p.get("attributes") { + None | Some(Value::Null) => return Ok(m), + Some(Value::Object(map)) => map, + Some(v) => return Err(bad(cmd, format!("`attributes` must be an object, not {v}"))), + }; + for (key, v) in map { + let slot = match key.as_str() { + "scrunch" => &mut m.scrunch, + "size" => &mut m.size, + "spin" => &mut m.spin, + "screen" => &mut m.screen, + "stain" => &mut m.stain, + "style" => &mut m.style, + _ => return Err(bad(cmd, format!("unknown attribute `{key}`"))), + }; + *slot = match v { + Value::Null => true, + Value::String(s) if s == "average" => true, + Value::String(s) if s == "userDefined" => false, + v => return Err(bad(cmd, format!("attribute `{key}` must be average or userDefined, not {v}"))), + }; + } + Ok(m) +} + +/// How far apart the Symbol Sprayer keeps instances at Symbol Set Density `density` (1..10), as a +/// share of the symbol's size: a denser set is packed closer. +pub(super) fn spacing(density: f64) -> f64 { + (1.15 - density * 0.1).max(0.1) +} + +/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. +const SET_DENSITY_KEY: &str = "symbolSetDensity"; + +/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). +fn set_density_of(d: &Document, set: NodeId) -> Option { + d.unknown.get(SET_DENSITY_KEY)?.get(set.0.to_string())?.as_f64().filter(|v| (1.0..=10.0).contains(v)) +} + +/// Record `density` as the Symbol Set Density of `sets`, and drop the records of ids that are no +/// longer symbol sets. +pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64) { + let mut map = match d.unknown.get(SET_DENSITY_KEY) { + Some(Value::Object(m)) => m.clone(), + _ => serde_json::Map::new(), + }; + for set in sets { + map.insert(set.0.to_string(), json!(density)); + } + map.retain(|k, _| k.parse::().ok().and_then(|id| d.node(NodeId(id))).is_some_and(is_symbol_set)); + if map.is_empty() { + d.unknown.remove(SET_DENSITY_KEY); + } else { + d.unknown.insert(SET_DENSITY_KEY.into(), Value::Object(map)); + } +} + +/// What a symbol instance shows of the values the symbolism tools change. +#[derive(Clone, Debug)] +pub(super) struct Look { + pub center: Point, + /// Its size as a share of its symbol's own size (1: the symbol's size). + pub scale: f64, + /// Its rotation in radians. + pub angle: f64, + pub opacity: f64, + /// The fill the Symbol Stainer or the Symbol Styler gave it, with its amount (0..1). + pub fill: Option<(Paint, f64)>, +} + +/// The [`Look`] of instance `n` (None for another object, or an instance without a size). +pub(super) fn look(d: &Document, n: &Node) -> Option { + let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; + let [a, b, c, e, ..] = xf.as_coeffs(); + let natural = d.symbol_natural_xf(symbol).as_coeffs(); + let (sx, sy) = (natural[0].abs().max(1e-9), natural[3].abs().max(1e-9)); + let scale = ((a * e - b * c) / (sx * sy)).abs().sqrt(); + if !(scale.is_finite() && scale > 0.0) { + return None; + } + Some(Look { + center: instance_center(n)?, + scale, + angle: b.atan2(a), + opacity: f64::from(n.opacity), + fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))), + }) +} + +/// The mean of the [`Look`]s of the instances under the brush. +#[derive(Clone, Debug)] +pub(super) struct Mean { + /// The geometric mean of the sizes. + pub scale: f64, + /// The mean direction of the rotations. + pub angle: f64, + pub opacity: f64, + /// The mean stain or style amount; an instance without one counts as 0. + pub amount: f64, + /// The stain or style of the instance nearest the brush's center that has one. + pub paint: Option, + /// The middle of the instances. + pub middle: Point, + /// Their mean distance from [`Mean::middle`]. + pub reach: f64, + /// The mean distance from each of them to the nearest of the others (None for one instance, or + /// when not asked for). + pub gap: Option, +} + +/// For each of `looks`, the distance to the nearest of the others (infinite for one alone). Each +/// is first looked for in the cells around it of a grid `cell` points wide: one found within `cell` +/// is the nearest, since every one that near is in those cells. Otherwise all are measured. +fn nearest_gaps(looks: &[&Look], cell: f64) -> Vec { + let cell = cell.max(1e-6); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + let distance = |i: usize, j: usize| if i == j { None } else { Some(looks.get(j)?.center.distance(looks.get(i)?.center)) }; + (0..looks.len()) + .map(|i| { + let mut best = f64::INFINITY; + for j in around(&cells, looks.get(i).map_or(Point::ZERO, |l| l.center), cell) { + best = distance(i, j).map_or(best, |d| best.min(d)); + // Instances on top of each other: none can be nearer. + if best == 0.0 { + break; + } + } + if best <= cell { best } else { (0..looks.len()).filter_map(|j| distance(i, j)).fold(f64::INFINITY, f64::min) } + }) + .collect() +} + +/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with +/// [`Mean::gap`] when `gap_cell` gives the grid width [`nearest_gaps`] uses. +pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option) -> Option { + if looks.is_empty() { + return None; + } + let n = looks.len() as f64; + let (mut log_scale, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); + let mut paint: Option<(&Paint, f64)> = None; + for l in looks { + log_scale += l.scale.ln(); + sin += l.angle.sin(); + cos += l.angle.cos(); + opacity += l.opacity; + middle += l.center.to_vec2(); + if let Some((p, o)) = &l.fill { + amount += o; + let far = l.center.distance(at); + if paint.is_none_or(|(_, nearest)| far < nearest) { + paint = Some((p, far)); + } + } + } + let middle = (middle / n).to_point(); + // Rotations that cancel out have no mean direction: the first instance's stands for it. + let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle }; + // One instance under the brush has no spacing there. + let gap = gap_cell.filter(|_| looks.len() > 1).map(|cell| nearest_gaps(looks, cell).iter().sum::() / n); + Some(Mean { + scale: (log_scale / n).exp(), + angle, + opacity: opacity / n, + amount: amount / n, + paint: paint.map(|(p, _)| p.clone()), + middle, + reach: looks.iter().map(|l| l.center.distance(middle)).sum::() / n, + gap, + }) +} + +/// `angle` (radians) brought into −π..π. +pub(super) fn wrap_angle(angle: f64) -> f64 { + let turn = std::f64::consts::TAU; + let a = angle.rem_euclid(turn); + if a > std::f64::consts::PI { a - turn } else { a } +} + +/// The instances of a symbol set by where they are, to find those under a brush without looking at +/// every one for every point of a stroke. +pub(super) struct Grid { + cell: f64, + looks: Vec, + cells: HashMap<(i64, i64), Vec>, +} + +fn key(p: Point, cell: f64) -> (i64, i64) { + ((p.x / cell).floor() as i64, (p.y / cell).floor() as i64) +} + +/// The indices in the cell of `at`, then in the eight around it. Saturating: a point far out on the +/// canvas has a key at the end of the range. +fn around(cells: &HashMap<(i64, i64), Vec>, at: Point, cell: f64) -> impl Iterator + '_ { + let (cx, cy) = key(at, cell); + let ring = (cx.saturating_sub(1)..=cx.saturating_add(1)) + .flat_map(move |x| (cy.saturating_sub(1)..=cy.saturating_add(1)).map(move |y| (x, y))) + .filter(move |c| *c != (cx, cy)); + std::iter::once((cx, cy)).chain(ring).flat_map(move |c| cells.get(&c).into_iter().flatten().copied()) +} + +impl Grid { + /// `looks` in cells `cell` points wide (the brush's radius). + pub fn new(looks: Vec, cell: f64) -> Self { + let cell = cell.max(1.0); + let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); + for (i, l) in looks.iter().enumerate() { + cells.entry(key(l.center, cell)).or_default().push(i); + } + Self { cell, looks, cells } + } + + /// The mean of the instances within `radius` (at most the cell width) of `at`, with + /// [`Mean::gap`] when `with_gap` is set. + pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option { + let near: Vec<&Look> = + around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect(); + mean(&near, at, with_gap.then_some(radius / 4.0)) + } +} + +/// `symbol.setDensity {from, to, ids?|id?}`: space the instances of the selected symbol sets as +/// Symbol Set Density `to` packs them, from the density each set was created at or last given +/// (`from` for a set without one): each instance moves along the line from the middle of its set's +/// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it. +/// The sets moved then have density `to`. One undo step, and none when no instance moves. +pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { + const C: &str = "symbol.setDensity"; + let density = |key: &str| match p.get(key) { + Some(v) => v.as_f64().filter(|d| (1.0..=10.0).contains(d)).ok_or_else(|| bad(C, format!("`{key}` must be a number from 1 to 10, not {v}"))), + None => Err(bad(C, format!("missing `{key}`"))), + }; + let (from, to) = (density("from")?, density("to")?); + crate::cmd::edit::refuse_symbol_part(s)?; + let st = s.doc()?; + let d = &st.doc; + let named = named_ids(p)?; + let ids: Vec = named.clone().unwrap_or_else(|| st.selection.objects.clone()); + if let Some(missing) = named.iter().flatten().find(|id| d.node(**id).is_none()) { + return Err(EngineError::Other(format!("no object {}", missing.0))); + } + let editable = d.editable(); + let mut sets: Vec = vec![]; + for id in ids { + if d.node(id).is_some_and(is_symbol_set) && editable(id) && !sets.contains(&id) { + sets.push(id); + } + } + if sets.is_empty() { + return Err(EngineError::Other("no symbol set selected".into())); + } + let mut moves: Vec<(NodeId, Vec2)> = vec![]; + let mut changed: Vec = vec![]; + for set in &sets { + // A set packs from the density it was created at or last given, else from `from`. + let ratio = spacing(to) / spacing(set_density_of(d, *set).unwrap_or(from)); + let centers: Vec<(NodeId, Point)> = + d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect(); + if centers.len() < 2 { + continue; + } + let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point(); + let before = moves.len(); + // A locked or hidden instance stays where it is. + moves.extend( + centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9), + ); + if moves.len() > before { + changed.push(*set); + } + } + drop(editable); + if !moves.is_empty() { + s.edit("Symbol Set Density", |d, _| { + for (id, v) in &moves { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*v), false); + } + } + record_set_density(d, &changed, to); + Ok(()) + })?; + } + Ok(json!({ "ids": ids_json(&changed), "count": moves.len() })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(x: f64, y: f64) -> Look { + Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None } + } + + /// The gaps are each instance's distance to its nearest neighbor, measured against every other + /// instance: close pairs whose members are far apart in the order, instances on top of each + /// other, and instances farther apart than the grid's cells. + #[test] + fn nearest_gaps_match_measuring_every_pair() { + let mut looks: Vec = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect(); + // The second member of each pair comes 300 places later. + looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0))); + looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]); + let refs: Vec<&Look> = looks.iter().collect(); + let brute: Vec = (0..refs.len()) + .map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)) + .collect(); + assert_eq!(nearest_gaps(&refs, 10.0), brute); + assert_eq!(nearest_gaps(&refs[..1], 10.0), [f64::INFINITY]); + } +} diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 1bfb8edea7..4ba3b22b62 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,4 +1,5 @@ use super::dynamic::{fit_overrides, type_id, type_param}; +use super::symbolism::{Grid, Mean, Method, look, mean, method_param, record_set_density, spacing, spray_modes, wrap_angle}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, @@ -843,16 +844,40 @@ pub(super) fn symbol_select_instances(s: &mut Session, p: &Value) -> Result Result> { + Ok(samples(p, cmd)?.into_iter().map(|(q, _)| q).collect()) +} + +/// The stroke's points, each with its pen pressure: the third number of `[x, y, pressure]`, kept +/// within 0..1, and 1 for a point that gives none (or null). A pressure that isn't a number is an +/// error. +fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; - let v: Vec = a.iter().filter_map(|q| Some(Point::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(); - if v.is_empty() || v.iter().any(|q| !q.x.is_finite() || !q.y.is_finite()) { + let mut v = Vec::with_capacity(a.len()); + for q in a { + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + let pressure = match q.get(2) { + None | Some(Value::Null) => 1.0, + Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, + }; + v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); + } + if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { return Err(bad(cmd, "points must be finite [x,y] pairs")); } Ok(v) } +/// The fill of the graphic style `p` names with `style`, else of the document's first style after +/// the default one. +fn style_paint(d: &Document, p: &Value) -> Option { + match str_param(p, "style") { + Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), + None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), + } +} + /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). -fn jitter(i: usize, q: Point) -> (f64, f64, f64) { +pub(super) fn jitter(i: usize, q: Point) -> (f64, f64, f64) { let mut h: u64 = 0xcbf2_9ce4_8422_2325 ^ i as u64; for v in [(q.x * 16.0).round() as i64 as u64, (q.y * 16.0).round() as i64 as u64] { h ^= v; @@ -863,7 +888,8 @@ fn jitter(i: usize, q: Point) -> (f64, f64, f64) { (f(0), f(1), f(2)) } -fn is_symbol_set(n: &Node) -> bool { +/// Whether `n` is a symbol set: the group the Symbol Sprayer sprays instances into. +pub fn is_symbol_set(n: &Node) -> bool { matches!(n.kind, NodeKind::Group { clip: false, .. }) && n.name.as_deref() == Some("Symbol Set") } @@ -876,6 +902,13 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let density = number_or(p, "density", 5.0, C)?.clamp(1.0, 10.0); let scale = number_or(p, "scale", 1.0, C)?.clamp(0.01, 100.0); let alt = switch_or(p, "alt", false, C)?; + let modes = spray_modes(p, C)?; + crate::cmd::paint::check_keep_model(p, C)?; + let stain = match color_param(p, "color", C)? { + Some(c) => crate::cmd::paint::new_color(s, p, c), + None => s.paint.fill.color().unwrap_or(Color::BLACK), + }; + let style = style_paint(&st.doc, p); let size = natural_size(&st.doc, &name); let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); // Only a new Symbol Set needs a layer that takes new art. @@ -903,25 +936,63 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "count": n })); } // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * (1.15 - density * 0.1).max(0.1); - let mut placed: Vec = vec![]; + let min_gap = size.0.max(size.1) * scale * spacing(density); + // The instances the selected set has, for the values a new one takes as their average. + let existing = set.filter(|_| modes.any_average()).map(|g| { + let d = &st.doc; + let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c)).collect(); + Grid::new(looks, radius) + }); + // Each instance to add: where, the mean of the set's instances under the brush there, and the + // direction of the stroke there (None while the pointer has not moved). + let mut placed: Vec<(Point, Option, Option)> = vec![]; for (i, q) in pts.iter().enumerate() { let (jx, jy, _) = jitter(i, *q); let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); - if placed.last().is_some_and(|l| l.distance(c) < min_gap) && i > 0 { + let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch)); + // Scrunch: Average spaces new instances as the ones under the brush are spaced. + let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap); + if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 { continue; } - placed.push(c); + let along = pts.get(i + 1).unwrap_or(q).to_vec2() - pts.get(i.saturating_sub(1)).unwrap_or(q).to_vec2(); + placed.push((c, near, (along.hypot() > 1e-9).then_some(along))); } let count = placed.len(); let reg = s.doc()?.doc.symbol_registration(&name); let id = s.edit("Symbol Sprayer", |d, sel| { let mut nodes = vec![]; - for (i, c) in placed.iter().enumerate() { + for (i, (c, near, along)) in placed.iter().enumerate() { let (_, _, js) = jitter(i + 7, *c); - let k = scale * (1.0 + js * 0.1); + let near = near.as_ref(); + // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained + // with the fill color and given the style, each in full. + let k = near.filter(|_| modes.size).map_or(scale, |m| m.scale) * (1.0 + js * 0.1); + let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; + let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); - nodes.push(Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: place_xf(*c, size, reg) * Affine::scale(k) })); + let mut n = Node::new(id, NodeKind::SymbolInstance { symbol: name.clone(), xf: turn * place_xf(*c, size, reg) * Affine::scale(k) }); + if modes.screen + && let Some(m) = near + { + n.opacity = (m.opacity as f32).clamp(0.05, 1.0); + } + // The stain and the style are both the instance's fill: the style, set last, replaces + // the stain, an averaged one too when the instances under the brush have a fill. + let averaged = near.filter(|m| m.amount > 0.0).and_then(|m| Some((m.paint.clone()?, m.amount as f32))); + let mut fill = if modes.stain { averaged.clone() } else { Some((Paint::solid(stain), 1.0)) }; + if modes.style { + fill = averaged.or(fill); + } else if let Some(paint) = style.as_ref().filter(|p| !matches!(p, Paint::None)) { + // A style without a fill (the default style) gives none. + fill = Some((paint.clone(), 1.0)); + } + if let Some((paint, amount)) = fill { + let mut f = FillLayer::new(paint); + f.opacity = amount.clamp(0.0, 1.0); + n.appearance.items.insert(0, AppearanceItem::Fill(f)); + } + nodes.push(n); } let gid = match set { Some(g) => { @@ -938,13 +1009,18 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { gid } }; + // A new set has the density it is sprayed at; more instances sprayed into a set leave the + // density the set has. + if set.is_none() { + record_set_density(d, &[gid], density); + } sel.set([gid]); Ok(gid) })?; Ok(json!({ "id": id.0, "count": count })) } -fn instance_center(n: &Node) -> Option { +pub(super) fn instance_center(n: &Node) -> Option { match &n.kind { NodeKind::SymbolInstance { xf, .. } => Some(*xf * Point::ZERO), _ => None, @@ -958,10 +1034,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("unknown tool `{tool}`"))); } crate::cmd::paint::check_keep_model(p, C)?; - let pts = points(p, C)?; + let pts = samples(p, C)?; let radius = number_or(p, "radius", 40.0, C)?.clamp(1.0, 2000.0); let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; + let use_pressure = switch_or(p, "usePressure", false, C)?; + let proportional = switch_or(p, "proportional", true, C)?; + let affects_density = switch_or(p, "affectsDensity", false, C)?; + // The Symbol Shifter has no Method. + let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. crate::cmd::edit::refuse_symbol_part(s)?; let st = s.doc()?; @@ -969,10 +1050,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; - let style_paint = match str_param(p, "style") { - Some(n) => st.doc.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => st.doc.graphic_styles.get(1).or(st.doc.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - }; + let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; let mut v = vec![]; @@ -1002,62 +1080,144 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "screen" => "Symbol Screener", _ => "Symbol Styler", }; - let count = s.edit(label, |d, _| { + // Random: each instance's share of the tool's change, from none of it to twice it, the same + // for the whole stroke (and for every preview of it). + let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); + let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // No undo step when no instance changes (none under the brush, or Average with each at the mean). + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { let mut touched = std::collections::BTreeSet::new(); - for (j, q) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1] } else { Vec2::ZERO }; + for (j, (q, pressure)) in pts.iter().enumerate() { + let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + // Use Pressure Pen: the pen's pressure at the point is the intensity there. + let strength = if use_pressure { *pressure } else { intensity }; + // Average: the mean of the instances under the brush, as they are at this point. + let target = (method == Method::Average) + .then(|| { + let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); + let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect(); + mean(&looks.iter().collect::>(), *q, None) + }) + .flatten(); for id in &candidates { - let Some(n) = d.node_mut(*id) else { continue }; - let Some(c) = instance_center(n) else { continue }; + let Some(c) = d.node(*id).and_then(instance_center) else { continue }; let dist = c.distance(*q); if dist > radius { continue; } - let w = intensity * (1.0 - dist / radius).max(0.0); + let w = strength * (1.0 - dist / radius).max(0.0); if w <= 0.0 { continue; } + let Some(cur) = d.node(*id).and_then(|n| look(d, n)) else { continue }; + // Average leaves an instance that already has the mean as it is. + let at_mean = target.as_ref().is_some_and(|t| match tool.as_str() { + "scrunch" => { + let out = (c - t.middle).hypot(); + out <= 1e-9 || (t.reach - out).abs() < 1e-9 + } + "size" => (t.scale / cur.scale - 1.0).abs() < 1e-9, + "spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9, + "stain" | "style" => { + (t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none()) + } + "screen" => (t.opacity - cur.opacity).abs() < 1e-6, + _ => false, + }); + if at_mean { + continue; + } + let Some(n) = d.node_mut(*id) else { continue }; touched.insert(*id); let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); + let share = share(*id); match tool.as_str() { "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), "scrunch" => { - let v = (*q - c) * (0.15 * w) * if alt { -1.0 } else { 1.0 }; + let v = match &target { + // Toward the instances' mean distance from their middle. + Some(t) => { + let out = c - t.middle; + if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO } + } + None => (*q - c) * (0.15 * w * share) * if alt { -1.0 } else { 1.0 }, + }; n.transform(Affine::translate(v), false); } "size" => { - let k = 1.0 + 0.08 * w; - n.transform(about(Affine::scale(if alt { 1.0 / k } else { k })), false); + let k = match &target { + Some(t) => (t.scale / cur.scale).powf(w.min(1.0)), + None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), + }; + // Without Proportional Resizing a drag resizes along its own direction: a + // level drag the width, an upright one the height. A click resizes both. + // The first point of a drag takes the direction to the second. + let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) }; + let (kx, ky) = if proportional || target.is_some() || along.hypot() <= 1e-9 { + (k, k) + } else { + let level = along.x.abs() / (along.x.abs() + along.y.abs()); + (k.powf(2.0 * level), k.powf(2.0 * (1.0 - level))) + }; + n.transform(about(Affine::scale_non_uniform(kx, ky)), false); + // Resizing Affects Density: instances move away from the brush's center as + // they grow and toward it as they shrink. + if affects_density { + n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); + } } "spin" => { - // Turn towards the drag direction; a click spins a little. - let a = if delta.hypot() > 1e-9 { (c - *q).cross(delta).signum() * 0.1 * w } else { 0.05 * w }; - n.transform(about(Affine::rotate(if alt { -a } else { a })), false); + let a = match (&target, method) { + (Some(t), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), + // A turn either way, whichever way the drag runs. + (None, Method::Random) => 0.1 * w * (share - 1.0), + // Turn towards the drag direction; a click spins a little. + (None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w, + (None, _) => 0.05 * w, + }; + n.transform(about(Affine::rotate(if alt && target.is_none() { -a } else { a })), false); } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } - let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); - let step = if tool == "style" { 1.0 } else { 0.15 * w as f32 }; - let o = if alt { (cur - step).max(0.0) } else { (cur + step).min(1.0) }; + let (paint, o) = match &target { + // Toward the mean amount, keeping the stain or style the instance has. + Some(t) => { + let (own, cur) = cur.fill.map_or((None, 0.0), |(p, o)| (Some(p), o)); + (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) + } + None => { + if tool == "style" && alt { + n.appearance.items.clear(); + continue; + } + let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + let step = match (tool.as_str(), method) { + ("style", Method::Random) => (share / 2.0) as f32, + ("style", _) => 1.0, + _ => (0.15 * w * share) as f32, + }; + (paint, if alt { cur - step } else { cur + step }) + } + }; n.appearance.items.retain(|i| !matches!(i, AppearanceItem::Fill(_))); if o > 0.0 { let mut f = FillLayer::new(paint); - f.opacity = o; + f.opacity = o.min(1.0); n.appearance.items.insert(0, AppearanceItem::Fill(f)); } } _ => { - let step = (0.1 * w) as f32; - n.opacity = if alt { (n.opacity + step).min(1.0) } else { (n.opacity - step).max(0.05) }; + let step = (0.1 * w * share) as f32; + n.opacity = match &target { + Some(t) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.05, 1.0), + None if alt => (n.opacity + step).min(1.0), + None => (n.opacity - step).max(0.05), + }; } } } } - Ok(touched.len()) + Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 5329f23331..708d845c4b 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -603,6 +603,7 @@ pub(super) const ALLOWED: &[&str] = &[ "symbol.replace", "symbol.selectInstances", "symbol.setCurrent", + "symbol.setDensity", "symbol.sortByName", "symbol.spray", "symbol.unused", diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f849901a4..262f8e980e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -193,6 +193,7 @@ mod swatchlib; mod symbol_nine_slice; mod symbolbounds; mod symboledit; +mod symbolism_options; mod symbollib; mod targeting; mod textcombos; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs new file mode 100644 index 0000000000..05b707f799 --- /dev/null +++ b/crates/engine/src/tests/symbolism_options.rs @@ -0,0 +1,559 @@ +//! The Symbolism Tools Options the commands take: Method and pen pressure in `symbol.adjust`, the +//! Symbol Sizer's two options, the Symbol Sprayer's `attributes`, and `symbol.setDensity`. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" (its first instance is at 10, 10) and nothing +/// selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn bounds(s: &Session, id: NodeId) -> Rect { + node(s, id).geometric_bounds().unwrap() +} + +fn xf(s: &Session, id: NodeId) -> Affine { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf, + other => panic!("not an instance: {other:?}"), + } +} + +fn center(s: &Session, id: NodeId) -> Point { + xf(s, id) * Point::ZERO +} + +/// The instance's rotation in radians. +fn angle(s: &Session, id: NodeId) -> f64 { + let c = xf(s, id).as_coeffs(); + c[1].atan2(c[0]) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// `cmd` with `p` fails with the bad-parameter message `want` and leaves the document and the +/// undo history as they were. +fn refused(s: &mut Session, cmd: &str, p: Value, want: &str) { + let before = state(s); + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{cmd} {p}: {r:?}"); + assert!(state(s) == before, "{cmd} {p} changed the document"); +} + +/// The children of symbol set `set`. +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// Method Average brings the sizes, rotations and opacities of the instances under the brush +/// toward their mean, whichever way Alt is; User Defined changes each one by the same amount. +#[test] +fn average_brings_the_instances_under_the_brush_toward_their_mean() { + // Two instances 20 pt apart, the first grown, turned and faded alone. + let pair = || { + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + let only_a = json!([[200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "spin", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": only_a, "radius": 5, "intensity": 10})); + } + (s, a, b) + }; + let (mut s, a, b) = pair(); + let (wa, wb) = (bounds(&s, a).width(), bounds(&s, b).width()); + let (ra, oa) = (angle(&s, a), node(&s, a).opacity); + assert!(wa > wb + 1.0 && ra.abs() > 0.1 && oa < 0.9, "{wa} {wb} {ra} {oa}"); + assert_eq!((angle(&s, b), node(&s, b).opacity), (0.0, 1.0)); + // User Defined grows both by the same factor: they stay as far apart in size. + let between = json!([[210, 150], [210, 150], [210, 150]]); + let (mut user, ..) = pair(); + adjust(&mut user, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10})); + let ratio = |s: &Session| xf(s, a).determinant() / xf(s, b).determinant(); + assert!((ratio(&user) - ratio(&s)).abs() < 1e-9); + // Average: the two sizes meet at their geometric mean. + let before = ratio(&s); + let product = xf(&s, a).determinant() * xf(&s, b).determinant(); + let (mut alt, ..) = pair(); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + assert!((ratio(&s) - 1.0).abs() < (before - 1.0).abs() / 2.0, "{} from {before}", ratio(&s)); + assert!((xf(&s, a).determinant() * xf(&s, b).determinant() / product - 1.0).abs() < 1e-9); + adjust(&mut alt, json!({"tool": "size", "points": between, "radius": 40, "intensity": 10, "method": "average", "alt": true})); + assert_eq!([xf(&alt, a), xf(&alt, b)], [xf(&s, a), xf(&s, b)], "Alt does not reverse an average"); + // The rotations and the opacities meet too. + adjust(&mut s, json!({"tool": "spin", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (na, nb) = (angle(&s, a), angle(&s, b)); + assert!((na - nb).abs() < ra.abs() / 2.0 && nb.abs() > 1e-3, "{na} {nb} from {ra}"); + adjust(&mut s, json!({"tool": "screen", "points": between, "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); +} + +/// Average over instances that already have the mean, or a stroke over no instance, changes +/// nothing and adds no undo step. +#[test] +fn average_at_the_mean_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let before = state(&s); + for tool in ["scrunch", "size", "spin", "stain", "screen", "style"] { + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150], [202, 150]], "radius": 30, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } + let r = adjust(&mut s, json!({"tool": "size", "points": [[50, 50]], "radius": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. +#[test] +fn average_evens_out_the_stain_and_the_spacing() { + let mut s = session(); + let (a, b, c) = (dot(&mut s, 180.0, 150.0), dot(&mut s, 200.0, 150.0), dot(&mut s, 260.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[180, 150], [180, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let amount = |s: &Session, id| node(s, id).appearance.fill().map_or(0.0, |f| f.opacity); + let stained = amount(&s, a); + assert!(stained > 0.2 && amount(&s, b) == 0.0); + adjust( + &mut s, + json!({"tool": "stain", "points": [[190, 150], [190, 150]], "radius": 30, "intensity": 10, "method": "average", "color": "#0000ff"}), + ); + assert!(amount(&s, a) < stained && amount(&s, b) > 0.0, "{} {}", amount(&s, a), amount(&s, b)); + // The stained instance keeps its red, and the other takes the red of the stained one. + for id in [a, b] { + assert_eq!(node(&s, id).appearance.fill().and_then(|f| f.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + } + // Scrunch: the three are 20 and 60 apart; their distances from their middle even out. + let reach = |s: &Session| { + let xs = [a, b, c].map(|id| center(s, id).x); + let middle = xs.iter().sum::() / 3.0; + xs.map(|x| (x - middle).abs()) + }; + let spread = |r: [f64; 3]| r.iter().cloned().fold(0.0, f64::max) - r.iter().cloned().fold(f64::INFINITY, f64::min); + let before = spread(reach(&s)); + adjust(&mut s, json!({"tool": "scrunch", "points": [[213, 150], [213, 150]], "radius": 120, "intensity": 10, "method": "average"})); + assert!(spread(reach(&s)) < before * 0.8, "{} from {before}", spread(reach(&s))); +} + +/// Method Random gives each instance its own share of the change, the same for a stroke however +/// often it is applied; User Defined changes instances at the same distance alike. +#[test] +fn random_changes_each_instance_by_its_own_share() { + let grown = |method: Option<&str>| { + let mut s = session(); + let ids = [(180.0, 150.0), (220.0, 150.0), (200.0, 130.0), (200.0, 170.0)].map(|(x, y)| dot(&mut s, x, y)); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10}); + if let Some(m) = method { + p["method"] = json!(m); + } + adjust(&mut s, p); + ids.map(|id| bounds(&s, id).width()) + }; + let user = grown(None); + assert!(user.iter().all(|w| (w - user[0]).abs() < 1e-9 && *w > 20.5), "{user:?}"); + assert_eq!(grown(Some("userDefined")), user); + let random = grown(Some("random")); + assert!(random.iter().any(|w| (w - random[0]).abs() > 0.05), "{random:?}"); + // From none of the User Defined change to twice it. + let twice = user[0] * user[0] / 20.0; + assert!(random.iter().all(|w| *w >= 20.0 - 1e-9 && *w <= twice + 1e-9), "{random:?} within 20..{twice}"); + assert_eq!(grown(Some("random")), random); +} + +/// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes +/// one and shifts as it does without. +#[test] +fn an_unknown_method_is_refused() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (bad, shown) in [(json!("smooth"), "\"smooth\""), (json!(3), "3"), (json!(true), "true"), (json!("Average"), "\"Average\"")] { + for tool in ["size", "shift"] { + let want = format!("`method` must be userDefined, average or random, not {shown}"); + refused(&mut s, "symbol.adjust", json!({"tool": tool, "points": [[200, 150]], "method": bad}), &want); + } + } + let shifted = |method: Value| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [215, 150]], "intensity": 10, "method": method})); + center(&s, a) + }; + let moved = shifted(Value::Null); + assert!(moved.x > 205.0); + for method in ["average", "random", "userDefined"] { + assert_eq!(shifted(json!(method)), moved, "{method}"); + } + assert_eq!(center(&s, a), Point::new(200.0, 150.0)); +} + +/// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is +/// not used. A pressure that isn't a number is an error. +#[test] +fn pen_pressure_is_the_intensity_with_use_pressure() { + let width = |points: Value, use_pressure: Option, intensity: f64| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 40, "intensity": intensity}); + if let Some(on) = use_pressure { + p["usePressure"] = json!(on); + } + let count = adjust(&mut s, p)["count"].as_u64().unwrap(); + (bounds(&s, a).width(), count) + }; + let (light, _) = width(json!([[200, 150, 0.25]]), Some(true), 5.0); + let (hard, _) = width(json!([[200, 150, 1.0]]), Some(true), 5.0); + assert!(20.0 < light && light < hard, "{light} {hard}"); + // Full pressure is intensity 10, whatever `intensity` says; a point without a pressure has 1. + assert_eq!(width(json!([[200, 150]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150]]), Some(true), 1.0).0, hard); + assert_eq!(width(json!([[200, 150, null]]), Some(true), 1.0).0, hard); + // No pressure: the instance stays as it is. + assert_eq!(width(json!([[200, 150, 0]]), Some(true), 5.0), (20.0, 0)); + // A pressure outside 0..1 is kept within it. + assert_eq!(width(json!([[200, 150, 7]]), Some(true), 5.0).0, hard); + // Without Use Pressure Pen the pressure is not used. + assert_eq!(width(json!([[200, 150, 0.25]]), None, 10.0).0, hard); + assert_eq!(width(json!([[200, 150, 0.25]]), Some(false), 10.0).0, hard); + let mut s = session(); + dot(&mut s, 200.0, 150.0); + for tool in ["size", "shift"] { + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), + "a point's pressure must be a number, not \"hard\"", + ); + } + for key in ["usePressure", "proportional", "affectsDensity"] { + let mut p = json!({"tool": "size", "points": [[200, 150]]}); + p[key] = json!("yes"); + refused(&mut s, "symbol.adjust", p, &format!("`{key}` must be true or false")); + } +} + +/// The Symbol Sizer without Proportional Resizing resizes along the drag: a level drag the width, +/// an upright one the height, a click both. +#[test] +fn the_sizer_without_proportional_resizing_resizes_along_the_drag() { + let size = |points: Value, proportional: Option| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + let mut p = json!({"tool": "size", "points": points, "radius": 60, "intensity": 10}); + if let Some(on) = proportional { + p["proportional"] = json!(on); + } + adjust(&mut s, p); + (bounds(&s, a).width(), bounds(&s, a).height()) + }; + let level = json!([[195, 150], [205, 150]]); + let (w, h) = size(level.clone(), Some(false)); + assert!(w > 21.0 && (h - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 145], [200, 155]]), Some(false)); + assert!(h > 21.0 && (w - 20.0).abs() < 1e-9, "{w} x {h}"); + let (w, h) = size(json!([[200, 150]]), Some(false)); + assert!(w > 20.5 && (w - h).abs() < 1e-9, "{w} x {h}"); + // Proportional Resizing (the default) keeps the shape for any drag, at the same area. + let (pw, ph) = size(level.clone(), None); + assert!(pw > 20.5 && (pw - ph).abs() < 1e-9, "{pw} x {ph}"); + assert_eq!(size(level.clone(), Some(true)), (pw, ph)); + let (w, h) = size(level, Some(false)); + assert!((w * h - pw * ph).abs() < 1e-6, "{w} x {h} against {pw} x {ph}"); +} + +/// With Resizing Affects Density an instance moves away from the brush's center as it grows and +/// toward it as it shrinks; without, it stays where it is. +#[test] +fn resizing_affects_density_moves_instances_from_the_brush_center() { + let at = |affects: Option, alt: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + let mut p = json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "alt": alt}); + if let Some(on) = affects { + p["affectsDensity"] = json!(on); + } + adjust(&mut s, p); + (center(&s, a), bounds(&s, a).width()) + }; + let (stays, grown) = at(None, false); + assert!((stays.x - 220.0).abs() < 1e-9 && grown > 20.5); + assert_eq!(at(Some(false), false), (stays, grown)); + let (away, width) = at(Some(true), false); + assert!(away.x > 220.5 && (away.y - 150.0).abs() < 1e-9 && width > 20.5, "{away:?}"); + let (toward, width) = at(Some(true), true); + assert!(toward.x < 219.5 && width < 19.5, "{toward:?}"); +} + +/// A new instance of the Symbol Sprayer takes the mean of the selected set's instances under the +/// brush for each attribute that is `average`, and the plain value for each that is `userDefined`. +#[test] +fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + // In an area without instances an average is the plain value. + assert!(node(&s, first).opacity == 1.0 && node(&s, first).appearance.fill().is_none() && angle(&s, first) == 0.0); + // Grow, fade and stain the set's one instance. + let on_it = json!([[200, 150], [200, 150], [200, 150], [200, 150], [200, 150], [200, 150]]); + for tool in ["size", "screen", "stain"] { + adjust(&mut s, json!({"tool": tool, "points": on_it, "radius": 40, "intensity": 10, "color": "#ff0000"})); + } + let look = |s: &Session, id: NodeId| { + let n = node(s, id); + (bounds(s, id).width(), n.opacity, n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity))) + }; + let (width, opacity, stain) = look(&s, first); + assert!(width > 24.0 && opacity < 0.7 && stain.as_ref().is_some_and(|(_, amount)| *amount > 0.5), "{width} {opacity} {stain:?}"); + let spray = |s: &mut Session, at: Value, extra: Value| { + let mut p = json!({"name": "Dot", "points": at, "radius": 30}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("symbol.spray", &p).unwrap(); + *members(s, set).last().unwrap() + }; + // Average (the default): the new instance, sprayed beside it, looks like it. + let near = spray(&mut s, json!([[215, 150]]), json!({})); + let (w, o, f) = look(&s, near); + assert!((w / width - 1.0).abs() < 0.11, "{w} of {width}"); + assert_eq!((o, f), (opacity, stain.clone())); + // The averages of two instances that look alike are theirs. + let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}})); + assert_eq!(look(&s, third).1, opacity); + // Style: Average replaces a User Defined stain with the fill of the instances under the brush. + let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"})); + assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + // Outside the brush's radius of every instance, the plain values. + let far = spray(&mut s, json!([[330, 250]]), json!({})); + let (w, o, f) = look(&s, far); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); + // User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush. + let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"}); + let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"})); + let (w, o, f) = look(&s, plain); + assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0, "{w} {o}"); + assert_eq!(f.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); + assert_eq!(angle(&s, plain), 0.0, "one point has no direction"); + // With no fill under the brush, Stain: User Defined is the fill color in full, and a User Defined + // style without a fill (the document has only the default style) leaves it. + let blue = spray(&mut s, json!([[330, 40]]), json!({"attributes": user, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + let styled = json!({"stain": "userDefined", "style": "userDefined"}); + let blue = spray(&mut s, json!([[330, 100]]), json!({"attributes": styled, "color": "#0000ff"})); + assert_eq!(look(&s, blue).2, Some((Some("#0000ff".to_string()), 1.0))); + // Spin: User Defined turns the instances the way the stroke runs (here: down the page). + let down = spray(&mut s, json!([[100, 40], [100, 140]]), json!({"attributes": {"spin": "userDefined"}})); + assert!((angle(&s, down) - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{}", angle(&s, down)); + let level = spray(&mut s, json!([[40, 260], [140, 260]]), json!({})); + assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush"); +} + +/// Spin: Average turns a new instance to the mean direction of the instances under the brush, and +/// Scrunch: Average spaces new instances as those under the brush are spaced. +#[test] +fn the_sprayer_averages_rotation_and_spacing() { + // A set of six instances 30 pt apart, turned by a drag of the Symbol Spinner; then a stroke + // along the row, 4 pt between its points, with Scrunch as given. Returns the rotations of the + // six, how many instances the stroke added and the rotation of the last one. + let sprayed = |scrunch: &str| { + let mut s = session(); + let row: Vec = (0..6).map(|i| json!([100.0 + 30.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": row, "radius": 2, "density": 10}); + let set = NodeId(s.execute("symbol.spray", &p).unwrap()["id"].as_u64().unwrap()); + assert_eq!(members(&s, set).len(), 6); + adjust(&mut s, json!({"tool": "spin", "points": [[175, 60], [176, 60], [177, 60], [178, 60]], "radius": 200, "intensity": 10})); + let turned: Vec = members(&s, set).iter().map(|id| angle(&s, *id)).collect(); + let stroke: Vec = (0..40).map(|i| json!([100.0 + 4.0 * f64::from(i), 100.0])).collect(); + let p = json!({"name": "Dot", "points": stroke, "radius": 40, "density": 10, "attributes": {"scrunch": scrunch}}); + let n = s.execute("symbol.spray", &p).unwrap()["count"].as_u64().unwrap(); + let new = *members(&s, set).last().unwrap(); + (turned, n, angle(&s, new)) + }; + let (turned, plain, _) = sprayed("userDefined"); + assert!(turned.iter().all(|a| a.abs() > 0.05 && a.signum() == turned[0].signum()), "{turned:?}"); + // User Defined keeps new instances 3 pt apart (20 pt × 0.15 at density 10); Average keeps them + // as far apart as the instances under the brush are, about 30 pt. + let (_, spaced, new_angle) = sprayed("average"); + assert!(spaced < plain, "{spaced} spaced like the row against {plain}"); + assert!(new_angle.signum() == turned[0].signum() && new_angle.abs() > 0.05, "{new_angle} against {turned:?}"); +} + +/// The Symbol Sprayer's `attributes` must be an object of the six keys, each `average` or +/// `userDefined`; anything else is an error and sprays nothing. +#[test] +fn bad_sprayer_attributes_are_refused() { + let mut s = session(); + let calls = [ + (json!("average"), "`attributes` must be an object, not \"average\"".to_string()), + (json!(["size"]), "`attributes` must be an object, not [\"size\"]".to_string()), + (json!({"density": "average"}), "unknown attribute `density`".to_string()), + (json!({"size": "big"}), "attribute `size` must be average or userDefined, not \"big\"".to_string()), + (json!({"spin": true}), "attribute `spin` must be average or userDefined, not true".to_string()), + (json!({"style": "Average"}), "attribute `style` must be average or userDefined, not \"Average\"".to_string()), + ]; + for (attributes, want) in calls { + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "attributes": attributes}), &want); + } + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false"); + refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\""); + let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); + assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1); +} + +/// `symbol.setDensity` spaces a symbol set's instances from its middle as the new density packs +/// them, as one undo step, and adds none when no instance moves. +#[test] +fn set_density_spaces_the_instances_of_a_symbol_set() { + let mut s = session(); + let row: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 8); + let centers = |s: &Session| ids.iter().map(|id| center(s, *id)).collect::>(); + let middle = |c: &[Point]| Point::new(c.iter().map(|p| p.x).sum::() / 8.0, c.iter().map(|p| p.y).sum::() / 8.0); + let (was, steps) = (centers(&s), undo_len(&s)); + // From 5 to 9: 0.25 / 0.65 of each distance from the middle, which stays where it is. + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert_eq!(undo_len(&s), steps + 1); + let now = centers(&s); + let (m, ratio) = (middle(&was), 0.25 / 0.65); + assert!(middle(&now).distance(m) < 1e-9); + for (before, after) in was.iter().zip(&now) { + assert!(after.distance(m + (*before - m) * ratio) < 1e-9, "{before:?} -> {after:?}"); + } + // Back from 9 to 5: where they were, once for a set named twice. + let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap(); + assert_eq!(r, json!({"ids": [set.0], "count": 8})); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); + // The density the set has (5, a `from` of 7 notwithstanding), or a set of one instance: no + // instance moves and no undo step is added. + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0})); + s.select(|_, sel| sel.clear()).unwrap(); + let one = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 40]]})).unwrap()["id"].as_u64().unwrap()); + let steps_with_one = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 1, "to": 10, "ids": [one.0]})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!((steps_with_one, undo_len(&s)), (steps + 1, steps + 1)); + // Undo puts a spaced set back. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap(); + assert!(centers(&s)[0].distance(was[0]) > 1.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); +} + +/// A set packs from the density it was created at, whatever `from` says and whatever density more +/// instances were sprayed into it at; a set without a recorded density packs from `from`. +#[test] +fn set_density_starts_from_the_density_a_set_was_sprayed_at() { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})).unwrap(); + let ratio = 0.25 / 0.95; + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * ratio)).abs() < 1e-9, "{before} -> {after}"); + } + // Given density 2, the set stays at 2 when more instances are sprayed into it at 9. + s.execute("symbol.setDensity", &json!({"from": 5, "to": 2, "ids": [set.0]})).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 200]], "radius": 4, "density": 9})).unwrap(); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 9, "to": 2, "ids": [set.0]})).unwrap()["count"], 0); + // Without the record (a set grouped by hand), `from` is the starting density. + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 200.0, 150.0)); + s.select(|_, sel| sel.set([a, b])).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(group) { + n.name = Some("Symbol Set".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [group.0]})).unwrap(); + assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); +} + +/// A locked instance of the set stays where it is, and the others move. +#[test] +fn set_density_leaves_a_locked_instance_in_place() { + let mut s = session(); + let row: Vec = (0..3).map(|i| json!([100.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + s.edit("Lock", |d, _| { + if let Some(n) = d.node_mut(ids[0]) { + n.locked = true; + } + Ok(()) + }) + .unwrap(); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + assert!(r["count"].as_u64().is_some_and(|n| (1..=2).contains(&n)), "{r}"); + assert_eq!(center(&s, ids[0]), was[0]); + assert!(center(&s, ids[2]).distance(was[2]) > 1.0); +} + +/// `symbol.setDensity` refuses a density left out, not a number or outside 1..10, an id naming no +/// object, and objects with no symbol set among them. +#[test] +fn set_density_refuses_bad_densities_and_objects_without_a_set() { + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + for (p, want) in [ + (json!({"to": 5}), "missing `from`".to_string()), + (json!({"from": 5}), "missing `to`".to_string()), + (json!({"from": "5", "to": 6}), "`from` must be a number from 1 to 10, not \"5\"".to_string()), + (json!({"from": 5, "to": 11}), "`to` must be a number from 1 to 10, not 11".to_string()), + (json!({"from": 0, "to": 5}), "`from` must be a number from 1 to 10, not 0".to_string()), + (json!({"from": null, "to": 5}), "`from` must be a number from 1 to 10, not null".to_string()), + ] { + refused(&mut s, "symbol.setDensity", p, &want); + } + let before = state(&s); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [987_654]})).is_err()); + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": "all"})).is_err()); + // An instance is not a set, and neither is nothing selected. + let member = members(&s, set)[0]; + assert!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [member.0]})).is_err()); + s.select(|_, sel| sel.clear()).unwrap(); + let r = s.execute("symbol.setDensity", &json!({"from": 5, "to": 9})); + assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); + assert!(state(&s) == before); +} diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index e801df4a7a..1ecdb6c98a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -937,7 +937,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index a4d1b1a64f..5603a0795d 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -23,7 +23,27 @@ const ROWS: &[Row] = &[ // Global Brush Dimensions. (LIQUIFY, Some("liquify"), &["width", "height", "angle", "intensity", "usePressure", "showBrush"]), (LIQUIFY, None, &["detail", "simplify", "simplifyOn", "rate", "complexity", "horizontal", "vertical", "affectAnchors", "affectIn", "affectOut"]), - (SYMBOLISM, Some("symbolism"), &["diameter", "intensity", "density"]), + // Symbolism Tools Options: the general options, then the Symbol Sprayer's and the Symbol Sizer's. + ( + SYMBOLISM, + Some("symbolism"), + &[ + "diameter", + "intensity", + "density", + "usePressure", + "method", + "showBrush", + "sprayScrunch", + "spraySize", + "spraySpin", + "sprayScreen", + "sprayStain", + "sprayStyle", + "proportional", + "affectsDensity", + ], + ), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 580e61d4fd..f407792170 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -23,9 +23,26 @@ pub fn create(id: &str) -> Option> { }) } +/// The values of Method in the Symbolism Tools Options. +pub const METHODS: [&str; 3] = ["userDefined", "average", "random"]; + +/// The values of each Symbol Sprayer option in the Symbolism Tools Options. +pub const SPRAY_MODES: [&str; 2] = ["average", "userDefined"]; + +/// The Symbol Sprayer options: (tool option, key in `symbol.spray`'s `attributes`). +pub const SPRAY_ATTRIBUTES: [(&str, &str); 6] = [ + ("sprayScrunch", "scrunch"), + ("spraySize", "size"), + ("spraySpin", "spin"), + ("sprayScreen", "screen"), + ("sprayStain", "stain"), + ("sprayStyle", "style"), +]; + pub struct SymbolismTool { id: &'static str, - points: Vec, + /// The drag's points, each with its pen pressure (0..1). + points: Vec<(Point, f64)>, /// How many points the last preview had ([`previews_at`] thins previews of a long drag). previewed: usize, active: bool, @@ -41,6 +58,24 @@ pub struct SymbolismTool { pub symbol: Option, /// Graphic style for the Styler (None = the document's first non-default style). pub style: Option, + /// Use Pressure Pen: each point's pen pressure is the intensity there. + pub use_pressure: bool, + /// Method of the Scruncher, Sizer, Spinner, Stainer, Screener and Styler: one of [`METHODS`]. + pub method: &'static str, + /// Show Brush Size and Intensity: the brush outline follows the pointer. + pub show_brush: bool, + /// The Symbol Sprayer options, in the order of [`SPRAY_ATTRIBUTES`]: each one of [`SPRAY_MODES`]. + pub spray: [&'static str; 6], + /// Symbol Sizer: Proportional Resizing. + pub proportional: bool, + /// Symbol Sizer: Resizing Affects Density. + pub affects_density: bool, +} + +/// `v` as one of `allowed`, when it is one. +fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { + let s = v.as_str()?; + allowed.iter().copied().find(|a| *a == s) } impl SymbolismTool { @@ -67,6 +102,12 @@ impl SymbolismTool { density: 5.0, symbol: None, style: None, + use_pressure: false, + method: "userDefined", + show_brush: true, + spray: ["average"; 6], + proportional: true, + affects_density: false, } } @@ -86,14 +127,28 @@ impl SymbolismTool { /// The command + params for the gesture so far. pub fn command(&self, cx: &ToolContext) -> (String, Value) { let radius = self.diameter / 2.0; - let pts = points_json(&self.points); if self.id == "symbolSprayer" { - let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt}); + let pts = points_json(&self.points.iter().map(|(p, _)| *p).collect::>()); + let attributes: serde_json::Map = + SPRAY_ATTRIBUTES.iter().zip(self.spray).map(|((_, key), mode)| (key.to_string(), json!(mode))).collect(); + let mut v = json!({"points": pts, "radius": radius, "density": self.density, "alt": self.alt, "attributes": attributes}); if let Some(s) = &self.symbol { v["name"] = json!(s); } + // Stain: User Defined stains the new instances with the fill color in its own model. + if self.spray[4] == "userDefined" + && let Some(c) = cx.paint.fill.color() + { + v["color"] = serde_json::to_value(c).unwrap_or(Value::Null); + v["keepModel"] = json!(true); + } + if let Some(s) = &self.style { + v["style"] = json!(s); + } return ("symbol.spray".into(), v); } + let pressure = self.use_pressure; + let pts = Value::Array(self.points.iter().map(|(p, f)| if pressure { json!([p.x, p.y, f]) } else { json!([p.x, p.y]) }).collect()); let tool = match self.id { "symbolShifter" => "shift", "symbolScruncher" => "scrunch", @@ -113,6 +168,17 @@ impl SymbolismTool { if let Some(s) = &self.style { v["style"] = json!(s); } + if pressure { + v["usePressure"] = json!(true); + } + // The Symbol Shifter has no Method. + if tool != "shift" { + v["method"] = json!(self.method); + } + if tool == "size" { + v["proportional"] = json!(self.proportional); + v["affectsDensity"] = json!(self.affects_density); + } ("symbol.adjust".into(), v) } } @@ -140,9 +206,10 @@ impl Tool for SymbolismTool { fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { let p = ev.pos; self.hover = Some(p); + let sample = (p, f64::from(ev.pressure).clamp(0.0, 1.0)); match ev.kind { PointerKind::Down => { - self.points = vec![p]; + self.points = vec![sample]; self.previewed = 1; self.active = true; self.alt = ev.mods.alt; @@ -153,10 +220,10 @@ impl Tool for SymbolismTool { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; // Each preview carries every point so far: a long drag stops growing and previews less often. - if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|l| l.distance(p) < step) { + if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|(l, _)| l.distance(p) < step) { return vec![]; } - self.points.push(p); + self.points.push(sample); if !previews_at(self.points.len()) { return vec![]; } @@ -193,9 +260,15 @@ impl Tool for SymbolismTool { vec![] } fn overlays(&self, _cx: &ToolContext) -> Vec { - let Some(p) = self.hover else { return vec![] }; - let circle = kurbo::Circle::new(p, self.diameter / 2.0).to_path(0.1); - vec![Overlay::Path { path: circle, color: FEEDBACK, width: 1.0, dashed: false }] + let Some(p) = self.hover.filter(|_| self.show_brush) else { return vec![] }; + let ring = |radius: f64, dashed| Overlay::Path { path: kurbo::Circle::new(p, radius).to_path(0.1), color: FEEDBACK, width: 1.0, dashed }; + let mut v = vec![ring(self.diameter / 2.0, false)]; + // The intensity: a dashed ring that fills the brush at 10. A pen's pressure sets it instead + // with Use Pressure Pen, so no ring is drawn then. + if !self.use_pressure && self.intensity < 10.0 { + v.push(ring(self.diameter / 2.0 * self.intensity / 10.0, true)); + } + v } fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { match self.id { @@ -210,7 +283,22 @@ impl Tool for SymbolismTool { } } fn options(&self) -> Value { - json!({"diameter": self.diameter, "intensity": self.intensity, "density": self.density, "symbol": self.symbol, "style": self.style}) + let mut v = json!({ + "diameter": self.diameter, + "intensity": self.intensity, + "density": self.density, + "symbol": self.symbol, + "style": self.style, + "usePressure": self.use_pressure, + "method": self.method, + "showBrush": self.show_brush, + "proportional": self.proportional, + "affectsDensity": self.affects_density, + }); + for ((key, _), mode) in SPRAY_ATTRIBUTES.iter().zip(self.spray) { + v[*key] = json!(mode); + } + v } fn set_option(&mut self, key: &str, v: &Value) { match key { @@ -219,7 +307,16 @@ impl Tool for SymbolismTool { "density" => self.density = v.as_f64().unwrap_or(self.density).clamp(1.0, 10.0), "symbol" => self.symbol = v.as_str().map(str::to_string), "style" => self.style = v.as_str().map(str::to_string), - _ => {} + "usePressure" => self.use_pressure = v.as_bool().unwrap_or(self.use_pressure), + "method" => self.method = one_of(v, &METHODS).unwrap_or(self.method), + "showBrush" => self.show_brush = v.as_bool().unwrap_or(self.show_brush), + "proportional" => self.proportional = v.as_bool().unwrap_or(self.proportional), + "affectsDensity" => self.affects_density = v.as_bool().unwrap_or(self.affects_density), + _ => { + if let Some(i) = SPRAY_ATTRIBUTES.iter().position(|(k, _)| *k == key) { + self.spray[i] = one_of(v, &SPRAY_MODES).unwrap_or(self.spray[i]); + } + } } } } @@ -376,6 +473,125 @@ mod tests { assert!(matches!(&a[1], Action::Preview(_, v) if v["color"] == fill && v["keepModel"] == true), "{a:?}"); } + /// The Symbolism Tools Options the tools keep, with what each is before it is set. + #[test] + fn the_options_dialog_fields_are_tool_options() { + let mut t = SymbolismTool::new("symbolSizer"); + let o = t.options(); + assert_eq!((o["usePressure"].clone(), o["method"].clone(), o["showBrush"].clone()), (json!(false), json!("userDefined"), json!(true))); + assert_eq!((o["proportional"].clone(), o["affectsDensity"].clone()), (json!(true), json!(false))); + for (key, _) in SPRAY_ATTRIBUTES { + assert_eq!(o[key], "average", "{key}"); + } + for (key, v) in [ + ("usePressure", json!(true)), + ("method", json!("random")), + ("showBrush", json!(false)), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ("sprayStain", json!("userDefined")), + ] { + t.set_option(key, &v); + assert_eq!(t.options()[key], v, "{key}"); + } + // A value that is none of an option's choices leaves it as it was. + for (key, v) in [("method", json!("smooth")), ("method", json!(2)), ("sprayStain", json!("random")), ("usePressure", json!("yes"))] { + let before = t.options(); + t.set_option(key, &v); + assert_eq!(t.options(), before, "{key}: {v}"); + } + } + + /// The adjusting tools send the Method (the Shifter has none), the Sizer its two options, and + /// with Use Pressure Pen each point's pen pressure. + #[test] + fn adjust_tools_send_the_method_the_sizer_options_and_the_pen_pressure() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let press = |t: &mut SymbolismTool| { + let down = PointerEvent { pressure: 0.25, ..PointerEvent::new(PointerKind::Down, 5.0, 5.0) }; + match t.pointer(&cx, &down).swap_remove(1) { + Action::Preview(_, v) => v, + other => panic!("{other:?}"), + } + }; + let mut sizer = SymbolismTool::new("symbolSizer"); + let v = press(&mut sizer); + assert_eq!((v["method"].clone(), v["proportional"].clone(), v["affectsDensity"].clone()), (json!("userDefined"), json!(true), json!(false))); + assert_eq!((v["points"].clone(), v.get("usePressure")), (json!([[5.0, 5.0]]), None)); + sizer.set_option("usePressure", &json!(true)); + sizer.set_option("method", &json!("average")); + sizer.set_option("affectsDensity", &json!(true)); + let v = press(&mut sizer); + assert_eq!((v["points"].clone(), v["usePressure"].clone()), (json!([[5.0, 5.0, 0.25]]), json!(true))); + assert_eq!((v["method"].clone(), v["affectsDensity"].clone()), (json!("average"), json!(true))); + let mut shifter = SymbolismTool::new("symbolShifter"); + shifter.set_option("method", &json!("random")); + let v = press(&mut shifter); + assert!(v.get("method").is_none() && v.get("proportional").is_none(), "{v}"); + let mut spinner = SymbolismTool::new("symbolSpinner"); + spinner.set_option("method", &json!("random")); + let v = press(&mut spinner); + assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); + } + + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is + /// User Defined. + #[test] + fn the_sprayer_sends_its_attributes() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolSprayer"); + t.set_option("usePressure", &json!(true)); + let spray = |t: &mut SymbolismTool| match t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)).swap_remove(1) { + Action::Preview(c, v) if c == "symbol.spray" => v, + other => panic!("{other:?}"), + }; + let v = spray(&mut t); + let average = + json!({"scrunch": "average", "size": "average", "spin": "average", "screen": "average", "stain": "average", "style": "average"}); + assert_eq!((v["attributes"].clone(), v.get("color"), v["points"].clone()), (average, None, json!([[5.0, 5.0]]))); + t.set_option("sprayStain", &json!("userDefined")); + t.set_option("spraySpin", &json!("userDefined")); + let v = spray(&mut t); + assert_eq!( + (v["attributes"]["stain"].clone(), v["attributes"]["spin"].clone(), v["attributes"]["size"].clone()), + (json!("userDefined"), json!("userDefined"), json!("average")) + ); + assert_eq!((v["color"].clone(), v["keepModel"].clone()), (serde_json::to_value(p.fill.color().unwrap()).unwrap(), json!(true))); + } + + /// Show Brush Size and Intensity: the brush's outline with a dashed ring for the intensity + /// inside it; no ring with Use Pressure Pen or at intensity 10, and nothing with it off. + #[test] + fn show_brush_size_and_intensity_draws_the_brush() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = SymbolismTool::new("symbolScruncher"); + assert!(t.overlays(&cx).is_empty(), "no pointer yet"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + let rings = |t: &SymbolismTool| { + t.overlays(&cx) + .into_iter() + .map(|o| match o { + Overlay::Path { path, dashed, .. } => (path.bounding_box().width().round(), dashed), + other => panic!("{other:?}"), + }) + .collect::>() + }; + assert_eq!(rings(&t), [(80.0, false), (40.0, true)]); + t.set_option("intensity", &json!(10)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("intensity", &json!(2)); + t.set_option("usePressure", &json!(true)); + assert_eq!(rings(&t), [(80.0, false)]); + t.set_option("showBrush", &json!(false)); + assert!(t.overlays(&cx).is_empty()); + } + #[test] fn brackets_change_diameter_and_intensity() { let (d, _) = doc_with_rect(); diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..524b4e5c8c 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -1,10 +1,16 @@ //! Symbolism Tools Options (double-click a Symbolism tool): the brush the eight tools share, which //! lasts across tool switches and is saved with the preferences. OK sets it with -//! `tool.setOption {tool, values}`. +//! `tool.setOption {tool, values}`, and gives a new Symbol Set Density to the selected symbol sets +//! with `symbol.setDensity`. //! -//! Fields: `tool`; `diameter` (points), `intensity` and `density` (Symbol Set Density), 1–10. +//! Fields: `tool` (the tool whose options show; the Tool row changes it); `diameter` (points), +//! `intensity` and `density` (Symbol Set Density), 1–10; `usePressure`; `method` (`userDefined`, +//! `average` or `random`); `showBrush`; `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, +//! `sprayStain` and `sprayStyle` (Symbol Sprayer, each `average` or `userDefined`); `proportional` +//! and `affectsDensity` (Symbol Sizer); `densityWas` (the density the dialog opened with). use serde_json::{Map, Value, json}; +use vectorcraft_tools::settings::SYMBOLISM; use super::{DialogResult, DialogSpec, form, run_and_close}; use crate::state::Dialog; @@ -14,19 +20,35 @@ use crate::{VectorcraftApp, widgets}; pub const KIND: &str = "symbolismOptions"; pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; + DialogSpec { heading: |_| tl!("Symbolism Tools Options").into(), body, confirm, min_width: 340.0, ..DialogSpec::FORM }; -/// The options the dialog edits. -const KEYS: [&str; 3] = ["diameter", "intensity", "density"]; +/// The numbers the dialog edits. +const NUMBERS: [&str; 3] = ["diameter", "intensity", "density"]; + +/// The checkboxes the dialog edits. +const SWITCHES: [&str; 4] = ["usePressure", "showBrush", "proportional", "affectsDensity"]; + +/// The Symbol Sprayer options. +const SPRAY: [&str; 6] = ["sprayScrunch", "spraySize", "spraySpin", "sprayScreen", "sprayStain", "sprayStyle"]; + +/// The density the dialog opened with: OK spaces the selected symbol sets from it to the new one. +const DENSITY_WAS: &str = "densityWas"; /// Width of the label column. const LABEL_W: f32 = 130.0; +/// Width of the dropdowns. +const CHOICE_W: f32 = 170.0; + /// Open the options of Symbolism tool `tool` (one of `vectorcraft_tools::settings::SYMBOLISM`) /// with their current values. pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { let o = app.session.tool_options_of(tool); - let mut fields: Map = KEYS.iter().filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + let keys = NUMBERS.iter().chain(&SWITCHES).chain(&SPRAY).chain(&["method"]); + let mut fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(*key)?.clone()))).collect(); + if let Some(density) = fields.get("density").cloned() { + fields.insert(DENSITY_WAS.into(), density); + } fields.insert("tool".into(), json!(tool)); app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); json!({ "dialog": KIND }) @@ -34,22 +56,74 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let unit = app.session.general_unit(); + // The tool whose options show below (the eight tools share one toolbar icon, so they are listed + // by name). + let tools: Vec<(&str, &str)> = SYMBOLISM.iter().filter_map(|id| Some((*id, vectorcraft_tools::tool_info(id)?.label))).collect(); + form::choice(ui, d, "tool", tl!("Tool:"), (LABEL_W, CHOICE_W), &tools); + let tool = d.str("tool"); + ui.add_space(6.0); widgets::label_row(ui, tl!("Diameter:"), LABEL_W, |ui| { form::length(ui, d, "diameter", unit, 100.0); }); - for (key, label) in [("intensity", tl!("Intensity:")), ("density", tl!("Symbol Set Density:"))] { - widgets::label_row(ui, label, LABEL_W, |ui| { - if let Some(v) = widgets::range_field(ui, ("symbolism", key), d.f64(key, 5.0), 1.0..=10.0, "", 0, 100.0) { - d.fields.insert(key.into(), json!(v)); + let pressure = d.bool("usePressure"); + widgets::label_row(ui, tl!("Intensity:"), LABEL_W, |ui| { + ui.add_enabled_ui(!pressure, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "intensity"), d.f64("intensity", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("intensity".into(), json!(v)); } }); + }); + widgets::label_row(ui, "", LABEL_W, |ui| form::check(ui, d, "usePressure", tl!("Use Pressure Pen"))); + widgets::label_row(ui, tl!("Symbol Set Density:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("symbolism", "density"), d.f64("density", 5.0), 1.0..=10.0, "", 0, 100.0) { + d.fields.insert("density".into(), json!(v)); + } + }); + // The Symbol Sprayer and the Symbol Shifter have no Method. + ui.add_enabled_ui(!["symbolSprayer", "symbolShifter"].contains(&tool.as_str()), |ui| { + let methods = [("userDefined", tl!("User Defined")), ("average", tl!("Average")), ("random", tl!("Random"))]; + form::choice(ui, d, "method", tl!("Method:"), (LABEL_W, CHOICE_W), &methods); + }); + if tool == "symbolSprayer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sprayer Options")); + ui.add_space(4.0); + let modes = [("average", tl!("Average")), ("userDefined", tl!("User Defined"))]; + let labels = [tl!("Scrunch:"), tl!("Size:"), tl!("Spin:"), tl!("Screen:"), tl!("Stain:"), tl!("Style:")]; + for (key, label) in SPRAY.iter().zip(labels) { + form::choice(ui, d, key, label, (LABEL_W, CHOICE_W), &modes); + } } + if tool == "symbolSizer" { + ui.add_space(10.0); + widgets::subheader(ui, tl!("Symbol Sizer Options")); + ui.add_space(4.0); + form::check(ui, d, "proportional", tl!("Proportional Resizing")); + form::check(ui, d, "affectsDensity", tl!("Resizing Affects Density")); + } + ui.add_space(10.0); + form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); false } -/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). +/// The selected symbol sets. +fn selected_sets(app: &VectorcraftApp) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set)).map(|id| id.0).collect() +} + +/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving +/// a new Symbol Set Density to the selected symbol sets. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); + let mut values: Map = + NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); + values.extend(SWITCHES.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.bool(k))))); + values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); + let sets = selected_sets(app); + if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { + app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; + } run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) } @@ -58,12 +132,21 @@ mod tests { use super::*; use vectorcraft_engine::Session; - #[test] - fn the_symbolism_tools_share_the_options_ok_sets() { + fn app() -> VectorcraftApp { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app + } + + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + #[test] + fn the_symbolism_tools_share_the_options_ok_sets() { + let mut app = app(); app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); - let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + let text = painted(&mut app); for label in ["Symbolism Tools Options", "Diameter:", "Intensity:", "Symbol Set Density:"] { assert!(text.contains(label), "{label} in {text}"); } @@ -78,4 +161,100 @@ mod tests { let o = app.session.tool_options_of("symbolSprayer"); assert_eq!((o["diameter"].as_f64(), o["intensity"].as_f64(), o["density"].as_f64()), (Some(120.0), Some(9.0), Some(2.0))); } + + /// Every tool shows the general options; the Symbol Sprayer and the Symbol Sizer show their own + /// sections, and the Tool row's choice decides which. + #[test] + fn the_sprayer_and_the_sizer_show_their_sections() { + let mut app = app(); + let general = ["Tool:", "Use Pressure Pen", "Method:", "User Defined", "Show Brush Size and Intensity"]; + let sprayer = ["Symbol Sprayer Options", "Scrunch:", "Size:", "Spin:", "Screen:", "Stain:", "Style:"]; + let sizer = ["Symbol Sizer Options", "Proportional Resizing", "Resizing Affects Density"]; + for (tool, own, others) in + [("symbolSprayer", &sprayer[..], &sizer[..]), ("symbolSizer", &sizer[..], &sprayer[..]), ("symbolStainer", &[][..], &sprayer[..])] + { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let text = painted(&mut app); + for label in general.iter().chain(own) { + assert!(text.contains(label), "{tool}: {label} in {text}"); + } + for label in others { + assert!(!text.contains(label), "{tool}: no {label} in {text}"); + } + } + // The Stainer's dialog, switched to the Sizer with the Tool row. + app.ui.dialog.as_mut().unwrap().fields.insert("tool".into(), json!("symbolSizer")); + let text = painted(&mut app); + assert!(text.contains("Proportional Resizing") && !text.contains("Scrunch:"), "{text}"); + } + + /// OK sets Method, Use Pressure Pen, Show Brush Size and Intensity and the Sprayer's and the + /// Sizer's options for the eight tools, and the dialog opens with them again. + #[test] + fn ok_sets_the_method_the_pen_and_the_tool_sections() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("showBrush")), ("userDefined".to_string(), false, true)); + assert_eq!((d.str("sprayStain"), d.bool("proportional"), d.bool("affectsDensity")), ("average".to_string(), true, false)); + for (k, v) in [ + ("method", json!("random")), + ("usePressure", json!(true)), + ("showBrush", json!(false)), + ("sprayStain", json!("userDefined")), + ("spraySpin", json!("userDefined")), + ("proportional", json!(false)), + ("affectsDensity", json!(true)), + ] { + d.fields.insert(k.into(), v); + } + super::super::confirm(&mut app).unwrap(); + let o = app.session.tool_options_of("symbolScreener"); + assert_eq!((o["method"].as_str(), o["usePressure"].as_bool(), o["showBrush"].as_bool()), (Some("random"), Some(true), Some(false))); + assert_eq!( + (o["sprayStain"].as_str(), o["spraySpin"].as_str(), o["sprayScrunch"].as_str()), + (Some("userDefined"), Some("userDefined"), Some("average")) + ); + assert_eq!((o["proportional"].as_bool(), o["affectsDensity"].as_bool()), (Some(false), Some(true))); + app.run("tool.options", json!({"tool": "symbolSizer"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("method"), d.bool("usePressure"), d.bool("affectsDensity")), ("random".to_string(), true, true)); + } + + /// A new Symbol Set Density spaces the instances of the selected symbol set, as one undo step; + /// the same density, or no set selected, adds none. + #[test] + fn ok_gives_a_new_density_to_the_selected_symbol_set() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let points: Vec = (0..8).map(|i| json!([40.0 + 40.0 * f64::from(i), 150.0])).collect(); + let set = app.run("symbol.spray", json!({"name": "Dot", "points": points, "radius": 4})).unwrap()["id"].as_u64().unwrap(); + let width = |app: &VectorcraftApp| { + let st = app.session.active().unwrap(); + st.doc.node(vectorcraft_doc::NodeId(set)).and_then(|n| n.geometric_bounds()).map(|b| b.width()).unwrap() + }; + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (was, steps) = (width(&app), undo(&app)); + // The same density: the set stays as it is. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + // A higher density packs the set closer, as one undo step. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); + super::super::confirm(&mut app).unwrap(); + assert!(width(&app) < was * 0.8, "{} of {was}", width(&app)); + assert_eq!(undo(&app), steps + 1); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + // Without a set selected only the option changes. + app.run("select.set", json!({"ids": []})).unwrap(); + let (was, steps) = (width(&app), undo(&app)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(2)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(2.0)); + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d43d17220c..0034f0f578 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -938,7 +938,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool, diameter (pt), intensity and density (1–10), shared by the eight tools; OK runs tool.setOption {tool, values}), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph (dialog `command` running graph.setType; an error without one), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 37ffd74300..9c008cb725 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1897,7 +1897,7 @@ and `text.createInPath`; `underline`, `strikethrough`, `allCaps`, `proportionalM in `text.setRangeStyle` and `text.setFormat`, which also checks `hyphenate`, `hyphenateCapitalized` and `romanHangingPunctuation`; `effective` and `story` in `text.getRange`; `story` in `text.setRangeStyle`; `on` in `type.opticalMarginAlignment`, `type.dynamicText`, `type.systemLayout` and `type.fractionalWidths`; `flip` in `type.dynamicTextPreset`; `remove` and `overhang` in `type.ruby`; `expandInstances` in `symbol.delete`; `alt` in -`symbol.spray` and `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in +`symbol.spray` and `symbol.adjust`; `usePressure`, `proportional` and `affectsDensity` in `symbol.adjust`; `spot` and `global` in `swatch.new` and `swatch.edit`; `unlink` in `swatch.delete`; `fromArtwork`, `toGlobal` and `includeTints` in `swatch.newGroup`; `global` and `selection` in `swatch.addUsedColors`; `visible` in `appearance.setItem`; `copy` in `appearance.transfer`; `reverse` and `append` in `appearance.copyFrom`; `reverse` and `stroke` in `paint.editGradient`; `stroke` in `paint.setGradientGeom` and in @@ -3098,6 +3098,36 @@ already walks Image Trace. Short agent entry points: symbol's scale are left as they are, and no undo step is added when nothing changes; an id that names no object, or objects without a symbol instance, is an error. It returns `{ids}`, the instances it changed. The menu item and the button are enabled only while a selected instance would change. +- The symbolism tools' options ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), + [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): + `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with + `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` + `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` + `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and + `style` for the User Defined stain and style. `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol + sets a new Symbol Set Density. VectorCraft's own rules: + - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice + it (the Spinner: a turn either way), the same each time the stroke is applied. + - `average` moves each instance's value toward the mean of the instances within the brush at that point: the + Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes, + the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. + `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when + no instance changes. + - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the + height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows + and toward it as it shrinks. + - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the + stroke point: their spacing, size, rotation and opacity, and the stain or style of the nearest one that has one, + at the mean amount. With no instance there it has the symbol's size, no rotation, full opacity and no stain or + style. `attributes` left out means `average` for all six. + - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to + (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and + adds none when no instance moves. `from` is the density each set was created at or last given, and the + `from` passed applies only to a set without one (a group named "Symbol Set" by hand); the sets moved then have + density `to`. A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the + instances moved. + - A `method`, an attribute or a density outside these values, a pressure that isn't a number, or no symbol set + among the objects of `symbol.setDensity`, is an error and changes nothing. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the @@ -10067,7 +10097,11 @@ tool keeps last across tool switches (and documents) and are saved with the pref `prefs.get`'s full object), as the reference app keeps them: the Liquify tools' brush and tool options, Mirror & Cut's axis and side, Puppet Warp's mesh, the Symbolism brush, the line, grid, pencil, brush and eraser tools' options, polygon sides and star points, the Flare Tool Options and the Shape Builder Tool Options. The Liquify tools share one set of Global Brush Dimensions (width, height, angle, -intensity), and the Symbolism tools one brush. Interaction state (pins, a reference point) starts afresh. In the +intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5), `density` (5), `usePressure` (false), +`method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` +and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are +VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at +`intensity`/10 of its radius (no ring at 10 or with `usePressure`). Interaction state (pins, a reference point) starts afresh. In the desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). @@ -10096,7 +10130,12 @@ drag that places the rings' end point, Space held moves the flare at its current are the artboard's top-left corner in document points, while the dialog shows X and Y at the reference point the Transform panel uses, counted from the ruler origin), a graph tool's the selected graph's Graph Type (an error without one), a Symbolism tool's the Symbolism Tools Options (dialog -`symbolismOptions`: `diameter` in points, `intensity` and `density` 1–10, one brush for the eight tools) and the +`symbolismOptions`: `tool` (the tool whose options show, which the Tool row changes), `diameter` in points, +`intensity` and `density` 1–10, `usePressure`, `method` (`userDefined`, `average` or `random`), `showBrush`, the +Symbol Sprayer's `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` and `sprayStyle` (each +`average` or `userDefined`) and the Symbol Sizer's `proportional` and `affectsDensity`: one brush for the eight +tools. OK runs `tool.setOption {tool, values}`, and with symbol sets selected and a new `density` it first runs +`symbol.setDensity` from the density the dialog opened with) and the Magic Wand tool's its panel. `ui.newArtboard` (Alt-click on the Artboards panel's New Artboard) opens Artboard Options for a new artboard, with `new: true` and the name, position and size that `artboard.new {}` would give it. OK runs `artboard.new` with the fields and makes the new artboard the active one, and Cancel adds no artboard. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9ba8866a8c..64f4fa4054 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -972,6 +972,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. + - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). From 1340719244f8b5f60b42222bc008a764115c15bc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:31:20 -0800 Subject: [PATCH 02/10] Symbols: a symbolism stroke counts only the instances it changes - The Symbol Sprayer uses neither Intensity nor pen pressure: the dialog disables both for it, and its brush overlay draws no intensity ring. - symbol.adjust counts an instance only when it changes, so a Random stroke that gives an instance no share, or a stroke at the tool's limit, adds no count and no undo step. - Average leaves an instance without a size (a scale of 0) as it is; the other methods shift, scrunch, spin, stain, screen and style it as before. - Params text and docs/mcp.md say which values are refused: a point's third number that isn't a number (in symbol.spray too), and a `from` or `to` of symbol.setDensity outside 1..10. - The 11 new dialog and command labels get rows in all 28 catalogs. --- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/symbols.rs | 53 +++++++++++------- crates/engine/src/tests/symbolism_options.rs | 56 +++++++++++++++++++ crates/tools/src/symbolism.rs | 12 +++- .../ui-egui/src/dialogs/symbolism_options.rs | 21 ++++++- crates/ui-egui/src/i18n/bg.tsv | 11 ++++ crates/ui-egui/src/i18n/bs.tsv | 11 ++++ crates/ui-egui/src/i18n/ca.tsv | 11 ++++ crates/ui-egui/src/i18n/cs.tsv | 11 ++++ crates/ui-egui/src/i18n/da.tsv | 11 ++++ crates/ui-egui/src/i18n/de.tsv | 11 ++++ crates/ui-egui/src/i18n/el.tsv | 11 ++++ crates/ui-egui/src/i18n/es.tsv | 11 ++++ crates/ui-egui/src/i18n/fi.tsv | 11 ++++ crates/ui-egui/src/i18n/fr.tsv | 11 ++++ crates/ui-egui/src/i18n/gu.tsv | 11 ++++ crates/ui-egui/src/i18n/hi.tsv | 11 ++++ crates/ui-egui/src/i18n/hu.tsv | 11 ++++ crates/ui-egui/src/i18n/id.tsv | 11 ++++ crates/ui-egui/src/i18n/it.tsv | 11 ++++ crates/ui-egui/src/i18n/ja.tsv | 11 ++++ crates/ui-egui/src/i18n/ka.tsv | 11 ++++ crates/ui-egui/src/i18n/ko.tsv | 11 ++++ crates/ui-egui/src/i18n/nl.tsv | 11 ++++ crates/ui-egui/src/i18n/pl.tsv | 11 ++++ crates/ui-egui/src/i18n/pt-br.tsv | 11 ++++ crates/ui-egui/src/i18n/ru.tsv | 11 ++++ crates/ui-egui/src/i18n/sv.tsv | 11 ++++ crates/ui-egui/src/i18n/tr.tsv | 11 ++++ crates/ui-egui/src/i18n/uk.tsv | 11 ++++ crates/ui-egui/src/i18n/vi.tsv | 11 ++++ crates/ui-egui/src/i18n/zh-hans.tsv | 11 ++++ crates/ui-egui/src/i18n/zh-hant.tsv | 11 ++++ docs/mcp.md | 9 ++- 34 files changed, 433 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index e8a98d6f7a..4c98e432e2 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -350,7 +350,7 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…], name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", + "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), @@ -368,7 +368,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. No undo step is added when no instance changes (none under the brush, or average with each already at the mean). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 4ba3b22b62..5c2f5a2a73 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1109,9 +1109,17 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { if w <= 0.0 { continue; } - let Some(cur) = d.node(*id).and_then(|n| look(d, n)) else { continue }; + // Average needs the instance's own values, so it leaves an instance without a size + // as it is; the other methods change it as before. + let avg = match (method, &target, d.node(*id).and_then(|n| look(d, n))) { + (Method::Average, Some(t), Some(cur)) => Some((t, cur)), + // No mean under the brush (every instance there without a size), or none of + // its own. + (Method::Average, ..) => continue, + _ => None, + }; // Average leaves an instance that already has the mean as it is. - let at_mean = target.as_ref().is_some_and(|t| match tool.as_str() { + let at_mean = avg.as_ref().is_some_and(|(t, cur)| match tool.as_str() { "scrunch" => { let out = (c - t.middle).hypot(); out <= 1e-9 || (t.reach - out).abs() < 1e-9 @@ -1128,15 +1136,16 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { continue; } let Some(n) = d.node_mut(*id) else { continue }; - touched.insert(*id); + // Counted only when it changes: Random can give an instance no share of the change. + let before = n.clone(); let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2()); let share = share(*id); match tool.as_str() { "shift" => n.transform(Affine::translate(delta * w.min(1.0)), false), "scrunch" => { - let v = match &target { + let v = match &avg { // Toward the instances' mean distance from their middle. - Some(t) => { + Some((t, _)) => { let out = c - t.middle; if out.hypot() > 1e-9 { out * ((t.reach - out.hypot()) / out.hypot() * w.min(1.0)) } else { Vec2::ZERO } } @@ -1145,15 +1154,15 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { n.transform(Affine::translate(v), false); } "size" => { - let k = match &target { - Some(t) => (t.scale / cur.scale).powf(w.min(1.0)), + let k = match &avg { + Some((t, cur)) => (t.scale / cur.scale).powf(w.min(1.0)), None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), }; // Without Proportional Resizing a drag resizes along its own direction: a // level drag the width, an upright one the height. A click resizes both. // The first point of a drag takes the direction to the second. let along = if j > 0 { delta } else { pts.get(1).map_or(Vec2::ZERO, |(next, _)| *next - *q) }; - let (kx, ky) = if proportional || target.is_some() || along.hypot() <= 1e-9 { + let (kx, ky) = if proportional || avg.is_some() || along.hypot() <= 1e-9 { (k, k) } else { let level = along.x.abs() / (along.x.abs() + along.y.abs()); @@ -1167,29 +1176,30 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } "spin" => { - let a = match (&target, method) { - (Some(t), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), + let a = match (&avg, method) { + (Some((t, cur)), _) => wrap_angle(t.angle - cur.angle) * w.min(1.0), // A turn either way, whichever way the drag runs. (None, Method::Random) => 0.1 * w * (share - 1.0), // Turn towards the drag direction; a click spins a little. (None, _) if delta.hypot() > 1e-9 => (c - *q).cross(delta).signum() * 0.1 * w, (None, _) => 0.05 * w, }; - n.transform(about(Affine::rotate(if alt && target.is_none() { -a } else { a })), false); + n.transform(about(Affine::rotate(if alt && avg.is_none() { -a } else { a })), false); } "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; - let (paint, o) = match &target { + let (paint, o) = match &avg { // Toward the mean amount, keeping the stain or style the instance has. - Some(t) => { - let (own, cur) = cur.fill.map_or((None, 0.0), |(p, o)| (Some(p), o)); + Some((t, look)) => { + let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o)); (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) } + // Alt with the Symbol Styler removes the instance's appearance. + None if tool == "style" && alt => { + n.appearance.items.clear(); + (paint, 0.0) + } None => { - if tool == "style" && alt { - n.appearance.items.clear(); - continue; - } let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); let step = match (tool.as_str(), method) { ("style", Method::Random) => (share / 2.0) as f32, @@ -1208,13 +1218,16 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } _ => { let step = (0.1 * w * share) as f32; - n.opacity = match &target { - Some(t) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.05, 1.0), + n.opacity = match &avg { + Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.05, 1.0), None if alt => (n.opacity + step).min(1.0), None => (n.opacity - step).max(0.05), }; } } + if *n != before { + touched.insert(*id); + } } } Ok((touched.len(), !touched.is_empty())) diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 05b707f799..635c17c7de 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -557,3 +557,59 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() { assert!(matches!(&r, Err(EngineError::Other(msg)) if msg == "no symbol set selected"), "{r:?}"); assert!(state(&s) == before); } + +/// An instance with no size is shifted and screened as before; only Average, which needs its size, +/// leaves it as it is. +#[test] +fn an_instance_without_a_size_is_changed_by_every_method_but_average() { + // A Dot at 200, 150 whose size is 0, and Dots at the other centers. + let flat = |others: &[(f64, f64)]| { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + for (x, y) in others { + dot(&mut s, *x, *y); + } + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + (s, a) + }; + let (mut s, a) = flat(&[(210.0, 150.0)]); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(center(&s, a).x > 200.5, "{:?}", center(&s, a)); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[205, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 2); + assert!(node(&s, a).opacity < 1.0); + // Average brings the other two toward their mean and leaves the one without a size as it is. + let (mut s, a) = flat(&[(190.0, 150.0), (210.0, 150.0)]); + adjust(&mut s, json!({"tool": "screen", "points": [[190, 150]], "radius": 2, "intensity": 10})); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 40, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 2); + assert_eq!(node(&s, a).opacity, 1.0); + // With only it under the brush there is no mean, and Average changes nothing. + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 5, "intensity": 10, "method": "average"})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + +/// A stroke that leaves every instance under the brush as it is (each already at full stain, or +/// at the least opacity) counts none and adds no undo step. +#[test] +fn a_stroke_that_changes_no_instance_adds_no_undo_step() { + let mut s = session(); + dot(&mut s, 200.0, 150.0); + let full = json!(vec![[200, 150]; 12]); + for tool in ["stain", "screen"] { + adjust(&mut s, json!({"tool": tool, "points": full, "radius": 40, "intensity": 10, "color": "#ff0000"})); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": tool, "points": [[200, 150]], "radius": 40, "intensity": 10, "color": "#ff0000"})); + assert_eq!(r["count"], 0, "{tool}"); + assert!(state(&s) == before, "{tool} changed the document"); + } +} diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 3f187cf68b..38471ccae1 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -264,8 +264,9 @@ impl Tool for SymbolismTool { let ring = |radius: f64, dashed| Overlay::Path { path: kurbo::Circle::new(p, radius).to_path(0.1), color: FEEDBACK, width: 1.0, dashed }; let mut v = vec![ring(self.diameter / 2.0, false)]; // The intensity: a dashed ring that fills the brush at 10. A pen's pressure sets it instead - // with Use Pressure Pen, so no ring is drawn then. - if !self.use_pressure && self.intensity < 10.0 { + // with Use Pressure Pen, so no ring is drawn then. The Symbol Sprayer uses neither, so it + // draws no ring. + if self.id != "symbolSprayer" && !self.use_pressure && self.intensity < 10.0 { v.push(ring(self.diameter / 2.0 * self.intensity / 10.0, true)); } v @@ -567,7 +568,8 @@ mod tests { } /// Show Brush Size and Intensity: the brush's outline with a dashed ring for the intensity - /// inside it; no ring with Use Pressure Pen or at intensity 10, and nothing with it off. + /// inside it; no ring with Use Pressure Pen, at intensity 10 or for the Symbol Sprayer, and + /// nothing with it off. #[test] fn show_brush_size_and_intensity_draws_the_brush() { let (d, _) = doc_with_rect(); @@ -593,6 +595,10 @@ mod tests { assert_eq!(rings(&t), [(80.0, false)]); t.set_option("showBrush", &json!(false)); assert!(t.overlays(&cx).is_empty()); + // The Symbol Sprayer uses neither Intensity nor pen pressure: the outline only. + let mut t = SymbolismTool::new("symbolSprayer"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 50.0, 50.0)); + assert_eq!(rings(&t), [(80.0, false)]); } #[test] diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 524b4e5c8c..d3dbbd8e06 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -65,15 +65,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::label_row(ui, tl!("Diameter:"), LABEL_W, |ui| { form::length(ui, d, "diameter", unit, 100.0); }); + // The Symbol Sprayer uses neither Intensity nor pen pressure. + let sprayer = tool == "symbolSprayer"; let pressure = d.bool("usePressure"); widgets::label_row(ui, tl!("Intensity:"), LABEL_W, |ui| { - ui.add_enabled_ui(!pressure, |ui| { + ui.add_enabled_ui(!pressure && !sprayer, |ui| { if let Some(v) = widgets::range_field(ui, ("symbolism", "intensity"), d.f64("intensity", 5.0), 1.0..=10.0, "", 0, 100.0) { d.fields.insert("intensity".into(), json!(v)); } }); }); - widgets::label_row(ui, "", LABEL_W, |ui| form::check(ui, d, "usePressure", tl!("Use Pressure Pen"))); + widgets::label_row(ui, "", LABEL_W, |ui| { + ui.add_enabled_ui(!sprayer, |ui| form::check(ui, d, "usePressure", tl!("Use Pressure Pen"))); + }); widgets::label_row(ui, tl!("Symbol Set Density:"), LABEL_W, |ui| { if let Some(v) = widgets::range_field(ui, ("symbolism", "density"), d.f64("density", 5.0), 1.0..=10.0, "", 0, 100.0) { d.fields.insert("density".into(), json!(v)); @@ -188,6 +192,19 @@ mod tests { assert!(text.contains("Proportional Resizing") && !text.contains("Scrunch:"), "{text}"); } + /// The Symbol Sprayer uses neither Intensity nor pen pressure: its Use Pressure Pen is disabled, + /// and the other tools' is not. + #[test] + fn the_sprayer_disables_use_pressure_pen() { + let mut app = app(); + for (tool, off) in [("symbolSprayer", true), ("symbolSizer", false), ("symbolShifter", false)] { + app.run("tool.options", json!({"tool": tool})).unwrap(); + let tree = crate::widgets::accessibility_tests::tree(|ui| super::super::show(&mut app, ui.ctx())); + let pen = crate::widgets::accessibility_tests::named(&tree, "Use Pressure Pen"); + assert_eq!(pen.is_disabled(), off, "{tool}"); + } + } + /// OK sets Method, Use Pressure Pen, Show Brush Size and Intensity and the Sprayer's and the /// Sizer's options for the eight tools, and the dialog opens with them again. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 2c14eb4e39..b1b0e1e007 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1254,6 +1254,17 @@ font-technology Variable Променливи Largest: Най-голям: Direction: Посока: Symbolism Tools Options Опции на символогичните инструменти + Tool: Инструмент: + Symbol Set Density Плътност на набор от символи + Symbol Sprayer Options Опции за разпръскване на символи + Scrunch: Свиване: + Spin: Завъртане: + Screen: Филтър: + Stain: Оцветяване: + Symbol Sizer Options Опции за мащабиране на символи + Proportional Resizing Пропорционално мащабиране + Resizing Affects Density Мащабирането влияе на плътността + Show Brush Size and Intensity Показване на размера и интензивността на четката Symbol Set Density: Плътност на набор от символи: Flat Image Плоско изображение Flat Logo Плоско лого diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 9b98280028..a4441eee05 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3203,6 +3203,17 @@ antiAlias Sharp Oštro Swatch Name: Naziv uzorka boje: Diameter: Prečnik: Symbolism Tools Options Opcije alata simbolizam + Tool: Alat: + Symbol Set Density Gustoća skupa simbola + Symbol Sprayer Options Opcije raspršivača simbola + Scrunch: Sabijanje: + Spin: Okretanje: + Screen: Prozirnost: + Stain: Bojenje: + Symbol Sizer Options Opcije mijenjača veličine simbola + Proportional Resizing Proporcionalna promjena veličine + Resizing Affects Density Promjena veličine utiče na gustoću + Show Brush Size and Intensity Prikaži veličinu i intenzitet četke Symbol Set Density: Gustoća skupa simbola: Intensity: Intenzitet: Place PDF Postavi PDF diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index f98daa7f92..eb1287827a 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4688,6 +4688,17 @@ digits Malayalam Malaiàlam Symbol Screener Tool Eina de filtre de símbols Symbol Scruncher Compressor de símbols Symbol Scruncher Tool Eina de compressor de símbols + Tool: Eina: + Symbol Set Density Densitat del conjunt de símbols + Symbol Sprayer Options Opcions del ruixador de símbols + Scrunch: Compressió: + Spin: Gir: + Screen: Filtre: + Stain: Tint: + Symbol Sizer Options Opcions de l’escalador de símbols + Proportional Resizing Canvi de mida proporcional + Resizing Affects Density El canvi de mida afecta la densitat + Show Brush Size and Intensity Mostra la mida i la intensitat del pinzell Symbol Set Density: Densitat del conjunt de símbols: Symbol Shifter Desplaçador de símbols Symbol Shifter Tool Eina de desplaçador de símbols diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index b174608032..b320417aff 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3281,6 +3281,17 @@ antiAlias Sharp Ostré Swatch Name: Název položky vzorníku: Diameter: Průměr: Symbolism Tools Options Možnosti nástrojů symbolů + Tool: Nástroj: + Symbol Set Density Hustota sady symbolů + Symbol Sprayer Options Volby rozprašovače symbolů + Scrunch: Zhuštění: + Spin: Otáčení: + Screen: Průhlednost: + Stain: Obarvení: + Symbol Sizer Options Volby velikosti symbolů + Proportional Resizing Proporcionální změna velikosti + Resizing Affects Density Změna velikosti ovlivňuje hustotu + Show Brush Size and Intensity Zobrazit velikost a intenzitu štětce Symbol Set Density: Hustota sady symbolů: Intensity: Intenzita: Place PDF Umístit PDF diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 0ae36e3699..c0d485b872 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3679,6 +3679,17 @@ antiAlias Sharp Skarp Swatch Name: Farveprøvenavn: Diameter: Diameter: Symbolism Tools Options Indstillinger for symbolværktøjer + Tool: Værktøj: + Symbol Set Density Tæthed for symbolsæt + Symbol Sprayer Options Indstillinger for symbolsprøjter + Scrunch: Samling: + Spin: Rotering: + Screen: Gennemsigtighed: + Stain: Farvning: + Symbol Sizer Options Indstillinger for symbolstørrelse + Proportional Resizing Proportional størrelsesændring + Resizing Affects Density Størrelsesændring påvirker tætheden + Show Brush Size and Intensity Vis penselstørrelse og intensitet Symbol Set Density: Tæthed for symbolsæt: Intensity: Intensitet: Place PDF Placér PDF diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 99e487ecb1..74538c850d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1285,6 +1285,17 @@ font-technology Variable Variabel Largest: Größter: Direction: Richtung: Symbolism Tools Options Optionen für die Symbol-Werkzeuge + Tool: Werkzeug: + Symbol Set Density Dichte des Symbolsatzes + Symbol Sprayer Options Optionen für „Symbol aufsprühen“ + Scrunch: Stauchen: + Spin: Drehen: + Screen: Transparenz: + Stain: Färben: + Symbol Sizer Options Optionen für „Symbol skalieren“ + Proportional Resizing Proportional skalieren + Resizing Affects Density Skalieren beeinflusst die Dichte + Show Brush Size and Intensity Pinselgröße und Intensität anzeigen Symbol Set Density: Dichte des Symbolsatzes: Flat Image Reduziertes Bild Flat Logo Flaches Logo diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 7fe692d27e..e0ba222e38 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1232,6 +1232,17 @@ font-technology Variable Μεταβλητές Largest: Μεγαλύτερο: Direction: Κατεύθυνση: Symbolism Tools Options Επιλογές εργαλείων συμβόλων + Tool: Εργαλείο: + Symbol Set Density Πυκνότητα συνόλου συμβόλων + Symbol Sprayer Options Επιλογές ψεκαστήρα συμβόλων + Scrunch: Σύμπτυξη: + Spin: Περιστροφή: + Screen: Αραίωση: + Stain: Χρωματισμός: + Symbol Sizer Options Επιλογές αλλαγής μεγέθους συμβόλων + Proportional Resizing Αναλογική αλλαγή μεγέθους + Resizing Affects Density Η αλλαγή μεγέθους επηρεάζει την πυκνότητα + Show Brush Size and Intensity Εμφάνιση μεγέθους και έντασης πινέλου Symbol Set Density: Πυκνότητα συνόλου συμβόλων: Flat Image Επίπεδη εικόνα Flat Logo Επίπεδο λογότυπο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index f0a5d12844..c4ba662d85 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1308,6 +1308,17 @@ font-technology Variable Variables Largest: Más grande: Direction: Dirección: Symbolism Tools Options Opciones de las herramientas de símbolos + Tool: Herramienta: + Symbol Set Density Densidad del conjunto de símbolos + Symbol Sprayer Options Opciones del rociador de símbolos + Scrunch: Concentración: + Spin: Giro: + Screen: Transparencia: + Stain: Tinte: + Symbol Sizer Options Opciones de tamaño de símbolos + Proportional Resizing Cambio de tamaño proporcional + Resizing Affects Density El cambio de tamaño afecta a la densidad + Show Brush Size and Intensity Mostrar tamaño e intensidad del pincel Symbol Set Density: Densidad del conjunto de símbolos: Flat Image Imagen acoplada Flat Logo Logotipo plano diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 718b99ea1b..7e55e505b4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3225,6 +3225,17 @@ antiAlias Sharp Terävä Swatch Name: Värimallin nimi: Diameter: Halkaisija: Symbolism Tools Options Symbolityökalujen asetukset + Tool: Työkalu: + Symbol Set Density Symbolijoukon tiheys + Symbol Sprayer Options Symbolisuihkuttimen asetukset + Scrunch: Tiivistys: + Spin: Kierto: + Screen: Läpinäkyvyys: + Stain: Värjäys: + Symbol Sizer Options Symbolien koonmuutoksen asetukset + Proportional Resizing Suhteellinen koonmuutos + Resizing Affects Density Koonmuutos vaikuttaa tiheyteen + Show Brush Size and Intensity Näytä siveltimen koko ja voimakkuus Symbol Set Density: Symbolijoukon tiheys: Intensity: Voimakkuus: Place PDF Sijoita PDF diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6b946a7f1e..81333cab32 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1302,6 +1302,17 @@ font-technology Variable Variables Largest: Le plus grand : Direction: Direction : Symbolism Tools Options Options des outils de symbolisme + Tool: Outil : + Symbol Set Density Densité du jeu de symboles + Symbol Sprayer Options Options de pulvérisation de symboles + Scrunch: Espacement : + Spin: Rotation : + Screen: Transparence : + Stain: Coloration : + Symbol Sizer Options Options de redimensionnement de symboles + Proportional Resizing Redimensionnement proportionnel + Resizing Affects Density Le redimensionnement modifie la densité + Show Brush Size and Intensity Afficher la taille et l’intensité du pinceau Symbol Set Density: Densité du jeu de symboles : Flat Image Image aplatie Flat Logo Logo en aplats diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 11e79e41d1..ca29d7b844 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3808,6 +3808,17 @@ Symbol Screener Tool સિમ્બોલ સ્ક્રીનર ટૂલ Symbol Scruncher સિમ્બોલ સ્ક્રન્ચર Symbol Scruncher Tool સિમ્બોલ સ્ક્રન્ચર ટૂલ + Tool: ટૂલ: + Symbol Set Density સિમ્બોલ સેટ ઘનતા + Symbol Sprayer Options સિમ્બોલ સ્પ્રેયર વિકલ્પો + Scrunch: સ્ક્રન્ચ: + Spin: સ્પિન: + Screen: સ્ક્રીન: + Stain: સ્ટેઇન: + Symbol Sizer Options સિમ્બોલ સાઇઝર વિકલ્પો + Proportional Resizing પ્રમાણસર કદ બદલવું + Resizing Affects Density કદ બદલવાથી ઘનતા બદલાય છે + Show Brush Size and Intensity બ્રશનું કદ અને તીવ્રતા બતાવો Symbol Set Density: સિમ્બોલ સેટ ઘનતા: Symbol Shifter સિમ્બોલ શિફ્ટર Symbol Shifter Tool સિમ્બોલ શિફ્ટર ટૂલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 2bb71a0b45..58f29dedd2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5068,6 +5068,17 @@ antiAlias Sharp शार्प Symbol Screener Tool सिंबल स्क्रीनर टूल Symbol Scruncher सिंबल स्क्रंचर Symbol Scruncher Tool सिंबल स्क्रंचर टूल + Tool: टूल: + Symbol Set Density सिंबल सेट डेंसिटी + Symbol Sprayer Options सिंबल स्प्रेयर विकल्प + Scrunch: स्क्रंच: + Spin: स्पिन: + Screen: स्क्रीन: + Stain: स्टेन: + Symbol Sizer Options सिंबल साइज़र विकल्प + Proportional Resizing आनुपातिक रीसाइज़िंग + Resizing Affects Density रीसाइज़िंग से डेंसिटी बदलती है + Show Brush Size and Intensity ब्रश का साइज़ और तीव्रता दिखाएँ Symbol Set Density: सिंबल सेट डेंसिटी: Symbol Shifter सिंबल शिफ्टर Symbol Shifter Tool सिंबल शिफ़्टर टूल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 253e8f6764..7cefd5f58c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4376,6 +4376,17 @@ mark-style Japanese Japán Symbol Libraries Szimbólumkönyvtárak Symbol Screener Tool Szimbólumhalványító Symbol Scruncher Tool Szimbólumtömörítő + Tool: Eszköz: + Symbol Set Density Szimbólumkészlet sűrűsége + Symbol Sprayer Options Szimbólumszóró beállításai + Scrunch: Tömörítés: + Spin: Forgatás: + Screen: Halványítás: + Stain: Színezés: + Symbol Sizer Options Szimbólumméretező beállításai + Proportional Resizing Arányos átméretezés + Resizing Affects Density Az átméretezés befolyásolja a sűrűséget + Show Brush Size and Intensity Ecsetméret és erősség megjelenítése Symbol Set Density: Szimbólumkészlet sűrűsége: Symbol Shifter Tool Szimbólumtoló Symbol Sizer Tool Szimbólumméretező diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5ef1c53ac..254e37a72e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3013,6 +3013,17 @@ antiAlias Sharp Tajam Swatch Name: Nama swatch: Diameter: Diameter: Symbolism Tools Options Opsi alat simbolisme + Tool: Alat: + Symbol Set Density Kepadatan set simbol + Symbol Sprayer Options Opsi penyemprot simbol + Scrunch: Perapatan: + Spin: Putaran: + Screen: Penyaringan: + Stain: Pewarnaan: + Symbol Sizer Options Opsi pengubah ukuran simbol + Proportional Resizing Ubah ukuran secara proporsional + Resizing Affects Density Perubahan ukuran memengaruhi kepadatan + Show Brush Size and Intensity Tampilkan ukuran dan intensitas kuas Symbol Set Density: Kepadatan set simbol: Intensity: Intensitas: Place PDF Tempatkan PDF diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index b0ef62f97a..8506a86426 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1315,6 +1315,17 @@ font-technology Variable Variabili Largest: Più grande: Direction: Direzione: Symbolism Tools Options Opzioni strumenti simboli + Tool: Strumento: + Symbol Set Density Densità del set di simboli + Symbol Sprayer Options Opzioni spruzzo simboli + Scrunch: Addensamento: + Spin: Rotazione: + Screen: Trasparenza: + Stain: Colorazione: + Symbol Sizer Options Opzioni ridimensionamento simboli + Proportional Resizing Ridimensionamento proporzionale + Resizing Affects Density Il ridimensionamento influisce sulla densità + Show Brush Size and Intensity Mostra dimensione e intensità del pennello Symbol Set Density: Densità del set di simboli: Flat Image Immagine appiattita Flat Logo Logo piatto diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ed4981b977..8c7c337747 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3847,6 +3847,17 @@ gradient-kind Radial 円形 Largest: 最大: Direction: 方向: Symbolism Tools Options シンボルツールオプション + Tool: ツール: + Symbol Set Density シンボルセットの密度 + Symbol Sprayer Options シンボルスプレーのオプション + Scrunch: スクランチ: + Spin: スピン: + Screen: スクリーン: + Stain: ステイン: + Symbol Sizer Options シンボルリサイザーのオプション + Proportional Resizing 縦横比を保持してサイズ変更 + Resizing Affects Density サイズ変更で密度を変更 + Show Brush Size and Intensity ブラシサイズと強度を表示 Symbol Set Density: シンボルセットの密度: Flattener presets 分割・統合プリセット file-filter All readable files 読み込めるすべてのファイル diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 358960bd37..bdaff6bb5b 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4981,6 +4981,17 @@ antiAlias Sharp მკვეთრი Swatch Name: ფერის ნიმუშის სახელი: Diameter: დიამეტრი: Symbolism Tools Options სიმბოლოების ხელსაწყოების პარამეტრები + Tool: ხელსაწყო: + Symbol Set Density სიმბოლოების ნაკრების სიმჭიდროვე + Symbol Sprayer Options სიმბოლოების სპრეის პარამეტრები + Scrunch: შეკუმშვა: + Spin: შემობრუნება: + Screen: გამჭვირვალობა: + Stain: შეფერადება: + Symbol Sizer Options სიმბოლოების ზომის შეცვლის პარამეტრები + Proportional Resizing პროპორციული ზომის შეცვლა + Resizing Affects Density ზომის შეცვლა სიმჭიდროვეზე მოქმედებს + Show Brush Size and Intensity ფუნჯის ზომისა და ინტენსივობის ჩვენება Symbol Set Density: სიმბოლოების ნაკრების სიმჭიდროვე: Intensity: ინტენსივობა: Place PDF PDF-ის განთავსება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index cd7130d7ef..1f56173373 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3835,6 +3835,17 @@ gradient-kind Radial 방사형 Largest: 최대: Direction: 방향: Symbolism Tools Options 심볼 도구 옵션 + Tool: 도구: + Symbol Set Density 심볼 세트 밀도 + Symbol Sprayer Options 심볼 분무기 옵션 + Scrunch: 스크런치: + Spin: 회전: + Screen: 스크린: + Stain: 염색: + Symbol Sizer Options 심볼 크기 조절기 옵션 + Proportional Resizing 비율에 맞게 크기 조정 + Resizing Affects Density 크기 조정이 밀도에 영향 + Show Brush Size and Intensity 브러시 크기 및 강도 표시 Symbol Set Density: 심볼 세트 밀도: Flattener presets 병합 프리셋 file-filter All readable files 읽을 수 있는 모든 파일 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 101d37b1e6..0ad3d79b4d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3575,6 +3575,17 @@ antiAlias Sharp Scherp Swatch Name: Staalnaam: Diameter: Diameter: Symbolism Tools Options Opties symbolisatiegereedschappen + Tool: Gereedschap: + Symbol Set Density Symboolsetdichtheid + Symbol Sprayer Options Opties voor symboolspuit + Scrunch: Verdichten: + Spin: Roteren: + Screen: Transparantie: + Stain: Kleuren: + Symbol Sizer Options Opties voor symboolgrootte + Proportional Resizing Proportioneel schalen + Resizing Affects Density Schalen beïnvloedt dichtheid + Show Brush Size and Intensity Penseelgrootte en intensiteit tonen Symbol Set Density: Symboolsetdichtheid: Intensity: Intensiteit: Place PDF PDF plaatsen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f5db22b1be..5a89e1ad02 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3165,6 +3165,17 @@ antiAlias Sharp Ostre Swatch Name: Nazwa próbki: Diameter: Średnica: Symbolism Tools Options Opcje narzędzi symboli + Tool: Narzędzie: + Symbol Set Density Gęstość zestawu symboli + Symbol Sprayer Options Opcje rozpylania symboli + Scrunch: Zagęszczanie: + Spin: Obracanie: + Screen: Przesłanianie: + Stain: Barwienie: + Symbol Sizer Options Opcje skalowania symboli + Proportional Resizing Skalowanie proporcjonalne + Resizing Affects Density Skalowanie wpływa na gęstość + Show Brush Size and Intensity Pokaż rozmiar i natężenie pędzla Symbol Set Density: Gęstość zestawu symboli: Intensity: Natężenie: Place PDF Umieść PDF diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a2b5cd06ba..d9ca9e0c65 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3627,6 +3627,17 @@ font-technology Variable Variáveis Largest: Maior: Direction: Direção: Symbolism Tools Options Opções das ferramentas de simbolismo + Tool: Ferramenta: + Symbol Set Density Densidade do conjunto de símbolos + Symbol Sprayer Options Opções do Pulverizador de Símbolos + Scrunch: Amontoar: + Spin: Girar: + Screen: Peneira: + Stain: Mancha: + Symbol Sizer Options Opções do Dimensionador de Símbolos + Proportional Resizing Redimensionamento proporcional + Resizing Affects Density Redimensionamento afeta a densidade + Show Brush Size and Intensity Mostrar tamanho e intensidade do pincel Symbol Set Density: Densidade do conjunto de símbolos: Flatten Artwork Achatar arte-final Graphics Gráficos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e5113d70ba..d525015e60 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1306,6 +1306,17 @@ font-technology Variable Вариативные Largest: Самое большое: Direction: Направление: Symbolism Tools Options Параметры инструментов символов + Tool: Инструмент: + Symbol Set Density Плотность набора символов + Symbol Sprayer Options Параметры распылителя символов + Scrunch: Сжатие: + Spin: Вращение: + Screen: Прозрачность: + Stain: Тонирование: + Symbol Sizer Options Параметры размера символов + Proportional Resizing Пропорциональное изменение размера + Resizing Affects Density Изменение размера влияет на плотность + Show Brush Size and Intensity Показывать размер и интенсивность кисти Symbol Set Density: Плотность набора символов: Flat Image Плоское изображение Flat Logo Плоский логотип diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e344e63b8f..27f303d375 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1265,6 +1265,17 @@ font-technology Variable Variabla Largest: Störst: Direction: Riktning: Symbolism Tools Options Alternativ för symbolverktyg + Tool: Verktyg: + Symbol Set Density Täthet för symboluppsättning + Symbol Sprayer Options Alternativ för symbolspruta + Scrunch: Dra ihop: + Spin: Rotera: + Screen: Opacitet: + Stain: Färga: + Symbol Sizer Options Alternativ för symbolstorlek + Proportional Resizing Proportionell storleksändring + Resizing Affects Density Storleksändring påverkar tätheten + Show Brush Size and Intensity Visa penselstorlek och intensitet Symbol Set Density: Täthet för symboluppsättning: Flat Image Platt bild Flat Logo Platt logotyp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c999e476e1..b7ac3afc69 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1261,6 +1261,17 @@ font-technology Variable Değişken Largest: En büyük: Direction: Yön: Symbolism Tools Options Sembolizm Araçları Seçenekleri + Tool: Araç: + Symbol Set Density Sembol Seti Yoğunluğu + Symbol Sprayer Options Sembol Püskürtücü Seçenekleri + Scrunch: Sıkıştırma: + Spin: Döndürme: + Screen: Saydamlaştırma: + Stain: Renklendirme: + Symbol Sizer Options Sembol Boyutlandırıcı Seçenekleri + Proportional Resizing Orantılı Yeniden Boyutlandırma + Resizing Affects Density Yeniden Boyutlandırma Yoğunluğu Etkiler + Show Brush Size and Intensity Fırça Boyutunu ve Yoğunluğunu Göster Symbol Set Density: Sembol Seti Yoğunluğu: Flat Image Düz Resim Flat Logo Düz Logo diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f4aed127a4..61ce4d8ba0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1309,6 +1309,17 @@ font-technology Variable Варіативні Largest: Найбільше: Direction: Напрямок: Symbolism Tools Options Параметри інструментів символів + Tool: Інструмент: + Symbol Set Density Щільність набору символів + Symbol Sprayer Options Параметри розпилювача символів + Scrunch: Стиск: + Spin: Обертання: + Screen: Прозорість: + Stain: Тонування: + Symbol Sizer Options Параметри розміру символів + Proportional Resizing Пропорційна зміна розміру + Resizing Affects Density Зміна розміру впливає на щільність + Show Brush Size and Intensity Показувати розмір та інтенсивність пензля Symbol Set Density: Щільність набору символів: Flat Image Плоске зображення Flat Logo Плоский логотип diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5a901079b3..5d1b06a158 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4101,6 +4101,17 @@ mark-style Japanese Kiểu Nhật Symbol Libraries Thư viện ký hiệu Symbol Screener Tool Công cụ Lọc ký hiệu Symbol Scruncher Tool Công cụ Thu gọn ký hiệu + Tool: Công cụ: + Symbol Set Density Mật độ bộ ký hiệu + Symbol Sprayer Options Tùy chọn phun ký hiệu + Scrunch: Thu gọn: + Spin: Xoay: + Screen: Lọc: + Stain: Tô màu: + Symbol Sizer Options Tùy chọn kích thước ký hiệu + Proportional Resizing Đổi kích thước theo tỷ lệ + Resizing Affects Density Đổi kích thước ảnh hưởng đến mật độ + Show Brush Size and Intensity Hiện kích thước và cường độ cọ Symbol Set Density: Mật độ bộ ký hiệu: Symbol Shifter Tool Công cụ Dịch chuyển ký hiệu Symbol Sizer Tool Công cụ Kích thước ký hiệu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 8d4c110afd..42a2243071 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1246,6 +1246,17 @@ antiAlias Sharp 锐利 Largest: 最大: Direction: 方向: Symbolism Tools Options 符号工具选项 + Tool: 工具: + Symbol Set Density 符号组密度 + Symbol Sprayer Options 符号喷枪选项 + Scrunch: 紧缩: + Spin: 旋转: + Screen: 透明度: + Stain: 着色: + Symbol Sizer Options 符号缩放选项 + Proportional Resizing 等比缩放 + Resizing Affects Density 缩放影响密度 + Show Brush Size and Intensity 显示画笔大小和强度 Symbol Set Density: 符号组密度: Flat Image 平面图像 Flatness: 平滑度: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 30da93ab71..a9d369156d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1280,6 +1280,17 @@ font-technology Variable 可變 Largest: 最大: Direction: 方向: Symbolism Tools Options 符號工具選項 + Tool: 工具: + Symbol Set Density 符號組密度 + Symbol Sprayer Options 符號噴灑器選項 + Scrunch: 緊縮: + Spin: 旋轉: + Screen: 濾色: + Stain: 染色: + Symbol Sizer Options 符號縮放器選項 + Proportional Resizing 等比例縮放 + Resizing Affects Density 縮放影響密度 + Show Brush Size and Intensity 顯示筆刷大小和強度 Symbol Set Density: 符號組密度: Flat Image 平面影像 Flatness: 平滑度: diff --git a/docs/mcp.md b/docs/mcp.md index 164fa77c84..ccb1f04cb5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3328,8 +3328,11 @@ already walks Image Trace. Short agent entry points: `from` passed applies only to a set without one (a group named "Symbol Set" by hand); the sets moved then have density `to`. A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. - - A `method`, an attribute or a density outside these values, a pressure that isn't a number, or no symbol set - among the objects of `symbol.setDensity`, is an error and changes nothing. + - A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray` + too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its + objects, is an error and changes nothing. + - Average leaves an instance without a size (a scale of 0) as it is; the other methods change it. A stroke that + changes no instance counts none and adds no undo step. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the @@ -10834,7 +10837,7 @@ intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5), `method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at -`intensity`/10 of its radius (no ring at 10 or with `usePressure`). Interaction state (pins, a reference point) starts afresh. In the +`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). Interaction state (pins, a reference point) starts afresh. In the desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). From 0bbddf5cc41c08b38e78442ec2b2277eb17e4dc4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:35:08 -0800 Subject: [PATCH 03/10] Symbols: Random styling and Symbol Set Density follow the brush and the set - With Method Random the Symbol Styler scales each instance's share of the style by the brush strength, so the brush edge and a light pen pressure style an instance less. - symbol.setDensity gives every selected set the new density, also a set whose instances do not move (one instance, or each locked), so a later change packs it from that density. No undo step is added when every set already has it. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbolism.rs | 16 ++++-- crates/engine/src/cmd/brushsym/symbols.rs | 4 +- crates/engine/src/tests/symbolism_options.rs | 53 +++++++++++++++++--- docs/mcp.md | 7 +-- 5 files changed, 66 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 4c98e432e2..68e9f8e7af 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -359,7 +359,7 @@ pub fn specs() -> Vec { "Symbol Set Density", [], None, - "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and the sets moved then have density `to`; a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves (a set already at `to`, or sets of one instance). A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", + "{from: 1..10, to: 1..10, ids?|id?} space the instances of the selected symbol sets (or those in `ids`) as Symbol Set Density `to` packs them, from the density each set was created at or last given (`from` for a set without one, such as one grouped by hand): each instance moves along the line from the middle of its set's instances, to (1.15 − 0.1·to) / (1.15 − 0.1·from) of its distance from it (each factor at least 0.1), as one undo step, and every set then has density `to`, also one whose instances do not move (one instance, or each locked); a higher density packs them closer, and a locked or hidden instance stays where it is. No undo step is added when no instance moves and every set already has density `to`. A `from` or `to` left out, not a number or outside 1..10, an id naming no object, or no symbol set among the objects is an error → {ids: the sets changed, count: the instances moved}", has_doc, symbol_set_density ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index f5df078745..8f288819b8 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -281,7 +281,8 @@ impl Grid { /// Symbol Set Density `to` packs them, from the density each set was created at or last given /// (`from` for a set without one): each instance moves along the line from the middle of its set's /// instances, to [`spacing`]`(to) / `[`spacing`]` of the set's density` of its distance from it. -/// The sets moved then have density `to`. One undo step, and none when no instance moves. +/// Every selected set then has density `to`, also one whose instances do not move. One undo step, +/// and none when no instance moves and every set already has density `to`. pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { const C: &str = "symbol.setDensity"; let density = |key: &str| match p.get(key) { @@ -311,10 +312,17 @@ pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { let mut changed: Vec = vec![]; for set in &sets { // A set packs from the density it was created at or last given, else from `from`. - let ratio = spacing(to) / spacing(set_density_of(d, *set).unwrap_or(from)); + let own = set_density_of(d, *set); + let ratio = spacing(to) / spacing(own.unwrap_or(from)); + // A set takes density `to` even when none of its instances moves (one instance, or each + // locked or on top of the others), so a later change packs it from `to`. + let restamp = own != Some(to); let centers: Vec<(NodeId, Point)> = d.node(*set).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| Some((c.id, instance_center(c)?))).collect(); if centers.len() < 2 { + if restamp { + changed.push(*set); + } continue; } let middle = (centers.iter().fold(Vec2::ZERO, |sum, (_, c)| sum + c.to_vec2()) / centers.len() as f64).to_point(); @@ -323,12 +331,12 @@ pub(super) fn symbol_set_density(s: &mut Session, p: &Value) -> Result { moves.extend( centers.iter().filter(|(id, _)| editable(*id)).map(|(id, c)| (*id, (*c - middle) * (ratio - 1.0))).filter(|(_, v)| v.hypot() > 1e-9), ); - if moves.len() > before { + if moves.len() > before || restamp { changed.push(*set); } } drop(editable); - if !moves.is_empty() { + if !changed.is_empty() { s.edit("Symbol Set Density", |d, _| { for (id, v) in &moves { if let Some(n) = d.node_mut(*id) { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 5c2f5a2a73..aefc32360f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1202,7 +1202,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { None => { let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); let step = match (tool.as_str(), method) { - ("style", Method::Random) => (share / 2.0) as f32, + // Random: the instance's share of the style, scaled by the + // brush strength there. + ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32, ("style", _) => 1.0, _ => (0.15 * w * share) as f32, }; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 635c17c7de..9fa03745ed 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -191,6 +191,24 @@ fn random_changes_each_instance_by_its_own_share() { assert_eq!(grown(Some("random")), random); } +/// With Method Random the Symbol Styler gives each instance its share of the style scaled by the +/// brush strength: at Intensity 1 a tenth of what it gives at Intensity 10. +#[test] +fn random_style_follows_the_brush_strength() { + let styled = |intensity: u32| { + let mut s = session(); + let ids = [(200.0, 150.0), (201.0, 150.0), (200.0, 151.0), (199.0, 150.0), (200.0, 149.0)].map(|(x, y)| dot(&mut s, x, y)); + let p = json!({"tool": "style", "points": [[200, 150]], "radius": 1000, "intensity": intensity, "method": "random", "color": "#ff0000"}); + adjust(&mut s, p); + ids.map(|id| f64::from(node(&s, id).appearance.fill().map_or(0.0, |f| f.opacity))) + }; + let (full, low) = (styled(10), styled(1)); + assert!(full.iter().any(|o| *o > 0.05), "{full:?}"); + for (f, l) in full.iter().zip(&low) { + assert!((l - f * 0.1).abs() < 1e-3, "{low:?} against {full:?}"); + } +} + /// A `method` that is none of the three is an error and changes nothing; the Symbol Shifter takes /// one and shifts as it does without. #[test] @@ -456,15 +474,11 @@ fn set_density_spaces_the_instances_of_a_symbol_set() { let r = s.execute("symbol.setDensity", &json!({"from": 9, "to": 5, "ids": [set.0, set.0]})).unwrap(); assert_eq!(r, json!({"ids": [set.0], "count": 8})); assert!(centers(&s).iter().zip(&was).all(|(a, b)| a.distance(*b) < 1e-9)); - // The density the set has (5, a `from` of 7 notwithstanding), or a set of one instance: no - // instance moves and no undo step is added. + // The density the set has (5, a `from` of 7 notwithstanding): no instance moves and no undo + // step is added. let steps = undo_len(&s); assert_eq!(s.execute("symbol.setDensity", &json!({"from": 7, "to": 5})).unwrap(), json!({"ids": [], "count": 0})); - s.select(|_, sel| sel.clear()).unwrap(); - let one = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[300, 40]]})).unwrap()["id"].as_u64().unwrap()); - let steps_with_one = undo_len(&s); - assert_eq!(s.execute("symbol.setDensity", &json!({"from": 1, "to": 10, "ids": [one.0]})).unwrap(), json!({"ids": [], "count": 0})); - assert_eq!((steps_with_one, undo_len(&s)), (steps + 1, steps + 1)); + assert_eq!(undo_len(&s), steps); // Undo puts a spaced set back. s.execute("symbol.setDensity", &json!({"from": 5, "to": 1, "id": set.0})).unwrap(); assert!(centers(&s)[0].distance(was[0]) > 1.0); @@ -508,6 +522,31 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() { assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); } +/// A set of one instance takes the new density without moving, as one undo step, so a later change +/// packs it from that density; setting the density it already has adds no undo step. +#[test] +fn set_density_gives_a_set_of_one_instance_the_new_density() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_len(&s); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [set.0], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + assert_eq!(s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(), json!({"ids": [], "count": 0})); + assert_eq!(undo_len(&s), steps + 1); + // A second instance, then from the set's 9 to 5: 0.65 / 0.25 of each distance from the middle. + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4, "density": 9})).unwrap(); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + let was: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let middle = Point::new((was[0].x + was[1].x) / 2.0, (was[0].y + was[1].y) / 2.0); + s.execute("symbol.setDensity", &json!({"from": 5, "to": 5, "ids": [set.0]})).unwrap(); + for (id, before) in ids.iter().zip(&was) { + let want = middle + (*before - middle) * (0.65 / 0.25); + assert!(center(&s, *id).distance(want) < 1e-9, "{before:?} -> {:?}", center(&s, *id)); + } +} + /// A locked instance of the set stays where it is, and the others move. #[test] fn set_density_leaves_a_locked_instance_in_place() { diff --git a/docs/mcp.md b/docs/mcp.md index ccb1f04cb5..7031f5e7ec 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3324,9 +3324,10 @@ already walks Image Trace. Short agent entry points: style. `attributes` left out means `average` for all six. - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and - adds none when no instance moves. `from` is the density each set was created at or last given, and the - `from` passed applies only to a set without one (a group named "Symbol Set" by hand); the sets moved then have - density `to`. A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the + adds none when no instance moves and every set already has density `to`. `from` is the density each set was + created at or last given, and the `from` passed applies only to a set without one (a group named "Symbol Set" by + hand); every set then has density `to`, also one whose instances do not move (one instance, or each locked). A + locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. - A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray` too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its From 6d470d98780ce31a27cedf6bc6d8a063264d603c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:48:14 -0800 Subject: [PATCH 04/10] Symbols: Average keeps opacities below the Screener's 5% minimum The Symbol Screener with Method Average, and the Symbol Sprayer with Screen: Average, clamped the averaged opacity to the Screener's 5% minimum. A new instance sprayed beside invisible ones became visible, and instances below 5% were raised instead of moving toward their mean. Averages now stay within 0..1; the non-average Screener still stops at 5%. docs/mcp.md also states that the User Defined Styler applies the whole style whatever the intensity or pen pressure. --- crates/engine/src/cmd/brushsym/symbols.rs | 5 ++-- crates/engine/src/tests/symbolism_options.rs | 24 ++++++++++++++++++++ docs/mcp.md | 5 +++- 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index d9183d0169..4338da1bf5 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1008,7 +1008,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { if modes.screen && let Some(m) = near { - n.opacity = (m.opacity as f32).clamp(0.05, 1.0); + n.opacity = (m.opacity as f32).clamp(0.0, 1.0); } // The stain and the style are both the instance's fill: the style, set last, replaces // the stain, an averaged one too when the instances under the brush have a fill. @@ -1254,7 +1254,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { _ => { let step = (0.1 * w * share) as f32; n.opacity = match &avg { - Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.05, 1.0), + // The mean may be below the 5% the Screener otherwise stops at. + Some((t, _)) => (n.opacity + ((t.opacity - f64::from(n.opacity)) * w.min(1.0)) as f32).clamp(0.0, 1.0), None if alt => (n.opacity + step).min(1.0), None => (n.opacity - step).max(0.05), }; diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 9fa03745ed..65ce6f8242 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -119,6 +119,30 @@ fn average_brings_the_instances_under_the_brush_toward_their_mean() { assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); } +/// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener +/// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush. +#[test] +fn average_keeps_opacities_below_the_screeners_least() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let a = members(&s, set)[0]; + let b = dot(&mut s, 220.0, 150.0); + for (id, opacity) in [(a, 0), (b, 2)] { + s.select(|_, sel| sel.set([id])).unwrap(); + s.execute("transparency.set", &json!({"opacity": opacity})).unwrap(); + } + s.select(|_, sel| sel.set([set])).unwrap(); + // A new instance beside the invisible one takes its opacity. + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[185, 150]], "radius": 20})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert_eq!(node(&s, sprayed).opacity, 0.0); + // The Screener with Average brings 0% and 2% toward 1%, not up to 5%. + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa < 0.02 && pb < 0.02 && pb > 0.0, "{pa} {pb}"); +} + /// Average over instances that already have the mean, or a stroke over no instance, changes /// nothing and adds no undo step. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 869c228683..209069983b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3427,7 +3427,10 @@ already walks Image Trace. Short agent entry points: Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when - no instance changes. + no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be + below the 5% that the Screener otherwise stops at. + - With `userDefined` the Styler gives each instance under the brush the whole style, whatever the intensity or the + pen pressure; `random` scales each instance's share by the brush strength there. - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. From b3c15f6e73bf7fc2111061d2e2787a915cfdbeb0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:51:30 -0800 Subject: [PATCH 05/10] Symbols: refuse bad Symbolism Tools Options and find spacing with a k-d tree tool.setOption for a Symbolism tool now refuses a method or Symbol Sprayer value outside its lists, and a usePressure, showBrush, proportional or affectsDensity that is not true or false, and sets none of the values. The Symbolism Tools Options dialog checks the same values before it gives the selected symbol sets a new density. Scrunch: Average measured each instance's nearest neighbor by scanning the grid cell around it, which compared every pair when many instances shared a cell. A k-d tree of the instances under the brush now finds each one's nearest neighbor. --- crates/engine/src/cmd/brushsym/symbolism.rs | 94 +++++++++++++------ crates/engine/src/cmd/brushsym/symbols.rs | 2 +- crates/engine/src/tests/symbolism_options.rs | 20 ++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/symbolism.rs | 24 +++++ .../ui-egui/src/dialogs/symbolism_options.rs | 22 ++++- docs/mcp.md | 4 +- 7 files changed, 135 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index 8f288819b8..0c925abda1 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -163,34 +163,65 @@ pub(super) struct Mean { pub gap: Option, } -/// For each of `looks`, the distance to the nearest of the others (infinite for one alone). Each -/// is first looked for in the cells around it of a grid `cell` points wide: one found within `cell` -/// is the nearest, since every one that near is in those cells. Otherwise all are measured. -fn nearest_gaps(looks: &[&Look], cell: f64) -> Vec { - let cell = cell.max(1e-6); - let mut cells: HashMap<(i64, i64), Vec> = HashMap::new(); - for (i, l) in looks.iter().enumerate() { - cells.entry(key(l.center, cell)).or_default().push(i); +/// The x (`axis` 0) or y (`axis` 1) of `p`. +fn coord(p: Point, axis: usize) -> f64 { + if axis == 0 { p.x } else { p.y } +} + +/// Arrange `order` (indices into `pts`) as a k-d tree: the middle entry of each slice splits the +/// rest by x at even depths and by y at odd ones, the smaller values before it. +fn kd_build(order: &mut [usize], pts: &[Point], axis: usize) { + if order.len() <= 1 { + return; } - let distance = |i: usize, j: usize| if i == j { None } else { Some(looks.get(j)?.center.distance(looks.get(i)?.center)) }; - (0..looks.len()) + let mid = order.len() / 2; + let at = |i: &usize| pts.get(*i).map_or(0.0, |p| coord(*p, axis)); + order.select_nth_unstable_by(mid, |a, b| at(a).total_cmp(&at(b))); + let (left, right) = order.split_at_mut(mid); + kd_build(left, pts, 1 - axis); + kd_build(right.get_mut(1..).unwrap_or_default(), pts, 1 - axis); +} + +/// The distance from `pts[i]` to the nearest of the others in k-d tree `order`, if nearer than +/// `best`. Instances on top of each other end the search: none can be nearer. +fn kd_nearest(order: &[usize], pts: &[Point], axis: usize, i: usize, best: &mut f64) { + let (Some(&j), Some(&p)) = (order.get(order.len() / 2), pts.get(i)) else { return }; + let Some(&q) = pts.get(j) else { return }; + if j != i { + *best = best.min(p.distance(q)); + } + if *best == 0.0 { + return; + } + let (left, right) = order.split_at(order.len() / 2); + let right = right.get(1..).unwrap_or_default(); + let diff = coord(p, axis) - coord(q, axis); + let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) }; + kd_nearest(near, pts, 1 - axis, i, best); + // The other side holds nothing nearer than the split line. + if diff.abs() < *best { + kd_nearest(far, pts, 1 - axis, i, best); + } +} + +/// For each of `looks`, the distance to the nearest of the others (infinite for one alone), found +/// through a k-d tree of their centers. +fn nearest_gaps(looks: &[&Look]) -> Vec { + let pts: Vec = looks.iter().map(|l| l.center).collect(); + let mut order: Vec = (0..pts.len()).collect(); + kd_build(&mut order, &pts, 0); + (0..pts.len()) .map(|i| { let mut best = f64::INFINITY; - for j in around(&cells, looks.get(i).map_or(Point::ZERO, |l| l.center), cell) { - best = distance(i, j).map_or(best, |d| best.min(d)); - // Instances on top of each other: none can be nearer. - if best == 0.0 { - break; - } - } - if best <= cell { best } else { (0..looks.len()).filter_map(|j| distance(i, j)).fold(f64::INFINITY, f64::min) } + kd_nearest(&order, &pts, 0, i, &mut best); + best }) .collect() } /// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with -/// [`Mean::gap`] when `gap_cell` gives the grid width [`nearest_gaps`] uses. -pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option) -> Option { +/// [`Mean::gap`] when `with_gap` is set. +pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { if looks.is_empty() { return None; } @@ -215,7 +246,7 @@ pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option) -> Option< // Rotations that cancel out have no mean direction: the first instance's stands for it. let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle }; // One instance under the brush has no spacing there. - let gap = gap_cell.filter(|_| looks.len() > 1).map(|cell| nearest_gaps(looks, cell).iter().sum::() / n); + let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::() / n); Some(Mean { scale: (log_scale / n).exp(), angle, @@ -273,7 +304,7 @@ impl Grid { pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option { let near: Vec<&Look> = around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect(); - mean(&near, at, with_gap.then_some(radius / 4.0)) + mean(&near, at, with_gap) } } @@ -358,20 +389,27 @@ mod tests { Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None } } + /// The distance from each instance in `from` to the nearest other one in `refs`, measured + /// against every other instance. + fn brute(refs: &[&Look], from: impl Iterator) -> Vec { + from.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)).collect() + } + /// The gaps are each instance's distance to its nearest neighbor, measured against every other /// instance: close pairs whose members are far apart in the order, instances on top of each - /// other, and instances farther apart than the grid's cells. + /// other, instances far from all others, many instances close together, and many on one line. #[test] fn nearest_gaps_match_measuring_every_pair() { let mut looks: Vec = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect(); // The second member of each pair comes 300 places later. looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0))); looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]); + // 400 instances within one point of each other, and 200 on one upright line. + looks.extend((0..400).map(|i| at(700.0 + f64::from(i % 20) * 0.05, 700.0 + f64::from(i / 20) * 0.05))); + looks.extend((0..200).map(|i| at(-50.0, f64::from(i) * 1.5))); let refs: Vec<&Look> = looks.iter().collect(); - let brute: Vec = (0..refs.len()) - .map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)) - .collect(); - assert_eq!(nearest_gaps(&refs, 10.0), brute); - assert_eq!(nearest_gaps(&refs[..1], 10.0), [f64::INFINITY]); + assert_eq!(nearest_gaps(&refs), brute(&refs, 0..refs.len())); + assert_eq!(nearest_gaps(&refs[..1]), [f64::INFINITY]); + assert_eq!(nearest_gaps(&refs[..0]), Vec::::new()); } } diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 4338da1bf5..f832e71e22 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1129,7 +1129,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { .then(|| { let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect(); - mean(&looks.iter().collect::>(), *q, None) + mean(&looks.iter().collect::>(), *q, false) }) .flatten(); for id in &candidates { diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index 65ce6f8242..bb52cf67c4 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -119,6 +119,26 @@ fn average_brings_the_instances_under_the_brush_toward_their_mean() { assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}"); } +/// `tool.setOption` refuses a Method, a Symbol Sprayer option or a checkbox value the Symbolism Tools +/// Options do not have, and sets none of the values given with it. +#[test] +fn bad_symbolism_tool_options_are_refused() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (values, want) in [ + (json!({"proportional": false, "method": "smooth"}), "`method` must be one of userDefined, average, random"), + (json!({"sprayScrunch": "random"}), "`sprayScrunch` must be one of average, userDefined"), + (json!({"method": "average", "usePressure": 1}), "`usePressure` must be true or false"), + (json!({"affectsDensity": "yes"}), "`affectsDensity` must be true or false"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": values})); + assert_eq!(r, Err(want.to_string()), "{values}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{values}"); + } + s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "key": "method", "value": "random"})).unwrap(); + assert_eq!(s.tool_options_of("symbolSizer")["method"], json!("random")); +} + /// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener /// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..2325c1187d 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1347,6 +1347,7 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + vectorcraft_tools::symbolism::check_options(tool.unwrap_or(self.tool.id()), &values)?; if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; // The most the selected image can be cropped to, when one is selected. diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 38471ccae1..ce2396c45c 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -72,6 +72,30 @@ pub struct SymbolismTool { pub affects_density: bool, } +/// Checks the Symbolism Tools Options in `values` before `tool.setOption` sets any, when `tool` is +/// a symbolism tool: `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not +/// one of [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that +/// is not true or false are errors. Ok for every other tool and every other key. Saved settings go +/// to the tool's `set_option` instead, which skips a value it cannot read. +pub fn check_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { + if !tool.starts_with("symbol") || create(tool).is_none() { + return Ok(()); + } + let must_be = |key: &str, names: &[&str]| format!("`{key}` must be one of {}", names.join(", ")); + for (key, v) in values { + let error = match key.as_str() { + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => (!v.is_boolean()).then(|| format!("`{key}` must be true or false")), + "method" => one_of(v, &METHODS).is_none().then(|| must_be(key, &METHODS)), + k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).is_none().then(|| must_be(key, &SPRAY_MODES)), + _ => None, + }; + if let Some(e) = error { + return Err(e); + } + } + Ok(()) +} + /// `v` as one of `allowed`, when it is one. fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> { let s = v.as_str()?; diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index d3dbbd8e06..677aa63fec 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -121,8 +121,10 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let mut values: Map = NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - values.extend(SWITCHES.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.bool(k))))); - values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + // The checkboxes and choices as the fields hold them, so a value the tools do not have is refused. + values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); + // An option `tool.setOption` refuses leaves the symbol sets as they are too. + vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?; let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { @@ -265,6 +267,22 @@ mod tests { assert!(width(&app) < was * 0.8, "{} of {was}", width(&app)); assert_eq!(undo(&app), steps + 1); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + // An option the tools do not have: neither the set nor the options change. + let (was, steps) = (width(&app), undo(&app)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert("method".into(), json!("smooth")); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert("usePressure".into(), json!(1)); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); + app.ui.dialog = None; // Without a set selected only the option changes. app.run("select.set", json!({"ids": []})).unwrap(); let (was, steps) = (width(&app), undo(&app)); diff --git a/docs/mcp.md b/docs/mcp.md index 209069983b..30d85c2056 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11296,7 +11296,9 @@ intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5), `method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain` and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at -`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). Interaction state (pins, a reference point) starts afresh. In the +`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). For a +Symbolism tool, a `method` or Symbol Sprayer value not in those lists, or a `usePressure`, `showBrush`, `proportional` +or `affectsDensity` that is not true or false, is an error that sets none of the values. Interaction state (pins, a reference point) starts afresh. In the desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). From 86694a1b30bda9a67e1f8046bc1b3d0ca25e225b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:28:21 -0800 Subject: [PATCH 06/10] Symbols: check dialog fields and the sprayed style before any change The Symbolism Tools Options dialog refuses a tool that is not a Symbolism tool and a number field that does not read as a number before it gives the selected symbol sets a new density, so a refused OK leaves the document as it was. A length with its unit is still a diameter. symbol.spray with Style: User Defined refuses a style the document does not have. The Symbol Sprayer leaves out a style that has been deleted, so the default style applies. --- crates/engine/src/cmd/brushsym.rs | 2 +- crates/engine/src/cmd/brushsym/symbols.rs | 4 +++ crates/engine/src/tests/symbolism_options.rs | 5 ++++ crates/tools/src/symbolism.rs | 3 +- .../ui-egui/src/dialogs/symbolism_options.rs | 29 ++++++++++++++++++- docs/mcp.md | 3 +- 6 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index f338dd34c7..0956bf5017 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -350,7 +350,7 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", + "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index f832e71e22..25c83152ff 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -942,6 +942,10 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { None => s.paint.fill.color().unwrap_or(Color::BLACK), }; let style = style_paint(&st.doc, p); + // Style: User Defined uses the style `style` names, so one the document does not have is an error. + if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { + return Err(bad(C, format!("unknown graphic style `{n}`"))); + } let size = natural_size(&st.doc, &name); let set = st.selection.objects.first().copied().filter(|id| st.selection.len() == 1 && st.doc.node(*id).is_some_and(is_symbol_set)); // Only a new Symbol Set needs a layer that takes new art. diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index bb52cf67c4..badd38a3ba 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -488,6 +488,11 @@ fn bad_sprayer_attributes_are_refused() { } refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150]], "keepModel": "yes"}), "`keepModel` must be true or false"); refused(&mut s, "symbol.spray", json!({"name": "Dot", "points": [[200, 150, "x"]]}), "a point's pressure must be a number, not \"x\""); + // Style: User Defined with a style the document does not have; Average does not use it. + let user = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": "Nope"}); + refused(&mut s, "symbol.spray", user, "unknown graphic style `Nope`"); + let average = json!({"name": "Dot", "points": [[200, 150]], "style": "Nope"}); + assert_eq!(s.execute("symbol.spray", &average).unwrap()["count"], 1); let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); assert_eq!(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "attributes": all})).unwrap()["count"], 1); } diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index ce2396c45c..2c51af2365 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -166,7 +166,8 @@ impl SymbolismTool { v["color"] = serde_json::to_value(c).unwrap_or(Value::Null); v["keepModel"] = json!(true); } - if let Some(s) = &self.style { + // A style the document no longer has (a deleted one) is left out: the default style applies. + if let Some(s) = self.style.as_ref().filter(|s| cx.doc.graphic_styles.iter().any(|g| g.name == **s)) { v["style"] = json!(s); } return ("symbol.spray".into(), v); diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 677aa63fec..969a625ee0 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -124,7 +124,20 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { // The checkboxes and choices as the fields hold them, so a value the tools do not have is refused. values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); // An option `tool.setOption` refuses leaves the symbol sets as they are too. - vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?; + let tool = d.str("tool"); + if !SYMBOLISM.contains(&tool.as_str()) { + return Err(format!("unknown tool `{tool}`")); + } + // A number, or text that reads as one (a length with its unit for the diameter). + let readable = |v: &Value| match v { + Value::Number(_) => true, + Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).is_some(), + _ => false, + }; + if let Some(k) = NUMBERS.iter().chain(&[DENSITY_WAS]).find(|k| d.fields.get(**k).is_some_and(|v| !readable(v))) { + return Err(format!("`{k}` must be a number")); + } + vectorcraft_tools::symbolism::check_options(&tool, &values)?; let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { @@ -281,6 +294,20 @@ mod tests { d.fields.insert("usePressure".into(), json!(1)); assert!(super::super::confirm(&mut app).is_err()); assert_eq!((width(&app), undo(&app)), (was, steps)); + // A tool that is not a Symbolism tool, or a density that is not a number. + for (k, v) in [("tool", json!("pen")), ("density", json!("three")), ("densityWas", json!(null))] { + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(3)); + d.fields.insert(k.into(), v); + assert!(super::super::confirm(&mut app).is_err(), "{k}"); + assert_eq!((width(&app), undo(&app)), (was, steps), "{k}"); + } + // A length with its unit is a diameter. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("diameter".into(), json!("12 pt")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("symbolSizer")["diameter"].as_f64(), Some(12.0)); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0)); app.ui.dialog = None; // Without a set selected only the option changes. diff --git a/docs/mcp.md b/docs/mcp.md index 30d85c2056..7528fd44db 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3419,7 +3419,8 @@ already walks Image Trace. Short agent entry points: `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and - `style` for the User Defined stain and style. `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol + `style` for the User Defined stain and style (with `style: userDefined`, a `style` the document does not have is an + error). `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice it (the Spinner: a turn either way), the same each time the stroke is applied. From a8abd874f2dcc8a75dc59ed271a56088e3e9f78f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:46:09 -0800 Subject: [PATCH 07/10] Symbols: symbol.spray refuses a style that is not a name A style parameter that is not a string was read as no style, and the default style applied. It is now an error. --- crates/engine/src/cmd/brushsym/symbols.rs | 3 +++ crates/engine/src/tests/symbolism_options.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 25c83152ff..c871f2405a 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -941,6 +941,9 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; + if let Some(v) = p.get("style").filter(|v| !v.is_string()) { + return Err(bad(C, format!("`style` must be a graphic style's name, not {v}"))); + } let style = style_paint(&st.doc, p); // Style: User Defined uses the style `style` names, so one the document does not have is an error. if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index badd38a3ba..f475bff74a 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -491,6 +491,8 @@ fn bad_sprayer_attributes_are_refused() { // Style: User Defined with a style the document does not have; Average does not use it. let user = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": "Nope"}); refused(&mut s, "symbol.spray", user, "unknown graphic style `Nope`"); + let number = json!({"name": "Dot", "points": [[200, 150]], "attributes": {"style": "userDefined"}, "style": 3}); + refused(&mut s, "symbol.spray", number, "`style` must be a graphic style's name, not 3"); let average = json!({"name": "Dot", "points": [[200, 150]], "style": "Nope"}); assert_eq!(s.execute("symbol.spray", &average).unwrap()["count"], 1); let all = json!({"scrunch": "average", "size": "userDefined", "spin": null, "screen": "average", "stain": "average", "style": "average"}); From 43a968d7513b09d8d7a516c6a8c8a291ef87e8da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:03:58 -0800 Subject: [PATCH 08/10] Symbols: the options dialog skips locked or hidden symbol sets OK gave a new density only to symbol sets that can be edited, but a locked or hidden one in the selection made symbol.setDensity fail, so the brush options were not saved either. The dialog now leaves such sets out. --- .../ui-egui/src/dialogs/symbolism_options.rs | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 969a625ee0..7a6fa2f29e 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -110,10 +110,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The selected symbol sets. +/// The selected symbol sets that can be edited (not locked or hidden). fn selected_sets(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set)).map(|id| id.0).collect() + let editable = st.doc.editable(); + st.selection + .objects + .iter() + .filter(|id| st.doc.node(**id).is_some_and(vectorcraft_engine::cmd::is_symbol_set) && editable(**id)) + .map(|id| id.0) + .collect() } /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving @@ -319,4 +325,25 @@ mod tests { assert_eq!((width(&app), undo(&app)), (was, steps)); assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(2.0)); } + + /// A locked symbol set in the selection keeps its spacing, and OK still sets the options. + #[test] + fn ok_sets_the_options_with_a_locked_symbol_set_selected() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 10, "height": 10})).unwrap(); + app.run("symbol.new", json!({"name": "Dot"})).unwrap(); + app.run("select.set", json!({"ids": []})).unwrap(); + let set = app.run("symbol.spray", json!({"name": "Dot", "points": [[40, 150], [120, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap(); + app.run("object.lock", json!({})).unwrap(); + app.session.select(|_, sel| sel.set([vectorcraft_doc::NodeId(set)])).unwrap(); + let steps = app.session.active().unwrap().history.undo.len(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("density".into(), json!(9)); + d.fields.insert("diameter".into(), json!(30)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + let o = app.session.tool_options_of("symbolSizer"); + assert_eq!((o["density"].as_f64(), o["diameter"].as_f64()), (Some(9.0), Some(30.0))); + } } From 3ef0e5e58883a6c548252d0d7f988c7e06d90c62 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 15:10:38 -0800 Subject: [PATCH 09/10] Symbols: the Symbolism tools take their new options, and OK checks them before any change tool.setOption now accepts usePressure, method, showBrush, the Symbol Sprayer options, proportional and affectsDensity for the Symbolism tools, so the Symbolism Tools Options dialog can save them. The dialog checks every option, the number ranges included, before symbol.setDensity re-spaces the selected symbol sets. - Size: Average gives a sprayed instance the mean size under the brush, or the symbol's own size with none there, without the size jitter. - A stroke that moves an instance away and back again does not count it, and adds no undo step. - symbol.adjust reads an instance's own values for Average only. --- crates/engine/src/cmd/brushsym/symbols.rs | 13 +++++--- crates/engine/src/tests/symbolism_options.rs | 21 ++++++++++--- crates/tools/src/symbolism.rs | 30 ++++++++----------- .../ui-egui/src/dialogs/symbolism_options.rs | 12 +++++--- 4 files changed, 47 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 88f3c5b65b..66588ad5be 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1036,8 +1036,9 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let (_, _, js) = jitter(i + 7, *c); let near = near.as_ref(); // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained - // with the fill color and given the style, each in full. - let k = near.filter(|_| modes.size).map_or(scale, |m| m.scale) * (1.0 + js * 0.1); + // with the fill color and given the style, each in full. Size: Average is the mean size + // under the brush, or the symbol's own size with none there, without the size jitter. + let k = if modes.size { near.map_or(scale, |m| m.scale) } else { scale * (1.0 + js * 0.1) }; let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); @@ -1155,7 +1156,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; // No undo step when no instance changes (none under the brush, or Average with each at the mean). - let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); for (j, (q, pressure)) in pts.iter().enumerate() { let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; @@ -1181,7 +1182,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } // Average needs the instance's own values, so it leaves an instance without a size // as it is; the other methods change it as before. - let avg = match (method, &target, d.node(*id).and_then(|n| look(d, n))) { + // The instance's own values are read for Average only. + let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n))).flatten(); + let avg = match (method, &target, own) { (Method::Average, Some(t), Some(cur)) => Some((t, cur)), // No mean under the brush (every instance there without a size), or none of // its own. @@ -1303,6 +1306,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } } + // An instance the stroke moved away and back again is not counted. + touched.retain(|id| d.node(*id) != orig.node(*id)); Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index f475bff74a..ca15570438 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -404,10 +404,10 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { s.execute("symbol.spray", &p).unwrap(); *members(s, set).last().unwrap() }; - // Average (the default): the new instance, sprayed beside it, looks like it. + // Average (the default): the new instance, sprayed beside it, looks like it, at its size. let near = spray(&mut s, json!([[215, 150]]), json!({})); let (w, o, f) = look(&s, near); - assert!((w / width - 1.0).abs() < 0.11, "{w} of {width}"); + assert!((w / width - 1.0).abs() < 1e-9, "{w} of {width}"); assert_eq!((o, f), (opacity, stain.clone())); // The averages of two instances that look alike are theirs. let third = spray(&mut s, json!([[208, 165]]), json!({"attributes": {"size": "average", "screen": null}})); @@ -415,10 +415,10 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { // Style: Average replaces a User Defined stain with the fill of the instances under the brush. let mixed = spray(&mut s, json!([[205, 160]]), json!({"attributes": {"stain": "userDefined"}, "color": "#0000ff"})); assert_eq!(look(&s, mixed).2.map(|(c, _)| c), stain.clone().map(|(c, _)| c)); - // Outside the brush's radius of every instance, the plain values. + // Outside the brush's radius of every instance, the plain values: the symbol's own size. let far = spray(&mut s, json!([[330, 250]]), json!({})); let (w, o, f) = look(&s, far); - assert!((w / 20.0 - 1.0).abs() < 0.11 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); + assert!((w / 20.0 - 1.0).abs() < 1e-9 && o == 1.0 && f.is_none(), "{w} {o} {f:?}"); // User Defined: the symbol's size and opaque; Style: Average still gives the fill under the brush. let user = json!({"size": "userDefined", "screen": "userDefined", "stain": "userDefined", "spin": "userDefined"}); let plain = spray(&mut s, json!([[212, 140]]), json!({"attributes": user, "color": "#0000ff"})); @@ -703,3 +703,16 @@ fn a_stroke_that_changes_no_instance_adds_no_undo_step() { assert!(state(&s) == before, "{tool} changed the document"); } } + +/// An instance a stroke moves away and back to where it was is not counted, and the stroke adds +/// no undo step: the Shifter's drag out and back moves it 8 pt right, then 8 pt left. +#[test] +fn an_instance_moved_away_and_back_is_not_counted() { + let mut s = session(); + let id = dot(&mut s, 200.0, 150.0); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[196, 166], [212, 166], [196, 166]], "radius": 40, "intensity": 10})); + assert_eq!(bounds(&s, id).center(), Point::new(200.0, 150.0)); + assert_eq!(r["count"], 0); + assert!(state(&s) == before, "the stroke added an undo step"); +} diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index bdd5058804..d6148bdd72 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -73,27 +73,19 @@ pub struct SymbolismTool { } /// Checks the Symbolism Tools Options in `values` before `tool.setOption` sets any, when `tool` is -/// a symbolism tool: `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not -/// one of [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that -/// is not true or false are errors. Ok for every other tool and every other key. Saved settings go -/// to the tool's `set_option` instead, which skips a value it cannot read. +/// a symbolism tool, with the tool's own checks ([`Tool::check_option`]): a number out of its +/// range, `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not one of +/// [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that is not +/// true or false are errors. Ok for every other tool, and for a key the tool does not report +/// (`tool.setOption` refuses that one as an unknown option). Saved settings go to the tool's +/// `set_option` instead, which skips a value it cannot read. pub fn check_options(tool: &str, values: &serde_json::Map) -> Result<(), String> { if !tool.starts_with("symbol") || create(tool).is_none() { return Ok(()); } - let must_be = |key: &str, names: &[&str]| format!("`{key}` must be one of {}", names.join(", ")); - for (key, v) in values { - let error = match key.as_str() { - "usePressure" | "showBrush" | "proportional" | "affectsDensity" => (!v.is_boolean()).then(|| format!("`{key}` must be true or false")), - "method" => one_of(v, &METHODS).is_none().then(|| must_be(key, &METHODS)), - k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).is_none().then(|| must_be(key, &SPRAY_MODES)), - _ => None, - }; - if let Some(e) = error { - return Err(e); - } - } - Ok(()) + let tool = SymbolismTool::new(tool); + let known = tool.options(); + values.iter().filter(|(key, _)| known.get(key.as_str()).is_some()).try_for_each(|(key, v)| tool.check_option(key, v)) } /// `v` as one of `allowed`, when it is one. @@ -347,10 +339,14 @@ impl Tool for SymbolismTool { } fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { use crate::option_check as c; + let must_be = |names: &[&str]| format!("`{key}` must be one of {}", names.join(", ")); match key { "diameter" => c::number(key, v, 2.0, 2000.0), "intensity" | "density" => c::number(key, v, 1.0, 10.0), "symbol" | "style" => c::string_or_null(key, v), + "usePressure" | "showBrush" | "proportional" | "affectsDensity" => c::boolean(key, v), + "method" => one_of(v, &METHODS).map(drop).ok_or_else(|| must_be(&METHODS)), + k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).map(drop).ok_or_else(|| must_be(&SPRAY_MODES)), _ => Err(c::unknown(key)), } } diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 5f50fba20a..43a37812b5 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -122,8 +122,9 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { .collect() } -/// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges), after giving -/// a new Symbol Set Density to the selected symbol sets. +/// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the +/// selected symbol sets. Every option is checked first, so a value the tools refuse (a number out +/// of its range included) leaves the symbol sets and the options as they are. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let mut values: Map = NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); @@ -300,8 +301,11 @@ mod tests { d.fields.insert("usePressure".into(), json!(1)); assert!(super::super::confirm(&mut app).is_err()); assert_eq!((width(&app), undo(&app)), (was, steps)); - // A tool that is not a Symbolism tool, or a density that is not a number. - for (k, v) in [("tool", json!("pen")), ("density", json!("three")), ("densityWas", json!(null))] { + // A tool that is not a Symbolism tool, a density that is not a number, or a number out of + // its range. + for (k, v) in + [("tool", json!("pen")), ("density", json!("three")), ("densityWas", json!(null)), ("diameter", json!(1)), ("intensity", json!(11))] + { app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); let d = app.ui.dialog.as_mut().unwrap(); d.fields.insert("density".into(), json!(3)); From bae4defa458a101b2704c80dd87c318676e28f1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 17:34:48 -0800 Subject: [PATCH 10/10] Symbols: Average sizes are sizes on the page, and a pen pressure change where the pen stays is kept The Sizer's and the Sprayer's Average compare each instance's size on the page, so a set that holds instances of different symbols meets at their mean drawn size. A symbol without a recorded size is measured by its art, once per command. With Size: Average and no instance under the brush, a sprayed instance has its symbol's own size whatever `scale` is, and new instances are spaced by the size they are placed at. With Use Pressure Pen, a drag sample at the same position is kept when the pressure changes by 0.05 or more. --- crates/engine/src/cmd/brushsym/symbolism.rs | 51 ++++++++++---- crates/engine/src/cmd/brushsym/symbols.rs | 40 ++++++++--- crates/engine/src/tests/symbolism_options.rs | 71 ++++++++++++++++++++ crates/tools/src/symbolism.rs | 35 +++++++++- docs/mcp.md | 11 +-- 5 files changed, 179 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index 0c925abda1..0199b7b13d 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -4,8 +4,10 @@ use std::collections::HashMap; -use super::symbols::{instance_center, is_symbol_set}; -use super::{Affine, Document, EngineError, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids}; +use super::symbols::{instance_center, is_symbol_set, stored_natural_size}; +use super::{ + Affine, Document, EngineError, HALF, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, Vec2, bad, ids_json, json, named_ids, +}; /// Method: how the Scruncher, Sizer, Spinner, Stainer, Screener and Styler adjust instances. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -114,8 +116,8 @@ pub(super) fn record_set_density(d: &mut Document, sets: &[NodeId], density: f64 #[derive(Clone, Debug)] pub(super) struct Look { pub center: Point, - /// Its size as a share of its symbol's own size (1: the symbol's size). - pub scale: f64, + /// Its size on the page: the side of a square with its area, the same measure for every symbol. + pub size: f64, /// Its rotation in radians. pub angle: f64, pub opacity: f64, @@ -123,8 +125,12 @@ pub(super) struct Look { pub fill: Option<(Paint, f64)>, } +/// The [`natural_side`] of each symbol measured so far in one command, so that one measure serves +/// every instance of the symbol. +pub(super) type Sides = HashMap; + /// The [`Look`] of instance `n` (None for another object, or an instance without a size). -pub(super) fn look(d: &Document, n: &Node) -> Option { +pub(super) fn look(d: &Document, n: &Node, sides: &mut Sides) -> Option { let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return None }; let [a, b, c, e, ..] = xf.as_coeffs(); let natural = d.symbol_natural_xf(symbol).as_coeffs(); @@ -133,20 +139,41 @@ pub(super) fn look(d: &Document, n: &Node) -> Option { if !(scale.is_finite() && scale > 0.0) { return None; } + let side = match sides.get(symbol) { + Some(side) => *side, + None => *sides.entry(symbol.clone()).or_insert_with(|| natural_side(d, symbol)), + }; + let size = scale * side; + if !(size.is_finite() && size > 0.0) { + return None; + } Some(Look { center: instance_center(n)?, - scale, + size, angle: b.atan2(a), opacity: f64::from(n.opacity), fill: n.appearance.fill().map(|f| (f.paint.clone(), f64::from(f.opacity))), }) } +/// The [`Look::size`] of an instance of symbol `name` at the symbol's own size. A symbol without a +/// recorded size draws its art at the art's own size, so its art is measured. +pub(super) fn natural_side(d: &Document, name: &str) -> f64 { + let recorded = stored_natural_size(d, name).is_some_and(|(w, h)| w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0); + // Each side's root first, so that a huge size does not overflow. + let art = (!recorded).then(|| d.symbol_art_bounds(name)).flatten().map(|r| r.width().sqrt() * r.height().sqrt()); + if let Some(side) = art.filter(|s| s.is_finite() && *s > 0.0) { + return side; + } + let natural = d.symbol_natural_xf(name).as_coeffs(); + 2.0 * HALF * natural[0].abs().max(1e-9).sqrt() * natural[3].abs().max(1e-9).sqrt() +} + /// The mean of the [`Look`]s of the instances under the brush. #[derive(Clone, Debug)] pub(super) struct Mean { - /// The geometric mean of the sizes. - pub scale: f64, + /// The geometric mean of the sizes ([`Look::size`]). + pub size: f64, /// The mean direction of the rotations. pub angle: f64, pub opacity: f64, @@ -226,10 +253,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { return None; } let n = looks.len() as f64; - let (mut log_scale, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); + let (mut log_size, mut sin, mut cos, mut opacity, mut amount, mut middle) = (0.0, 0.0, 0.0, 0.0, 0.0, Vec2::ZERO); let mut paint: Option<(&Paint, f64)> = None; for l in looks { - log_scale += l.scale.ln(); + log_size += l.size.ln(); sin += l.angle.sin(); cos += l.angle.cos(); opacity += l.opacity; @@ -248,7 +275,7 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { // One instance under the brush has no spacing there. let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::() / n); Some(Mean { - scale: (log_scale / n).exp(), + size: (log_size / n).exp(), angle, opacity: opacity / n, amount: amount / n, @@ -386,7 +413,7 @@ mod tests { use super::*; fn at(x: f64, y: f64) -> Look { - Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None } + Look { center: Point::new(x, y), size: 20.0, angle: 0.0, opacity: 1.0, fill: None } } /// The distance from each instance in `from` to the nearest other one in `refs`, measured diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 66588ad5be..6f1b96b52f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,5 +1,5 @@ use super::dynamic::{fit_overrides, type_id, type_param}; -use super::symbolism::{Grid, Mean, Method, look, mean, method_param, record_set_density, spacing, spray_modes, wrap_angle}; +use super::symbolism::{Grid, Mean, Method, Sides, look, mean, method_param, natural_side, record_set_density, spacing, spray_modes, wrap_angle}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, @@ -1005,12 +1005,27 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { } return Ok(json!({ "count": n })); } - // Keep instances at least this far apart along the stroke (denser = closer). - let min_gap = size.0.max(size.1) * scale * spacing(density); + let side = natural_side(&st.doc, &name); + // The symbol's longest side as drawn at its own size: its art's, when it has no recorded size. + let recorded = stored_natural_size(&st.doc, &name).filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0); + let extent = match recorded { + Some((w, h)) => w.max(h), + None => { + let art = st.doc.symbol_art_bounds(&name).map(|r| r.width().max(r.height())); + art.filter(|e| e.is_finite() && *e > 0.0).unwrap_or(size.0.max(size.1)) + } + }; + // The scale a new instance is placed at, before the User Defined size jitter. Size: Average is + // the mean size on the page under the brush, of any symbol, or the symbol's own size with none + // there (not `scale`). + let placed_scale = |near: Option<&Mean>| { + if modes.size { near.map(|m| m.size / side).filter(|k| k.is_finite() && *k > 0.0).unwrap_or(1.0) } else { scale } + }; // The instances the selected set has, for the values a new one takes as their average. let existing = set.filter(|_| modes.any_average()).map(|g| { let d = &st.doc; - let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c)).collect(); + let mut sides = Sides::new(); + let looks = d.node(g).and_then(|n| n.children()).into_iter().flatten().filter_map(|c| look(d, c, &mut sides)).collect(); Grid::new(looks, radius) }); // Each instance to add: where, the mean of the set's instances under the brush there, and the @@ -1020,6 +1035,9 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let (jx, jy, _) = jitter(i, *q); let c = Point::new(q.x + jx * radius * 0.5, q.y + jy * radius * 0.5); let near = existing.as_ref().and_then(|g| g.mean(*q, radius, modes.scrunch)); + // Keep instances at least this far apart along the stroke (denser = closer), by the size + // the instance is placed at. + let min_gap = extent * placed_scale(near.as_ref()) * spacing(density); // Scrunch: Average spaces new instances as the ones under the brush are spaced. let gap = near.as_ref().and_then(|m| m.gap).filter(|_| modes.scrunch).unwrap_or(min_gap); if placed.last().is_some_and(|(l, ..)| l.distance(c) < gap) && i > 0 { @@ -1036,9 +1054,8 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { let (_, _, js) = jitter(i + 7, *c); let near = near.as_ref(); // User Defined: the symbol's own size, turned the way the stroke runs, opaque, stained - // with the fill color and given the style, each in full. Size: Average is the mean size - // under the brush, or the symbol's own size with none there, without the size jitter. - let k = if modes.size { near.map_or(scale, |m| m.scale) } else { scale * (1.0 + js * 0.1) }; + // with the fill color and given the style, each in full. Size: Average has no size jitter. + let k = if modes.size { placed_scale(near) } else { scale * (1.0 + js * 0.1) }; let angle = if modes.spin { near.map_or(0.0, |m| m.angle) } else { along.map_or(0.0, |v| v.atan2()) }; let turn = Affine::translate(c.to_vec2()) * Affine::rotate(angle) * Affine::translate(-c.to_vec2()); let id = d.alloc_id(); @@ -1158,6 +1175,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // No undo step when no instance changes (none under the brush, or Average with each at the mean). let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); + let mut sides = Sides::new(); for (j, (q, pressure)) in pts.iter().enumerate() { let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; // Use Pressure Pen: the pen's pressure at the point is the intensity there. @@ -1166,7 +1184,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let target = (method == Method::Average) .then(|| { let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius); - let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect(); + let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n, &mut sides))).collect(); mean(&looks.iter().collect::>(), *q, false) }) .flatten(); @@ -1183,7 +1201,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // Average needs the instance's own values, so it leaves an instance without a size // as it is; the other methods change it as before. // The instance's own values are read for Average only. - let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n))).flatten(); + let own = (method == Method::Average).then(|| d.node(*id).and_then(|n| look(d, n, &mut sides))).flatten(); let avg = match (method, &target, own) { (Method::Average, Some(t), Some(cur)) => Some((t, cur)), // No mean under the brush (every instance there without a size), or none of @@ -1197,7 +1215,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let out = (c - t.middle).hypot(); out <= 1e-9 || (t.reach - out).abs() < 1e-9 } - "size" => (t.scale / cur.scale - 1.0).abs() < 1e-9, + "size" => (t.size / cur.size - 1.0).abs() < 1e-9, "spin" => wrap_angle(t.angle - cur.angle).abs() < 1e-9, "stain" | "style" => { (t.amount - cur.fill.as_ref().map_or(0.0, |f| f.1)).abs() < 1e-6 && (cur.fill.is_some() || t.paint.is_none()) @@ -1228,7 +1246,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } "size" => { let k = match &avg { - Some((t, cur)) => (t.scale / cur.scale).powf(w.min(1.0)), + Some((t, cur)) => (t.size / cur.size).powf(w.min(1.0)), None => (1.0 + 0.08 * w).powf(if alt { -share } else { share }), }; // Without Proportional Resizing a drag resizes along its own direction: a diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index ca15570438..b8cb29f213 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -440,6 +440,77 @@ fn the_sprayer_gives_new_instances_the_average_or_the_user_defined_values() { assert_eq!(angle(&s, level), 0.0, "Average, with no instance under the brush"); } +/// Size: Average is a size on the page, the same measure for every symbol: a 20 pt symbol sprayed +/// beside an 80 pt one is 80 pt, and the Sizer brings the two to 40 pt. With no instance under the +/// brush a sprayed instance has its symbol's own size, whatever `scale` is. +#[test] +fn average_sizes_are_sizes_on_the_page_for_every_symbol() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Big", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let big = members(&s, set)[0]; + assert!((bounds(&s, big).width() - 80.0).abs() < 1e-9); + let spray = |s: &mut Session, at: Value| { + s.execute("symbol.spray", &json!({"name": "Dot", "points": at, "radius": 30, "scale": 2})).unwrap(); + *members(s, set).last().unwrap() + }; + let near = spray(&mut s, json!([[215, 150]])); + assert!((bounds(&s, near).width() - 80.0).abs() < 1e-9, "{}", bounds(&s, near).width()); + let far = spray(&mut s, json!([[350, 40]])); + assert!((bounds(&s, far).width() - 20.0).abs() < 1e-9, "{}", bounds(&s, far).width()); + // The Sizer: an unscaled Dot and an unscaled Big meet at the geometric mean of 20 and 80. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 80, "height": 80})).unwrap(); + s.execute("symbol.new", &json!({"name": "Big"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let big = NodeId(s.execute("symbol.place", &json!({"name": "Big", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + let between = json!([[210, 150], [210, 150], [210, 150], [210, 150], [210, 150], [210, 150]]); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wb) = (bounds(&s, small).width(), bounds(&s, big).width()); + assert!(ws > 30.0 && wb < 55.0 && (ws * wb / 1600.0 - 1.0).abs() < 1e-9, "{ws} {wb}"); + // A symbol without a recorded size is measured by its art: here 80 pt art drawn at its own size. + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 200, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Loose"})).unwrap(); + s.edit("Forget size", |d, _| { + if let Some(m) = d.unknown.get_mut(vectorcraft_doc::SYMBOL_SIZES).and_then(Value::as_object_mut) { + m.remove("Loose"); + } + for sym in d.symbols.iter_mut().filter(|sym| sym.name == "Loose") { + std::sync::Arc::make_mut(&mut sym.art).transform(Affine::scale(4.0), false); + } + Ok(()) + }) + .unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let small = dot(&mut s, 200.0, 150.0); + let loose = NodeId(s.execute("symbol.place", &json!({"name": "Loose", "x": 220, "y": 150})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + // Its width as drawn, measured by its symbol's art. + let drawn = |s: &Session| { + let d = &s.doc().unwrap().doc; + node(s, loose).geometric_bounds_with(&d.symbol_boxes()).unwrap().width() + }; + assert!((drawn(&s) - 80.0).abs() < 1e-9, "{}", drawn(&s)); + adjust(&mut s, json!({"tool": "size", "points": between, "radius": 30, "intensity": 10, "method": "average"})); + let (ws, wl) = (bounds(&s, small).width(), drawn(&s)); + assert!(ws > 30.0 && wl < 55.0, "{ws} {wl}"); + // A new set sprayed with Size: Average is spaced by the size it is placed at, not by `scale`. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 20.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Dot", "points": stroke, "radius": 2, "scale": 100})).unwrap(); + assert!(r["count"].as_u64().unwrap() > 5, "{r}"); + // The 80 pt art of a symbol without a recorded size spaces new instances by its own size. + s.select(|_, sel| sel.clear()).unwrap(); + let stroke: Vec = (0..50).map(|i| json!([100.0 + 4.0 * f64::from(i), 280.0])).collect(); + let r = s.execute("symbol.spray", &json!({"name": "Loose", "points": stroke, "radius": 2})).unwrap(); + assert!(r["count"].as_u64().unwrap() <= 5, "{r}"); +} + /// Spin: Average turns a new instance to the mean direction of the instances under the brush, and /// Scrunch: Average spaces new instances as those under the brush are spaced. #[test] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index d6148bdd72..a4fc04e0cc 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -236,8 +236,12 @@ impl Tool for SymbolismTool { PointerKind::Drag if self.active => { // Sprayer: thin the samples to a fraction of the brush; others: every few pixels. let step = if self.id == "symbolSprayer" { (self.diameter * 0.15).max(cx.tol(3.0)) } else { cx.tol(3.0) }; + // With Use Pressure Pen a change of pressure of at least 0.05 is kept where the pen + // stays (the Sprayer does not use the pressure). + let pressed = self.use_pressure && self.id != "symbolSprayer"; + let thinned = self.points.last().is_some_and(|(l, f)| l.distance(p) < step && !(pressed && (sample.1 - f).abs() >= 0.05)); // Each preview carries every point so far: a long drag stops growing and previews less often. - if self.points.len() >= MAX_STROKE_SAMPLES || self.points.last().is_some_and(|(l, _)| l.distance(p) < step) { + if self.points.len() >= MAX_STROKE_SAMPLES || thinned { return vec![]; } self.points.push(sample); @@ -573,6 +577,35 @@ mod tests { assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); } + /// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes; + /// without it, or with the same pressure, the drag keeps thinning the samples by distance. + #[test] + fn a_pressure_change_where_the_pen_stays_is_kept() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let stroke = |use_pressure: bool, pressures: [f32; 3]| { + let mut t = SymbolismTool::new("symbolSizer"); + t.set_option("usePressure", &json!(use_pressure)); + let at = |kind, pressure| PointerEvent { pressure, ..PointerEvent::new(kind, 5.0, 5.0) }; + let events = + [(PointerKind::Down, pressures[0]), (PointerKind::Drag, pressures[1]), (PointerKind::Drag, pressures[2]), (PointerKind::Up, 0.0)]; + // The points of the last preview, the one the drag commits. + let mut last = Value::Null; + for (kind, pressure) in events { + for a in t.pointer(&cx, &at(kind, pressure)) { + if let Action::Preview(_, v) = a { + last = v["points"].clone(); + } + } + } + last + }; + assert_eq!(stroke(true, [0.0, 1.0, 1.0]), json!([[5.0, 5.0, 0.0], [5.0, 5.0, 1.0]])); + assert_eq!(stroke(true, [0.5, 0.52, 0.5]), json!([[5.0, 5.0, 0.5]])); + assert_eq!(stroke(false, [0.0, 1.0, 1.0]), json!([[5.0, 5.0]])); + } + /// The Sprayer sends its six options as `attributes`, and the fill color only while Stain is /// User Defined. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9f1b014389..f56cb8e7b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3790,8 +3790,8 @@ already walks Image Trace. Short agent entry points: - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice it (the Spinner: a turn either way), the same each time the stroke is applied. - `average` moves each instance's value toward the mean of the instances within the brush at that point: the - Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes, - the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. + Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes + on the page, whatever their symbols, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be below the 5% that the Screener otherwise stops at. @@ -3801,9 +3801,10 @@ already walks Image Trace. Short agent entry points: height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the - stroke point: their spacing, size, rotation and opacity, and the stain or style of the nearest one that has one, - at the mean amount. With no instance there it has the symbol's size, no rotation, full opacity and no stain or - style. `attributes` left out means `average` for all six. + stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of + the nearest one that has one, at the mean amount. With no instance there it has the symbol's own size (not + `scale`), no rotation, full opacity and no stain or style. New instances are spaced by the size they are placed + at. `attributes` left out means `average` for all six. - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and adds none when no instance moves and every set already has density `to`. `from` is the density each set was