brush fixes and improvements

This commit is contained in:
Skyler Lehmkuhl
2026-03-05 20:24:38 -05:00
parent 292328bf87
commit f2c15d7f0d
7 changed files with 571 additions and 185 deletions
@@ -15,8 +15,22 @@
//! The GPU compute shader (`brush_dab.wgsl`) is the authoritative implementation.
//!
//! ### Dab placement
//! Spacing = 1 / max(dabs_per_basic_radius/radius, dabs_per_actual_radius/actual_radius).
//! Fractional remainder is tracked across consecutive calls via `StrokeState`.
//! Follows the libmypaint model: distance-based and time-based contributions are
//! **summed** into a single `partial_dabs` accumulator. A dab fires whenever the
//! accumulator reaches 1.0.
//!
//! Rate (dabs per pixel) = dabs_per_actual_radius / actual_radius
//! + dabs_per_basic_radius / base_radius
//! Time contribution added per call = dt × dabs_per_second
//!
//! ### Opacity
//! Matches libmypaint's `opaque_linearize` formula. `dabs_per_pixel` is a fixed
//! brush-level estimate of how many dabs overlap at any pixel:
//!
//! `dabs_per_pixel = 1 + opaque_linearize × ((dabs_per_actual + dabs_per_basic) × 2 - 1)`
//! `per_dab_alpha = 1 - (1 - raw_opacity) ^ (1 / dabs_per_pixel)`
//!
//! With `opaque_linearize = 0` the raw opacity is used directly per dab.
//!
//! ### Blending
//! Normal mode uses the standard "over" operator on premultiplied RGBA.
@@ -70,8 +84,9 @@ pub struct GpuDab {
/// Transient brush stroke state (tracks position and randomness between segments)
pub struct StrokeState {
/// Distance along the path already "consumed" toward the next dab (in pixels)
pub distance_since_last_dab: f32,
/// Fractional dab accumulator — reaches 1.0 when the next dab should fire.
/// Initialised to 1.0 so the very first call always emits at least one dab.
pub partial_dabs: f32,
/// Exponentially-smoothed cursor X for slow_tracking
pub smooth_x: f32,
/// Exponentially-smoothed cursor Y for slow_tracking
@@ -91,7 +106,8 @@ pub struct StrokeState {
impl StrokeState {
pub fn new() -> Self {
Self {
distance_since_last_dab: 0.0,
// Start at 1.0 so the first call always emits the stroke-start dab.
partial_dabs: 1.0,
smooth_x: 0.0,
smooth_y: 0.0,
smooth_initialized: false,
@@ -111,7 +127,7 @@ impl Default for StrokeState {
// Helpers
// ---------------------------------------------------------------------------
/// xorshift32 — fast, no-alloc PRNG. Returns a value in [0, 1).
/// xorshift32 — fast, no-alloc PRNG. Returns a value in [0, 1).
#[inline]
fn xorshift(seed: &mut u32) -> f32 {
let mut s = *seed;
@@ -122,8 +138,17 @@ fn xorshift(seed: &mut u32) -> f32 {
(s as f32) / (u32::MAX as f32)
}
/// Convert linear RGB (premultiplied, alpha already separated) to HSV.
/// Input: r, g, b in [0, 1] (not premultiplied; caller divides by alpha first).
/// Box-Muller Gaussian sample with mean 0 and std-dev 1.
/// Consumes two xorshift samples; the second half of the pair is discarded
/// (acceptable for brush jitter which doesn't need correlated pairs).
#[inline]
fn gaussian(seed: &mut u32) -> f32 {
let u1 = xorshift(seed).max(1e-7); // avoid ln(0)
let u2 = xorshift(seed);
(-2.0 * u1.ln()).sqrt() * (2.0 * std::f32::consts::PI * u2).cos()
}
/// Convert linear RGB (not premultiplied) to HSV.
fn rgb_to_hsv(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
let max = r.max(g).max(b);
let min = r.min(g).min(b);
@@ -160,20 +185,108 @@ fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (f32, f32, f32) {
}
}
// ---------------------------------------------------------------------------
// Per-dab effects helper
// ---------------------------------------------------------------------------
/// Apply per-dab randomness and color-shift effects, matching libmypaint.
///
/// Returns `(ex, ey, radius, opacity, cr, cg, cb)` ready for the dab emitter.
///
/// Opacity uses the `opaque_linearize` formula (same fixed brush-level estimate
/// whether called from the single-point path or the drag path).
///
/// Jitter uses Gaussian noise (matching libmypaint), not uniform.
///
/// Radius jitter applies an opacity correction `× (base_r / jittered_r)²` to
/// keep perceived ink-amount constant as radius varies (matches libmypaint).
fn apply_dab_effects(
state: &mut StrokeState,
bs: &crate::brush_settings::BrushSettings,
x: f32, y: f32,
base_radius: f32, // radius_at_pressure(pressure), before jitter
pressure: f32,
color: [f32; 4],
) -> (f32, f32, f32, f32, f32, f32, f32) {
// ---- Opacity (libmypaint opaque_linearize formula) --------------------
// Estimate average dab overlap per pixel from brush settings (fixed, not
// speed-dependent), then convert stroke-level opacity to per-dab alpha.
let raw_dpp = ((bs.dabs_per_actual_radius + bs.dabs_per_radius) * 2.0).max(1.0);
let dabs_per_pixel = (1.0 + bs.opaque_linearize * (raw_dpp - 1.0)).max(1.0);
let raw_o = bs.opacity_at_pressure(pressure);
let mut opacity = 1.0 - (1.0 - raw_o).powf(1.0 / dabs_per_pixel);
// ---- Radius jitter (Gaussian in log-space, matching libmypaint) -------
let mut radius = base_radius;
if bs.radius_by_random != 0.0 {
let noise = gaussian(&mut state.rng_seed) * bs.radius_by_random;
let jittered_log = bs.radius_log + noise;
radius = jittered_log.exp().clamp(0.5, 500.0);
// Opacity correction: keep ink-amount constant as radius varies.
let alpha_correction = (base_radius / radius).powi(2);
opacity = (opacity * alpha_correction).clamp(0.0, 1.0);
}
// ---- Position jitter + fixed offset (Gaussian, matching libmypaint) ---
let mut ex = x;
let mut ey = y;
if bs.offset_by_random != 0.0 || bs.offset_x != 0.0 || bs.offset_y != 0.0 {
// libmypaint uses base_radius (no-pressure) for the jitter scale.
let base_r_fixed = bs.radius_log.exp();
ex += gaussian(&mut state.rng_seed) * bs.offset_by_random * base_r_fixed
+ bs.offset_x * base_r_fixed;
ey += gaussian(&mut state.rng_seed) * bs.offset_by_random * base_r_fixed
+ bs.offset_y * base_r_fixed;
}
// ---- Per-dab color phase shifts ---------------------------------------
state.color_h_phase += bs.change_color_h;
state.color_v_phase += bs.change_color_v;
state.color_s_phase += bs.change_color_hsv_s;
let (mut cr, mut cg, mut cb) = (color[0], color[1], color[2]);
let ca = color[3];
if ca > 1e-6
&& (bs.change_color_h != 0.0
|| bs.change_color_v != 0.0
|| bs.change_color_hsv_s != 0.0)
{
let (ur, ug, ub) = (cr / ca, cg / ca, cb / ca);
let (mut h, mut s, mut v) = rgb_to_hsv(ur, ug, ub);
h = (h + state.color_h_phase).rem_euclid(1.0);
v = (v + state.color_v_phase).clamp(0.0, 1.0);
s = (s + state.color_s_phase).clamp(0.0, 1.0);
let (r2, g2, b2) = hsv_to_rgb(h, s, v);
cr = r2 * ca;
cg = g2 * ca;
cb = b2 * ca;
}
(ex, ey, radius, opacity.clamp(0.0, 1.0), cr, cg, cb)
}
// ---------------------------------------------------------------------------
// Brush engine
// ---------------------------------------------------------------------------
/// Pure-Rust MyPaint-style Gaussian dab brush engine
pub struct BrushEngine;
impl BrushEngine {
/// Compute the list of GPU dabs for a stroke segment.
///
/// Uses the MyPaint dab-spacing formula and produces [`GpuDab`] structs for
/// upload to the GPU compute pipeline.
/// `dt` is the elapsed time in seconds since the previous call for this
/// stroke. Pass `0.0` on the very first call (stroke start).
///
/// Also returns the union bounding box of all dabs as `(x0, y0, x1, y1)` in
/// integer canvas pixel coordinates (`x0==i32::MAX` when the Vec is empty).
/// Follows the libmypaint spacing model: distance-based and time-based
/// contributions are **summed** in a single `partial_dabs` accumulator.
/// A dab is emitted whenever `partial_dabs` reaches 1.0.
///
/// Also returns the union bounding box of all dabs as `(x0, y0, x1, y1)`.
pub fn compute_dabs(
stroke: &StrokeRecord,
state: &mut StrokeState,
dt: f32,
) -> (Vec<GpuDab>, (i32, i32, i32, i32)) {
let mut dabs: Vec<GpuDab> = Vec::new();
let mut bbox = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
@@ -218,25 +331,55 @@ impl BrushEngine {
});
};
// Time-based accumulation: dt × dabs_per_second contributes to partial_dabs
// regardless of whether the cursor moved.
// Cap dt to 0.1 s to avoid a burst of dabs after a long pause.
let dt_capped = dt.min(0.1);
state.partial_dabs += dt_capped * bs.dabs_per_second;
// ----------------------------------------------------------------
// Single-point path: emit time-based (and stroke-start) dabs.
// The caller is responsible for timing; we just fire whenever
// partial_dabs ≥ 1.0.
// ----------------------------------------------------------------
if stroke.points.len() < 2 {
if let Some(pt) = stroke.points.first() {
let r = bs.radius_at_pressure(pt.pressure);
// Default dpr for a single tap: prefer actual_radius spacing
let dpr = if bs.dabs_per_radius > 0.0 { bs.dabs_per_radius }
else { bs.dabs_per_actual_radius.max(0.01) };
let raw_o = bs.opacity_at_pressure(pt.pressure);
let o = (1.0 - (1.0 - raw_o).powf(dpr * 0.5)
* (1.0 + bs.opaque_multiply)).clamp(0.0, 1.0);
if !matches!(base_blend, RasterBlendMode::Smudge) {
let (cr, cg, cb) = (stroke.color[0], stroke.color[1], stroke.color[2]);
push_dab(&mut dabs, &mut bbox, pt.x, pt.y, r, o, cr, cg, cb,
0.0, 0.0, 0.0);
if !state.smooth_initialized {
state.smooth_x = pt.x;
state.smooth_y = pt.y;
state.smooth_initialized = true;
}
while state.partial_dabs >= 1.0 {
state.partial_dabs -= 1.0;
let base_r = bs.radius_at_pressure(pt.pressure);
let (ex, ey, r, o, cr, cg, cb) = apply_dab_effects(
state, bs, pt.x, pt.y, base_r, pt.pressure, stroke.color,
);
if !matches!(base_blend, RasterBlendMode::Smudge) {
push_dab(&mut dabs, &mut bbox, ex, ey, r, o, cr, cg, cb,
0.0, 0.0, 0.0);
}
}
state.distance_since_last_dab = 0.0;
}
return (dabs, bbox);
}
// ----------------------------------------------------------------
// Drag path: walk the polyline, accumulating partial_dabs from
// both distance-based and time-based contributions.
// ----------------------------------------------------------------
// Track the last smoothed position so that any residual time-based
// dabs can be emitted at the end of the segment walk.
let mut last_smooth_x = state.smooth_x;
let mut last_smooth_y = state.smooth_y;
let mut last_pressure = stroke.points.last()
.map(|p| p.pressure)
.unwrap_or(1.0);
// Fixed base radius (no pressure) used for the basic-radius spacing rate.
let base_radius_fixed = bs.radius_log.exp();
for window in stroke.points.windows(2) {
let p0 = &window[0];
let p1 = &window[1];
@@ -246,27 +389,39 @@ impl BrushEngine {
let seg_len = (dx * dx + dy * dy).sqrt();
if seg_len < 1e-4 { continue; }
last_pressure = p1.pressure;
let mut t = 0.0f32;
while t < 1.0 {
let pressure = p0.pressure + t * (p1.pressure - p0.pressure);
let radius2 = bs.radius_at_pressure(pressure);
let radius_for_rate = bs.radius_at_pressure(pressure);
// Spacing: densest wins between basic-radius and actual-radius methods.
// dabs_per_basic_radius = N dabs per basic_radius pixels → spacing = basic_r / N
// dabs_per_actual_radius = N dabs per actual_radius pixels → spacing = actual_r / N
let spacing_basic = if bs.dabs_per_radius > 0.0 {
radius2 / bs.dabs_per_radius
} else { f32::MAX };
let spacing_actual = if bs.dabs_per_actual_radius > 0.0 {
radius2 / bs.dabs_per_actual_radius
} else { f32::MAX };
let spacing = spacing_basic.min(spacing_actual).max(0.5);
// Dab rate = sum of distance-based contributions (dabs per pixel).
// Matches libmypaint: dabs_per_actual/actual_r + dabs_per_basic/base_r.
// For elliptical brushes use the minor-axis radius so dabs connect
// when moving perpendicular to the major axis.
let eff_radius = if bs.elliptical_dab_ratio > 1.001 {
radius_for_rate / bs.elliptical_dab_ratio
} else {
radius_for_rate
};
let rate_actual = if bs.dabs_per_actual_radius > 0.0 {
bs.dabs_per_actual_radius / eff_radius
} else { 0.0 };
let rate_basic = if bs.dabs_per_radius > 0.0 {
bs.dabs_per_radius / base_radius_fixed
} else { 0.0 };
let rate = rate_actual + rate_basic; // dabs per pixel
let dist_to_next = spacing - state.distance_since_last_dab;
let seg_t_to_next = (dist_to_next / seg_len).max(0.0);
let remaining = 1.0 - state.partial_dabs;
let pixels_to_next = if rate > 1e-8 { remaining / rate } else { f32::MAX };
let seg_t_to_next = (pixels_to_next / seg_len).max(0.0);
if seg_t_to_next > 1.0 - t {
state.distance_since_last_dab += seg_len * (1.0 - t);
// Won't reach the next dab within this segment.
if rate > 1e-8 {
state.partial_dabs += (1.0 - t) * seg_len * rate;
}
break;
}
@@ -275,17 +430,11 @@ impl BrushEngine {
// Stroke threshold gating
if pressure2 < bs.stroke_threshold {
state.distance_since_last_dab = 0.0;
state.partial_dabs = 0.0;
continue;
}
let mut radius2 = bs.radius_at_pressure(pressure2);
// Opacity — normalised so dense dabs don't saturate faster than sparse ones
let dpr = radius2 / spacing; // effective dabs per radius
let raw_opacity = bs.opacity_at_pressure(pressure2);
let mut opacity2 = 1.0 - (1.0 - raw_opacity).powf(dpr * 0.5);
opacity2 = (opacity2 * (1.0 + bs.opaque_multiply)).clamp(0.0, 1.0);
let base_r2 = bs.radius_at_pressure(pressure2);
// Slow tracking: exponential position smoothing
let x2 = p0.x + t * dx;
@@ -294,57 +443,25 @@ impl BrushEngine {
state.smooth_x = x2; state.smooth_y = y2;
state.smooth_initialized = true;
}
// spacing_px ≈ 1 / rate (pixels per dab), used as time-constant scale
let spacing_px = if rate > 1e-8 { 1.0 / rate } else { 1.0 };
let k = if bs.slow_tracking > 0.0 {
(-spacing / bs.slow_tracking.max(0.1)).exp()
(-spacing_px / bs.slow_tracking.max(0.1)).exp()
} else { 0.0 };
state.smooth_x = state.smooth_x * k + x2 * (1.0 - k);
state.smooth_y = state.smooth_y * k + y2 * (1.0 - k);
let mut ex = state.smooth_x;
let mut ey = state.smooth_y;
last_smooth_x = state.smooth_x;
last_smooth_y = state.smooth_y;
// Radius jitter (log-scale)
if bs.radius_by_random != 0.0 {
let r_rng = xorshift(&mut state.rng_seed) * 2.0 - 1.0;
radius2 = (radius2 * (bs.radius_by_random * r_rng).exp()).clamp(0.5, 500.0);
}
// Position jitter + fixed offset
if bs.offset_by_random != 0.0 || bs.offset_x != 0.0 || bs.offset_y != 0.0 {
let jitter = bs.offset_by_random * radius2;
ex += (xorshift(&mut state.rng_seed) * 2.0 - 1.0) * jitter
+ bs.offset_x * radius2;
ey += (xorshift(&mut state.rng_seed) * 2.0 - 1.0) * jitter
+ bs.offset_y * radius2;
}
// Per-dab color phase shifts
state.color_h_phase += bs.change_color_h;
state.color_v_phase += bs.change_color_v;
state.color_s_phase += bs.change_color_hsv_s;
let (mut cr, mut cg, mut cb) = (
stroke.color[0], stroke.color[1], stroke.color[2],
let (sx, sy) = (state.smooth_x, state.smooth_y);
let (ex, ey, radius2, opacity2, cr, cg, cb) = apply_dab_effects(
state, bs, sx, sy, base_r2, pressure2, stroke.color,
);
let ca = stroke.color[3];
if ca > 1e-6 {
// un-premultiply for HSV conversion
let (ur, ug, ub) = (cr / ca, cg / ca, cb / ca);
let (mut h, mut s, mut v) = rgb_to_hsv(ur, ug, ub);
if bs.change_color_h != 0.0 || bs.change_color_v != 0.0
|| bs.change_color_hsv_s != 0.0 {
h = (h + state.color_h_phase).rem_euclid(1.0);
v = (v + state.color_v_phase).clamp(0.0, 1.0);
s = (s + state.color_s_phase).clamp(0.0, 1.0);
let (r2, g2, b2) = hsv_to_rgb(h, s, v);
cr = r2 * ca; cg = g2 * ca; cb = b2 * ca;
}
}
if matches!(base_blend, RasterBlendMode::Smudge) {
let ndx = dx / seg_len;
let ndy = dy / seg_len;
let smudge_dist =
(radius2 * dpr).max(1.0) * bs.smudge_radius_log.exp();
let smudge_dist = radius2 * bs.smudge_radius_log.exp();
push_dab(&mut dabs, &mut bbox,
ex, ey, radius2, opacity2, cr, cg, cb,
ndx, ndy, smudge_dist);
@@ -354,7 +471,34 @@ impl BrushEngine {
0.0, 0.0, 0.0);
}
state.distance_since_last_dab = 0.0;
state.partial_dabs = 0.0;
}
}
// Emit any residual time-based dabs (partial_dabs ≥ 1.0 from the dt
// contribution not consumed by distance-based movement) at the last
// known cursor position.
if state.partial_dabs >= 1.0 && !matches!(base_blend, RasterBlendMode::Smudge) {
// Initialise smooth position if we never entered the segment loop.
if !state.smooth_initialized {
if let Some(pt) = stroke.points.last() {
state.smooth_x = pt.x;
state.smooth_y = pt.y;
state.smooth_initialized = true;
last_smooth_x = state.smooth_x;
last_smooth_y = state.smooth_y;
}
}
while state.partial_dabs >= 1.0 {
state.partial_dabs -= 1.0;
let base_r = bs.radius_at_pressure(last_pressure);
let (ex, ey, r, o, cr, cg, cb) = apply_dab_effects(
state, bs,
last_smooth_x, last_smooth_y,
base_r, last_pressure, stroke.color,
);
push_dab(&mut dabs, &mut bbox, ex, ey, r, o, cr, cg, cb,
0.0, 0.0, 0.0);
}
}