Skip to content

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

33.0 KB
Raw Blame
//! Native Rust port of `src/engine/InputStabilizer.ts` + CSP Post-Correction.
//!
//! CSP-calibrated input stabilizer:
//! - 1-Euro asymmetric attack/decay filter for pen pressure
//! - CSP stabilization slider (0..50) mapped via `baseLengthPx = 3.5 + 23.5*t + 21.0*t^2`
//! - Velocity-adaptive tightening so fast gestures never rubber-band
//! - Strictly isotropic 3-stage exponential smoothing cascade (zero axis/tangent locking
//!   and zero directional anisotropy on diagonals or curves)
//! - Targeted 1-sample hardware backtrack & lift-off twitch guards (rejects transient
//!   digitizer jump-backs and near-zero-pressure nib lift wobbles without fighting real turns)
//! - Confirmed sharp-corner snapping (`sharpCorners`) with bounded `CornerConvergencePlan`
//!   sub-steps (requires sustained outgoing travel or decisive excursion, never firing on
//!   single-packet micro-jitter or stroke-start landing skids)
//! - Curvature-preserving cubic Bézier pen-up catch-up (`flush_catch_up`)
//! - CSP Post-Correction (`apply_csp_post_correction`, 0..5 passes preserving sharp corners)

use super::StrokePoint;

#[inline]
fn clamp_f64(v: f64, lo: f64, hi: f64) -> f64 {
    v.clamp(lo, hi)
}

#[inline]
fn alpha_from_cutoff(dt_sec: f64, cutoff_hz: f64) -> f64 {
    let tau = 1.0 / (2.0 * std::f64::consts::PI * cutoff_hz.max(0.001));
    1.0 / (1.0 + tau / dt_sec.max(1e-4))
}

/// 1-Euro low-pass filter axis with optional asymmetric attack/decay responsiveness
/// (used for fast pen-down attack + smooth lift decay on pressure).
#[derive(Debug, Clone)]
pub struct OneEuroAxis {
    min_cutoff: f64,
    beta: f64,
    d_cutoff: f64,
    x_prev: Option<f64>,
    dx_prev: f64,
}

impl OneEuroAxis {
    pub fn new(min_cutoff: f64, beta: f64, d_cutoff: f64) -> Self {
        Self {
            min_cutoff,
            beta,
            d_cutoff,
            x_prev: None,
            dx_prev: 0.0,
        }
    }

    pub fn reset(&mut self) {
        self.x_prev = None;
        self.dx_prev = 0.0;
    }

    pub fn filter(&mut self, value: f64, dt_sec: f64) -> f64 {
        let Some(prev) = self.x_prev else {
            self.x_prev = Some(value);
            self.dx_prev = 0.0;
            return value;
        };
        let dt = dt_sec.clamp(1.0 / 1000.0, 0.1);
        let raw_dx = (value - prev) / dt;
        let a_d = alpha_from_cutoff(dt, self.d_cutoff);
        let dx_hat = a_d * raw_dx + (1.0 - a_d) * self.dx_prev;

        // Asymmetric pressure responsiveness: faster attack when pressing down
        let speed_boost = if raw_dx > 0.0 { 1.35 } else { 1.0 };
        let cutoff = (self.min_cutoff + self.beta * dx_hat.abs() * speed_boost).max(0.1);
        let a = alpha_from_cutoff(dt, cutoff);
        let x_hat = a * value + (1.0 - a) * prev;

        self.x_prev = Some(x_hat);
        self.dx_prev = dx_hat;
        x_hat
    }
}

#[derive(Debug, Clone, Copy)]
pub struct StabilizerConfig {
    /// CSP stabilization level `0..=50`.
    pub stabilization: f32,
    /// Enable sharp-corner detection and smooth corner convergence.
    pub sharp_corners: bool,
    /// Current viewport zoom (for screen-pixel calibration).
    pub zoom: f32,
    /// Optional pressure smoothing intensity (`0.0..=1.0`, default 0.35).
    pub pressure_smoothing: f32,
}

impl Default for StabilizerConfig {
    fn default() -> Self {
        Self {
            stabilization: 0.0,
            sharp_corners: false,
            zoom: 1.0,
            pressure_smoothing: 0.35,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct StabilizedSample {
    pub x: f64,
    pub y: f64,
    pub pressure: f32,
    pub tilt_x: f32,
    pub tilt_y: f32,
    pub twist: f32,
    pub timestamp_ms: f64,
    /// Document-space speed (`px/ms`).
    pub velocity: f64,
    pub is_corner: bool,
    pub should_emit: bool,
    /// Optional bounded convergence sub-steps before the corner vertex itself.
    pub corner_convergence: Option<CornerConvergencePlan>,
}

/// Bounded sub-path bridging the lagged stabilizer point smoothly into a detected
/// sharp corner vertex (prevents visual teleports while maintaining exact C0 apex).
#[derive(Debug, Clone, Copy)]
pub struct CornerConvergencePlan {
    pub mid_x: f64,
    pub mid_y: f64,
    pub apex_x: f64,
    pub apex_y: f64,
}

#[derive(Debug, Clone, Copy)]
struct RawEntry {
    x: f64,
    y: f64,
}

/// CSP-calibrated input stabilizer matching `InputStabilizer.ts`.
#[derive(Debug, Clone)]
pub struct InputStabilizer {
    config: StabilizerConfig,
    pressure_filter: OneEuroAxis,

    // 3-stage isotropic exponential smoothing cascade (in document space)
    s1_x: f64,
    s1_y: f64,
    s2_x: f64,
    s2_y: f64,
    s3_x: f64,
    s3_y: f64,

    // Last emitted point & raw pointer tracking
    last_out_x: f64,
    last_out_y: f64,
    last_raw_x: f64,
    last_raw_y: f64,
    last_timestamp_ms: f64,
    last_pressure: f32,
    last_raw_pressure: f32,
    last_tilt_x: f32,
    last_tilt_y: f32,
    last_twist: f32,

    // Velocity & tangent tracking (used for lookahead & spike rejection, never anisotropic damping)
    ema_vel_doc_per_ms: f64,
    tangent_x: f64,
    tangent_y: f64,
    has_tangent: bool,
    total_travel_screen: f64,

    // Backtrack/lift-off spike guard & sharp-corner state
    recent_raw: Vec<RawEntry>,
    backtrack_hold_count: u32,
    liftoff_hold_count: u32,
    initialized: bool,
    sample_count: u64,
    last_corner_sample: u64,
}

impl InputStabilizer {
    pub fn new(config: StabilizerConfig) -> Self {
        let p_smooth = config.pressure_smoothing.clamp(0.0, 1.0) as f64;
        let min_cutoff = 6.0 - 4.0 * p_smooth;
        Self {
            config,
            pressure_filter: OneEuroAxis::new(min_cutoff, 14.0, 1.5),
            s1_x: 0.0,
            s1_y: 0.0,
            s2_x: 0.0,
            s2_y: 0.0,
            s3_x: 0.0,
            s3_y: 0.0,
            last_out_x: 0.0,
            last_out_y: 0.0,
            last_raw_x: 0.0,
            last_raw_y: 0.0,
            last_timestamp_ms: 0.0,
            last_pressure: 0.5,
            last_raw_pressure: 0.5,
            last_tilt_x: 0.0,
            last_tilt_y: 0.0,
            last_twist: 0.0,
            ema_vel_doc_per_ms: 0.0,
            tangent_x: 1.0,
            tangent_y: 0.0,
            has_tangent: false,
            total_travel_screen: 0.0,
            recent_raw: Vec::with_capacity(16),
            backtrack_hold_count: 0,
            liftoff_hold_count: 0,
            initialized: false,
            sample_count: 0,
            last_corner_sample: 0,
        }
    }

    pub fn update_config(&mut self, config: StabilizerConfig) {
        self.config = config;
    }

    pub fn reset(&mut self) {
        self.pressure_filter.reset();
        self.initialized = false;
        self.has_tangent = false;
        self.total_travel_screen = 0.0;
        self.ema_vel_doc_per_ms = 0.0;
        self.recent_raw.clear();
        self.backtrack_hold_count = 0;
        self.liftoff_hold_count = 0;
        self.sample_count = 0;
        self.last_corner_sample = 0;
    }

    #[inline]
    pub fn last_output(&self) -> (f64, f64) {
        (self.last_out_x, self.last_out_y)
    }

    #[inline]
    pub fn last_raw(&self) -> (f64, f64) {
        (self.last_raw_x, self.last_raw_y)
    }

    #[inline]
    pub fn velocity_doc_per_ms(&self) -> f64 {
        self.ema_vel_doc_per_ms
    }

    #[inline]
    pub fn tangent(&self) -> (f64, f64, bool) {
        (self.tangent_x, self.tangent_y, self.has_tangent)
    }

    /// Computes CSP-calibrated rope/cascade length in screen pixels (`level` in `0..=50`).
    /// Exact formula from `InputStabilizer.ts`: `baseLengthPx = 3.5 + 23.5*t + 21.0*t^2`.
    #[inline]
    pub fn csp_base_length_px(stabilization: f32) -> f64 {
        let lvl = (stabilization as f64).clamp(0.0, 50.0);
        if lvl <= 0.001 {
            return 0.0;
        }
        let t = lvl / 50.0;
        3.5 + 23.5 * t + 21.0 * t * t
    }

    /// Per-stage time constant (ms) bounding how long the stabilized tip may trail a pen that
    /// has slowed down or stopped. Grows with the stabilization level so heavy settings still
    /// glide, but never drags (level 6 ≈ 13 ms, level 20 ≈ 28 ms, level 50 ≈ 61 ms per stage).
    #[inline]
    pub fn settle_tau_ms(stabilization: f32) -> f64 {
        6.0 + 1.1 * (stabilization as f64).clamp(0.0, 50.0)
    }

    /// Processes a single incoming pointer sample in document space.
    #[allow(clippy::too_many_arguments)]
    pub fn process(
        &mut self,
        raw_x: f64,
        raw_y: f64,
        pressure: f32,
        tilt_x: f32,
        tilt_y: f32,
        twist: f32,
        timestamp_ms: f64,
    ) -> StabilizedSample {
        let safe_p = if pressure.is_finite() {
            pressure.clamp(0.0, 1.0)
        } else {
            self.last_pressure
        };
        let safe_zoom = (self.config.zoom as f64).clamp(0.05, 64.0);

        if !self.initialized {
            self.initialized = true;
            self.s1_x = raw_x;
            self.s1_y = raw_y;
            self.s2_x = raw_x;
            self.s2_y = raw_y;
            self.s3_x = raw_x;
            self.s3_y = raw_y;
            self.last_out_x = raw_x;
            self.last_out_y = raw_y;
            self.last_raw_x = raw_x;
            self.last_raw_y = raw_y;
            self.last_timestamp_ms = timestamp_ms;
            self.last_pressure = safe_p;
            self.last_raw_pressure = safe_p;
            self.last_tilt_x = tilt_x;
            self.last_tilt_y = tilt_y;
            self.last_twist = twist;
            self.total_travel_screen = 0.0;
            self.backtrack_hold_count = 0;
            self.liftoff_hold_count = 0;
            self.sample_count = 1;
            self.recent_raw.clear();
            self.recent_raw.push(RawEntry {
                x: raw_x,
                y: raw_y,
            });
            let p_out = self.pressure_filter.filter(safe_p as f64, 0.008) as f32;
            return StabilizedSample {
                x: raw_x,
                y: raw_y,
                pressure: p_out.clamp(0.0, 1.0),
                tilt_x,
                tilt_y,
                twist,
                timestamp_ms,
                velocity: 0.0,
                is_corner: false,
                should_emit: true,
                corner_convergence: None,
            };
        }

        self.sample_count += 1;
        let dt_ms = (timestamp_ms - self.last_timestamp_ms).clamp(0.5, 100.0);
        let dt_sec = dt_ms * 0.001;

        let raw_dx = raw_x - self.last_raw_x;
        let raw_dy = raw_y - self.last_raw_y;
        let raw_dist_doc = raw_dx.hypot(raw_dy);
        let raw_dist_screen = raw_dist_doc * safe_zoom;

        // 1. Targeted hardware spike & stylus lift-off twitch guards:
        // (a) Single-packet backward reversal during brisk motion (>= 141 deg): hold for 1 sample
        //     so isolated digitizer jump-backs never inject a V-glitch hook.
        // (b) Stylus lift-off wobble: when pressure collapses sharply to near-zero (nib breaking
        //     contact with the tablet) and the coil reports a sudden sharp sideways/backward jump
        //     (> 75 deg from the stroke trajectory), hold so pen-up never draws a hook.
        //     Clean tapered flicks along the stroke direction (fwd_dot > 0.25) pass untouched.
        let mut eff_x = raw_x;
        let mut eff_y = raw_y;
        let mut held_glitch = false;
        let is_liftoff_pressure = (safe_p <= 0.035 && self.last_raw_pressure > 0.06)
            || (safe_p <= 0.015 && self.last_raw_pressure <= 0.035);

        if self.has_tangent && self.total_travel_screen >= 6.0 && raw_dist_screen > 1.5 {
            let ux = raw_dx / raw_dist_doc.max(1e-6);
            let uy = raw_dy / raw_dist_doc.max(1e-6);
            let fwd_dot = ux * self.tangent_x + uy * self.tangent_y;

            if is_liftoff_pressure && fwd_dot < 0.25 && self.liftoff_hold_count < 2 {
                self.liftoff_hold_count += 1;
                eff_x = self.last_raw_x;
                eff_y = self.last_raw_y;
                held_glitch = true;
            } else if raw_dist_screen > 2.0
                && self.ema_vel_doc_per_ms * safe_zoom > 0.35
                && fwd_dot < -0.78
                && self.backtrack_hold_count == 0
            {
                self.backtrack_hold_count = 1;
                eff_x = self.last_raw_x;
                eff_y = self.last_raw_y;
                held_glitch = true;
            } else {
                self.backtrack_hold_count = 0;
                if !is_liftoff_pressure {
                    self.liftoff_hold_count = 0;
                }
            }
        } else {
            self.backtrack_hold_count = 0;
            if !is_liftoff_pressure {
                self.liftoff_hold_count = 0;
            }
        }

        let step_dx = eff_x - self.last_raw_x;
        let step_dy = eff_y - self.last_raw_y;
        let step_dist_doc = step_dx.hypot(step_dy);
        let step_dist_screen = step_dist_doc * safe_zoom;
        self.total_travel_screen += step_dist_screen;
        let inst_vel = step_dist_doc / dt_ms;
        self.ema_vel_doc_per_ms = self.ema_vel_doc_per_ms * 0.72 + inst_vel * 0.28;

        // Pressure 1-Euro filtering
        let filtered_p = (self.pressure_filter.filter(safe_p as f64, dt_sec) as f32).clamp(0.0, 1.0);
        // Subtle tilt smoothing
        let tilt_alpha = 0.55f32;
        let smooth_tx = self.last_tilt_x + (tilt_x - self.last_tilt_x) * tilt_alpha;
        let smooth_ty = self.last_tilt_y + (tilt_y - self.last_tilt_y) * tilt_alpha;
        self.last_tilt_x = smooth_tx;
        self.last_tilt_y = smooth_ty;
        self.last_twist = twist;
        self.last_pressure = filtered_p;
        self.last_raw_pressure = safe_p;

        let level = self.config.stabilization.clamp(0.0, 50.0);

        // Zero stabilization fast-path: pass raw pointer directly
        if level <= 0.001 {
            if step_dist_doc > 1e-4 && self.total_travel_screen >= 2.0 {
                let nx = step_dx / step_dist_doc;
                let ny = step_dy / step_dist_doc;
                if self.has_tangent {
                    let bx = self.tangent_x * 0.55 + nx * 0.45;
                    let by = self.tangent_y * 0.55 + ny * 0.45;
                    let blen = bx.hypot(by);
                    if blen > 1e-5 {
                        self.tangent_x = bx / blen;
                        self.tangent_y = by / blen;
                    }
                } else {
                    self.tangent_x = nx;
                    self.tangent_y = ny;
                    self.has_tangent = true;
                }
            }
            self.s1_x = eff_x;
            self.s1_y = eff_y;
            self.s2_x = eff_x;
            self.s2_y = eff_y;
            self.s3_x = eff_x;
            self.s3_y = eff_y;
            self.last_out_x = eff_x;
            self.last_out_y = eff_y;
            self.last_raw_x = eff_x;
            self.last_raw_y = eff_y;
            self.last_timestamp_ms = timestamp_ms;
            if !held_glitch {
                self.push_raw_history(eff_x, eff_y);
            }
            return StabilizedSample {
                x: eff_x,
                y: eff_y,
                pressure: filtered_p,
                tilt_x: smooth_tx,
                tilt_y: smooth_ty,
                twist,
                timestamp_ms,
                velocity: self.ema_vel_doc_per_ms,
                is_corner: false,
                should_emit: !held_glitch
                    && (step_dist_doc > 0.05 || (safe_p - filtered_p).abs() > 0.05),
                corner_convergence: None,
            };
        }

        // 2. Confirmed sharp-corner detection (before smoothing cascade swallows a genuine apex).
        // Never snaps during initial touchdown travel or during lift-off pressure collapse,
        // and requires either sustained multi-sample outgoing motion or a decisive large turn.
        let mut corner_convergence: Option<CornerConvergencePlan> = None;
        if self.config.sharp_corners
            && !held_glitch
            && !is_liftoff_pressure
            && self.total_travel_screen >= 12.0
            && self.recent_raw.len() >= 3
            && self.sample_count.saturating_sub(self.last_corner_sample) >= 3
        {
            if let Some((apex_x, apex_y)) = self.detect_sharp_corner(eff_x, eff_y, safe_zoom) {
                self.last_corner_sample = self.sample_count;
                let dist_to_apex = (apex_x - self.last_out_x).hypot(apex_y - self.last_out_y);
                let max_direct_step = (3.5 / safe_zoom).max(1.5);
                if dist_to_apex > max_direct_step {
                    // Smooth bounded midpoint convergence instead of hard teleport
                    corner_convergence = Some(CornerConvergencePlan {
                        mid_x: self.last_out_x + (apex_x - self.last_out_x) * 0.55,
                        mid_y: self.last_out_y + (apex_y - self.last_out_y) * 0.55,
                        apex_x,
                        apex_y,
                    });
                }
                // Re-anchor 3-stage cascade at the detected apex so outgoing leg starts crisp
                self.s1_x = apex_x;
                self.s1_y = apex_y;
                self.s2_x = apex_x;
                self.s2_y = apex_y;
                self.s3_x = apex_x;
                self.s3_y = apex_y;
                // Update tangent to outgoing leg direction
                let out_dx = eff_x - apex_x;
                let out_dy = eff_y - apex_y;
                let out_len = out_dx.hypot(out_dy);
                if out_len > 1e-4 {
                    self.tangent_x = out_dx / out_len;
                    self.tangent_y = out_dy / out_len;
                    self.has_tangent = true;
                }
                self.last_out_x = apex_x;
                self.last_out_y = apex_y;
                self.last_raw_x = eff_x;
                self.last_raw_y = eff_y;
                self.last_timestamp_ms = timestamp_ms;
                // Reset raw history to start cleanly from the snapped apex
                self.recent_raw.clear();
                self.recent_raw.push(RawEntry {
                    x: apex_x,
                    y: apex_y,
                });
                self.recent_raw.push(RawEntry { x: eff_x, y: eff_y });
                return StabilizedSample {
                    x: apex_x,
                    y: apex_y,
                    pressure: filtered_p,
                    tilt_x: smooth_tx,
                    tilt_y: smooth_ty,
                    twist,
                    timestamp_ms,
                    velocity: self.ema_vel_doc_per_ms,
                    is_corner: true,
                    should_emit: true,
                    corner_convergence,
                };
            }
        }

        // 3. Step-length guard (strictly scalar so filtering remains 100% isotropic):
        // Prevents a sudden isolated perpendicular spike from inflating the scalar gain `k`
        // across all 3 stages, while applying the EXACT SAME gain to X and Y so the filter
        // can NEVER lock onto an axis or bend a diagonal line!
        let mut effective_step_doc = step_dist_doc;
        if self.has_tangent && step_dist_doc > 1e-4 {
            let along = step_dx * self.tangent_x + step_dy * self.tangent_y;
            effective_step_doc = step_dist_doc.min(along.max(0.0).max(0.62 * step_dist_doc));
        }

        // 4. Velocity-adaptive CSP-calibrated strictly isotropic 3-stage exponential cascade
        // Matches CSP steady-state lag bounds:
        // - Level 1: ~3.5px screen lag
        // - Level 18..20: ~14..16px screen lag (always <= 18px on smooth sine waves)
        // - Level 50: ~42..48px screen lag (capped smoothly at high gesture velocity)
        let base_len_screen = Self::csp_base_length_px(level);
        let vel_screen_per_ms = self.ema_vel_doc_per_ms * safe_zoom;
        // Velocity-adaptive tightening: tighten lag gently at high flick speeds so cursor never rubber-bands
        let vel_tighten = 1.0 / (1.0 + (vel_screen_per_ms * 0.42).powf(1.3));
        let eff_len_screen = (base_len_screen * (0.45 + 0.55 * vel_tighten)).max(0.5);
        let eff_len_doc = eff_len_screen / safe_zoom;

        // Exact sample-rate-invariant steady-state lag for a 3-stage cascade:
        // Steady-state lag per stage is `ds * (1 - k) / k = stage_len` => `k = ds / (ds + stage_len)`.
        // Identical feel across 60 Hz mouse, 144 Hz WinInk, and 500 Hz WinTab!
        let stage_len = (eff_len_doc / 3.0).max(1e-4);
        let dist_to_target = (eff_x - self.s1_x).hypot(eff_y - self.s1_y);
        let ds = effective_step_doc.max(dist_to_target * 0.12);
        // Time-based convergence floor. The distance-driven gain above tends to zero as the
        // residual lag shrinks, so once the hand slows or stops the line used to creep toward
        // the pen asymptotically (~400 ms at level 6) — the "rubbery" drag inkers complain
        // about. A per-millisecond time constant guarantees a bounded settle time and makes the
        // settle feel identical at 60 Hz mouse, 240 Hz Windows Ink, and 1 kHz WinTab rates.
        // While the pen is still travelling (slow careful lines, tremor) the floor relaxes 2.5x so
        // jitter smoothing is preserved; it bites fully only once the pen has actually stopped.
        let motion = clamp_f64(inst_vel * safe_zoom / 0.08, 0.0, 1.0);
        let settle_tau_ms = Self::settle_tau_ms(level) * (1.0 + 1.5 * motion);
        let k_time = 1.0 - (-dt_ms / settle_tau_ms).exp();
        let k = clamp_f64((ds / (ds + stage_len)).max(k_time), 0.0, 0.92);

        // Strictly isotropic 3-stage convex cascade: identical scalar gain in every direction
        // (zero axis bias, zero tangent lock-in, zero elbowing on diagonals or curves).
        self.s1_x += (eff_x - self.s1_x) * k;
        self.s1_y += (eff_y - self.s1_y) * k;
        self.s2_x += (self.s1_x - self.s2_x) * k;
        self.s2_y += (self.s1_y - self.s2_y) * k;
        self.s3_x += (self.s2_x - self.s3_x) * k;
        self.s3_y += (self.s2_y - self.s3_y) * k;

        // Hard lag leash so smooth sine waves at medium stabilization (18..20) never exceed CSP ceiling
        let max_leash_doc = (base_len_screen * 1.12) / safe_zoom;
        let lag_dx = eff_x - self.s3_x;
        let lag_dy = eff_y - self.s3_y;
        let lag_dist = lag_dx.hypot(lag_dy);
        if lag_dist > max_leash_doc && lag_dist > 1e-6 {
            let pull = (lag_dist - max_leash_doc) / lag_dist;
            self.s3_x += lag_dx * pull;
            self.s3_y += lag_dy * pull;
            self.s2_x += lag_dx * pull * 0.65;
            self.s2_y += lag_dy * pull * 0.65;
        }

        let out_dx = self.s3_x - self.last_out_x;
        let out_dy = self.s3_y - self.last_out_y;
        let out_dist_doc = out_dx.hypot(out_dy);

        // Update smooth tangent ONLY from meaningful stabilized output motion (never from a
        // 0.5px raw touchdown micro-step, which can point in an arbitrary quantized direction).
        if out_dist_doc > (0.5 / safe_zoom) && self.total_travel_screen >= 3.0 {
            let nx = out_dx / out_dist_doc;
            let ny = out_dy / out_dist_doc;
            if self.has_tangent {
                let bx = self.tangent_x * 0.55 + nx * 0.45;
                let by = self.tangent_y * 0.55 + ny * 0.45;
                let blen = bx.hypot(by);
                if blen > 1e-5 {
                    self.tangent_x = bx / blen;
                    self.tangent_y = by / blen;
                }
            } else {
                self.tangent_x = nx;
                self.tangent_y = ny;
                self.has_tangent = true;
            }
        }

        let min_emit_doc = (0.35 / safe_zoom).max(0.05);
        let should_emit = out_dist_doc >= min_emit_doc;
        if should_emit {
            self.last_out_x = self.s3_x;
            self.last_out_y = self.s3_y;
        }

        self.last_raw_x = eff_x;
        self.last_raw_y = eff_y;
        self.last_timestamp_ms = timestamp_ms;
        if !held_glitch {
            self.push_raw_history(eff_x, eff_y);
        }

        StabilizedSample {
            x: self.s3_x,
            y: self.s3_y,
            pressure: filtered_p,
            tilt_x: smooth_tx,
            tilt_y: smooth_ty,
            twist,
            timestamp_ms,
            velocity: self.ema_vel_doc_per_ms,
            is_corner: false,
            should_emit,
            corner_convergence: None,
        }
    }

    /// Returns the full-tail catch-up target when the pen lifts, converging the lagged
    /// stabilized tip smoothly all the way to the exact final raw stylus coordinate.
    pub fn get_catch_up_target(&self) -> Option<(f64, f64, f64)> {
        if !self.initialized {
            return None;
        }
        let dx = self.last_raw_x - self.last_out_x;
        let dy = self.last_raw_y - self.last_out_y;
        let dist = dx.hypot(dy);
        if dist < 0.25 {
            return None;
        }
        Some((self.last_raw_x, self.last_raw_y, dist))
    }

    /// Generates curvature-preserving cubic Bézier catch-up samples from `last_out` (`s3`)
    /// through the cascade state `(s2, s1)` to `last_raw` on pen-up.
    /// Guarantees C1 tangent continuity at `last_out`, zero overshoot (convex hull property),
    /// and exact convergence onto the final lift coordinate without straight-chord corner cutting.
    pub fn flush_catch_up(&mut self, final_timestamp_ms: f64) -> Vec<StabilizedSample> {
        let Some((tx, ty, dist)) = self.get_catch_up_target() else {
            return Vec::new();
        };
        let safe_zoom = (self.config.zoom as f64).clamp(0.05, 64.0);
        let step_len = (6.0 / safe_zoom).max(1.5);
        let steps = ((dist / step_len).ceil() as usize).clamp(1, 16);
        let mut out = Vec::with_capacity(steps);
        let p0x = self.last_out_x;
        let p0y = self.last_out_y;
        let p1x = self.s2_x;
        let p1y = self.s2_y;
        let p2x = self.s1_x;
        let p2y = self.s1_y;
        let start_t = self.last_timestamp_ms;
        let dt_total = (final_timestamp_ms - start_t).max(1.0);

        for i in 1..=steps {
            let u = i as f64 / steps as f64;
            let inv = 1.0 - u;
            let b0 = inv * inv * inv;
            let b1 = 3.0 * inv * inv * u;
            let b2 = 3.0 * inv * u * u;
            let b3 = u * u * u;
            let x = b0 * p0x + b1 * p1x + b2 * p2x + b3 * tx;
            let y = b0 * p0y + b1 * p1y + b2 * p2y + b3 * ty;
            out.push(StabilizedSample {
                x,
                y,
                pressure: self.last_pressure,
                tilt_x: self.last_tilt_x,
                tilt_y: self.last_tilt_y,
                twist: self.last_twist,
                timestamp_ms: start_t + dt_total * u,
                velocity: self.ema_vel_doc_per_ms,
                is_corner: false,
                should_emit: true,
                corner_convergence: None,
            });
        }

        self.s1_x = tx;
        self.s1_y = ty;
        self.s2_x = tx;
        self.s2_y = ty;
        self.s3_x = tx;
        self.s3_y = ty;
        self.last_out_x = tx;
        self.last_out_y = ty;
        out
    }

    fn push_raw_history(&mut self, x: f64, y: f64) {
        self.recent_raw.push(RawEntry { x, y });
        if self.recent_raw.len() > 14 {
            self.recent_raw.remove(0);
        }
    }

    /// Detects a genuine intentional sharp corner (>= 72 deg directional turn) while strictly
    /// rejecting 1-sample digitizer twitches, touchdown wobbles, and smooth curves.
    ///
    /// Two confirmation paths:
    /// - Path A (decisive single excursion): incoming leg >= 10 screen px AND outgoing excursion
    ///   >= 14 screen px at >= 72 deg (handles 60 Hz mouse / fast flick corners).
    /// - Path B (multi-sample confirmed corner for 240–500 Hz tablets): candidate apex 1–3 samples
    ///   back with incoming leg >= 10 screen px and >= 2 consecutive coherent outgoing samples
    ///   spanning >= 8 screen px at >= 72 deg.
    fn detect_sharp_corner(&self, cur_x: f64, cur_y: f64, zoom: f64) -> Option<(f64, f64)> {
        let n = self.recent_raw.len();
        if n < 3 {
            return None;
        }
        let in_min_doc = (10.0 / zoom).max(3.0);
        let single_out_min_doc = (14.0 / zoom).max(5.0);
        let multi_out_min_doc = (8.0 / zoom).max(2.5);
        // Corner threshold: turning angle >= ~72 degrees (cos < 0.31)
        const MAX_CORNER_COS: f64 = 0.31;

        let find_incoming_vec = |apex_idx: usize| -> Option<(f64, f64, f64)> {
            let apex = self.recent_raw[apex_idx];
            for i in (0..apex_idx).rev() {
                let cand = self.recent_raw[i];
                let dx = apex.x - cand.x;
                let dy = apex.y - cand.y;
                let len = dx.hypot(dy);
                if len >= in_min_doc {
                    return Some((dx, dy, len));
                }
            }
            None
        };

        // Path A: Decisive single excursion from the most recent raw point
        let last_apex = self.recent_raw[n - 1];
        let out_dx = cur_x - last_apex.x;
        let out_dy = cur_y - last_apex.y;
        let out_len = out_dx.hypot(out_dy);
        if out_len >= single_out_min_doc {
            if let Some((in_dx, in_dy, in_len)) = find_incoming_vec(n - 1) {
                let cos_angle =
                    ((in_dx * out_dx + in_dy * out_dy) / (in_len * out_len)).clamp(-1.0, 1.0);
                if cos_angle < MAX_CORNER_COS {
                    return Some((last_apex.x, last_apex.y));
                }
            }
        }

        // Path B: Multi-sample confirmed corner (apex 1..=3 samples back, >= 2 coherent outgoing steps)
        let max_back = (n - 1).min(4);
        for back in 2..=max_back {
            let apex_idx = n - back;
            let apex = self.recent_raw[apex_idx];
            let odx = cur_x - apex.x;
            let ody = cur_y - apex.y;
            let olen = odx.hypot(ody);
            if olen < multi_out_min_doc {
                continue;
            }
            let Some((in_dx, in_dy, in_len)) = find_incoming_vec(apex_idx) else {
                continue;
            };
            let cos_angle = ((in_dx * odx + in_dy * ody) / (in_len * olen)).clamp(-1.0, 1.0);
            if cos_angle >= MAX_CORNER_COS {
                continue;
            }
            // Confirm intermediate samples from apex -> cur progress coherently along outgoing ray
            let uox = odx / olen;
            let uoy = ody / olen;
            let mut prev_proj = 0.0f64;
            let mut coherent = true;
            for j in (apex_idx + 1)..n {
                let pt = self.recent_raw[j];
                let rx = pt.x - apex.x;
                let ry = pt.y - apex.y;
                let proj = rx * uox + ry * uoy;
                let perp = (rx * (-uoy) + ry * uox).abs();
                if proj < prev_proj - (0.5 / zoom) || perp > olen * 0.35 + (1.0 / zoom) {
                    coherent = false;
                    break;
                }
                prev_proj = proj;
            }
            if coherent && olen > prev_proj {
                return Some((apex.x, apex.y));
            }
        }

        None
    }
}

/// CSP Post-Correction (`postCorrection` 0..=5):
/// Applies gentle Laplacian / Gaussian-weighted polyline smoothing on pen-up while
/// strictly pinning endpoints and sharp corners (`is_corner == true` or turning angle >= 55°).
pub fn apply_csp_post_correction(points: &[StrokePoint], level: u8) -> Vec<StrokePoint> {
    let clamped = level.min(5);
    if clamped == 0 || points.len() < 4 {
        return points.to_vec();
    }

    let mut cur = points.to_vec();
    let n = cur.len();

    // Pre-identify pinned sharp corners
    let mut pinned = vec![false; n];
    pinned[0] = true;
    pinned[n - 1] = true;
    for i in 1..(n - 1) {
        if cur[i].is_corner {
            pinned[i] = true;
            continue;
        }
        let ax = cur[i].x - cur[i - 1].x;
        let ay = cur[i].y - cur[i - 1].y;
        let bx = cur[i + 1].x - cur[i].x;
        let by = cur[i + 1].y - cur[i].y;
        let la = ax.hypot(ay);
        let lb = bx.hypot(by);
        if la > 4.0 && lb > 4.0 {
            let cos_a = ((ax * bx + ay * by) / (la * lb)).clamp(-1.0, 1.0);
            // Only auto-pin genuine sharp geometric corners (>= ~78.5 deg); allow small
            // high-frequency hand jitter oscillations to smooth cleanly.
            if cos_a < 0.20 {
                pinned[i] = true;
            }
        }
    }

    // Passes & weight calibrated to CSP Post Correction 1..5
    let passes = (clamped as usize) * 2;
    let weight = 0.22 + (clamped as f64) * 0.05;
    let mut next = cur.clone();

    for _ in 0..passes {
        for i in 1..(n - 1) {
            if pinned[i] {
                next[i] = cur[i];
                continue;
            }
            let avg_x = 0.25 * cur[i - 1].x + 0.5 * cur[i].x + 0.25 * cur[i + 1].x;
            let avg_y = 0.25 * cur[i - 1].y + 0.5 * cur[i].y + 0.25 * cur[i + 1].y;
            let avg_p = 0.25 * cur[i - 1].pressure + 0.5 * cur[i].pressure + 0.25 * cur[i + 1].pressure;
            next[i] = cur[i];
            next[i].x = cur[i].x + (avg_x - cur[i].x) * weight;
            next[i].y = cur[i].y + (avg_y - cur[i].y) * weight;
            next[i].pressure = cur[i].pressure + (avg_p - cur[i].pressure) * (weight as f32 * 0.5);
        }
        std::mem::swap(&mut cur, &mut next);
    }

    cur
}