Skip to content

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

34.1 KB
Raw Blame
import React, { useRef, useEffect, useMemo, useCallback } from 'react';
import {
  TransformSession,
  Point2D,
  TransformMode,
  PuppetPin,
  CagePoint,
} from '../types/editor';
import {
  FlipHorizontal,
  FlipVertical,
  RotateCcw,
  Trash2,
  ArrowUp,
  ArrowDown,
  Check,
  X,
} from 'lucide-react';
import {
  nativeTransformSwitchMode,
  nativeTransformUpdate,
  type NativeTransformUpdatePayload,
} from '../utils/nativeEngineBridge';
import { nativeTransformSnapshotToSession } from '../hooks/drawing/useSelectionTools';
import { useI18n } from '../i18n';

interface TransformOverlayProps {
  session: TransformSession;
  zoom: number;
  rotation: number;
  flipX?: boolean;
  flipY?: boolean;
  isSpaceDown?: boolean;
  onUpdateSession: (updater: (prev: TransformSession) => TransformSession) => void;
  onApply: () => void;
  onCancel: () => void;
}

function getBoundsOfPoints(pts: readonly Point2D[]) {
  if (pts.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
  let minX = Infinity;
  let minY = Infinity;
  let maxX = -Infinity;
  let maxY = -Infinity;
  for (const p of pts) {
    if (p.x < minX) minX = p.x;
    if (p.y < minY) minY = p.y;
    if (p.x > maxX) maxX = p.x;
    if (p.y > maxY) maxY = p.y;
  }
  return { minX, minY, maxX, maxY, width: maxX - minX, height: maxY - minY };
}

function computeAffineQuad(s: TransformSession): [Point2D, Point2D, Point2D, Point2D] {
  const cx = s.x + s.width * 0.5;
  const cy = s.y + s.height * 0.5;
  const hw = s.width * 0.5;
  const hh = s.height * 0.5;
  const rad = (s.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const rot = (lx: number, ly: number): Point2D => ({
    x: cx + lx * cos - ly * sin,
    y: cy + lx * sin + ly * cos,
  });
  return [rot(-hw, -hh), rot(hw, -hh), rot(hw, hh), rot(-hw, hh)];
}

function buildUpdatePayload(s: TransformSession): NativeTransformUpdatePayload {
  const mode = s.mode || 'affine';
  if (mode === 'perspective' && s.perspectiveQuad) {
    return { mode: 'perspective', corners: s.perspectiveQuad };
  }
  if (mode === 'mesh' && s.meshPoints && s.meshPoints.length >= 2) {
    const vRows = s.meshPoints.length;
    const vCols = s.meshPoints[0]?.length ?? 0;
    const flat: Point2D[] = [];
    for (let r = 0; r < vRows; r++) {
      for (let c = 0; c < vCols; c++) {
        flat.push(s.meshPoints[r][c]);
      }
    }
    return {
      mode: 'mesh',
      mesh: {
        cols: Math.max(1, vCols - 1),
        rows: Math.max(1, vRows - 1),
        points: flat,
      },
    };
  }
  if (mode === 'puppet' && s.puppet) {
    return {
      mode: 'puppet',
      puppetPins: s.puppet.pins.map((p) => ({
        id: p.id,
        restX: p.restX,
        restY: p.restY,
        x: p.x,
        y: p.y,
        rotation: p.rotation ?? 0,
        depth: p.depth ?? 0,
      })),
    };
  }
  if (mode === 'cage' && s.cage) {
    return {
      mode: 'cage',
      cage: {
        restPoints: s.cage.points.map((p) => ({ x: p.restX, y: p.restY })),
        points: s.cage.points.map((p) => ({ x: p.x, y: p.y })),
        closed: s.cage.phase === 'deform' || Boolean(s.cage.closed),
      },
    };
  }

  return {
    mode: 'affine',
    affine: {
      x: s.x,
      y: s.y,
      width: Math.max(1, s.width),
      height: Math.max(1, s.height),
      rotation: (s.rotation * Math.PI) / 180,
      skewX: 0,
      skewY: 0,
      flipX: Boolean(s.flipH),
      flipY: Boolean(s.flipV),
    },
  };
}

/**
 * Pure Lightweight SVG Handle & Gizmo Transform Overlay (Phase 6 Native DX12 GPU Transform).
 *
 * Holds ZERO `<canvas>` elements and runs ZERO JS pixel resampling. Every drag updates
 * control-point coordinates in Rust's `GpuTransformEngine` (`nativeTransformUpdate`) for
 * real-time 120+ FPS GPU mesh warp across all 5 modes (`affine`, `perspective`, `mesh`,
 * `puppet`, `cage`), with Lanczos-3 / lossless 90° tile bake on Apply.
 */
export const TransformOverlay: React.FC<TransformOverlayProps> = ({
  session,
  zoom,
  rotation: canvasRotation,
  flipX = false,
  flipY = false,
  isSpaceDown = false,
  onUpdateSession,
  onApply,
  onCancel,
}) => {
  const { t } = useI18n();
  const docOriginRef = useRef<HTMLDivElement>(null);
  const activeDragCleanupRef = useRef<(() => void) | null>(null);
  const pinIdCounterRef = useRef(1);
  const cageIdCounterRef = useRef(100);
  const syncInFlightRef = useRef<boolean>(false);
  const pendingPayloadRef = useRef<NativeTransformUpdatePayload | null>(null);
  const sessionRef = useRef<TransformSession>(session);
  sessionRef.current = session;

  const flushGpuTransformUpdate = useCallback((payload: NativeTransformUpdatePayload) => {
    if (syncInFlightRef.current) {
      pendingPayloadRef.current = payload;
      return;
    }
    syncInFlightRef.current = true;
    void nativeTransformUpdate(payload)
      .catch((err) => {
        console.warn('[TransformOverlay] nativeTransformUpdate failed:', err);
      })
      .finally(() => {
        syncInFlightRef.current = false;
        const queued = pendingPayloadRef.current;
        if (queued) {
          pendingPayloadRef.current = null;
          flushGpuTransformUpdate(queued);
        }
      });
  }, []);

  const updateAndSync = useCallback(
    (updater: (prev: TransformSession) => TransformSession) => {
      const next = updater(sessionRef.current);
      sessionRef.current = next;
      onUpdateSession(() => next);
      flushGpuTransformUpdate(buildUpdatePayload(next));
    },
    [onUpdateSession, flushGpuTransformUpdate]
  );

  useEffect(() => {
    return () => {
      if (activeDragCleanupRef.current) {
        activeDragCleanupRef.current();
      }
    };
  }, []);

  // Keyboard shortcuts: Enter = Close cage (if defining) or Apply, Escape = Cancel, Delete/Backspace = delete selected pin/point
  useEffect(() => {
    const onKeyDown = (ev: KeyboardEvent) => {
      const target = ev.target as HTMLElement | null;
      if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
      if (ev.key === 'Enter') {
        ev.preventDefault();
        const cur = sessionRef.current;
        if (
          cur.mode === 'cage' &&
          cur.cage &&
          cur.cage.phase !== 'deform' &&
          !cur.cage.closed &&
          cur.cage.points.length >= 3
        ) {
          updateAndSync((prev) =>
            prev.cage
              ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } }
              : prev
          );
          return;
        }
        onApply();
      } else if (ev.key === 'Escape') {
        ev.preventDefault();
        onCancel();
      } else if (ev.key === 'Delete' || ev.key === 'Backspace') {
        const cur = sessionRef.current;
        if (cur.mode === 'puppet' && cur.puppet?.selectedPinId) {
          ev.preventDefault();
          const delId = cur.puppet.selectedPinId;
          updateAndSync((prev) => {
            if (!prev.puppet) return prev;
            const remaining = prev.puppet.pins.filter((p) => p.id !== delId);
            return {
              ...prev,
              puppet: {
                ...prev.puppet,
                pins: remaining,
                selectedPinId: remaining[0]?.id ?? null,
              },
            };
          });
        } else if (cur.mode === 'cage' && cur.cage?.selectedPointId) {
          ev.preventDefault();
          const delId = cur.cage.selectedPointId;
          updateAndSync((prev) => {
            if (!prev.cage) return prev;
            const isClosed = prev.cage.phase === 'deform' || Boolean(prev.cage.closed);
            if (isClosed && prev.cage.points.length <= 3) return prev;
            const remaining = prev.cage.points.filter((pt) => pt.id !== delId);
            return {
              ...prev,
              cage: {
                ...prev.cage,
                points: remaining,
                selectedPointId: null,
              },
            };
          });
        }
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [onApply, onCancel, updateAndSync]);

  const invZoom = 1 / Math.max(0.05, zoom || 1);
  const mode: TransformMode = session.mode || 'affine';

  const screenDeltaToDoc = useCallback(
    (dxScreen: number, dyScreen: number): Point2D => {
      const rad = -(canvasRotation * Math.PI) / 180;
      const cos = Math.cos(rad);
      const sin = Math.sin(rad);
      const rx = (dxScreen * cos - dyScreen * sin) / Math.max(0.05, zoom);
      const ry = (dxScreen * sin + dyScreen * cos) / Math.max(0.05, zoom);
      return { x: flipX ? -rx : rx, y: flipY ? -ry : ry };
    },
    [canvasRotation, zoom, flipX, flipY]
  );

  const clientToDoc = useCallback(
    (clientX: number, clientY: number): Point2D => {
      const el = docOriginRef.current;
      if (!el) return { x: 0, y: 0 };
      const rect = el.getBoundingClientRect();
      return screenDeltaToDoc(clientX - rect.left, clientY - rect.top);
    },
    [screenDeltaToDoc]
  );

  const startPointerDrag = useCallback(
    (
      e: React.PointerEvent,
      onMove: (dxDoc: number, dyDoc: number, ev: PointerEvent) => void
    ) => {
      if (isSpaceDown) return;
      e.preventDefault();
      e.stopPropagation();
      if (activeDragCleanupRef.current) activeDragCleanupRef.current();
      const startX = e.clientX;
      const startY = e.clientY;
      const handleMove = (ev: PointerEvent) => {
        const d = screenDeltaToDoc(ev.clientX - startX, ev.clientY - startY);
        onMove(d.x, d.y, ev);
      };
      const cleanup = () => {
        window.removeEventListener('pointermove', handleMove);
        window.removeEventListener('pointerup', handleUp);
        window.removeEventListener('pointercancel', handleUp);
        activeDragCleanupRef.current = null;
      };
      const handleUp = () => cleanup();
      activeDragCleanupRef.current = cleanup;
      window.addEventListener('pointermove', handleMove);
      window.addEventListener('pointerup', handleUp);
      window.addEventListener('pointercancel', handleUp);
    },
    [isSpaceDown, screenDeltaToDoc]
  );

  const handleSwitchMode = useCallback(
    (nextMode: TransformMode) => {
      if (nextMode === session.mode) return;
      void nativeTransformSwitchMode(nextMode)
        .then((snap) => {
          if (!snap) return;
          onUpdateSession((prev) =>
            nativeTransformSnapshotToSession(snap, prev.layerId, Boolean(prev.isSelection))
          );
        })
        .catch(() => {});
    },
    [session.mode, onUpdateSession]
  );

  const handleFlip = useCallback(
    (axis: 'h' | 'v') => {
      updateAndSync((prev) => ({
        ...prev,
        flipH: axis === 'h' ? !prev.flipH : prev.flipH,
        flipV: axis === 'v' ? !prev.flipV : prev.flipV,
      }));
    },
    [updateAndSync]
  );

  const handleReset = useCallback(() => {
    updateAndSync((prev) => {
      const b = prev.bounds;
      const quad: [Point2D, Point2D, Point2D, Point2D] = [
        { x: b.x, y: b.y },
        { x: b.x + b.width, y: b.y },
        { x: b.x + b.width, y: b.y + b.height },
        { x: b.x, y: b.y + b.height },
      ];
      const cols = prev.meshCols || 4;
      const rows = prev.meshRows || 4;
      const meshPoints: Point2D[][] = [];
      for (let r = 0; r < rows; r++) {
        const row: Point2D[] = [];
        for (let c = 0; c < cols; c++) {
          row.push({
            x: b.x + (c / Math.max(1, cols - 1)) * b.width,
            y: b.y + (r / Math.max(1, rows - 1)) * b.height,
          });
        }
        meshPoints.push(row);
      }
      return {
        ...prev,
        x: b.x,
        y: b.y,
        width: b.width,
        height: b.height,
        rotation: 0,
        flipH: false,
        flipV: false,
        perspectiveQuad: quad,
        meshPoints,
        puppet: prev.puppet ? { ...prev.puppet, pins: [], selectedPinId: null } : prev.puppet,
        cage: prev.cage
          ? {
              ...prev.cage,
              points: prev.cage.points.map((p) => ({ ...p, x: p.restX, y: p.restY })),
            }
          : prev.cage,
      };
    });
  }, [updateAndSync]);

  const affineQuad = useMemo(() => computeAffineQuad(session), [session]);
  const quad = session.perspectiveQuad ?? affineQuad;
  const meshPoints = session.meshPoints ?? [];
  const puppetPins = session.puppet?.pins ?? [];
  const cagePoints = session.cage?.points ?? [];
  const cageClosed = session.cage?.phase === 'deform';

  const toolbarBounds = useMemo(() => {
    if (mode === 'perspective') return getBoundsOfPoints(quad);
    if (mode === 'mesh' && meshPoints.length > 0) return getBoundsOfPoints(meshPoints.flat());
    if (mode === 'cage' && cagePoints.length > 0) return getBoundsOfPoints(cagePoints);
    return getBoundsOfPoints(affineQuad);
  }, [mode, quad, meshPoints, cagePoints, affineQuad]);

  const handleSize = 10 * invZoom;

  // --- Mode-specific pointer handlers ---
  const handleBodyMove = (e: React.PointerEvent) => {
    const startX = session.x;
    const startY = session.y;
    startPointerDrag(e, (dx, dy) => {
      updateAndSync((prev) => ({ ...prev, x: startX + dx, y: startY + dy }));
    });
  };

  const handleAffineResize = (
    e: React.PointerEvent,
    handle: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'
  ) => {
    const s0 = { x: session.x, y: session.y, w: session.width, h: session.height };
    const rad = (session.rotation * Math.PI) / 180;
    const cos = Math.cos(-rad);
    const sin = Math.sin(-rad);
    startPointerDrag(e, (dxDoc, dyDoc, ev) => {
      const lx = dxDoc * cos - dyDoc * sin;
      const ly = dxDoc * sin + dyDoc * cos;
      let nx = s0.x;
      let ny = s0.y;
      let nw = s0.w;
      let nh = s0.h;
      if (handle.includes('e')) nw = Math.max(4, s0.w + lx);
      if (handle.includes('s')) nh = Math.max(4, s0.h + ly);
      if (handle.includes('w')) {
        nw = Math.max(4, s0.w - lx);
        nx = s0.x + (s0.w - nw);
      }
      if (handle.includes('n')) {
        nh = Math.max(4, s0.h - ly);
        ny = s0.y + (s0.h - nh);
      }
      if (ev.shiftKey && s0.w > 0 && s0.h > 0) {
        const aspect = s0.w / s0.h;
        if (Math.abs(nw - s0.w) >= Math.abs(nh - s0.h)) {
          nh = Math.max(4, nw / aspect);
        } else {
          nw = Math.max(4, nh * aspect);
        }
      }
      updateAndSync((prev) => ({ ...prev, x: nx, y: ny, width: nw, height: nh }));
    });
  };

  const handleAffineRotate = (e: React.PointerEvent) => {
    const cx = session.x + session.width * 0.5;
    const cy = session.y + session.height * 0.5;
    const startPt = clientToDoc(e.clientX, e.clientY);
    const startAngle = Math.atan2(startPt.y - cy, startPt.x - cx);
    const baseRot = session.rotation;
    startPointerDrag(e, (_dx, _dy, ev) => {
      const curPt = clientToDoc(ev.clientX, ev.clientY);
      let deg = baseRot + ((Math.atan2(curPt.y - cy, curPt.x - cx) - startAngle) * 180) / Math.PI;
      if (ev.shiftKey) deg = Math.round(deg / 15) * 15;
      updateAndSync((prev) => ({ ...prev, rotation: deg }));
    });
  };

  const handlePuppetSurfaceClick = (e: React.PointerEvent) => {
    if (mode !== 'puppet' || isSpaceDown || e.button !== 0) return;
    e.stopPropagation();
    const pt = clientToDoc(e.clientX, e.clientY);
    const id = `pin-${pinIdCounterRef.current++}`;
    const newPin: PuppetPin = {
      id,
      restX: pt.x,
      restY: pt.y,
      x: pt.x,
      y: pt.y,
      rotation: 0,
      depth: 0,
    };
    updateAndSync((prev) => ({
      ...prev,
      puppet: {
        ...(prev.puppet ?? {
          pins: [],
          selectedPinId: null,
          rigidity: 'normal',
          density: 'normal',
          expansion: 6,
          showMesh: true,
        }),
        pins: [...(prev.puppet?.pins ?? []), newPin],
        selectedPinId: id,
      },
    }));
  };

  const handleCageSurfaceClick = (e: React.PointerEvent) => {
    if (mode !== 'cage' || cageClosed || isSpaceDown || e.button !== 0) return;
    e.stopPropagation();
    const pt = clientToDoc(e.clientX, e.clientY);
    if (cagePoints.length >= 3) {
      const first = cagePoints[0];
      if (Math.hypot(first.x - pt.x, first.y - pt.y) <= 14 * invZoom) {
        updateAndSync((prev) =>
          prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } } : prev
        );
        return;
      }
    }
    const newPt: CagePoint = {
      id: `cage-${cageIdCounterRef.current++}`,
      restX: pt.x,
      restY: pt.y,
      x: pt.x,
      y: pt.y,
    };
    updateAndSync((prev) => ({
      ...prev,
      cage: {
        ...(prev.cage ?? { phase: 'define', points: [], selectedPointId: null, showCage: true }),
        points: [...(prev.cage?.points ?? []), newPt],
        selectedPointId: newPt.id,
      },
    }));
  };

  const modes: { id: TransformMode; label: string }[] = [
    { id: 'affine', label: t('Free') },
    { id: 'perspective', label: t('Perspective') },
    { id: 'mesh', label: t('Mesh') },
    { id: 'puppet', label: t('Puppet') },
    { id: 'cage', label: t('Cage') },
  ];

  const affineMid = (a: Point2D, b: Point2D): Point2D => ({
    x: (a.x + b.x) * 0.5,
    y: (a.y + b.y) * 0.5,
  });

  const affineHandles: Array<{
    key: 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w';
    pt: Point2D;
  }> = [
    { key: 'nw', pt: affineQuad[0] },
    { key: 'n', pt: affineMid(affineQuad[0], affineQuad[1]) },
    { key: 'ne', pt: affineQuad[1] },
    { key: 'e', pt: affineMid(affineQuad[1], affineQuad[2]) },
    { key: 'se', pt: affineQuad[2] },
    { key: 's', pt: affineMid(affineQuad[2], affineQuad[3]) },
    { key: 'sw', pt: affineQuad[3] },
    { key: 'w', pt: affineMid(affineQuad[3], affineQuad[0]) },
  ];

  const topMid = affineMid(affineQuad[0], affineQuad[1]);
  const centerPt: Point2D = { x: session.x + session.width * 0.5, y: session.y + session.height * 0.5 };
  const rotStemLen = 28 * invZoom;
  const rotRad = ((session.rotation - 90) * Math.PI) / 180;
  const rotHandlePt: Point2D = {
    x: topMid.x + Math.cos(rotRad) * rotStemLen,
    y: topMid.y + Math.sin(rotRad) * rotStemLen,
  };

  return (
    <div
      className="absolute inset-0 z-35 pointer-events-none select-none"
      style={{ pointerEvents: isSpaceDown ? 'none' : undefined }}
    >
      {/* Anchor at document (0,0) for accurate clientToDoc conversion */}
      <div ref={docOriginRef} className="absolute top-0 left-0 w-0 h-0 pointer-events-none" />

      {/* Puppet / Cage interactive placement hit plane */}
      {(mode === 'puppet' || (mode === 'cage' && !cageClosed)) && !isSpaceDown && (
        <div
          className="absolute inset-0 pointer-events-auto cursor-crosshair"
          onPointerDown={mode === 'puppet' ? handlePuppetSurfaceClick : handleCageSurfaceClick}
        />
      )}

      {/* Lightweight SVG Handle & Wireframe Gizmos (ZERO <canvas>!) */}
      <svg className="absolute inset-0 w-full h-full overflow-visible pointer-events-none">
        {mode === 'affine' && (
          <g>
            <polygon
              points={affineQuad.map((p) => `${p.x},${p.y}`).join(' ')}
              fill="rgba(56, 189, 248, 0.03)"
              stroke="#38bdf8"
              strokeWidth={1.5 * invZoom}
              className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-move'}
              onPointerDown={handleBodyMove}
            />
            <line
              x1={topMid.x}
              y1={topMid.y}
              x2={rotHandlePt.x}
              y2={rotHandlePt.y}
              stroke="#38bdf8"
              strokeWidth={1.25 * invZoom}
            />
            <circle
              cx={rotHandlePt.x}
              cy={rotHandlePt.y}
              r={5.5 * invZoom}
              fill="#0f172a"
              stroke="#38bdf8"
              strokeWidth={1.75 * invZoom}
              className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-grab'}
              onPointerDown={handleAffineRotate}
            />
            <circle
              cx={centerPt.x}
              cy={centerPt.y}
              r={3 * invZoom}
              fill="none"
              stroke="#38bdf8"
              strokeWidth={1.2 * invZoom}
            />
            {affineHandles.map(({ key, pt }) => (
              <rect
                key={key}
                x={pt.x - handleSize * 0.5}
                y={pt.y - handleSize * 0.5}
                width={handleSize}
                height={handleSize}
                fill="#ffffff"
                stroke="#0284c7"
                strokeWidth={1.5 * invZoom}
                className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-pointer'}
                onPointerDown={(ev) => handleAffineResize(ev, key)}
              />
            ))}
          </g>
        )}

        {mode === 'perspective' && (
          <g>
            <polygon
              points={quad.map((p) => `${p.x},${p.y}`).join(' ')}
              fill="rgba(56, 189, 248, 0.03)"
              stroke="#38bdf8"
              strokeWidth={1.5 * invZoom}
            />
            {quad.map((pt, idx) => (
              <circle
                key={`persp-${idx}`}
                cx={pt.x}
                cy={pt.y}
                r={6.5 * invZoom}
                fill="#ffffff"
                stroke="#0284c7"
                strokeWidth={2 * invZoom}
                className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-grab'}
                onPointerDown={(e) => {
                  const basePt = { ...pt };
                  startPointerDrag(e, (dx, dy) => {
                    updateAndSync((prev) => {
                      const cur = [...(prev.perspectiveQuad ?? quad)] as [
                        Point2D,
                        Point2D,
                        Point2D,
                        Point2D,
                      ];
                      cur[idx] = { x: basePt.x + dx, y: basePt.y + dy };
                      return { ...prev, perspectiveQuad: cur };
                    });
                  });
                }}
              />
            ))}
          </g>
        )}

        {mode === 'mesh' && meshPoints.length > 0 && (
          <g>
            {meshPoints.map((row, r) =>
              row.slice(0, -1).map((a, c) => {
                const b = row[c + 1];
                return (
                  <line
                    key={`mh-${r}-${c}`}
                    x1={a.x}
                    y1={a.y}
                    x2={b.x}
                    y2={b.y}
                    stroke="#38bdf8"
                    strokeOpacity={0.8}
                    strokeWidth={1.25 * invZoom}
                  />
                );
              })
            )}
            {meshPoints.slice(0, -1).map((row, r) =>
              row.map((a, c) => {
                const b = meshPoints[r + 1][c];
                return (
                  <line
                    key={`mv-${r}-${c}`}
                    x1={a.x}
                    y1={a.y}
                    x2={b.x}
                    y2={b.y}
                    stroke="#38bdf8"
                    strokeOpacity={0.8}
                    strokeWidth={1.25 * invZoom}
                  />
                );
              })
            )}
            {meshPoints.map((row, r) =>
              row.map((pt, c) => (
                <circle
                  key={`mp-${r}-${c}`}
                  cx={pt.x}
                  cy={pt.y}
                  r={5.5 * invZoom}
                  fill="#ffffff"
                  stroke="#0284c7"
                  strokeWidth={1.75 * invZoom}
                  className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-grab'}
                  onPointerDown={(e) => {
                    const base = { ...pt };
                    startPointerDrag(e, (dx, dy) => {
                      updateAndSync((prev) => {
                        const nextGrid = (prev.meshPoints ?? meshPoints).map((rr, ri) =>
                          ri === r
                            ? rr.map((cc, ci) =>
                                ci === c ? { x: base.x + dx, y: base.y + dy } : cc
                              )
                            : rr
                        );
                        return { ...prev, meshPoints: nextGrid };
                      });
                    });
                  }}
                />
              ))
            )}
          </g>
        )}

        {mode === 'puppet' && (
          <g>
            <polygon
              points={affineQuad.map((p) => `${p.x},${p.y}`).join(' ')}
              fill="none"
              stroke="#38bdf8"
              strokeOpacity={0.45}
              strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
              strokeWidth={1 * invZoom}
            />
            {puppetPins.map((pin) => {
              const isSelected = session.puppet?.selectedPinId === pin.id;
              return (
                <circle
                  key={pin.id}
                  cx={pin.x}
                  cy={pin.y}
                  r={(isSelected ? 7.5 : 6) * invZoom}
                  fill={isSelected ? '#f59e0b' : '#fbbf24'}
                  stroke="#0f172a"
                  strokeWidth={2 * invZoom}
                  className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-grab'}
                  onContextMenu={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    updateAndSync((prev) =>
                      prev.puppet
                        ? {
                            ...prev,
                            puppet: {
                              ...prev.puppet,
                              pins: prev.puppet.pins.filter((p) => p.id !== pin.id),
                              selectedPinId: null,
                            },
                          }
                        : prev
                    );
                  }}
                  onPointerDown={(e) => {
                    if (e.button === 2) return;
                    const base = { x: pin.x, y: pin.y, rot: pin.rotation ?? 0 };
                    const isRot = e.altKey;
                    updateAndSync((prev) =>
                      prev.puppet ? { ...prev, puppet: { ...prev.puppet, selectedPinId: pin.id } } : prev
                    );
                    startPointerDrag(e, (dx, dy) => {
                      updateAndSync((prev) => {
                        if (!prev.puppet) return prev;
                        return {
                          ...prev,
                          puppet: {
                            ...prev.puppet,
                            pins: prev.puppet.pins.map((p) =>
                              p.id === pin.id
                                ? isRot
                                  ? { ...p, rotation: base.rot + dx * 0.02 }
                                  : { ...p, x: base.x + dx, y: base.y + dy }
                                : p
                            ),
                          },
                        };
                      });
                    });
                  }}
                />
              );
            })}
          </g>
        )}

        {mode === 'cage' && (
          <g>
            {cagePoints.length >= 2 && (
              <polyline
                points={
                  (cageClosed ? [...cagePoints, cagePoints[0]] : cagePoints)
                    .map((p) => `${p.x},${p.y}`)
                    .join(' ')
                }
                fill={cageClosed ? 'rgba(56, 189, 248, 0.05)' : 'none'}
                stroke="#38bdf8"
                strokeWidth={1.5 * invZoom}
              />
            )}
            {cagePoints.map((pt, idx) => (
              <circle
                key={pt.id}
                cx={pt.x}
                cy={pt.y}
                r={6 * invZoom}
                fill={idx === 0 && !cageClosed ? '#22c55e' : '#ffffff'}
                stroke="#0284c7"
                strokeWidth={2 * invZoom}
                className={isSpaceDown ? 'pointer-events-none' : 'pointer-events-auto cursor-grab'}
                onPointerDown={(e) => {
                  if (!cageClosed && idx === 0 && cagePoints.length >= 3) {
                    e.stopPropagation();
                    updateAndSync((prev) =>
                      prev.cage ? { ...prev, cage: { ...prev.cage, phase: 'deform', closed: true } } : prev
                    );
                    return;
                  }
                  const base = { x: pt.x, y: pt.y };
                  startPointerDrag(e, (dx, dy) => {
                    updateAndSync((prev) => {
                      if (!prev.cage) return prev;
                      return {
                        ...prev,
                        cage: {
                          ...prev.cage,
                          points: prev.cage.points.map((p) =>
                            p.id === pt.id
                              ? cageClosed
                                ? { ...p, x: base.x + dx, y: base.y + dy }
                                : { ...p, x: base.x + dx, y: base.y + dy, restX: base.x + dx, restY: base.y + dy }
                              : p
                          ),
                        },
                      };
                    });
                  });
                }}
              />
            ))}
          </g>
        )}
      </svg>

      {/* Floating Transform Mode & Action Toolbar */}
      <div
        data-native-occluder="true"
        onPointerDown={(e) => e.stopPropagation()}
        className="absolute z-45 pointer-events-auto flex items-center gap-1 px-2 py-1 rounded-ui-md bg-ui-floating border border-ui-default shadow-ui-floating text-[11px] text-ui-primary whitespace-nowrap"
        style={{
          left: `${toolbarBounds.minX}px`,
          top: `${Math.max(8, toolbarBounds.minY - 52 * invZoom)}px`,
          transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,
          transformOrigin: 'top left',
        }}
      >
        {modes.map((m) => (
          <button
            key={m.id}
            type="button"
            onClick={() => handleSwitchMode(m.id)}
            className={`px-1.5 py-0.5 rounded-ui-xs transition-colors cursor-pointer ${
              mode === m.id
                ? 'bg-ui-accent text-ui-accent-contrast font-medium'
                : 'text-ui-secondary hover:bg-ui-control-hover hover:text-ui-primary'
            }`}
          >
            {m.label}
          </button>
        ))}

        <div className="w-px h-4 bg-ui-subtle mx-0.5" />

        {mode === 'puppet' && session.puppet?.selectedPinId && (
          <>
            <button
              type="button"
              title={t('Raise Pin Depth')}
              onClick={() =>
                updateAndSync((prev) =>
                  prev.puppet
                    ? {
                        ...prev,
                        puppet: {
                          ...prev.puppet,
                          pins: prev.puppet.pins.map((p) =>
                            p.id === prev.puppet?.selectedPinId
                              ? { ...p, depth: (p.depth ?? 0) + 1 }
                              : p
                          ),
                        },
                      }
                    : prev
                )
              }
              className="p-1 rounded-ui-xs hover:bg-ui-control-hover cursor-pointer"
            >
              <ArrowUp className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              title={t('Lower Pin Depth')}
              onClick={() =>
                updateAndSync((prev) =>
                  prev.puppet
                    ? {
                        ...prev,
                        puppet: {
                          ...prev.puppet,
                          pins: prev.puppet.pins.map((p) =>
                            p.id === prev.puppet?.selectedPinId
                              ? { ...p, depth: (p.depth ?? 0) - 1 }
                              : p
                          ),
                        },
                      }
                    : prev
                )
              }
              className="p-1 rounded-ui-xs hover:bg-ui-control-hover cursor-pointer"
            >
              <ArrowDown className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              title={t('Remove Selected Pin')}
              onClick={() =>
                updateAndSync((prev) =>
                  prev.puppet
                    ? {
                        ...prev,
                        puppet: {
                          ...prev.puppet,
                          pins: prev.puppet.pins.filter((p) => p.id !== prev.puppet?.selectedPinId),
                          selectedPinId: null,
                        },
                      }
                    : prev
                )
              }
              className="p-1 rounded-ui-xs hover:bg-ui-danger/15 hover:text-ui-danger cursor-pointer"
            >
              <Trash2 className="w-3.5 h-3.5" />
            </button>
          </>
        )}

        <button
          type="button"
          title={t('Flip Horizontal')}
          onClick={() => handleFlip('h')}
          className="p-1 rounded-ui-xs hover:bg-ui-control-hover cursor-pointer"
        >
          <FlipHorizontal className="w-3.5 h-3.5" />
        </button>
        <button
          type="button"
          title={t('Flip Vertical')}
          onClick={() => handleFlip('v')}
          className="p-1 rounded-ui-xs hover:bg-ui-control-hover cursor-pointer"
        >
          <FlipVertical className="w-3.5 h-3.5" />
        </button>
        <button
          type="button"
          title={t('Reset Transform')}
          onClick={handleReset}
          className="p-1 rounded-ui-xs hover:bg-ui-control-hover cursor-pointer"
        >
          <RotateCcw className="w-3.5 h-3.5" />
        </button>

        <div className="w-px h-4 bg-ui-subtle mx-0.5" />

        <button
          type="button"
          onClick={onApply}
          className="px-2 py-0.5 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 flex items-center gap-1 font-medium cursor-pointer"
        >
          <Check className="w-3.5 h-3.5" />
          <span>{t('Apply')}</span>
        </button>
        <button
          type="button"
          onClick={onCancel}
          className="px-2 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle flex items-center gap-1 cursor-pointer"
        >
          <X className="w-3.5 h-3.5" />
          <span>{t('Cancel')}</span>
        </button>
      </div>
    </div>
  );
};