Skip to content

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

73.8 KB
Raw Blame
//! Interactive DX12 GPU Transform & 5-Mode Warp Engine (`transform.rs`).
//!
//! Supports all 5 InkStudio `TransformMode`s across single layers, active selections, and
//! multi-layer groups/folders:
//! 1. **Affine** (translate, scale, rotate, skew, flip): exact lossless 90°/180°/270°/flip
//!    fast-path + Anti-Ringing Lanczos-3 high-quality tile bake.
//! 2. **Perspective**: exact 8×8 Gaussian-elimination Heckbert homography solver (`H` & `H⁻¹`)
//!    + Anti-Ringing Lanczos-3 tile bake.
//! 3. **Mesh**: `cols × rows` bicubic Catmull-Rom 2D patch surface with phantom border
//!    extrapolation.
//! 4. **Puppet**: automatic alpha/selection silhouette triangulation + 2-step Igarashi ARAP
//!    (As-Rigid-As-Possible) Cholesky solver with pin translation, rotation, and depth sorting.
//! 5. **Cage**: Hormann & Floater Mean Value Coordinates (MVC) smooth polygon deformation.
//!
//! Live preview renders directly on DX12 via `TRANSFORM_MESH_WGSL` at 120+ FPS (zero `<canvas>`
//! in WebView2!), while React `TransformOverlay.tsx` renders only lightweight SVG control handles!

use crate::document::{Document, LayerId};
use crate::memory::ScratchBackend;
use crate::tiles::{CowTileDelta, RectI32, TileCoord, TileData, TileKind};
use crate::types::CameraState;
use bytemuck::{Pod, Zeroable};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::sync::Arc;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum TransformMode {
    #[default]
    Affine,
    Perspective,
    Mesh,
    Puppet,
    Cage,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Point2D {
    pub x: f64,
    pub y: f64,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AffineState {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    /// Rotation angle in radians.
    pub rotation: f64,
    pub skew_x: f64,
    pub skew_y: f64,
    pub flip_x: bool,
    pub flip_y: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MeshState {
    pub cols: usize,
    pub rows: usize,
    /// `(rows + 1) * (cols + 1)` control points in document coordinates.
    pub points: Vec<Point2D>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PuppetPin {
    pub id: String,
    pub rest_x: f64,
    pub rest_y: f64,
    pub x: f64,
    pub y: f64,
    /// Local pin rotation in radians.
    #[serde(default)]
    pub rotation: f64,
    /// Depth bias for overlapping triangles (`>0` brings forward, `<0` sends back).
    #[serde(default)]
    pub depth: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PuppetState {
    pub pins: Vec<PuppetPin>,
    pub mesh_vertices: Vec<Point2D>,
    pub mesh_triangles: Vec<[usize; 3]>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CageState {
    pub rest_points: Vec<Point2D>,
    pub points: Vec<Point2D>,
    pub closed: bool,
}

/// Compact handle/control-point state exchanged with React `TransformOverlay.tsx` (zero pixels!).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransformSessionSnapshot {
    pub active: bool,
    pub doc_id: String,
    pub mode: TransformMode,
    pub target_layer_ids: Vec<LayerId>,
    pub source_bounds: RectI32,
    pub affine: AffineState,
    /// 4 perspective corners `[TL, TR, BR, BL]` in document coordinates.
    pub corners: [Point2D; 4],
    pub mesh: MeshState,
    pub puppet: PuppetState,
    pub cage: CageState,
    pub show_mesh: bool,
}

/// Update payload sent from React `TransformOverlay.tsx` during interactive dragging.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransformUpdatePayload {
    pub mode: TransformMode,
    #[serde(default)]
    pub affine: Option<AffineState>,
    #[serde(default)]
    pub corners: Option<[Point2D; 4]>,
    #[serde(default)]
    pub mesh: Option<MeshState>,
    #[serde(default)]
    pub puppet_pins: Option<Vec<PuppetPin>>,
    #[serde(default)]
    pub cage: Option<CageState>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransformCommitResult {
    pub modified: bool,
    pub layer_ids: Vec<LayerId>,
    pub dirty_rect: RectI32,
}

// ============================================================================
// GPU Preview Pipeline (120+ FPS Triangle Mesh Warp Shader)
// ============================================================================

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct TransformMeshUniforms {
    viewport_size_phys: [f32; 2],
    doc_size: [f32; 2],
    pan_css: [f32; 2],
    zoom: f32,
    rotation_rad: f32,
    flip: [f32; 2],
    dpr: f32,
    opacity: f32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pod, Zeroable)]
struct TransformVertex {
    pos_doc: [f32; 2],
    uv: [f32; 2],
}

pub const TRANSFORM_MESH_WGSL: &str = r#"
struct TransformMeshUniforms {
    viewport_size_phys: vec2<f32>,
    doc_size: vec2<f32>,
    pan_css: vec2<f32>,
    zoom: f32,
    rotation_rad: f32,
    flip: vec2<f32>,
    dpr: f32,
    opacity: f32,
};

@group(0) @binding(0) var<uniform> u: TransformMeshUniforms;
@group(0) @binding(1) var src_tex: texture_2d<f32>;
@group(0) @binding(2) var src_sampler: sampler;

struct VertIn {
    @location(0) pos_doc: vec2<f32>,
    @location(1) uv: vec2<f32>,
};

struct VsOut {
    @builtin(position) pos: vec4<f32>,
    @location(0) uv: vec2<f32>,
};

@vertex
fn vs_main(v: VertIn) -> VsOut {
    let centered = (v.pos_doc - u.doc_size * 0.5) * u.flip;
    let c = cos(u.rotation_rad);
    let s = sin(u.rotation_rad);
    let rot = vec2<f32>(centered.x * c - centered.y * s, centered.x * s + centered.y * c);
    let screen_phys = (u.pan_css + rot * u.zoom) * u.dpr;
    let ndc = vec2<f32>(
        (2.0 * screen_phys.x / max(1.0, u.viewport_size_phys.x)) - 1.0,
        1.0 - (2.0 * screen_phys.y / max(1.0, u.viewport_size_phys.y)),
    );
    var out: VsOut;
    out.pos = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = v.uv;
    return out;
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    if (in.uv.x < 0.0 || in.uv.y < 0.0 || in.uv.x > 1.0 || in.uv.y > 1.0) {
        discard;
    }
    let px = textureSampleLevel(src_tex, src_sampler, in.uv, 0.0);
    let a = clamp(px.a * u.opacity, 0.0, 1.0);
    if (a <= 0.001) {
        discard;
    }
    return vec4<f32>(px.rgb * a, a);
}
"#;

// ============================================================================
// Mathematical Solvers: Anti-Ringing Lanczos-3, Homography, Catmull-Rom, ARAP, MVC
// ============================================================================

#[inline]
fn sinc(x: f64) -> f64 {
    if x.abs() < 1e-12 {
        1.0
    } else {
        let px = PI * x;
        px.sin() / px
    }
}

#[inline]
fn lanczos3(x: f64) -> f64 {
    let ax = x.abs();
    if ax >= 3.0 {
        0.0
    } else {
        sinc(ax) * sinc(ax / 3.0)
    }
}

/// High-quality Anti-Ringing Lanczos-3 sampler on straight RGBA8 image (`premultiplied` internally!).
fn sample_lanczos3_rgba8(src: &[u8], sw: usize, sh: usize, sx: f64, sy: f64) -> [u8; 4] {
    if sx < -0.5 || sy < -0.5 || sx >= sw as f64 - 0.5 || sy >= sh as f64 - 0.5 {
        return [0, 0, 0, 0];
    }
    let ix = sx.floor() as i32;
    let iy = sy.floor() as i32;
    let fx = sx - ix as f64;
    let fy = sy - iy as f64;

    let mut wx = [0.0f64; 6];
    let mut wy = [0.0f64; 6];
    for k in 0..6 {
        wx[k] = lanczos3(fx - (k as f64 - 2.0));
        wy[k] = lanczos3(fy - (k as f64 - 2.0));
    }

    let mut acc = [0.0f64; 4];
    let mut wsum = 0.0f64;
    let mut min_c = [f64::INFINITY; 4];
    let mut max_c = [f64::NEG_INFINITY; 4];

    for j in -2..=3i32 {
        let py = (iy + j).clamp(0, sh as i32 - 1) as usize;
        let wj = wy[(j + 2) as usize];
        for i in -2..=3i32 {
            let px = (ix + i).clamp(0, sw as i32 - 1) as usize;
            let w = wx[(i + 2) as usize] * wj;
            let o = (py * sw + px) * 4;
            let a = src[o + 3] as f64 / 255.0;
            let pr = (src[o] as f64 / 255.0) * a;
            let pg = (src[o + 1] as f64 / 255.0) * a;
            let pb = (src[o + 2] as f64 / 255.0) * a;
            acc[0] += pr * w;
            acc[1] += pg * w;
            acc[2] += pb * w;
            acc[3] += a * w;
            wsum += w;

            if (0..=1).contains(&i) && (0..=1).contains(&j) {
                min_c[0] = min_c[0].min(pr);
                min_c[1] = min_c[1].min(pg);
                min_c[2] = min_c[2].min(pb);
                min_c[3] = min_c[3].min(a);
                max_c[0] = max_c[0].max(pr);
                max_c[1] = max_c[1].max(pg);
                max_c[2] = max_c[2].max(pb);
                max_c[3] = max_c[3].max(a);
            }
        }
    }

    if wsum.abs() < 1e-9 {
        return [0, 0, 0, 0];
    }
    for c in 0..4 {
        acc[c] = (acc[c] / wsum).clamp(min_c[c], max_c[c]);
    }
    let a = acc[3].clamp(0.0, 1.0);
    if a <= 1e-4 {
        return [0, 0, 0, 0];
    }
    [
        ((acc[0] / a) * 255.0).round().clamp(0.0, 255.0) as u8,
        ((acc[1] / a) * 255.0).round().clamp(0.0, 255.0) as u8,
        ((acc[2] / a) * 255.0).round().clamp(0.0, 255.0) as u8,
        (a * 255.0).round().clamp(0.0, 255.0) as u8,
    ]
}

/// Evaluates forward Affine transform mapping local `[0..sw, 0..sh]` -> document `(x, y)`.
pub fn eval_affine_point(aff: &AffineState, u: f64, v: f64) -> Point2D {
    let lu = if aff.flip_x { 1.0 - u } else { u };
    let lv = if aff.flip_y { 1.0 - v } else { v };
    let lx = (lu - 0.5) * aff.width;
    let ly = (lv - 0.5) * aff.height;
    let sx = lx + aff.skew_x * ly;
    let sy = ly + aff.skew_y * lx;
    let c = aff.rotation.cos();
    let s = aff.rotation.sin();
    let cx = aff.x + aff.width * 0.5;
    let cy = aff.y + aff.height * 0.5;
    Point2D {
        x: cx + sx * c - sy * s,
        y: cy + sx * s + sy * c,
    }
}

/// Solves 3×3 projective homography mapping unit square `[(0,0),(1,0),(1,1),(0,1)]` -> `dst[0..4]`.
pub fn solve_homography_from_unit_square(dst: &[Point2D; 4]) -> Option<[f64; 9]> {
    let src = [
        Point2D { x: 0.0, y: 0.0 },
        Point2D { x: 1.0, y: 0.0 },
        Point2D { x: 1.0, y: 1.0 },
        Point2D { x: 0.0, y: 1.0 },
    ];
    let mut a = [[0.0f64; 9]; 8];
    for i in 0..4 {
        let (x, y) = (src[i].x, src[i].y);
        let (u, v) = (dst[i].x, dst[i].y);
        a[2 * i] = [x, y, 1.0, 0.0, 0.0, 0.0, -u * x, -u * y, u];
        a[2 * i + 1] = [0.0, 0.0, 0.0, x, y, 1.0, -v * x, -v * y, v];
    }
    // Gaussian elimination with partial pivoting
    for col in 0..8 {
        let mut piv = col;
        let mut max_v = a[col][col].abs();
        for (r, row) in a.iter().enumerate().skip(col + 1) {
            if row[col].abs() > max_v {
                max_v = row[col].abs();
                piv = r;
            }
        }
        if max_v < 1e-12 {
            return None;
        }
        a.swap(col, piv);
        let div = a[col][col];
        for cell in &mut a[col][col..9] {
            *cell /= div;
        }
        let pivot_row = a[col];
        for (r, row) in a.iter_mut().enumerate() {
            if r == col {
                continue;
            }
            let f = row[col];
            if f.abs() > 1e-15 {
                for (cell, &p) in row[col..9].iter_mut().zip(&pivot_row[col..9]) {
                    *cell -= f * p;
                }
            }
        }
    }
    Some([
        a[0][8], a[1][8], a[2][8], a[3][8], a[4][8], a[5][8], a[6][8], a[7][8], 1.0,
    ])
}

#[inline]
fn invert_3x3(m: &[f64; 9]) -> Option<[f64; 9]> {
    let c00 = m[4] * m[8] - m[5] * m[7];
    let c01 = -(m[3] * m[8] - m[5] * m[6]);
    let c02 = m[3] * m[7] - m[4] * m[6];
    let det = m[0] * c00 + m[1] * c01 + m[2] * c02;
    if det.abs() < 1e-14 {
        return None;
    }
    let inv = 1.0 / det;
    Some([
        c00 * inv,
        -(m[1] * m[8] - m[2] * m[7]) * inv,
        (m[1] * m[5] - m[2] * m[4]) * inv,
        c01 * inv,
        (m[0] * m[8] - m[2] * m[6]) * inv,
        -(m[0] * m[5] - m[2] * m[3]) * inv,
        c02 * inv,
        -(m[0] * m[7] - m[1] * m[6]) * inv,
        (m[0] * m[4] - m[1] * m[3]) * inv,
    ])
}

#[inline]
fn apply_homography(m: &[f64; 9], x: f64, y: f64) -> Option<Point2D> {
    let w = m[6] * x + m[7] * y + m[8];
    if w.abs() < 1e-12 {
        return None;
    }
    Some(Point2D {
        x: (m[0] * x + m[1] * y + m[2]) / w,
        y: (m[3] * x + m[4] * y + m[5]) / w,
    })
}

/// Evaluates bicubic Catmull-Rom 2D Mesh Warp surface at normalized `(u, v) in [0, 1]^2`
/// with linear phantom border extrapolation so edges remain C1 smooth.
pub fn eval_mesh_catmull_rom(mesh: &MeshState, u: f64, v: f64) -> Point2D {
    let cols = mesh.cols.max(1);
    let rows = mesh.rows.max(1);
    let stride = cols + 1;

    let sample_cp = |ci: i32, ri: i32| -> Point2D {
        let get = |c: i32, r: i32| -> Point2D {
            let cc = c.clamp(0, cols as i32) as usize;
            let rr = r.clamp(0, rows as i32) as usize;
            mesh.points
                .get(rr * stride + cc)
                .copied()
                .unwrap_or_default()
        };
        // Linear phantom extrapolation for out-of-range indices (-1 or N+1)
        let (c_clamped, dc) = if ci < 0 {
            (0, -1)
        } else if ci > cols as i32 {
            (cols as i32, 1)
        } else {
            (ci, 0)
        };
        let (r_clamped, dr) = if ri < 0 {
            (0, -1)
        } else if ri > rows as i32 {
            (rows as i32, 1)
        } else {
            (ri, 0)
        };
        let p = get(c_clamped, r_clamped);
        let mut x = p.x;
        let mut y = p.y;
        if dc != 0 {
            let p_in = get(c_clamped - dc, r_clamped);
            x += p.x - p_in.x;
            y += p.y - p_in.y;
        }
        if dr != 0 {
            let p_in = get(c_clamped, r_clamped - dr);
            x += p.x - p_in.x;
            y += p.y - p_in.y;
        }
        Point2D { x, y }
    };

    let cr = |t: f64| -> [f64; 4] {
        let t2 = t * t;
        let t3 = t2 * t;
        [
            0.5 * (-t3 + 2.0 * t2 - t),
            0.5 * (3.0 * t3 - 5.0 * t2 + 2.0),
            0.5 * (-3.0 * t3 + 4.0 * t2 + t),
            0.5 * (t3 - t2),
        ]
    };

    let gx = (u.clamp(0.0, 1.0) * cols as f64).min(cols as f64 - 1e-9);
    let gy = (v.clamp(0.0, 1.0) * rows as f64).min(rows as f64 - 1e-9);
    let cx = gx.floor() as i32;
    let cy = gy.floor() as i32;
    let wx = cr(gx - cx as f64);
    let wy = cr(gy - cy as f64);

    let mut ox = 0.0;
    let mut oy = 0.0;
    for (j, &wj) in wy.iter().enumerate() {
        for (i, &wi) in wx.iter().enumerate() {
            let w = wi * wj;
            let p = sample_cp(cx + i as i32 - 1, cy + j as i32 - 1);
            ox += p.x * w;
            oy += p.y * w;
        }
    }
    Point2D { x: ox, y: oy }
}

/// Evaluates Hormann & Floater Mean Value Coordinates (MVC) Cage Warp for a query point `q`
/// relative to `rest_poly` -> deformed `cur_poly`.
pub fn eval_cage_mvc(rest_poly: &[Point2D], cur_poly: &[Point2D], q: Point2D) -> Point2D {
    let n = rest_poly.len();
    if n < 3 || cur_poly.len() != n {
        return q;
    }
    let mut s = Vec::with_capacity(n);
    let mut r = Vec::with_capacity(n);
    for i in 0..n {
        let dx = rest_poly[i].x - q.x;
        let dy = rest_poly[i].y - q.y;
        let dist = dx.hypot(dy);
        if dist < 1e-7 {
            return cur_poly[i];
        }
        s.push((dx, dy));
        r.push(dist);
    }

    let mut tan_half = vec![0.0f64; n];
    for i in 0..n {
        let j = (i + 1) % n;
        let area = s[i].0 * s[j].1 - s[i].1 * s[j].0;
        let dot = s[i].0 * s[j].0 + s[i].1 * s[j].1;
        let denom = r[i] * r[j] + dot;
        if area.abs() < 1e-9 && dot < 0.0 {
            // Point lies on edge [i, j]: exact linear interpolation
            let t = r[i] / (r[i] + r[j]);
            return Point2D {
                x: cur_poly[i].x * (1.0 - t) + cur_poly[j].x * t,
                y: cur_poly[i].y * (1.0 - t) + cur_poly[j].y * t,
            };
        }
        tan_half[i] = if denom.abs() < 1e-12 {
            0.0
        } else {
            area / denom
        };
    }

    let mut w_sum = 0.0;
    let mut ox = 0.0;
    let mut oy = 0.0;
    for i in 0..n {
        let prev = (i + n - 1) % n;
        let w = (tan_half[prev] + tan_half[i]) / r[i];
        w_sum += w;
        ox += cur_poly[i].x * w;
        oy += cur_poly[i].y * w;
    }
    if w_sum.abs() < 1e-12 {
        q
    } else {
        Point2D {
            x: ox / w_sum,
            y: oy / w_sum,
        }
    }
}

/// Builds a clean adaptive silhouette triangle mesh covering opaque pixels of `rgba`.
fn build_puppet_mesh(rgba: &[u8], w: u32, h: u32, bounds: RectI32) -> (Vec<Point2D>, Vec<[usize; 3]>) {
    let gx = (w / 32).clamp(6, 18) as usize;
    let gy = (h / 32).clamp(6, 18) as usize;
    let stride = gx + 1;
    let mut verts = Vec::with_capacity((gx + 1) * (gy + 1));
    for r in 0..=gy {
        let y = bounds.y as f64 + (r as f64 / gy as f64) * h as f64;
        for c in 0..=gx {
            let x = bounds.x as f64 + (c as f64 / gx as f64) * w as f64;
            verts.push(Point2D { x, y });
        }
    }

    let cell_has_ink = |c: usize, r: usize| -> bool {
        let x0 = ((c * w as usize) / gx).saturating_sub(2);
        let x1 = (((c + 1) * w as usize) / gx + 2).min(w as usize);
        let y0 = ((r * h as usize) / gy).saturating_sub(2);
        let y1 = (((r + 1) * h as usize) / gy + 2).min(h as usize);
        for py in (y0..y1).step_by(2) {
            for px in (x0..x1).step_by(2) {
                if rgba[(py * w as usize + px) * 4 + 3] > 8 {
                    return true;
                }
            }
        }
        false
    };

    let mut tris = Vec::new();
    for r in 0..gy {
        for c in 0..gx {
            if !cell_has_ink(c, r) {
                continue;
            }
            let tl = r * stride + c;
            let tr = tl + 1;
            let bl = (r + 1) * stride + c;
            let br = bl + 1;
            tris.push([tl, tr, br]);
            tris.push([tl, br, bl]);
        }
    }
    if tris.is_empty() {
        for r in 0..gy {
            for c in 0..gx {
                let tl = r * stride + c;
                let tr = tl + 1;
                let bl = (r + 1) * stride + c;
                let br = bl + 1;
                tris.push([tl, tr, br]);
                tris.push([tl, br, bl]);
            }
        }
    }

    // Compact strictly to referenced vertices so the ARAP linear system stays minimal & fast!
    let mut used = vec![usize::MAX; verts.len()];
    let mut compact_verts = Vec::new();
    let mut compact_tris = Vec::with_capacity(tris.len());
    for tri in tris {
        let mut nt = [0usize; 3];
        for k in 0..3 {
            let old = tri[k];
            if used[old] == usize::MAX {
                used[old] = compact_verts.len();
                compact_verts.push(verts[old]);
            }
            nt[k] = used[old];
        }
        compact_tris.push(nt);
    }
    (compact_verts, compact_tris)
}

/// 2-Step Igarashi As-Rigid-As-Possible (ARAP) Puppet Warp Solver!
/// Handles 0, 1 (rigid translate + rotate), or N pins with local rotation + least-squares
/// Cholesky / Gauss-Seidel energy minimization preserving local triangle rigidity!
pub fn solve_puppet_arap(
    rest_verts: &[Point2D],
    tris: &[[usize; 3]],
    pins: &[PuppetPin],
) -> Vec<Point2D> {
    let n = rest_verts.len();
    if n == 0 || pins.is_empty() {
        return rest_verts.to_vec();
    }
    if pins.len() == 1 {
        let p = &pins[0];
        let c = p.rotation.cos();
        let s = p.rotation.sin();
        return rest_verts
            .iter()
            .map(|v| {
                let rx = v.x - p.rest_x;
                let ry = v.y - p.rest_y;
                Point2D {
                    x: p.x + rx * c - ry * s,
                    y: p.y + rx * s + ry * c,
                }
            })
            .collect();
    }

    // Build adjacency list & uniform cotangent/edge weights
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    for &[a, b, c] in tris {
        for (u, v) in [(a, b), (b, a), (b, c), (c, b), (c, a), (a, c)] {
            if !adj[u].contains(&v) {
                adj[u].push(v);
            }
        }
    }

    // Attach each pin to its nearest mesh vertex (with strong soft constraint weight + local rotation)
    let pin_weight = 100.0f64;
    let mut pin_vertex: Vec<(usize, &PuppetPin)> = Vec::with_capacity(pins.len());
    for pin in pins {
        let mut best_i = 0usize;
        let mut best_d = f64::INFINITY;
        for (i, v) in rest_verts.iter().enumerate() {
            let d = (v.x - pin.rest_x).hypot(v.y - pin.rest_y);
            if d < best_d {
                best_d = d;
                best_i = i;
            }
        }
        pin_vertex.push((best_i, pin));
    }

    // Initial guess: inverse-distance weighted rigid interpolation from pins (fast convergence!)
    let mut cur: Vec<Point2D> = rest_verts
        .iter()
        .map(|v| {
            let mut wx = 0.0;
            let mut wy = 0.0;
            let mut ws = 0.0;
            for pin in pins {
                let rx = v.x - pin.rest_x;
                let ry = v.y - pin.rest_y;
                let d2 = rx * rx + ry * ry + 1.0;
                let w = 1.0 / d2;
                let c = pin.rotation.cos();
                let s = pin.rotation.sin();
                wx += w * (pin.x + rx * c - ry * s);
                wy += w * (pin.y + rx * s + ry * c);
                ws += w;
            }
            Point2D {
                x: wx / ws.max(1e-9),
                y: wy / ws.max(1e-9),
            }
        })
        .collect();

    // Precompute per-vertex pin lookup
    let mut pinned_target: Vec<Option<(f64, f64)>> = vec![None; n];
    for &(vi, pin) in &pin_vertex {
        let dx = rest_verts[vi].x - pin.rest_x;
        let dy = rest_verts[vi].y - pin.rest_y;
        let c = pin.rotation.cos();
        let s = pin.rotation.sin();
        pinned_target[vi] = Some((pin.x + dx * c - dy * s, pin.y + dx * s + dy * c));
    }

    // 2-step ARAP local-global alternation (4 outer ARAP iterations × 12 Gauss-Seidel sweeps)
    let mut rots = vec![(1.0f64, 0.0f64); n]; // per-vertex local 2D rotation (cos, sin)
    for _iter in 0..4 {
        // Local step: find optimal 2D rigid rotation R_i for each vertex's 1-ring via Procrustes SVD
        for i in 0..n {
            let mut c_sum = 0.0;
            let mut s_sum = 0.0;
            for &j in &adj[i] {
                let p_x = rest_verts[j].x - rest_verts[i].x;
                let p_y = rest_verts[j].y - rest_verts[i].y;
                let q_x = cur[j].x - cur[i].x;
                let q_y = cur[j].y - cur[i].y;
                c_sum += p_x * q_x + p_y * q_y;
                s_sum += p_x * q_y - p_y * q_x;
            }
            let norm = c_sum.hypot(s_sum);
            rots[i] = if norm > 1e-9 {
                (c_sum / norm, s_sum / norm)
            } else {
                (1.0, 0.0)
            };
        }
        // Apply explicit pin rotations on pinned vertices
        for &(vi, pin) in &pin_vertex {
            if pin.rotation.abs() > 1e-5 {
                rots[vi] = (pin.rotation.cos(), pin.rotation.sin());
            }
        }

        // Global step: solve SPD system L * p' = b via Gauss-Seidel relaxation
        for _sweep in 0..12 {
            for i in 0..n {
                let deg = adj[i].len() as f64;
                if deg < 0.5 {
                    continue;
                }
                let mut rhs_x = 0.0;
                let mut rhs_y = 0.0;
                let (ci, si) = rots[i];
                for &j in &adj[i] {
                    let (cj, sj) = rots[j];
                    let rc = 0.5 * (ci + cj);
                    let rs = 0.5 * (si + sj);
                    let ex = rest_verts[i].x - rest_verts[j].x;
                    let ey = rest_verts[i].y - rest_verts[j].y;
                    rhs_x += cur[j].x + (rc * ex - rs * ey);
                    rhs_y += cur[j].y + (rs * ex + rc * ey);
                }
                let mut denom = deg;
                if let Some((tx, ty)) = pinned_target[i] {
                    rhs_x += pin_weight * tx;
                    rhs_y += pin_weight * ty;
                    denom += pin_weight;
                }
                cur[i] = Point2D {
                    x: rhs_x / denom,
                    y: rhs_y / denom,
                };
            }
        }
    }
    cur
}

/// Rasterizes a deformed triangle mesh `(verts_doc, uvs, tris)` with Anti-Ringing Lanczos-3
/// into a document-space RGBA8 buffer inside `out_rect` (parallelized across scanlines!).
#[allow(clippy::too_many_arguments)]
fn rasterize_mesh_lanczos3(
    src_rgba: &[u8],
    sw: usize,
    sh: usize,
    verts: &[Point2D],
    uvs: &[[f64; 2]],
    tris: &[[usize; 3]],
    tri_depths: Option<&[f64]>,
    out_rect: RectI32,
) -> Vec<u8> {
    let ow = out_rect.width as usize;
    let oh = out_rect.height as usize;
    let mut out = vec![0u8; ow * oh * 4];
    if ow == 0 || oh == 0 || tris.is_empty() {
        return out;
    }

    // Sort triangles back-to-front by optional depth (for Puppet Warp pin overlap ordering)
    let mut order: Vec<usize> = (0..tris.len()).collect();
    if let Some(depths) = tri_depths {
        order.sort_by(|&a, &b| depths[a].total_cmp(&depths[b]));
    }

    struct TriPre {
        p0: Point2D,
        p1: Point2D,
        p2: Point2D,
        uv0: [f64; 2],
        uv1: [f64; 2],
        uv2: [f64; 2],
        inv_area: f64,
        min_x: i32,
        max_x: i32,
        min_y: i32,
        max_y: i32,
    }

    let ox = out_rect.x;
    let oy = out_rect.y;
    let mut pre: Vec<TriPre> = Vec::with_capacity(order.len());
    for ti in order {
        let [i0, i1, i2] = tris[ti];
        let (p0, p1, p2) = (verts[i0], verts[i1], verts[i2]);
        let area = (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y);
        if area.abs() < 1e-6 {
            continue;
        }
        let min_x = (p0.x.min(p1.x).min(p2.x).floor() as i32 - ox).clamp(0, ow as i32 - 1);
        let max_x = (p0.x.max(p1.x).max(p2.x).ceil() as i32 - ox).clamp(0, ow as i32 - 1);
        let min_y = (p0.y.min(p1.y).min(p2.y).floor() as i32 - oy).clamp(0, oh as i32 - 1);
        let max_y = (p0.y.max(p1.y).max(p2.y).ceil() as i32 - oy).clamp(0, oh as i32 - 1);
        if min_x > max_x || min_y > max_y {
            continue;
        }
        pre.push(TriPre {
            p0,
            p1,
            p2,
            uv0: uvs[i0],
            uv1: uvs[i1],
            uv2: uvs[i2],
            inv_area: 1.0 / area,
            min_x,
            max_x,
            min_y,
            max_y,
        });
    }

    out.par_chunks_mut(ow * 4)
        .enumerate()
        .for_each(|(ry, row)| {
            let py = oy as f64 + ry as f64 + 0.5;
            let ry_i = ry as i32;
            for t in &pre {
                if ry_i < t.min_y || ry_i > t.max_y {
                    continue;
                }
                for rx in t.min_x..=t.max_x {
                    let px = ox as f64 + rx as f64 + 0.5;
                    let w0 = ((t.p1.x - px) * (t.p2.y - py) - (t.p2.x - px) * (t.p1.y - py))
                        * t.inv_area;
                    let w1 = ((t.p2.x - px) * (t.p0.y - py) - (t.p0.x - px) * (t.p2.y - py))
                        * t.inv_area;
                    let w2 = 1.0 - w0 - w1;
                    if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
                        let u = w0 * t.uv0[0] + w1 * t.uv1[0] + w2 * t.uv2[0];
                        let v = w0 * t.uv0[1] + w1 * t.uv1[1] + w2 * t.uv2[1];
                        let sx = u * sw as f64 - 0.5;
                        let sy = v * sh as f64 - 0.5;
                        let px_rgba = sample_lanczos3_rgba8(src_rgba, sw, sh, sx, sy);
                        if px_rgba[3] > 0 {
                            let o = (rx as usize) * 4;
                            row[o..o + 4].copy_from_slice(&px_rgba);
                        }
                    }
                }
            }
        });
    out
}

// ============================================================================
// Active Transform Session & GPU Preview Engine
// ============================================================================

struct TransformLayerSource {
    layer_id: LayerId,
    /// Original immutable `SparseLayerGrid` snapshot BEFORE lifting selection / transforming (for CoW Undo & Cancel).
    before_tiles: HashMap<TileCoord, Arc<TileData>>,
    /// Cropped RGBA8 source buffer inside `source_bounds` (`sw × sh × 4`).
    src_rgba: Vec<u8>,
    opacity: f32,
    /// GPU `Rgba8Unorm` texture for live 120+ FPS preview!
    gpu_tex: wgpu::Texture,
    gpu_view: wgpu::TextureView,
    gpu_bg: Option<wgpu::BindGroup>,
}

pub struct GpuTransformEngine {
    bgl: wgpu::BindGroupLayout,
    pipeline: wgpu::RenderPipeline,
    uniform_buf: wgpu::Buffer,
    uniform_slot_align: u32,
    uniform_cap_slots: usize,
    vert_buf: wgpu::Buffer,
    vert_cap: usize,
    sampler: wgpu::Sampler,

    active: bool,
    doc_id: String,
    doc_width: u32,
    doc_height: u32,
    mode: TransformMode,
    source_bounds: RectI32,
    from_selection: bool,
    affine: AffineState,
    corners: [Point2D; 4],
    mesh: MeshState,
    puppet_rest_verts: Vec<Point2D>,
    puppet_rest_uvs: Vec<[f64; 2]>,
    puppet_tris: Vec<[usize; 3]>,
    puppet_pins: Vec<PuppetPin>,
    cage: CageState,
    layers: Vec<TransformLayerSource>,
    cached_gpu_verts: Vec<TransformVertex>,
}

impl GpuTransformEngine {
    pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat) -> Self {
        let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("ink-transform-mesh-bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: true,
                        min_binding_size: std::num::NonZeroU64::new(
                            std::mem::size_of::<TransformMeshUniforms>() as u64,
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("ink-transform-mesh-shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(TRANSFORM_MESH_WGSL)),
        });
        let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("ink-transform-mesh-pl"),
            bind_group_layouts: &[Some(&bgl)],
            immediate_size: 0,
        });
        let vlayout = wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<TransformVertex>() as u64,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x2,
                },
                wgpu::VertexAttribute {
                    offset: 8,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32x2,
                },
            ],
        };
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("ink-transform-mesh-pipeline"),
            layout: Some(&pl),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(vlayout)],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: surface_format,
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState::default(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });
        let uniform_slot_align = device.limits().min_uniform_buffer_offset_alignment.max(256);
        let uniform_cap_slots = 16usize;
        let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-transform-uniforms"),
            size: (uniform_cap_slots as u64) * (uniform_slot_align as u64),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let vert_cap = 4096usize;
        let vert_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("ink-transform-verts"),
            size: (vert_cap * std::mem::size_of::<TransformVertex>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("ink-transform-linear-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        Self {
            bgl,
            pipeline,
            uniform_buf,
            uniform_slot_align,
            uniform_cap_slots,
            vert_buf,
            vert_cap,
            sampler,
            active: false,
            doc_id: String::new(),
            doc_width: 1,
            doc_height: 1,
            mode: TransformMode::Affine,
            source_bounds: RectI32::empty(),
            from_selection: false,
            affine: AffineState {
                x: 0.0,
                y: 0.0,
                width: 1.0,
                height: 1.0,
                rotation: 0.0,
                skew_x: 0.0,
                skew_y: 0.0,
                flip_x: false,
                flip_y: false,
            },
            corners: [Point2D::default(); 4],
            mesh: MeshState {
                cols: 3,
                rows: 3,
                points: Vec::new(),
            },
            puppet_rest_verts: Vec::new(),
            puppet_rest_uvs: Vec::new(),
            puppet_tris: Vec::new(),
            puppet_pins: Vec::new(),
            cage: CageState {
                rest_points: Vec::new(),
                points: Vec::new(),
                closed: false,
            },
            layers: Vec::new(),
            cached_gpu_verts: Vec::new(),
        }
    }

    #[inline]
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Set of layer IDs currently hidden from the base compositor because their transformed
    /// pixels are rendered live by `GpuTransformEngine`!
    pub fn hidden_layer_ids(&self) -> HashSet<String> {
        if !self.active || self.from_selection {
            return HashSet::new();
        }
        self.layers.iter().map(|l| l.layer_id.clone()).collect()
    }

    fn upload_rgba8_tex(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        w: u32,
        h: u32,
        rgba: &[u8],
    ) -> (wgpu::Texture, wgpu::TextureView) {
        let tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("ink-transform-src-rgba8"),
            size: wgpu::Extent3d {
                width: w.max(1),
                height: h.max(1),
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        if w > 0 && h > 0 && rgba.len() == (w as usize) * (h as usize) * 4 {
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &tex,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                rgba,
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(w * 4),
                    rows_per_image: Some(h),
                },
                wgpu::Extent3d {
                    width: w,
                    height: h,
                    depth_or_array_layers: 1,
                },
            );
        }
        (tex, view)
    }

    fn init_rest_geometry(&mut self, composite_rgba: &[u8]) {
        let b = self.source_bounds;
        let (x, y, w, h) = (b.x as f64, b.y as f64, b.width as f64, b.height as f64);
        self.affine = AffineState {
            x,
            y,
            width: w,
            height: h,
            rotation: 0.0,
            skew_x: 0.0,
            skew_y: 0.0,
            flip_x: false,
            flip_y: false,
        };
        self.corners = [
            Point2D { x, y },
            Point2D { x: x + w, y },
            Point2D { x: x + w, y: y + h },
            Point2D { x, y: y + h },
        ];
        let cols = 3usize;
        let rows = 3usize;
        let mut pts = Vec::with_capacity((cols + 1) * (rows + 1));
        for r in 0..=rows {
            for c in 0..=cols {
                pts.push(Point2D {
                    x: x + (c as f64 / cols as f64) * w,
                    y: y + (r as f64 / rows as f64) * h,
                });
            }
        }
        self.mesh = MeshState {
            cols,
            rows,
            points: pts,
        };

        let (pv, pt) = build_puppet_mesh(composite_rgba, b.width, b.height, b);
        self.puppet_rest_uvs = pv
            .iter()
            .map(|p| [(p.x - x) / w.max(1.0), (p.y - y) / h.max(1.0)])
            .collect();
        self.puppet_rest_verts = pv;
        self.puppet_tris = pt;
        self.puppet_pins.clear();

        let cage_pts = vec![
            Point2D { x: x - 12.0, y: y - 12.0 },
            Point2D { x: x + w + 12.0, y: y - 12.0 },
            Point2D { x: x + w + 12.0, y: y + h + 12.0 },
            Point2D { x: x - 12.0, y: y + h + 12.0 },
        ];
        self.cage = CageState {
            rest_points: cage_pts.clone(),
            points: cage_pts,
            closed: true,
        };
        self.rebuild_gpu_mesh();
    }

    /// Begins a new Transform/Warp session on a single layer, active selection, or multi-layer group!
    pub fn begin_session(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        doc: &mut Document,
        mode: TransformMode,
        explicit_layer_ids: Option<&[String]>,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<TransformSessionSnapshot, String> {
        // Resolve target editable raster layer IDs (expands folders automatically!)
        let mut target_ids: Vec<LayerId> = Vec::new();
        let seed_ids: Vec<String> = match explicit_layer_ids {
            Some(ids) if !ids.is_empty() => ids.to_vec(),
            _ => doc.active_layer_id.iter().cloned().collect(),
        };
        for sid in seed_ids {
            if let Some(l) = doc.layer(&sid) {
                if l.meta.layer_type == crate::document::LayerType::Folder
                    || l.meta.layer_type == crate::document::LayerType::FrameFolder
                {
                    // Collect all editable descendant raster layers
                    let mut stack = vec![sid.clone()];
                    while let Some(pid) = stack.pop() {
                        for child in &doc.layers {
                            if child.meta.parent_id.as_deref() == Some(pid.as_str()) {
                                if child.meta.layer_type.has_tiles()
                                    && !child.meta.locked
                                    && !target_ids.contains(&child.meta.id)
                                {
                                    target_ids.push(child.meta.id.clone());
                                } else if child.meta.layer_type == crate::document::LayerType::Folder
                                    || child.meta.layer_type == crate::document::LayerType::FrameFolder
                                {
                                    stack.push(child.meta.id.clone());
                                }
                            }
                        }
                    }
                } else if l.meta.layer_type.has_tiles()
                    && !l.meta.locked
                    && !target_ids.contains(&l.meta.id)
                {
                    target_ids.push(l.meta.id.clone());
                }
            }
        }
        if target_ids.is_empty() {
            return Err("No editable raster layer available to transform".to_string());
        }

        let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
        let active_sel = doc.selection.as_ref().filter(|s| !s.is_empty()).cloned();
        let from_selection = active_sel.is_some();

        // Determine union opaque pixel bounding box across target layers (or active selection bounds)
        let bounds = if let Some(ref sel) = active_sel {
            sel.bounds.intersect(doc_rect)
        } else {
            let mut min_x = doc.dimensions.width as i32;
            let mut min_y = doc.dimensions.height as i32;
            let mut max_x = -1i32;
            let mut max_y = -1i32;
            for lid in &target_ids {
                if let Some(layer) = doc.layer(lid) {
                    if let Some(tb) = layer.grid.tile_bounds() {
                        let clipped = tb.intersect(doc_rect);
                        if clipped.is_empty() {
                            continue;
                        }
                        let rgba = layer.grid.read_rgba8_rect(clipped, false, scratch)?;
                        let cw = clipped.width as usize;
                        let ch = clipped.height as usize;
                        for y in 0..ch {
                            for x in 0..cw {
                                if rgba[(y * cw + x) * 4 + 3] > 0 {
                                    let gx = clipped.x + x as i32;
                                    let gy = clipped.y + y as i32;
                                    min_x = min_x.min(gx);
                                    min_y = min_y.min(gy);
                                    max_x = max_x.max(gx);
                                    max_y = max_y.max(gy);
                                }
                            }
                        }
                    }
                }
            }
            if max_x < min_x || max_y < min_y {
                return Err("Selected layer(s) have no opaque pixels to transform".to_string());
            }
            RectI32::new(
                min_x,
                min_y,
                (max_x - min_x + 1) as u32,
                (max_y - min_y + 1) as u32,
            )
        };

        if bounds.is_empty() {
            return Err("Empty transform bounds".to_string());
        }

        let sel_mask = active_sel.as_ref().map(|s| s.read_rect(bounds));
        let sw = bounds.width as usize;
        let sh = bounds.height as usize;
        let mut composite_rgba = vec![0u8; sw * sh * 4];
        let mut sources = Vec::with_capacity(target_ids.len());

        // Capture CoW snapshots & extract source textures (lifting selection pixels cleanly!)
        for lid in &target_ids {
            let Some(layer) = doc.layer_mut(lid) else {
                continue;
            };
            let before_tiles = layer.grid.snapshot_all_cow(TileKind::Raster);
            let mut src_rgba = layer.grid.read_rgba8_rect(bounds, false, scratch)?;

            if let Some(ref sm) = sel_mask {
                let mut remain = src_rgba.clone();
                for i in 0..(sw * sh) {
                    let m = sm[i] as u32;
                    let orig_a = src_rgba[i * 4 + 3] as u32;
                    src_rgba[i * 4 + 3] = ((orig_a * m + 127) / 255) as u8;
                    remain[i * 4 + 3] = ((orig_a * (255 - m) + 127) / 255) as u8;
                }
                // Temporarily remove lifted pixels from layer so preview shows live floating move!
                let mono_t = layer.meta.mono_threshold.unwrap_or(128);
                let _ = layer.grid.write_rgba8_rect(&remain, bounds, mono_t, scratch);
            }

            for i in 0..(sw * sh) {
                if src_rgba[i * 4 + 3] > composite_rgba[i * 4 + 3] {
                    composite_rgba[i * 4..i * 4 + 4].copy_from_slice(&src_rgba[i * 4..i * 4 + 4]);
                }
            }

            let (gpu_tex, gpu_view) =
                Self::upload_rgba8_tex(device, queue, bounds.width, bounds.height, &src_rgba);
            sources.push(TransformLayerSource {
                layer_id: lid.clone(),
                before_tiles,
                src_rgba,
                opacity: layer.meta.opacity.clamp(0.0, 1.0),
                gpu_tex,
                gpu_view,
                gpu_bg: None,
            });
        }

        if from_selection {
            doc.dirty_for_render = true;
        }

        self.active = true;
        self.doc_id = doc.id.clone();
        self.doc_width = doc.dimensions.width.max(1);
        self.doc_height = doc.dimensions.height.max(1);
        self.mode = mode;
        self.source_bounds = bounds;
        self.from_selection = from_selection;
        self.layers = sources;
        self.init_rest_geometry(&composite_rgba);

        Ok(self.snapshot())
    }

    pub fn update_state(&mut self, payload: TransformUpdatePayload) -> Result<TransformSessionSnapshot, String> {
        if !self.active {
            return Err("No active transform session".to_string());
        }
        self.mode = payload.mode;
        if let Some(aff) = payload.affine {
            self.affine = aff;
        }
        if let Some(c) = payload.corners {
            self.corners = c;
        }
        if let Some(m) = payload.mesh {
            self.mesh = m;
        }
        if let Some(pins) = payload.puppet_pins {
            self.puppet_pins = pins;
        }
        if let Some(cage) = payload.cage {
            self.cage = cage;
        }
        self.rebuild_gpu_mesh();
        Ok(self.snapshot())
    }

    /// Switches seamlessly between any two transform modes (e.g. Affine -> Mesh -> Puppet -> Cage)
    /// by baking intermediate transformed pixels cleanly in Rust and re-initializing fresh rest handles!
    pub fn switch_mode(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        next_mode: TransformMode,
    ) -> Result<TransformSessionSnapshot, String> {
        if !self.active {
            return Err("No active transform session".to_string());
        }
        if self.mode == next_mode {
            return Ok(self.snapshot());
        }

        let doc_rect = RectI32::new(0, 0, self.doc_width, self.doc_height);
        let new_bounds = self.compute_deformed_bounds().intersect(doc_rect);
        if new_bounds.is_empty() {
            self.mode = next_mode;
            return Ok(self.snapshot());
        }

        let nw = new_bounds.width as usize;
        let nh = new_bounds.height as usize;
        let mut comp = vec![0u8; nw * nh * 4];
        let mut baked_list = Vec::with_capacity(self.layers.len());
        for ls in &self.layers {
            let baked = self.bake_layer_rgba(&ls.src_rgba, new_bounds);
            for i in 0..(nw * nh) {
                if baked[i * 4 + 3] > comp[i * 4 + 3] {
                    comp[i * 4..i * 4 + 4].copy_from_slice(&baked[i * 4..i * 4 + 4]);
                }
            }
            baked_list.push(baked);
        }

        for (ls, baked) in self.layers.iter_mut().zip(baked_list) {
            let (tex, view) =
                Self::upload_rgba8_tex(device, queue, new_bounds.width, new_bounds.height, &baked);
            ls.src_rgba = baked;
            ls.gpu_tex = tex;
            ls.gpu_view = view;
        }

        self.source_bounds = new_bounds;
        self.mode = next_mode;
        self.init_rest_geometry(&comp);
        Ok(self.snapshot())
    }

    /// Builds subdivided triangle geometry for the current mode (used for both GPU preview and bake).
    #[allow(clippy::type_complexity)]
    fn eval_deformed_mesh(&self, subdiv: usize) -> (Vec<Point2D>, Vec<[f64; 2]>, Vec<[usize; 3]>, Option<Vec<f64>>) {
        match self.mode {
            TransformMode::Puppet => {
                let deformed = solve_puppet_arap(
                    &self.puppet_rest_verts,
                    &self.puppet_tris,
                    &self.puppet_pins,
                );
                let depths: Vec<f64> = self
                    .puppet_tris
                    .iter()
                    .map(|&[a, b, c]| {
                        if self.puppet_pins.is_empty() {
                            return 0.0;
                        }
                        let cx = (self.puppet_rest_verts[a].x
                            + self.puppet_rest_verts[b].x
                            + self.puppet_rest_verts[c].x)
                            / 3.0;
                        let cy = (self.puppet_rest_verts[a].y
                            + self.puppet_rest_verts[b].y
                            + self.puppet_rest_verts[c].y)
                            / 3.0;
                        let mut d_acc = 0.0;
                        let mut w_acc = 0.0;
                        for pin in &self.puppet_pins {
                            let w = 1.0 / ((cx - pin.rest_x).hypot(cy - pin.rest_y).powi(2) + 1.0);
                            d_acc += w * pin.depth;
                            w_acc += w;
                        }
                        d_acc / w_acc.max(1e-9)
                    })
                    .collect();
                (
                    deformed,
                    self.puppet_rest_uvs.clone(),
                    self.puppet_tris.clone(),
                    Some(depths),
                )
            }
            _ => {
                let n = subdiv.max(2);
                let stride = n + 1;
                let mut verts = Vec::with_capacity(stride * stride);
                let mut uvs = Vec::with_capacity(stride * stride);
                let hom = if self.mode == TransformMode::Perspective {
                    solve_homography_from_unit_square(&self.corners)
                } else {
                    None
                };
                let b = self.source_bounds;

                for r in 0..=n {
                    let v = r as f64 / n as f64;
                    for c in 0..=n {
                        let u = c as f64 / n as f64;
                        let p = match self.mode {
                            TransformMode::Affine => eval_affine_point(&self.affine, u, v),
                            TransformMode::Perspective => hom
                                .as_ref()
                                .and_then(|h| apply_homography(h, u, v))
                                .unwrap_or(Point2D {
                                    x: b.x as f64 + u * b.width as f64,
                                    y: b.y as f64 + v * b.height as f64,
                                }),
                            TransformMode::Mesh => eval_mesh_catmull_rom(&self.mesh, u, v),
                            TransformMode::Cage => {
                                let q = Point2D {
                                    x: b.x as f64 + u * b.width as f64,
                                    y: b.y as f64 + v * b.height as f64,
                                };
                                if self.cage.closed && self.cage.rest_points.len() >= 3 {
                                    eval_cage_mvc(&self.cage.rest_points, &self.cage.points, q)
                                } else {
                                    q
                                }
                            }
                            TransformMode::Puppet => unreachable!(),
                        };
                        verts.push(p);
                        uvs.push([u, v]);
                    }
                }
                let mut tris = Vec::with_capacity(n * n * 2);
                for r in 0..n {
                    for c in 0..n {
                        let tl = r * stride + c;
                        let tr = tl + 1;
                        let bl = (r + 1) * stride + c;
                        let br = bl + 1;
                        tris.push([tl, tr, br]);
                        tris.push([tl, br, bl]);
                    }
                }
                (verts, uvs, tris, None)
            }
        }
    }

    fn rebuild_gpu_mesh(&mut self) {
        let subdiv = match self.mode {
            TransformMode::Affine => 2,
            TransformMode::Perspective => 16,
            TransformMode::Mesh | TransformMode::Cage => 24,
            TransformMode::Puppet => 1,
        };
        let (verts, uvs, tris, depths) = self.eval_deformed_mesh(subdiv);
        let mut order: Vec<usize> = (0..tris.len()).collect();
        if let Some(d) = depths {
            order.sort_by(|&a, &b| d[a].total_cmp(&d[b]));
        }
        self.cached_gpu_verts.clear();
        self.cached_gpu_verts.reserve(order.len() * 3);
        for ti in order {
            for &vi in &tris[ti] {
                self.cached_gpu_verts.push(TransformVertex {
                    pos_doc: [verts[vi].x as f32, verts[vi].y as f32],
                    uv: [uvs[vi][0] as f32, uvs[vi][1] as f32],
                });
            }
        }
    }

    fn compute_deformed_bounds(&self) -> RectI32 {
        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;
        for v in &self.cached_gpu_verts {
            min_x = min_x.min(v.pos_doc[0] as f64);
            min_y = min_y.min(v.pos_doc[1] as f64);
            max_x = max_x.max(v.pos_doc[0] as f64);
            max_y = max_y.max(v.pos_doc[1] as f64);
        }
        if !min_x.is_finite() {
            return RectI32::empty();
        }
        let x0 = min_x.floor() as i32 - 2;
        let y0 = min_y.floor() as i32 - 2;
        let x1 = max_x.ceil() as i32 + 2;
        let y1 = max_y.ceil() as i32 + 2;
        RectI32::new(x0, y0, (x1 - x0).max(1) as u32, (y1 - y0).max(1) as u32)
    }

    /// Encodes the live GPU Transform/Warp preview directly into `encoder` (zero extra `queue.submit`!).
    #[allow(clippy::too_many_arguments)]
    pub fn encode_preview(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        if !self.active || self.cached_gpu_verts.is_empty() || self.layers.is_empty() || vp_w == 0 || vp_h == 0 {
            return;
        }
        if self.cached_gpu_verts.len() > self.vert_cap {
            self.vert_cap = self.cached_gpu_verts.len().next_power_of_two();
            self.vert_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-transform-verts"),
                size: (self.vert_cap * std::mem::size_of::<TransformVertex>()) as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
        }
        queue.write_buffer(&self.vert_buf, 0, bytemuck::cast_slice(&self.cached_gpu_verts));

        let layer_count = self.layers.len();
        let stride = self.uniform_slot_align as usize;
        if layer_count > self.uniform_cap_slots {
            self.uniform_cap_slots = layer_count.next_power_of_two();
            self.uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("ink-transform-uniforms"),
                size: (self.uniform_cap_slots as u64) * (self.uniform_slot_align as u64),
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            for ls in &mut self.layers {
                ls.gpu_bg = None;
            }
        }

        // Pack all layers' uniforms (bottom-to-top) into one dynamic uniform upload
        let mut uniform_staging = vec![0u8; layer_count * stride];
        let u_size = std::mem::size_of::<TransformMeshUniforms>();
        for (idx, ls) in self.layers.iter_mut().rev().enumerate() {
            let u = TransformMeshUniforms {
                viewport_size_phys: [vp_w as f32, vp_h as f32],
                doc_size: [self.doc_width as f32, self.doc_height as f32],
                pan_css: [camera.pan_x, camera.pan_y],
                zoom: camera.zoom.max(0.01),
                rotation_rad: camera.rotation.to_radians(),
                flip: [
                    if camera.flip_x { -1.0 } else { 1.0 },
                    if camera.flip_y { -1.0 } else { 1.0 },
                ],
                dpr: dpr.max(0.05),
                opacity: ls.opacity,
            };
            let dst = idx * stride;
            uniform_staging[dst..dst + u_size].copy_from_slice(bytemuck::bytes_of(&u));
            if ls.gpu_bg.is_none() {
                ls.gpu_bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
                    label: Some("ink-transform-mesh-bg"),
                    layout: &self.bgl,
                    entries: &[
                        wgpu::BindGroupEntry {
                            binding: 0,
                            resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                                buffer: &self.uniform_buf,
                                offset: 0,
                                size: std::num::NonZeroU64::new(u_size as u64),
                            }),
                        },
                        wgpu::BindGroupEntry {
                            binding: 1,
                            resource: wgpu::BindingResource::TextureView(&ls.gpu_view),
                        },
                        wgpu::BindGroupEntry {
                            binding: 2,
                            resource: wgpu::BindingResource::Sampler(&self.sampler),
                        },
                    ],
                }));
            }
        }
        queue.write_buffer(&self.uniform_buf, 0, &uniform_staging);

        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("ink-transform-preview-pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view: target_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        pass.set_pipeline(&self.pipeline);
        pass.set_vertex_buffer(0, self.vert_buf.slice(..));
        for (idx, ls) in self.layers.iter().rev().enumerate() {
            let dyn_off = (idx as u32) * self.uniform_slot_align;
            if let Some(ref bg) = ls.gpu_bg {
                pass.set_bind_group(0, bg, &[dyn_off]);
                pass.draw(0..self.cached_gpu_verts.len() as u32, 0..1);
            }
        }
    }

    /// Renders the live GPU Transform/Warp preview directly onto `target_view` at 120+ FPS!
    #[allow(clippy::too_many_arguments)]
    pub fn render_preview(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        camera: &CameraState,
        vp_w: u32,
        vp_h: u32,
        dpr: f32,
        target_view: &wgpu::TextureView,
    ) {
        if !self.active || self.cached_gpu_verts.is_empty() || self.layers.is_empty() || vp_w == 0 || vp_h == 0 {
            return;
        }
        let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("ink-transform-preview-enc"),
        });
        self.encode_preview(device, queue, &mut enc, camera, vp_w, vp_h, dpr, target_view);
        queue.submit(Some(enc.finish()));
    }

    /// High-quality CPU Rayon Lanczos-3 / Lossless 90°-step bake for a single source layer buffer.
    fn bake_layer_rgba(&self, src_rgba: &[u8], out_rect: RectI32) -> Vec<u8> {
        let sw = self.source_bounds.width as usize;
        let sh = self.source_bounds.height as usize;
        let ow = out_rect.width as usize;
        let oh = out_rect.height as usize;

        match self.mode {
            TransformMode::Affine => {
                // Fast exact lossless 0°/90°/180°/270° integer translation + flip check!
                let aff = &self.affine;
                let deg = aff.rotation.to_degrees().rem_euclid(360.0);
                let nearest_90 = (deg / 90.0).round() as i32 % 4;
                let is_right_angle = (deg - (nearest_90 as f64 * 90.0)).abs() < 1e-4
                    || (360.0 - deg).abs() < 1e-4;
                let is_unskewed = aff.skew_x.abs() < 1e-5 && aff.skew_y.abs() < 1e-5;
                let is_unit_scale =
                    (aff.width - sw as f64).abs() < 1e-3 && (aff.height - sh as f64).abs() < 1e-3;
                let is_int_pos = (aff.x - aff.x.round()).abs() < 1e-3
                    && (aff.y - aff.y.round()).abs() < 1e-3;

                if is_right_angle && is_unskewed && is_unit_scale && is_int_pos && nearest_90 == 0 {
                    let mut out = vec![0u8; ow * oh * 4];
                    let dx0 = aff.x.round() as i32;
                    let dy0 = aff.y.round() as i32;
                    for sy in 0..sh {
                        let fy = if aff.flip_y { sh - 1 - sy } else { sy };
                        let dy = dy0 + sy as i32 - out_rect.y;
                        if dy < 0 || dy >= oh as i32 {
                            continue;
                        }
                        for sx in 0..sw {
                            let fx = if aff.flip_x { sw - 1 - sx } else { sx };
                            let dx = dx0 + sx as i32 - out_rect.x;
                            if dx < 0 || dx >= ow as i32 {
                                continue;
                            }
                            let so = (fy * sw + fx) * 4;
                            let doff = (dy as usize * ow + dx as usize) * 4;
                            out[doff..doff + 4].copy_from_slice(&src_rgba[so..so + 4]);
                        }
                    }
                    return out;
                }

                // Exact inverse Affine matrix + Anti-Ringing Lanczos-3 resample
                let cx = aff.x + aff.width * 0.5;
                let cy = aff.y + aff.height * 0.5;
                let c = (-aff.rotation).cos();
                let s = (-aff.rotation).sin();
                let det_skew = 1.0 - aff.skew_x * aff.skew_y;
                if det_skew.abs() < 1e-9 || aff.width.abs() < 1e-6 || aff.height.abs() < 1e-6 {
                    return vec![0u8; ow * oh * 4];
                }
                let mut out = vec![0u8; ow * oh * 4];
                out.par_chunks_mut(ow * 4)
                    .enumerate()
                    .for_each(|(ry, row)| {
                        let py = out_rect.y as f64 + ry as f64 + 0.5;
                        for rx in 0..ow {
                            let px = out_rect.x as f64 + rx as f64 + 0.5;
                            let dx = px - cx;
                            let dy = py - cy;
                            let rxp = dx * c - dy * s;
                            let ryp = dx * s + dy * c;
                            let lx = (rxp - aff.skew_x * ryp) / det_skew;
                            let ly = (ryp - aff.skew_y * rxp) / det_skew;
                            let mut u = lx / aff.width + 0.5;
                            let mut v = ly / aff.height + 0.5;
                            if aff.flip_x {
                                u = 1.0 - u;
                            }
                            if aff.flip_y {
                                v = 1.0 - v;
                            }
                            if (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v) {
                                let px_c = sample_lanczos3_rgba8(
                                    src_rgba,
                                    sw,
                                    sh,
                                    u * sw as f64 - 0.5,
                                    v * sh as f64 - 0.5,
                                );
                                row[rx * 4..rx * 4 + 4].copy_from_slice(&px_c);
                            }
                        }
                    });
                out
            }
            TransformMode::Perspective => {
                let Some(h_fwd) = solve_homography_from_unit_square(&self.corners) else {
                    return vec![0u8; ow * oh * 4];
                };
                let Some(h_inv) = invert_3x3(&h_fwd) else {
                    return vec![0u8; ow * oh * 4];
                };
                let mut out = vec![0u8; ow * oh * 4];
                out.par_chunks_mut(ow * 4)
                    .enumerate()
                    .for_each(|(ry, row)| {
                        let py = out_rect.y as f64 + ry as f64 + 0.5;
                        for rx in 0..ow {
                            let px = out_rect.x as f64 + rx as f64 + 0.5;
                            if let Some(uv) = apply_homography(&h_inv, px, py) {
                                if (0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y) {
                                    let px_c = sample_lanczos3_rgba8(
                                        src_rgba,
                                        sw,
                                        sh,
                                        uv.x * sw as f64 - 0.5,
                                        uv.y * sh as f64 - 0.5,
                                    );
                                    row[rx * 4..rx * 4 + 4].copy_from_slice(&px_c);
                                }
                            }
                        }
                    });
                out
            }
            TransformMode::Mesh | TransformMode::Cage | TransformMode::Puppet => {
                let subdiv = if self.mode == TransformMode::Puppet { 1 } else { 32 };
                let (verts, uvs, tris, depths) = self.eval_deformed_mesh(subdiv);
                rasterize_mesh_lanczos3(
                    src_rgba,
                    sw,
                    sh,
                    &verts,
                    &uvs,
                    &tris,
                    depths.as_deref(),
                    out_rect,
                )
            }
        }
    }

    /// Commits high-quality Lanczos-3 baked tiles across all transformed layers with a single
    /// atomic CoW Undo entry!
    pub fn commit_session(
        &mut self,
        doc: &mut Document,
        scratch: Option<&dyn ScratchBackend>,
    ) -> Result<TransformCommitResult, String> {
        if !self.active || self.doc_id != doc.id {
            self.active = false;
            self.layers.clear();
            return Ok(TransformCommitResult {
                modified: false,
                layer_ids: Vec::new(),
                dirty_rect: RectI32::empty(),
            });
        }

        let doc_rect = RectI32::new(0, 0, doc.dimensions.width, doc.dimensions.height);
        let out_rect = self.compute_deformed_bounds().intersect(doc_rect);
        let mut all_deltas: Vec<CowTileDelta> = Vec::new();
        let mut modified_ids: Vec<LayerId> = Vec::new();
        let mut dirty_union = self.source_bounds.union(out_rect).intersect(doc_rect);

        let sources = std::mem::take(&mut self.layers);
        for ls in sources {
            let baked = if out_rect.is_empty() {
                Vec::new()
            } else {
                self.bake_layer_rgba(&ls.src_rgba, out_rect)
            };

            let Some(layer) = doc.layer_mut(&ls.layer_id) else {
                continue;
            };
            let mono_t = layer.meta.mono_threshold.unwrap_or(128);

            if self.from_selection {
                // Composite transformed selection pixels over the unselected remainder!
                if !out_rect.is_empty() {
                    let mut dst = layer.grid.read_rgba8_rect(out_rect, false, scratch)?;
                    crate::io::compositor_cpu::blend_rgba8_over(
                        &mut dst,
                        &baked,
                        1.0,
                        crate::document::BlendMode::Normal,
                    );
                    let _ = layer.grid.write_rgba8_rect(&dst, out_rect, mono_t, scratch);
                }
            } else {
                // Full-layer transform: clear old tiles and write freshly baked transformed tiles
                layer.grid.clear_all();
                if !out_rect.is_empty() {
                    let _ = layer.grid.write_rgba8_rect(&baked, out_rect, mono_t, scratch);
                }
            }

            // Diff before_tiles vs after tiles for atomic CoW Undo
            let mut coords: HashSet<crate::tiles::TileCoord> =
                ls.before_tiles.keys().copied().collect();
            coords.extend(layer.grid.tiles.keys().copied());
            let mut layer_changed = false;
            for coord in coords {
                let before = ls.before_tiles.get(&coord).cloned();
                let after = layer.grid.tiles.get(&coord).cloned();
                let same = match (&before, &after) {
                    (None, None) => true,
                    (Some(a), Some(b)) => Arc::ptr_eq(a, b) || a.version == b.version,
                    _ => false,
                };
                if !same {
                    layer_changed = true;
                    all_deltas.push(CowTileDelta {
                        layer_id: ls.layer_id.clone(),
                        coord,
                        kind: TileKind::Raster,
                        before,
                        after,
                        remote_epoch: layer.grid.remote_epochs.get(&coord).copied().unwrap_or(0),
                    });
                }
            }
            if layer_changed {
                modified_ids.push(ls.layer_id);
            }
        }

        if !all_deltas.is_empty() {
            let primary = modified_ids
                .first()
                .cloned()
                .or_else(|| doc.active_layer_id.clone())
                .unwrap_or_default();
            let label = match self.mode {
                TransformMode::Affine => "Free Transform",
                TransformMode::Perspective => "Perspective Transform",
                TransformMode::Mesh => "Mesh Warp",
                TransformMode::Puppet => "Puppet Warp",
                TransformMode::Cage => "Cage Warp",
            };
            doc.record_stroke_deltas(&primary, "transform", label, all_deltas, None, None);
            doc.dirty_for_render = true;
        } else {
            dirty_union = RectI32::empty();
        }

        self.active = false;
        self.cached_gpu_verts.clear();
        Ok(TransformCommitResult {
            modified: !modified_ids.is_empty(),
            layer_ids: modified_ids,
            dirty_rect: dirty_union,
        })
    }

    /// Cancels an active transform session, restoring lifted selection pixels with zero undo mutation!
    pub fn cancel_session(&mut self, doc: Option<&mut Document>) {
        if let Some(d) = doc {
            if self.active && self.doc_id == d.id && self.from_selection {
                for ls in &self.layers {
                    if let Some(layer) = d.layer_mut(&ls.layer_id) {
                        layer.grid.tiles = ls.before_tiles.clone();
                        layer.grid.mark_all_lods_dirty();
                        layer.grid.bump_version();
                    }
                }
                d.dirty_for_render = true;
            }
        }
        self.active = false;
        self.layers.clear();
        self.cached_gpu_verts.clear();
    }

    pub fn snapshot(&self) -> TransformSessionSnapshot {
        let puppet_verts = if self.mode == TransformMode::Puppet && !self.puppet_pins.is_empty() {
            solve_puppet_arap(
                &self.puppet_rest_verts,
                &self.puppet_tris,
                &self.puppet_pins,
            )
        } else {
            self.puppet_rest_verts.clone()
        };
        TransformSessionSnapshot {
            active: self.active,
            doc_id: self.doc_id.clone(),
            mode: self.mode,
            target_layer_ids: self.layers.iter().map(|l| l.layer_id.clone()).collect(),
            source_bounds: self.source_bounds,
            affine: self.affine,
            corners: self.corners,
            mesh: self.mesh.clone(),
            puppet: PuppetState {
                pins: self.puppet_pins.clone(),
                mesh_vertices: puppet_verts,
                mesh_triangles: self.puppet_tris.clone(),
            },
            cage: self.cage.clone(),
            show_mesh: true,
        }
    }
}