diff --git a/apps/vectorcraft/src/mac_tablet.rs b/apps/vectorcraft/src/mac_tablet.rs index 1d9aabd442..ade798a393 100644 --- a/apps/vectorcraft/src/mac_tablet.rs +++ b/apps/vectorcraft/src/mac_tablet.rs @@ -1,4 +1,5 @@ -//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764). winit 0.30 +//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush +//! pen's finger wheel. winit 0.30 //! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit //! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas //! reads, as on X11 ([`crate::tablet`]). @@ -14,8 +15,9 @@ //! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the //! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read //! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation -//! from one held upright and unturned. Each reads as none until the pen reports a value other -//! than 0 after it comes near ([`Pen`]). +//! from one held upright and unturned. Its `tangentialPressure` (−1..1, an airbrush pen's finger +//! wheel) goes into the pose as the wheel, 0 for a pen without one as well. Each reads as none +//! until the pen reports a value other than 0 after it comes near ([`Pen`]). //! A mouse event of any other subtype is a mouse's or a trackpad's: the feed is set to `None`. //! - An `NSEventTypeTabletPoint` event carries the same pressure, tilt and rotation without a move. //! - A tablet proximity event (`NSEventTypeTabletProximity`, or a mouse event of that subtype) says @@ -68,6 +70,8 @@ struct RawEvent { tilt: (f64, f64), /// `rotation`, in degrees (the same events as `pressure`). rotation: f32, + /// `tangentialPressure`, −1..1 (the same events as `pressure`). + tangential: f32, /// `pointingDeviceType` (proximity events only). device: usize, /// `isEnteringProximity` (proximity events only). @@ -107,18 +111,42 @@ impl RawEvent { /// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the /// angle is negated and brought into 0..360. /// - /// The tilt is left out unless `tilts`, and the rotation unless `turns` ([`Pen`]). - fn pose(&self, tilts: bool, turns: bool) -> PenPose { + /// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the + /// devices that have one (). + /// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is + /// clamped. + /// + /// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel + /// unless `read.wheels` ([`Pen`]). + fn pose(&self, read: Reads) -> PenPose { let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32; // `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0. - let rotation = turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); - PenPose { tilt: tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation } + let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0)); + let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0); + PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel } } - /// Whether the event reports a tilt other than 0, and a rotation other than 0. - fn reads(&self) -> (bool, bool) { + /// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential + /// pressure other than 0. + fn reads(&self) -> Reads { let read = |v: f64| v.is_finite() && v != 0.0; - (read(self.tilt.0) || read(self.tilt.1), read(f64::from(self.rotation))) + Reads { tilts: read(self.tilt.0) || read(self.tilt.1), turns: read(f64::from(self.rotation)), wheels: read(f64::from(self.tangential)) } + } +} + +/// Which of a pen's tilt, rotation and finger wheel it has reported. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Reads { + tilts: bool, + turns: bool, + wheels: bool, +} + +impl Reads { + fn add(&mut self, other: Reads) { + self.tilts |= other.tilts; + self.turns |= other.turns; + self.wheels |= other.wheels; } } @@ -148,14 +176,14 @@ impl Update { } } -/// Which end of the pen is near the tablet, and whether it has reported a tilt or a rotation other -/// than 0 since it came near: until it has, its tilt or rotation reads as none, since AppKit gives -/// 0 for a pen without one and for one held upright or unturned. +/// Which end of the pen is near the tablet, and whether it has reported a tilt, a rotation or a +/// tangential pressure other than 0 since it came near: until it has, that value reads as none, +/// since AppKit gives 0 for a pen without one and for one held upright, unturned or with its +/// wheel half way. #[derive(Clone, Copy, Debug, Default, PartialEq)] struct Pen { eraser: bool, - tilts: bool, - turns: bool, + read: Reads, } impl Pen { @@ -163,16 +191,14 @@ impl Pen { if e.proximity() { // Entering with the tip or the eraser end: it hovers. A puck, or leaving, is a mouse. self.eraser = e.entering && e.device == device::ERASER; - (self.tilts, self.turns) = (false, false); + self.read = Reads::default(); let pen = e.entering && e.device != device::CURSOR; return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() })); } if e.point() { - let (tilts, turns) = e.reads(); - self.tilts |= tilts; - self.turns |= turns; + self.read.add(e.reads()); } - let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.tilts, self.turns) }; + let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) }; match (e.point(), e.mouse()) { (true, true) => Update::Move(sample), (true, false) => Update::Set(Some(sample)), @@ -246,6 +272,7 @@ mod monitor { let tilt = e.tilt(); raw.tilt = (tilt.x, tilt.y); raw.rotation = e.rotation(); + raw.tangential = e.tangentialPressure(); } if raw.proximity() { raw.device = e.pointingDeviceType().0; @@ -326,26 +353,44 @@ mod tests { let sample = |pressure, pose| PenSample { pressure, eraser: false, pose }; assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet"); let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) }; - let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0) }; + let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None }; assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose))); let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0) }; + let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None }; assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped"); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") }; assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned"); assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}"); let feed = StylusFeed::default(); p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed); - assert_eq!(feed.pose(), Some(PenPose { tilt: None, rotation: Some(90.0) }), "a tilt that is not a number is left out"); + assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out"); p.handle(&proximity(1, true)); let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) }; - let pose = PenPose { tilt: Some([0.0, 30.0]), rotation: None }; + let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() }; assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near"); p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed); assert_eq!(feed.pose(), None, "a mouse moved"); } + /// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as + /// 0..1, once the pen has reported a value other than 0 since it came near. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut p = Pen::default(); + let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) { + Update::Move(s) => s.pose.wheel, + u => panic!("a pen's drag is a move: {u:?}"), + }; + assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet"); + assert_eq!(wheel(&mut p, -1.0), Some(0.0)); + assert_eq!(wheel(&mut p, 0.5), Some(0.75)); + assert_eq!(wheel(&mut p, 0.0), Some(0.5), "once reported, 0 is half way"); + assert_eq!(wheel(&mut p, 3.0), Some(1.0), "clamped"); + p.handle(&proximity(1, true)); + assert_eq!(wheel(&mut p, 0.0), None, "not reported since the pen came near"); + } + #[test] fn the_feed_gets_each_moves_pressure_within_0_to_1() { let feed = StylusFeed::default(); diff --git a/apps/vectorcraft/src/tablet.rs b/apps/vectorcraft/src/tablet.rs index ed4087e33e..f9371bd368 100644 --- a/apps/vectorcraft/src/tablet.rs +++ b/apps/vectorcraft/src/tablet.rs @@ -1,4 +1,5 @@ -//! Linux: a drawing tablet's pen pressure, tilt and barrel rotation under X11, XWayland included +//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under +//! X11, XWayland included //! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app //! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`] //! (`Services::stylus`), which the canvas reads. @@ -14,11 +15,17 @@ //! - "Abs Tilt X" and "Abs Tilt Y" (a pen that has both), in degrees as they are when the range //! fits in ±90, otherwise scaled to ±[`TILT_DEGREES`]; //! - "Abs Rotary Z" (the barrel rotation of an Art Pen), scaled to a turn with the middle of the -//! range at 0°. +//! range at 0°; +//! - "Abs Wheel" (the finger wheel of an airbrush pen), scaled from the valuator's range to 0..1. +//! XWayland also sends an Art Pen's barrel rotation on this valuator +//! (), so under +//! XWayland it reads as the wheel. A tablet pad's wheel is on a device without a pressure axis, +//! which is not read. //! //! Any other pointer device moving sets the feed to `None`. Raw events carry only the valuators //! that changed, so the last value of each axis of each pen is kept; an axis the pen has that no -//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. +//! event has carried yet reads 0 (upright, unturned), and an axis it lacks reads nothing. The +//! wheel reads nothing until an event carries it. //! //! The X server lists a pen's eraser end as a device of its own, whose name or XInput type contains //! "eraser" (xf86-input-wacom's "… Pen eraser" of type `ERASER`, xf86-input-libinput's @@ -60,6 +67,7 @@ enum AxisKind { TiltX, TiltY, Rotation, + Wheel, } impl AxisKind { @@ -70,6 +78,7 @@ impl AxisKind { "Abs Tilt X" => Some(Self::TiltX), "Abs Tilt Y" => Some(Self::TiltY), "Abs Rotary Z" => Some(Self::Rotation), + "Abs Wheel" => Some(Self::Wheel), _ => None, } } @@ -81,6 +90,7 @@ impl AxisKind { Self::TiltX => 1, Self::TiltY => 2, Self::Rotation => 3, + Self::Wheel => 4, } } } @@ -95,18 +105,22 @@ struct Axis { } impl Axis { - /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90) or a - /// rotation in degrees (−180..180, the middle of the range at 0). A value that is not a number - /// is a mouse's pressure, 1, or a tilt or rotation of 0. + /// A raw value of this valuator as a pressure of 0..1, a tilt in degrees (−90..90), a rotation + /// in degrees (−180..180, the middle of the range at 0) or a wheel of 0..1. A value that is not + /// a number is a mouse's pressure, 1, a tilt or rotation of 0, or a wheel half way. fn map(&self, v: f64) -> f32 { if !v.is_finite() { - return if self.kind == AxisKind::Pressure { 1.0 } else { 0.0 }; + return match self.kind { + AxisKind::Pressure => 1.0, + AxisKind::Wheel => 0.5, + _ => 0.0, + }; } let span = self.max - self.min; let unit = if span.is_finite() && span > 0.0 { (v - self.min) / span } else { v }; let unit = unit.clamp(0.0, 1.0); match self.kind { - AxisKind::Pressure => unit as f32, + AxisKind::Pressure | AxisKind::Wheel => unit as f32, AxisKind::TiltX | AxisKind::TiltY if self.min >= -90.0 && self.max <= 90.0 && span > 0.0 => v.clamp(-90.0, 90.0) as f32, AxisKind::TiltX | AxisKind::TiltY => ((unit * 2.0 - 1.0) * TILT_DEGREES) as f32, AxisKind::Rotation => ((unit - 0.5) * 360.0) as f32, @@ -173,7 +187,7 @@ enum Update { #[derive(Debug, Default)] struct Pens { devices: HashMap, - last: HashMap; 4]>, + last: HashMap; 5]>, } impl Pens { @@ -200,10 +214,12 @@ impl Pens { } } } - // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. + // An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The + // wheel reads nothing until an event carries it: XWayland lists the axis for every pen. let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0)); let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]); - let pose = PenPose { tilt, rotation: value(AxisKind::Rotation) }; + let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten()); + let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel }; Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose })) } @@ -430,7 +446,7 @@ mod tests { let mut pens = Pens::default(); pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]); let feed = StylusFeed::default(); - let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; pens.raw_event(&feed, 9, &[0b100], &[32767.5]); assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose }))); assert_eq!(feed.eraser(), Some(false)); @@ -479,10 +495,36 @@ mod tests { // A pen whose tilt and rotation no event has carried yet is upright and unturned. let mut fresh = Pens::default(); fresh.set_devices([pen(9)]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } + /// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an + /// event carries it; a pen that lists it but has not moved it reads no wheel, and a device + /// without a pressure axis (a tablet pad's wheel) is not a pen. + #[test] + fn an_airbrush_wheel_goes_into_the_feed() { + let mut valuators = pen_valuators(); + valuators.push((6, "Abs Wheel".to_string(), 0.0, 1023.0)); + let airbrush = Device::new(9, "Wacom Intuos Pro M Pen stylus", Some("STYLUS"), valuators); + let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]); + let mut pens = Pens::default(); + pens.set_devices([airbrush, pad, pen(10)]); + let feed = StylusFeed::default(); + pens.raw_event(&feed, 9, &[0b100], &[32767.5]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet"); + pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25)); + pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range"); + pens.raw_event(&feed, 9, &[0b100], &[100.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move"); + pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]); + assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen"); + pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]); + assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator"); + } + /// A device listed again unchanged keeps its last tilt and rotation; another device listed /// under the same id starts upright and unturned. #[test] @@ -495,7 +537,7 @@ mod tests { assert_eq!(pose.tilt, Some([-30.0, 45.0])); let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators()); pens.set_devices([other]); - let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0) }; + let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None }; assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright }))); } diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 5e996c4bdd..e1ea35104d 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -133,12 +133,13 @@ fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, po /// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is /// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the -/// rotation when it reports one, each kept within [`PenPose`]'s ranges. +/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no +/// field for an airbrush pen's finger wheel, so the pose has none. fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose { let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 }; let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]); let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32); - PenPose { tilt, rotation }.sanitized() + PenPose { tilt, rotation, wheel: None }.sanitized() } /// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse, @@ -426,12 +427,12 @@ mod tests { #[test] fn a_pens_tilt_and_rotation_come_where_it_reports_them() { let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION; - assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0) }); + assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None }); assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither"); - assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), rotation: None }, "one axis"); - assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { tilt: None, rotation: Some(359.0) }, "a 6D Art Pen's barrel"); + assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis"); + assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel"); let wild = pen_pose(all, 400, i32::MIN, 720); - assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0) }, "kept within the ranges"); + assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges"); let pose = pen_pose(all, 10, 20, 180); assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose); } diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index f25615c589..4ae788613c 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -159,7 +159,7 @@ impl Calligraphic { pub fn uses_pressure(&self) -> bool { self.modes().contains(&Variation::Pressure) } - /// Does the pen (its pressure, tilt, bearing or rotation) change the nib? + /// Does the pen (its pressure, tilt, bearing, rotation or wheel) change the nib? pub fn uses_pen(&self) -> bool { self.modes().iter().any(|m| m.follows_pen()) } @@ -201,11 +201,25 @@ pub enum Variation { /// The value plus the variation times the pen barrel's rotation over 180°, counter-clockwise /// from where the pen reports 0° round to ±180°. Rotation, + /// From the value less the variation with an airbrush pen's finger wheel at one end of its + /// travel to the value plus the variation at the other (the value itself half way). + StylusWheel, } impl Variation { - pub const ALL: [Variation; 6] = + pub const ALL: [Variation; 7] = + [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + /// The modes Brush Options offers for a value other than a size (a Calligraphic brush's Angle + /// and Roundness, a Scatter brush's Spacing, Scatter and Rotation): all but + /// [`Variation::StylusWheel`], which drives a Calligraphic or Scatter brush's Size and an Art + /// brush's Width. + pub const OTHER: [Variation; 6] = [Variation::Fixed, Variation::Random, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + /// The modes Brush Options offers for a size (`true`: [`Self::ALL`]) or another value + /// ([`Self::OTHER`]). + pub fn offered(size: bool) -> &'static [Variation] { + if size { &Self::ALL } else { &Self::OTHER } + } /// The name brush definitions use. pub fn id(self) -> &'static str { match self { @@ -215,6 +229,7 @@ impl Variation { Variation::Tilt => "tilt", Variation::Bearing => "bearing", Variation::Rotation => "rotation", + Variation::StylusWheel => "stylusWheel", } } pub fn label(self) -> &'static str { @@ -225,15 +240,16 @@ impl Variation { Variation::Tilt => "Tilt", Variation::Bearing => "Bearing", Variation::Rotation => "Rotation", + Variation::StylusWheel => "Stylus Wheel", } } pub fn parse(id: &str) -> Option { Self::ALL.into_iter().find(|v| v.id() == id) } /// Does the value follow something the pen records along a stroke (Pressure, Tilt, Bearing, - /// Rotation)? + /// Rotation, Stylus Wheel)? pub fn follows_pen(self) -> bool { - matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation) + matches!(self, Variation::Pressure | Variation::Tilt | Variation::Bearing | Variation::Rotation | Variation::StylusWheel) } } @@ -250,12 +266,14 @@ pub(crate) struct PenAt { bearing: f64, /// ½ plus the counter-clockwise barrel rotation over 360°. rotation: f64, + /// Where the airbrush finger wheel was set, 0 at one end of its travel to 1 at the other. + wheel: f64, } impl PenAt { /// Every input at `c`. pub(crate) fn uniform(c: f64) -> Self { - Self { pressure: c, tilt: c, bearing: c, rotation: c } + Self { pressure: c, tilt: c, bearing: c, rotation: c, wheel: c } } /// What `stroke` recorded at `f` (the fraction of its path's length). pub(crate) fn of(stroke: &StrokeLayer, f: f64) -> Self { @@ -266,6 +284,7 @@ impl PenAt { tilt: 1.0 - stroke.tilt.as_ref().map_or(mid, |p| p.at(f)), bearing: turn(stroke.bearing.as_ref()), rotation: turn(stroke.rotation.as_ref()), + wheel: stroke.wheel.as_ref().map_or(mid, |p| p.at(f)), } } /// The 0..1 a value on `mode` takes, or `None` for a mode that doesn't follow the pen. @@ -276,6 +295,7 @@ impl PenAt { Variation::Tilt => self.tilt, Variation::Bearing => self.bearing, Variation::Rotation => self.rotation, + Variation::StylusWheel => self.wheel, }; Some(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 }) } @@ -300,9 +320,10 @@ pub struct Scatter { /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, - /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°). `None` - /// (brushes saved before there were modes): Random where the two differ, else Fixed (see - /// [`Scatter::modes`]). + /// Bearing and Rotation the first at −180° and the second at 180° (half way at 0°), and Stylus + /// Wheel (the size's only) the first at one end of an airbrush pen's finger wheel and the + /// second at the other. `None` (brushes saved before there were modes): Random where the two + /// differ, else Fixed (see [`Scatter::modes`]). #[serde(skip_serializing_if = "Option::is_none")] pub modes: Option<[Variation; 4]>, } @@ -373,11 +394,12 @@ pub struct ArtBrush { /// How the width varies along a stroke: `None` (Fixed) always `width`; a mode that follows the /// pen goes from `width` to [`Self::width_max`] over the ranges [`Variation`] gives: Pressure /// from the lightest pressure to the heaviest, Tilt from the pen lying flat to upright, Bearing - /// and Rotation from −180° to 180° (half way at 0°). + /// and Rotation from −180° to 180° (half way at 0°), Stylus Wheel from one end of an airbrush + /// pen's finger wheel to the other. #[serde(skip_serializing_if = "Option::is_none")] pub width_mode: Option, - /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, or - /// at 180° (`width` without one). + /// The second width (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`width` without one). #[serde(skip_serializing_if = "Option::is_none")] pub width_max: Option, pub flip_along: bool, @@ -716,7 +738,7 @@ impl Brush { } BrushKind::Art(a) => { a.width = within(a.width, ArtBrush::WIDTH_RANGE, 100.0); - // The width follows the pen (its pressure, tilt, bearing or rotation) or stays fixed. + // The width follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. if !a.width_mode.is_some_and(Variation::follows_pen) { a.width_mode = None; } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index affd2fa6b7..00c485c1be 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1060,6 +1060,64 @@ fn pressure_varies_angle_and_roundness() { assert!(near(h, expected, 0.05), "{h} vs {expected}"); } +/// A stroke that recorded an airbrush pen's finger wheel going from `from` to `to` along it. +fn wheeled(from: f64, to: f64) -> StrokeLayer { + StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, from), (1.0, to)] }), ..stroke(1.0) } +} + +/// Stylus Wheel: a Calligraphic brush's size goes from size − variation at one end of the finger +/// wheel to size + variation at the other, a Scatter brush's size from its first value to its +/// second, and an Art brush's width from Width to the second width. Each reads only the wheel: the +/// pressure, tilt, bearing or rotation recorded instead leaves the value half way. +#[test] +fn the_stylus_wheel_varies_sizes_and_widths() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + let c = Calligraphic { + size: 6.0, + variation: [0.0, 0.0, 4.0], + modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), + ..Default::default() + }; + let nib = Brush { name: "w".into(), kind: BrushKind::Calligraphic(c) }; + let out = stroke_pieces(&doc, &nib, &bp, &wheeled(0.0, 1.0)); + // Round nib: 2 pt across at the start, 10 pt at the end, 6 pt half way. + assert!(near(half_width(&out, 0.5, 1.5), 1.0, 0.1), "{}", half_width(&out, 0.5, 1.5)); + assert!(near(half_width(&out, 98.5, 99.5), 5.0, 0.1), "{}", half_width(&out, 98.5, 99.5)); + assert!(near(half_width(&out, 49.5, 50.5), 3.0, 0.1), "{}", half_width(&out, 49.5, 50.5)); + let others = [ + pressed(vec![(0.0, 0.0), (1.0, 1.0)]), + StrokeLayer { tilt: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }, + posed(None, Some(90.0), Some(-90.0)), + ]; + for st in &others { + let h = bounds(&stroke_pieces(&doc, &nib, &bp, st)).height(); + assert!(near(h, 6.0, 0.05), "{st:?}: {h}"); + } + // Scatter size 50 % to 300 % of 4 pt art: 2 pt at one end of the wheel, 12 pt at the other. + let spray = sized_scatter(50.0, 300.0, Variation::StylusWheel); + let h: Vec = + stroke_pieces(&doc, &spray, &line(0.0, 0.0, 400.0, 0.0), &wheeled(1.0, 0.0)).iter().map(|n| n.geometric_bounds().unwrap().height()).collect(); + assert!(near(h[0], 12.0, 0.2) && h[h.len() - 1] < 3.0, "{h:?}"); + // Art width 50 % to 300 % of 4 pt art. + let mut ribbon = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); + if let BrushKind::Art(a) = &mut ribbon.kind { + (a.width, a.width_mode, a.width_max) = (50.0, Some(Variation::StylusWheel), Some(300.0)); + } + let out = stroke_pieces(&doc, &ribbon, &bp, &wheeled(1.0, 0.0)); + assert!(near(half_width(&out, 0.0, 1.0), 6.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 99.0, 100.0), 1.0, 0.1), "{}", half_width(&out, 99.0, 100.0)); + for st in &others { + let h = bounds(&stroke_pieces(&doc, &ribbon, &bp, st)).height(); + assert!(near(h, 7.0, 1e-6), "{st:?}: {h}"); + } + // A definition keeps the mode by name. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "art", "art": rect_art(10.0, 4.0), "width_mode": "stylusWheel", "width_max": 300.0}, + ])); + assert!(matches!(&lib[0].kind, BrushKind::Art(a) if a.width_mode == Some(Variation::StylusWheel))); +} + /// A stroke that recorded the pen's tilt (`tilt`: 0 upright to 1 flat), bearing and barrel /// rotation (degrees counter-clockwise), each the same all along it where given. fn posed(tilt: Option, bearing: Option, rotation: Option) -> StrokeLayer { @@ -1126,7 +1184,7 @@ fn bearing_and_rotation_turn_the_nib() { #[test] fn pen_modes_without_a_recording_draw_the_value_itself() { let horizontal = line(0.0, 0.0, 100.0, 0.0); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { let c = Calligraphic { angle: 90.0, roundness: 50.0, size: 10.0, variation: [90.0, 50.0, 6.0], modes: Some([mode; 3]) }; let b = Brush { name: "n".into(), kind: BrushKind::Calligraphic(c) }; let h = bounds(&stroke_pieces(&Document::new(1.0, 1.0), &b, &horizontal, &stroke(1.0))).height(); @@ -1173,7 +1231,7 @@ fn a_mouse_stroke_draws_pen_modes_as_pressure_did() { }; let (calli_before, scatter_before) = (calli(Variation::Pressure), scattered(Variation::Pressure)); assert!(!calli_before.is_empty() && !scatter_before.is_empty()); - for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation] { + for mode in [Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel] { assert_eq!(calli(mode), calli_before, "{mode:?}"); assert_eq!(scattered(mode), scatter_before, "{mode:?}"); } @@ -1241,8 +1299,12 @@ fn brushes_without_modes_vary_randomly_as_before() { stroke_pieces(&Document::new(1.0, 1.0), &old, &bp, &pressed(vec![(0.0, 0.0), (1.0, 1.0)])) ); // Modes are saved by name. - assert_eq!(serde_json::to_value(Variation::ALL).unwrap(), serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation"])); - assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v))); + assert_eq!( + serde_json::to_value(Variation::ALL).unwrap(), + serde_json::json!(["fixed", "random", "pressure", "tilt", "bearing", "rotation", "stylusWheel"]) + ); + assert!(Variation::ALL.iter().all(|v| Variation::parse(v.id()) == Some(*v) && serde_json::to_value(v).unwrap() == v.id())); + assert!(!Variation::offered(false).contains(&Variation::StylusWheel) && Variation::offered(true).contains(&Variation::StylusWheel)); } /// Junk definitions and pressure never panic and never draw non-finite art. diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index ba0f5fc013..b7252ea734 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -127,8 +127,8 @@ impl Appearance { pub fn stroke_mut(&mut self) -> Option<&mut StrokeLayer> { self.items.iter_mut().rev().find_map(|i| if let AppearanceItem::Stroke(s) = i { Some(s) } else { None }) } - /// This appearance for other art: the pen pressure, tilt, bearing and rotation its strokes - /// were drawn with stay with them. + /// This appearance for other art: the pen pressure, tilt, bearing, rotation and wheel its + /// strokes were drawn with stay with them. pub fn without_pressure(mut self) -> Self { for it in &mut self.items { if let AppearanceItem::Stroke(s) = it { @@ -136,6 +136,7 @@ impl Appearance { s.tilt = None; s.bearing = None; s.rotation = None; + s.wheel = None; } } self diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index f8a58758d8..583e619c4a 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -108,6 +108,11 @@ pub struct StrokeLayer { /// pressure, it stays with this path. #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + /// Where the finger wheel of an airbrush pen was set along the stroke: 0 at one end of its + /// travel to 1 at the other. Brushes with Stylus Wheel variation vary with it. Like the + /// pressure, it stays with this path. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } /// How a gradient on a stroke is laid out (the Gradient panel's Stroke buttons). Saved by variant @@ -181,6 +186,7 @@ impl StrokeLayer { tilt: None, bearing: None, rotation: None, + wheel: None, } } /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least diff --git a/crates/doc/src/appearance/profile.rs b/crates/doc/src/appearance/profile.rs index 3d89615016..e6f69e6670 100644 --- a/crates/doc/src/appearance/profile.rs +++ b/crates/doc/src/appearance/profile.rs @@ -130,8 +130,9 @@ impl WidthProfile { /// Pen pressure recorded along a stroke (the Paintbrush with a graphics tablet): (position 0..1 /// along the path, pressure 0..1) samples in order, positions measured as a [`WidthProfile`]'s -/// are. The pen's tilt is kept the same way ([`StrokeLayer::tilt`]). Calligraphic and Scatter -/// brushes with Pressure or Tilt variation read them; everything else ignores them. +/// are. The pen's tilt and an airbrush pen's finger wheel are kept the same way +/// ([`StrokeLayer::tilt`], [`StrokeLayer::wheel`]). Brushes with Pressure, Tilt or Stylus Wheel +/// variation read them; everything else ignores them. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PressureProfile { pub points: Vec<(f64, f64)>, diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index 22e5659051..b968939af5 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -166,7 +166,7 @@ fn angle_profiles_join_samples_the_shorter_way_round() { #[test] fn strokes_without_pressure_round_trip_unchanged() { let json = serde_json::to_value(StrokeLayer::new(Paint::None, 2.0)).unwrap(); - for key in ["pressure", "tilt", "bearing", "rotation"] { + for key in ["pressure", "tilt", "bearing", "rotation", "wheel"] { assert!(json.get(key).is_none(), "{key}"); } let st: StrokeLayer = serde_json::from_value(json).unwrap(); @@ -177,19 +177,21 @@ fn strokes_without_pressure_round_trip_unchanged() { let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); ap.stroke_mut().unwrap().pressure = Some(PressureProfile::sample()); assert_eq!(ap.without_pressure().stroke().unwrap().pressure, None); - // The pen's tilt, bearing and rotation load, save and stay behind the same way. + // The pen's tilt, bearing, rotation and wheel load, save and stay behind the same way. let posed = StrokeLayer { tilt: Some(PressureProfile::sample()), bearing: Some(AngleProfile::sample()), rotation: Some(AngleProfile { points: vec![(0.0, -45.0)] }), + wheel: Some(PressureProfile { points: vec![(0.0, 0.25), (1.0, 0.75)] }), ..back }; + assert_eq!(serde_json::to_value(&posed).unwrap()["wheel"], serde_json::json!({"points": [[0.0, 0.25], [1.0, 0.75]]})); let again: StrokeLayer = serde_json::from_value(serde_json::to_value(&posed).unwrap()).unwrap(); assert_eq!(again, posed); let mut ap = Appearance::basic(Paint::None, Paint::None, 1.0); *ap.stroke_mut().unwrap() = posed; let st = ap.without_pressure().stroke().cloned().unwrap(); - assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation), (None, None, None, None)); + assert_eq!((st.pressure, st.tilt, st.bearing, st.rotation, st.wheel), (None, None, None, None, None)); } /// The Lens profile's widths at its middle, a quarter of the way along and past its end. diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index d9e179286f..151692b78c 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -6,7 +6,7 @@ //! tool clicked. //! - **Paint**: colours, gradients (stops resampled to a common set when their counts differ), //! opacity, stroke weight, dashes, miter limit, width profiles and the pen pressure, tilt, -//! bearing and rotation that brushes read interpolate; what can't +//! bearing, rotation and wheel that brushes read interpolate; what can't //! (caps, joins, brushes, fonts, symbols, text content) switches halfway. //! - **Groups** pair their children in stacking order; the children one group has more of grow //! out of the other group's centre. Compound paths stay compound paths. @@ -373,8 +373,8 @@ fn lerp_angle(x: Option<&AngleProfile>, y: Option<&AngleProfile>, t: f64) -> Opt } /// Interpolate a stroke's paint, weight, opacity, miter limit, dashes, arrowhead scale, width -/// profile and the pen pressure, tilt, bearing and rotation its brush reads into `o` (a copy of -/// the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). +/// profile and the pen pressure, tilt, bearing, rotation and wheel its brush reads into `o` (a +/// copy of the nearer stroke, so caps, joins, alignment, arrowheads and brushes switch halfway). fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { let tf = t as f32; o.paint = lerp_paint(&x.paint, &y.paint, tf); @@ -388,6 +388,7 @@ fn lerp_stroke(o: &mut StrokeLayer, x: &StrokeLayer, y: &StrokeLayer, t: f64) { o.tilt = lerp_pressure(x.tilt.as_ref(), y.tilt.as_ref(), t); o.bearing = lerp_angle(x.bearing.as_ref(), y.bearing.as_ref(), t); o.rotation = lerp_angle(x.rotation.as_ref(), y.rotation.as_ref(), t); + o.wheel = lerp_pressure(x.wheel.as_ref(), y.wheel.as_ref(), t); } /// Interpolate appearance stacks: item by item when their structure matches, else the top fill @@ -607,8 +608,8 @@ fn reoriented(points: &[(f64, V)], o: Orient, at: impl Fn(f64) -> V, wr } /// A key's stroke read along its subpath turned as `o` says: its width profile (whose sides swap -/// when reversed), pen pressure, tilt, bearing and rotation, and on a reversed open path its -/// arrowheads. +/// when reversed), pen pressure, tilt, bearing, rotation and wheel, and on a reversed open path +/// its arrowheads. fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { if o.is_identity() { return; @@ -634,7 +635,7 @@ fn reorient_stroke(s: &mut StrokeLayer, o: Orient) { let out = reoriented(&pts, o, |f| p.at(f), |v| v, |(l, r)| (r, l)); p.points = out.into_iter().map(|(t, (l, r))| (t, l, r)).collect(); } - for p in [&mut s.pressure, &mut s.tilt].into_iter().flatten() { + for p in [&mut s.pressure, &mut s.tilt, &mut s.wheel].into_iter().flatten() { let out = reoriented(&p.points, o, |f| p.at(f), same, same); p.points = out; } diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index 7ff6cdeea2..779800c889 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -320,7 +320,8 @@ pub fn appearance_heap_bytes(a: &Appearance) -> usize { AppearanceItem::Stroke(s) => { s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern)) + s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points)) - + s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + [&s.pressure, &s.tilt, &s.wheel].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + + [&s.bearing, &s.rotation].into_iter().flatten().map(|p| vec_bytes(&p.points)).sum::() + s.brush.as_ref().map_or(0, String::capacity) } _ => 0, @@ -391,6 +392,27 @@ mod tests { d } + #[test] + fn every_pen_recording_of_a_stroke_counts() { + use crate::{AngleProfile, PressureProfile}; + let plain = Appearance::default_art(); + let base = appearance_heap_bytes(&plain); + let ramp = || PressureProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 0.5)).collect() }; + let turn = || AngleProfile { points: (0..100).map(|i| (f64::from(i) / 99.0, 10.0)).collect() }; + for i in 0..5 { + let mut a = plain.clone(); + let s = a.stroke_mut().unwrap(); + match i { + 0 => s.pressure = Some(ramp()), + 1 => s.tilt = Some(ramp()), + 2 => s.bearing = Some(turn()), + 3 => s.rotation = Some(turn()), + _ => s.wheel = Some(ramp()), + } + assert!(appearance_heap_bytes(&a) >= base + 100 * size_of::<(f64, f64)>(), "recording {i}"); + } + } + #[test] fn an_unchanged_copy_keeps_nothing_of_its_own() { let d = doc_with_rects(10); diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 50c63b59cd..1895690d20 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -162,7 +162,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 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°; 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 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°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, 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°; 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. 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}", has_doc, brush_options ), diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 8946aa4351..5469012981 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation,wheel]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation. An airbrush pen's finger wheel 0..1 (clamped): the stroke keeps it for brushes with Stylus Wheel variation, a point without one half way; null for what a point lacks), fidelity?: pt (1.5), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\"|\"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end: \"start\"|\"end\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end; with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/common.rs b/crates/engine/src/cmd/draw2/common.rs index 0ca376b243..0ab17d42d7 100644 --- a/crates/engine/src/cmd/draw2/common.rs +++ b/crates/engine/src/cmd/draw2/common.rs @@ -22,11 +22,13 @@ pub(super) struct Sample { tilt: Option<[f64; 2]>, /// Barrel rotation, degrees clockwise. rotation: Option, + /// The airbrush finger wheel, 0..1. + wheel: Option, } /// The keys of a point's pen values, in the order a point given as an array holds them after its /// x and y. -const PEN_KEYS: [&str; 4] = ["pressure", "tiltX", "tiltY", "rotation"]; +const PEN_KEYS: [&str; 5] = ["pressure", "tiltX", "tiltY", "rotation", "wheel"]; /// The point `[x, y, …]` or `{x, y, …}` that `v` holds, or an error when its x or y is not a finite /// number. @@ -40,16 +42,16 @@ pub(super) fn point_entry(v: &Value, cmd: &str) -> Result { } /// [`points_param`] with what a pen read at each point, as far as it is given: -/// `[[x,y,pressure,tiltX,tiltY,rotation]…]` or `[{x,y,pressure,tiltX,tiltY,rotation}…]`. Pressure -/// is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); rotation in -/// degrees clockwise. A point whose x or y is not a number, or whose pressure, tilt or rotation is -/// neither a number nor null, is an error. +/// `[[x,y,pressure,tiltX,tiltY,rotation,wheel]…]` or `[{x,y,pressure,tiltX,tiltY,rotation,wheel}…]`. +/// Pressure is 0..1; tilt in degrees, each −90..90 (one of the two without the other is 0); +/// rotation in degrees clockwise; the wheel 0..1 (clamped). A point whose x or y is not a number, +/// or whose pressure, tilt, rotation or wheel is neither a number nor null, is an error. pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result> { let a = p.get(key).and_then(Value::as_array).ok_or_else(|| bad(cmd, format!("missing array `{key}`")))?; let pts: Vec = a .iter() .map(|v| { - let mut pen = [None; 4]; + let mut pen = [None; 5]; for (i, (key, slot)) in PEN_KEYS.iter().zip(&mut pen).enumerate() { let given = match v { Value::Array(xy) => xy.get(i + 2), @@ -61,9 +63,10 @@ pub(super) fn samples_param(p: &Value, key: &str, cmd: &str) -> Result return Err(bad(cmd, format!("`{key}` must be a number, not {v}"))), }; } - let [pressure, tx, ty, rotation] = pen; + let [pressure, tx, ty, rotation, wheel] = pen; let tilt = (tx.is_some() || ty.is_some()).then(|| [tx, ty].map(|t| t.unwrap_or(0.0).clamp(-90.0, 90.0))); - Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation }) + let wheel = wheel.map(|w| w.clamp(0.0, 1.0)); + Ok(Sample { pt: point_entry(v, cmd)?, pressure, tilt, rotation, wheel }) }) .collect::>()?; if pts.is_empty() { @@ -96,6 +99,15 @@ fn stroke_pressure(samples: &[Sample]) -> Option { PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.pressure.unwrap_or(1.0)))) } +/// Where an airbrush pen's finger wheel was set along a freehand stroke, when any of its samples +/// has it; samples without it count as the middle of its travel, which draws a brush's own value. +fn stroke_wheel(samples: &[Sample]) -> Option { + if samples.iter().all(|s| s.wheel.is_none()) { + return None; + } + PressureProfile::from_samples(along(samples).into_iter().zip(samples).map(|(t, s)| (t, s.wheel.unwrap_or(PressureProfile::MID)))) +} + /// A pen that leans less than this many degrees from upright leans no way in particular: its /// bearing is the one before it. const UPRIGHT: f64 = 1.0; @@ -135,24 +147,31 @@ fn stroke_pose(samples: &[Sample]) -> (Option, Option, tilt: Option, bearing: Option, rotation: Option, + wheel: Option, } impl PenRecord { /// What a freehand stroke's samples recorded. pub(super) fn of_samples(samples: &[Sample]) -> Self { let (tilt, bearing, rotation) = stroke_pose(samples); - Self { pressure: stroke_pressure(samples), tilt, bearing, rotation } + Self { pressure: stroke_pressure(samples), tilt, bearing, rotation, wheel: stroke_wheel(samples) } } pub(super) fn of(st: &StrokeLayer) -> Self { - Self { pressure: st.pressure.clone(), tilt: st.tilt.clone(), bearing: st.bearing.clone(), rotation: st.rotation.clone() } + Self { + pressure: st.pressure.clone(), + tilt: st.tilt.clone(), + bearing: st.bearing.clone(), + rotation: st.rotation.clone(), + wheel: st.wheel.clone(), + } } pub(super) fn is_empty(&self) -> bool { *self == Self::default() @@ -165,6 +184,7 @@ impl PenRecord { tilt: PressureProfile::extended(self.tilt.as_ref(), old_len, added.tilt.as_ref(), added_len), bearing: AngleProfile::extended(self.bearing.as_ref(), old_len, added.bearing.as_ref(), added_len), rotation: AngleProfile::extended(self.rotation.as_ref(), old_len, added.rotation.as_ref(), added_len), + wheel: PressureProfile::extended(self.wheel.as_ref(), old_len, added.wheel.as_ref(), added_len), } } /// The record along the path reversed. @@ -174,6 +194,7 @@ impl PenRecord { tilt: self.tilt.as_ref().map(PressureProfile::reversed), bearing: self.bearing.as_ref().map(AngleProfile::reversed), rotation: self.rotation.as_ref().map(AngleProfile::reversed), + wheel: self.wheel.as_ref().map(PressureProfile::reversed), } } /// Keep the record on stroke `st`. @@ -182,6 +203,7 @@ impl PenRecord { st.tilt = self.tilt; st.bearing = self.bearing; st.rotation = self.rotation; + st.wheel = self.wheel; } } diff --git a/crates/engine/src/cmd/globaledit.rs b/crates/engine/src/cmd/globaledit.rs index 98f53b102e..e4c34fb39d 100644 --- a/crates/engine/src/cmd/globaledit.rs +++ b/crates/engine/src/cmd/globaledit.rs @@ -664,8 +664,8 @@ fn give_appearance(a: &Appearance, b: &Appearance, m: &Appearance, n: &mut Share } /// Give the member's fill or stroke `n` the settings of the model's that changed from `a` to `b`, -/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing and -/// rotation stay its own. +/// with the values of `m` (`b` placed on the member). A stroke's pen pressure, tilt, bearing, +/// rotation and wheel stay its own. fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut AppearanceItem) { use AppearanceItem::{Fill, Stroke}; match (a, b, m, n) { @@ -698,6 +698,7 @@ fn give_item(a: &AppearanceItem, b: &AppearanceItem, m: &AppearanceItem, n: &mut tilt: _, bearing: _, rotation: _, + wheel: _, } = m; give_fields!(a, b, n: paint, width, cap, join, miter_limit, align, dash, start_arrow, end_arrow, arrow_scale, profile, brush, opacity, blend, visible, effects, arrow_align, overprint, gradient_mode); } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 1a1fcd87b5..c6798233c2 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1070,6 +1070,73 @@ fn freehand_points_record_the_pens_tilt_bearing_and_rotation() { assert_eq!(tilt.unwrap().at(0.9), vectorcraft_doc::PressureProfile::MID, "half way over without one"); } +/// The airbrush finger wheel recorded on the stroke `id`. +fn wheel_of(s: &Session, id: NodeId) -> Option { + node(s, id).appearance.stroke().and_then(|st| st.wheel.clone()) +} + +/// `path.freehand` points carry an airbrush pen's finger wheel seventh (or as `wheel`), 0..1 and +/// clamped; the stroke keeps it, a continued or reversed stroke keeps it in step, a point that is +/// not a number is refused, and the Paintbrush records it from the pen. A Calligraphic brush with +/// Size on Stylus Wheel draws it, and it lasts through saving, new art leaving it behind. +#[test] +fn freehand_points_record_the_stylus_wheel() { + let mut s = session(); + let draw = |s: &mut Session, points: Value| { + NodeId(s.execute("path.freehand", &json!({"points": points, "style": "brush"})).unwrap()["id"].as_u64().unwrap()) + }; + let id = draw(&mut s, json!([[0, 50, null, null, null, null, 0], [100, 50, null, null, null, null, 1]])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + assert_eq!(pose_of(&s, id), (None, None, None), "the wheel alone"); + assert_eq!(pressure_of(&s, id), None); + // As keys, clamped; a point without one is half way. + let id = draw(&mut s, json!([{"x": 0, "y": 150, "wheel": -2}, {"x": 50, "y": 150}, {"x": 100, "y": 150, "wheel": 9}])); + let w = wheel_of(&s, id).unwrap(); + assert!(w.at(0.0) < 1e-6 && (w.at(0.5) - 0.5).abs() < 1e-6 && (w.at(1.0) - 1.0).abs() < 1e-6, "{w:?}"); + // No wheel given: none recorded. + let id = draw(&mut s, json!([[0, 250, 0.5, 30, 0, 90], [100, 250, 0.5, 30, 0, 90]])); + assert_eq!(wheel_of(&s, id), None); + // Not a number: refused, and nothing drawn. + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("path.freehand", &json!({"points": [[0, 0, null, null, null, null, "0.5"], [10, 0]], "style": "brush"})); + assert!(err.unwrap_err().to_string().contains("`wheel` must be a number")); + assert_eq!(s.doc().unwrap().doc.layers, before.layers, "the document is unchanged"); + // Continued at its end by a stroke without a wheel: the old part keeps it, the new one is half way. + let id = draw(&mut s, json!([[0, 350, null, null, null, null, 1], [100, 350, null, null, null, null, 1]])); + s.execute("path.freehand", &json!({"points": [[100, 350], [200, 350]], "style": "brush", "extend": {"id": id.0, "end": "end"}})).unwrap(); + let w = wheel_of(&s, id).unwrap(); + assert!((w.at(0.25) - 1.0).abs() < 1e-6 && (w.at(0.9) - 0.5).abs() < 1e-6, "{w:?}"); + // The Paintbrush records it, and a brush with Size on Stylus Wheel draws it. + let params = json!({"angle": 0, "roundness": 100, "size": 6, "variation": [0, 0, 4], "modes": ["fixed", "fixed", "stylusWheel"]}); + s.execute("brush.options", &json!({"name": "3 pt. Round", "params": params})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "3 pt. Round"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("paintbrush", v).unwrap(); + let strokes = |s: &mut Session, y: f64, wheel: Option| { + let pen = wheel.map(|w| PenPose { wheel: Some(w), ..PenPose::default() }); + for (k, x) in [(PointerKind::Down, 20.0), (PointerKind::Drag, 120.0), (PointerKind::Drag, 220.0), (PointerKind::Up, 320.0)] { + s.pointer(&PointerEvent { pen, ..PointerEvent::new(k, x, y) }, v).unwrap(); + } + let id = s.doc().unwrap().selection.objects[0]; + select(s, &[]); + id + }; + let far = strokes(&mut s, 500.0, Some(1.0)); + let near = strokes(&mut s, 600.0, Some(0.0)); + let mouse = strokes(&mut s, 700.0, None); + assert_eq!(wheel_of(&s, far).map(|w| w.at(0.5)), Some(1.0)); + assert_eq!(wheel_of(&s, mouse), None, "a mouse has no wheel"); + let height = |s: &Session, id| brushed_bounds(s, id).height(); + assert!((height(&s, far) - 10.0).abs() < 0.1 && (height(&s, near) - 2.0).abs() < 0.1, "{} {}", height(&s, far), height(&s, near)); + assert!((height(&s, mouse) - 6.0).abs() < 0.1, "the brush's own size: {}", height(&s, mouse)); + // Saved and reopened as it was; new art takes the look without the wheel. + let doc: Document = (*s.doc().unwrap().doc).clone(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(far).unwrap().appearance.stroke(), doc.node(far).unwrap().appearance.stroke()); + assert!(vectorcraft_doc::Appearance::clone(&doc.node(far).unwrap().appearance).without_pressure().stroke().is_some_and(|st| st.wheel.is_none())); +} + /// #764: a stroke that connects two paths joins the pen's tilt, bearing and rotation of both, the /// connected path's after the stroke's. #[test] @@ -1109,7 +1176,7 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { select(s, &[]); id }; - let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0) })); + let pen = strokes(&mut s, 60.0, Some(PenPose { tilt: Some([0.0, 0.0]), rotation: Some(30.0), wheel: None })); let (tilt, bearing, rotation) = pose_of(&s, pen); assert_eq!(tilt.as_ref().map(|t| t.at(0.5)), Some(0.0), "upright"); assert!(bearing.is_some() && (rotation.unwrap().at(0.5) + 30.0).abs() < 1e-6); diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 8c4e95f4e6..b43123a428 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7960,8 +7960,9 @@ fn an_art_brush_whose_art_doesnt_bend_keeps_its_paths_look() { } /// Settings the other tests don't use come back: a Calligraphic brush varying with tilt and bearing, -/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, and brushes whose -/// modes aren't given (the reader gives them, the same ones). +/// a Scatter brush keeping its art's colors whose rotation doesn't follow the path, a Calligraphic +/// and a Scatter brush whose size follows an airbrush pen's finger wheel, and brushes whose modes +/// aren't given (the reader gives them, the same ones). #[test] fn more_brush_settings_are_read_back() { use vectorcraft_brush::{Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; @@ -7985,8 +7986,20 @@ fn more_brush_settings_are_read_back() { let lib = vec![ Brush { name: "Tilted".into(), kind: BrushKind::Calligraphic(tilted.clone()) }, Brush { name: "Still".into(), kind: BrushKind::Scatter(scatter.clone()) }, - Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted }) }, - Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter }) }, + Brush { name: "Unset nib".into(), kind: BrushKind::Calligraphic(Calligraphic { modes: None, ..tilted.clone() }) }, + Brush { name: "Unset spray".into(), kind: BrushKind::Scatter(Scatter { modes: None, ..scatter.clone() }) }, + Brush { + name: "Wheel nib".into(), + kind: BrushKind::Calligraphic(Calligraphic { modes: Some([Variation::Fixed, Variation::Fixed, Variation::StylusWheel]), ..tilted }), + }, + Brush { + name: "Wheel spray".into(), + kind: BrushKind::Scatter(Scatter { + size: (40.0, 160.0), + modes: Some([Variation::StylusWheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), + ..scatter + }), + }, ]; let mut doc = Document::new(300.0, 200.0); vectorcraft_brush::store(&mut doc, &lib); diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 2c281e702d..1f45cb3c6e 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -96,6 +96,7 @@ fn code(v: Variation) -> f64 { Variation::Fixed => 0.0, Variation::Random => 1.0, Variation::Pressure => 2.0, + Variation::StylusWheel => 3.0, Variation::Tilt => 4.0, Variation::Bearing => 5.0, Variation::Rotation => 6.0, diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index 5a5db47114..7848c13d21 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -200,12 +200,13 @@ fn numbers(s: &str) -> Option> { s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() } -/// How a value varies, by its code: `None` for the stylus wheel and codes that aren't known. +/// How a value varies, by its code: `None` for codes that aren't known. fn variation(code: f64) -> Option { match code { 0.0 => Some(Variation::Fixed), 1.0 => Some(Variation::Random), 2.0 => Some(Variation::Pressure), + 3.0 => Some(Variation::StylusWheel), 4.0 => Some(Variation::Tilt), 5.0 => Some(Variation::Bearing), 6.0 => Some(Variation::Rotation), diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 3c0ac39a05..0ed3f7b3b2 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -9954,11 +9954,11 @@ fn a_gradients_br_is_not_a_brush() { /// The Brush Options codes for how a Calligraphic brush's values vary: Tilt, Bearing and Rotation /// are the pen's other channels (#372: a 6D Art Pen brush varies its diameter with the pressure, -/// its roundness with the bearing and its angle with the barrel's rotation). The stylus wheel isn't -/// read: it varies at random, as an unknown code does. +/// its roundness with the bearing and its angle with the barrel's rotation), and code 3 is an +/// airbrush pen's finger wheel. An unknown code varies at random. #[test] fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { - use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, Tilt}; + use vectorcraft_brush::Variation::{Bearing, Fixed, Pressure, Random, Rotation, StylusWheel, Tilt}; let modes = |params: &str| { let d = brush::parse_tool_object(brush::Tool::Calligraphic, "Pen", params).unwrap(); let brush::DraftKind::Calligraphic(c) = d.kind else { panic!("{d:?}") }; @@ -9966,8 +9966,9 @@ fn a_calligraphic_brushs_pen_channels_come_in_by_their_codes() { }; assert_eq!(modes("1 51 69 13 57 -346 14 2 5 6 0"), [Rotation, Bearing, Pressure]); assert_eq!(modes("1 2 6 40 60 -30 10 4 4 4 0"), [Tilt, Tilt, Tilt]); - assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [Random, Random, Random], "the stylus wheel"); - assert_eq!(modes("1 4 4 50 50 10 10 3 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); + assert_eq!(modes("1 2 6 40 60 -30 10 3 3 3 0"), [StylusWheel, StylusWheel, StylusWheel], "the stylus wheel"); + assert_eq!(modes("1 2 6 40 60 -30 10 7 9 7 0"), [Random, Random, Random], "unknown codes"); + assert_eq!(modes("1 4 4 50 50 10 10 7 9 9 0"), [Fixed, Fixed, Fixed], "nothing to vary"); } /// A 6D Art Pen brush: diameter 4 to 8 with the pressure, roundness 30 to 50 with the bearing and diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index d4d69c945f..cb86467035 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -214,6 +214,7 @@ pub fn tool_definitions() -> Vec { "tiltX": num("Pen tilt in degrees −90..90, positive leaning right (document axes); with tiltY, the tilt the Paintbrush records for Tilt and Bearing brushes. One without the other is 0"), "tiltY": num("Pen tilt in degrees −90..90, positive leaning down the page"), "rotation": num("Pen barrel rotation in degrees clockwise: the rotation the Paintbrush records for Rotation brushes"), + "wheel": num("Airbrush pen finger wheel 0..1 (clamped): the wheel the Paintbrush records for Stylus Wheel brushes"), "holdMs": num("Milliseconds the pointer then holds still, button down (0..60000): Twirl, Pucker and Bloat keep applying"), }), &["kind", "x", "y"]), }, diff --git a/crates/render/src/changed.rs b/crates/render/src/changed.rs index 1c15247034..cea07dab35 100644 --- a/crates/render/src/changed.rs +++ b/crates/render/src/changed.rs @@ -360,8 +360,8 @@ fn same_but_anchors(a: &Node, b: &Node) -> bool { } /// Does `n` paint each pixel from the segments near it alone: no effects, every visible fill and -/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing or -/// rotation, arrowheads, a brush or effects? +/// stroke a solid color, and no stroke with dashes, a width profile, pressure, tilt, bearing, +/// rotation or wheel, arrowheads, a brush or effects? fn local_paint(n: &Node) -> bool { use vectorcraft_doc::AppearanceItem; let solid = |p: &vectorcraft_color::Paint| matches!(p, vectorcraft_color::Paint::Solid { .. } | vectorcraft_color::Paint::None); @@ -379,6 +379,7 @@ fn local_paint(n: &Node) -> bool { && s.tilt.is_none() && s.bearing.is_none() && s.rotation.is_none() + && s.wheel.is_none() && s.start_arrow.is_none() && s.end_arrow.is_none() && s.brush.is_none() diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index e4811418c7..3c90518da7 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -10,8 +10,9 @@ //! Smart Guides ([`DrawSnap`]: an anchor, a path, in line with the art), hovering too; the points //! between follow the hand. The Paintbrush records the pen pressure of each point (a stroke a pen //! pressed less than fully on sends `[x, y, pressure]` points) for pressure-sensitive brushes, and -//! the pen's tilt and barrel rotation where the pen reads them (`[x, y, pressure, tiltX, tiltY, -//! rotation]` points, `null` for what a point lacks) for brushes that vary with them. The Blob +//! the pen's tilt, barrel rotation and airbrush finger wheel where the pen reads them (`[x, y, +//! pressure, tiltX, tiltY, rotation, wheel]` points, `null` for what a point lacks) for brushes +//! that vary with them. The Blob //! Brush and Eraser also record pressure when their Size varies with Pressure. The other tools //! collect the drag polyline (shown as an overlay) and run one command on release. With Shift //! held, the Blob Brush's points stay on the horizontal or @@ -51,7 +52,7 @@ pub struct GestureTool { /// The pen pressure of each of `points` (the Paintbrush, and the Blob Brush and the Eraser /// with `size_pressure`). pressures: Vec, - /// The pen's tilt and rotation at each of `points` (the Paintbrush only). + /// The pen's tilt, rotation and wheel at each of `points` (the Paintbrush only). poses: Vec>, active: bool, began: bool, @@ -250,7 +251,8 @@ impl GestureTool { self.id != "pencil" || self.live_preview } - /// Add a stroke sample, with the pen's pressure, tilt and rotation of the event `ev` there. + /// Add a stroke sample, with the pen's pressure, tilt, rotation and wheel of the event `ev` + /// there. fn push(&mut self, p: Point, ev: &PointerEvent) { self.points.push(p); if self.id == "paintbrush" || (self.varies_size() && self.size_pressure) { @@ -357,20 +359,28 @@ impl GestureTool { (self.varies_size() && self.size_pressure && !self.smoothing && pressed).then_some(self.pressures.as_slice()) } - /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation]` when a pen read its tilt or - /// rotation anywhere along it (`null` for what a point lacks, and for the pressure of a stroke + /// The stroke's points: `[x, y, pressure, tiltX, tiltY, rotation, wheel]` when a pen read its + /// wheel anywhere along it, else `[x, y, pressure, tiltX, tiltY, rotation]` when it read its + /// tilt or rotation anywhere (`null` for what a point lacks, and for the pressure of a stroke /// pressed fully all along), else `[x, y, pressure]` when a pen pressed less than fully /// anywhere (a mouse always presses fully), else `[x, y]`. fn stroke_json(&self) -> Value { let n = self.points.len(); let pressed = self.pressures.len() == n && self.pressures.iter().any(|p| *p < 1.0); - let posed = self.poses.len() == n && self.poses.iter().flatten().any(|q| q.tilt.is_some() || q.rotation.is_some()); + let poses = || self.poses.iter().flatten(); + let wheeled = self.poses.len() == n && poses().any(|q| q.wheel.is_some()); + let posed = wheeled || (self.poses.len() == n && poses().any(|q| q.tilt.is_some() || q.rotation.is_some())); let round = |v: f32, k: f64| (f64::from(v) * k).round() / k; if posed { let points = self.points.iter().zip(&self.pressures).zip(&self.poses).map(|((p, f), q)| { let q = q.unwrap_or_default(); let (tilt, rotation) = (q.tilt.map(|t| t.map(|v| round(v, 100.0))), q.rotation.map(|r| round(r, 100.0))); - json!([p.x, p.y, pressed.then(|| round(*f, 1000.0)), tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + let pressure = pressed.then(|| round(*f, 1000.0)); + if wheeled { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation, q.wheel.map(|w| round(w, 1000.0))]) + } else { + json!([p.x, p.y, pressure, tilt.map(|t| t[0]), tilt.map(|t| t[1]), rotation]) + } }); Value::Array(points.collect()) } else if pressed { diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index a0fe487289..18089105e5 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -82,7 +82,7 @@ fn paintbrush_sends_pen_tilt_and_rotation() { let Some(Action::Preview(_, v)) = last.first() else { panic!("{last:?}") }; v["points"].clone() }; - let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r }); + let leaning = |x: f32, r: Option| Some(PenPose { tilt: Some([x, -10.0]), rotation: r, wheel: None }); assert_eq!( stroke("paintbrush", 0.5, [leaning(30.0, Some(45.0)), leaning(40.0, Some(-90.0)), None]), json!([[0.0, 0.0, 0.5, 30.0, -10.0, 45.0], [40.0, 0.0, 0.5, 40.0, -10.0, 270.0], [80.0, 0.0, 0.5, null, null, null]]) @@ -92,6 +92,12 @@ fn paintbrush_sends_pen_tilt_and_rotation() { // A pose that reads nothing is a mouse's. assert_eq!(stroke("paintbrush", 1.0, [Some(PenPose::default()); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); assert_eq!(stroke("pencil", 0.5, [leaning(30.0, Some(45.0)); 3]), json!([[0.0, 0.0], [40.0, 0.0], [80.0, 0.0]])); + // An airbrush pen's finger wheel comes seventh, and a point without it sends null. + let wheel = |w: f32| Some(PenPose { wheel: Some(w), ..PenPose::default() }); + assert_eq!( + stroke("paintbrush", 1.0, [wheel(0.0), wheel(0.25), None]), + json!([[0.0, 0.0, null, null, null, null, 0.0], [40.0, 0.0, null, null, null, null, 0.25], [80.0, 0.0, null, null, null, null, null]]) + ); } #[test] diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 9b53d2404c..0f4a905443 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -43,8 +43,8 @@ pub struct PointerEvent { pub backquote: bool, #[serde(default = "one")] pub pressure: f32, - /// The pen's tilt and barrel rotation, when the pointer is a pen that reads either (a mouse: - /// `None`). + /// The pen's tilt, barrel rotation and finger wheel, when the pointer is a pen that reads any of + /// them (a mouse: `None`). #[serde(default, skip_serializing_if = "Option::is_none")] pub pen: Option, } @@ -55,23 +55,27 @@ fn one() -> f32 { /// How a pen is held, as far as it reads it. Tilt is in degrees, each −90..90 as Pointer Events /// give it, in document axes: `[x, y]`, x positive when the pen leans to the right and y positive -/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). +/// when it leans down the page. Rotation is the barrel's, in degrees clockwise (0..360). The wheel +/// is where an airbrush pen's finger wheel is set, 0..1 from one end of its travel to the other. #[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PenPose { #[serde(default, skip_serializing_if = "Option::is_none")] pub tilt: Option<[f32; 2]>, #[serde(default, skip_serializing_if = "Option::is_none")] pub rotation: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wheel: Option, } impl PenPose { - /// Within its ranges: each tilt is clamped to −90..90 and the rotation brought into 0..360; a - /// tilt or rotation that is not a number is left out. + /// Within its ranges: each tilt is clamped to −90..90, the rotation brought into 0..360 and the + /// wheel clamped to 0..1; a tilt, rotation or wheel that is not a number is left out. pub fn sanitized(self) -> Self { let tilt = self.tilt.filter(|t| t.iter().all(|v| v.is_finite())).map(|t| t.map(|v| v.clamp(-90.0, 90.0))); // `rem_euclid` can round a tiny negative angle up to 360 itself. let rotation = self.rotation.filter(|r| r.is_finite()).map(|r| r.rem_euclid(360.0)).map(|r| if r >= 360.0 { 0.0 } else { r }); - Self { tilt, rotation } + let wheel = self.wheel.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 1.0)); + Self { tilt, rotation, wheel } } } @@ -89,14 +93,15 @@ impl PointerEvent { } /// The pen's tilt and rotation of a pointer event given as JSON (control channel, MCP): /// `tiltX` and `tiltY` (degrees, −90..90, in document axes; one without the other is 0) and - /// `rotation` (degrees clockwise, brought into 0..360). Values that are not numbers are left - /// out; `None` without any. + /// `rotation` (degrees clockwise, brought into 0..360) and `wheel` (an airbrush pen's finger + /// wheel, clamped to 0..1). Values that are not numbers are left out; `None` without any. pub fn json_pen(e: &Value) -> Option { let num = |k: &str| e.get(k).and_then(Value::as_f64).filter(|f| f.is_finite()); let tilt = |v: Option| v.map_or(0.0, |v| v.clamp(-90.0, 90.0) as f32); let (tx, ty) = (num("tiltX"), num("tiltY")); let tilt = (tx.is_some() || ty.is_some()).then(|| [tilt(tx), tilt(ty)]); - let pose = PenPose { tilt, rotation: num("rotation").map(|r| r.rem_euclid(360.0) as f32) }.sanitized(); + let rotation = num("rotation").map(|r| r.rem_euclid(360.0) as f32); + let pose = PenPose { tilt, rotation, wheel: num("wheel").map(|w| w.clamp(0.0, 1.0) as f32) }.sanitized(); (pose != PenPose::default()).then_some(pose) } /// How long the pointer then holds still, in seconds, from a JSON pointer event's `holdMs` @@ -110,11 +115,13 @@ impl PointerEvent { v.get("backquote").map_or(Ok(default), |b| b.as_bool().ok_or_else(|| "`backquote` must be a boolean".to_owned())) } /// Checks the optional keys of a JSON pointer event (control channel, MCP): `pressure`, - /// `holdMs`, `tiltX`, `tiltY` and `rotation` must be numbers, and `space` must be `doc` or - /// `screen`. A key that is absent or null keeps its default. + /// `holdMs`, `tiltX`, `tiltY`, `rotation` and `wheel` must be numbers, and `space` must be + /// `doc` or `screen`. A key that is absent or null keeps its default. pub fn json_check(e: &Value) -> Result<(), String> { let given = |k: &str| e.get(k).filter(|v| !v.is_null()); - if let Some(k) = ["pressure", "holdMs", "tiltX", "tiltY", "rotation"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) { + if let Some(k) = + ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"].into_iter().find(|k| given(k).is_some_and(|v| v.as_f64().is_none())) + { return Err(format!("`{k}` must be a number")); } if given("space").is_some_and(|v| !matches!(v.as_str(), Some("doc" | "screen"))) { @@ -154,13 +161,13 @@ mod tests { use serde_json::json; for ok in [ json!({}), - json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "space": "screen"}), + json!({"pressure": 0.5, "holdMs": 10, "tiltX": -5, "tiltY": 5, "rotation": 400, "wheel": 0.25, "space": "screen"}), json!({"pressure": null, "space": null}), json!({"space": "doc"}), ] { assert_eq!(PointerEvent::json_check(&ok), Ok(()), "{ok}"); } - for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation"] { + for k in ["pressure", "holdMs", "tiltX", "tiltY", "rotation", "wheel"] { for bad in [json!("1"), json!(true), json!([1])] { assert_eq!(PointerEvent::json_check(&json!({k: bad})), Err(format!("`{k}` must be a number")), "{k}: {bad}"); } @@ -169,6 +176,19 @@ mod tests { assert_eq!(PointerEvent::json_check(&json!({"space": bad})), Err("`space` must be doc or screen".to_owned()), "{bad}"); } } + + #[test] + fn json_pen_reads_the_wheel_within_its_range() { + use serde_json::json; + let wheel = |v: Value| PointerEvent::json_pen(&json!({"wheel": v})).and_then(|q| q.wheel); + assert_eq!(wheel(json!(0.25)), Some(0.25)); + assert_eq!(wheel(json!(-3)), Some(0.0)); + assert_eq!(wheel(json!(7)), Some(1.0)); + assert_eq!(wheel(json!(null)), None); + assert_eq!(PointerEvent::json_pen(&json!({"wheel": 0.5})), Some(PenPose { wheel: Some(0.5), ..PenPose::default() })); + assert_eq!(PenPose { wheel: Some(f32::NAN), ..PenPose::default() }.sanitized(), PenPose::default()); + assert_eq!(PenPose { wheel: Some(1.5), ..PenPose::default() }.sanitized().wheel, Some(1.0)); + } } /// Keys tools care about. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 8597607717..25765c7719 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8957,8 +8957,8 @@ fn frame_moves_stop_at_the_button_up() { let up = egui::Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c), egui::Event::PointerMoved(d)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; - let after = PenPose { tilt: Some([50.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; + let after = PenPose { tilt: Some([50.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, after), (0.8, after)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -8983,7 +8983,7 @@ fn frame_moves_keep_the_last_move_when_the_button_went_up_elsewhere() { let up = egui::Event::PointerButton { pos: up_at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; let events = vec![egui::Event::PointerMoved(a), egui::Event::PointerMoved(b), up, egui::Event::PointerMoved(c)]; let feed = StylusFeed::default(); - let at_b = PenPose { tilt: Some([20.0, 0.0]), rotation: None }; + let at_b = PenPose { tilt: Some([20.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.4, PenPose::default()), (0.6, at_b), (0.7, PenPose::default())] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -9009,7 +9009,7 @@ fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() { assert_eq!(mouse, [(a, None, None), (b, None, None)], "the last move follows the normal pointer path"); // A macOS pen: the feed kept a pressure and a pose for each move, the last for the last. let feed = StylusFeed::default(); - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: None }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }; for (p, pose) in [(0.9, leaning), (0.3, leaning), (0.0, PenPose::default()), (0.5, leaning)] { feed.set_move(crate::stylus::PenSample { pressure: p, pose, ..Default::default() }); } @@ -9488,7 +9488,7 @@ fn the_hosts_pen_tilt_and_rotation_reach_the_paintbrush() { assert_eq!(cmd, "path.freehand"); p["points"].as_array().unwrap().iter().map(|s| [3, 4, 5].map(|i| s.get(i).and_then(serde_json::Value::as_f64))).collect() }; - let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0) }; + let leaning = PenPose { tilt: Some([30.0, 0.0]), rotation: Some(45.0), wheel: None }; let points = stroke(&mut app, 260.0, Some(leaning)); assert!(!points.is_empty() && points.iter().all(|p| *p == [Some(30.0), Some(0.0), Some(45.0)]), "{points:?}"); // With the view rotated 90° clockwise, a pen leaning to the right of the screen leans up the @@ -9519,7 +9519,7 @@ fn moves_in_the_release_frame_reach_the_paintbrush_with_their_tilt() { let moved = |tilt: f32| { feed.set_move(crate::stylus::PenSample { pressure: 0.5, - pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, ..Default::default() }) }; @@ -9562,8 +9562,11 @@ fn the_last_move_of_a_frame_keeps_its_own_tilt() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); let at = |x: f64| xf.to_screen(Point::new(x, 300.0)); let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; - let sample = - |tilt: f32| crate::stylus::PenSample { pressure: 0.5, pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0) }, ..Default::default() }; + let sample = |tilt: f32| crate::stylus::PenSample { + pressure: 0.5, + pose: PenPose { tilt: Some([tilt, 0.0]), rotation: Some(0.0), wheel: None }, + ..Default::default() + }; feed.set_move(sample(10.0)); frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(300.0)), button(at(300.0), true)]); feed.set_move(sample(20.0)); diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8bc0e66a2e..072dd86d13 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -254,7 +254,8 @@ fn scatter_mode(d: &Dialog, key: &str) -> Variation { Variation::parse(&d.str(&mode_key(key))).unwrap_or_default() } -/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing or rotation. +/// How an art brush's width varies: Fixed, or with the pen's pressure, tilt, bearing, rotation or +/// wheel. fn art_width_mode(d: &Dialog) -> Variation { Variation::parse(&d.str("widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } @@ -434,7 +435,6 @@ fn flips(ui: &mut egui::Ui, d: &mut Dialog) { fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { let labels = [tl!("Size:"), tl!("Spacing:"), tl!("Scatter:"), tl!("Rotation:")]; - let modes = Variation::ALL.map(Variation::label); egui::Grid::new("brush-options-scatter").num_columns(4).spacing([8.0, 8.0]).show(ui, |ui| { for (((key, suffix), range), text) in SCATTER.into_iter().zip(Scatter::RANGES).zip(labels) { super::swatch_options::label(ui, text); @@ -448,7 +448,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { } }); } - if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let modes: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-scatter-mode", key), mode.label(), &modes, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } ui.end_row(); @@ -467,7 +469,7 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { super::form::slider_field_named(ui, d, "width", tl!("Width:"), range.0..=range.1, "%", &|_| rail); let mode = art_width_mode(d); number(ui, d, "widthMax", range, "%", mode.follows_pen()); - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation]; + let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; if let Some(m) = widgets::dropdown(ui, "brush-art-width-mode", mode.label(), &modes.map(Variation::label), 104.0).and_then(|i| modes.get(i)) { d.fields.insert("widthMode".into(), json!(m.id())); } diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index bcc880958a..2f43f12d21 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -310,8 +310,9 @@ fn calligraphic_body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert(key.into(), json!(v)); } let mode = Variation::parse(&d.str(&mode_key(key))).unwrap_or_default(); - let labels = Variation::ALL.map(Variation::label); - if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| Variation::ALL.get(i)) { + let offered = Variation::offered(key == "size"); + let labels: Vec<&str> = offered.iter().map(|m| m.label()).collect(); + if let Some(m) = widgets::dropdown(ui, ("brush-mode", key), mode.label(), &labels, 104.0).and_then(|i| offered.get(i)) { d.fields.insert(mode_key(key), json!(m.id())); } label(ui, tl!("Variation:")); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..d9bb9e4361 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2092,6 +2092,7 @@ font-technology Variable Променливи Pressure Натиск Tilt Наклон Bearing Азимут + Stylus Wheel Колелце на писалката Shape: Форма: Bristle Length: Дължина на косъма: Bristle Density: Плътност на косъмчетата: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..f8bd9ab74c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3222,6 +3222,7 @@ antiAlias Sharp Oštro Pressure Pritisak Tilt Nagib Bearing Smjer + Stylus Wheel Kotačić olovke Random Nasumično Scatter Raspršeno Color Burn Tamnjenje boje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..baa1d2778e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -481,6 +481,7 @@ antiAlias Sharp Nítid Batch Lot Batch… Lot… Bearing Orientació + Stylus Wheel Roda del llapis Before Last: Abans de l’últim: Begin Recording Comença a enregistrar Exclude from playback Exclou de la reproducció diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..cfe29bc510 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3260,6 +3260,7 @@ antiAlias Sharp Ostré # Command labels and other interface strings Art Obrazový Bearing Azimut + Stylus Wheel Kolečko pera Bristle Štětinový Calligraphic Kaligrafický Dots Body diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..c5f1439192 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3006,6 +3006,7 @@ antiAlias Sharp Skarp Width Point Edit Redigér breddepunkt Art Kunst Bearing Retning + Stylus Wheel Pennehjul Bristle Borst Calligraphic Kalligrafisk Dots Prikker diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..92c36e8972 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2126,6 +2126,7 @@ file-filter Templates Vorlagen Pressure Druck Tilt Neigung Bearing Richtung + Stylus Wheel Stiftrad Shape: Form: Bristle Length: Borstenlänge: Bristle Density: Borstendichte: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..4a2951a4c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1814,6 +1814,7 @@ font-technology Variable Μεταβλητές Pressure Πίεση Tilt Κλίση Bearing Αζιμούθιο + Stylus Wheel Τροχός γραφίδας Shape: Σχήμα: New Brush… Νέο πινέλο… New Brush Νέο πινέλο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..e2200b96a3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2164,6 +2164,7 @@ font-technology Variable Variables Pressure Presión Tilt Inclinación Bearing Orientación + Stylus Wheel Rueda del lápiz Shape: Forma: Bristle Length: Longitud de cerdas: Bristle Density: Densidad de cerdas: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..3e8e3a1bf1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3202,6 +3202,7 @@ antiAlias Sharp Terävä Width Point Edit Leveyspisteen muokkaus Art Kuvitus Bearing Suunta + Stylus Wheel Kynän rulla Bristle Harjas Calligraphic Kalligrafinen Dots Pisteet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..af0ddd3e0e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2156,6 +2156,7 @@ font-technology Variable Variables Pressure Pression Tilt Inclinaison Bearing Orientation + Stylus Wheel Molette du stylet Shape: Forme : Bristle Length: Longueur des soies : Bristle Density: Densité des soies : diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..94161d0d0a 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -559,6 +559,7 @@ antiAlias Sharp शार्प Batch Trace Folder फ़ोल्डर बैच ट्रेस करें Batch… बैच… Bearing दिशा + Stylus Wheel स्टाइलस व्हील Before Last: अंत के पहले: Begin Recording रिकॉर्डिंग शुरू करें Begin Undo Group पूर्ववत समूह शुरू करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..8fc37af0b6 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -409,6 +409,7 @@ font-technology Variable Változó Basic Latin Alap latin Batch Kötegelt feldolgozás Bearing Irány + Stylus Wheel Tollkerék Begin Recording Felvétel indítása Exclude from playback Kizárás a lejátszásból Include in playback Bevonás a lejátszásba diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..c8c4505bfb 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3006,6 +3006,7 @@ antiAlias Sharp Tajam Width Point Edit Edit titik lebar Art Seni Bearing Arah + Stylus Wheel Roda stylus Bristle Bristle Calligraphic Kaligrafis Dots Titik diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..c222cf51e9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2202,6 +2202,7 @@ file-filter Templates Modelli Pressure Pressione Tilt Inclinazione Bearing Orientamento + Stylus Wheel Rotella dello stilo Shape: Forma: Bristle Length: Lunghezza setole: Bristle Density: Densità setole: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..effe1443dc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2411,6 +2411,7 @@ antiAlias Sharp シャープ Pressure 筆圧 Tilt 傾き Bearing 方位 + Stylus Wheel スタイラスホイール Shape: 形状: Bristle Length: 毛の長さ: Bristle Density: 毛の密度: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..08c5bbe6c2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2844,6 +2844,7 @@ antiAlias Sharp მკვეთრი Width Point Edit სიგანის წერტილის რედაქტირება Art ნახატი Bearing აზიმუტი + Stylus Wheel სტილუსის ბორბალი Bristle ჯაგრისი Calligraphic კალიგრაფიული Dots წერტილები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..e391ccd8e7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2401,6 +2401,7 @@ antiAlias Sharp 날카롭게 Pressure 필압 Tilt 기울기 Bearing 방위 + Stylus Wheel 스타일러스 휠 Shape: 모양: Bristle Length: 강모 길이: Bristle Density: 강모 밀도: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..2af4f6c27d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3020,6 +3020,7 @@ antiAlias Sharp Scherp Width Point Edit Breedtepunt bewerken Art Illustratie Bearing Richting + Stylus Wheel Pennenwiel Bristle Borstel Calligraphic Kalligrafisch Dots Stippen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..cec399ca2b 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3139,6 +3139,7 @@ antiAlias Sharp Ostre Width Point Edit Edycja punktu szerokości Art Artystyczny Bearing Kierunek + Stylus Wheel Kółko pióra Bristle Włosiankowy Calligraphic Kaligraficzny Dots Kropki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..9cd91a2e7b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5004,6 +5004,7 @@ axis Both Ambos Pressure Pressão Tilt Inclinação Bearing Orientação + Stylus Wheel Roda da caneta Bristle Length: Comprimento das Cerdas: Bristle Density: Densidade das Cerdas: Bristle Thickness: Espessura das Cerdas: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..2aca4dd3db 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2189,6 +2189,7 @@ file-filter Templates Шаблоны Pressure Нажим Tilt Наклон Bearing Азимут + Stylus Wheel Колесико пера Shape: Форма: Bristle Length: Длина щетинок: Bristle Density: Плотность щетинок: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..45887baa89 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2103,6 +2103,7 @@ font-technology Variable Variabla Pressure Tryck Tilt Lutning Bearing Riktning + Stylus Wheel Pennhjul Shape: Form: Bristle Length: Borstlängd: Bristle Density: Borsttäthet: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..c1b71f8997 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1984,6 +1984,7 @@ font-technology Variable Değişken Pressure Basınç Tilt Eğim Bearing Yön + Stylus Wheel Kalem tekerleği Shape: Şekil: Bristle Length: Kıl Uzunluğu: Bristle Density: Kıl Yoğunluğu: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..56ac882927 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2194,6 +2194,7 @@ file-filter Templates Шаблони Pressure Натиск Tilt Нахил Bearing Азимут + Stylus Wheel Коліщатко пера Shape: Форма: Bristle Length: Довжина щетинок: Bristle Density: Щільність щетинок: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..1c4c781465 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -331,6 +331,7 @@ font-technology Variable Biến thiên Basic Latin Latin cơ bản Batch Hàng loạt Bearing Hướng + Stylus Wheel Bánh xe bút Begin Recording Bắt đầu ghi Exclude from playback Loại khỏi phát lại Include in playback Đưa vào phát lại diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..3acc1575b0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2059,6 +2059,7 @@ file-filter Templates 模板 Pressure 压力 Tilt 倾斜 Bearing 方位 + Stylus Wheel 光笔滚轮 Shape: 形状: Bristle Length: 鬃毛长度: Bristle Density: 鬃毛密度: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..e6086aa8cd 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3251,6 +3251,7 @@ file-filter Templates 範本 Pressure 壓力 Tilt 傾斜 Bearing 方位 + Stylus Wheel 光筆滾輪 Shape: 形狀: Bristle Length: 鬃毛長度: Bristle Density: 鬃毛密度: diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 8f29c70475..148e9be140 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -98,8 +98,9 @@ fn preview(ui: &Ui, doc: &Document, def: &Value, key: u64, size: egui::Vec2) -> /// What a stroke preview of brush definition `def`, `w` × `h` pt, renders: a copy of `resources` /// (a document whose patterns, symbols, swatches and images the brush art may use) without its art, /// and a stroke painted with the brush across it. The stroke goes from light to heavy pen pressure -/// and back, from an upright pen to one lying flat and back, and once round every bearing and barrel -/// rotation, so brushes that vary with the pen show how they vary. +/// and back, from an upright pen to one lying flat and back, once round every bearing and barrel +/// rotation, and from one end of an airbrush pen's finger wheel to the other and back, so brushes +/// that vary with the pen show how they vary. fn preview_doc(resources: &Document, def: &Value, w: f64, h: f64) -> Option { let mut doc = resources.clone(); let layer = doc.alloc_id(); @@ -113,6 +114,7 @@ fn preview_doc(resources: &Document, def: &Value, w: f64, h: f64) -> Option