Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

14.7 KB
Raw Blame
//! Taper Engine & CSP Starting/Ending (`CspTaperSettings`) evaluator.
//!
//! Ports:
//! 1. `src/engine/TaperEngine.ts`:
//!    - G-Pen 3-stage piecewise cubic Hermite S-curve pressure response (`map_pressure`)
//!    - Time-calibrated `smooth_pressure`
//!    - Ballistic exit flick extrapolation (`compute_flick_taper`) with screen-space
//!      speed normalization, dwell gate (`<= 32 ms`), and bounded tail length
//! 2. `src/types/editor.ts` (`CspTaperSettings`) & `BrushEngine.ts` (`evaluateCspTaperFactors`):
//!    - `useIn` / `inLength` / `inRatio`
//!    - `useOut` / `outLength` / `outRatio`
//!    - `inOutType`: 0 (Off), 1 (Percentage), 2 (Length px), 3 (Fade)
//!    - `inOutBySpeed`, `startingSharpness`, `endingSharpness`
//!    - Per-channel taper multipliers: `size`, `opacity`, `density`, `amount_of_paint`,
//!      `density_of_paint`, `load`

use super::StrokePoint;
use serde::{Deserialize, Serialize};

#[inline]
fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
    let t = ((x - edge0) / (edge1 - edge0).max(1e-6)).clamp(0.0, 1.0);
    t * t * (3.0 - 2.0 * t)
}

/// Complete CSP Starting & Ending taper configuration matching `CspTaperSettings`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CspTaperSettings {
    #[serde(default)]
    pub use_in: bool,
    /// Taper-in length in px (for `in_out_type == 2`).
    #[serde(default)]
    pub in_length: f32,
    /// Taper-in ratio `0..=1` (for `in_out_type == 1` or fallback).
    #[serde(default)]
    pub in_ratio: f32,
    #[serde(default)]
    pub use_out: bool,
    /// Taper-out length in px (for `in_out_type == 2`).
    #[serde(default)]
    pub out_length: f32,
    /// Taper-out ratio `0..=1` (for `in_out_type == 1` or fallback).
    #[serde(default)]
    pub out_ratio: f32,
    /// CSP In/Out mode: `0` = Off, `1` = Percentage, `2` = Length (px), `3` = Fade.
    #[serde(default = "default_in_out_type")]
    pub in_out_type: u8,
    /// Scale ending taper length proportionally with exit gesture velocity.
    #[serde(default)]
    pub in_out_by_speed: bool,
    /// Starting tip sharpness `0.0..=1.0` (higher = sharper needle tip).
    #[serde(default = "default_sharpness")]
    pub starting_sharpness: f32,
    /// Ending tip sharpness `0.0..=1.0`.
    #[serde(default = "default_sharpness")]
    pub ending_sharpness: f32,

    // Per-channel taper target toggles & minimums
    #[serde(default = "default_true")]
    pub affect_size: bool,
    #[serde(default)]
    pub min_size_ratio: f32,
    #[serde(default)]
    pub affect_opacity: bool,
    #[serde(default)]
    pub affect_density: bool,
    #[serde(default)]
    pub min_density_ratio: f32,
    #[serde(default)]
    pub affect_amount_of_paint: bool,
    #[serde(default)]
    pub min_amount_ratio: f32,
    #[serde(default)]
    pub affect_density_of_paint: bool,
    #[serde(default)]
    pub min_paint_density_ratio: f32,
    #[serde(default)]
    pub affect_load: bool,
}

fn default_in_out_type() -> u8 {
    2
}
fn default_sharpness() -> f32 {
    0.5
}
fn default_true() -> bool {
    true
}

impl Default for CspTaperSettings {
    fn default() -> Self {
        Self {
            use_in: false,
            in_length: 0.0,
            in_ratio: 0.0,
            use_out: false,
            out_length: 0.0,
            out_ratio: 0.0,
            in_out_type: 2,
            in_out_by_speed: false,
            starting_sharpness: 0.5,
            ending_sharpness: 0.5,
            affect_size: true,
            min_size_ratio: 0.0,
            affect_opacity: false,
            affect_density: false,
            min_density_ratio: 0.0,
            affect_amount_of_paint: false,
            min_amount_ratio: 0.0,
            affect_density_of_paint: false,
            min_paint_density_ratio: 0.0,
            affect_load: false,
        }
    }
}

impl CspTaperSettings {
    #[inline]
    pub fn is_active(&self) -> bool {
        self.in_out_type != 0 && (self.use_in || self.use_out)
    }
}

/// Per-channel evaluated taper multipliers (`0.0..=1.0`) at a stroke sample.
#[derive(Debug, Clone, Copy)]
pub struct CspTaperFactors {
    pub raw_factor: f32,
    pub size: f32,
    pub opacity: f32,
    pub density: f32,
    pub amount_of_paint: f32,
    pub density_of_paint: f32,
    pub load: f32,
}

impl Default for CspTaperFactors {
    fn default() -> Self {
        Self {
            raw_factor: 1.0,
            size: 1.0,
            opacity: 1.0,
            density: 1.0,
            amount_of_paint: 1.0,
            density_of_paint: 1.0,
            load: 1.0,
        }
    }
}

/// Evaluates CSP Starting & Ending taper multipliers at `arc_dist` along a stroke of `total_length`.
///
/// Supports both live progressive strokes (`total_length` unknown -> `None`, only `use_in` applies)
/// and finalized strokes (`total_length = Some(len)`, both `use_in` and `use_out` apply).
pub fn evaluate_csp_taper_factors(
    taper: &CspTaperSettings,
    arc_dist: f64,
    total_length: Option<f64>,
    exit_velocity_doc_per_ms: f64,
) -> CspTaperFactors {
    if !taper.is_active() {
        return CspTaperFactors::default();
    }

    let mut factor = 1.0f32;

    // Starting taper (In)
    if taper.use_in {
        let in_span = match taper.in_out_type {
            1 => {
                // Percentage of total length (or fallback to in_length if progressive)
                let ratio = taper.in_ratio.clamp(0.0, 0.95) as f64;
                total_length
                    .map(|tl| tl * ratio)
                    .unwrap_or_else(|| (taper.in_length as f64).max(1.0))
            }
            2 | 3 => (taper.in_length as f64).max(0.0),
            _ => 0.0,
        };
        if in_span > 1e-4 && arc_dist < in_span {
            let t = (arc_dist / in_span).clamp(0.0, 1.0) as f32;
            let sharp = taper.starting_sharpness.clamp(0.0, 1.0);
            let shaped = shape_taper_ramp(t, sharp);
            factor = factor.min(shaped);
        }
    }

    // Ending taper (Out) — requires known total stroke length
    if taper.use_out {
        if let Some(total_len) = total_length {
            let speed_mult = if taper.in_out_by_speed {
                (0.65 + (exit_velocity_doc_per_ms as f32) * 0.85).clamp(0.5, 2.2)
            } else {
                1.0
            };
            let out_span = match taper.in_out_type {
                1 => total_len * (taper.out_ratio.clamp(0.0, 0.95) as f64) * speed_mult as f64,
                2 | 3 => (taper.out_length as f64).max(0.0) * speed_mult as f64,
                _ => 0.0,
            };
            let dist_from_end = (total_len - arc_dist).max(0.0);
            if out_span > 1e-4 && dist_from_end < out_span {
                let t = (dist_from_end / out_span).clamp(0.0, 1.0) as f32;
                let sharp = taper.ending_sharpness.clamp(0.0, 1.0);
                let shaped = shape_taper_ramp(t, sharp);
                factor = factor.min(shaped);
            }
        }
    }

    // Fade mode (`in_out_type == 3`) implicitly fades opacity as well as size
    let is_fade = taper.in_out_type == 3;
    let lerp_min = |min_r: f32, f: f32| {
        let m = min_r.clamp(0.0, 1.0);
        m + (1.0 - m) * f
    };

    CspTaperFactors {
        raw_factor: factor,
        size: if taper.affect_size {
            lerp_min(taper.min_size_ratio, factor)
        } else {
            1.0
        },
        opacity: if taper.affect_opacity || is_fade {
            lerp_min(taper.min_density_ratio, factor)
        } else {
            1.0
        },
        density: if taper.affect_density {
            lerp_min(taper.min_density_ratio, factor)
        } else {
            1.0
        },
        amount_of_paint: if taper.affect_amount_of_paint {
            lerp_min(taper.min_amount_ratio, factor)
        } else {
            1.0
        },
        density_of_paint: if taper.affect_density_of_paint {
            lerp_min(taper.min_paint_density_ratio, factor)
        } else {
            1.0
        },
        load: if taper.affect_load {
            lerp_min(0.05, factor)
        } else {
            1.0
        },
    }
}

/// Shapes a linear `[0, 1]` taper ramp by CSP sharpness (`0.0` = blunt/full, `0.5` = linear/smooth, `1.0` = sharp needle).
#[inline]
fn shape_taper_ramp(t: f32, sharpness: f32) -> f32 {
    let tc = t.clamp(0.0, 1.0);
    let s = sharpness.clamp(0.0, 1.0);
    // Exponential shaping: s=0 -> pow(0.45) (blunt), s=0.5 -> pow(1.0) (linear), s=1.0 -> pow(2.1) (needle)
    let exp = if s < 0.5 {
        0.45 + (s / 0.5) * 0.55
    } else {
        1.0 + ((s - 0.5) / 0.5) * 1.1
    };
    let curved = tc.powf(exp);
    // Blend gently with smoothstep at low sharpness to avoid harsh shoulder knees
    let smooth = smoothstep(0.0, 1.0, tc);
    curved * 0.8 + smooth * 0.2
}

/// Configuration for ballistic flick taper (`TaperEngine.ts`).
#[derive(Debug, Clone, Copy)]
pub struct FlickTaperConfig {
    /// Minimum screen-space exit speed (`px/ms`) required to trigger a ballistic flick.
    pub min_screen_speed_px_per_ms: f64,
    /// Maximum dwell duration (`ms`) between last motion sample and pointer-up.
    /// Exceeding 32 ms means the artist paused before lifting -> suppress flick!
    pub max_dwell_ms: f64,
    /// Maximum flick tail length in document pixels (capped proportional to brush size & zoom).
    pub max_tail_px: f64,
}

impl Default for FlickTaperConfig {
    fn default() -> Self {
        Self {
            min_screen_speed_px_per_ms: 0.55,
            max_dwell_ms: 32.0,
            max_tail_px: 48.0,
        }
    }
}

/// Core ink taper utilities matching `src/engine/TaperEngine.ts`.
pub struct TaperEngine;

impl TaperEngine {
    /// G-Pen 3-stage piecewise cubic Hermite S-curve pressure response:
    /// - Zone 1 `[0.00, 0.12]`: delicate hairline landing (`0.00 -> 0.06`)
    /// - Zone 2 `[0.12, 0.65]`: expressive main ink sweep (`0.06 -> 0.72`)
    /// - Zone 3 `[0.65, 1.00]`: full bold accent saturation (`0.72 -> 1.00`)
    pub fn map_pressure(raw_pressure: f32) -> f32 {
        let p = raw_pressure.clamp(0.0, 1.0);
        if p <= 0.12 {
            let t = p / 0.12;
            0.06 * (t * t * (3.0 - 2.0 * t))
        } else if p <= 0.65 {
            let t = (p - 0.12) / (0.65 - 0.12);
            0.06 + (0.72 - 0.06) * (t * t * (3.0 - 2.0 * t))
        } else {
            let t = (p - 0.65) / (1.0 - 0.65);
            0.72 + (1.0 - 0.72) * (t * t * (3.0 - 2.0 * t))
        }
    }

    /// Time-calibrated asymmetric exponential pressure smoothing (`dt_ms` frame-rate independent).
    pub fn smooth_pressure(prev: f32, target: f32, dt_ms: f64, responsiveness: f32) -> f32 {
        let dt = dt_ms.clamp(0.5, 64.0);
        let base_tau = (22.0 * (1.0 - responsiveness.clamp(0.0, 0.95) as f64)).max(2.0);
        // Faster attack on rising pressure, gentler release on falling pressure
        let tau = if target > prev {
            base_tau * 0.55
        } else {
            base_tau
        };
        let alpha = (1.0 - (-dt / tau).exp()) as f32;
        (prev + (target - prev) * alpha).clamp(0.0, 1.0)
    }

    /// Computes ballistic exit flick extrapolation points on pen-up.
    ///
    /// Parity rules from `TaperEngine.ts` & `strokePipelineIntegration.test.ts`:
    /// - Requires at least 3 recent points.
    /// - Dwell gate: if `lift_timestamp_ms - last_moving_point.timestamp_ms > 32.0`,
    ///   the artist paused before lifting -> returns empty `Vec`.
    /// - Screen-space speed gate: `doc_speed * zoom` must exceed `min_screen_speed_px_per_ms`
    ///   (so zoomed-out 0.1x strokes with low screen velocity don't explode into massive tails).
    /// - Extrapolates smoothly along the exit tangent with monotonically decaying width & pressure
    ///   to a razor tip, capping tail length cleanly.
    pub fn compute_flick_taper(
        recent_points: &[StrokePoint],
        lift_timestamp_ms: f64,
        zoom: f64,
        brush_size_doc: f64,
        config: FlickTaperConfig,
    ) -> Vec<StrokePoint> {
        if recent_points.len() < 3 {
            return Vec::new();
        }
        let last = recent_points[recent_points.len() - 1];

        // Find last meaningfully moving point to measure exit dwell accurately
        let mut last_moving_idx = recent_points.len() - 1;
        while last_moving_idx > 0 {
            let a = recent_points[last_moving_idx - 1];
            let b = recent_points[last_moving_idx];
            if (b.x - a.x).hypot(b.y - a.y) > 0.25 {
                break;
            }
            last_moving_idx -= 1;
        }
        let moving_end = recent_points[last_moving_idx];
        let dwell_ms = (lift_timestamp_ms - moving_end.timestamp_ms).max(0.0);
        if dwell_ms > config.max_dwell_ms {
            return Vec::new();
        }

        // Measure exit velocity & tangent over last ~24ms window (up to 5 points)
        let window_start = last_moving_idx.saturating_sub(4);
        let anchor = recent_points[window_start];
        let dx = moving_end.x - anchor.x;
        let dy = moving_end.y - anchor.y;
        let dist_doc = dx.hypot(dy);
        let dt_ms = (moving_end.timestamp_ms - anchor.timestamp_ms).max(1.0);
        if dist_doc < 1.0 {
            return Vec::new();
        }

        let safe_zoom = zoom.clamp(0.05, 64.0);
        let doc_speed = dist_doc / dt_ms;
        let screen_speed = doc_speed * safe_zoom;
        if screen_speed < config.min_screen_speed_px_per_ms {
            return Vec::new();
        }

        let dir_x = dx / dist_doc;
        let dir_y = dy / dist_doc;

        // Tail length scales with excess screen velocity, converted back to document space,
        // and tightly capped so zoomed-out strokes never produce wild runaways
        let excess = (screen_speed - config.min_screen_speed_px_per_ms).min(3.0);
        let raw_tail_screen = (excess * 18.0).clamp(4.0, config.max_tail_px);
        let max_tail_doc = (brush_size_doc * 2.5).clamp(12.0, config.max_tail_px / safe_zoom.max(0.5));
        let tail_doc = (raw_tail_screen / safe_zoom).min(max_tail_doc);

        let steps = ((tail_doc / 3.0).ceil() as usize).clamp(3, 8);
        let mut out = Vec::with_capacity(steps);
        for i in 1..=steps {
            let frac = i as f64 / steps as f64;
            let ease_pos = 1.0 - (1.0 - frac) * (1.0 - frac);
            let decay = (1.0 - frac).powf(1.6) as f32;
            let dist = tail_doc * ease_pos;
            out.push(StrokePoint {
                x: last.x + dir_x * dist,
                y: last.y + dir_y * dist,
                pressure: (last.pressure * decay).max(0.002),
                width: (last.width * decay).max(0.1),
                tilt_x: last.tilt_x,
                tilt_y: last.tilt_y,
                twist: last.twist,
                velocity: doc_speed * (1.0 - frac * 0.6),
                timestamp_ms: lift_timestamp_ms + frac * 12.0,
                is_corner: false,
            });
        }

        out
    }
}