Skip to content

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

8.8 KB
Raw Blame
//! Pressure & velocity curve evaluation:
//! - Monotone cubic Hermite (Fritsch–Carlson PCHIP) 256-entry LUT matching
//!   `BrushEngine.ts` (`getCompiledCurveLut` / `evaluateFastSpline`), including
//!   CSP leading/trailing stub deadzone protection.
//! - Global `PressureCurveSettings` (`pressureCurve.ts`) + per-brush gamma & curve.
//! - `calculate_stroke_width` matching `canvasUtils.ts` (including light-pressure
//!   anti-collapse floor for `pressure > 0.005`).

use serde::{Deserialize, Serialize};

/// Monotone 256-entry LUT compiled from sorted `[[x, y], ...]` control points
/// using Fritsch–Carlson PCHIP cubic Hermite interpolation.
#[derive(Debug, Clone)]
pub struct CompiledCurveLut {
    lut: [f32; 256],
}

impl CompiledCurveLut {
    pub fn linear() -> Self {
        let mut lut = [0.0f32; 256];
        for (i, slot) in lut.iter_mut().enumerate() {
            *slot = i as f32 / 255.0;
        }
        Self { lut }
    }

    /// Compiles control points into a 256-entry LUT matching `BrushEngine.ts`.
    pub fn compile(points: &[[f32; 2]]) -> Self {
        if points.len() < 2 {
            return Self::linear();
        }

        let mut sorted: Vec<[f32; 2]> = points
            .iter()
            .filter(|p| p[0].is_finite() && p[1].is_finite())
            .map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0)])
            .collect();
        if sorted.len() < 2 {
            return Self::linear();
        }
        sorted.sort_by(|a, b| a[0].total_cmp(&b[0]));

        // Deduplicate nearly-identical x coordinates (preserve latest y)
        let mut pts: Vec<[f32; 2]> = Vec::with_capacity(sorted.len());
        for p in sorted {
            if let Some(last) = pts.last_mut() {
                if (p[0] - last[0]).abs() < 1e-5 {
                    last[1] = p[1];
                    continue;
                }
            }
            pts.push(p);
        }
        if pts.len() < 2 {
            return Self::linear();
        }

        let n = pts.len();
        let mut dx = vec![0.0f64; n - 1];
        let mut slope = vec![0.0f64; n - 1];
        for i in 0..(n - 1) {
            dx[i] = (pts[i + 1][0] - pts[i][0]).max(1e-6) as f64;
            slope[i] = (pts[i + 1][1] - pts[i][1]) as f64 / dx[i];
        }

        // Fritsch–Carlson monotone cubic Hermite (PCHIP) tangents — matches BrushEngine.ts
        let mut m = vec![0.0f64; n];
        m[0] = slope[0];
        m[n - 1] = slope[n - 2];

        for i in 1..(n - 1) {
            if slope[i - 1] * slope[i] <= 0.0 {
                m[i] = 0.0;
            } else {
                let w1 = 2.0 * dx[i] + dx[i - 1];
                let w2 = dx[i] + 2.0 * dx[i - 1];
                m[i] = (w1 + w2) / (w1 / slope[i - 1] + w2 / slope[i]);
            }
        }

        // CSP compatibility: avoid zero-tangent deadzones caused by tiny leading/trailing stubs
        if n >= 3 && dx[0] < 0.08 && slope[0].abs() < 1e-3 {
            m[0] = 0.0;
        }
        if n >= 3 && dx[n - 2] < 0.08 && slope[n - 2].abs() < 1e-3 {
            m[n - 1] = 0.0;
        }

        // Endpoint monotonicity clamp (Fritsch–Carlson)
        if n >= 3 {
            if slope[0] == 0.0 || m[0].signum() != slope[0].signum() {
                m[0] = 0.0;
            } else if m[0].abs() > 3.0 * slope[0].abs() {
                m[0] = 3.0 * slope[0];
            }

            let last = n - 2;
            if slope[last] == 0.0 || m[n - 1].signum() != slope[last].signum() {
                m[n - 1] = 0.0;
            } else if m[n - 1].abs() > 3.0 * slope[last].abs() {
                m[n - 1] = 3.0 * slope[last];
            }
        }

        let mut lut = [0.0f32; 256];
        for (idx, slot) in lut.iter_mut().enumerate() {
            let x = idx as f64 / 255.0;
            if x <= pts[0][0] as f64 {
                *slot = pts[0][1].clamp(0.0, 1.0);
                continue;
            }
            if x >= pts[n - 1][0] as f64 {
                *slot = pts[n - 1][1].clamp(0.0, 1.0);
                continue;
            }

            let mut seg = 0usize;
            for i in 0..(n - 1) {
                if x >= pts[i][0] as f64 && x <= pts[i + 1][0] as f64 {
                    seg = i;
                    break;
                }
            }

            let h = dx[seg];
            let t = ((x - pts[seg][0] as f64) / h).clamp(0.0, 1.0);
            let t2 = t * t;
            let t3 = t2 * t;
            let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
            let h10 = t3 - 2.0 * t2 + t;
            let h01 = -2.0 * t3 + 3.0 * t2;
            let h11 = t3 - t2;

            let y = h00 * pts[seg][1] as f64
                + h10 * h * m[seg]
                + h01 * pts[seg + 1][1] as f64
                + h11 * h * m[seg + 1];
            *slot = (y as f32).clamp(0.0, 1.0);
        }

        Self { lut }
    }

    /// Evaluates the compiled LUT with linear interpolation between adjacent buckets.
    #[inline]
    pub fn evaluate(&self, t: f32) -> f32 {
        let clamped = t.clamp(0.0, 1.0);
        let scaled = clamped * 255.0;
        let idx = (scaled.floor() as usize).min(255);
        if idx >= 255 {
            return self.lut[255];
        }
        let frac = scaled - idx as f32;
        self.lut[idx] + (self.lut[idx + 1] - self.lut[idx]) * frac
    }
}

/// Evaluates an arbitrary spline curve directly (convenience helper for tests/one-offs).
pub fn evaluate_fast_spline(points: &[[f32; 2]], t: f32) -> f32 {
    if points.len() < 2 {
        return t.clamp(0.0, 1.0);
    }
    CompiledCurveLut::compile(points).evaluate(t)
}

/// Global pen-pressure curve settings synced from `AppSettings.pressureCurve`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GlobalPressureCurve {
    #[serde(default)]
    pub enabled: bool,
    /// Control points `[[x, y], ...]` normalized in `[0, 1]`.
    #[serde(default)]
    pub points: Vec<[f32; 2]>,
    #[serde(default = "default_gamma")]
    pub gamma: f32,
}

fn default_gamma() -> f32 {
    1.0
}

impl Default for GlobalPressureCurve {
    fn default() -> Self {
        Self {
            enabled: false,
            points: vec![[0.0, 0.0], [1.0, 1.0]],
            gamma: 1.0,
        }
    }
}

impl GlobalPressureCurve {
    pub fn compile_lut(&self) -> Option<CompiledCurveLut> {
        if !self.enabled {
            return None;
        }
        if self.points.len() >= 2 {
            Some(CompiledCurveLut::compile(&self.points))
        } else {
            None
        }
    }

    pub fn evaluate_raw(&self, raw_pressure: f32, compiled: Option<&CompiledCurveLut>) -> f32 {
        let p = raw_pressure.clamp(0.0, 1.0);
        if !self.enabled {
            return p;
        }
        let curved = if let Some(lut) = compiled {
            lut.evaluate(p)
        } else if self.points.len() >= 2 {
            evaluate_fast_spline(&self.points, p)
        } else {
            p
        };
        let gamma = self.gamma.clamp(0.2, 5.0);
        if (gamma - 1.0).abs() > 1e-4 {
            curved.clamp(0.0, 1.0).powf(gamma)
        } else {
            curved.clamp(0.0, 1.0)
        }
    }
}

/// Evaluates effective brush width from pressure, base size, min-size factor, gamma,
/// and optional compiled brush pressure curve.
///
/// Mirrors `calculateStrokeWidth` in `src/utils/canvasUtils.ts`:
/// - When `use_pressure == false`: returns `base_size`.
/// - Applies optional brush `pressure_curve` LUT and `pressure_curve_gamma`.
/// - Preserves real light-pressure contact (`raw_pressure > 0.005`) from collapsing to
///   zero while allowing `raw_pressure <= 0.005` to taper cleanly down to `0.1px`.
pub fn calculate_stroke_width(
    raw_pressure: f32,
    base_size: f32,
    use_pressure: bool,
    min_size_factor: f32,
    pressure_curve_gamma: f32,
    brush_curve_lut: Option<&CompiledCurveLut>,
) -> f32 {
    let base = base_size.max(0.1);
    if !use_pressure {
        return base;
    }

    let p = raw_pressure.clamp(0.0, 1.0);
    let min_factor = min_size_factor.clamp(0.0, 1.0);

    // Apply brush pressure curve LUT if provided, else gamma
    let mapped = if let Some(lut) = brush_curve_lut {
        lut.evaluate(p)
    } else {
        let g = pressure_curve_gamma.clamp(0.2, 5.0);
        if (g - 1.0).abs() > 1e-4 {
            p.powf(g)
        } else {
            p
        }
    };

    let factor = min_factor + (1.0 - min_factor) * mapped;
    let raw_width = base * factor;

    // Light-pressure anti-collapse floor (matches strokeStabilizerAndTabletResilience.test.ts):
    // Genuine stylus contact (> 0.005) retains a perceptible minimum hairline instead of collapsing
    // to 0.1px on steep S-curves; zero/near-zero exit pressure (<= 0.005) tapers cleanly to 0.1px.
    if p > 0.005 {
        let contact_floor = (base * min_factor.max(0.02)).min(base).max(0.25);
        raw_width.max(contact_floor).min(base * 2.0)
    } else {
        raw_width.max(0.1)
    }
}