Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Brush strokes carry their timing: the first moves count, smoothing feels the same on any device, a held airbrush builds up (#2110)

Tanish Mankua680ed22c96f
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 94d62069a..e50be669f 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -412,6 +412,12 @@ impl LiveStroke {
self.mirrors.iter().zip(&self.mirror_distinct).filter(|(_, distinct)| **distinct).fold(bounds, |b, (r, _)| b.union(&r.bounds()))
}
+ /// Does the stroke change with time while the pointer is held still (airbrush Build-up, or
+ /// smoothing still catching up)? See `photocraft_paint::dynamics::DabGenerator::wants_time`.
+ pub fn wants_time(&self) -> bool {
+ self.renderer.wants_time()
+ }
+
/// Render more points; returns the rectangle that changed. The doc shows the stroke as
/// committing it now would: with smoothing, the brush lags behind the pointer and catches up
/// when the stroke ends, so that catch-up tail is drawn too (and redrawn on every step), and
diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs
index 8000c42ed..dc53e9b86 100644
--- a/crates/paint/src/brush_tests.rs
+++ b/crates/paint/src/brush_tests.rs
@@ -615,6 +615,48 @@ fn smoothing_modes() {
assert!(out.last().unwrap().x < 70.0, "{}", out.last().unwrap().x);
}
+#[test]
+fn smoothing_pulls_by_time_not_by_how_often_the_device_reports() {
+ // The pointer jumps 100 px and is held there for 32 ms, reported at 1000 Hz or about 60 Hz.
+ let cfg = Smoothing { amount: 0.8, catch_up: true, catch_up_on_end: false, ..Default::default() };
+ let run = |interval: f64| {
+ let mut s = Smoother::new(&cfg, 1.0);
+ let mut out = Vec::new();
+ s.push(StrokePoint::new(0.0, 0.0, 1.0), &mut out);
+ let mut t = 0.0;
+ while t < 32.0 {
+ t += interval;
+ s.push(StrokePoint { time: t, ..StrokePoint::new(100.0, 0.0, 1.0) }, &mut out);
+ }
+ out.last().map_or(0.0, |p| p.x)
+ };
+ let (fast, slow) = (run(1.0), run(16.0));
+ // Two 16 ms steps of a 0.2 pull: 1 - 0.8² = 36 % of the way.
+ assert!((slow - 36.0).abs() < 1e-4, "{slow}");
+ assert!((fast - slow).abs() < 1e-4, "1000 Hz {fast} vs 60 Hz {slow}");
+ // Without timestamps each point is one step, as before.
+ let mut s = Smoother::new(&cfg, 1.0);
+ let mut out = Vec::new();
+ for x in [0.0, 100.0] {
+ s.push(StrokePoint::new(x, 0.0, 1.0), &mut out);
+ }
+ assert!((out.last().map_or(0.0, |p| p.x) - 20.0).abs() < 1e-4);
+}
+
+#[test]
+fn smoothing_without_catch_up_stops_while_the_pointer_pauses() {
+ let cfg = Smoothing { amount: 0.8, catch_up: false, catch_up_on_end: false, ..Default::default() };
+ let mut s = Smoother::new(&cfg, 1.0);
+ let mut out = Vec::new();
+ s.push(StrokePoint::new(0.0, 0.0, 1.0), &mut out);
+ s.push(StrokePoint { time: 16.0, ..StrokePoint::new(100.0, 0.0, 1.0) }, &mut out);
+ let n = out.len();
+ for t in [32.0, 48.0, 64.0] {
+ s.push(StrokePoint { time: t, ..StrokePoint::new(100.0, 0.0, 1.0) }, &mut out);
+ }
+ assert_eq!(out.len(), n, "held still: the brush doesn't move");
+}
+
#[test]
fn pose_overrides_stylus_values() {
let b = BrushSettings {
diff --git a/crates/paint/src/dynamics.rs b/crates/paint/src/dynamics.rs
index bd84ed4b3..3318ca39c 100644
--- a/crates/paint/src/dynamics.rs
+++ b/crates/paint/src/dynamics.rs
@@ -12,6 +12,8 @@ use crate::{Dab, StrokePoint};
/// Maximum pulled-string length at 100 % smoothing, in screen pixels.
pub const MAX_STRING_PX: f64 = 100.0;
+/// Stroke time over which exponential smoothing moves its fraction of the way to the pointer.
+pub const SMOOTHING_STEP_MS: f64 = 16.0;
/// With Spacing unchecked, one dab per this many milliseconds of stroke time, so faster strokes
/// space their dabs further apart (Photoshop: "the speed of the cursor determines the spacing").
@@ -88,20 +90,41 @@ impl Smoother {
}
return;
}
- // Exponential: each iteration moves `a` of the way towards the pointer.
+ // Exponential: every SMOOTHING_STEP_MS of stroke time moves `a` of the way towards the
+ // pointer, so the feel doesn't depend on how often the device reports. Input without
+ // timestamps takes one step per point.
let a = 1.0 - amount.min(0.95);
- let iters = match prev_input {
- Some(q) if self.cfg.catch_up && p.time > q.time => ((p.time - q.time) / 16.0).round().clamp(1.0, 64.0) as usize,
- _ => 1,
+ let dt = prev_input.map_or(0.0, |q| p.time - q.time);
+ let still = prev_input.is_some_and(|q| q.x == p.x && q.y == p.y);
+ if still && !self.cfg.catch_up {
+ // Without Stroke Catch-Up the brush stops while the pointer pauses (Photoshop).
+ return;
+ }
+ let (iters, step) = if dt > 0.0 && dt.is_finite() {
+ let steps = dt / SMOOTHING_STEP_MS;
+ let iters = steps.ceil().clamp(1.0, 64.0);
+ // Each of `iters` moves covers `steps / iters` steps' worth of pull.
+ (iters as usize, 1.0 - (1.0 - a).powf(steps.min(64.0) / iters))
+ } else {
+ (1, a)
};
let mut cur = pos;
for _ in 0..iters {
- cur = StrokePoint { x: cur.x + (p.x - cur.x) * a, y: cur.y + (p.y - cur.y) * a, ..p };
+ cur = StrokePoint { x: cur.x + (p.x - cur.x) * step, y: cur.y + (p.y - cur.y) * step, ..p };
out.push(cur);
}
self.pos = Some(cur);
}
+ /// Is Stroke Catch-Up still pulling the brush towards a pointer that has stopped? Then the
+ /// stroke needs time to keep passing (repeats of the last point) while the pointer is held.
+ pub fn lagging(&self) -> bool {
+ match (self.active() && self.cfg.catch_up && !self.cfg.pulled_string, self.pos, self.last_input) {
+ (true, Some(pos), Some(last)) => (pos.x - last.x).abs() + (pos.y - last.y).abs() > 0.01,
+ _ => false,
+ }
+ }
+
/// End of stroke: with Catch-Up On Stroke End the brush finishes at the last pointer position.
pub fn finish(&mut self, out: &mut Vec<StrokePoint>) {
if !self.active() || !self.cfg.catch_up_on_end {
@@ -599,6 +622,12 @@ pub struct DabGenerator {
}
impl DabGenerator {
+ /// Does the stroke change with time while the pointer is held still (airbrush Build-up, or
+ /// smoothing still catching up)? The canvas then keeps feeding it the held point.
+ pub fn wants_time(&self) -> bool {
+ self.walker.interval.is_some() || self.smoother.lagging()
+ }
+
pub fn new(brush: &BrushSettings, zoom: f32) -> Self {
let brush = brush.bounded_for_render();
let interval = brush.build_up.then(|| 1000.0 / f64::from(brush.build_up_rate.clamp(0.1, 1000.0)));
diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs
index 65fb825c6..290e72830 100644
--- a/crates/paint/src/render.rs
+++ b/crates/paint/src/render.rs
@@ -517,6 +517,11 @@ impl StrokeRenderer {
self.dual_buf = duals;
}
+ /// See [`DabGenerator::wants_time`].
+ pub fn wants_time(&self) -> bool {
+ self.generator.wants_time()
+ }
+
/// Feed input points (any chunking gives the same result).
pub fn push(&mut self, pts: &[StrokePoint]) {
self.generator.push(pts, &mut self.dab_buf, &mut self.dual_buf);
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 594d0f427..c388a0730 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -259,6 +259,15 @@ enum EngineStroke {
}
impl EngineStroke {
+ /// The brush engine's strokes can change while the pointer is held still (see
+ /// `LiveStroke::wants_time`); the retouch strokes don't.
+ fn wants_time(&self) -> bool {
+ match self {
+ EngineStroke::Brush(l) => l.wants_time(),
+ EngineStroke::Retouch(_) | EngineStroke::Dab(_) => false,
+ }
+ }
+
fn doc(&self) -> &std::sync::Arc<photocraft_doc::Document> {
match self {
Self::Brush(s) => &s.doc,
@@ -470,12 +479,15 @@ fn feed_live_stroke(app: &mut PhotocraftApp) {
}
let (Some(l), Some(d)) = (app.live_stroke.as_mut(), app.drag.as_ref()) else { return };
let pose = &app.stylus.stroke;
+ // The same times `stroke_points` gives the commit (from the drag's first point).
+ let t0 = app.stylus.point_ms(0);
let pts: Vec<_> = (l.fed..d.points.len())
.filter_map(|i| {
let p = d.points.get(i)?;
let t = pose.get(i).or(pose.last()).copied().unwrap_or_default();
let mut sp = photocraft_engine::paint::StrokePoint::new(p[0], p[1], p[2] as f32);
(sp.tilt_x, sp.tilt_y, sp.rotation) = (t[0], t[1], t[2]);
+ sp.time = app.stylus.point_ms(i) - t0;
Some(sp)
})
.collect();
@@ -489,6 +501,26 @@ fn feed_live_stroke(app: &mut PhotocraftApp) {
}
}
+/// While a stroke is held still, its point repeats this often (in ms) so time-based brush
+/// features (airbrush build-up, smoothing catch-up) keep going, as when the pen moves.
+const HOLD_REPEAT_MS: f64 = 16.0;
+
+/// Is the live stroke one that changes while the pointer is held still (airbrush Build-up, or
+/// smoothing catching up)? Only then does a held pointer repeat its point and keep repainting.
+fn stroke_wants_time(app: &PhotocraftApp) -> bool {
+ app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time())
+}
+
+/// Time of sample `k` of the `n` samples a frame delivered, spread evenly after `base` (the
+/// previous point) up to `now` (this frame): egui's pointer events carry no timestamps.
+pub(crate) fn spread_ms(base: f64, now: f64, k: usize, n: usize) -> f64 {
+ // Not after `base` (or not comparable, NaN): every sample takes the frame time.
+ if n == 0 || now.partial_cmp(&base) != Some(std::cmp::Ordering::Greater) {
+ return now;
+ }
+ base + (now - base) * (k + 1) as f64 / n as f64
+}
+
/// Tools whose gesture follows a freehand path (a polyline of the input points), so every pointer
/// sample the OS delivered improves the result. Other tools are driven by the pointer's latest
/// position (endpoints, anchors, guides), so feeding them a whole frame's moves only repeats work.
@@ -2574,6 +2606,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// A drag is only recognised once the pointer has moved past egui's click distance: the
// gesture starts where the button went down, not where it is now (#123).
let gesture_active_before = app.drag.is_some();
+ // Stroke timing: egui's events carry no timestamps, so a press takes the frame time and
+ // the moves below are spread between the previous point and this frame (`spread_ms`).
+ let now_ms = ui.input(|i| i.time) * 1000.0;
+ app.stylus.clock_ms = now_ms;
// Live painting tools start on the press, not once the pointer passes egui's click
// distance: the first dab shows at once. The drag recognised later continues that stroke,
// and a click (or a long press that never moved) just ends it.
@@ -2603,7 +2639,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let press_mods = if tool.is_type() { ctx.data(|d| d.get_temp(type_press)).unwrap_or(mods) } else { mods };
tool_event(app, ToolEvent::Down { x: d[0], y: d[1], pressure: app.stylus.pressure() }, press_mods);
}
- if buttons.dragged || buttons.stopped {
+ // A stroke started on the press takes its moves from the press on, not only once egui
+ // recognises a drag (past its click distance): otherwise the first few points are lost
+ // and the stroke starts with a straight segment and no pressure ramp.
+ let press_stroke_moving = press_stroke && app.drag.is_some();
+ if buttons.dragged || buttons.stopped || press_stroke_moving {
// Feed every pointer move the OS delivered this frame, not just the latest position, so
// a fast stroke is sampled densely and renders as a smooth curve instead of a coarse
// polyline. egui-winit pushes one `PointerMoved` per `CursorMoved`, and they accumulate
@@ -2633,16 +2673,24 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// A frame with no raw move still tracks a held gesture (a still pointer, a modifier
// change): fall back to the latest position, as the old code always did.
if positions.is_empty()
- && buttons.dragged
- && let Some(p) = response.interact_pointer_pos()
+ && (buttons.dragged || press_stroke_moving)
+ && let Some(p) = response.interact_pointer_pos().or(ui.input(|i| i.pointer.latest_pos()))
{
positions.push(p);
}
app.defer_live_stroke = true;
- for p in positions {
+ let base = app.stylus.last_point_ms().map_or(now_ms, |t| t.min(now_ms));
+ let n = positions.len();
+ for (k, p) in positions.into_iter().enumerate() {
+ app.stylus.clock_ms = spread_ms(base, now_ms, k, n);
let d = xf.to_doc(p);
tool_event(app, ToolEvent::Move { x: d[0], y: d[1], pressure: app.stylus.pressure() }, mods);
}
+ app.stylus.clock_ms = now_ms;
+ // A held pen keeps the clock running for airbrush build-up and smoothing catch-up.
+ if app.drag.is_some() && stroke_wants_time(app) {
+ ctx.request_repaint_after(std::time::Duration::from_millis(HOLD_REPEAT_MS as u64));
+ }
app.defer_live_stroke = false;
// One live-stroke update for the whole frame, not one per recovered sample.
feed_live_stroke(app);
@@ -3476,7 +3524,11 @@ fn tool_move(app: &mut PhotocraftApp, x: f64, y: f64, pressure: f32, mods: egui:
// ⇧: straight 0/45/90° strokes, 45° gradient angles (stroke_constraint.rs).
let last = d.points.last().map_or(d.start, |p| [p[0], p[1]]);
let [x, y] = crate::stroke_constraint::constrain(d.tool, &mut d.constrain, d.start, last, [x, y], mods.shift, zoom);
- if d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25) {
+ let moved = d.points.last().is_none_or(|p| (p[0] - x).abs() + (p[1] - y).abs() > 0.25);
+ // A held pen repeats its point now and then, so the stroke's time keeps advancing.
+ let held = app.stylus.last_point_ms().is_some_and(|t| app.stylus.clock_ms - t >= HOLD_REPEAT_MS)
+ && app.live_stroke.as_ref().is_some_and(|l| l.stroke.wants_time());
+ if moved || held {
d.points.push([x, y, pressure as f64]);
app.stylus.record_point();
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 1da4fb55f..1e37b7a52 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -1719,6 +1719,8 @@ mod stamp_tests;
#[cfg(test)]
mod alt_click_tests;
+#[cfg(test)]
+mod stroke_timing_tests;
#[cfg(test)]
mod polygon_lasso_tests;
diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/paint_mouse.rs
index 51245cb01..9bdd54eb7 100644
--- a/crates/ui-egui/src/paint_mouse.rs
+++ b/crates/ui-egui/src/paint_mouse.rs
@@ -273,9 +273,12 @@ mod tests {
let strokes = strokes(&h);
assert_eq!(strokes.len(), 2, "a Shift-click commits one connected stroke");
let points = strokes[1]["points"].as_array().unwrap();
- assert_eq!(points.len(), 2, "a click has the previous endpoint and clicked endpoint");
+ // The previous endpoint, then the clicked one. While the button is held, smoothing that is
+ // still catching up repeats the clicked point with later times.
assert_eq!(points[0][0], previous[0]);
assert_eq!(points[0][1], previous[1]);
+ let clicked = &points[1];
+ assert!(points[1..].iter().all(|p| p[0] == clicked[0] && p[1] == clicked[1]), "{points:?}");
assert!(alpha_at(&h, end + vec2(60.0, 40.0)) > 0.9, "the segment between the strokes is painted");
}
diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs
new file mode 100644
index 000000000..2211faad1
--- /dev/null
+++ b/crates/ui-egui/src/stroke_timing_tests.rs
@@ -0,0 +1,141 @@
+//! Brush strokes through the real canvas: the moves before egui recognises a drag reach the
+//! stroke, and stroke points carry the times the engine's time-based features need.
+
+use egui::{Modifiers, PointerButton, Pos2, vec2};
+use egui_kittest::Harness;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::ViewXform;
+use crate::state::Tool;
+
+fn harness() -> Harness<'static, PhotocraftApp> {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap();
+ app.sync_views();
+ app.ui.tool = Tool::Brush;
+ let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state(
+ |ui, app: &mut PhotocraftApp| {
+ let ctx = ui.ctx().clone();
+ if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
+ return;
+ }
+ egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
+ },
+ app,
+ );
+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
+ h.run_steps(4);
+ let v = &mut h.state_mut().ui.views[0];
+ v.zoom = 1.0;
+ v.center = [100.0, 50.0];
+ v.fit_pending = false;
+ h.run_steps(2);
+ h
+}
+
+fn screen(h: &Harness<'static, PhotocraftApp>, x: f32, y: f32) -> Pos2 {
+ let app = h.state();
+ let v = &app.ui.views[0];
+ let xf = ViewXform {
+ rect: crate::rulers::content_rect(app, app.last_canvas_rect),
+ zoom: v.zoom,
+ center: v.center,
+ flip: app.ui.view.flip_horizontal,
+ rotation: v.rotation,
+ };
+ xf.to_screen(x, y)
+}
+
+fn button(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32, down: bool) {
+ let p = screen(h, x, y);
+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+}
+
+fn move_to(h: &mut Harness<'static, PhotocraftApp>, x: f32, y: f32) {
+ let p = screen(h, x, y);
+ h.event(egui::Event::PointerMoved(p));
+ h.run_steps(1);
+}
+
+/// The points of the committed `paint.stroke`.
+fn committed_points(h: &Harness<'static, PhotocraftApp>) -> Vec<Vec<f64>> {
+ let (_, p) = h.state().session.journal.iter().rev().find(|(id, _)| id == "paint.stroke").cloned().expect("a committed stroke");
+ p["points"].as_array().expect("points").iter().map(|v| v.as_array().expect("point").iter().filter_map(Value::as_f64).collect()).collect()
+}
+
+#[test]
+fn moves_before_the_drag_threshold_reach_the_stroke() {
+ let mut h = harness();
+ move_to(&mut h, 20.0, 50.0);
+ button(&mut h, 20.0, 50.0, true);
+ // Small steps, each well inside egui's click distance from the press.
+ for x in [21.0, 22.0, 23.0] {
+ move_to(&mut h, x, 50.0);
+ }
+ for x in [40.0, 60.0] {
+ move_to(&mut h, x, 50.0);
+ }
+ button(&mut h, 60.0, 50.0, false);
+ h.run_steps(2);
+ let xs: Vec<f64> = committed_points(&h).iter().map(|p| p[0]).collect();
+ for x in [21.0, 22.0, 23.0] {
+ assert!(xs.iter().any(|v| (v - x).abs() < 0.01), "the move to {x} is part of the stroke: {xs:?}");
+ }
+}
+
+#[test]
+fn stroke_points_carry_increasing_times_from_zero() {
+ let mut h = harness();
+ move_to(&mut h, 20.0, 50.0);
+ button(&mut h, 20.0, 50.0, true);
+ for x in [30.0, 40.0, 50.0, 60.0] {
+ move_to(&mut h, x, 50.0);
+ }
+ button(&mut h, 60.0, 50.0, false);
+ h.run_steps(2);
+ let pts = committed_points(&h);
+ assert!(pts.len() >= 4, "{pts:?}");
+ let times: Vec<f64> = pts.iter().map(|p| *p.get(6).expect("timeMs")).collect();
+ assert_eq!(times.first().copied(), Some(0.0), "{times:?}");
+ assert!(times.windows(2).all(|w| w[1] >= w[0]), "times never go back: {times:?}");
+ assert!(times.last().copied().unwrap_or(0.0) > 0.0, "time advances over the frames: {times:?}");
+}
+
+/// Points of the drag in progress after holding the pointer still for a while.
+fn held_points(h: &mut Harness<'static, PhotocraftApp>) -> (usize, usize) {
+ move_to(h, 20.0, 50.0);
+ button(h, 20.0, 50.0, true);
+ move_to(h, 30.0, 50.0);
+ let before = h.state().drag.as_ref().map_or(0, |d| d.points.len());
+ h.run_steps(12);
+ let after = h.state().drag.as_ref().map_or(0, |d| d.points.len());
+ button(h, 30.0, 50.0, false);
+ (before, after)
+}
+
+#[test]
+fn a_held_airbrush_keeps_the_stroke_clock_running() {
+ let mut h = harness();
+ h.state_mut().run("tools.setBrush", json!({"buildUp": true, "smoothing": {"amount": 0.0}})).unwrap();
+ let (before, after) = held_points(&mut h);
+ assert!(after > before, "a held airbrush adds timed repeats of its point ({before} → {after})");
+}
+
+#[test]
+fn a_held_plain_brush_adds_nothing() {
+ let mut h = harness();
+ h.state_mut().run("tools.setBrush", json!({"buildUp": false, "smoothing": {"amount": 0.0}})).unwrap();
+ let (before, after) = held_points(&mut h);
+ assert_eq!(after, before, "nothing changes with time, so nothing is repeated");
+}
+
+#[test]
+fn spread_ms_spaces_a_frames_samples_after_the_last_point() {
+ use crate::canvas::spread_ms;
+ assert_eq!((0..4).map(|k| spread_ms(100.0, 116.0, k, 4)).collect::<Vec<_>>(), vec![104.0, 108.0, 112.0, 116.0]);
+ assert_eq!(spread_ms(116.0, 116.0, 0, 3), 116.0, "a press frame's moves share its time");
+ assert_eq!(spread_ms(120.0, 116.0, 0, 1), 116.0, "a clock that went back never goes below now");
+ assert_eq!(spread_ms(f64::NAN, 116.0, 0, 1), 116.0);
+}
diff --git a/crates/ui-egui/src/stylus.rs b/crates/ui-egui/src/stylus.rs
index 64d63246e..9ddc4ff7d 100644
--- a/crates/ui-egui/src/stylus.rs
+++ b/crates/ui-egui/src/stylus.rs
@@ -95,11 +95,27 @@ pub struct Stylus {
lifted: bool,
/// Tilt X, tilt Y, rotation of each point of the current drag (parallel to its points).
pub(crate) stroke: Vec<[f32; 3]>,
+ /// Time in milliseconds of each point of the current drag (parallel to its points), from
+ /// [`Stylus::clock_ms`]. Speed spacing, airbrush build-up and smoothing catch-up use it.
+ pub(crate) times: Vec<f64>,
+ /// Time of the tool event being processed, in milliseconds. The canvas spreads a frame's
+ /// samples between the previous and the current frame time (egui's events carry none).
+ pub(crate) clock_ms: f64,
}
impl Default for Stylus {
fn default() -> Self {
- Self { feed: StylusFeed::default(), use_pressure: true, end: None, tool_before_eraser: None, touch: None, lifted: false, stroke: Vec::new() }
+ Self {
+ feed: StylusFeed::default(),
+ use_pressure: true,
+ end: None,
+ tool_before_eraser: None,
+ touch: None,
+ lifted: false,
+ stroke: Vec::new(),
+ times: Vec::new(),
+ clock_ms: 0.0,
+ }
}
}
@@ -173,28 +189,46 @@ impl Stylus {
/// Start recording a drag's tilt/rotation.
pub(crate) fn begin_stroke(&mut self) {
self.stroke.clear();
+ self.times.clear();
self.record_point();
}
- /// Record the tilt/rotation of a point just added to the drag.
+ /// Record the tilt/rotation and time of a point just added to the drag.
pub(crate) fn record_point(&mut self) {
let s = self.sample().unwrap_or_default();
self.stroke.push([s.tilt_x, s.tilt_y, s.rotation]);
+ self.times.push(self.clock_ms);
+ }
+
+ /// Time of the drag's last recorded point.
+ pub(crate) fn last_point_ms(&self) -> Option<f64> {
+ self.times.last().copied()
+ }
+
+ /// Time of drag point `i` (the last known time past the end).
+ pub(crate) fn point_ms(&self, i: usize) -> f64 {
+ self.times.get(i).or(self.times.last()).copied().unwrap_or(0.0)
}
/// Stroke points for `paint.stroke`: `[x, y, pressure]`, extended with
- /// `tiltX, tiltY, rotation` when the drag carried any tilt or rotation.
+ /// `tiltX, tiltY, rotation` when the drag carried any tilt or rotation, and with `timeMs`
+ /// (from the drag's first point) when its points carry times.
pub fn stroke_points(&self, points: &[[f64; 3]]) -> Vec<Vec<f64>> {
let has_pose = self.stroke.iter().any(|t| t.iter().any(|v| *v != 0.0));
+ let t0 = self.point_ms(0);
+ let has_time = self.times.iter().any(|t| *t != t0);
points
.iter()
.enumerate()
.map(|(i, p)| {
let mut v = vec![p[0], p[1], p[2]];
- if has_pose {
+ if has_pose || has_time {
let t = self.stroke.get(i).or(self.stroke.last()).copied().unwrap_or_default();
v.extend(t.map(f64::from));
}
+ if has_time {
+ v.push(self.point_ms(i) - t0);
+ }
v
})
.collect()