A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
//! Brush-feel reference metrics for line-art inking (G-Pen class brushes).
//!
//! These tests drive the real [`NativeStrokePipeline`] with synthetic, timestamped stylus
//! traces (240 Hz WinInk cadence) and measure the three things an inker actually feels:
//! 1. Pressure response: latency of the pressure path and exactness of the curve.
//! 2. Taper: how thin the ends of a fast stroke really get when the pen lifts mid-motion.
//! 3. Stabilizer: lag, settle time after the hand stops, and the shape of the pen-up tail.
use crate::stroke::{
calculate_stroke_width, InputStabilizer, NativeStrokePipeline, StabilizerConfig,
StrokePipelineConfig, StrokePoint,
};
const HZ: f64 = 240.0;
const DT: f64 = 1000.0 / HZ;
fn gpen_cfg(stabilization: f32) -> StrokePipelineConfig {
StrokePipelineConfig {
base_size: 12.0,
min_size_factor: 0.0,
use_pressure: true,
stabilization,
enable_flick_taper: true,
zoom: 1.0,
..Default::default()
}
}
/// Runs a trace `(x, y, pressure, t_ms)` through the pipeline and returns the finalized points.
fn run_trace(trace: &[(f64, f64, f32, f64)], cfg: StrokePipelineConfig) -> Vec<StrokePoint> {
let mut pipe = NativeStrokePipeline::new();
let (x0, y0, p0, t0) = trace[0];
pipe.begin(x0, y0, p0, 0.0, 0.0, 0.0, t0, false, None, cfg);
for &(x, y, p, t) in &trace[1..] {
pipe.push_move(x, y, p, 0.0, 0.0, 0.0, t, false);
}
let lift_t = trace.last().unwrap().3 + DT;
pipe.end(lift_t).finalized_points.unwrap()
}
/// A fast flick: 3 px/ms, pressure ramps 0 -> 0.8 over 20 ms, holds, then releases to 0
/// over the final 25 ms while the hand is still moving (classic hair/eyelash stroke).
fn fast_flick_trace() -> Vec<(f64, f64, f32, f64)> {
let total_ms = 140.0;
let n = (total_ms / DT) as usize;
(0..=n)
.map(|i| {
let t = i as f64 * DT;
let x = 100.0 + 3.0 * t;
let y = 200.0;
let p = if t < 20.0 {
0.8 * (t / 20.0)
} else if t > total_ms - 25.0 {
0.8 * ((total_ms - t) / 25.0).max(0.0)
} else {
0.8
} as f32;
(x, y, p, t)
})
.collect()
}
#[test]
fn brush_feel_pressure_path_has_low_latency() {
// Step response of the pressure path: 0.2 -> 0.8 while moving slowly.
let mut stab = InputStabilizer::new(StabilizerConfig {
stabilization: 0.0,
..Default::default()
});
let mut t = 0.0;
for i in 0..24 {
stab.process(i as f64, 0.0, 0.2, 0.0, 0.0, 0.0, t);
t += DT;
}
let mut rise_ms = None;
for i in 0..120 {
let s = stab.process(24.0 + i as f64, 0.0, 0.8, 0.0, 0.0, 0.0, t);
if rise_ms.is_none() && s.pressure >= 0.2 + 0.9 * 0.6 {
rise_ms = Some(i as f64 * DT);
}
t += DT;
}
let mut fall_ms = None;
for i in 0..120 {
let s = stab.process(144.0 + i as f64, 0.0, 0.2, 0.0, 0.0, 0.0, t);
if fall_ms.is_none() && s.pressure <= 0.8 - 0.9 * 0.6 {
fall_ms = Some(i as f64 * DT);
}
t += DT;
}
let rise = rise_ms.expect("pressure never rose");
let fall = fall_ms.expect("pressure never fell");
eprintln!("[brush-feel] pressure 90% rise = {rise:.1} ms, 90% fall = {fall:.1} ms");
assert!(rise <= 17.0, "pressure attack too sluggish: {rise} ms");
assert!(fall <= 21.0, "pressure release too sluggish (blunt tapers): {fall} ms");
// Steady pressure must be reproduced exactly (predictable curve, no filter bias).
let mut steady = 0.0;
for i in 0..60 {
steady = stab
.process(300.0 + i as f64, 0.0, 0.437, 0.0, 0.0, 0.0, t)
.pressure;
t += DT;
}
assert!((steady - 0.437).abs() < 1e-3, "steady pressure biased: {steady}");
}
#[test]
fn brush_feel_pressure_jitter_is_still_suppressed() {
// Cheap-tablet ±0.02 alternating pressure noise at constant hand pressure.
let mut stab = InputStabilizer::new(StabilizerConfig::default());
let mut t = 0.0;
let mut outs = Vec::new();
for i in 0..200 {
let noise = if i % 2 == 0 { 0.02 } else { -0.02 };
let s = stab.process(i as f64 * 0.8, 0.0, 0.5 + noise, 0.0, 0.0, 0.0, t);
if i > 40 {
outs.push(s.pressure);
}
t += DT;
}
let max = outs.iter().cloned().fold(f32::MIN, f32::max);
let min = outs.iter().cloned().fold(f32::MAX, f32::min);
eprintln!("[brush-feel] jitter ripple = {:.4}", max - min);
assert!(max - min < 0.03, "pressure jitter leaks through: ripple {}", max - min);
}
#[test]
fn brush_feel_fast_stroke_tapers_to_a_point() {
let trace = fast_flick_trace();
for stab in [0.0f32, 6.0, 15.0] {
let pts = run_trace(&trace, gpen_cfg(stab));
let first = pts.first().unwrap();
let last = pts.last().unwrap();
let max_w = pts.iter().map(|p| p.width).fold(0.0f32, f32::max);
eprintln!(
"[brush-feel] stab={stab:>4}: start w={:.2} end w={:.2} max w={:.2} pts={}",
first.width,
last.width,
max_w,
pts.len()
);
assert!(max_w > 8.0, "stroke body never reached full width (stab={stab})");
assert!(
first.width <= 0.12 * max_w + 0.3,
"start is blunt (stab={stab}): {}",
first.width
);
assert!(
last.width <= 0.12 * max_w + 0.3,
"end is blunt on a fast release (stab={stab}): {}",
last.width
);
// Width over the last quarter of the stroke must decrease monotonically
// (no "bulb" or re-thickening at the tail).
let tail_start = pts.len() * 3 / 4;
let mut prev = f32::MAX;
for p in &pts[tail_start..] {
assert!(
p.width <= prev + 0.05,
"tail re-thickens (stab={stab}): {} after {}",
p.width,
prev
);
prev = p.width;
}
}
}
#[test]
fn brush_feel_stabilizer_settles_without_rubber_banding() {
// Hand moves at 1.2 px/ms then stops dead; tablet keeps reporting the resting position.
for level in [6.0f32, 15.0, 30.0] {
let mut stab = InputStabilizer::new(StabilizerConfig {
stabilization: level,
zoom: 1.0,
..Default::default()
});
let mut t = 0.0;
let mut x = 0.0;
for _ in 0..96 {
stab.process(x, 0.0, 0.6, 0.0, 0.0, 0.0, t);
x += 1.2 * DT;
t += DT;
}
let stop_x = x - 1.2 * DT;
let mut settle_ms = None;
let mut overshoot = 0.0f64;
for i in 0..240 {
let s = stab.process(stop_x, 0.0, 0.6, 0.0, 0.0, 0.0, t);
overshoot = overshoot.max(s.x - stop_x);
if settle_ms.is_none() && (stop_x - s.x).abs() < 0.5 {
settle_ms = Some(i as f64 * DT);
}
t += DT;
}
let settle = settle_ms.unwrap_or(f64::INFINITY);
eprintln!("[brush-feel] stab={level:>4}: settle after stop = {settle:.1} ms, overshoot = {overshoot:.3}px");
assert!(overshoot < 0.05, "stabilizer overshoots (rubber band) at {level}");
assert!(
settle < 120.0 + level as f64 * 4.0,
"stabilizer drags after the hand stops at level {level}: {settle} ms"
);
}
}
/// Slow careful line (0.15 px/ms) with 10 Hz ±1.5 px hand tremor; returns lateral RMS of output.
fn tremor_rms(level: f32, hz: f64) -> f64 {
let dt = 1000.0 / hz;
let mut stab = InputStabilizer::new(StabilizerConfig {
stabilization: level,
zoom: 1.0,
..Default::default()
});
let n = (2000.0 / dt) as usize;
let mut sum = 0.0;
let mut cnt = 0usize;
for i in 0..n {
let t = i as f64 * dt;
let x = 0.15 * t;
let y = 1.5 * (2.0 * std::f64::consts::PI * 10.0 * t / 1000.0).sin();
let s = stab.process(x, y, 0.6, 0.0, 0.0, 0.0, t);
if t > 300.0 {
sum += s.y * s.y;
cnt += 1;
}
}
(sum / cnt as f64).sqrt()
}
#[test]
fn brush_feel_slow_line_tremor_is_smoothed() {
let raw_rms = 1.5 / 2f64.sqrt();
for level in [6.0f32, 15.0, 30.0] {
let rms = tremor_rms(level, 240.0);
eprintln!(
"[brush-feel] tremor stab={level:>4}: output RMS {rms:.3}px ({:.0}% of raw)",
100.0 * rms / raw_rms
);
// Thresholds pinned to the pre-settle-floor smoothing so the "no rubber band"
// fix can never silently trade away slow-line steadiness.
let limit = if level >= 15.0 { 0.17 } else { 0.36 };
assert!(rms < raw_rms * limit, "tremor not smoothed at level {level}: {rms}");
}
}
#[test]
fn brush_feel_settle_is_sample_rate_invariant() {
// Same gesture sampled at 60 Hz (mouse), 240 Hz (Windows Ink) and 1 kHz (WinTab).
let settle = |hz: f64| -> f64 {
let dt = 1000.0 / hz;
let mut stab = InputStabilizer::new(StabilizerConfig {
stabilization: 15.0,
zoom: 1.0,
..Default::default()
});
let mut t = 0.0;
while t < 400.0 {
stab.process(t * 1.0, 0.0, 0.6, 0.0, 0.0, 0.0, t);
t += dt;
}
let stop_x = (t - dt) * 1.0;
let start = t;
loop {
let s = stab.process(stop_x, 0.0, 0.6, 0.0, 0.0, 0.0, t);
if (stop_x - s.x).abs() < 0.5 || t - start > 2000.0 {
return t - start;
}
t += dt;
}
};
let (a, b, c) = (settle(60.0), settle(240.0), settle(1000.0));
eprintln!("[brush-feel] settle @60Hz={a:.0}ms @240Hz={b:.0}ms @1kHz={c:.0}ms");
let lo = a.min(b).min(c);
let hi = a.max(b).max(c);
assert!(hi < 200.0, "settle too slow at some sample rate: {a} / {b} / {c}");
assert!(hi - lo < 60.0, "settle differs too much across sample rates: {a} / {b} / {c}");
}
#[test]
fn brush_feel_pen_up_tail_follows_the_curve() {
// Quarter-circle arc (r = 80) drawn quickly with heavy stabilization, lift at the end.
let r = 80.0;
let n = 60;
let trace: Vec<(f64, f64, f32, f64)> = (0..=n)
.map(|i| {
let a = std::f64::consts::FRAC_PI_2 * i as f64 / n as f64;
(200.0 + r * a.cos(), 200.0 + r * a.sin(), 0.6, i as f64 * DT)
})
.collect();
let pts = run_trace(
&trace,
StrokePipelineConfig {
enable_flick_taper: false,
..gpen_cfg(30.0)
},
);
// Every finalized point must stay close to the true arc (radius 80).
let mut worst = 0.0f64;
for p in &pts {
let d = ((p.x - 200.0).hypot(p.y - 200.0) - r).abs();
worst = worst.max(d);
}
let last = pts.last().unwrap();
eprintln!("[brush-feel] arc stab=30: worst radial error = {worst:.2}px, pts={}", pts.len());
assert!((last.x - 200.0).abs() < 1e-3 && (last.y - 280.0).abs() < 1e-3, "tail must land on the lift point");
assert!(worst < 6.0, "pen-up tail cuts the curve (straight chord): {worst}px");
}
#[test]
fn brush_feel_pressure_curve_is_monotone_and_exact() {
// Width must be a strictly non-decreasing function of pressure for a plain G-Pen.
let mut prev = 0.0f32;
for i in 0..=1000 {
let p = i as f32 / 1000.0;
let w = calculate_stroke_width(p, 12.0, true, 0.0, 1.0, None);
assert!(w + 1e-6 >= prev, "width not monotone at p={p}: {w} < {prev}");
prev = w;
}
assert!((calculate_stroke_width(1.0, 12.0, true, 0.0, 1.0, None) - 12.0).abs() < 1e-5);
assert!((calculate_stroke_width(0.5, 12.0, true, 0.0, 1.0, None) - 6.0).abs() < 1e-5);
}
#[test]
fn brush_feel_diagonal_after_vertical_touchdown_never_bends_or_elbows() {
// Reproduces the exact initial-tangent lock bug: pen touches down, slips 1px vertically
// on contact, then pulls smoothly down-left along a straight diagonal with G-Pen defaults
// (stabilization = 10, sharp_corners = true). Must never track vertically or kink!
let mut trace = vec![
(400.0, 100.0, 0.08f32, 0.0),
(400.0, 101.0, 0.20, DT), // 1px vertical touchdown skid
];
let dir_x = -0.55;
let dir_y = 0.8351646544245033; // unit vector down-left
for i in 2..=70 {
let s = (i - 1) as f64 * 3.5;
trace.push((400.0 + dir_x * s, 101.0 + dir_y * s, 0.65, i as f64 * DT));
}
let pts = run_trace(
&trace,
StrokePipelineConfig {
sharp_corners: true,
enable_flick_taper: false,
..gpen_cfg(10.0)
},
);
let mut max_perp_err = 0.0f64;
let mut false_corners = 0usize;
for p in &pts {
if p.is_corner {
false_corners += 1;
}
// Perpendicular distance to the diagonal ray starting at (400, 101)
let rx = p.x - 400.0;
let ry = p.y - 101.0;
let perp = (rx * (-dir_y) + ry * dir_x).abs();
max_perp_err = max_perp_err.max(perp);
}
eprintln!(
"[brush-feel] diagonal w/ vertical touchdown: max_perp_err={max_perp_err:.3}px, false_corners={false_corners}"
);
assert_eq!(
false_corners, 0,
"diagonal stroke must not trigger false sharp corners"
);
assert!(
max_perp_err < 1.25,
"diagonal stroke bent off-axis after vertical touchdown: {max_perp_err:.3}px"
);
}
#[test]
fn brush_feel_freehand_line_rejects_micro_twitches_and_liftoff_hooks() {
// Freehand diagonal stroke with:
// 1. A 4px touchdown skid at start,
// 2. A 1-sample 5px sideways digitizer twitch mid-stroke,
// 3. A 7px sideways 90-degree stylus lift-off wobble as pressure collapses to near-zero.
// With G-Pen defaults (stab=10, sharp_corners=true), NONE of these may cause a 90° hook!
let mut trace = Vec::new();
let mut t = 0.0;
trace.push((300.0, 100.0, 0.05f32, t));
t += DT;
// Slight touchdown jitter
trace.push((297.5, 100.5, 0.12, t));
t += DT;
for i in 1..=50 {
let mut x = 300.0 - i as f64 * 2.0;
let mut y = 100.0 + i as f64 * 3.5;
let p = if i < 45 {
0.65
} else {
(0.65 * (50 - i) as f32 / 5.0).max(0.02)
};
// Mid-stroke 1-sample 5px sideways twitch
if i == 25 {
x -= 5.0;
y -= 2.0;
}
trace.push((x, y, p, t));
t += DT;
}
// Lift-off 90-degree sideways tilt hook right as pressure collapses to 0.01
let (lx, ly, _, _) = *trace.last().unwrap();
trace.push((lx - 7.0, ly - 4.0, 0.01, t));
let pts = run_trace(
&trace,
StrokePipelineConfig {
sharp_corners: true,
enable_flick_taper: false,
..gpen_cfg(10.0)
},
);
let corners = pts.iter().filter(|p| p.is_corner).count();
let last = pts.last().unwrap();
let end_err = (last.x - lx).hypot(last.y - ly);
eprintln!(
"[brush-feel] twitch+liftoff guard: corners={corners}, end_err_from_clean_end={end_err:.3}px"
);
assert_eq!(corners, 0, "micro-twitches must never snap sharp corners");
assert!(
end_err < 1.5,
"stylus lift-off sideways wobble leaked into stroke end: {end_err:.3}px"
);
}
#[test]
fn brush_feel_intentional_240hz_sharp_corner_still_snaps_cleanly() {
// Real intentional 90-degree L-corner at 240Hz (~3.5px/sample) MUST still trigger sharp corner!
let mut stab = InputStabilizer::new(StabilizerConfig {
stabilization: 12.0,
sharp_corners: true,
zoom: 1.0,
pressure_smoothing: 0.35,
});
let mut t = 0.0;
for i in 0..20 {
stab.process(100.0 + i as f64 * 3.5, 100.0, 0.7, 0.0, 0.0, 0.0, t);
t += DT;
}
let apex_x = 100.0 + 19.0 * 3.5;
let mut snapped_apex = None;
for j in 1..=8 {
let s = stab.process(apex_x, 100.0 + j as f64 * 3.5, 0.7, 0.0, 0.0, 0.0, t);
if s.is_corner {
snapped_apex = Some((s.x, s.y));
break;
}
t += DT;
}
let (ax, ay) = snapped_apex.expect("intentional 240Hz 90-degree corner must snap");
assert!(
(ax - apex_x).abs() < 4.0 && (ay - 100.0).abs() < 4.0,
"corner apex drifted too far: ({ax}, {ay}) vs ({apex_x}, 100.0)"
);
}