Skip to content

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

22.1 KB
Raw Blame
//! Fast Native Rust Vector Layer & Cubic Bézier Pen Rasterizer (`vector.rs`).
//!
//! Keeps lightweight vector knot/control-point metadata in React while rasterizing
//! variable-width Catmull-Rom vector strokes and Cubic Bézier Pen paths directly into
//! `Document`'s sparse tile grid with Rayon parallelism, 4×4 supersampled AA, active
//! `SparseSelectionMask`, and atomic Copy-on-Write Undo!

use crate::document::{Document, LayerId};
use crate::memory::ScratchBackend;
use crate::tiles::{parse_hex_rgba8, CowTileDelta, RectI32, TileKind};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::sync::Arc;

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VectorStrokePoint {
    pub x: f32,
    pub y: f32,
    #[serde(default = "default_one")]
    pub pressure: f32,
    #[serde(default)]
    pub width: Option<f32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VectorStrokePath {
    pub id: String,
    pub points: Vec<VectorStrokePoint>,
    pub color: String,
    pub size: f32,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default = "default_hardness")]
    pub hardness: f32,
    #[serde(default)]
    pub closed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BezierAnchor {
    pub x: f32,
    pub y: f32,
    #[serde(default)]
    pub handle_in: Option<[f32; 2]>,
    #[serde(default)]
    pub handle_out: Option<[f32; 2]>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BezierPathParams {
    pub anchors: Vec<BezierAnchor>,
    #[serde(default)]
    pub closed: bool,
    #[serde(default = "default_black")]
    pub stroke_color: String,
    #[serde(default)]
    pub fill_color: Option<String>,
    #[serde(default = "default_stroke_width")]
    pub stroke_width: f32,
    #[serde(default = "default_one")]
    pub opacity: f32,
    #[serde(default = "default_true")]
    pub stroke: bool,
    #[serde(default)]
    pub fill: bool,
    #[serde(default = "default_true")]
    pub anti_alias: bool,
    #[serde(default)]
    pub layer_id: Option<LayerId>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VectorRasterResult {
    pub modified: bool,
    pub layer_id: LayerId,
    pub dirty_rect: RectI32,
}

fn default_one() -> f32 {
    1.0
}
fn default_hardness() -> f32 {
    0.92
}
fn default_stroke_width() -> f32 {
    4.0
}
fn default_black() -> String {
    "#000000".to_string()
}
fn default_true() -> bool {
    true
}

#[inline]
fn eval_catmull_rom(p0: f32, p1: f32, p2: f32, p3: f32, t: f32) -> f32 {
    let t2 = t * t;
    let t3 = t2 * t;
    0.5 * ((2.0 * p1)
        + (-p0 + p2) * t
        + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2
        + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3)
}

/// Samples a variable-width `VectorStrokePath` into dense capsules `(x0, y0, r0, x1, y1, r1)`.
fn tessellate_vector_stroke(path: &VectorStrokePath) -> Vec<[f32; 6]> {
    let n = path.points.len();
    if n == 0 {
        return Vec::new();
    }
    let radius_of = |pt: &VectorStrokePoint| -> f32 {
        let w = pt.width.unwrap_or(path.size * pt.pressure.clamp(0.05, 1.0));
        (w * 0.5).max(0.5)
    };
    if n == 1 {
        let r = radius_of(&path.points[0]);
        return vec![[path.points[0].x, path.points[0].y, r, path.points[0].x, path.points[0].y, r]];
    }

    let mut samples: Vec<[f32; 3]> = Vec::with_capacity(n * 6);
    let seg_count = if path.closed { n } else { n - 1 };
    for i in 0..seg_count {
        let p0 = &path.points[if i == 0 {
            if path.closed { n - 1 } else { 0 }
        } else {
            i - 1
        }];
        let p1 = &path.points[i];
        let p2 = &path.points[(i + 1) % n];
        let p3 = &path.points[if i + 2 >= n {
            if path.closed { (i + 2) % n } else { n - 1 }
        } else {
            i + 2
        }];
        let r0 = radius_of(p0);
        let r1 = radius_of(p1);
        let r2 = radius_of(p2);
        let r3 = radius_of(p3);
        let chord = (p2.x - p1.x).hypot(p2.y - p1.y);
        let steps = ((chord / 4.0).ceil() as usize).clamp(2, 24);
        let start_s = if i == 0 { 0 } else { 1 };
        for s in start_s..=steps {
            let t = s as f32 / steps as f32;
            let x = eval_catmull_rom(p0.x, p1.x, p2.x, p3.x, t);
            let y = eval_catmull_rom(p0.y, p1.y, p2.y, p3.y, t);
            let r = eval_catmull_rom(r0, r1, r2, r3, t).max(0.5);
            samples.push([x, y, r]);
        }
    }

    let mut caps = Vec::with_capacity(samples.len());
    for win in samples.windows(2) {
        caps.push([win[0][0], win[0][1], win[0][2], win[1][0], win[1][1], win[1][2]]);
    }
    caps
}

/// Rasterizes a vector layer's complete `strokes` list cleanly onto the layer's sparse tiles
/// (replacing existing vector layer pixels with an atomic CoW Undo entry!).
pub fn rasterize_vector_layer(
    doc: &mut Document,
    layer_id: &str,
    strokes: &[VectorStrokePath],
    record_history: bool,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<VectorRasterResult, String> {
    let (mono_thresh, locked) = {
        let l = doc
            .layer(layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        if !l.meta.layer_type.has_tiles() {
            return Err("Target layer cannot store rasterized vector tiles".to_string());
        }
        (l.meta.mono_threshold.unwrap_or(128), l.meta.locked)
    };
    if locked {
        return Err("Target layer is locked".to_string());
    }

    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);

    // Pre-tessellate all vector strokes and compute union bounding box
    type PreparedVectorStroke = ([u8; 4], f32, f32, Vec<[f32; 6]>, [f32; 4]);
    let mut prepared: Vec<PreparedVectorStroke> =
        Vec::with_capacity(strokes.len());
    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;

    for s in strokes {
        let caps = tessellate_vector_stroke(s);
        if caps.is_empty() {
            continue;
        }
        let mut smin_x = f32::INFINITY;
        let mut smin_y = f32::INFINITY;
        let mut smax_x = f32::NEG_INFINITY;
        let mut smax_y = f32::NEG_INFINITY;
        for c in &caps {
            let r = c[2].max(c[5]) + 2.0;
            smin_x = smin_x.min(c[0].min(c[3]) - r);
            smin_y = smin_y.min(c[1].min(c[4]) - r);
            smax_x = smax_x.max(c[0].max(c[3]) + r);
            smax_y = smax_y.max(c[1].max(c[4]) + r);
        }
        min_x = min_x.min(smin_x);
        min_y = min_y.min(smin_y);
        max_x = max_x.max(smax_x);
        max_y = max_y.max(smax_y);
        let rgba = parse_hex_rgba8(&s.color).unwrap_or([0, 0, 0, 255]);
        prepared.push((
            rgba,
            s.opacity.clamp(0.0, 1.0),
            s.hardness.clamp(0.0, 1.0),
            caps,
            [smin_x, smin_y, smax_x, smax_y],
        ));
    }

    let before_snap = doc
        .layer(layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?
        .grid
        .snapshot_all_cow(TileKind::Raster);

    let work_rect = if prepared.is_empty() || !min_x.is_finite() {
        RectI32::empty()
    } else {
        RectI32::new(
            min_x.floor() as i32,
            min_y.floor() as i32,
            ((max_x.ceil() - min_x.floor()) as i32 + 1).max(1) as u32,
            ((max_y.ceil() - min_y.floor()) as i32 + 1).max(1) as u32,
        )
        .intersect(doc_rect)
    };

    if !work_rect.is_empty() {
        let w = work_rect.width as usize;
        let h = work_rect.height as usize;
        let mut out = vec![0u8; w * h * 4];

        out.par_chunks_mut(w * 4).enumerate().for_each(|(ry, row)| {
            let py = work_rect.y as f32 + ry as f32 + 0.5;
            for (rgba, opacity, hardness, caps, aabb) in &prepared {
                if py < aabb[1] || py > aabb[3] {
                    continue;
                }
                let x0 = ((aabb[0].floor() as i32) - work_rect.x).clamp(0, w as i32 - 1) as usize;
                let x1 = ((aabb[2].ceil() as i32) - work_rect.x).clamp(0, w as i32 - 1) as usize;
                let sr = rgba[0] as f32 / 255.0;
                let sg = rgba[1] as f32 / 255.0;
                let sb = rgba[2] as f32 / 255.0;
                let base_a = (rgba[3] as f32 / 255.0) * *opacity;
                let aa_soft = (1.0 - *hardness).max(0.05) * 1.4;

                for rx in x0..=x1 {
                    let px = work_rect.x as f32 + rx as f32 + 0.5;
                    let mut best_cov = 0.0f32;
                    for c in caps {
                        let rmax = c[2].max(c[5]) + aa_soft + 1.0;
                        if px < c[0].min(c[3]) - rmax
                            || px > c[0].max(c[3]) + rmax
                            || py < c[1].min(c[4]) - rmax
                            || py > c[1].max(c[4]) + rmax
                        {
                            continue;
                        }
                        let abx = c[3] - c[0];
                        let aby = c[4] - c[1];
                        let ab2 = abx * abx + aby * aby;
                        let t = if ab2 > 1e-5 {
                            (((px - c[0]) * abx + (py - c[1]) * aby) / ab2).clamp(0.0, 1.0)
                        } else {
                            0.0
                        };
                        let d = (px - (c[0] + abx * t)).hypot(py - (c[1] + aby * t));
                        let r = c[2] + (c[5] - c[2]) * t;
                        let edge = (r * (1.0 - *hardness)).max(1.0);
                        let cov = ((r + 0.5 - d) / edge).clamp(0.0, 1.0);
                        if cov > best_cov {
                            best_cov = cov;
                            if best_cov >= 0.999 {
                                break;
                            }
                        }
                    }
                    let sa = best_cov * base_a;
                    if sa <= 1e-4 {
                        continue;
                    }
                    let o = rx * 4;
                    let da = row[o + 3] as f32 / 255.0;
                    let out_a = (sa + da * (1.0 - sa)).clamp(0.0, 1.0);
                    if out_a <= 1e-5 {
                        continue;
                    }
                    let dr = row[o] as f32 / 255.0;
                    let dg = row[o + 1] as f32 / 255.0;
                    let db = row[o + 2] as f32 / 255.0;
                    row[o] = (((sr * sa + dr * da * (1.0 - sa)) / out_a) * 255.0)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                    row[o + 1] = (((sg * sa + dg * da * (1.0 - sa)) / out_a) * 255.0)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                    row[o + 2] = (((sb * sa + db * da * (1.0 - sa)) / out_a) * 255.0)
                        .round()
                        .clamp(0.0, 255.0) as u8;
                    row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
            }
        });

        if let Some(layer) = doc.layer_mut(layer_id) {
            layer.grid.clear_all();
            layer
                .grid
                .write_rgba8_rect(&out, work_rect, mono_thresh, scratch)?;
        }
    } else if let Some(layer) = doc.layer_mut(layer_id) {
        layer.grid.clear_all();
    }

    let deltas = {
        let layer = doc
            .layer(layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        let mut coords: HashSet<crate::tiles::TileCoord> = before_snap.keys().copied().collect();
        coords.extend(layer.grid.tiles.keys().copied());
        let mut d = Vec::new();
        for coord in coords {
            let b = before_snap.get(&coord).cloned();
            let a = layer.grid.tiles.get(&coord).cloned();
            let same = match (&b, &a) {
                (None, None) => true,
                (Some(x), Some(y)) => Arc::ptr_eq(x, y) || x.version == y.version,
                _ => false,
            };
            if !same {
                d.push(CowTileDelta {
                    layer_id: layer_id.to_string(),
                    coord,
                    kind: TileKind::Raster,
                    before: b,
                    after: a,
                    remote_epoch: layer.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
                });
            }
        }
        d
    };

    let modified = !deltas.is_empty();
    if modified && record_history {
        doc.record_stroke_deltas(layer_id, "vector", "Vector Stroke", deltas, None, None);
    } else if modified {
        doc.dirty_for_render = true;
    }

    Ok(VectorRasterResult {
        modified,
        layer_id: layer_id.to_string(),
        dirty_rect: work_rect,
    })
}

/// Evaluates a Cubic Bézier Pen path into a polyline and rasterizes stroke + optional fill
/// directly onto `Document`'s target layer honoring `SparseSelectionMask`, `alphaLocked`, and CoW Undo!
pub fn rasterize_bezier_path(
    doc: &mut Document,
    params: &BezierPathParams,
    scratch: Option<&dyn ScratchBackend>,
) -> Result<VectorRasterResult, String> {
    if params.anchors.len() < 2 {
        return Ok(VectorRasterResult {
            modified: false,
            layer_id: params
                .layer_id
                .clone()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default(),
            dirty_rect: RectI32::empty(),
        });
    }
    let layer_id = params
        .layer_id
        .clone()
        .or_else(|| doc.active_layer_id.clone())
        .ok_or_else(|| "No active layer for pen path".to_string())?;
    let (alpha_locked, mono_thresh) = {
        let l = doc
            .layer(&layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        if !l.meta.layer_type.has_tiles() || l.meta.locked {
            return Err("Target layer is locked or non-raster".to_string());
        }
        (
            l.meta.alpha_locked.unwrap_or(false),
            l.meta.mono_threshold.unwrap_or(128),
        )
    };

    // Flatten cubic Bézier segments into dense polyline
    let n = params.anchors.len();
    let seg_count = if params.closed { n } else { n - 1 };
    let mut poly: Vec<[f32; 2]> = Vec::with_capacity(seg_count * 16);
    for i in 0..seg_count {
        let a = &params.anchors[i];
        let b = &params.anchors[(i + 1) % n];
        let p0 = [a.x, a.y];
        let p1 = a.handle_out.unwrap_or(p0);
        let p3 = [b.x, b.y];
        let p2 = b.handle_in.unwrap_or(p3);
        let est_len = (p1[0] - p0[0]).hypot(p1[1] - p0[1])
            + (p2[0] - p1[0]).hypot(p2[1] - p1[1])
            + (p3[0] - p2[0]).hypot(p3[1] - p2[1]);
        let steps = ((est_len / 3.0).ceil() as usize).clamp(4, 64);
        let s0 = if i == 0 { 0 } else { 1 };
        for s in s0..=steps {
            let t = s as f32 / steps as f32;
            let u = 1.0 - t;
            let x = u * u * u * p0[0]
                + 3.0 * u * u * t * p1[0]
                + 3.0 * u * t * t * p2[0]
                + t * t * t * p3[0];
            let y = u * u * u * p0[1]
                + 3.0 * u * u * t * p1[1]
                + 3.0 * u * t * t * p2[1]
                + t * t * t * p3[1];
            poly.push([x, y]);
        }
    }

    let mut min_x = f32::INFINITY;
    let mut min_y = f32::INFINITY;
    let mut max_x = f32::NEG_INFINITY;
    let mut max_y = f32::NEG_INFINITY;
    for p in &poly {
        min_x = min_x.min(p[0]);
        min_y = min_y.min(p[1]);
        max_x = max_x.max(p[0]);
        max_y = max_y.max(p[1]);
    }
    let half_sw = (params.stroke_width * 0.5).max(0.5);
    let pad = (half_sw + 3.0).ceil() as i32;
    let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
    let work_rect = RectI32::new(
        min_x.floor() as i32 - pad,
        min_y.floor() as i32 - pad,
        ((max_x.ceil() - min_x.floor()) as i32 + pad * 2 + 1).max(1) as u32,
        ((max_y.ceil() - min_y.floor()) as i32 + pad * 2 + 1).max(1) as u32,
    )
    .intersect(doc_rect);
    if work_rect.is_empty() {
        return Ok(VectorRasterResult {
            modified: false,
            layer_id,
            dirty_rect: RectI32::empty(),
        });
    }

    let stroke_c = parse_hex_rgba8(&params.stroke_color).unwrap_or([0, 0, 0, 255]);
    let fill_c = params
        .fill_color
        .as_deref()
        .and_then(parse_hex_rgba8)
        .unwrap_or(stroke_c);
    let op = params.opacity.clamp(0.0, 1.0);
    let aa = if params.anti_alias { 1.0f32 } else { 0.001f32 };
    let sel_mask = doc
        .selection
        .as_ref()
        .filter(|s| !s.is_empty())
        .map(|s| s.read_rect(work_rect));

    let mut dst_rgba = doc
        .layer(&layer_id)
        .ok_or_else(|| format!("Layer not found: {layer_id}"))?
        .grid
        .read_rgba8_rect(work_rect, false, scratch)?;

    let w = work_rect.width as usize;
    let do_fill = params.fill && params.closed && poly.len() >= 3;
    let do_stroke = params.stroke;

    dst_rgba
        .par_chunks_mut(w * 4)
        .enumerate()
        .for_each(|(ry, row)| {
            let py = work_rect.y as f32 + ry as f32 + 0.5;
            let roff = ry * w;
            for rx in 0..w {
                let px = work_rect.x as f32 + rx as f32 + 0.5;
                let mut best_d = f32::INFINITY;
                for win in poly.windows(2) {
                    let a = win[0];
                    let b = win[1];
                    let abx = b[0] - a[0];
                    let aby = b[1] - a[1];
                    let ab2 = abx * abx + aby * aby;
                    let t = if ab2 > 1e-6 {
                        (((px - a[0]) * abx + (py - a[1]) * aby) / ab2).clamp(0.0, 1.0)
                    } else {
                        0.0
                    };
                    let d = (px - (a[0] + abx * t)).hypot(py - (a[1] + aby * t));
                    if d < best_d {
                        best_d = d;
                    }
                }
                let fill_a = if do_fill {
                    let mut inside = false;
                    let mut j = poly.len() - 1;
                    for i in 0..poly.len() {
                        let (xi, yi) = (poly[i][0], poly[i][1]);
                        let (xj, yj) = (poly[j][0], poly[j][1]);
                        if ((yi > py) != (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi) + xi)
                        {
                            inside = !inside;
                        }
                        j = i;
                    }
                    let sd = if inside { -best_d } else { best_d };
                    ((0.5 - sd / aa).clamp(0.0, 1.0)) * (fill_c[3] as f32 / 255.0) * op
                } else {
                    0.0
                };
                let stroke_a = if do_stroke {
                    ((half_sw + 0.5 * aa - best_d) / aa).clamp(0.0, 1.0)
                        * (stroke_c[3] as f32 / 255.0)
                        * op
                } else {
                    0.0
                };

                let sel_a = sel_mask
                    .as_ref()
                    .map(|m| m[roff + rx] as f32 / 255.0)
                    .unwrap_or(1.0);
                let sa_s = stroke_a * sel_a;
                let sa_f = fill_a * sel_a;
                let src_a = (sa_s + sa_f * (1.0 - sa_s)).clamp(0.0, 1.0);
                if src_a <= 1e-4 {
                    continue;
                }
                let mut srgb = [0.0f32; 3];
                for c in 0..3 {
                    srgb[c] = ((stroke_c[c] as f32 / 255.0) * sa_s
                        + (fill_c[c] as f32 / 255.0) * sa_f * (1.0 - sa_s))
                        / src_a;
                }

                let o = rx * 4;
                let da = row[o + 3] as f32 / 255.0;
                if alpha_locked {
                    if da <= 1e-4 {
                        continue;
                    }
                    for c in 0..3 {
                        let dr = row[o + c] as f32 / 255.0;
                        row[o + c] =
                            ((dr + (srgb[c] - dr) * src_a) * 255.0).round().clamp(0.0, 255.0) as u8;
                    }
                } else {
                    let out_a = (src_a + da * (1.0 - src_a)).clamp(0.0, 1.0);
                    if out_a <= 1e-5 {
                        continue;
                    }
                    for c in 0..3 {
                        let dr = row[o + c] as f32 / 255.0;
                        row[o + c] = (((srgb[c] * src_a + dr * da * (1.0 - src_a)) / out_a)
                            * 255.0)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                    }
                    row[o + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
            }
        });

    let deltas = {
        let layer = doc
            .layer_mut(&layer_id)
            .ok_or_else(|| format!("Layer not found: {layer_id}"))?;
        let before = layer.grid.snapshot_all_cow(TileKind::Raster);
        let touched = layer
            .grid
            .write_rgba8_rect(&dst_rgba, work_rect, mono_thresh, scratch)?;
        let mut d = Vec::with_capacity(touched.len());
        for coord in touched {
            let b = before.get(&coord).cloned();
            let a = layer.grid.tiles.get(&coord).cloned();
            let same = match (&b, &a) {
                (None, None) => true,
                (Some(x), Some(y)) => Arc::ptr_eq(x, y) || x.version == y.version,
                _ => false,
            };
            if !same {
                d.push(CowTileDelta {
                    layer_id: layer_id.clone(),
                    coord,
                    kind: TileKind::Raster,
                    before: b,
                    after: a,
                    remote_epoch: layer.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
                });
            }
        }
        d
    };

    let modified = !deltas.is_empty();
    if modified {
        doc.record_stroke_deltas(&layer_id, "pen", "Pen Path", deltas, None, None);
    }
    Ok(VectorRasterResult {
        modified,
        layer_id,
        dirty_rect: work_rect,
    })
}