Skip to content

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

3.7 KB
Raw Blame
//! Native Speculative Stroke Head Prediction (`prediction.rs`).
//!
//! Strictly ephemeral: builds transient predicted cubic Bézier segments from:
//! 1. The unsealed trailing spline bridge (`provisional_tail`),
//! 2. Smooth stabilizer catch-up toward the latest raw stylus coordinate, and
//! 3. Bounded velocity lookahead (`~10–14 ms`) along the instantaneous stroke tangent.
//!
//! Never mutates committed knots, stabilizer history, or document dirty bounds.
//! Rendered natively inside the `wgpu` compositor frame so `#ink-predicted-canvas`
//! can be completely deleted from the DOM!

use super::spline::{generate_provisional_segment, CubicBezierSegment, SplineGenerator};
use super::stabilizer::InputStabilizer;
use super::StrokePoint;

/// Configuration for speculative stroke head prediction.
#[derive(Debug, Clone, Copy)]
pub struct PredictionConfig {
    /// Lookahead horizon in milliseconds (default `12.0` ms, ~1 frame at 80–120 Hz).
    pub lookahead_ms: f64,
    /// Maximum velocity lookahead extension in screen pixels (prevents overshoot on turns).
    pub max_lookahead_screen_px: f64,
    /// Maximum catch-up bridge length in screen pixels.
    pub max_catchup_screen_px: f64,
}

impl Default for PredictionConfig {
    fn default() -> Self {
        Self {
            lookahead_ms: 12.0,
            max_lookahead_screen_px: 28.0,
            max_catchup_screen_px: 64.0,
        }
    }
}

/// Strictly ephemeral predicted tip geometry built from read-only references to
/// `SplineGenerator` and `InputStabilizer`.
pub fn build_predicted_segments(
    spline: &SplineGenerator,
    stabilizer: &InputStabilizer,
    zoom: f64,
    config: PredictionConfig,
) -> Vec<CubicBezierSegment> {
    let knots = spline.knots();
    if knots.is_empty() {
        return Vec::new();
    }

    let safe_zoom = zoom.clamp(0.05, 64.0);
    let mut out = spline.provisional_tail();

    let last_knot = *knots.last().unwrap();
    let prev_knot = if knots.len() >= 2 && !last_knot.is_corner {
        Some(knots[knots.len() - 2])
    } else {
        None
    };

    // 1. Stabilizer catch-up segment from last committed knot toward raw stylus tip
    let (raw_x, raw_y) = stabilizer.last_raw();
    let dx_raw = raw_x - last_knot.x;
    let dy_raw = raw_y - last_knot.y;
    let dist_raw = dx_raw.hypot(dy_raw);

    let mut head_anchor = last_knot;
    let mut head_prev = prev_knot;

    let min_bridge_doc = (0.6 / safe_zoom).max(0.2);
    if dist_raw > min_bridge_doc {
        let max_bridge_doc = config.max_catchup_screen_px / safe_zoom;
        let clamped_dist = dist_raw.min(max_bridge_doc);
        let scale = clamped_dist / dist_raw;
        let catchup_pt = StrokePoint {
            x: last_knot.x + dx_raw * scale,
            y: last_knot.y + dy_raw * scale,
            is_corner: false,
            ..last_knot
        };
        out.push(generate_provisional_segment(head_prev, head_anchor, catchup_pt));
        head_prev = Some(head_anchor);
        head_anchor = catchup_pt;
    }

    // 2. Bounded velocity lookahead (~12ms) when moving briskly
    let vel = stabilizer.velocity_doc_per_ms();
    let (tx, ty, has_tangent) = stabilizer.tangent();
    let screen_vel = vel * safe_zoom;
    if has_tangent && screen_vel > 0.25 && config.lookahead_ms > 0.0 {
        let look_doc = (vel * config.lookahead_ms)
            .min(config.max_lookahead_screen_px / safe_zoom);
        if look_doc > min_bridge_doc {
            let look_pt = StrokePoint {
                x: head_anchor.x + tx * look_doc,
                y: head_anchor.y + ty * look_doc,
                is_corner: false,
                ..head_anchor
            };
            out.push(generate_provisional_segment(head_prev, head_anchor, look_pt));
        }
    }

    out
}