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
//! Centripetal Catmull–Rom spline generator, provisional Hermite stitching,
//! and exact arc-length resampler with zero-drift carry-over.
//!
//! Ported from `src/engine/SplineGenerator.ts` and `src/engine/BrushEngine.ts`.
use super::StrokePoint;
/// Cubic Bézier curve segment carrying interpolated stylus attributes at endpoints.
#[derive(Debug, Clone, Copy)]
pub struct CubicBezierSegment {
pub p0: StrokePoint,
pub cp1x: f64,
pub cp1y: f64,
pub cp2x: f64,
pub cp2y: f64,
pub p3: StrokePoint,
}
impl CubicBezierSegment {
/// Evaluates position `(x, y)` and unnormalized tangent `(tx, ty)` at parameter `t` in `[0, 1]`.
#[inline]
pub fn eval_pos_tangent(&self, t: f64) -> (f64, f64, f64, f64) {
let u = 1.0 - t;
let u2 = u * u;
let t2 = t * t;
let b0 = u2 * u;
let b1 = 3.0 * u2 * t;
let b2 = 3.0 * u * t2;
let b3 = t2 * t;
let x = b0 * self.p0.x + b1 * self.cp1x + b2 * self.cp2x + b3 * self.p3.x;
let y = b0 * self.p0.y + b1 * self.cp1y + b2 * self.cp2y + b3 * self.p3.y;
let tx = 3.0 * u2 * (self.cp1x - self.p0.x)
+ 6.0 * u * t * (self.cp2x - self.cp1x)
+ 3.0 * t2 * (self.p3.x - self.cp2x);
let ty = 3.0 * u2 * (self.cp1y - self.p0.y)
+ 6.0 * u * t * (self.cp2y - self.cp1y)
+ 3.0 * t2 * (self.p3.y - self.cp2y);
(x, y, tx, ty)
}
/// Linearly interpolates stylus metadata (pressure, width, tilt, twist, velocity, timestamp)
/// along the segment at parameter `t`.
#[inline]
pub fn sample_point(&self, t: f64) -> StrokePoint {
let tc = t.clamp(0.0, 1.0);
let tf = tc as f32;
let (x, y, _, _) = self.eval_pos_tangent(tc);
StrokePoint {
x,
y,
pressure: self.p0.pressure + (self.p3.pressure - self.p0.pressure) * tf,
width: self.p0.width + (self.p3.width - self.p0.width) * tf,
tilt_x: self.p0.tilt_x + (self.p3.tilt_x - self.p0.tilt_x) * tf,
tilt_y: self.p0.tilt_y + (self.p3.tilt_y - self.p0.tilt_y) * tf,
twist: interpolate_angle_deg(self.p0.twist, self.p3.twist, tf),
velocity: self.p0.velocity + (self.p3.velocity - self.p0.velocity) * tc,
timestamp_ms: self.p0.timestamp_ms
+ (self.p3.timestamp_ms - self.p0.timestamp_ms) * tc,
is_corner: tc >= 0.9999 && self.p3.is_corner,
}
}
/// Builds a linear (straight-line) cubic Bézier segment between two points.
#[inline]
pub fn linear(p0: StrokePoint, p3: StrokePoint) -> Self {
Self {
cp1x: p0.x + (p3.x - p0.x) / 3.0,
cp1y: p0.y + (p3.y - p0.y) / 3.0,
cp2x: p0.x + (p3.x - p0.x) * (2.0 / 3.0),
cp2y: p0.y + (p3.y - p0.y) * (2.0 / 3.0),
p0,
p3,
}
}
}
#[inline]
fn interpolate_angle_deg(a: f32, b: f32, t: f32) -> f32 {
let mut delta = (b - a) % 360.0;
if delta > 180.0 {
delta -= 360.0;
} else if delta < -180.0 {
delta += 360.0;
}
a + delta * t
}
/// Converts 4 knots `(p0, p1, p2, p3)` into a centripetal Catmull–Rom cubic Bézier segment
/// spanning `p1 -> p2` with Barry–Goldman parameterization (`alpha = 0.5`), handle clamping
/// (`0.48 * d12`), and degenerate micro-chord protection (`< 1e-3`).
///
/// Exact port of `SplineGenerator.centripetalCatmullRomToBezier`.
pub fn centripetal_catmull_rom_to_bezier(
p0: StrokePoint,
p1: StrokePoint,
p2: StrokePoint,
p3: StrokePoint,
tension: f64,
) -> CubicBezierSegment {
let d01 = (p1.x - p0.x).hypot(p1.y - p0.y);
let d12 = (p2.x - p1.x).hypot(p2.y - p1.y);
let d23 = (p3.x - p2.x).hypot(p3.y - p2.y);
if d12 < 1e-3 {
return CubicBezierSegment::linear(p1, p2);
}
// Sharp corner C0 continuity: zero tangents across corner boundaries
let left_corner = p1.is_corner;
let right_corner = p2.is_corner;
let alpha = 0.5f64;
let dt0 = d01.max(1e-4).powf(alpha);
let dt1 = d12.max(1e-4).powf(alpha);
let dt2 = d23.max(1e-4).powf(alpha);
let scale = (1.0 - tension.clamp(0.0, 1.0)).max(0.0);
// Incoming tangent at p1
let (t1x, t1y) = if left_corner || d01 < 1e-3 {
((p2.x - p1.x) * scale, (p2.y - p1.y) * scale)
} else {
let m1x = ((p1.x - p0.x) / dt0 - (p2.x - p0.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1) * dt1;
let m1y = ((p1.y - p0.y) / dt0 - (p2.y - p0.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1) * dt1;
(m1x * scale, m1y * scale)
};
// Outgoing tangent at p2
let (t2x, t2y) = if right_corner || d23 < 1e-3 {
((p2.x - p1.x) * scale, (p2.y - p1.y) * scale)
} else {
let m2x = ((p2.x - p1.x) / dt1 - (p3.x - p1.x) / (dt1 + dt2) + (p3.x - p2.x) / dt2) * dt1;
let m2y = ((p2.y - p1.y) / dt1 - (p3.y - p1.y) / (dt1 + dt2) + (p3.y - p2.y) / dt2) * dt1;
(m2x * scale, m2y * scale)
};
// Clamp handle lengths to 0.48 * d12 and prevent backward-pointing handles (hairpin
// overshoot loops when two knots nearly reverse without an explicit sharp corner).
let chord_ux = (p2.x - p1.x) / d12;
let chord_uy = (p2.y - p1.y) / d12;
let max_handle = 0.48 * d12;
let mut h1x = t1x / 3.0;
let mut h1y = t1y / 3.0;
let h1_fwd = h1x * chord_ux + h1y * chord_uy;
if h1_fwd < 0.0 {
// Project out backward component so cp1 never shoots behind p1 to create a loop
h1x -= h1_fwd * chord_ux;
h1y -= h1_fwd * chord_uy;
}
let h1_len = h1x.hypot(h1y);
if h1_len > max_handle && h1_len > 1e-6 {
let f = max_handle / h1_len;
h1x *= f;
h1y *= f;
}
let mut h2x = t2x / 3.0;
let mut h2y = t2y / 3.0;
let h2_fwd = h2x * chord_ux + h2y * chord_uy;
if h2_fwd < 0.0 {
h2x -= h2_fwd * chord_ux;
h2y -= h2_fwd * chord_uy;
}
let h2_len = h2x.hypot(h2y);
if h2_len > max_handle && h2_len > 1e-6 {
let f = max_handle / h2_len;
h2x *= f;
h2y *= f;
}
CubicBezierSegment {
p0: p1,
cp1x: p1.x + h1x,
cp1y: p1.y + h1y,
cp2x: p2.x - h2x,
cp2y: p2.y - h2y,
p3: p2,
}
}
/// Generates a provisional Hermite segment spanning `p1 -> p2` before `p3` arrives,
/// ensuring zero-latency live stroke rendering and seamless speculative prediction.
pub fn generate_provisional_segment(
p0: Option<StrokePoint>,
p1: StrokePoint,
p2: StrokePoint,
) -> CubicBezierSegment {
let chord_x = p2.x - p1.x;
let chord_y = p2.y - p1.y;
let d12 = chord_x.hypot(chord_y);
if d12 < 1e-3 || p1.is_corner || p2.is_corner {
return CubicBezierSegment::linear(p1, p2);
}
let Some(prev) = p0 else {
return CubicBezierSegment::linear(p1, p2);
};
let d01 = (p1.x - prev.x).hypot(p1.y - prev.y);
if d01 < 1e-3 {
return CubicBezierSegment::linear(p1, p2);
}
// Incoming tangent at p1 blended toward chord direction
let dt0 = d01.sqrt();
let dt1 = d12.sqrt();
let m1x = ((p1.x - prev.x) / dt0 - (p2.x - prev.x) / (dt0 + dt1) + (p2.x - p1.x) / dt1) * dt1;
let m1y = ((p1.y - prev.y) / dt0 - (p2.y - prev.y) / (dt0 + dt1) + (p2.y - p1.y) / dt1) * dt1;
let max_handle = 0.48 * d12;
let chord_ux = chord_x / d12;
let chord_uy = chord_y / d12;
let mut h1x = m1x / 3.0;
let mut h1y = m1y / 3.0;
let h1_fwd = h1x * chord_ux + h1y * chord_uy;
if h1_fwd < 0.0 {
h1x -= h1_fwd * chord_ux;
h1y -= h1_fwd * chord_uy;
}
let h1_len = h1x.hypot(h1y);
if h1_len > max_handle && h1_len > 1e-6 {
let f = max_handle / h1_len;
h1x *= f;
h1y *= f;
}
// Natural quadratic-like end handle at p2
let cp2x = p2.x - chord_x * 0.33;
let cp2y = p2.y - chord_y * 0.33;
CubicBezierSegment {
p0: p1,
cp1x: p1.x + h1x,
cp1y: p1.y + h1y,
cp2x,
cp2y,
p3: p2,
}
}
/// Converts a complete list of `StrokePoint`s into centripetal Catmull–Rom Bézier segments
/// (respecting `is_corner` breaks for C0 continuity).
pub fn polyline_to_bezier_segments(points: &[StrokePoint], tension: f64) -> Vec<CubicBezierSegment> {
if points.len() < 2 {
return Vec::new();
}
let n = points.len();
let mut segs = Vec::with_capacity(n - 1);
for i in 0..(n - 1) {
let p0 = if i == 0 || points[i].is_corner {
points[i]
} else {
points[i - 1]
};
let p1 = points[i];
let p2 = points[i + 1];
let p3 = if i + 2 >= n || points[i + 1].is_corner {
points[i + 1]
} else {
points[i + 2]
};
segs.push(centripetal_catmull_rom_to_bezier(p0, p1, p2, p3, tension));
}
segs
}
/// Streaming spline builder that accepts stabilized knots incrementally and emits
/// sealed centripetal Catmull–Rom segments while exposing the trailing unsealed knots
/// for speculative head prediction.
#[derive(Debug, Clone)]
pub struct SplineGenerator {
tension: f64,
knots: Vec<StrokePoint>,
/// Index of the next unsealed segment start (`knots[sealed_until] -> knots[sealed_until + 1]`).
sealed_until: usize,
}
impl SplineGenerator {
pub fn new(tension: f64) -> Self {
Self {
tension,
knots: Vec::with_capacity(64),
sealed_until: 0,
}
}
pub fn reset(&mut self) {
self.knots.clear();
self.sealed_until = 0;
}
pub fn knots(&self) -> &[StrokePoint] {
&self.knots
}
pub fn sealed_until(&self) -> usize {
self.sealed_until
}
/// Appends a knot and returns any newly sealed `CubicBezierSegment`s.
///
/// Sharp corners immediately seal all pending segments up to the corner so C0
/// continuity is never blurred across an apex.
pub fn push_knot(&mut self, pt: StrokePoint) -> Vec<CubicBezierSegment> {
// Guard against duplicate coincident points unless corner flag changes
if let Some(last) = self.knots.last() {
let d = (pt.x - last.x).hypot(pt.y - last.y);
if d < 1e-3 && !pt.is_corner {
return Vec::new();
}
}
self.knots.push(pt);
let mut emitted = Vec::new();
let n = self.knots.len();
// Whenever a corner arrives, seal immediately up to it
if pt.is_corner && n >= 2 {
while self.sealed_until + 1 < n {
let i = self.sealed_until;
let p0 = if i == 0 || self.knots[i].is_corner {
self.knots[i]
} else {
self.knots[i - 1]
};
let p1 = self.knots[i];
let p2 = self.knots[i + 1];
let p3 = if i + 2 < n && !p2.is_corner {
self.knots[i + 2]
} else {
p2
};
emitted.push(centripetal_catmull_rom_to_bezier(
p0,
p1,
p2,
p3,
self.tension,
));
self.sealed_until += 1;
}
return emitted;
}
// Standard Catmull–Rom sealing: segment [i -> i+1] can seal once knot i+2 exists
while self.sealed_until + 2 < n {
let i = self.sealed_until;
let p0 = if i == 0 || self.knots[i].is_corner {
self.knots[i]
} else {
self.knots[i - 1]
};
let p1 = self.knots[i];
let p2 = self.knots[i + 1];
let p3 = if self.knots[i + 1].is_corner {
self.knots[i + 1]
} else {
self.knots[i + 2]
};
emitted.push(centripetal_catmull_rom_to_bezier(
p0,
p1,
p2,
p3,
self.tension,
));
self.sealed_until += 1;
}
emitted
}
/// Seals the remaining trailing segment(s) on pen-up.
pub fn finish(&mut self) -> Vec<CubicBezierSegment> {
let mut emitted = Vec::new();
let n = self.knots.len();
while self.sealed_until + 1 < n {
let i = self.sealed_until;
let p0 = if i == 0 || self.knots[i].is_corner {
self.knots[i]
} else {
self.knots[i - 1]
};
let p1 = self.knots[i];
let p2 = self.knots[i + 1];
let p3 = if i + 2 < n && !p2.is_corner {
self.knots[i + 2]
} else {
p2
};
emitted.push(centripetal_catmull_rom_to_bezier(
p0,
p1,
p2,
p3,
self.tension,
));
self.sealed_until += 1;
}
emitted
}
/// Builds the current unsealed provisional trailing segment(s) WITHOUT mutating state.
pub fn provisional_tail(&self) -> Vec<CubicBezierSegment> {
let mut out = Vec::new();
let n = self.knots.len();
for i in self.sealed_until..n.saturating_sub(1) {
let p0 = if i == 0 || self.knots[i].is_corner {
None
} else {
Some(self.knots[i - 1])
};
out.push(generate_provisional_segment(
p0,
self.knots[i],
self.knots[i + 1],
));
}
out
}
}
/// Exact arc-length lookup table for a [`CubicBezierSegment`] enabling uniform
/// arc-length dab spacing with exact carry-over across segment boundaries.
#[derive(Debug, Clone)]
pub struct ArcLengthTable {
samples: usize,
cum_len: Vec<f64>,
pub total_length: f64,
}
impl ArcLengthTable {
pub fn build(seg: &CubicBezierSegment, samples: usize) -> Self {
let n = samples.clamp(8, 256);
let mut cum_len = Vec::with_capacity(n + 1);
cum_len.push(0.0);
let mut prev_x = seg.p0.x;
let mut prev_y = seg.p0.y;
let mut acc = 0.0;
for i in 1..=n {
let t = i as f64 / n as f64;
let (x, y, _, _) = seg.eval_pos_tangent(t);
acc += (x - prev_x).hypot(y - prev_y);
cum_len.push(acc);
prev_x = x;
prev_y = y;
}
Self {
samples: n,
cum_len,
total_length: acc,
}
}
/// Maps target arc-length distance `s` in `[0, total_length]` to curve parameter `t` in `[0, 1]`
/// via binary search + linear interpolation.
pub fn t_at_distance(&self, s: f64) -> f64 {
if self.total_length <= 1e-6 || s <= 0.0 {
return 0.0;
}
if s >= self.total_length {
return 1.0;
}
let mut lo = 0usize;
let mut hi = self.samples;
while lo + 1 < hi {
let mid = (lo + hi) >> 1;
if self.cum_len[mid] <= s {
lo = mid;
} else {
hi = mid;
}
}
let seg_start = self.cum_len[lo];
let seg_end = self.cum_len[hi];
let span = (seg_end - seg_start).max(1e-9);
let frac = ((s - seg_start) / span).clamp(0.0, 1.0);
(lo as f64 + frac) / self.samples as f64
}
}
/// Sample emitted by [`ArcLengthResampler`] along a spline segment.
#[derive(Debug, Clone, Copy)]
pub struct ResampledPoint {
pub point: StrokePoint,
pub angle_rad: f64,
pub arc_distance: f64,
pub step_distance: f64,
}
/// Stateful exact arc-length resampler carrying fractional remainder distance across segments.
#[derive(Debug, Clone)]
pub struct ArcLengthResampler {
pub remainder_dist: f64,
pub total_arc_length: f64,
pub last_angle_rad: f64,
pub has_last_angle: bool,
pub initial_angle_rad: f64,
pub has_initial_angle: bool,
}
impl Default for ArcLengthResampler {
fn default() -> Self {
Self::new()
}
}
impl ArcLengthResampler {
pub fn new() -> Self {
Self {
remainder_dist: 0.0,
total_arc_length: 0.0,
last_angle_rad: 0.0,
has_last_angle: false,
initial_angle_rad: 0.0,
has_initial_angle: false,
}
}
pub fn reset(&mut self) {
*self = Self::new();
}
/// Resamples `seg` using caller-provided dynamic step function `step_fn(point, angle_rad)`
/// (allowing elliptical step distance & interval sensor modulation per dab!).
pub fn resample_segment<F>(&mut self, seg: &CubicBezierSegment, mut step_fn: F) -> Vec<ResampledPoint>
where
F: FnMut(&StrokePoint, f64) -> f64,
{
let chord = (seg.p3.x - seg.p0.x).hypot(seg.p3.y - seg.p0.y);
let table_samples = ((chord / 2.0).ceil() as usize).clamp(12, 128);
let table = ArcLengthTable::build(seg, table_samples);
if table.total_length <= 1e-5 {
return Vec::new();
}
let mut out = Vec::new();
let mut s = self.remainder_dist;
// Guard loop count on extremely dense tiny spacings
let max_iters = 4096usize;
let mut iters = 0usize;
while s <= table.total_length && iters < max_iters {
iters += 1;
let t = table.t_at_distance(s);
let pt = seg.sample_point(t);
let (_, _, tx, ty) = seg.eval_pos_tangent(t);
let angle = if tx.hypot(ty) > 1e-5 {
ty.atan2(tx)
} else if self.has_last_angle {
self.last_angle_rad
} else {
(seg.p3.y - seg.p0.y).atan2(seg.p3.x - seg.p0.x)
};
if !self.has_initial_angle {
self.initial_angle_rad = angle;
self.has_initial_angle = true;
}
self.last_angle_rad = angle;
self.has_last_angle = true;
let step = step_fn(&pt, angle).max(0.25);
out.push(ResampledPoint {
point: pt,
angle_rad: angle,
arc_distance: self.total_arc_length + s,
step_distance: step,
});
s += step;
}
self.remainder_dist = (s - table.total_length).max(0.0);
self.total_arc_length += table.total_length;
out
}
}