M13.1/M13.2: paint (Brush, Clone Stamp, Eraser) and puppet pins
Paint: non-destructive Paint effect with Brush/Clone/Eraser stroke groups (Path, Stroke Options, Transform, Duration spans, Write On End keys), dab rasterizer (diameter/angle/roundness/hardness/spacing/flow/opacity, pressure dynamics, modes, channels), eraser modes, clone from layer/time, cache keys include visible strokes. paint.stroke/options/brushPreset/ setCloneSource/removeStroke/presets. Layer panel with paint tools, Paint and Brushes panels. Puppet: Puppet effect with meshes and Position/Advanced/Bend/Starch/Overlap pins; alpha contour -> expansion (exact EDT) -> simplified outline -> Delaunay with constraint recovery; ARAP (Igarashi 2005) two-step solve with CG; anti-aliased texture-mapped rendering with overlap depth. puppet.addPin/ movePin/setPin/removePin/mesh/info. Puppet tools in the viewer with mesh overlay and header options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
5273f1ba96
commit
d6f6a10757
@@ -0,0 +1,327 @@
|
||||
//! As-rigid-as-possible mesh deformation, after Igarashi, Moscovich & Hughes,
|
||||
//! "As-Rigid-As-Possible Shape Manipulation" (SIGGRAPH 2005).
|
||||
//!
|
||||
//! Two linear least-squares steps per frame:
|
||||
//!
|
||||
//! 1. **Similarity step.** Each triangle edge `(i, j)` expresses the third vertex `k` in the
|
||||
//! edge's local frame, `v_k = v_i + x·(v_j − v_i) + y·R90(v_j − v_i)`. Minimising the error of
|
||||
//! that relation over all three edges of every triangle, with the pinned vertices fixed,
|
||||
//! gives a deformation that is locally a similarity (rotation + uniform scale).
|
||||
//! 2. **Scale-adjustment step.** Each triangle of the step-1 result is fitted with a rigid copy
|
||||
//! of its rest shape (2D Procrustes: best rotation about the centroid). The final positions
|
||||
//! minimise the difference between every triangle's edge vectors and its fitted edge vectors.
|
||||
//!
|
||||
//! Optional extra iterations repeat step 2 on its own result (rotation refinement). Triangle
|
||||
//! weights stiffen regions (Starch); edge-vector targets implement Bend/Advanced pin rotation
|
||||
//! and scale. Both systems are symmetric positive definite (a tiny regulariser towards the
|
||||
//! initial guess keeps under-constrained meshes well-posed) and are solved with Jacobi-
|
||||
//! preconditioned conjugate gradients on a sparse matrix.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// A soft target for the vector `v_j − v_i`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EdgeTarget {
|
||||
pub i: usize,
|
||||
pub j: usize,
|
||||
pub vec: [f64; 2],
|
||||
pub weight: f64,
|
||||
}
|
||||
|
||||
/// Constraints for one solve.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Handles {
|
||||
/// Hard position constraints (vertex, position).
|
||||
pub fixed: Vec<(usize, [f64; 2])>,
|
||||
pub edges: Vec<EdgeTarget>,
|
||||
}
|
||||
|
||||
/// Sparse symmetric matrix in row maps (assembly), then CSR for the solve.
|
||||
struct Sparse {
|
||||
rows: Vec<BTreeMap<usize, f64>>,
|
||||
}
|
||||
|
||||
impl Sparse {
|
||||
fn new(n: usize) -> Sparse {
|
||||
Sparse { rows: vec![BTreeMap::new(); n] }
|
||||
}
|
||||
fn add(&mut self, i: usize, j: usize, v: f64) {
|
||||
*self.rows[i].entry(j).or_insert(0.0) += v;
|
||||
}
|
||||
}
|
||||
|
||||
struct Csr {
|
||||
ptr: Vec<usize>,
|
||||
col: Vec<usize>,
|
||||
val: Vec<f64>,
|
||||
diag: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Csr {
|
||||
fn mul(&self, x: &[f64], y: &mut [f64]) {
|
||||
for (r, yr) in y.iter_mut().enumerate() {
|
||||
let mut s = 0.0;
|
||||
for k in self.ptr[r]..self.ptr[r + 1] {
|
||||
s += self.val[k] * x[self.col[k]];
|
||||
}
|
||||
*yr = s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Solve `A x = b` restricted to the free unknowns (`free[i]`), with the fixed unknowns at
|
||||
/// their values in `x`. Jacobi-preconditioned conjugate gradients, starting from `x`.
|
||||
fn solve(a: &Sparse, b: &[f64], x: &mut [f64], free: &[bool]) {
|
||||
let n = b.len();
|
||||
let idx: Vec<usize> = (0..n).filter(|i| free[*i]).collect();
|
||||
if idx.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut pos = vec![usize::MAX; n];
|
||||
for (k, i) in idx.iter().enumerate() {
|
||||
pos[*i] = k;
|
||||
}
|
||||
let m = idx.len();
|
||||
// Reduced system: A_ff x_f = b_f − A_fc x_c.
|
||||
let mut ptr = vec![0];
|
||||
let mut col = vec![];
|
||||
let mut val = vec![];
|
||||
let mut diag = vec![1.0; m];
|
||||
let mut rhs = vec![0.0; m];
|
||||
for (k, &i) in idx.iter().enumerate() {
|
||||
let mut r = b[i];
|
||||
for (&j, &v) in &a.rows[i] {
|
||||
if free[j] {
|
||||
col.push(pos[j]);
|
||||
val.push(v);
|
||||
if j == i {
|
||||
diag[k] = if v.abs() > 1e-300 { v } else { 1.0 };
|
||||
}
|
||||
} else {
|
||||
r -= v * x[j];
|
||||
}
|
||||
}
|
||||
rhs[k] = r;
|
||||
ptr.push(col.len());
|
||||
}
|
||||
let csr = Csr { ptr, col, val, diag };
|
||||
let mut xf: Vec<f64> = idx.iter().map(|i| x[*i]).collect();
|
||||
let mut ax = vec![0.0; m];
|
||||
csr.mul(&xf, &mut ax);
|
||||
let mut r: Vec<f64> = rhs.iter().zip(&ax).map(|(b, a)| b - a).collect();
|
||||
let bnorm = rhs.iter().map(|v| v * v).sum::<f64>().sqrt().max(1e-30);
|
||||
let mut z: Vec<f64> = r.iter().zip(&csr.diag).map(|(r, d)| r / d).collect();
|
||||
let mut p = z.clone();
|
||||
let mut rz: f64 = r.iter().zip(&z).map(|(a, b)| a * b).sum();
|
||||
let mut ap = vec![0.0; m];
|
||||
for _ in 0..(4 * m + 50) {
|
||||
if r.iter().map(|v| v * v).sum::<f64>().sqrt() <= 1e-13 * bnorm {
|
||||
break;
|
||||
}
|
||||
csr.mul(&p, &mut ap);
|
||||
let pap: f64 = p.iter().zip(&ap).map(|(a, b)| a * b).sum();
|
||||
if pap.abs() < 1e-300 {
|
||||
break;
|
||||
}
|
||||
let alpha = rz / pap;
|
||||
for k in 0..m {
|
||||
xf[k] += alpha * p[k];
|
||||
r[k] -= alpha * ap[k];
|
||||
}
|
||||
for k in 0..m {
|
||||
z[k] = r[k] / csr.diag[k];
|
||||
}
|
||||
let rz2: f64 = r.iter().zip(&z).map(|(a, b)| a * b).sum();
|
||||
let beta = rz2 / rz;
|
||||
rz = rz2;
|
||||
for k in 0..m {
|
||||
p[k] = z[k] + beta * p[k];
|
||||
}
|
||||
}
|
||||
for (k, i) in idx.iter().enumerate() {
|
||||
x[*i] = xf[k];
|
||||
}
|
||||
}
|
||||
|
||||
const REG: f64 = 1e-9;
|
||||
|
||||
/// Deform a mesh: `rest` vertices, CCW `tris` with per-triangle `weights` (1 = normal,
|
||||
/// larger = stiffer), constraints, and `refine` extra rigid-fit iterations. Returns the
|
||||
/// deformed vertex positions.
|
||||
pub fn deform(rest: &[[f64; 2]], tris: &[[usize; 3]], weights: &[f64], h: &Handles, refine: usize) -> Vec<[f64; 2]> {
|
||||
let n = rest.len();
|
||||
if n == 0 {
|
||||
return vec![];
|
||||
}
|
||||
// Initial guess: rest translated by the mean handle displacement.
|
||||
let mut t = [0.0, 0.0];
|
||||
for (i, p) in &h.fixed {
|
||||
t[0] += p[0] - rest[*i][0];
|
||||
t[1] += p[1] - rest[*i][1];
|
||||
}
|
||||
if !h.fixed.is_empty() {
|
||||
t[0] /= h.fixed.len() as f64;
|
||||
t[1] /= h.fixed.len() as f64;
|
||||
}
|
||||
let x0: Vec<[f64; 2]> = rest.iter().map(|p| [p[0] + t[0], p[1] + t[1]]).collect();
|
||||
let mut fixed = vec![false; n];
|
||||
for (i, _) in &h.fixed {
|
||||
fixed[*i] = true;
|
||||
}
|
||||
let w = |k: usize| weights.get(k).copied().unwrap_or(1.0);
|
||||
let scale2 = mean_edge2(rest, tris).max(1e-12);
|
||||
|
||||
// ---- Step 1: similarity-invariant energy over 2n unknowns (x0, y0, x1, y1, …).
|
||||
let mut a = Sparse::new(2 * n);
|
||||
let mut b = vec![0.0; 2 * n];
|
||||
for (k, t) in tris.iter().enumerate() {
|
||||
let wk = w(k);
|
||||
for (i, j, l) in [(t[0], t[1], t[2]), (t[1], t[2], t[0]), (t[2], t[0], t[1])] {
|
||||
let e = [rest[j][0] - rest[i][0], rest[j][1] - rest[i][1]];
|
||||
let d = [rest[l][0] - rest[i][0], rest[l][1] - rest[i][1]];
|
||||
let ee = e[0] * e[0] + e[1] * e[1];
|
||||
if ee <= 1e-18 {
|
||||
continue;
|
||||
}
|
||||
// R90(u) = (-u.y, u.x).
|
||||
let r90 = [-e[1], e[0]];
|
||||
let x = (d[0] * e[0] + d[1] * e[1]) / ee;
|
||||
let y = (d[0] * r90[0] + d[1] * r90[1]) / ee;
|
||||
// residual = B_l v_l + B_i v_i + B_j v_j with 2x2 blocks; R = [[0,-1],[1,0]].
|
||||
let bl = [[1.0, 0.0], [0.0, 1.0]];
|
||||
let bi = [[x - 1.0, -y], [y, x - 1.0]];
|
||||
let bj = [[-x, y], [-y, -x]];
|
||||
let blocks = [(l, bl), (i, bi), (j, bj)];
|
||||
for (va, ba) in &blocks {
|
||||
for (vb, bb) in &blocks {
|
||||
// ba^T bb
|
||||
for r in 0..2 {
|
||||
for c in 0..2 {
|
||||
let v = ba[0][r] * bb[0][c] + ba[1][r] * bb[1][c];
|
||||
if v != 0.0 {
|
||||
a.add(2 * va + r, 2 * vb + c, wk * v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for e in &h.edges {
|
||||
let ww = e.weight;
|
||||
for c in 0..2 {
|
||||
a.add(2 * e.i + c, 2 * e.i + c, ww);
|
||||
a.add(2 * e.j + c, 2 * e.j + c, ww);
|
||||
a.add(2 * e.i + c, 2 * e.j + c, -ww);
|
||||
a.add(2 * e.j + c, 2 * e.i + c, -ww);
|
||||
b[2 * e.j + c] += ww * e.vec[c];
|
||||
b[2 * e.i + c] -= ww * e.vec[c];
|
||||
}
|
||||
}
|
||||
let reg = REG * scale2.recip().min(1.0);
|
||||
for i in 0..n {
|
||||
for c in 0..2 {
|
||||
a.add(2 * i + c, 2 * i + c, reg);
|
||||
b[2 * i + c] += reg * x0[i][c];
|
||||
}
|
||||
}
|
||||
let mut x: Vec<f64> = x0.iter().flat_map(|p| [p[0], p[1]]).collect();
|
||||
for (i, p) in &h.fixed {
|
||||
x[2 * i] = p[0];
|
||||
x[2 * i + 1] = p[1];
|
||||
}
|
||||
let free2: Vec<bool> = (0..2 * n).map(|k| !fixed[k / 2]).collect();
|
||||
solve(&a, &b, &mut x, &free2);
|
||||
let mut cur: Vec<[f64; 2]> = (0..n).map(|i| [x[2 * i], x[2 * i + 1]]).collect();
|
||||
|
||||
// ---- Step 2: fit rigid triangles, then match edge vectors (x and y separately).
|
||||
let mut l = Sparse::new(n);
|
||||
for (k, t) in tris.iter().enumerate() {
|
||||
let wk = w(k);
|
||||
for (i, j) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
l.add(i, i, wk);
|
||||
l.add(j, j, wk);
|
||||
l.add(i, j, -wk);
|
||||
l.add(j, i, -wk);
|
||||
}
|
||||
}
|
||||
for e in &h.edges {
|
||||
l.add(e.i, e.i, e.weight);
|
||||
l.add(e.j, e.j, e.weight);
|
||||
l.add(e.i, e.j, -e.weight);
|
||||
l.add(e.j, e.i, -e.weight);
|
||||
}
|
||||
for i in 0..n {
|
||||
l.add(i, i, reg);
|
||||
}
|
||||
let free1: Vec<bool> = (0..n).map(|i| !fixed[i]).collect();
|
||||
for _ in 0..=refine {
|
||||
let mut bx = vec![0.0; n];
|
||||
let mut by = vec![0.0; n];
|
||||
for (k, t) in tris.iter().enumerate() {
|
||||
let wk = w(k);
|
||||
let f = fit_rigid([rest[t[0]], rest[t[1]], rest[t[2]]], [cur[t[0]], cur[t[1]], cur[t[2]]]);
|
||||
for (a2, b2) in [(0, 1), (1, 2), (2, 0)] {
|
||||
let (i, j) = (t[a2], t[b2]);
|
||||
let d = [f[b2][0] - f[a2][0], f[b2][1] - f[a2][1]];
|
||||
bx[j] += wk * d[0];
|
||||
bx[i] -= wk * d[0];
|
||||
by[j] += wk * d[1];
|
||||
by[i] -= wk * d[1];
|
||||
}
|
||||
}
|
||||
for e in &h.edges {
|
||||
bx[e.j] += e.weight * e.vec[0];
|
||||
bx[e.i] -= e.weight * e.vec[0];
|
||||
by[e.j] += e.weight * e.vec[1];
|
||||
by[e.i] -= e.weight * e.vec[1];
|
||||
}
|
||||
for i in 0..n {
|
||||
bx[i] += reg * x0[i][0];
|
||||
by[i] += reg * x0[i][1];
|
||||
}
|
||||
let mut xs: Vec<f64> = cur.iter().map(|p| p[0]).collect();
|
||||
let mut ys: Vec<f64> = cur.iter().map(|p| p[1]).collect();
|
||||
for (i, p) in &h.fixed {
|
||||
xs[*i] = p[0];
|
||||
ys[*i] = p[1];
|
||||
}
|
||||
solve(&l, &bx, &mut xs, &free1);
|
||||
solve(&l, &by, &mut ys, &free1);
|
||||
cur = (0..n).map(|i| [xs[i], ys[i]]).collect();
|
||||
}
|
||||
cur
|
||||
}
|
||||
|
||||
fn mean_edge2(rest: &[[f64; 2]], tris: &[[usize; 3]]) -> f64 {
|
||||
if tris.is_empty() {
|
||||
return 1.0;
|
||||
}
|
||||
let mut s = 0.0;
|
||||
for t in tris {
|
||||
let (a, b) = (rest[t[0]], rest[t[1]]);
|
||||
s += (a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2);
|
||||
}
|
||||
s / tris.len() as f64
|
||||
}
|
||||
|
||||
/// Best rigid copy of triangle `rest` over triangle `cur` (rotation about the centroids).
|
||||
pub fn fit_rigid(rest: [[f64; 2]; 3], cur: [[f64; 2]; 3]) -> [[f64; 2]; 3] {
|
||||
let cr = [(rest[0][0] + rest[1][0] + rest[2][0]) / 3.0, (rest[0][1] + rest[1][1] + rest[2][1]) / 3.0];
|
||||
let cc = [(cur[0][0] + cur[1][0] + cur[2][0]) / 3.0, (cur[0][1] + cur[1][1] + cur[2][1]) / 3.0];
|
||||
let (mut sd, mut sc) = (0.0, 0.0);
|
||||
for k in 0..3 {
|
||||
let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]];
|
||||
let q = [cur[k][0] - cc[0], cur[k][1] - cc[1]];
|
||||
sd += p[0] * q[0] + p[1] * q[1];
|
||||
sc += p[0] * q[1] - p[1] * q[0];
|
||||
}
|
||||
let ang = sc.atan2(sd);
|
||||
let (s, c) = ang.sin_cos();
|
||||
let mut out = [[0.0; 2]; 3];
|
||||
for k in 0..3 {
|
||||
let p = [rest[k][0] - cr[0], rest[k][1] - cr[1]];
|
||||
out[k] = [cc[0] + p[0] * c - p[1] * s, cc[1] + p[0] * s + p[1] * c];
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
//! Puppet meshes: the layer's alpha outline → contour → simplified polygon → expansion →
|
||||
//! constrained triangulation with density control.
|
||||
//!
|
||||
//! * The alpha channel is thresholded at 50 % and grown (or shrunk) by Expansion with an exact
|
||||
//! Euclidean distance transform (the lower-envelope-of-parabolas method of Felzenszwalb &
|
||||
//! Huttenlocher, "Distance Transforms of Sampled Functions").
|
||||
//! * The 4-connected region under the click (holes filled) is traced along pixel cracks into a
|
||||
//! closed polygon, simplified with Douglas–Peucker and split so no edge is longer than the
|
||||
//! target edge length.
|
||||
//! * Interior points on a jittered hexagonal lattice are added, everything is triangulated with
|
||||
//! Bowyer–Watson Delaunay insertion, missing outline edges are recovered by edge flips (the
|
||||
//! textbook constrained-Delaunay edge-recovery procedure), and triangles outside the outline
|
||||
//! are dropped.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
|
||||
/// A triangle mesh in layer space. Triangles are counter-clockwise in the (x right, y down)
|
||||
/// layer coordinates, i.e. `cross(b - a, c - a) > 0`.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Mesh {
|
||||
pub verts: Vec<[f64; 2]>,
|
||||
pub tris: Vec<[usize; 3]>,
|
||||
/// The outline polygon (layer space).
|
||||
pub outline: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
/// Binary coverage grid in buffer pixels.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Grid {
|
||||
pub w: usize,
|
||||
pub h: usize,
|
||||
pub on: Vec<bool>,
|
||||
}
|
||||
|
||||
impl Grid {
|
||||
#[inline]
|
||||
pub fn at(&self, x: i64, y: i64) -> bool {
|
||||
x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.on[y as usize * self.w + x as usize]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cross(o: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
|
||||
(a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
}
|
||||
|
||||
fn dist2(a: [f64; 2], b: [f64; 2]) -> f64 {
|
||||
(a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2)
|
||||
}
|
||||
|
||||
/// 1D squared-distance transform of `f` (Felzenszwalb & Huttenlocher).
|
||||
fn dt1(f: &[f64], out: &mut [f64]) {
|
||||
let n = f.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let mut v = vec![0usize; n];
|
||||
let mut z = vec![0.0f64; n + 1];
|
||||
let mut k = 0usize;
|
||||
z[0] = f64::NEG_INFINITY;
|
||||
z[1] = f64::INFINITY;
|
||||
let inter = |q: usize, p: usize| ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2.0 * q as f64 - 2.0 * p as f64);
|
||||
for q in 1..n {
|
||||
let mut s = inter(q, v[k]);
|
||||
while s <= z[k] {
|
||||
k -= 1;
|
||||
s = inter(q, v[k]);
|
||||
}
|
||||
k += 1;
|
||||
v[k] = q;
|
||||
z[k] = s;
|
||||
z[k + 1] = f64::INFINITY;
|
||||
}
|
||||
let mut k = 0;
|
||||
for (q, o) in out.iter_mut().enumerate() {
|
||||
while z[k + 1] < q as f64 {
|
||||
k += 1;
|
||||
}
|
||||
let p = v[k];
|
||||
*o = (q as f64 - p as f64).powi(2) + f[p];
|
||||
}
|
||||
}
|
||||
|
||||
/// Squared Euclidean distance from every cell to the nearest cell where `src` is true.
|
||||
pub fn distance_sq(w: usize, h: usize, src: &[bool]) -> Vec<f64> {
|
||||
let inf = 1e20;
|
||||
let mut g = vec![inf; w * h];
|
||||
let mut col = vec![0.0; h];
|
||||
let mut colo = vec![0.0; h];
|
||||
for x in 0..w {
|
||||
for y in 0..h {
|
||||
col[y] = if src[y * w + x] { 0.0 } else { inf };
|
||||
}
|
||||
dt1(&col, &mut colo);
|
||||
for y in 0..h {
|
||||
g[y * w + x] = colo[y];
|
||||
}
|
||||
}
|
||||
let mut out = vec![0.0; w * h];
|
||||
for y in 0..h {
|
||||
dt1(&g[y * w..(y + 1) * w], &mut out[y * w..(y + 1) * w]);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Grow (`e > 0`) or shrink (`e < 0`) a grid by `e` cells.
|
||||
pub fn expand(g: &Grid, e: f64) -> Grid {
|
||||
if e.abs() < 1e-9 {
|
||||
return g.clone();
|
||||
}
|
||||
if e > 0.0 {
|
||||
let d = distance_sq(g.w, g.h, &g.on);
|
||||
Grid { w: g.w, h: g.h, on: d.iter().map(|v| *v <= e * e).collect() }
|
||||
} else {
|
||||
let off: Vec<bool> = g.on.iter().map(|b| !b).collect();
|
||||
let d = distance_sq(g.w, g.h, &off);
|
||||
Grid { w: g.w, h: g.h, on: d.iter().zip(&g.on).map(|(v, on)| *on && *v > e * e).collect() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The 4-connected region containing (or nearest to) `seed`, with holes filled.
|
||||
pub fn region(g: &Grid, seed: [f64; 2]) -> Option<Grid> {
|
||||
let (w, h) = (g.w, g.h);
|
||||
if w == 0 || h == 0 {
|
||||
return None;
|
||||
}
|
||||
let sx = (seed[0].floor() as i64).clamp(0, w as i64 - 1);
|
||||
let sy = (seed[1].floor() as i64).clamp(0, h as i64 - 1);
|
||||
let start = if g.at(sx, sy) {
|
||||
(sx as usize, sy as usize)
|
||||
} else {
|
||||
// Nearest on-cell.
|
||||
let mut best: Option<(i64, usize, usize)> = None;
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if g.on[y * w + x] {
|
||||
let d = (x as i64 - sx).pow(2) + (y as i64 - sy).pow(2);
|
||||
if best.is_none_or(|b| d < b.0) {
|
||||
best = Some((d, x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let b = best?;
|
||||
(b.1, b.2)
|
||||
};
|
||||
let mut on = vec![false; w * h];
|
||||
let mut q = VecDeque::new();
|
||||
on[start.1 * w + start.0] = true;
|
||||
q.push_back(start);
|
||||
while let Some((x, y)) = q.pop_front() {
|
||||
let mut visit = |nx: i64, ny: i64| {
|
||||
if g.at(nx, ny) && !on[ny as usize * w + nx as usize] {
|
||||
on[ny as usize * w + nx as usize] = true;
|
||||
q.push_back((nx as usize, ny as usize));
|
||||
}
|
||||
};
|
||||
visit(x as i64 - 1, y as i64);
|
||||
visit(x as i64 + 1, y as i64);
|
||||
visit(x as i64, y as i64 - 1);
|
||||
visit(x as i64, y as i64 + 1);
|
||||
}
|
||||
// Fill holes: everything not reachable from the border through off-cells.
|
||||
let mut outside = vec![false; w * h];
|
||||
let mut q = VecDeque::new();
|
||||
for x in 0..w {
|
||||
for y in [0, h - 1] {
|
||||
if !on[y * w + x] && !outside[y * w + x] {
|
||||
outside[y * w + x] = true;
|
||||
q.push_back((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
for y in 0..h {
|
||||
for x in [0, w - 1] {
|
||||
if !on[y * w + x] && !outside[y * w + x] {
|
||||
outside[y * w + x] = true;
|
||||
q.push_back((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some((x, y)) = q.pop_front() {
|
||||
for (dx, dy) in [(-1i64, 0i64), (1, 0), (0, -1), (0, 1)] {
|
||||
let (nx, ny) = (x as i64 + dx, y as i64 + dy);
|
||||
if nx < 0 || ny < 0 || nx >= w as i64 || ny >= h as i64 {
|
||||
continue;
|
||||
}
|
||||
let i = ny as usize * w + nx as usize;
|
||||
if !on[i] && !outside[i] {
|
||||
outside[i] = true;
|
||||
q.push_back((nx as usize, ny as usize));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Grid { w, h, on: outside.iter().map(|o| !o).collect() })
|
||||
}
|
||||
|
||||
/// Trace the outer boundary of a hole-free region along pixel cracks: a closed polygon through
|
||||
/// pixel corners, region on the left when walking (counter-clockwise in y-down coordinates).
|
||||
pub fn trace(g: &Grid) -> Vec<[f64; 2]> {
|
||||
// Directed boundary edges between corners; region on the right of the edge in y-down
|
||||
// screen terms (we fix orientation at the end anyway).
|
||||
let mut next: BTreeMap<(i64, i64), Vec<(i64, i64)>> = BTreeMap::new();
|
||||
for y in 0..g.h as i64 {
|
||||
for x in 0..g.w as i64 {
|
||||
if !g.at(x, y) {
|
||||
continue;
|
||||
}
|
||||
if !g.at(x, y - 1) {
|
||||
next.entry((x, y)).or_default().push((x + 1, y));
|
||||
}
|
||||
if !g.at(x + 1, y) {
|
||||
next.entry((x + 1, y)).or_default().push((x + 1, y + 1));
|
||||
}
|
||||
if !g.at(x, y + 1) {
|
||||
next.entry((x + 1, y + 1)).or_default().push((x, y + 1));
|
||||
}
|
||||
if !g.at(x - 1, y) {
|
||||
next.entry((x, y + 1)).or_default().push((x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut best: Vec<[f64; 2]> = vec![];
|
||||
let mut best_area = 0.0;
|
||||
while let Some(&start) = next.iter().find(|(_, v)| !v.is_empty()).map(|(k, _)| k) {
|
||||
let mut lp = vec![start];
|
||||
let mut cur = start;
|
||||
let mut dir = (0i64, 0i64);
|
||||
let mut guard = 0;
|
||||
loop {
|
||||
guard += 1;
|
||||
if guard > 4 * (g.w + 2) * (g.h + 2) {
|
||||
break;
|
||||
}
|
||||
let Some(outs) = next.get_mut(&cur) else { break };
|
||||
if outs.is_empty() {
|
||||
break;
|
||||
}
|
||||
// At a saddle corner pick the right-most turn relative to the incoming direction
|
||||
// (keeps diagonal-touching parts separate).
|
||||
let k = if outs.len() == 1 || dir == (0, 0) {
|
||||
0
|
||||
} else {
|
||||
let score = |o: &(i64, i64)| {
|
||||
let d = (o.0 - cur.0, o.1 - cur.1);
|
||||
dir.0 * d.1 - dir.1 * d.0
|
||||
};
|
||||
(0..outs.len()).max_by_key(|i| score(&outs[*i])).unwrap_or(0)
|
||||
};
|
||||
let nx = outs.swap_remove(k);
|
||||
dir = (nx.0 - cur.0, nx.1 - cur.1);
|
||||
cur = nx;
|
||||
if cur == start {
|
||||
break;
|
||||
}
|
||||
lp.push(cur);
|
||||
}
|
||||
let pts: Vec<[f64; 2]> = lp.iter().map(|p| [p.0 as f64, p.1 as f64]).collect();
|
||||
let a = signed_area(&pts).abs();
|
||||
if a > best_area {
|
||||
best_area = a;
|
||||
best = pts;
|
||||
}
|
||||
}
|
||||
// Drop collinear corners.
|
||||
let n = best.len();
|
||||
if n < 3 {
|
||||
return best;
|
||||
}
|
||||
let mut out = vec![];
|
||||
for i in 0..n {
|
||||
let (a, b, c) = (best[(i + n - 1) % n], best[i], best[(i + 1) % n]);
|
||||
if cross(a, b, c).abs() > 1e-12 {
|
||||
out.push(b);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn signed_area(p: &[[f64; 2]]) -> f64 {
|
||||
let n = p.len();
|
||||
let mut a = 0.0;
|
||||
for i in 0..n {
|
||||
let (u, v) = (p[i], p[(i + 1) % n]);
|
||||
a += u[0] * v[1] - v[0] * u[1];
|
||||
}
|
||||
a * 0.5
|
||||
}
|
||||
|
||||
fn seg_dist2(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {
|
||||
let ab = [b[0] - a[0], b[1] - a[1]];
|
||||
let l = ab[0] * ab[0] + ab[1] * ab[1];
|
||||
let t = if l > 0.0 { (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / l).clamp(0.0, 1.0) } else { 0.0 };
|
||||
dist2(p, [a[0] + ab[0] * t, a[1] + ab[1] * t])
|
||||
}
|
||||
|
||||
/// Douglas–Peucker simplification of a closed polygon.
|
||||
pub fn simplify(p: &[[f64; 2]], tol: f64) -> Vec<[f64; 2]> {
|
||||
let n = p.len();
|
||||
if n <= 4 {
|
||||
return p.to_vec();
|
||||
}
|
||||
// Split the loop at vertex 0 and the vertex farthest from it; simplify both open chains.
|
||||
let far = (1..n).max_by(|a, b| dist2(p[0], p[*a]).total_cmp(&dist2(p[0], p[*b]))).unwrap_or(n / 2);
|
||||
let mut ext = p.to_vec();
|
||||
ext.push(p[0]);
|
||||
let mut keep = vec![false; n + 1];
|
||||
let tol2 = tol * tol;
|
||||
let mut stack = vec![(0usize, far), (far, n)];
|
||||
keep[0] = true;
|
||||
keep[far] = true;
|
||||
while let Some((a, b)) = stack.pop() {
|
||||
if b <= a + 1 {
|
||||
continue;
|
||||
}
|
||||
let mut best = (0.0, 0);
|
||||
for i in a + 1..b {
|
||||
let d = seg_dist2(ext[i], ext[a], ext[b]);
|
||||
if d > best.0 {
|
||||
best = (d, i);
|
||||
}
|
||||
}
|
||||
if best.0 > tol2 {
|
||||
keep[best.1] = true;
|
||||
stack.push((a, best.1));
|
||||
stack.push((best.1, b));
|
||||
}
|
||||
}
|
||||
(0..n).filter(|i| keep[*i]).map(|i| p[i]).collect()
|
||||
}
|
||||
|
||||
/// Split polygon edges so none is longer than `max_len`.
|
||||
pub fn densify(p: &[[f64; 2]], max_len: f64) -> Vec<[f64; 2]> {
|
||||
let n = p.len();
|
||||
let mut out = vec![];
|
||||
for i in 0..n {
|
||||
let (a, b) = (p[i], p[(i + 1) % n]);
|
||||
out.push(a);
|
||||
let l = dist2(a, b).sqrt();
|
||||
let k = (l / max_len.max(1e-6)).ceil() as usize;
|
||||
for j in 1..k {
|
||||
let t = j as f64 / k as f64;
|
||||
out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Even-odd point-in-polygon test.
|
||||
pub fn inside(poly: &[[f64; 2]], p: [f64; 2]) -> bool {
|
||||
let n = poly.len();
|
||||
let mut c = false;
|
||||
let mut j = n.wrapping_sub(1);
|
||||
for i in 0..n {
|
||||
let (a, b) = (poly[i], poly[j]);
|
||||
if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0] {
|
||||
c = !c;
|
||||
}
|
||||
j = i;
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
fn poly_dist2(poly: &[[f64; 2]], p: [f64; 2]) -> f64 {
|
||||
let n = poly.len();
|
||||
(0..n).map(|i| seg_dist2(p, poly[i], poly[(i + 1) % n])).fold(f64::MAX, f64::min)
|
||||
}
|
||||
|
||||
/// Circumcircle test: is `d` strictly inside the circumcircle of CCW (`cross > 0`) triangle abc?
|
||||
fn in_circle(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
|
||||
let (ax, ay) = (a[0] - d[0], a[1] - d[1]);
|
||||
let (bx, by) = (b[0] - d[0], b[1] - d[1]);
|
||||
let (cx, cy) = (c[0] - d[0], c[1] - d[1]);
|
||||
let (la, lb, lc) = (ax * ax + ay * ay, bx * bx + by * by, cx * cx + cy * cy);
|
||||
let det = la * (bx * cy - cx * by) - lb * (ax * cy - cx * ay) + lc * (ax * by - bx * ay);
|
||||
let m = la.max(lb).max(lc);
|
||||
det > 1e-12 * m * m
|
||||
}
|
||||
|
||||
/// Bowyer–Watson Delaunay triangulation of `pts` (CCW triangles, `cross > 0`).
|
||||
pub fn delaunay(pts: &[[f64; 2]]) -> Vec<[usize; 3]> {
|
||||
let n = pts.len();
|
||||
if n < 3 {
|
||||
return vec![];
|
||||
}
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for p in pts {
|
||||
x0 = x0.min(p[0]);
|
||||
y0 = y0.min(p[1]);
|
||||
x1 = x1.max(p[0]);
|
||||
y1 = y1.max(p[1]);
|
||||
}
|
||||
let d = (x1 - x0).max(y1 - y0).max(1.0) * 20.0;
|
||||
let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5);
|
||||
let mut v = pts.to_vec();
|
||||
v.push([cx - d, cy - d]);
|
||||
v.push([cx + d, cy - d]);
|
||||
v.push([cx, cy + d]);
|
||||
let mut tris: Vec<[usize; 3]> = vec![orient(&v, [n, n + 1, n + 2])];
|
||||
for i in 0..n {
|
||||
let p = v[i];
|
||||
let mut bad = vec![];
|
||||
for (k, t) in tris.iter().enumerate() {
|
||||
if in_circle(v[t[0]], v[t[1]], v[t[2]], p) {
|
||||
bad.push(k);
|
||||
}
|
||||
}
|
||||
if bad.is_empty() {
|
||||
// On a circle or exactly on an edge: find the containing triangle instead.
|
||||
if let Some(k) =
|
||||
tris.iter().position(|t| cross(v[t[0]], v[t[1]], p) >= 0.0 && cross(v[t[1]], v[t[2]], p) >= 0.0 && cross(v[t[2]], v[t[0]], p) >= 0.0)
|
||||
{
|
||||
bad.push(k);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Cavity boundary: edges of bad triangles not shared by two of them.
|
||||
let mut count: HashMap<(usize, usize), u32> = HashMap::new();
|
||||
for k in &bad {
|
||||
let t = tris[*k];
|
||||
for e in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
*count.entry((e.0.min(e.1), e.0.max(e.1))).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let mut edges = vec![];
|
||||
for k in &bad {
|
||||
let t = tris[*k];
|
||||
for e in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
if count[&(e.0.min(e.1), e.0.max(e.1))] == 1 {
|
||||
edges.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sorted = bad.clone();
|
||||
sorted.sort_unstable_by(|a, b| b.cmp(a));
|
||||
for k in sorted {
|
||||
tris.swap_remove(k);
|
||||
}
|
||||
for (a, b) in edges {
|
||||
if cross(v[a], v[b], p).abs() > 1e-12 {
|
||||
tris.push(orient(&v, [a, b, i]));
|
||||
}
|
||||
}
|
||||
}
|
||||
tris.retain(|t| t.iter().all(|i| *i < n));
|
||||
tris
|
||||
}
|
||||
|
||||
fn orient(v: &[[f64; 2]], t: [usize; 3]) -> [usize; 3] {
|
||||
if cross(v[t[0]], v[t[1]], v[t[2]]) < 0.0 { [t[0], t[2], t[1]] } else { t }
|
||||
}
|
||||
|
||||
fn seg_cross(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> bool {
|
||||
let d1 = cross(a, b, c);
|
||||
let d2 = cross(a, b, d);
|
||||
let d3 = cross(c, d, a);
|
||||
let d4 = cross(c, d, b);
|
||||
((d1 > 1e-12 && d2 < -1e-12) || (d1 < -1e-12 && d2 > 1e-12)) && ((d3 > 1e-12 && d4 < -1e-12) || (d3 < -1e-12 && d4 > 1e-12))
|
||||
}
|
||||
|
||||
fn key(a: usize, b: usize) -> (usize, usize) {
|
||||
(a.min(b), a.max(b))
|
||||
}
|
||||
|
||||
/// Recover constraint edges in a triangulation by flipping crossing edges.
|
||||
pub fn recover_edges(v: &[[f64; 2]], tris: &mut [[usize; 3]], constraints: &[(usize, usize)]) {
|
||||
let mut edge_tris: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
|
||||
for (k, t) in tris.iter().enumerate() {
|
||||
for e in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
edge_tris.entry(key(e.0, e.1)).or_default().push(k);
|
||||
}
|
||||
}
|
||||
let fixed: std::collections::HashSet<(usize, usize)> = constraints.iter().map(|&(a, b)| key(a, b)).collect();
|
||||
for &(a, b) in constraints {
|
||||
if edge_tris.get(&key(a, b)).is_some_and(|t| !t.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
let mut queue: VecDeque<(usize, usize)> =
|
||||
edge_tris.iter().filter(|(e, t)| t.len() == 2 && seg_cross(v[a], v[b], v[e.0], v[e.1])).map(|(e, _)| *e).collect();
|
||||
let mut guard = 0;
|
||||
while let Some(e) = queue.pop_front() {
|
||||
guard += 1;
|
||||
if guard > 20_000 {
|
||||
break;
|
||||
}
|
||||
let Some(ts) = edge_tris.get(&e).cloned() else { continue };
|
||||
if ts.len() != 2 || fixed.contains(&e) {
|
||||
continue;
|
||||
}
|
||||
let (t0, t1) = (tris[ts[0]], tris[ts[1]]);
|
||||
let p = t0.iter().copied().find(|x| *x != e.0 && *x != e.1);
|
||||
let q = t1.iter().copied().find(|x| *x != e.0 && *x != e.1);
|
||||
let (Some(p), Some(q)) = (p, q) else { continue };
|
||||
// Convex quad (u, p, w, q)? Then the diagonal pq crosses uw.
|
||||
if !seg_cross(v[p], v[q], v[e.0], v[e.1]) {
|
||||
if queue.is_empty() {
|
||||
break;
|
||||
}
|
||||
queue.push_back(e);
|
||||
continue;
|
||||
}
|
||||
// Flip.
|
||||
for (k, t) in [(ts[0], t0), (ts[1], t1)] {
|
||||
for ed in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
if let Some(l) = edge_tris.get_mut(&key(ed.0, ed.1)) {
|
||||
l.retain(|x| *x != k);
|
||||
}
|
||||
}
|
||||
}
|
||||
let n0 = orient(v, [p, q, e.0]);
|
||||
let n1 = orient(v, [p, q, e.1]);
|
||||
tris[ts[0]] = n0;
|
||||
tris[ts[1]] = n1;
|
||||
for (k, t) in [(ts[0], n0), (ts[1], n1)] {
|
||||
for ed in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
edge_tris.entry(key(ed.0, ed.1)).or_default().push(k);
|
||||
}
|
||||
}
|
||||
edge_tris.retain(|_, l| !l.is_empty());
|
||||
if seg_cross(v[a], v[b], v[p], v[q]) {
|
||||
queue.push_back(key(p, q));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mesh options (Puppet ▸ Mesh: Triangles, Density, Expansion).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MeshOpts {
|
||||
/// Target triangle count.
|
||||
pub triangles: f64,
|
||||
/// 0–100; 50 = the target count, each 25 doubles / halves it.
|
||||
pub density: f64,
|
||||
/// Outline growth in layer pixels.
|
||||
pub expansion: f64,
|
||||
}
|
||||
|
||||
impl Default for MeshOpts {
|
||||
fn default() -> Self {
|
||||
MeshOpts { triangles: 350.0, density: 50.0, expansion: 3.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic jitter in [-0.5, 0.5).
|
||||
fn jitter(i: u64) -> f64 {
|
||||
let mut x = i.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ 0x2545_f491_4f6c_dd1d;
|
||||
x ^= x >> 31;
|
||||
x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
x ^= x >> 29;
|
||||
(x >> 11) as f64 / (1u64 << 53) as f64 - 0.5
|
||||
}
|
||||
|
||||
/// Build a mesh over a polygon outline (layer space) with the option's target size.
|
||||
pub fn triangulate(outline: &[[f64; 2]], opts: &MeshOpts) -> Mesh {
|
||||
let mut poly = outline.to_vec();
|
||||
if signed_area(&poly) < 0.0 {
|
||||
poly.reverse();
|
||||
}
|
||||
let area = signed_area(&poly).abs();
|
||||
if poly.len() < 3 || area <= 0.0 {
|
||||
return Mesh::default();
|
||||
}
|
||||
let target = (opts.triangles.max(2.0) * 2f64.powf((opts.density - 50.0) / 25.0)).clamp(2.0, 20_000.0);
|
||||
let l = (4.0 * area / (3f64.sqrt() * target)).sqrt().max(0.5);
|
||||
let boundary = densify(&poly, l);
|
||||
let nb = boundary.len();
|
||||
let mut pts = boundary.clone();
|
||||
// Interior: a jittered hexagonal lattice, kept away from the outline.
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for p in &poly {
|
||||
x0 = x0.min(p[0]);
|
||||
y0 = y0.min(p[1]);
|
||||
x1 = x1.max(p[0]);
|
||||
y1 = y1.max(p[1]);
|
||||
}
|
||||
let dy = l * 3f64.sqrt() * 0.5;
|
||||
let mut row = 0u64;
|
||||
let mut y = y0 + dy * 0.5;
|
||||
let min_d2 = (0.55 * l).powi(2);
|
||||
while y < y1 {
|
||||
let mut x = x0 + if row % 2 == 1 { l * 0.5 } else { 0.0 } + l * 0.25;
|
||||
let mut col = 0u64;
|
||||
while x < x1 {
|
||||
let id = row * 100_003 + col;
|
||||
let p = [x + jitter(id * 2) * l * 0.08, y + jitter(id * 2 + 1) * l * 0.08];
|
||||
if inside(&poly, p) && poly_dist2(&boundary, p) >= min_d2 {
|
||||
pts.push(p);
|
||||
}
|
||||
x += l;
|
||||
col += 1;
|
||||
}
|
||||
y += dy;
|
||||
row += 1;
|
||||
}
|
||||
let mut tris = delaunay(&pts);
|
||||
let constraints: Vec<(usize, usize)> = (0..nb).map(|i| (i, (i + 1) % nb)).collect();
|
||||
recover_edges(&pts, &mut tris, &constraints);
|
||||
tris.retain(|t| {
|
||||
let c = [(pts[t[0]][0] + pts[t[1]][0] + pts[t[2]][0]) / 3.0, (pts[t[0]][1] + pts[t[1]][1] + pts[t[2]][1]) / 3.0];
|
||||
cross(pts[t[0]], pts[t[1]], pts[t[2]]) > 1e-9 && inside(&poly, c)
|
||||
});
|
||||
// Compact the vertex list.
|
||||
let mut map = vec![usize::MAX; pts.len()];
|
||||
let mut verts = vec![];
|
||||
for t in tris.iter_mut() {
|
||||
for i in t.iter_mut() {
|
||||
if map[*i] == usize::MAX {
|
||||
map[*i] = verts.len();
|
||||
verts.push(pts[*i]);
|
||||
}
|
||||
*i = map[*i];
|
||||
}
|
||||
}
|
||||
Mesh { verts, tris, outline: poly }
|
||||
}
|
||||
|
||||
/// The outline of the alpha region under `seed` (buffer pixels → layer space via `scale` and
|
||||
/// `offset`), expanded by `expansion` layer pixels.
|
||||
pub fn outline(alpha: &[f32], w: usize, h: usize, scale: f64, offset: [f64; 2], seed: [f64; 2], expansion: f64) -> Vec<[f64; 2]> {
|
||||
// Pad so expansion can grow past the buffer edge.
|
||||
let pad = (expansion.max(0.0) * scale).ceil() as usize + 2;
|
||||
let (pw, ph) = (w + 2 * pad, h + 2 * pad);
|
||||
let mut on = vec![false; pw * ph];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
on[(y + pad) * pw + x + pad] = alpha[y * w + x] >= 0.5;
|
||||
}
|
||||
}
|
||||
let g = expand(&Grid { w: pw, h: ph, on }, expansion * scale);
|
||||
let sp = [seed[0] * scale + offset[0] + pad as f64, seed[1] * scale + offset[1] + pad as f64];
|
||||
let Some(r) = region(&g, sp) else { return vec![] };
|
||||
let c = trace(&r);
|
||||
let c = simplify(&c, 0.75);
|
||||
c.iter().map(|p| [(p[0] - pad as f64 - offset[0]) / scale, (p[1] - pad as f64 - offset[1]) / scale]).collect()
|
||||
}
|
||||
@@ -0,0 +1,517 @@
|
||||
//! Puppet: mesh deformation driven by pins (the Puppet Position, Advanced, Bend, Starch and
|
||||
//! Overlap Pin tools).
|
||||
//!
|
||||
//! ```text
|
||||
//! Puppet (effect `ec.distort.puppet`; Mesh Rotation Refinement)
|
||||
//! Mesh 1 (match `mesh`: Density, Expansion, Triangles; hidden seed)
|
||||
//! Deform (match `deform`)
|
||||
//! Puppet Pin 1 (match `pin`: Position | Scale, Rotation | Amount, Extent |
|
||||
//! In Front, Extent; hidden pin type and rest position)
|
||||
//! ```
|
||||
//!
|
||||
//! Each frame the mesh is built from the effect's input alpha (see [`mesh`]; cached by content),
|
||||
//! pins are attached to their nearest mesh vertices at rest, the as-rigid-as-possible solver
|
||||
//! ([`arap`]) moves the vertices, and the input is texture-mapped through the deformed
|
||||
//! triangles (bilinear sampling, 2×2 coverage anti-aliasing on the outline, Overlap pins'
|
||||
//! In Front deciding which triangles draw on top).
|
||||
|
||||
pub mod arap;
|
||||
pub mod mesh;
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
|
||||
use effectcraft_raster::Image;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, Params, p, slider};
|
||||
pub use mesh::{Mesh, MeshOpts};
|
||||
|
||||
/// Effect id of the Puppet effect.
|
||||
pub const ID: &str = "ec.distort.puppet";
|
||||
|
||||
/// Puppet pin types (the five Puppet tools).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum PinKind {
|
||||
#[default]
|
||||
Position,
|
||||
Advanced,
|
||||
Bend,
|
||||
Starch,
|
||||
Overlap,
|
||||
}
|
||||
|
||||
impl PinKind {
|
||||
pub const ALL: [PinKind; 5] = [PinKind::Position, PinKind::Advanced, PinKind::Bend, PinKind::Starch, PinKind::Overlap];
|
||||
pub fn index(self) -> u32 {
|
||||
PinKind::ALL.iter().position(|k| *k == self).unwrap_or(0) as u32
|
||||
}
|
||||
pub fn from_index(i: u32) -> PinKind {
|
||||
PinKind::ALL.get(i as usize).copied().unwrap_or_default()
|
||||
}
|
||||
pub fn from_name(s: &str) -> Option<PinKind> {
|
||||
let n = s.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
Some(match n.trim_end_matches("pin") {
|
||||
"position" | "puppet" | "puppetposition" => PinKind::Position,
|
||||
"advanced" | "puppetadvanced" => PinKind::Advanced,
|
||||
"bend" | "puppetbend" => PinKind::Bend,
|
||||
"starch" | "puppetstarch" => PinKind::Starch,
|
||||
"overlap" | "puppetoverlap" => PinKind::Overlap,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
PinKind::Position => "position",
|
||||
PinKind::Advanced => "advanced",
|
||||
PinKind::Bend => "bend",
|
||||
PinKind::Starch => "starch",
|
||||
PinKind::Overlap => "overlap",
|
||||
}
|
||||
}
|
||||
/// Group name prefix (`Puppet Pin 3`, `Starch 1`, `Overlap 2`).
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
PinKind::Starch => "Starch",
|
||||
PinKind::Overlap => "Overlap",
|
||||
_ => "Puppet Pin",
|
||||
}
|
||||
}
|
||||
/// Pins that hold a position (Starch and Overlap pins sit on the rest mesh).
|
||||
pub fn moves(self) -> bool {
|
||||
matches!(self, PinKind::Position | PinKind::Advanced)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
vec![EffectSpec {
|
||||
id: ID,
|
||||
name: "Puppet",
|
||||
category: "Distort",
|
||||
params: vec![p("refinement", "Mesh Rotation Refinement", Value::Scalar(20.0), slider(0.0, 100.0, 0.0, 100.0, 0))],
|
||||
render,
|
||||
gpu: false,
|
||||
float: true,
|
||||
}]
|
||||
}
|
||||
|
||||
fn hidden(ids: &mut Ids, m: &str, v: Value) -> Property {
|
||||
let mut p = ids.prop(m, m, v).with_ui(ParamUi::Hidden);
|
||||
p.static_only = true;
|
||||
p
|
||||
}
|
||||
|
||||
/// A new mesh group (`Mesh 1`) whose outline is the alpha region under `seed` (layer space).
|
||||
pub fn mesh_group(ids: &mut Ids, name: &str, seed: [f64; 2], opts: &MeshOpts) -> PropGroup {
|
||||
let mut g = ids.group("mesh", name);
|
||||
g.kind = GroupKind::Indexed;
|
||||
g.children.push(ids.prop("density", "Density", Value::Scalar(opts.density)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)).into());
|
||||
g.children.push(ids.prop("expansion", "Expansion", Value::Scalar(opts.expansion)).with_ui(slider(-100.0, 200.0, -20.0, 50.0, 1)).into());
|
||||
g.children.push(ids.prop("triangles", "Triangles", Value::Scalar(opts.triangles)).with_ui(slider(10.0, 10_000.0, 10.0, 2000.0, 0)).into());
|
||||
g.children.push(hidden(ids, "seed", Value::Vec2(seed)).into());
|
||||
g.children.push(ids.group("deform", "Deform").into());
|
||||
g
|
||||
}
|
||||
|
||||
/// A new pin group at layer-space `rest`.
|
||||
pub fn pin_group(ids: &mut Ids, name: &str, kind: PinKind, rest: [f64; 2]) -> PropGroup {
|
||||
let mut g = ids.group("pin", name);
|
||||
g.kind = GroupKind::Indexed;
|
||||
g.children.push(hidden(ids, "kind", Value::Enum(kind.index())).into());
|
||||
g.children.push(hidden(ids, "rest", Value::Vec2(rest)).into());
|
||||
if kind != PinKind::Bend {
|
||||
g.children.push(ids.prop("position", "Position", Value::Vec2(rest)).with_ui(ParamUi::Point).spatial().into());
|
||||
}
|
||||
match kind {
|
||||
PinKind::Advanced | PinKind::Bend => {
|
||||
g.children.push(ids.prop("scale", "Scale", Value::Scalar(100.0)).with_ui(ParamUi::Percent).into());
|
||||
g.children.push(ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle).into());
|
||||
}
|
||||
PinKind::Starch => {
|
||||
g.children.push(ids.prop("amount", "Amount", Value::Scalar(50.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 1)).into());
|
||||
g.children.push(ids.prop("extent", "Extent", Value::Scalar(15.0)).with_ui(ParamUi::Pixels).into());
|
||||
}
|
||||
PinKind::Overlap => {
|
||||
g.children.push(ids.prop("in_front", "In Front", Value::Scalar(50.0)).with_ui(slider(-100.0, 100.0, -100.0, 100.0, 1)).into());
|
||||
g.children.push(ids.prop("extent", "Extent", Value::Scalar(15.0)).with_ui(ParamUi::Pixels).into());
|
||||
}
|
||||
PinKind::Position => {}
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// Mesh groups of a Puppet effect instance.
|
||||
pub fn meshes(fx: &PropGroup) -> impl Iterator<Item = &PropGroup> {
|
||||
fx.groups().filter(|g| g.match_id == "mesh")
|
||||
}
|
||||
|
||||
/// Pin groups of a mesh group.
|
||||
pub fn pins(mesh: &PropGroup) -> impl Iterator<Item = &PropGroup> {
|
||||
mesh.sub("deform").into_iter().flat_map(|d| d.groups().filter(|g| g.match_id == "pin"))
|
||||
}
|
||||
|
||||
/// Next pin name for a kind, unique across the effect's meshes (`fx` is the Puppet effect).
|
||||
pub fn next_pin_name(fx: &PropGroup, kind: PinKind) -> String {
|
||||
let n = meshes(fx).flat_map(pins).filter(|p| PinKind::from_index(p.get("kind").map(|k| k.value.as_enum()).unwrap_or(0)).label() == kind.label()).count();
|
||||
format!("{} {}", kind.label(), n + 1)
|
||||
}
|
||||
|
||||
/// Is `g` a Puppet effect instance?
|
||||
pub fn is_puppet(g: &PropGroup) -> bool {
|
||||
matches!(&g.kind, GroupKind::Effect { effect } if effect == ID)
|
||||
}
|
||||
|
||||
/// A pin evaluated at the render time.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pin {
|
||||
pub kind: PinKind,
|
||||
pub uid: u64,
|
||||
pub rest: [f64; 2],
|
||||
pub position: [f64; 2],
|
||||
pub scale: f64,
|
||||
pub rotation: f64,
|
||||
pub amount: f64,
|
||||
pub extent: f64,
|
||||
pub in_front: f64,
|
||||
}
|
||||
|
||||
/// A mesh group evaluated at the render time.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MeshParams {
|
||||
pub uid: u64,
|
||||
pub seed: [f64; 2],
|
||||
pub opts: MeshOpts,
|
||||
pub pins: Vec<Pin>,
|
||||
}
|
||||
|
||||
fn fd(p: &Params, k: &str, d: f64) -> f64 {
|
||||
p.get(k).map(Value::as_f64).unwrap_or(d)
|
||||
}
|
||||
|
||||
/// Parse the meshes and pins out of flattened Puppet parameters.
|
||||
pub fn parse(params: &Params) -> Vec<MeshParams> {
|
||||
let mut out = vec![];
|
||||
for pre in params.groups("") {
|
||||
if params.s(&format!("{pre}@match")) != "mesh" || !params.get(&format!("{pre}@enabled")).is_none_or(Value::as_bool) {
|
||||
continue;
|
||||
}
|
||||
let k = |m: &str| format!("{pre}{m}");
|
||||
let mut pins = vec![];
|
||||
if let Some(d) = params.group(&pre, "deform") {
|
||||
for pp in params.groups(&d) {
|
||||
if params.s(&format!("{pp}@match")) != "pin" || !params.get(&format!("{pp}@enabled")).is_none_or(Value::as_bool) {
|
||||
continue;
|
||||
}
|
||||
let q = |m: &str| format!("{pp}{m}");
|
||||
let rest = params.get(&q("rest")).map(Value::as_vec2).unwrap_or([0.0; 2]);
|
||||
pins.push(Pin {
|
||||
kind: PinKind::from_index(params.get(&q("kind")).map(Value::as_enum).unwrap_or(0)),
|
||||
uid: fd(params, &q("@uid"), 0.0) as u64,
|
||||
rest,
|
||||
position: params.get(&q("position")).map(Value::as_vec2).unwrap_or(rest),
|
||||
scale: fd(params, &q("scale"), 100.0) / 100.0,
|
||||
rotation: fd(params, &q("rotation"), 0.0),
|
||||
amount: fd(params, &q("amount"), 50.0),
|
||||
extent: fd(params, &q("extent"), 15.0),
|
||||
in_front: fd(params, &q("in_front"), 50.0),
|
||||
});
|
||||
}
|
||||
}
|
||||
out.push(MeshParams {
|
||||
uid: fd(params, &k("@uid"), 0.0) as u64,
|
||||
seed: params.get(&k("seed")).map(Value::as_vec2).unwrap_or([0.0; 2]),
|
||||
opts: MeshOpts {
|
||||
density: fd(params, &k("density"), 50.0),
|
||||
expansion: fd(params, &k("expansion"), 3.0),
|
||||
triangles: fd(params, &k("triangles"), 350.0),
|
||||
},
|
||||
pins,
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// Mesh cache.
|
||||
|
||||
struct MeshCache {
|
||||
entries: Vec<(u64, Arc<Mesh>)>,
|
||||
}
|
||||
|
||||
static CACHE: Mutex<MeshCache> = Mutex::new(MeshCache { entries: Vec::new() });
|
||||
|
||||
fn fnv(h: &mut u64, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
*h ^= *b as u64;
|
||||
*h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
/// The mesh for `m` over a buffer's alpha (built once per distinct outline and options).
|
||||
pub fn mesh_for(buf: &Buf, m: &MeshParams) -> Arc<Mesh> {
|
||||
let (w, h) = (buf.img.width as usize, buf.img.height as usize);
|
||||
let alpha: Vec<f32> = buf.img.data.iter().map(|p| p[3]).collect();
|
||||
let mut key = 0xcbf2_9ce4_8422_2325u64;
|
||||
fnv(&mut key, &(w as u64).to_le_bytes());
|
||||
fnv(&mut key, &(h as u64).to_le_bytes());
|
||||
for v in [buf.scale, buf.offset[0], buf.offset[1], m.seed[0], m.seed[1], m.opts.density, m.opts.expansion, m.opts.triangles] {
|
||||
fnv(&mut key, &v.to_bits().to_le_bytes());
|
||||
}
|
||||
let mut bits = 0u8;
|
||||
for (i, a) in alpha.iter().enumerate() {
|
||||
bits = (bits << 1) | (*a >= 0.5) as u8;
|
||||
if i % 8 == 7 {
|
||||
fnv(&mut key, &[bits]);
|
||||
}
|
||||
}
|
||||
fnv(&mut key, &[bits]);
|
||||
if let Ok(c) = CACHE.lock()
|
||||
&& let Some((_, mesh)) = c.entries.iter().find(|(k, _)| *k == key)
|
||||
{
|
||||
return mesh.clone();
|
||||
}
|
||||
let outline = mesh::outline(&alpha, w, h, buf.scale.max(1e-9), buf.offset, m.seed, m.opts.expansion);
|
||||
let mesh = Arc::new(mesh::triangulate(&outline, &m.opts));
|
||||
if let Ok(mut c) = CACHE.lock() {
|
||||
c.entries.push((key, mesh.clone()));
|
||||
if c.entries.len() > 16 {
|
||||
c.entries.remove(0);
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
|
||||
fn nearest(verts: &[[f64; 2]], p: [f64; 2]) -> Option<usize> {
|
||||
(0..verts.len()).min_by(|a, b| {
|
||||
let da = (verts[*a][0] - p[0]).powi(2) + (verts[*a][1] - p[1]).powi(2);
|
||||
let db = (verts[*b][0] - p[0]).powi(2) + (verts[*b][1] - p[1]).powi(2);
|
||||
da.total_cmp(&db)
|
||||
})
|
||||
}
|
||||
|
||||
/// Per-triangle stiffness from Starch pins.
|
||||
pub fn starch_weights(mesh: &Mesh, pins: &[Pin]) -> Vec<f64> {
|
||||
mesh.tris
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let c = centroid(mesh, t);
|
||||
let mut w = 1.0;
|
||||
for p in pins.iter().filter(|p| p.kind == PinKind::Starch) {
|
||||
let d = ((c[0] - p.rest[0]).powi(2) + (c[1] - p.rest[1]).powi(2)).sqrt();
|
||||
let ext = p.extent.max(0.0) + 1e-9;
|
||||
let f = (1.0 - d / (ext * 2.0)).clamp(0.0, 1.0);
|
||||
w += f * p.amount.max(0.0) * 2.0;
|
||||
}
|
||||
w
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn centroid(mesh: &Mesh, t: &[usize; 3]) -> [f64; 2] {
|
||||
let v = &mesh.verts;
|
||||
[(v[t[0]][0] + v[t[1]][0] + v[t[2]][0]) / 3.0, (v[t[0]][1] + v[t[1]][1] + v[t[2]][1]) / 3.0]
|
||||
}
|
||||
|
||||
/// Solve the deformation of `mesh` for `pins` (layer space). Returns deformed vertices.
|
||||
pub fn solve(mesh: &Mesh, pins: &[Pin], refine: usize) -> Vec<[f64; 2]> {
|
||||
let mut h = arap::Handles::default();
|
||||
let mut adj: Vec<Vec<usize>> = vec![vec![]; mesh.verts.len()];
|
||||
for t in &mesh.tris {
|
||||
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
if !adj[a].contains(&b) {
|
||||
adj[a].push(b);
|
||||
}
|
||||
if !adj[b].contains(&a) {
|
||||
adj[b].push(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut used = std::collections::HashSet::new();
|
||||
for p in pins {
|
||||
let Some(v) = nearest(&mesh.verts, p.rest) else { continue };
|
||||
let r = mesh.verts[v];
|
||||
if p.kind.moves() && used.insert(v) {
|
||||
h.fixed.push((v, [p.position[0] + r[0] - p.rest[0], p.position[1] + r[1] - p.rest[1]]));
|
||||
}
|
||||
if matches!(p.kind, PinKind::Advanced | PinKind::Bend) {
|
||||
let (s, c) = p.rotation.to_radians().sin_cos();
|
||||
for &j in &adj[v] {
|
||||
let e = [mesh.verts[j][0] - r[0], mesh.verts[j][1] - r[1]];
|
||||
let vec = [p.scale * (e[0] * c - e[1] * s), p.scale * (e[0] * s + e[1] * c)];
|
||||
h.edges.push(arap::EdgeTarget { i: v, j, vec, weight: 10.0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
if h.fixed.is_empty() && h.edges.is_empty() {
|
||||
return mesh.verts.clone();
|
||||
}
|
||||
let w = starch_weights(mesh, pins);
|
||||
arap::deform(&mesh.verts, &mesh.tris, &w, &h, refine)
|
||||
}
|
||||
|
||||
/// Per-triangle depth from Overlap pins (higher draws in front).
|
||||
pub fn depths(mesh: &Mesh, pins: &[Pin]) -> Vec<f64> {
|
||||
mesh.tris
|
||||
.iter()
|
||||
.map(|t| {
|
||||
let c = centroid(mesh, t);
|
||||
let mut d: Option<f64> = None;
|
||||
for p in pins.iter().filter(|p| p.kind == PinKind::Overlap) {
|
||||
let dist = ((c[0] - p.rest[0]).powi(2) + (c[1] - p.rest[1]).powi(2)).sqrt();
|
||||
if dist <= p.extent.max(0.0) + 1e-9 {
|
||||
d = Some(d.map_or(p.in_front, |x: f64| x.max(p.in_front)));
|
||||
}
|
||||
}
|
||||
d.unwrap_or(0.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Map a point of the deformed mesh back to rest space (barycentric through the triangle that
|
||||
/// contains it, or the nearest vertex's offset).
|
||||
pub fn unmap(mesh: &Mesh, deformed: &[[f64; 2]], p: [f64; 2]) -> [f64; 2] {
|
||||
for t in &mesh.tris {
|
||||
let (a, b, c) = (deformed[t[0]], deformed[t[1]], deformed[t[2]]);
|
||||
if let Some(l) = bary(a, b, c, p)
|
||||
&& l.iter().all(|x| *x >= -1e-9)
|
||||
{
|
||||
let v = &mesh.verts;
|
||||
return [l[0] * v[t[0]][0] + l[1] * v[t[1]][0] + l[2] * v[t[2]][0], l[0] * v[t[0]][1] + l[1] * v[t[1]][1] + l[2] * v[t[2]][1]];
|
||||
}
|
||||
}
|
||||
match nearest(deformed, p) {
|
||||
Some(i) => [p[0] - deformed[i][0] + mesh.verts[i][0], p[1] - deformed[i][1] + mesh.verts[i][1]],
|
||||
None => p,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bary(a: [f64; 2], b: [f64; 2], c: [f64; 2], p: [f64; 2]) -> Option<[f64; 3]> {
|
||||
let d = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
|
||||
if d.abs() < 1e-12 {
|
||||
return None;
|
||||
}
|
||||
let l0 = ((b[1] - c[1]) * (p[0] - c[0]) + (c[0] - b[0]) * (p[1] - c[1])) / d;
|
||||
let l1 = ((c[1] - a[1]) * (p[0] - c[0]) + (a[0] - c[0]) * (p[1] - c[1])) / d;
|
||||
Some([l0, l1, 1.0 - l0 - l1])
|
||||
}
|
||||
|
||||
fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
let meshes = parse(ctx.params);
|
||||
if meshes.is_empty() {
|
||||
return buf;
|
||||
}
|
||||
let refine = (ctx.params.get("refinement").map(Value::as_f64).unwrap_or(20.0) / 10.0).round().clamp(0.0, 10.0) as usize;
|
||||
// Triangles of every mesh in pixel space: (rest px, deformed px, depth).
|
||||
let mut tris: Vec<([[f64; 2]; 3], [[f64; 2]; 3], f64)> = vec![];
|
||||
let px = |q: [f64; 2]| [q[0] * buf.scale + buf.offset[0], q[1] * buf.scale + buf.offset[1]];
|
||||
for m in &meshes {
|
||||
let mesh = mesh_for(&buf, m);
|
||||
if mesh.tris.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let def = solve(&mesh, &m.pins, refine);
|
||||
let dep = depths(&mesh, &m.pins);
|
||||
for (k, t) in mesh.tris.iter().enumerate() {
|
||||
let r = [px(mesh.verts[t[0]]), px(mesh.verts[t[1]]), px(mesh.verts[t[2]])];
|
||||
let d = [px(def[t[0]]), px(def[t[1]]), px(def[t[2]])];
|
||||
tris.push((r, d, dep[k]));
|
||||
}
|
||||
}
|
||||
if tris.is_empty() {
|
||||
return buf;
|
||||
}
|
||||
// Stable sort: back to front.
|
||||
tris.sort_by(|a, b| a.2.total_cmp(&b.2));
|
||||
rasterize(&buf, &tris)
|
||||
}
|
||||
|
||||
/// Texture-map `buf` through triangles (rest px → deformed px), back to front.
|
||||
fn rasterize(buf: &Buf, tris: &[([[f64; 2]; 3], [[f64; 2]; 3], f64)]) -> Buf {
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for (_, d, _) in tris {
|
||||
for p in d {
|
||||
x0 = x0.min(p[0]);
|
||||
y0 = y0.min(p[1]);
|
||||
x1 = x1.max(p[0]);
|
||||
y1 = y1.max(p[1]);
|
||||
}
|
||||
}
|
||||
let ox = x0.floor() as i64 - 1;
|
||||
let oy = y0.floor() as i64 - 1;
|
||||
let w = ((x1.ceil() as i64 + 1 - ox).max(1) as u32).min(16384);
|
||||
let h = ((y1.ceil() as i64 + 1 - oy).max(1) as u32).min(16384);
|
||||
let mut out = Image::new(w, h);
|
||||
// Triangle y-ranges for row bucketing.
|
||||
let ranges: Vec<(f64, f64)> = tris.iter().map(|(_, d, _)| (d[0][1].min(d[1][1]).min(d[2][1]), d[0][1].max(d[1][1]).max(d[2][1]))).collect();
|
||||
const SUB: [[f64; 2]; 4] = [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]];
|
||||
out.rows_mut().for_each(|(row, line)| {
|
||||
let y = (oy + row as i64) as f64;
|
||||
let n = line.len();
|
||||
let mut cover = vec![0u8; n];
|
||||
let mut center: Vec<Option<usize>> = vec![None; n];
|
||||
let mut any: Vec<Option<usize>> = vec![None; n];
|
||||
for (k, (_, d, _)) in tris.iter().enumerate() {
|
||||
let (ya, yb) = ranges[k];
|
||||
if yb < y || ya > y + 1.0 {
|
||||
continue;
|
||||
}
|
||||
let xa = (d[0][0].min(d[1][0]).min(d[2][0]).floor() as i64 - ox).max(0) as usize;
|
||||
let xb = ((d[0][0].max(d[1][0]).max(d[2][0]).ceil() as i64 - ox + 1).max(0) as usize).min(n);
|
||||
for (i, ((cv, ce), an)) in cover.iter_mut().zip(center.iter_mut()).zip(any.iter_mut()).enumerate().take(xb).skip(xa) {
|
||||
let x = (ox + i as i64) as f64;
|
||||
for (s, o) in SUB.iter().enumerate() {
|
||||
if let Some(l) = bary(d[0], d[1], d[2], [x + o[0], y + o[1]])
|
||||
&& l.iter().all(|v| *v >= -1e-9)
|
||||
{
|
||||
*cv |= 1 << s;
|
||||
*an = Some(k);
|
||||
}
|
||||
}
|
||||
if let Some(l) = bary(d[0], d[1], d[2], [x + 0.5, y + 0.5])
|
||||
&& l.iter().all(|v| *v >= -1e-9)
|
||||
{
|
||||
*ce = Some(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, px) in line.iter_mut().enumerate() {
|
||||
let c = cover[i].count_ones();
|
||||
let Some(k) = center[i].or(any[i]) else { continue };
|
||||
if c == 0 && center[i].is_none() {
|
||||
continue;
|
||||
}
|
||||
let (r, d, _) = &tris[k];
|
||||
let p = [(ox + i as i64) as f64 + 0.5, y + 0.5];
|
||||
let Some(l) = bary(d[0], d[1], d[2], p) else { continue };
|
||||
let src = [l[0] * r[0][0] + l[1] * r[1][0] + l[2] * r[2][0], l[0] * r[0][1] + l[1] * r[1][1] + l[2] * r[2][1]];
|
||||
let s = buf.img.sample_bilinear(src[0], src[1]);
|
||||
let cov = if center[i].is_some() && c == 4 { 1.0 } else { c.max(1) as f32 / 4.0 };
|
||||
*px = [s[0] * cov, s[1] * cov, s[2] * cov, s[3] * cov];
|
||||
}
|
||||
});
|
||||
Buf { img: out, offset: [buf.offset[0] - ox as f64, buf.offset[1] - oy as f64], scale: buf.scale }
|
||||
}
|
||||
|
||||
/// Count of nodes in a group tree (for tests and readouts).
|
||||
pub fn pin_count(fx: &PropGroup) -> usize {
|
||||
meshes(fx).map(|m| pins(m).count()).sum()
|
||||
}
|
||||
|
||||
/// The deformed mesh for overlays: mesh, deformed vertices (layer space) per mesh group uid.
|
||||
pub fn overlay(buf: &Buf, params: &Params) -> Vec<(u64, Arc<Mesh>, Vec<[f64; 2]>, Vec<Pin>)> {
|
||||
let refine = (params.get("refinement").map(Value::as_f64).unwrap_or(20.0) / 10.0).round().clamp(0.0, 10.0) as usize;
|
||||
parse(params)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
let mesh = mesh_for(buf, &m);
|
||||
let def = solve(&mesh, &m.pins, refine);
|
||||
(m.uid, mesh, def, m.pins)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,308 @@
|
||||
use super::mesh::*;
|
||||
use super::*;
|
||||
use crate::{EffectEnv, flatten_params, instantiate};
|
||||
|
||||
fn disc_alpha(w: usize, h: usize, c: [f64; 2], r: f64) -> Vec<f32> {
|
||||
let mut a = vec![0.0; w * h];
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let d = ((x as f64 + 0.5 - c[0]).powi(2) + (y as f64 + 0.5 - c[1]).powi(2)).sqrt();
|
||||
a[y * w + x] = if d <= r { 1.0 } else { 0.0 };
|
||||
}
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn check_valid(m: &Mesh) {
|
||||
assert!(!m.tris.is_empty());
|
||||
for t in &m.tris {
|
||||
let a = cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]);
|
||||
assert!(a > 0.0, "flipped or degenerate triangle {t:?} area {a}");
|
||||
}
|
||||
let tri_area: f64 = m.tris.iter().map(|t| cross(m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]) * 0.5).sum();
|
||||
let poly_area = signed_area(&m.outline).abs();
|
||||
assert!((tri_area - poly_area).abs() < 1e-6 * poly_area.max(1.0), "triangles {tri_area} vs outline {poly_area}");
|
||||
}
|
||||
|
||||
fn covered(m: &Mesh, p: [f64; 2]) -> bool {
|
||||
m.tris.iter().any(|t| {
|
||||
let (a, b, c) = (m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]);
|
||||
cross(a, b, p) >= -1e-9 && cross(b, c, p) >= -1e-9 && cross(c, a, p) >= -1e-9
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distance_transform_matches_brute_force() {
|
||||
let (w, h) = (13, 9);
|
||||
let src: Vec<bool> = (0..w * h).map(|i| i % 17 == 3 || i == 50).collect();
|
||||
let d = distance_sq(w, h, &src);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut best = f64::MAX;
|
||||
for yy in 0..h {
|
||||
for xx in 0..w {
|
||||
if src[yy * w + xx] {
|
||||
best = best.min(((x as f64 - xx as f64).powi(2)) + (y as f64 - yy as f64).powi(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(d[y * w + x], best, "({x},{y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangulation_is_valid_and_covers_the_alpha() {
|
||||
let (w, h) = (120, 100);
|
||||
let alpha = disc_alpha(w, h, [60.0, 50.0], 38.0);
|
||||
let outline = outline(&alpha, w, h, 1.0, [0.0; 2], [60.0, 50.0], 3.0);
|
||||
let m = triangulate(&outline, &MeshOpts::default());
|
||||
check_valid(&m);
|
||||
assert!(m.tris.len() > 150 && m.tris.len() < 800, "{} triangles", m.tris.len());
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
if alpha[y * w + x] > 0.0 {
|
||||
assert!(covered(&m, [x as f64 + 0.5, y as f64 + 0.5]), "alpha pixel ({x},{y}) not covered");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Density controls the triangle count.
|
||||
let fine = triangulate(&outline, &MeshOpts { density: 100.0, ..MeshOpts::default() });
|
||||
check_valid(&fine);
|
||||
assert!(fine.tris.len() > m.tris.len() * 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concave_outline_keeps_its_edges() {
|
||||
// A U shape (concave) and an L shape.
|
||||
let (w, h) = (100, 100);
|
||||
let mut alpha = vec![0.0f32; w * h];
|
||||
for y in 10..90 {
|
||||
for x in 10..90 {
|
||||
let notch = (35..65).contains(&x) && y < 70;
|
||||
alpha[y * w + x] = if notch { 0.0 } else { 1.0 };
|
||||
}
|
||||
}
|
||||
let o = outline(&alpha, w, h, 1.0, [0.0; 2], [20.0, 50.0], 0.0);
|
||||
let m = triangulate(&o, &MeshOpts { triangles: 120.0, ..Default::default() });
|
||||
check_valid(&m);
|
||||
// Nothing in the notch.
|
||||
assert!(!covered(&m, [50.0, 30.0]));
|
||||
for (x, y) in [(15.0, 15.0), (85.0, 15.0), (50.0, 80.0), (12.0, 88.0)] {
|
||||
assert!(covered(&m, [x, y]), "({x},{y})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expansion_grows_the_outline() {
|
||||
let (w, h) = (80, 80);
|
||||
let alpha = disc_alpha(w, h, [40.0, 40.0], 20.0);
|
||||
let a0 = signed_area(&outline(&alpha, w, h, 1.0, [0.0; 2], [40.0, 40.0], 0.0)).abs();
|
||||
let a5 = signed_area(&outline(&alpha, w, h, 1.0, [0.0; 2], [40.0, 40.0], 5.0)).abs();
|
||||
let am = signed_area(&outline(&alpha, w, h, 1.0, [0.0; 2], [40.0, 40.0], -5.0)).abs();
|
||||
let pi = std::f64::consts::PI;
|
||||
assert!((a0 - pi * 400.0).abs() < 60.0, "{a0}");
|
||||
assert!((a5 - pi * 625.0).abs() < 90.0, "{a5}");
|
||||
assert!((am - pi * 225.0).abs() < 60.0, "{am}");
|
||||
}
|
||||
|
||||
fn rect_mesh(w: f64, h: f64, tris: f64) -> Mesh {
|
||||
triangulate(&[[0.0, 0.0], [w, 0.0], [w, h], [0.0, h]], &MeshOpts { triangles: tris, density: 50.0, expansion: 0.0 })
|
||||
}
|
||||
|
||||
fn pin(kind: PinKind, rest: [f64; 2], pos: [f64; 2]) -> Pin {
|
||||
Pin { kind, uid: 0, rest, position: pos, scale: 1.0, rotation: 0.0, amount: 50.0, extent: 15.0, in_front: 50.0 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arap_identity_with_pins_at_rest() {
|
||||
let m = rect_mesh(100.0, 60.0, 200.0);
|
||||
check_valid(&m);
|
||||
let pins = [pin(PinKind::Position, [0.0, 0.0], [0.0, 0.0]), pin(PinKind::Position, [100.0, 60.0], [100.0, 60.0])];
|
||||
let d = solve(&m, &pins, 2);
|
||||
for (a, b) in d.iter().zip(&m.verts) {
|
||||
assert!((a[0] - b[0]).abs() < 1e-7 && (a[1] - b[1]).abs() < 1e-7, "{a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arap_single_pin_translates_rigidly() {
|
||||
let m = rect_mesh(100.0, 60.0, 200.0);
|
||||
let d = solve(&m, &[pin(PinKind::Position, [50.0, 30.0], [70.0, 15.0])], 2);
|
||||
let v = m.verts[nearest(&m.verts, [50.0, 30.0]).unwrap()];
|
||||
let t = [70.0 - 50.0 + (v[0] - 50.0) * 0.0, 15.0 - 30.0];
|
||||
for (a, b) in d.iter().zip(&m.verts) {
|
||||
assert!((a[0] - b[0] - t[0]).abs() < 1e-7 && (a[1] - b[1] - t[1]).abs() < 1e-7, "{a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arap_two_pins_rotate_rigidly() {
|
||||
let m = rect_mesh(100.0, 40.0, 200.0);
|
||||
let (a, b) = (m.verts[nearest(&m.verts, [0.0, 20.0]).unwrap()], m.verts[nearest(&m.verts, [100.0, 20.0]).unwrap()]);
|
||||
let c = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
|
||||
let ang = 30f64.to_radians();
|
||||
let rot = |p: [f64; 2]| {
|
||||
let (s, co) = ang.sin_cos();
|
||||
let d = [p[0] - c[0], p[1] - c[1]];
|
||||
[c[0] + d[0] * co - d[1] * s, c[1] + d[0] * s + d[1] * co]
|
||||
};
|
||||
let pins = [pin(PinKind::Position, a, rot(a)), pin(PinKind::Position, b, rot(b))];
|
||||
let d = solve(&m, &pins, 0);
|
||||
for (p, r) in d.iter().zip(&m.verts) {
|
||||
let e = rot(*r);
|
||||
assert!((p[0] - e[0]).abs() < 1e-3 && (p[1] - e[1]).abs() < 1e-3, "{p:?} vs {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn distortion(m: &Mesh, d: &[[f64; 2]], near: [f64; 2], radius: f64) -> f64 {
|
||||
let mut s = 0.0;
|
||||
for t in &m.tris {
|
||||
let c = [(m.verts[t[0]][0] + m.verts[t[1]][0] + m.verts[t[2]][0]) / 3.0, (m.verts[t[0]][1] + m.verts[t[1]][1] + m.verts[t[2]][1]) / 3.0];
|
||||
if (c[0] - near[0]).hypot(c[1] - near[1]) > radius {
|
||||
continue;
|
||||
}
|
||||
for (i, j) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
|
||||
let l0 = (m.verts[i][0] - m.verts[j][0]).hypot(m.verts[i][1] - m.verts[j][1]);
|
||||
let l1 = (d[i][0] - d[j][0]).hypot(d[i][1] - d[j][1]);
|
||||
s += (l1 / l0 - 1.0).powi(2);
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starch_reduces_distortion() {
|
||||
let m = rect_mesh(200.0, 40.0, 300.0);
|
||||
// Squash the bar: both ends pushed inwards and one end lifted.
|
||||
let base = vec![pin(PinKind::Position, [0.0, 20.0], [30.0, 20.0]), pin(PinKind::Position, [200.0, 20.0], [160.0, 60.0])];
|
||||
let plain = solve(&m, &base, 2);
|
||||
let mut st = base.clone();
|
||||
st.push(Pin { amount: 100.0, extent: 30.0, ..pin(PinKind::Starch, [100.0, 20.0], [100.0, 20.0]) });
|
||||
let starched = solve(&m, &st, 2);
|
||||
let (a, b) = (distortion(&m, &plain, [100.0, 20.0], 25.0), distortion(&m, &starched, [100.0, 20.0], 25.0));
|
||||
assert!(b < a * 0.5, "starch {b} vs plain {a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bend_pin_rotates_around_it() {
|
||||
let m = rect_mesh(100.0, 40.0, 200.0);
|
||||
let mut bend = pin(PinKind::Bend, [100.0, 20.0], [100.0, 20.0]);
|
||||
bend.rotation = 45.0;
|
||||
let d = solve(&m, &[pin(PinKind::Position, [0.0, 20.0], [0.0, 20.0]), bend], 2);
|
||||
// The far end turned downwards (positive rotation in y-down layer space).
|
||||
let v = nearest(&m.verts, [100.0, 40.0]).unwrap();
|
||||
let u = nearest(&m.verts, [100.0, 0.0]).unwrap();
|
||||
assert!(d[v][0] < d[u][0] - 5.0, "bottom {:?} top {:?}", d[v], d[u]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlap_pins_set_depth() {
|
||||
let m = rect_mesh(100.0, 40.0, 100.0);
|
||||
let mut o = pin(PinKind::Overlap, [20.0, 20.0], [20.0, 20.0]);
|
||||
o.in_front = 80.0;
|
||||
o.extent = 15.0;
|
||||
let d = depths(&m, &[o]);
|
||||
assert!(d.contains(&80.0));
|
||||
assert!(d.contains(&0.0));
|
||||
}
|
||||
|
||||
fn puppet_fx(pins: &[(PinKind, [f64; 2], [f64; 2])]) -> PropGroup {
|
||||
let mut next = 5000;
|
||||
let mut ids = Ids(&mut next);
|
||||
let mut fx = instantiate(crate::find(ID).unwrap(), &mut ids, "Puppet", [64.0, 64.0]);
|
||||
let mut mesh = mesh_group(&mut ids, "Mesh 1", pins.first().map(|p| p.1).unwrap_or([32.0; 2]), &MeshOpts::default());
|
||||
for (k, (kind, rest, pos)) in pins.iter().enumerate() {
|
||||
let mut g = pin_group(&mut ids, &format!("Puppet Pin {}", k + 1), *kind, *rest);
|
||||
if let Some(p) = g.get_mut("position") {
|
||||
p.value = Value::Vec2(*pos);
|
||||
}
|
||||
mesh.sub_mut("deform").unwrap().children.push(g.into());
|
||||
}
|
||||
fx.children.push(mesh.into());
|
||||
fx
|
||||
}
|
||||
|
||||
fn run(fx: &PropGroup, img: Image) -> Buf {
|
||||
let params = flatten_params(fx, &mut |p| p.value.clone());
|
||||
let ctx =
|
||||
EffectCtx { params: ¶ms, time: 0.0, layer_size: [img.width as f64, img.height as f64], seed: 1, adjustment: false, env: EffectEnv::default() };
|
||||
crate::apply(crate::find(ID).unwrap(), &ctx, Buf { img, offset: [0.0; 2], scale: 1.0 })
|
||||
}
|
||||
|
||||
fn test_image() -> Image {
|
||||
let mut img = Image::new(64, 64);
|
||||
for y in 0..64u32 {
|
||||
for x in 0..64u32 {
|
||||
if (12..52).contains(&x) && (16..48).contains(&y) {
|
||||
img.set(x, y, [x as f32 / 64.0, y as f32 / 64.0, ((x + y) % 3) as f32 / 3.0, 1.0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
img
|
||||
}
|
||||
|
||||
/// Output pixel at layer pixel (x, y).
|
||||
fn at(b: &Buf, x: i64, y: i64) -> [f32; 4] {
|
||||
b.img.get(x + b.offset[0] as i64, y + b.offset[1] as i64)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_identity_and_translation() {
|
||||
let img = test_image();
|
||||
let id = run(&puppet_fx(&[(PinKind::Position, [30.0, 30.0], [30.0, 30.0])]), img.clone());
|
||||
for y in 17..47 {
|
||||
for x in 13..51 {
|
||||
let (o, e) = (at(&id, x, y), img.get(x, y));
|
||||
assert!((0..4).all(|c| (o[c] - e[c]).abs() < 1e-5), "({x},{y}) {o:?} vs {e:?}");
|
||||
}
|
||||
}
|
||||
let moved = run(&puppet_fx(&[(PinKind::Position, [30.0, 30.0], [40.0, 35.0])]), img.clone());
|
||||
for y in 17..47 {
|
||||
for x in 13..51 {
|
||||
let o = at(&moved, x + 10, y + 5);
|
||||
let e = img.get(x, y);
|
||||
for c in 0..4 {
|
||||
assert!((o[c] - e[c]).abs() < 1e-4, "({x},{y}) {o:?} vs {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Outside the mesh: nothing.
|
||||
assert_eq!(at(&moved, 2, 2), [0.0; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn render_is_deterministic_and_antialiased() {
|
||||
let img = test_image();
|
||||
let fx = puppet_fx(&[(PinKind::Position, [14.0, 30.0], [14.0, 30.0]), (PinKind::Position, [50.0, 30.0], [45.0, 10.0])]);
|
||||
let a = run(&fx, img.clone());
|
||||
let b = run(&fx, img);
|
||||
assert_eq!(a.img, b.img);
|
||||
assert_eq!(a.offset, b.offset);
|
||||
assert!(a.img.data.iter().any(|p| p[3] > 0.05 && p[3] < 0.95), "expected soft edges");
|
||||
assert!(a.img.data.iter().all(|p| p[3] <= 1.0001 && p.iter().all(|c| c.is_finite())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmap_inverts_the_deformation() {
|
||||
let m = rect_mesh(100.0, 40.0, 150.0);
|
||||
let pins = [pin(PinKind::Position, [0.0, 20.0], [10.0, 30.0]), pin(PinKind::Position, [100.0, 20.0], [90.0, 0.0])];
|
||||
let d = solve(&m, &pins, 1);
|
||||
let q = unmap(&m, &d, d[5]);
|
||||
assert!((q[0] - m.verts[5][0]).abs() < 1e-6 && (q[1] - m.verts[5][1]).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_round_trip_serde() {
|
||||
let fx = puppet_fx(&[(PinKind::Position, [1.0, 2.0], [3.0, 4.0]), (PinKind::Starch, [5.0, 5.0], [5.0, 5.0])]);
|
||||
let j = serde_json::to_string(&fx).unwrap();
|
||||
let back: PropGroup = serde_json::from_str(&j).unwrap();
|
||||
assert_eq!(back, fx);
|
||||
assert_eq!(pin_count(&back), 2);
|
||||
let params = flatten_params(&back, &mut |p| p.value.clone());
|
||||
let m = parse(¶ms);
|
||||
assert_eq!(m.len(), 1);
|
||||
assert_eq!(m[0].pins.len(), 2);
|
||||
assert_eq!(m[0].pins[1].kind, PinKind::Starch);
|
||||
assert_eq!(m[0].pins[0].position, [3.0, 4.0]);
|
||||
}
|
||||
Reference in New Issue
Block a user