Skip to content

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

10.6 KB
Raw Blame
//! Native Straight Ruler & Perspective Ruler Snapping in Rust.
//!
//! Exact ports of:
//! - `src/utils/straightRulerMath.ts` (`StraightRulerSnapSession`)
//! - `src/utils/perspectiveSnapping.ts` & `src/utils/perspectiveMath.ts` (`PerspectiveSnapSession`)

use serde::{Deserialize, Serialize};

/// Straight ruler configuration synced from React (`StraightRulerConfig`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StraightRulerConfig {
    pub enabled: bool,
    pub visible: bool,
    pub snap_enabled: bool,
    /// Center X in document pixels.
    pub x: f64,
    /// Center Y in document pixels.
    pub y: f64,
    /// Angle in degrees.
    pub angle: f64,
    /// Length in document pixels.
    #[serde(default = "default_ruler_length")]
    pub length: f64,
    #[serde(default)]
    pub locked: bool,
}

fn default_ruler_length() -> f64 {
    600.0
}

impl StraightRulerConfig {
    #[inline]
    pub fn direction(&self) -> (f64, f64) {
        let rad = self.angle.to_radians();
        (rad.cos(), rad.sin())
    }

    #[inline]
    pub fn normal(&self) -> (f64, f64) {
        let (dx, dy) = self.direction();
        (-dy, dx)
    }

    #[inline]
    pub fn signed_distance_to_line(&self, px: f64, py: f64) -> f64 {
        let (nx, ny) = self.normal();
        (px - self.x) * nx + (py - self.y) * ny
    }

    #[inline]
    pub fn project_onto_line(&self, px: f64, py: f64) -> (f64, f64) {
        let (dx, dy) = self.direction();
        let t = (px - self.x) * dx + (py - self.y) * dy;
        (self.x + dx * t, self.y + dy * t)
    }
}

/// Active per-stroke Straight Ruler snapping session (`straightRulerMath.ts`).
#[derive(Debug, Clone)]
pub struct StraightRulerSnapSession {
    anchor_x: f64,
    anchor_y: f64,
    dir_x: f64,
    dir_y: f64,
    pub snapped_to_edge: bool,
    pub active: bool,
}

impl StraightRulerSnapSession {
    /// Starts a straight-ruler snap session at pointer-down `(start_x, start_y)`.
    ///
    /// Matches `StraightRulerSnapSession` in `straightRulerMath.ts`:
    /// - If within `26.0 / zoom` doc px of the ruler edge, locks directly onto the ruler line.
    /// - Otherwise draws a parallel guideline passing through `(start_x, start_y)`.
    pub fn begin(
        ruler: &StraightRulerConfig,
        start_x: f64,
        start_y: f64,
        zoom: f64,
        alt_override: bool,
    ) -> Self {
        if !ruler.enabled || !ruler.visible || !ruler.snap_enabled || alt_override {
            return Self {
                anchor_x: start_x,
                anchor_y: start_y,
                dir_x: 1.0,
                dir_y: 0.0,
                snapped_to_edge: false,
                active: false,
            };
        }

        let (dir_x, dir_y) = ruler.direction();
        let edge_threshold = 26.0 / zoom.clamp(0.05, 64.0);
        let dist = ruler.signed_distance_to_line(start_x, start_y).abs();
        if dist <= edge_threshold {
            let (px, py) = ruler.project_onto_line(start_x, start_y);
            Self {
                anchor_x: px,
                anchor_y: py,
                dir_x,
                dir_y,
                snapped_to_edge: true,
                active: true,
            }
        } else {
            Self {
                anchor_x: start_x,
                anchor_y: start_y,
                dir_x,
                dir_y,
                snapped_to_edge: false,
                active: true,
            }
        }
    }

    #[inline]
    pub fn snap(&self, x: f64, y: f64, alt_override: bool) -> (f64, f64) {
        if !self.active || alt_override {
            return (x, y);
        }
        let t = (x - self.anchor_x) * self.dir_x + (y - self.anchor_y) * self.dir_y;
        (self.anchor_x + self.dir_x * t, self.anchor_y + self.dir_y * t)
    }
}

/// Perspective ruler vanishing point.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VanishingPoint {
    pub id: String,
    pub x: f64,
    pub y: f64,
    #[serde(default = "default_vp_enabled")]
    pub enabled: bool,
}

fn default_vp_enabled() -> bool {
    true
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PerspectiveMode {
    #[serde(rename = "1-point")]
    OnePoint,
    #[serde(rename = "2-point")]
    TwoPoint,
    #[serde(rename = "3-point")]
    ThreePoint,
}

/// Perspective ruler configuration synced from React (`PerspectiveRuler`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PerspectiveRulerConfig {
    pub enabled: bool,
    pub visible: bool,
    pub snap_enabled: bool,
    pub mode: PerspectiveMode,
    #[serde(default)]
    pub horizon_angle: f64,
    #[serde(default)]
    pub vanishing_points: Vec<VanishingPoint>,
}

/// Locked perspective axis ray passing through the stroke's starting point.
#[derive(Debug, Clone, Copy)]
pub struct LockedPerspectiveAxis {
    pub dir_x: f64,
    pub dir_y: f64,
    pub axis_index: usize,
}

/// Active per-stroke Perspective Ruler snapping session (`perspectiveSnapping.ts`).
#[derive(Debug, Clone)]
pub struct PerspectiveSnapSession {
    active: bool,
    start_x: f64,
    start_y: f64,
    candidate_axes: Vec<(f64, f64)>,
    locked_axis: Option<LockedPerspectiveAxis>,
    lock_threshold_doc: f64,
}

impl PerspectiveSnapSession {
    /// Initializes candidate snapping rays passing through `(start_x, start_y)`.
    ///
    /// Matches `PerspectiveSnapSession` (`perspectiveSnapping.ts` & `perspectiveMath.ts`):
    /// - 1-point: ray to VP0 + horizontal along horizon + vertical perpendicular to horizon.
    /// - 2-point: rays to VP0 & VP1 + vertical perpendicular to horizon.
    /// - 3-point: rays to VP0, VP1, & VP2.
    /// - Lock threshold: `4.0` doc px, selecting candidate maximizing `|dot(move_dir, axis_dir)|`.
    pub fn begin(
        ruler: &PerspectiveRulerConfig,
        start_x: f64,
        start_y: f64,
        alt_override: bool,
    ) -> Self {
        if !ruler.enabled || !ruler.visible || !ruler.snap_enabled || alt_override {
            return Self {
                active: false,
                start_x,
                start_y,
                candidate_axes: Vec::new(),
                locked_axis: None,
                lock_threshold_doc: 4.0,
            };
        }

        let mut axes: Vec<(f64, f64)> = Vec::with_capacity(4);
        let h_rad = ruler.horizon_angle.to_radians();
        let h_dir = (h_rad.cos(), h_rad.sin());
        let v_dir = (-h_rad.sin(), h_rad.cos());

        let max_vps = match ruler.mode {
            PerspectiveMode::OnePoint => 1,
            PerspectiveMode::TwoPoint => 2,
            PerspectiveMode::ThreePoint => 3,
        };

        for vp in ruler.vanishing_points.iter().take(max_vps) {
            if !vp.enabled {
                continue;
            }
            let dx = vp.x - start_x;
            let dy = vp.y - start_y;
            let len = dx.hypot(dy);
            if len > 1e-4 {
                axes.push((dx / len, dy / len));
            }
        }

        match ruler.mode {
            PerspectiveMode::OnePoint => {
                axes.push(h_dir);
                axes.push(v_dir);
            }
            PerspectiveMode::TwoPoint => {
                axes.push(v_dir);
            }
            PerspectiveMode::ThreePoint => {
                // If fewer than 3 VPs are active, still provide vertical fallback if empty
                if axes.is_empty() {
                    axes.push(v_dir);
                }
            }
        }

        Self {
            active: !axes.is_empty(),
            start_x,
            start_y,
            candidate_axes: axes,
            locked_axis: None,
            lock_threshold_doc: 4.0,
        }
    }

    pub fn locked_axis(&self) -> Option<LockedPerspectiveAxis> {
        self.locked_axis
    }

    /// Snaps `(x, y)` onto the best-aligned perspective ray once the pointer has moved
    /// past the `4.0` doc px lock threshold.
    pub fn snap(&mut self, x: f64, y: f64, alt_override: bool) -> (f64, f64) {
        if !self.active || alt_override {
            return (x, y);
        }

        let dx = x - self.start_x;
        let dy = y - self.start_y;
        let dist = dx.hypot(dy);

        if self.locked_axis.is_none() {
            if dist < self.lock_threshold_doc {
                // Hold gently at start point until directional intent exceeds 4 doc px
                return (self.start_x, self.start_y);
            }
            let ux = dx / dist;
            let uy = dy / dist;
            let mut best_idx = 0usize;
            let mut best_abs_dot = -1.0f64;
            for (i, &(ax, ay)) in self.candidate_axes.iter().enumerate() {
                let d = (ux * ax + uy * ay).abs();
                if d > best_abs_dot {
                    best_abs_dot = d;
                    best_idx = i;
                }
            }
            let (dir_x, dir_y) = self.candidate_axes[best_idx];
            self.locked_axis = Some(LockedPerspectiveAxis {
                dir_x,
                dir_y,
                axis_index: best_idx,
            });
        }

        if let Some(axis) = self.locked_axis {
            let t = dx * axis.dir_x + dy * axis.dir_y;
            (self.start_x + axis.dir_x * t, self.start_y + axis.dir_y * t)
        } else {
            (x, y)
        }
    }
}

/// Combined per-stroke ruler snapping session (Straight Ruler takes priority over Perspective
/// Ruler when both are active, matching `pointerDownHandler.ts`).
#[derive(Debug, Clone)]
pub enum ActiveRulerSession {
    None,
    Straight(StraightRulerSnapSession),
    Perspective(PerspectiveSnapSession),
}

impl ActiveRulerSession {
    pub fn begin(
        straight: Option<&StraightRulerConfig>,
        perspective: Option<&PerspectiveRulerConfig>,
        start_x: f64,
        start_y: f64,
        zoom: f64,
        alt_override: bool,
    ) -> Self {
        if let Some(sr) = straight {
            let sess = StraightRulerSnapSession::begin(sr, start_x, start_y, zoom, alt_override);
            if sess.active {
                return Self::Straight(sess);
            }
        }
        if let Some(pr) = perspective {
            let sess = PerspectiveSnapSession::begin(pr, start_x, start_y, alt_override);
            if sess.active {
                return Self::Perspective(sess);
            }
        }
        Self::None
    }

    #[inline]
    pub fn snap(&mut self, x: f64, y: f64, alt_override: bool) -> (f64, f64) {
        match self {
            Self::None => (x, y),
            Self::Straight(s) => s.snap(x, y, alt_override),
            Self::Perspective(p) => p.snap(x, y, alt_override),
        }
    }

    #[inline]
    pub fn is_active(&self) -> bool {
        !matches!(self, Self::None)
    }
}