Skip to content

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

7.0 KB
Raw Blame
//! Pure-Rust Comic Panel / Frame Border geometry builders (`frame-folder`).
//!
//! Direct port of `triangulatePolygon` and `buildFrameBorderTriangles` from
//! `src/utils/frameEngine.ts` for GPU polygon mask clipping and mitered panel borders.

use super::stack_cache::DocBounds;
use crate::document::types::{ComicFrame, Point2D};

/// Computes signed area of a 2D polygon (positive = CW in screen Y-down coordinates).
pub fn signed_polygon_area(polygon: &[Point2D]) -> f64 {
    if polygon.len() < 3 {
        return 0.0;
    }
    let mut sum = 0.0;
    for i in 0..polygon.len() {
        let a = polygon[i];
        let b = polygon[(i + 1) % polygon.len()];
        sum += a.x * b.y - b.x * a.y;
    }
    sum * 0.5
}

fn deduplicate_polygon(poly: &[Point2D], eps: f64) -> Vec<Point2D> {
    let mut out: Vec<Point2D> = Vec::with_capacity(poly.len());
    for &p in poly {
        if let Some(prev) = out.last() {
            if (p.x - prev.x).hypot(p.y - prev.y) <= eps {
                continue;
            }
        }
        out.push(p);
    }
    if out.len() > 1 {
        let first = out[0];
        let last = *out.last().unwrap();
        if (first.x - last.x).hypot(first.y - last.y) <= eps {
            out.pop();
        }
    }
    out
}

#[inline]
fn point_in_triangle(p: Point2D, a: Point2D, b: Point2D, c: Point2D) -> bool {
    let cross = |o: Point2D, u: Point2D, v: Point2D| (u.x - o.x) * (v.y - o.y) - (u.y - o.y) * (v.x - o.x);
    let d1 = cross(p, a, b);
    let d2 = cross(p, b, c);
    let d3 = cross(p, c, a);
    let has_neg = d1 < -1e-6 || d2 < -1e-6 || d3 < -1e-6;
    let has_pos = d1 > 1e-6 || d2 > 1e-6 || d3 > 1e-6;
    !(has_neg && has_pos)
}

/// Ear-clipping triangulation of a simple 2D polygon into triangle vertices `[x, y]`.
pub fn triangulate_polygon(polygon: &[Point2D]) -> Vec<[f32; 2]> {
    let pts = deduplicate_polygon(polygon, 1e-4);
    if pts.len() < 3 {
        return Vec::new();
    }
    if pts.len() == 3 {
        return vec![
            [pts[0].x as f32, pts[0].y as f32],
            [pts[1].x as f32, pts[1].y as f32],
            [pts[2].x as f32, pts[2].y as f32],
        ];
    }

    let mut indices: Vec<usize> = (0..pts.len()).collect();
    if signed_polygon_area(&pts) < 0.0 {
        indices.reverse();
    }

    let mut out = Vec::with_capacity((pts.len() - 2) * 3);
    let mut guard = indices.len() * indices.len();

    while indices.len() > 3 && guard > 0 {
        guard -= 1;
        let mut ear_found = false;
        let len = indices.len();
        for i in 0..len {
            let i_prev = indices[(i + len - 1) % len];
            let i_curr = indices[i];
            let i_next = indices[(i + 1) % len];

            let a = pts[i_prev];
            let b = pts[i_curr];
            let c = pts[i_next];

            let cross = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
            if cross <= 1e-6 {
                continue;
            }

            let mut contains_any = false;
            for &idx in &indices {
                if idx == i_prev || idx == i_curr || idx == i_next {
                    continue;
                }
                if point_in_triangle(pts[idx], a, b, c) {
                    contains_any = true;
                    break;
                }
            }

            if !contains_any {
                out.push([a.x as f32, a.y as f32]);
                out.push([b.x as f32, b.y as f32]);
                out.push([c.x as f32, c.y as f32]);
                indices.remove(i);
                ear_found = true;
                break;
            }
        }
        if !ear_found {
            break;
        }
    }

    if indices.len() == 3 {
        let a = pts[indices[0]];
        let b = pts[indices[1]];
        let c = pts[indices[2]];
        out.push([a.x as f32, a.y as f32]);
        out.push([b.x as f32, b.y as f32]);
        out.push([c.x as f32, c.y as f32]);
    }

    out
}

/// Builds crisp mitered border stroke triangles in document space for GPU rendering on top of
/// clipped panel contents.
pub fn build_frame_border_triangles(
    polygon: &[Point2D],
    border_width: f32,
    miter_limit: f64,
) -> Vec<[f32; 2]> {
    let pts = deduplicate_polygon(polygon, 1e-4);
    if pts.len() < 3 || border_width <= 0.0 {
        return Vec::new();
    }

    let ordered = if signed_polygon_area(&pts) >= 0.0 {
        pts
    } else {
        pts.into_iter().rev().collect()
    };
    let n = ordered.len();
    let half_w = border_width as f64 * 0.5;
    let safe_miter = miter_limit.max(1.0);

    let mut edge_normals = Vec::with_capacity(n);
    for i in 0..n {
        let a = ordered[i];
        let b = ordered[(i + 1) % n];
        let dx = b.x - a.x;
        let dy = b.y - a.y;
        let len = dx.hypot(dy).max(1e-9);
        edge_normals.push(Point2D {
            x: dy / len,
            y: -dx / len,
        });
    }

    let mut outer_pts = Vec::with_capacity(n);
    let mut inner_pts = Vec::with_capacity(n);

    for i in 0..n {
        let n_prev = edge_normals[(i + n - 1) % n];
        let n_curr = edge_normals[i];
        let mut mx = n_prev.x + n_curr.x;
        let mut my = n_prev.y + n_curr.y;
        let m_len = mx.hypot(my);

        let (ox, oy) = if m_len < 1e-4 {
            (n_curr.x * half_w, n_curr.y * half_w)
        } else {
            mx /= m_len;
            my /= m_len;
            let dot = (mx * n_curr.x + my * n_curr.y).max(1.0 / safe_miter);
            let miter_dist = half_w / dot;
            (mx * miter_dist, my * miter_dist)
        };

        let p = ordered[i];
        outer_pts.push([((p.x + ox) as f32), ((p.y + oy) as f32)]);
        inner_pts.push([((p.x - ox) as f32), ((p.y - oy) as f32)]);
    }

    let mut out = Vec::with_capacity(n * 6);
    for i in 0..n {
        let next = (i + 1) % n;
        let o0 = outer_pts[i];
        let o1 = outer_pts[next];
        let i0 = inner_pts[i];
        let i1 = inner_pts[next];
        out.push(o0);
        out.push(o1);
        out.push(i1);
        out.push(o0);
        out.push(i1);
        out.push(i0);
    }

    out
}

/// Computes the union document-space AABB (including border margin) for a slice of comic frames.
pub fn frames_union_bounds(frames: &[ComicFrame]) -> Option<DocBounds> {
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;
    let mut max_border = 0.0f64;

    for f in frames {
        if f.polygon.len() < 3 {
            continue;
        }
        max_border = max_border.max((f.border_width.max(3.0)) as f64);
        for pt in &f.polygon {
            min_x = min_x.min(pt.x);
            min_y = min_y.min(pt.y);
            max_x = max_x.max(pt.x);
            max_y = max_y.max(pt.y);
        }
    }

    if !min_x.is_finite() || !max_x.is_finite() {
        return None;
    }
    let pad = max_border.ceil() + 4.0;
    Some(DocBounds {
        min_x: (min_x - pad).floor() as i32,
        min_y: (min_y - pad).floor() as i32,
        max_x: (max_x + pad).ceil() as i32,
        max_y: (max_y + pad).ceil() as i32,
    })
}