diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 41541c525e..85dfc8e084 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -571,6 +571,15 @@ pub struct PatternBrush { pub end_swatch: Option, /// Scale in percent. pub scale: f64, + /// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the + /// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art + /// brush's width does ([`ArtBrush::width_mode`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_mode: Option, + /// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`scale` without one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_max: Option, /// Space between tiles in percent of the tile width. pub spacing: f64, pub fit: PatternFit, @@ -583,6 +592,15 @@ impl PatternBrush { /// The ranges of the scale and of the spacing (%). pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0); pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0); + + /// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the + /// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen. + pub fn scale_range(&self) -> (f64, f64) { + match self.scale_mode { + Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)), + _ => (self.scale, self.scale), + } + } } impl Default for PatternBrush { @@ -606,6 +624,8 @@ impl Default for PatternBrush { end_frame: None, end_swatch: None, scale: 100.0, + scale_mode: None, + scale_max: None, spacing: 0.0, fit: PatternFit::Stretch, flip_along: false, @@ -791,6 +811,11 @@ impl Brush { } BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); + // The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. + if !p.scale_mode.is_some_and(Variation::follows_pen) { + p.scale_mode = None; + } + p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale)); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { if frame.is_some_and(|f| !valid_tile_frame(f)) { @@ -846,6 +871,8 @@ struct ArtOptions { #[derive(Serialize, Deserialize)] struct PatternOptions { scale: f64, + scale_mode: Option, + scale_max: Option, spacing: f64, fit: PatternFit, flip_along: bool, @@ -873,7 +900,7 @@ impl BrushKind { "brightness_jitter", ], BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], - BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"], BrushKind::Bristle(_) => &[], } } @@ -911,6 +938,8 @@ impl BrushKind { }), BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { scale: p.scale, + scale_mode: p.scale_mode, + scale_max: p.scale_max, spacing: p.spacing, fit: p.fit, flip_along: p.flip_along, @@ -940,8 +969,8 @@ impl BrushKind { } BrushKind::Pattern(p) => { let o: PatternOptions = serde_json::from_value(v)?; - (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = - (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + (p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing); + (p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization); } BrushKind::Bristle(_) => {} } @@ -1165,7 +1194,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), - BrushKind::Pattern(p) => warp::pattern(p, bp, w), + BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke), }; let colorization = brush.kind.colorization(); for n in &mut out { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index d23580cdea..0b6cbf6011 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2381,6 +2381,297 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() { assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]); } +/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`. +fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option, max: Option) -> Brush { + let mut b = pattern_brush(fit, corners); + if let BrushKind::Pattern(p) = &mut b.kind { + (p.scale, p.scale_mode, p.scale_max) = (scale, mode, max); + } + b +} + +/// The bounds of each piece, left to right. +fn piece_spans(out: &[Node]) -> Vec { + let mut spans: Vec = out.iter().filter_map(Node::geometric_bounds).collect(); + spans.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + spans +} + +/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen +/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen +/// pressed harder, and each Fit still fits them to the path. +#[test] +fn pattern_brush_scale_follows_the_pressure() { + let bp = line(0.0, 0.0, 200.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + // 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0)); + assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0)); + // Stretch to Fit fills the path, and the tiles grow longer along it. + let spans = piece_spans(&out); + assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out)); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}"); + assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}"); + // The stroke weight scales it. + let out = + draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() }); + assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0)); + // Without recorded pressure, half way between the two scales. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0)); + assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out)); + // With an even pressure, Add Space with spacing places as many tiles as the one scale that + // pressure gives: the spacing counts when the tiles are counted again. + let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]); + let spaced = |mode: Option, max: Option| { + let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 100.0; + } + piece_spans(&draw(&b, &even)).len() + }; + assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None)); + // With spacing, Stretch to Fit still fills the path and Approximate Path still centers the + // tiles, with the gaps between them counted and none after the last. + for fit in [PatternFit::Stretch, PatternFit::Approximate] { + let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 50.0; + } + let spans = piece_spans(&draw(&b, &ramp)); + let (first, last) = (spans[0], spans[spans.len() - 1]); + assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}"); + if fit == PatternFit::Stretch { + assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}"); + } + } + // Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it. + for fit in [PatternFit::AddSpace, PatternFit::Approximate] { + let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + let spans = piece_spans(&out); + assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}"); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}"); + let (first, last) = (spans[0], spans[spans.len() - 1]); + if fit == PatternFit::AddSpace { + assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}"); + } else { + assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}"); + } + } +} + +/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own +/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a +/// brush without the setting does. +#[test] +fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() { + let bp = line(0.0, 0.0, 100.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0)); + let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) }; + // 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %. + for (mode, st, height) in [ + (Variation::Tilt, posed(Some(0.0), None, None), 12.0), + (Variation::Tilt, posed(Some(1.0), None, None), 2.0), + (Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5), + (Variation::Rotation, posed(None, None, Some(-90.0)), 4.5), + (Variation::StylusWheel, wheel(1.0), 12.0), + (Variation::StylusWheel, wheel(0.0), 2.0), + // Without its own input, half way. + (Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0), + (Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0), + (Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0), + (Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0), + (Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0), + ] { + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, height, 1e-6), "{mode:?}: {h}"); + } + // Fixed, a mode without a second scale, and a second scale equal to the first draw what the + // brush draws without them. + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp); + for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] { + assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}"); + } + let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap(); + assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}"); + // A mode the scale does not take is read as Fixed, and the second scale is kept within range. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308}, + {"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0}, + ])); + let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") }; + assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0))); + // A stroke sets its own mode and second scale. + let mut own = serde_json::Map::new(); + own.insert("scale_mode".into(), serde_json::json!("pressure")); + own.insert("scale_max".into(), serde_json::json!(300.0)); + let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap(); + assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}"); +} + +/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale +/// where they are, on open and closed paths, and stays finite at the ends of the scale's range. +#[test] +fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() { + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let doc = Document::new(1.0, 1.0); + // Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile. + let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut ends.kind { + (p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0))); + } + let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp); + let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap()); + assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}"); + assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}"); + // A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends. + let mut rect = BezPath::new(); + rect.move_to((0.0, 0.0)); + rect.line_to((100.0, 0.0)); + rect.line_to((100.0, 60.0)); + rect.line_to((0.0, 60.0)); + rect.close_path(); + for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] { + for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] { + for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] { + let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max)); + let out = stroke_pieces(&doc, &b, bp, &ramp); + assert!(!out.is_empty(), "{fit:?} {scale} {max}"); + let r = bounds(&out); + assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}"); + } + } + } + // On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller + // than the last one's. + let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0)); + let out = stroke_pieces(&doc, &b, &rect, &ramp); + let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp); + assert_ne!(out, fixed); + let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height())); + let corners: Vec = out.iter().take(4).map(corner).collect(); + assert!(corners[0] < corners[3], "{corners:?}"); + // The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the + // first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile. + let first_side = out.get(4).and_then(Node::geometric_bounds); + assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}"); +} + +/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at +/// its middle, even when the scale rises again further along and the tile would not fit at the +/// whole run's length. +#[test] +fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + // From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end. + let q = 2.0 / 99.0; + for (start, points, span) in [ + (true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)), + (false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(6.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + // The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %. + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } + // 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt + // tile at 100 % fits at its middle, although at the scale at its first length's middle it is as + // long as that length. + for (start, points, span) in [ + (true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)), + (false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(30.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } +} + +/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale +/// recorded at the end of the stroke there, where the tile is drawn. +#[test] +fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0)); + // Light over the first 90 % of the stroke, heavy at its end. + let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]); + let mut before = 0; + for r in (100..=120).map(f64::from) { + // A circle of radius `r` as 720 sides, from (r, 0) on towards +y. + let mut bp = BezPath::new(); + bp.move_to((r, 0.0)); + for i in 1..720 { + let a = std::f64::consts::TAU * f64::from(i) / 720.0; + bp.line_to((r * a.cos(), r * a.sin())); + } + bp.close_path(); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") }; + if first.y0 < -0.5 { + // The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end. + before += 1; + assert!(first.x1 > r + 3.0, "{r}: {first:?}"); + } + } + assert!(before > 0, "no first tile starts before the path's start"); +} + +/// On a closed path, a tile over the path's start follows the scale on both sides of the start, +/// even when the scale is the same at the tile's ends, its middle and every pen sample within it. +#[test] +fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() { + let doc = Document::new(1.0, 1.0); + let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.side = rect_art(54.0, 4.0); + } + // A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter + // turn, and the same turned three more times. + let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)]; + let mut bp = BezPath::new(); + let mut at = (0.0, 0.0); + bp.move_to(at); + for turn in 0..4 { + for &(x, y) in &quarter { + let (dx, dy) = match turn { + 0 => (x, y), + 1 => (-y, x), + 2 => (-x, -y), + _ => (y, -x), + }; + at = (at.0 + dx, at.1 + dy); + if at != (0.0, 0.0) { + bp.line_to(at); + } + } + } + bp.close_path(); + // 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five + // 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and + // the samples at 4 pt before the start and at the start, but larger from 4 pt before it. + let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") }; + // The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the + // start, where the scale is 250 %. + assert!(first.y0 < -3.5, "{first:?}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 7659c96330..7ffcb472ff 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -649,6 +649,253 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross) } +/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies +/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs +/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it +/// is too when the scale is the same at both ends of the span, at every sample within it and, at +/// a closed track's start within it, on both sides of the start. +fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { + let mid = k((s0 + s1) / 2.0); + // Only the samples within the span are looked at. + let within = |marks: &[f64]| { + let from = marks.partition_point(|&s| s <= s0); + let to = from + marks[from..].partition_point(|&s| s < s1); + marks[from..to].iter().all(|&s| k(s) == mid) + }; + // A closed track's scale goes from the one at its end to the one at its start where it wraps + // round, so a span over its start (or a track's length before or after it) takes both. + let l = t.len(); + let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor(); + let ends = || !seam || (k(0.0) == mid && k(l) == mid); + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends(); + if mid <= 0.0 || marks.is_none_or(even) { + return tile_on(t, tile, s0, s1, mid); + } + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid) +} + +/// The most side tiles a run of a pattern brush places. +const MAX_TILES: usize = 20000; + +/// How many times a pattern brush whose scale varies measures its side tiles again where the fit +/// puts them. +const REFITS: usize = 3; + +/// How many times a pattern brush whose scale varies halves the range a start or end tile's +/// length lies in. +const END_SOLVE_STEPS: usize = 48; + +/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end +/// tile before it halves the range the tile's length lies in. +const END_SCAN_STEPS: usize = 64; + +/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along +/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and +/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include +/// that next one when there is room for part of it. +fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) { + let mut tiles = vec![]; + let mut pos = 0.0; + while tiles.len() < MAX_TILES { + let (w, g) = natural(a + pos); + if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) { + break; + } + tiles.push((w, g)); + if pos + w > avail { + let whole = (tiles.len() - 1) as f64; + return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0)); + } + pos += w + g; + } + let whole = tiles.len() as f64; + (tiles, whole) +} + +/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p` +/// (0 at the first scale, 1 at the second). +fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 { + let (light, heavy) = pb.scale_range(); + weight * (light + (heavy - light) * p).max(1.0) / 100.0 +} + +/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke. +/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that +/// input's missing value gives. +fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) { + let (light, heavy) = pb.scale_range(); + match pb.scale_mode { + Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true), + Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false), + _ => (weight * pb.scale.max(1.0) / 100.0, false), + } +} + +/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at +/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at +/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are +/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded +/// pen sample), and the range between the last one the tile is too long for and the first one it +/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`, +/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and +/// the tile then takes its length at that scale. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 { + let length = |w: f64| width * k_mid(w); + let first = length(0.0); + let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else { + return first; + }; + let mut tries: Vec = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect(); + tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room)); + tries.sort_by(f64::total_cmp); + let Some(i) = tries.iter().position(|&w| length(w) <= w) else { + return length(room); + }; + let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]); + for _ in 0..END_SOLVE_STEPS { + let mid = (short + long) / 2.0; + if length(mid) > mid { + short = mid; + } else { + long = mid; + } + } + long +} + +/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its +/// arc length, and again a track's length before and after it, for tiles of a closed track that +/// wrap round, in order. +fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { + let points = match mode { + Variation::Fixed | Variation::Random => None, + Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points), + Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points), + Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points), + Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), + Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), + }; + let mut marks: Vec = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect(); + marks.sort_by(f64::total_cmp); + marks +} + +/// Whether `stroke` recorded the pen input `mode` follows. +fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool { + match mode { + Variation::Fixed | Variation::Random => false, + Variation::Pressure => stroke.pressure.is_some(), + Variation::Tilt => stroke.tilt.is_some(), + Variation::Bearing => stroke.bearing.is_some(), + Variation::Rotation => stroke.rotation.is_some(), + Variation::StylusWheel => stroke.wheel.is_some(), + } +} + +/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they +/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between +/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to +/// `avail`. An added tile is +/// `natural(s)` long at `s` from the run's start. +fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) { + let mut length: f64 = tiles.iter().map(|t| t.0).sum(); + let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + // How much of the run the tiles and the spacing between them take. + let run = |length: f64, gaps: f64| length + gaps; + while let [.., (_, before), (w, _)] = tiles.as_slice() { + let (w, before) = (*w, *before); + let (now, without) = (run(length, gaps), run(length - w, gaps - before)); + let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() }; + if !drop { + break; + } + tiles.pop(); + length -= w; + gaps -= before; + } + while tiles.len() < MAX_TILES { + let last_gap = tiles.last().map_or(0.0, |t| t.1); + let now = run(length, gaps); + let (w, g) = natural(run(length, gaps + last_gap)); + if w.is_nan() || w <= 1e-9 { + break; + } + let with = run(length + w, gaps + last_gap); + let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() }; + if !add { + break; + } + tiles.push((w, g)); + length += w; + gaps += last_gap; + } +} + +/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as +/// [`tile_scaled`] takes them), at the scale `k(s)` at +/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps +/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles +/// (around a lone tile), and Approximate keeps both and centers the tiles on the run. +fn varied_side_tiles( + out: &mut Budget, + t: &Track, + pb: &PatternBrush, + side: &(Node, Rect), + (a, avail): (f64, f64), + k: &dyn Fn(f64) -> f64, + marks: &[f64], +) { + let tw = side.1.width(); + // Each side tile and the gap after it as long as the scale at the tile's middle. + let natural = |s: f64| { + let w = tw * k(s + tw * k(s) / 2.0); + (w, w * pb.spacing.max(0.0) / 100.0) + }; + let (tiles, count) = varied_tiles(a, avail, &natural); + let n = match pb.fit { + PatternFit::AddSpace => count.floor(), + PatternFit::Stretch | PatternFit::Approximate => count.round(), + } + .max(1.0) as usize; + let mut tiles = tiles[..n.min(tiles.len())].to_vec(); + // How far the fit stretches the tiles and gaps, where the first tile starts, and the space + // between tiles when the fit sets it. + let fitted = |tiles: &[(f64, f64)]| { + let length: f64 = tiles.iter().map(|t| t.0).sum(); + // The gaps between the tiles: after every tile but the last. + let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + match pb.fit { + PatternFit::Stretch => (avail / (length + gaps), 0.0, None), + PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))), + PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None), + PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None), + } + }; + // The fit moves the tiles from where they were measured, so each is measured again at the + // middle of where the fit puts it, and the fit worked out again, a few times over. + for _ in 0..REFITS { + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for tile in &mut tiles { + let placed = tile.0 * stretch; + let w = tw * k(s0 + placed / 2.0); + s0 += placed + space.unwrap_or(tile.1 * stretch); + *tile = (w, w * pb.spacing.max(0.0) / 100.0); + } + recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s)); + } + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for &(w, g) in &tiles { + let w = w * stretch; + out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks))); + if out.full() { + break; + } + s0 += w + space.unwrap_or(g * stretch); + } +} + /// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what /// [`CornerSource`] gives. #[derive(Clone, Copy)] @@ -803,10 +1050,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true })) } -pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { +/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt, +/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives +/// (half way without a recording), each tile and the gap after it as long as the scale at its +/// middle, and each corner tile at the scale at its corner. +pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec { let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; - let k = weight * pb.scale.max(1.0) / 100.0; + let scale_at = |p: f64| pattern_scale_at(pb, weight, p); + let (k, varies) = pattern_scale(pb, weight, stroke); let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); @@ -825,6 +1077,17 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if l <= 1e-9 { continue; } + // The scale at arc length `s` of the track; on a closed track a point before its start or + // past its end wraps round as `Track::frame` places it (its end itself keeps the scale at + // the end), and on an open track a point past either end takes the scale at that end. + let ks = |s: f64| { + if !varies { + return k; + } + let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) }; + scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5)) + }; + let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l)); let corners = t.corner_positions(); // Corner tiles, centred on the corner and turned to the bisector. The path on each side of // a corner is shortened by `trims` (`None`: half the widest corner tile art). @@ -848,17 +1111,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec }; before.min(after) }; - for (ci, &(i, _)) in corners.iter().enumerate() { + for (ci, &(i, at)) in corners.iter().enumerate() { if out.full() { break; } + let kc = ks(at); let (a, b) = t.in_out(i); // Turning towards the left normal puts the tile's +y side on the inside. let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) }; let (art, bb) = match tile { Some(Corner::Art(tile)) => tile, Some(Corner::Source(source)) => { - let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci)); + let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci)); for n in pieces { out.take(Some(n)); } @@ -870,8 +1134,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec continue; } }; - trims.push(None); - corner_half = corner_half.max(bb.width() * k / 2.0); + // With a scale that varies, each corner's tile is its own size, so the path beside it + // is shortened by half of that tile. + trims.push(varies.then_some(bb.width() * kc / 2.0)); + corner_half = corner_half.max(bb.width() * kc / 2.0); // Inner and outer corner art is the corner that joins a side tile on its right to one // below it, so its arms point along +x and +y (as the flips leave them). The tile is // turned so that the line halving its arms lies on the line halving the sides at the @@ -881,7 +1147,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 }); let sides = b - a; let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x); - let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2()); + let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2()); let mut n = art.clone(); n.transform(xf, true); out.take(Some(n)); @@ -914,9 +1180,11 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri == 0 && let Some(st) = &start { - let w = st.1.width() * k; + // As long as the scale at its middle. + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect()); + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref()); if b - a > w { - out.take(tile_on(&t, st, a, a + w, k)); + out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; } } @@ -924,9 +1192,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri + 1 == nruns && let Some(en) = &end { - let w = en.1.width() * k; + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect()); + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref()); if b - a > w { - out.take(tile_on(&t, en, b - w, b, k)); + out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; } } @@ -934,6 +1203,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if avail <= 1e-6 { continue; } + if let Some(marks) = &marks { + varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks); + continue; + } let unit = tw + gap; match pb.fit { PatternFit::Stretch => { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 960d0cce1a..3828d67d0c 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off), saturation_jitter 0..100% (each copy moves the saturation of its solid colors, after the colorization and the hue jitter, by its own amount up to this many points either way, keeping their hue and brightness, the same on every redraw; colors without a hue stay; 0: off), brightness_jitter 0..100% (each copy moves the brightness of its solid colors, after the colorization and the hue and saturation jitter, by its own amount up to this many points either way, keeping their hue and saturation, the same on every redraw; white, black and grays move too; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization, hue_jitter, saturation_jitter, brightness_jitter; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b6ab619d55..af71b2dae9 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -583,7 +583,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result merged.insert(k.clone(), next); } keep_drawn_modes(b, &was, ¶ms, &mut merged); - keep_largest_width(b, &was, ¶ms, &mut merged); + keep_second_value(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -646,27 +646,34 @@ fn keep_drawn_modes( merged.insert("modes".into(), Value::Array(kept)); } -/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when -/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is -/// the width, so without this a changed width would also change the largest width. -fn keep_largest_width( +/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when +/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern +/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the +/// first, so without this a changed first value would also change the second. +fn keep_second_value( b: &Brush, was: &serde_json::Map, params: &serde_json::Map, merged: &mut serde_json::Map, ) { - if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + let (first, second) = match b.kind { + BrushKind::Art(_) => ("width", "width_max"), + BrushKind::Pattern(_) => ("scale", "scale_max"), + _ => return, + }; + if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) { return; } - let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { - Some(BrushKind::Art(a)) => Some(a), + // The first value, the second value of its own, and whether the value follows the pen. + let values = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))), + Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))), _ => None, }; - let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; - let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); - // Only a width that followed the pen has a largest width, and only one that still does uses it. - if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { - merged.insert("width_max".into(), json!(before.width)); + let (Some(before), Some(after)) = (values(was), values(merged)) else { return }; + // Only a value that followed the pen has a second value, and only one that still does uses it. + if before.1.is_none() && before.2 && after.2 && after.0 != before.0 { + merged.insert(second.into(), json!(before.0)); } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index f2c77a1b4d..032e3ddb8c 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); } +/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0 +/// and 1. +fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Stitches").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(), + k => panic!("not a pattern brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap(); + // Both scales follow the pressure; the first path's second scale is its scale, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The scale the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new first scale leaves each path's second scale as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A second scale the params give is set on each path, and the brush keeps its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); + let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + // A mode that is not one is refused, and nothing changes. + let steps = undo_steps(&s); + assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err()); + assert_eq!(undo_steps(&s), steps); +} + +/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options` +/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out. +#[test] +fn pattern_brush_scale_mode_goes_through_the_brush_commands() { + let mut s = session(); + let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0); + let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300}); + s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap(); + let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap(); + let def = get(&mut s); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err()); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index df482dc13b..1d6f6cc6f4 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1132,13 +1132,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 9d6fe2e887..828aff4e01 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -440,7 +440,8 @@ impl Tool for BrushPaintTool { } /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values - /// differ, or an Art brush whose width is on it with two different widths. + /// differ, an Art brush whose width is on it with two different widths, or a Pattern brush + /// whose scale is on it with two different scales. fn reads_wheel(&self, cx: &ToolContext) -> bool { use vectorcraft_brush::{BrushKind, Variation}; let wheel = |mode: Variation| mode == Variation::StylusWheel; @@ -449,7 +450,8 @@ impl Tool for BrushPaintTool { BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, - BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + BrushKind::Pattern(p) => p.scale_mode.is_some_and(wheel) && p.scale_range().0 != p.scale_range().1, + BrushKind::Bristle(_) => false, } } fn busy(&self) -> bool { @@ -775,7 +777,7 @@ mod tests { #[test] fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { - use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, PatternBrush, Scatter, Variation}; let wheel = Variation::StylusWheel; let calligraphic = |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); @@ -783,6 +785,7 @@ mod tests { BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) }; let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let pattern = |scale_mode, scale_max| BrushKind::Pattern(PatternBrush { scale_mode, scale_max: Some(scale_max), ..PatternBrush::default() }); let library = [ Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, @@ -792,6 +795,9 @@ mod tests { Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, Brush { name: "Flat".into(), kind: art(None, 200.0) }, + Brush { name: "Tiles".into(), kind: pattern(Some(wheel), 200.0) }, + Brush { name: "Even tiles".into(), kind: pattern(Some(wheel), 100.0) }, + Brush { name: "Fixed tiles".into(), kind: pattern(None, 200.0) }, ]; let (mut d, _) = doc_with_rect(); d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); @@ -808,6 +814,9 @@ mod tests { ("Taper", true), ("Even taper", false), ("Flat", false), + ("Tiles", true), + ("Even tiles", false), + ("Fixed tiles", false), ("Deleted", false), ]; for (name, varies) in brushes { diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index dc209b1ec8..af0a306d8c 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -14,7 +14,9 @@ //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, //! `overlap` (bend on each run between sharp corners). -//! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, +//! Pattern: `scale`, `scaleMax` (the scale at the heaviest pen pressure, upright, at 180° or at +//! the wheel's far end, %), `scaleMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation` | +//! `stylusWheel`), `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, //! `flipAcross`, and the tiles `outerCornerTile`, `sideTile`, `innerCornerTile`, `startTile` and //! `endTile` (`original`: the art the brush draws there | `none` | `pattern:` | for a //! corner `autoCentered` | `autoBetween` | `autoSliced` | `autoOverlap`: a tile made from the side @@ -41,7 +43,7 @@ use craft::ui::primitives::IconSpec; use craft::ui::runtime::env::UnitKind; use craft::ui::runtime::requests::EyedropperRequest; use craft::ui::text::NumberField; -use craft::ui::value_drag::{Slider, SliderScale}; +use craft::ui::value_drag::Slider; use egui::{Color32, ColorImage, Response, Ui}; use serde_json::{Map, Value, json}; use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization, CornerSource, Direction, PatternBrush, PatternFit, Scatter, Variation}; @@ -225,6 +227,8 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { } BrushKind::Pattern(p) => { f.insert("scale".into(), json!(p.scale)); + f.insert("scaleMode".into(), json!(p.scale_mode.unwrap_or_default().id())); + f.insert("scaleMax".into(), json!(p.scale_range().1)); f.insert("spacing".into(), json!(p.spacing)); f.insert("fit".into(), json!(id_of(&p.fit))); f.insert("flipAlong".into(), json!(p.flip_along)); @@ -284,6 +288,66 @@ fn art_width_mode(f: &DialogFields) -> Variation { Variation::parse(&text(f, "widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } +/// How a pattern brush's scale varies: Fixed, or with the pen's pressure, tilt, bearing, rotation +/// or wheel. +fn pattern_scale_mode(f: &DialogFields) -> Variation { + Variation::parse(&text(f, "scaleMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) +} + +/// The second value (`max_key`, the definition's `def_max`) of a value that follows the pen (`key`, +/// the same in the definition), for `brush.options` params. `null` in Options of Selected Object +/// when the path it opened with has no second value and the second value has not been changed from +/// the value it opened with, so each selected path keeps its own. +fn second_value(f: &DialogFields, (key, max_key, def_max): (&str, &str, &str), range: (f64, f64)) -> Value { + let v = clamped(f, max_key, range); + let def = json_field(f, "__def"); + let opened = def.and_then(|def| def.get(key)).and_then(Value::as_f64); + let unset = def.and_then(|def| def.get(def_max)).is_none_or(Value::is_null); + let object = f.bool(super::brush_options::OBJECT).unwrap_or(false); + if object && unset && opened == Some(v) { Value::Null } else { json!(v) } +} + +/// The modes an art brush's width and a pattern brush's scale offer, in menu order. +const PEN_SIZE_MODES: [Variation; 6] = + [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + +/// A value that can follow the pen (an art brush's Width, a pattern brush's Scale): its field and +/// the fields of its second value and its [`PEN_SIZE_MODES`] menu. +struct PenSize { + key: &'static str, + max_key: &'static str, + mode_key: &'static str, + /// The row's label and the name of its slider. + label: &'static str, + /// The names of the second value's field and of the menu. + max_label: &'static str, + mode_label: &'static str, + range: (f64, f64), + mode: fn(&DialogFields) -> Variation, +} + +/// The row of `size`: a slider, the second value (live only for a mode that follows the pen) and +/// how the value varies. +fn pen_size_row(size: PenSize) -> Param { + let PenSize { key, max_key, mode_key, label, max_label, mode_label, range, mode } = size; + Param::custom(key, label, move |ui, f, _| { + let mode = mode(f); + let entries = variation_entries(&PEN_SIZE_MODES); + Row::new() + .show(ui, |ui, _| { + let slid = Slider::new(Bind::given(clamped(f, key, range)), range.0..=range.1).step(1.0).label(label).id_salt(key).show(ui); + if let Some(value) = slid.events.landed() { + // The slider quantizes new edits; Cancel restores the exact opening value. + f.set(key, *value); + } + number_cell(ui, f, max_key, max_label, range, UnitKind::Percent, mode.follows_pen()); + id_select(ui, f, mode_key, mode_label, &entries, mode.id().to_string()); + }) + .output + }) + .companions([max_key, mode_key]) +} + /// `brush.options` params from the fields. pub(super) fn params(f: &DialogFields) -> Value { let flag = |key: &str| f.bool(key).unwrap_or(false); @@ -313,7 +377,7 @@ pub(super) fn params(f: &DialogFields) -> Value { json!({ "width": clamped(f, "width", ArtBrush::WIDTH_RANGE), "width_mode": if pen { json!(mode.id()) } else { Value::Null }, - "width_max": if pen { json!(clamped(f, "widthMax", ArtBrush::WIDTH_RANGE)) } else { Value::Null }, + "width_max": if pen { second_value(f, ("width", "widthMax", "width_max"), ArtBrush::WIDTH_RANGE) } else { Value::Null }, "scale": serde_json::to_value(scale).unwrap_or_default(), "direction": id_of(&parse_field::(f, "direction")), "flip_along": flag("flipAlong"), @@ -322,8 +386,12 @@ pub(super) fn params(f: &DialogFields) -> Value { }) } _ => { + let mode = pattern_scale_mode(f); + let pen = mode.follows_pen(); let mut p = json!({ "scale": clamped(f, "scale", PatternBrush::SCALE_RANGE), + "scale_mode": if pen { json!(mode.id()) } else { Value::Null }, + "scale_max": if pen { second_value(f, ("scale", "scaleMax", "scale_max"), PatternBrush::SCALE_RANGE) } else { Value::Null }, "spacing": clamped(f, "spacing", PatternBrush::SPACING_RANGE), "fit": id_of(&parse_field::(f, "fit")), "flip_along": flag("flipAlong"), @@ -500,26 +568,16 @@ fn check(key: &str, label: &'static str) -> Param { fn art_rows(object: bool) -> Vec { // Width, then the second width (only when the width follows the pen) and how it varies. - let range = ArtBrush::WIDTH_RANGE; - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; - let width = Param::custom("width", tl!("Width"), move |ui, f, _| { - let mode = art_width_mode(f); - let entries = variation_entries(&modes); - Row::new() - .show(ui, |ui, _| { - let slid = - Slider::new(Bind::given(clamped(f, "width", range)), range.0..=range.1).step(1.0).label(tl!("Width")).id_salt("width").show(ui); - if let Some(value) = slid.events.landed() { - // The slider quantizes new edits; Cancel restores the exact opening width. - f.set("width", *value); - } - number_cell(ui, f, "widthMax", tl!("Width"), range, UnitKind::Percent, mode.follows_pen()); - id_select(ui, f, "widthMode", tl!("Width"), &entries, mode.id().to_string()); - }) - .output - }) - .companions(["widthMax", "widthMode"]); - let mut rows = vec![width]; + let mut rows = vec![pen_size_row(PenSize { + key: "width", + max_key: "widthMax", + mode_key: "widthMode", + label: tl!("Width"), + max_label: tl!("Width: Maximum"), + mode_label: tl!("Width: Mode"), + range: ArtBrush::WIDTH_RANGE, + mode: art_width_mode, + })]; // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. if !object { let scales = vec![ @@ -558,8 +616,17 @@ fn direction_row() -> Param { } fn pattern_rows(object: bool) -> Vec { - let (lo, hi) = PatternBrush::SCALE_RANGE; - let mut rows = vec![Param::new("scale", tl!("Scale"), ParamKind::range(lo, hi, 100.0, SliderScale::Linear)).unit(UnitKind::Percent)]; + // Scale, then the second scale (only when the scale follows the pen) and how it varies. + let mut rows = vec![pen_size_row(PenSize { + key: "scale", + max_key: "scaleMax", + mode_key: "scaleMode", + label: tl!("Scale"), + max_label: tl!("Scale: Maximum"), + mode_label: tl!("Scale: Mode"), + range: PatternBrush::SCALE_RANGE, + mode: pattern_scale_mode, + })]; let (lo, hi) = PatternBrush::SPACING_RANGE; rows.push(Param::number("spacing", tl!("Spacing"), 0.0, 1.0, 0).bounds(Some(lo), Some(hi)).unit(UnitKind::Percent)); // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 608df2843a..0daecbd7c7 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -188,7 +188,7 @@ fn canceled_art_width_drag_restores_the_opening_width() { let initial = fields_of(&panel.app()).number("width").unwrap(); assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored width"); let mode = fields_of(&panel.app()).text("widthMode").map(str::to_owned); - panel.click_role("Width", Role::COMBO_BOX); + panel.click_role("Width: Mode", Role::COMBO_BOX); panel.key(Key::ArrowDown, Modifiers::NONE); panel.key(Key::Escape, Modifiers::NONE); assert_eq!(fields_of(&panel.app()).text("widthMode").map(str::to_owned), mode); @@ -216,6 +216,56 @@ fn canceled_art_width_drag_restores_the_opening_width() { assert_eq!(panel.app().run("brush.get", json!({"name": "Arrow"})).unwrap(), original); } +/// Pattern Brush Options' Scale row: a held drag ended with Escape and a mode menu closed with +/// Escape leave the open dialog's fields as they opened, and Cancel leaves the brush as it was; a +/// released drag is kept by OK. +#[test] +fn canceled_pattern_scale_edits_do_not_reach_the_brush() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = app(); + app.run("brush.options", json!({"name": "Diamonds", "params": {"scale": 100.25}})).unwrap(); + let original = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw_hosted_options); + panel.room(egui::vec2(1000.0, 1000.0)); + open(&mut panel.app(), "Diamonds"); + panel.frame(); + let initial = fields_of(&panel.app()).number("scale").unwrap(); + assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored scale"); + let mode = fields_of(&panel.app()).text("scaleMode").map(str::to_owned); + panel.click_role("Scale: Mode", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app())); + assert_eq!(fields_of(&panel.app()).text("scaleMode").map(str::to_owned), mode); + panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0)); + assert_ne!(fields_of(&panel.app()).number("scale"), Some(initial), "the held drag previews another scale"); + panel.key(Key::Escape, Modifiers::NONE); + panel.release(); + assert!(is_open(&panel.app())); + assert_eq!(fields_of(&panel.app()).number("scale"), Some(initial), "the canceled drag restores the opening scale"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + open(&mut panel.app(), "Diamonds"); + panel.frame(); + panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0)); + panel.release(); + let accepted = fields_of(&panel.app()).number("scale").unwrap(); + assert_ne!(accepted, initial); + panel.click("OK"); + panel.frame(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale"], accepted); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original); +} + /// What a step of the table expects at a JSON pointer of the saved brush. enum Expect { Is(Value), @@ -410,6 +460,70 @@ fn ok_redraws_the_strokes_painted_with_the_brush() { assert!((drawn_height(&app, id) - before).abs() < 1e-6); } +/// The names screen readers read in the open dialogs, from the access tree of an app frame drawn +/// once the dialog has settled. +fn access_names(app: &mut VectorcraftApp) -> Vec { + crate::dialogs::tests::settle(app); + let out = crate::dialogs::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_string).collect() +} + +/// Pattern Brush Options' Scale menu: Pressure, Tilt, Bearing, Rotation and Stylus Wheel each take +/// a second scale, a stroke drawn without the pen's input is half way between the two, and the +/// dialog shows the mode set when it opens again; Fixed drops the second scale. +#[test] +fn pattern_options_scale_follows_the_pen() { + let mut app = app(); + let (id, before) = brushed(&mut app, "Diamonds"); + open(&mut app, "Diamonds"); + let f = fields_of(&app); + assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some("fixed"), Some(100.0))); + // Screen readers name the second scale and the menu after the Scale row. + let names = access_names(&mut app); + for name in ["Scale: Maximum", "Scale: Mode"] { + assert!(names.iter().any(|n| n == name), "{name} in {names:?}"); + } + cancel(&mut app); + for mode in ["pressure", "tilt", "bearing", "rotation", "stylusWheel"] { + open(&mut app, "Diamonds"); + set(&mut app, json!({"scaleMode": mode, "scaleMax": 300})); + confirm(&mut app).unwrap_or_else(|error| panic!("{mode}: {error}")); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(100.0), &json!(mode), &json!(300.0)), "{mode}"); + // A stroke drawn without the pen's input is half way: 200 %. + let after = drawn_height(&app, id); + assert!((after - 2.0 * before).abs() < 0.01 * before, "{mode}: {before} then {after}"); + open(&mut app, "Diamonds"); + let f = fields_of(&app); + assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some(mode), Some(300.0)), "{mode}"); + cancel(&mut app); + } + // A second scale past the range is kept within it. + open(&mut app, "Diamonds"); + set(&mut app, json!({"scaleMode": "pressure", "scaleMax": 1e9})); + confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale_max"], json!(10000.0)); + // Fixed drops the second scale, and the stroke draws as it did. + open(&mut app, "Diamonds"); + set(&mut app, json!({"scaleMode": "fixed"})); + confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!((drawn_height(&app, id) - before).abs() < 1e-6); +} + +/// Art Brush Options names its second width and its menu after the Width row. +#[test] +fn art_options_name_the_second_width_and_its_menu() { + let mut app = app(); + open(&mut app, "Tapered Stroke"); + let names = access_names(&mut app); + for name in ["Width: Maximum", "Width: Mode"] { + assert!(names.iter().any(|n| n == name), "{name} in {names:?}"); + } +} + /// Art Brush Options draws each Direction segment as an arrow icon named by its tooltip, so the /// accessibility tree reads the direction instead of an arrow glyph. #[test] @@ -904,6 +1018,46 @@ fn options_of_selected_object_set_one_paths_art_brush_settings() { assert_eq!(own_options(&app, a), json!({"width": 50.0})); } +/// Options of Selected Object for a pattern brush sets one path's Scale mode and second scale; the +/// brush and the other path keep theirs. +#[test] +fn options_of_selected_object_set_one_paths_pattern_scale_mode() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Diamonds"); + let b = brushed_line(&mut app, 100.0, "Diamonds"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scaleMode": "tilt", "scaleMax": 250})); + confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale_mode": "tilt", "scale_max": 250.0})); + assert_eq!(own_options(&app, b), json!({})); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none(), "{def}"); + // Opened again, it shows the path's own mode and second scale. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let f = fields_of(&app); + assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some("tilt"), Some(250.0))); + cancel(&mut app); + // With paths of different scales selected, choosing a mode alone leaves each path's scale and + // second scale its own: the first path's scale is not given to the second path as its second + // scale. + app.run("brush.objectOptions", json!({"ids": [a], "params": {"scale": 50, "scale_mode": null, "scale_max": null}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"scale": 80}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scaleMode": "pressure"})); + confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 50.0, "scale_mode": "pressure"})); + assert_eq!(own_options(&app, b), json!({"scale": 80.0, "scale_mode": "pressure"})); + // A changed Scale alone keeps each path's own second scale: its old scale. + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scale": 60})); + confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 50.0})); + assert_eq!(own_options(&app, b), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 80.0})); +} + /// Options of Selected Object shows a scatter path's hue, saturation and brightness jitter, and OK /// sets them on that path only. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5e866c34bd..028283b027 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1133,13 +1133,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°, saturationJitter 0..100%, brightnessJitter 0..100%), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 37eae066c5..0c3a73b8cc 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -22,7 +22,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | | Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | -| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Pattern and Bristle brushes do not use them (an Art brush's Width follows them); 3–6 h (#372) | +| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | | Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | diff --git a/docs/mcp.md b/docs/mcp.md index ac8c849136..2b989af8c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4943,13 +4943,15 @@ already walks Image Trace. Short agent entry points: level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` (counter-clockwise), `modes`, `rotation_relative_to_path`, `colorization`, `hue_jitter`, `saturation_jitter` and `brightness_jitter`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, - `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + `overlap` and `colorization`; pattern `scale`, `scale_mode`, `scale_max`, `spacing`, `fit`, `flip_along`, + `flip_across` and `colorization`. Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + a pattern `scale` without a `scale_max` (omitted or `null`) keeps the second scale of each path whose scale follows the pen, and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different @@ -4988,6 +4990,19 @@ already walks Image Trace. Short agent entry points: uses the wheel (the Paintbrush with a brush on Stylus Wheel whose range the wheel can change, or the Blob Brush or the Eraser with a value on it and a variation above 0), so there a Paintbrush stroke drawn with another brush keeps no wheel. The web build does not read it. `.ai` brush definitions read and write the wheel as variation code 3. +- Pattern brush scale from the pen: a pattern brush's `scale_mode` (`brush.new`, `brush.options`, + `brush.objectOptions`; `null` for Fixed) takes `pressure`, `tilt`, `bearing`, `rotation` and + `stylusWheel`, and `scale_max` (1..10000%) is the second scale. `brush.new` without a `scale_mode` makes a + Fixed brush; `brush.options` without one keeps the brush's mode, and `brush.objectOptions` without one keeps + each path's mode. The tiles go from `scale` where the pen reads 0 to + `scale_max` where it reads 1, over the ranges an Art brush's `width_mode` uses, and half way on a stroke drawn + without that input; without a `scale_max` both ends are `scale`. Each side, start and end tile is as tall as the + scale at each point of the stroke, and the tile and the gap after it are as long as the scale at the tile's + middle. A corner tile takes the scale at its corner. Stretch to Fit then stretches the tiles and gaps of each run + to fill it, Add Space to Fit shares the space left between the tiles, and Approximate Path centers the tiles on + the run. Another mode, such as `random`, is read as Fixed. A brush with a fixed scale draws as before, and a + brush or stroke without the new fields saves without them. `.ai` files do not read or write the pattern scale's + mode. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ead5db22ed..ca6e91253b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -343,7 +343,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -615,7 +615,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -2206,7 +2206,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2216,6 +2216,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). + Pattern Brush Options' Scale has a menu of Fixed, Pressure, Tilt, Bearing, Rotation and Stylus Wheel with a second scale beside it, in the library brush's dialog and in Options of Selected Object, from the pen tablet options the Pattern brush options section of the help page (, archived copy) lists for Scale (`brush.options` and `brush.objectOptions` `scale_mode` and `scale_max`). The tiles go from Scale where the pen reads 0 to the second scale where it reads 1, over the same ranges as Art Brush Options' Width, and half way on a stroke without that input. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile is as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit stretches the tiles and gaps of each run to fill it, Add Space to Fit shares out what is left between the tiles, and Approximate Path centers them on the run. The help page does not say how the pen maps to the scale or how the tiles are measured along the stroke, so those rules are VectorCraft's own. A brush with a fixed scale draws as before. `.ai` files do not read or write the pattern scale's mode, and the Width tool does not turn the pen's data into width points. Evidence: `tests::pattern_brush_scale_follows_the_pressure`, `tests::pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel`, `tests::pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles` (vectorcraft-brush), `tests::brushsym::options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes`, `tests::brushsym::pattern_brush_scale_mode_goes_through_the_brush_commands` (vectorcraft-engine), `dialogs::brush_options::tests::pattern_options_scale_follows_the_pen`, `dialogs::brush_options::tests::options_of_selected_object_set_one_paths_pattern_scale_mode` (vectorcraft-ui-egui). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, on macOS from AppKit's `tangentialPressure`, and in the web build from Pointer Events' `tangentialPressure` (), for each move of a pen including the positions a fast stroke's events coalesce. Windows pointer messages have no field for it, so on Windows the app reads it from the tablet driver's Wintab interface, as the tangential pressure (`pkTangentPressure`) of a cursor the driver reports as an airbrush, placed within its device's `DVC_TPRESSURE` range (, ). `Wintab32.dll` is loaded from the system directory only; without it, or when a call fails, Windows pens read no wheel and draw as before. The library is loaded and the context opened only while the active tool uses the wheel (the Paintbrush with a brush on Stylus Wheel, or the Blob Brush or the Eraser with a value on it), and the context closes when it stops; this is VectorCraft's own rule. A pen first reads the wheel from an airbrush packet that came within 200 ms of one of its pointer messages, and from none when packets of two tablets' cursors both did or neither did. That pen then holds the readings: its later messages take that airbrush's last wheel, even when the pen has been held still, no packet has come for longer, or another tablet's cursor has been read since, and other pens read no wheel until the readings start afresh (the pen leaves or turns to its other end, or a cursor comes near, leaves or changes). 0 counts as no wheel until the pen has reported another value since it came near, as on macOS and in the web build; the web build reads the wheel afresh for another pen, the other end, a canceled press and a pen that left the hover range. These are VectorCraft's own rules. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed`, `windows_stylus::tests::an_airbrush_wheel_goes_into_the_sample`, `windows_wintab::tests::a_pen_message_takes_the_wheel_of_the_recent_airbrush` and `windows_wintab::tests::the_driver_is_left_alone_until_the_wheel_is_used` (vectorcraft), `pencil::tests::an_airbrush_wheel_goes_into_the_feed`, `pencil::tests::coalesced_moves_keep_their_wheel` and `pencil::tests::the_wheel_is_read_afresh_for_each_pen_and_end` (vectorcraft-web), `symbolism::tests::the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush` (vectorcraft-tools) and `stylus::tests::the_host_is_told_when_the_tool_starts_and_stops_reading_the_wheel` (vectorcraft-ui-egui). - **Blob Brush Size on the stylus wheel:** Blob Brush Tool Options' Size menu offers Stylus Wheel beside Fixed and Pressure. The Blob Brush paints with the Calligraphic brush options ([help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=273)), whose Size an airbrush pen's wheel can vary ([help page](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html)), and the Eraser's Size menu offers the same wheel choice ([help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html)). With Stylus Wheel a stroke is Size − Variation wide at one end of the wheel's travel, but at least 0.1 pt, and Size + Variation at the other; a point without a wheel counts as half way, and a mouse stroke keeps the Size. A stroke whose points all lie at one place paints one dab sized from its first reading, on Pressure too. While the Blob Brush paints, the tip outline at the pointer takes the size the pen gives, on Pressure too, and keeps the Size when the menu changes to Stylus Wheel during the drag, or to Pressure during a drag that started on Fixed, as the release paints. A drag that started on Stylus Wheel records the pen pressure, so a change to Pressure follows that pressure from the start of the drag when the pen pressed less than fully anywhere. The direction of travel and the half-way value are VectorCraft's own rules. `path.blob` takes `sizeMode: "stylusWheel"` with the wheel seventh in each point. Evidence: `tests::draw2::blob_brush_size_follows_the_stylus_wheel` (vectorcraft-engine), `draw2::gesture::tests::the_blob_brush_size_follows_the_stylus_wheel` (vectorcraft-tools), `dialogs::freehand::tests::the_blob_brush_size_offers_the_stylus_wheel` (vectorcraft-ui-egui). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample.