A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.
TypeScript animationcartoonclip-studio-paintcollaborativedesktop-appdigital-paintingdrawing-appillustrationmangamultiplayeropen-sourcerusttaurithreejswebglwebtoon
1.0.2
sora0fdd4135daaf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d58992..05f4279 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,35 @@# Changelog+## v1.0.2++### New+- Added Auto-Reconnect, Roles, and Access Rights in the Collaborative Room+- Implemented all 28 blend modes (17 existing + 11 missing: vivid-light, linear-light, pin-light, hard-mix, subtract, darker-color, lighter-color, hue, saturation, color, luminosity) with lossless PSD/PSB round-trip and deduplicated GLSL shaders+- Added a Natural Paint Engine with a dedicated Natural Paint brush category+- Added Cut (`Ctrl+X`), Copy (`Ctrl+C`), Paste (`Ctrl+V`), and Move to New Layer (`Ctrl+Shift+J`) for Lasso and all selection tools to extract selected regions from a single layer into a new layer+- Added Delete Section and Delete Outside Section functions to the Lasso tool and all selection tools+- Added an interactive 3D Sphere Color Picker inside the Color Panel (alongside Color Wheel and Color Sliders) with painterly shadow, base, and highlight lighting slots+- Added Pin / Unpin support to detach the 3D Sphere Color Picker into a non-blocking, draggable, and resizable floating palette anywhere over the workspace+- Added exit confirmation dialog when closing Ink Studio, with per-canvas save prompts for one or multiple unsaved documents+- Added Gradient Tool (`Shift+G`) supporting Linear, Radial, and interactive bicubic Mesh Gradients with multi-stop RGBA editing, presets, repeat/reflect modes, blend modes, and 4x4 Bayer dithering+- Added Retouch Tool (`S`) with Smudge (premultiplied pickup + Finger Painting), Blur, Dodge, Burn (Shadows/Midtones/Highlights + Protect Tones), and Clone Stamp (`Alt+Click` origin, aligned mode, active/all-visible sampling)+- Added Bezier Pen Tool (`P`) with true cubic Bezier curves, interactive anchor/tangent handles, symmetry breaking (`Alt+Drag`), de Casteljau curve splitting, closed fills, and direct editing of `VectorStroke` Bezier paths++### Improvements+- Reworked a new canvas menu and made it more user-friendly+- Third-Party optimization of engines+- Removed duplicate formats and old branding (`.sora`)+- Improved optimization and synchronization within collaborative drawing+- Implemented full operation and layer-tree synchronization in collaborative mode+- Refactored `server.rs` from a dumb relay into a single-lock linearized stateful room authority, with matching client wiring+- Heavy parsing, pixel math, compression, and pen input now run in Rust over raw binary IPC+- Fixed a quality issue that occurred when using Mesh Warp or Liquify+- Merged duplicate floating selection toolbars into a single unified selection bar+- Upgraded `VectorStroke` and `VectorKnot` to natively store, bound (analytical cubic extrema), render (`bezierCurveTo`), pinch, and serialize cubic Bezier handles alongside Catmull-Rom strokes++### Bug Fixes+- Fixed bug with hand cursor stays on while drawing+## v1.0.1### Newdiff --git a/index.html b/index.htmlindex 1237d41..8712af3 100644--- a/index.html+++ b/index.html@@ -5,7 +5,7 @@<link rel="icon" type="image/x-icon" href="/favicon.ico" /><link rel="icon" type="image/png" href="/app-icon.png" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>Ink Studio - Collaborative Drawing Studio</title>+ <title>Ink Studio</title></head><body>diff --git a/package-lock.json b/package-lock.jsonindex e7f0889..cce0407 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "ink-studio",- "version": "1.0.1",+ "version": "1.0.2","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "ink-studio",- "version": "1.0.1",+ "version": "1.0.2","license": "GPL-3.0","dependencies": {"@tailwindcss/vite": "^4.3.3",@@ -14,14 +14,12 @@"@tauri-apps/plugin-opener": "^2","@tauri-apps/plugin-process": "^2.4.0","@tauri-apps/plugin-updater": "^2.14.1",- "@types/sql.js": "^1.4.11","@types/three": "^0.186.0","ag-psd": "^31.0.2","fflate": "^0.8.3","lucide-react": "^1.48.0","react": "^19.1.0","react-dom": "^19.1.0",- "sql.js": "^1.14.2","tailwindcss": "^4.3.3","three": "^0.186.1"},@@ -582,6 +580,66 @@"node": ">=14.0.0"}},+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {+ "version": "1.11.1",+ "inBundle": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@emnapi/wasi-threads": "1.2.2",+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {+ "version": "1.11.1",+ "inBundle": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {+ "version": "1.2.2",+ "inBundle": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {+ "version": "1.1.4",+ "inBundle": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "@tybys/wasm-util": "^0.10.1"+ },+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/Brooooooklyn"+ },+ "peerDependencies": {+ "@emnapi/core": "^1.7.1",+ "@emnapi/runtime": "^1.7.1"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {+ "version": "0.10.2",+ "inBundle": true,+ "license": "MIT",+ "optional": true,+ "dependencies": {+ "tslib": "^2.4.0"+ }+ },+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {+ "version": "2.8.1",+ "inBundle": true,+ "license": "0BSD",+ "optional": true+ },"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {"version": "4.3.3","resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",@@ -921,12 +979,6 @@"dev": true,"license": "MIT"},- "node_modules/@types/emscripten": {- "version": "1.41.6",- "resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.6.tgz",- "integrity": "sha512-uN+9i8bFT5CUcZfyIEYDrSueACEyKGbUs5kC/72DGlZZoinh84sJfVV0i8UOJD1asdzkvLPBRrKs41kZ8MdEXg==",- "license": "MIT"- },"node_modules/@types/estree": {"version": "1.0.9","resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",@@ -934,15 +986,6 @@"dev": true,"license": "MIT"},- "node_modules/@types/node": {- "version": "26.6.2",- "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.2.tgz",- "integrity": "sha512-X1P21scMv4zGKLYqjdGjaKa7COa0RKVYYZZN/NfvLQ1JegxFhdhpZG/Lyn8AXx6CDUavKAd11v6BvfpkDByK8g==",- "license": "MIT",- "dependencies": {- "undici-types": "~8.9.0"- }- },"node_modules/@types/react": {"version": "19.3.0","resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",@@ -963,16 +1006,6 @@"@types/react": "^19.3.0"}},- "node_modules/@types/sql.js": {- "version": "1.4.11",- "resolved": "https://registry.npmjs.org/@types/sql.js/-/sql.js-1.4.11.tgz",- "integrity": "sha512-QXIx38p2ZThJaK9vP5ZdqdlRe1FG9I8SmCZOS7FHfB/2qPAjZwkL7/vlfPg6N/oWHuuOaGg/P/IRwfP2W0kWVQ==",- "license": "MIT",- "dependencies": {- "@types/emscripten": "*",- "@types/node": "*"- }- },"node_modules/@types/stats.js": {"version": "0.17.4","resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",@@ -1673,12 +1706,6 @@"node": ">=0.10.0"}},- "node_modules/sql.js": {- "version": "1.14.2",- "resolved": "https://registry.npmjs.org/sql.js/-/sql.js-1.14.2.tgz",- "integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==",- "license": "MIT"- },"node_modules/std-env": {"version": "4.2.0","resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",@@ -1761,12 +1788,6 @@"node": ">=14.17"}},- "node_modules/undici-types": {- "version": "8.9.0",- "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",- "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",- "license": "MIT"- },"node_modules/vite": {"version": "8.3.1","resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",diff --git a/package.json b/package.jsonindex ec6979d..b928fc0 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "ink-studio","private": true,- "version": "1.0.1",+ "version": "1.0.2","description": "Collaborative Drawing Studio","author": "Sora","license": "GPL-3.0",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 1013056..44d2055 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2021,7 +2021,7 @@ dependencies = [[[package]]name = "ink-studio"-version = "1.0.1"+version = "1.0.2"dependencies = ["axum","flate2",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 1cad739..36b139c 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "ink-studio"-version = "1.0.1"+version = "1.0.2"description = "Collaborative Drawing Studio"authors = ["Sora"]license = "GPL-3.0"diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 827c9ea..7020463 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -9,6 +9,7 @@"updater:default","process:allow-restart","core:window:allow-close",+ "core:window:allow-destroy","core:window:allow-minimize","core:window:allow-toggle-maximize","core:window:allow-start-dragging",diff --git a/src-tauri/src/raster_ops.rs b/src-tauri/src/raster_ops.rsindex c362e88..39b0351 100644--- a/src-tauri/src/raster_ops.rs+++ b/src-tauri/src/raster_ops.rs@@ -924,8 +924,10 @@ pub fn liquify_step_rgba(-p.strength * 0.45};let row_bytes = p.roi_w * 4;- let max_sx = (p.roi_w as f32) - 1.0001;- let max_sy = (p.roi_h as f32) - 1.0001;+ let max_x_idx = p.roi_w.saturating_sub(1);+ let max_y_idx = p.roi_h.saturating_sub(1);+ let max_sx = max_x_idx as f32;+ let max_sy = max_y_idx as f32;dst.par_chunks_exact_mut(row_bytes).enumerate()@@ -966,17 +968,33 @@ pub fn liquify_step_rgba(let alpha = (p.strength * weight * 0.35).min(1.0);let inv_a = 1.0 - alpha;let ii = ry * row_bytes + di;- dst_row[di] =- (dst_row[di] as f32 * inv_a + init[ii] as f32 * alpha).round() as u8;- dst_row[di + 1] =- (dst_row[di + 1] as f32 * inv_a + init[ii + 1] as f32 * alpha).round()- as u8;- dst_row[di + 2] =- (dst_row[di + 2] as f32 * inv_a + init[ii + 2] as f32 * alpha).round()- as u8;- dst_row[di + 3] =- (dst_row[di + 3] as f32 * inv_a + init[ii + 3] as f32 * alpha).round()- as u8;+ let da = dst_row[di + 3] as f32;+ let ta = init[ii + 3] as f32;+ let out_a = da * inv_a + ta * alpha;+ if out_a <= 0.5 {+ dst_row[di] = 0;+ dst_row[di + 1] = 0;+ dst_row[di + 2] = 0;+ dst_row[di + 3] = 0;+ } else {+ let inv_out = 1.0 / out_a;+ dst_row[di] = ((dst_row[di] as f32 * da * inv_a+ + init[ii] as f32 * ta * alpha)+ * inv_out)+ .round()+ .clamp(0.0, 255.0) as u8;+ dst_row[di + 1] = ((dst_row[di + 1] as f32 * da * inv_a+ + init[ii + 1] as f32 * ta * alpha)+ * inv_out)+ .round()+ .clamp(0.0, 255.0) as u8;+ dst_row[di + 2] = ((dst_row[di + 2] as f32 * da * inv_a+ + init[ii + 2] as f32 * ta * alpha)+ * inv_out)+ .round()+ .clamp(0.0, 255.0) as u8;+ dst_row[di + 3] = out_a.round().clamp(0.0, 255.0) as u8;+ }}continue;}@@ -1011,43 +1029,87 @@ pub fn liquify_step_rgba(let lsx = (src_x - p.min_x).clamp(0.0, max_sx);let lsy = (src_y - p.min_y).clamp(0.0, max_sy);- let x0 = lsx as usize;- let y0 = lsy as usize;- let x1 = (x0 + 1).min(p.roi_w - 1);- let y1 = (y0 + 1).min(p.roi_h - 1);+ let x0 = lsx.floor() as usize;+ let y0 = lsy.floor() as usize;let fx = lsx - x0 as f32;let fy = lsy - y0 as f32;- let w00 = (1.0 - fx) * (1.0 - fy);- let w10 = fx * (1.0 - fy);- let w01 = (1.0 - fx) * fy;- let w11 = fx * fy;-- let i00 = (y0 * p.roi_w + x0) * 4;- let i10 = (y0 * p.roi_w + x1) * 4;- let i01 = (y1 * p.roi_w + x0) * 4;- let i11 = (y1 * p.roi_w + x1) * 4;-- dst_row[di] = (w00 * src_roi[i00] as f32- + w10 * src_roi[i10] as f32- + w01 * src_roi[i01] as f32- + w11 * src_roi[i11] as f32)- .round() as u8;- dst_row[di + 1] = (w00 * src_roi[i00 + 1] as f32- + w10 * src_roi[i10 + 1] as f32- + w01 * src_roi[i01 + 1] as f32- + w11 * src_roi[i11 + 1] as f32)- .round() as u8;- dst_row[di + 2] = (w00 * src_roi[i00 + 2] as f32- + w10 * src_roi[i10 + 2] as f32- + w01 * src_roi[i01 + 2] as f32- + w11 * src_roi[i11 + 2] as f32)- .round() as u8;- dst_row[di + 3] = (w00 * src_roi[i00 + 3] as f32- + w10 * src_roi[i10 + 3] as f32- + w01 * src_roi[i01 + 3] as f32- + w11 * src_roi[i11 + 3] as f32)- .round() as u8;+ if fx < 1e-5 && fy < 1e-5 {+ let off = (y0 * p.roi_w + x0) * 4;+ dst_row[di] = src_roi[off];+ dst_row[di + 1] = src_roi[off + 1];+ dst_row[di + 2] = src_roi[off + 2];+ dst_row[di + 3] = src_roi[off + 3];+ continue;+ }++ let fx2 = fx * fx;+ let fx3 = fx2 * fx;+ let wx = [+ -0.5 * fx + fx2 - 0.5 * fx3,+ 1.0 - 2.5 * fx2 + 1.5 * fx3,+ 0.5 * fx + 2.0 * fx2 - 1.5 * fx3,+ -0.5 * fx2 + 0.5 * fx3,+ ];++ let fy2 = fy * fy;+ let fy3 = fy2 * fy;+ let wy = [+ -0.5 * fy + fy2 - 0.5 * fy3,+ 1.0 - 2.5 * fy2 + 1.5 * fy3,+ 0.5 * fy + 2.0 * fy2 - 1.5 * fy3,+ -0.5 * fy2 + 0.5 * fy3,+ ];++ let ix = [+ x0.saturating_sub(1),+ x0,+ (x0 + 1).min(max_x_idx),+ (x0 + 2).min(max_x_idx),+ ];++ let mut sum_pr = 0.0f32;+ let mut sum_pg = 0.0f32;+ let mut sum_pb = 0.0f32;+ let mut sum_a = 0.0f32;++ for r in 0..4usize {+ let iy = (y0 + r).saturating_sub(1).min(max_y_idx);+ let row_base = iy * p.roi_w;+ let mut r_pr = 0.0f32;+ let mut r_pg = 0.0f32;+ let mut r_pb = 0.0f32;+ let mut r_a = 0.0f32;+ for c in 0..4usize {+ let off = (row_base + ix[c]) * 4;+ let a = src_roi[off + 3];+ if a == 0 {+ continue;+ }+ let wa = wx[c] * a as f32;+ r_pr += wa * src_roi[off] as f32;+ r_pg += wa * src_roi[off + 1] as f32;+ r_pb += wa * src_roi[off + 2] as f32;+ r_a += wa;+ }+ sum_pr += wy[r] * r_pr;+ sum_pg += wy[r] * r_pg;+ sum_pb += wy[r] * r_pb;+ sum_a += wy[r] * r_a;+ }++ if sum_a <= 0.5 {+ dst_row[di] = 0;+ dst_row[di + 1] = 0;+ dst_row[di + 2] = 0;+ dst_row[di + 3] = 0;+ } else {+ let inv_a = 1.0 / sum_a;+ dst_row[di] = (sum_pr * inv_a).round().clamp(0.0, 255.0) as u8;+ dst_row[di + 1] = (sum_pg * inv_a).round().clamp(0.0, 255.0) as u8;+ dst_row[di + 2] = (sum_pb * inv_a).round().clamp(0.0, 255.0) as u8;+ dst_row[di + 3] = sum_a.round().clamp(0.0, 255.0) as u8;+ }}});@@ -1308,9 +1370,17 @@ mod tests {},).unwrap();- // Pixel should have moved right (+x)+ // Pixel should have moved right (+x) and retained pure red without dark alpha fringinglet shifted = (16 * w + 19) * 4;assert!(out[shifted] > 0 || out[(16 * w + 18) * 4] > 0);+ for x in 14..24 {+ let off = (16 * w + x) * 4;+ if out[off + 3] > 10 {+ assert!(out[off] >= 250, "Expected pure red without dark halo, got {}", out[off]);+ assert_eq!(out[off + 1], 0);+ assert_eq!(out[off + 2], 0);+ }+ }}#[test]diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 3d60b5e..33186ee 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "Ink Studio",- "version": "1.0.1",+ "version": "1.0.2","identifier": "com.inkstudio.app","build": {"beforeDevCommand": "npm run dev",@@ -13,7 +13,7 @@"windows": [{"label": "main",- "title": "Ink Studio - Collaborative Drawing Studio",+ "title": "Ink Studio","width": 1280,"height": 840,"minWidth": 900,diff --git a/src/App.tsx b/src/App.tsxindex d2aa8fd..5a3b669 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -1,5 +1,5 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { AnimationTimeline, BlendMode, ExpressionColor, FilterType, LayerItem } from './types/editor';+import { AnimationTimeline, BlendMode, ExpressionColor, FilterType, LayerItem, LayerTreeDelta } from './types/editor';import {createDefaultAnimationTimeline,removeFrameCel,@@ -16,6 +16,9 @@ import { updaterService } from './services/updaterService';import { useCanvasDrawing } from './hooks/useCanvasDrawing';import {PushHistoryStepFn,+ useGradientTool,+ usePenTool,+ useRetouchTool,useSelectionTools,useShapeAndFillTools,useVectorDrawing,@@ -94,7 +97,9 @@ export function App() {documentStoreActions.setAnimationTimeline(timeline);if (activeDocumentId) {documentStoreActions.setDocuments((docs) =>- docs.map((d) => (d.id === activeDocumentId ? { ...d, animation: timeline } : d))+ docs.map((d) =>+ d.id === activeDocumentId ? { ...d, animation: timeline, isDirty: true } : d+ ));}},@@ -209,6 +214,8 @@ export function App() {updateLayerThumbnail: layerMgr.updateLayerThumbnail,pushHistoryStep: stablePushHistoryStep,showToast,+ copySelectionToClipboard: layerMgr.copySelectionToClipboard,+ createLayerFromTileSnapshot: layerMgr.createLayerFromTileSnapshot,});const handleCollabStrokeStart = useCallback(@@ -288,6 +295,7 @@ export function App() {: true,layers: hasOpenDocument ? layerMgr.layers : [],onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,+ onApplyLayerTreeDelta: layerMgr.applyLayerTreeDelta,isMaskMode: activeEditTarget === 'mask',onUpdateMaskThumbnail: layerMgr.updateMaskThumbnail,draftCanvasRef,@@ -383,6 +391,55 @@ export function App() {showToast,});+ // Modular Gradient Tool (Linear / Radial / Mesh)+ const gradientTools = useGradientTool({+ dimensions,+ colorMode,+ activeLayer: layerMgr.activeLayer,+ activeLayerId: layerMgr.activeLayerId,+ selection: selectionTools.selection,+ zoomRef: nav.navigation.zoomRef,+ flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,+ getCanvasCoords,+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,+ pushHistoryStep: drawing.pushHistoryStep,+ showToast,+ });++ // Modular Retouch Tools (Smudge / Blur / Dodge / Burn / Clone Stamp)+ const retouchTools = useRetouchTool({+ dimensions,+ colorMode,+ layers: layerMgr.layers,+ activeLayer: layerMgr.activeLayer,+ activeLayerId: layerMgr.activeLayerId,+ selection: selectionTools.selection,+ flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,+ getEffectiveOpacity: layerMgr.getEffectiveOpacity,+ getCanvasCoords,+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,+ pushHistoryStep: drawing.pushHistoryStep,+ showToast,+ });++ // Modular True Cubic Bézier Pen Tool+ const penTools = usePenTool({+ dimensions,+ colorMode,+ activeLayer: layerMgr.activeLayer,+ activeLayerId: layerMgr.activeLayerId,+ selection: selectionTools.selection,+ zoomRef: nav.navigation.zoomRef,+ flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,+ getCanvasCoords,+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,+ pushHistoryStep: drawing.pushHistoryStep,+ showToast,+ });+// Tonal, Filter, Adjustment, Styles, Screentone & Expression Color Actionsconst tonalActions = useTonalAndFilterActions({hasOpenDocument,@@ -424,6 +481,7 @@ export function App() {resizeCanvas: layerMgr.resizeCanvas,copyLayer: layerMgr.copyLayer,pasteLayer: layerMgr.pasteLayer,+ onDeselectAfterPaste: selectionTools.handleDeselect,deleteLayer: collab.handleDeleteLayer,pasteLayerFromFile: layerMgr.pasteLayerFromFile,resetZoomAndCenter: nav.resetZoomAndCenter,@@ -437,8 +495,9 @@ export function App() {layerMgr.setLayers((prev) =>prev.map((l) => (l.id === layerId ? { ...l, isReference: !l.isReference } : l)));+ documentStoreActions.markDocumentDirty(activeDocumentId, true);},- [layerMgr.setLayers]+ [activeDocumentId, layerMgr.setLayers]);const handleMergeDown = useCallback(() => {@@ -453,13 +512,27 @@ export function App() {}, [layerMgr.mergeDown, activeDocumentId, showToast]);const handleAddDefaultFrameFolder = useCallback(() => {+ drawing.flushPendingHistoryTasks();const dpi = dimensions.dpi ?? 600;const defaultFrame = createDefaultPageFrame('', dimensions.width, dimensions.height, dpi, 15);- const { folder } = layerMgr.createFrameFolder([defaultFrame], undefined, true);- drawing.pushHistoryStep('frame', 'New Frame Border Folder', null, null, folder.id);+ const { folder, layerTreeDelta } = layerMgr.createFrameFolder([defaultFrame], undefined, true);+ drawing.pushHistoryStep(+ 'frame',+ 'New Frame Border Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );autoActionStoreActions.recordStep('create-frame-folder', 'New Frame Border Folder');showToast('Created Frame Border Folder');- }, [dimensions, layerMgr.createFrameFolder, drawing.pushHistoryStep, showToast]);+ }, [dimensions, layerMgr.createFrameFolder, drawing.flushPendingHistoryTasks, drawing.pushHistoryStep, showToast]);const handleRasterizeLayer = useCallback((layerId: string) => {@@ -547,6 +620,7 @@ export function App() {let currentLayerId = layerMgr.activeLayerId;let groupStartSnapshot: Map<string, TileSnapshotEntry> | null = null;let groupTargetLayerId = currentLayerId;+ let groupLayerTreeDelta: LayerTreeDelta | undefined;const ctx: AutoActionExecutionContext = {getActiveLayerId: () => currentLayerId,@@ -563,7 +637,22 @@ export function App() {createFrameFolder: (name) => {const dpi = dimensions.dpi ?? 600;const df = createDefaultPageFrame('', dimensions.width, dimensions.height, dpi, 15);- const { folder } = layerMgr.createFrameFolder([df], name, true);+ const { folder, layerTreeDelta } = layerMgr.createFrameFolder([df], name, true);+ if (!groupLayerTreeDelta) {+ groupLayerTreeDelta = {+ addedLayers: [...(layerTreeDelta.addedLayers || [])],+ insertBeforeLayerId: layerTreeDelta.insertBeforeLayerId,+ insertIndex: layerTreeDelta.insertIndex,+ beforeActiveLayerId: layerTreeDelta.beforeActiveLayerId,+ afterActiveLayerId: layerTreeDelta.afterActiveLayerId,+ };+ } else {+ groupLayerTreeDelta.addedLayers = [+ ...(layerTreeDelta.addedLayers || []),+ ...(groupLayerTreeDelta.addedLayers || []),+ ];+ groupLayerTreeDelta.afterActiveLayerId = layerTreeDelta.afterActiveLayerId;+ }currentLayerId = folder.id;return folder.id;},@@ -642,7 +731,12 @@ export function App() {null,targetId,undefined,- tileDeltas && tileDeltas.length > 0 ? tileDeltas : undefined+ tileDeltas && tileDeltas.length > 0 ? tileDeltas : undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ groupLayerTreeDelta);},};@@ -770,6 +864,21 @@ export function App() {return;}+ if (tool === 'gradient') {+ gradientTools.handleGradientPointerDown(e, pt);+ return;+ }++ if (tool === 'retouch') {+ retouchTools.handleRetouchPointerDown(e, pt);+ return;+ }++ if (tool === 'pen') {+ penTools.handlePenPointerDown(e, pt);+ return;+ }+if (selectionTools.handleSelectionPointerDown(e, pt)) return;shapeFillTools.handleShapeFillPointerDown(e, pt);},@@ -779,6 +888,9 @@ export function App() {selectionTools,drawing,vectorTools,+ gradientTools,+ retouchTools,+ penTools,shapeFillTools,collab.isConnected,collab.isReconnecting,@@ -805,10 +917,22 @@ export function App() {vectorTools.handleVectorEditPointerMove(e);return;}+ if (tool === 'gradient') {+ gradientTools.handleGradientPointerMove(e);+ return;+ }+ if (tool === 'retouch') {+ retouchTools.handleRetouchPointerMove(e);+ return;+ }+ if (tool === 'pen') {+ penTools.handlePenPointerMove(e);+ return;+ }if (shapeFillTools.handleShapeFillPointerMove(e)) return;selectionTools.handleSelectionPointerMove(getCanvasCoords(e));},- [drawing, vectorTools, shapeFillTools, selectionTools, getCanvasCoords]+ [drawing, vectorTools, gradientTools, retouchTools, penTools, shapeFillTools, selectionTools, getCanvasCoords]);const handlePointerUp = useCallback(@@ -823,10 +947,22 @@ export function App() {return;}const pt = getCanvasCoords(e);+ if (tool === 'gradient') {+ gradientTools.handleGradientPointerUp(e, pt);+ return;+ }+ if (tool === 'retouch') {+ retouchTools.handleRetouchPointerUp(e);+ return;+ }+ if (tool === 'pen') {+ penTools.handlePenPointerUp(e);+ return;+ }if (selectionTools.handleSelectionPointerUp(pt)) return;shapeFillTools.handleShapeFillPointerUp(e, pt);},- [drawing, vectorTools, getCanvasCoords, selectionTools, shapeFillTools]+ [drawing, vectorTools, gradientTools, retouchTools, penTools, getCanvasCoords, selectionTools, shapeFillTools]);// Memoized Top Menu Bar Sections (independent of brush size & color)@@ -854,6 +990,11 @@ export function App() {handleSave: docLifecycle.handleSave,handleSaveAs: docLifecycle.handleSaveAs,handleExportImage: docLifecycle.handleExportImage,+ handleCutSelection: selectionTools.handleCutSelection,+ handleCopySelection: selectionTools.handleCopySelection,+ handleMoveSelectionToNewLayer: selectionTools.handleMoveSelectionToNewLayer,+ handleClearSelection: selectionTools.handleClearSelection,+ handleDeleteOutsideSelection: selectionTools.handleDeleteOutsideSelection,handleCopySelectedLayer: docLifecycle.handleCopySelectedLayer,handlePasteSelectedLayer: docLifecycle.handlePasteSelectedLayer,handleTriggerPasteFromFile: docLifecycle.handleTriggerPasteFromFile,@@ -914,6 +1055,7 @@ export function App() {navigation: nav.navigation,isSpaceDown: nav.isSpaceDown,isShiftDown: nav.isShiftDown,+ heldModifierAction: nav.heldModifierAction,isRotateModifier: nav.isRotateModifier,isPanning: nav.isPanning,isRotating: nav.isRotating,@@ -949,6 +1091,11 @@ export function App() {onFillScreentone: tonalActions.handleFillScreentone,onFillColor: selectionTools.handleFillSelectionColor,onClearSelection: selectionTools.handleClearSelection,+ onDeleteOutsideSelection: selectionTools.handleDeleteOutsideSelection,+ onCutSelection: selectionTools.handleCutSelection,+ onCopySelection: selectionTools.handleCopySelection,+ onPasteSelection: docLifecycle.handlePasteSelectedLayer,+ onMoveSelectionToNewLayer: selectionTools.handleMoveSelectionToNewLayer,onInvertSelection: selectionTools.handleInvertSelection,onExpandSelection: selectionTools.handleExpandSelection,onContractSelection: selectionTools.handleContractSelection,@@ -968,6 +1115,15 @@ export function App() {onDeleteBalloon: shapeFillTools.handleDeleteBalloon,frameDragPreview: shapeFillTools.frameDragPreview,shapeDragPreview: shapeFillTools.shapeDragPreview,+ gradientDragPreview: gradientTools.gradientDragPreview,+ gradientMesh: gradientTools.gradientMesh,+ onApplyGradientMesh: gradientTools.handleApplyGradientMesh,+ onCancelGradientMesh: gradientTools.handleCancelGradientMesh,+ cloneSourceIndicator: retouchTools.cloneSourceIndicator,+ penSession: penTools.penSession,+ onCommitPenPath: penTools.handleCommitPenPath,+ onCancelPenPath: penTools.handleCancelPenPath,+ onToggleClosePenPath: penTools.handleClosePenPath,animationTimeline: activeAnimationTimeline,onUpdateAnimationTimeline: handleUpdateAnimationTimeline,onAddAnimationCel: handleAddAnimationCel,@@ -977,6 +1133,7 @@ export function App() {[nav,docLifecycle.handleViewportReady,+ docLifecycle.handlePasteSelectedLayer,drawing.isHovering,drawing.cursorPos,drawing.handlePointerEnter,@@ -1008,6 +1165,15 @@ export function App() {shapeFillTools.frameDragPreview,shapeFillTools.shapeDragPreview,shapeFillTools.handleSampleColor,+ gradientTools.gradientDragPreview,+ gradientTools.gradientMesh,+ gradientTools.handleApplyGradientMesh,+ gradientTools.handleCancelGradientMesh,+ retouchTools.cloneSourceIndicator,+ penTools.penSession,+ penTools.handleCommitPenPath,+ penTools.handleCancelPenPath,+ penTools.handleClosePenPath,handleUndo,drawing.redo,activeAnimationTimeline,@@ -1126,6 +1292,7 @@ export function App() {resetToNewCanvas={layerMgr.resetToNewCanvas}resetZoomAndCenter={nav.resetZoomAndCenter}resetHistory={drawing.resetHistory}+ onSelectDocument={docLifecycle.handleSelectDocument}/><GlobalShortcutListener@@ -1150,8 +1317,12 @@ export function App() {handleSave={docLifecycle.handleSave}handleSaveAs={docLifecycle.handleSaveAs}duplicateLayer={layerMgr.duplicateLayer}+ handleCutSelection={selectionTools.handleCutSelection}+ handleCopySelection={selectionTools.handleCopySelection}handleCopySelectedLayer={docLifecycle.handleCopySelectedLayer}handlePasteSelectedLayer={docLifecycle.handlePasteSelectedLayer}+ handleMoveSelectionToNewLayer={selectionTools.handleMoveSelectionToNewLayer}+ handleCopySelectionToNewLayer={selectionTools.handleCopySelectionToNewLayer}handleGroupSelectedLayers={collab.handleGroupSelectedLayers}handleStartTransform={selectionTools.handleStartTransform}handleSelectAll={selectionTools.handleSelectAll}@@ -1220,6 +1391,7 @@ export function App() {joinRoom={collab.joinRoom}onCaptureTimelapseNow={handleCaptureTimelapseNow}handleSave={docLifecycle.handleSave}+ handleSaveDocumentById={docLifecycle.handleSaveDocumentById}showToast={showToast}/></AppShell>diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsxindex 358a070..14ba56c 100644--- a/src/components/AppShell.tsx+++ b/src/components/AppShell.tsx@@ -10,13 +10,18 @@ import {SpeechBalloon,TransformSession,ShapeDragPreview,+ GradientDragPreview,+ GradientMeshState,+ PenPathSession,} from '../types/editor';+import type { CloneSourceIndicator } from '../hooks/drawing/useRetouchTool';import { CollabPeer } from '../types/multiplayer';import { SparseTileGrid } from '../utils/tileEngine';import { RecentDocument } from '../utils/recentDocumentsManager';import {getAccentContrastColor,hexToRgb,+ ModifierAction,resolveModernAccentColor,} from '../types/settings';import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';@@ -52,6 +57,7 @@ interface CanvasAreaContainerProps {navigation: CanvasNavigationHandle;isSpaceDown: boolean;isShiftDown: boolean;+ heldModifierAction?: ModifierAction;isRotateModifier: boolean;isPanning: boolean;isRotating: boolean;@@ -91,6 +97,11 @@ interface CanvasAreaContainerProps {onFillScreentone: () => void;onFillColor: () => void;onClearSelection: () => void;+ onDeleteOutsideSelection: () => void;+ onCutSelection: () => void;+ onCopySelection: () => void;+ onPasteSelection: () => void;+ onMoveSelectionToNewLayer: () => void;onInvertSelection: () => void;onExpandSelection: (pixels?: number) => void;onContractSelection: (pixels?: number) => void;@@ -110,6 +121,15 @@ interface CanvasAreaContainerProps {onDeleteBalloon: () => void;frameDragPreview?: FrameDragPreview | null;shapeDragPreview?: ShapeDragPreview | null;+ gradientDragPreview?: GradientDragPreview | null;+ gradientMesh?: GradientMeshState | null;+ onApplyGradientMesh?: () => void;+ onCancelGradientMesh?: () => void;+ cloneSourceIndicator?: CloneSourceIndicator | null;+ penSession?: PenPathSession | null;+ onCommitPenPath?: () => void;+ onCancelPenPath?: () => void;+ onToggleClosePenPath?: () => void;animationTimeline: AnimationTimeline | null;onUpdateAnimationTimeline: (timeline: AnimationTimeline | null) => void;onAddAnimationCel: (frameIndex: number) => void;@@ -126,6 +146,9 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propconst tool = useToolStore((s) => s.tool);const brushSettings = useToolStore((s) => s.brushSettings);const liquifySettings = useToolStore((s) => s.liquifySettings);+ const gradientSettings = useToolStore((s) => s.gradientSettings);+ const retouchSettings = useToolStore((s) => s.retouchSettings);+ const penSettings = useToolStore((s) => s.penSettings);const primaryColor = useToolStore((s) => s.primaryColor);const secondaryColor = useToolStore((s) => s.secondaryColor);@@ -199,6 +222,7 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propnavigation={props.navigation}isSpaceDown={props.isSpaceDown}isShiftDown={props.isShiftDown}+ heldModifierAction={props.heldModifierAction}isRotateModifier={props.isRotateModifier}isPanning={props.isPanning}isRotating={props.isRotating}@@ -236,6 +260,10 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proptool={tool}liquifySettings={liquifySettings}onUpdateLiquifySettings={toolStoreActions.updateLiquifySettings}+ gradientSettings={gradientSettings}+ retouchSettings={retouchSettings}+ onUpdateRetouchSettings={toolStoreActions.updateRetouchSettings}+ penSettings={penSettings}primaryColor={primaryColor}onSwapColors={toolStoreActions.swapColors}selection={props.selection}@@ -244,6 +272,11 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proponFillScreentone={props.onFillScreentone}onFillColor={props.onFillColor}onClearSelection={props.onClearSelection}+ onDeleteOutsideSelection={props.onDeleteOutsideSelection}+ onCutSelection={props.onCutSelection}+ onCopySelection={props.onCopySelection}+ onPasteSelection={props.onPasteSelection}+ onMoveSelectionToNewLayer={props.onMoveSelectionToNewLayer}onInvertSelection={props.onInvertSelection}onExpandSelection={props.onExpandSelection}onContractSelection={props.onContractSelection}@@ -275,6 +308,15 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((proponDeleteBalloon={props.onDeleteBalloon}frameDragPreview={props.frameDragPreview}shapeDragPreview={props.shapeDragPreview}+ gradientDragPreview={props.gradientDragPreview}+ gradientMesh={props.gradientMesh}+ onApplyGradientMesh={props.onApplyGradientMesh}+ onCancelGradientMesh={props.onCancelGradientMesh}+ cloneSourceIndicator={props.cloneSourceIndicator}+ penSession={props.penSession}+ onCommitPenPath={props.onCommitPenPath}+ onCancelPenPath={props.onCancelPenPath}+ onToggleClosePenPath={props.onToggleClosePenPath}secondaryColor={secondaryColor}animationTimeline={props.animationTimeline}onUpdateAnimationTimeline={props.onUpdateAnimationTimeline}@@ -962,6 +1004,12 @@ export const AppShell: React.FC<AppShellProps> = React.memo(commandHandlers={commandHandlers}onDeselect={canvasProps.onDeselect}onTransformSelection={canvasProps.onTransformSelection}+ onClearSelection={canvasProps.onClearSelection}+ onDeleteOutsideSelection={canvasProps.onDeleteOutsideSelection}+ onCutSelection={canvasProps.onCutSelection}+ onCopySelection={canvasProps.onCopySelection}+ onPasteSelection={canvasProps.onPasteSelection}+ onMoveSelectionToNewLayer={canvasProps.onMoveSelectionToNewLayer}onExpandSelection={canvasProps.onExpandSelection}onContractSelection={canvasProps.onContractSelection}onFeatherSelection={canvasProps.onFeatherSelection}diff --git a/src/components/BrushStudioModal.tsx b/src/components/BrushStudioModal.tsxnew file mode 100644index 0000000..65b4a21--- /dev/null+++ b/src/components/BrushStudioModal.tsx@@ -0,0 +1,309 @@+import React, { useState, useEffect, useCallback } from 'react';+import {+ X,+ Paintbrush,+ Spline,+ Grid3X3,+ Layers,+ Droplets,+ Sparkles,+ Sliders,+ Info,+} from 'lucide-react';+import type { BrushCategory, BrushSettings, CspBrush } from '../types/editor';+import { useToolStore, toolStoreActions } from '../stores';+import { BUILTIN_BRUSHES } from '../utils/presetBrushes';+import {+ DEFAULT_BRUSH_PRESET_ID,+ NEUTRAL_BRUSH_DEFAULTS,+ resetBrushSettingsToDefault,+ saveActivePresetId,+} from '../utils/brushPresetManager';+import {+ getCachedCustomBrushes,+ prepareBrushSettingsForCsp,+ saveCustomBrush,+ saveCustomBrushDebounced,+} from '../utils/brushStorage';+import {+ buildExportableBrush,+ exportBrushToInkbFile,+ importBrushFile,+} from '../utils/inkbBrushFormat';+import { BrushStudioScratchpad } from './brushStudio/BrushStudioScratchpad';+import {+ DualBrushTab,+ ShapeBristlesTab,+ StrokeTaperTab,+ TextureGrainTab,+} from './brushStudio/BrushStudioTabsPrimary';+import {+ AboutPresetsTab,+ DynamicsSensorMatrixTab,+ ImpastoWetEdgeTab,+ NaturalPaintMixingTab,+} from './brushStudio/BrushStudioTabsSecondary';++type StudioTabId =+ | 'shape'+ | 'stroke'+ | 'texture'+ | 'dual'+ | 'mixing'+ | 'impasto'+ | 'dynamics'+ | 'about';++const STUDIO_TABS: Array<{ id: StudioTabId; label: string; icon: React.ReactNode }> = [+ { id: 'shape', label: 'Shape & Bristles', icon: <Paintbrush className="w-3.5 h-3.5" /> },+ { id: 'stroke', label: 'Stroke & Taper', icon: <Spline className="w-3.5 h-3.5" /> },+ { id: 'texture', label: 'Texture & Grain', icon: <Grid3X3 className="w-3.5 h-3.5" /> },+ { id: 'dual', label: 'Dual Brush', icon: <Layers className="w-3.5 h-3.5" /> },+ { id: 'mixing', label: 'Natural Paint', icon: <Droplets className="w-3.5 h-3.5" /> },+ { id: 'impasto', label: 'Impasto & Wet', icon: <Sparkles className="w-3.5 h-3.5" /> },+ { id: 'dynamics', label: 'Sensor Matrix', icon: <Sliders className="w-3.5 h-3.5" /> },+ { id: 'about', label: 'About & Presets', icon: <Info className="w-3.5 h-3.5" /> },+];++export interface BrushStudioModalProps {+ isOpen: boolean;+ onClose: () => void;+ showToast?: (msg: string) => void;+}++export const BrushStudioModal: React.FC<BrushStudioModalProps> = ({+ isOpen,+ onClose,+ showToast,+}) => {+ const brushSettings = useToolStore((s) => s.brushSettings);+ const activePreset = useToolStore((s) => s.activePresetId) || DEFAULT_BRUSH_PRESET_ID;++ const [activeTab, setActiveTab] = useState<StudioTabId>('shape');+ const [brushName, setBrushName] = useState<string>(brushSettings.brushName || 'Brush');+ const [category, setCategory] = useState<BrushCategory | 'custom'>('natural-paint');+ const [description, setDescription] = useState<string>('');++ useEffect(() => {+ if (!isOpen) return;+ const builtin = BUILTIN_BRUSHES.find((b) => b.id === activePreset);+ const custom = getCachedCustomBrushes().find((b) => b.id === activePreset);+ setBrushName(custom?.name || builtin?.name || brushSettings.brushName || 'Custom Brush');+ setCategory(custom?.category || builtin?.category || 'custom');+ setDescription(custom?.desc || builtin?.desc || '');+ }, [isOpen, activePreset, brushSettings.brushName]);++ useEffect(() => {+ if (!isOpen) return;+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [isOpen, onClose]);++ const handlePatchSettings = useCallback(+ (patch: Partial<BrushSettings>) => {+ toolStoreActions.updateBrushSettings(patch);+ const custom = getCachedCustomBrushes().find((b) => b.id === activePreset);+ if (custom) {+ const merged = { ...useToolStore.getState().brushSettings, ...patch };+ const updated: CspBrush = {+ ...buildExportableBrush(activePreset, getCachedCustomBrushes(), merged),+ id: custom.id,+ name: brushName || custom.name,+ category,+ desc: description,+ badge: custom.badge || 'INKB',+ };+ saveCustomBrushDebounced(updated);+ }+ },+ [activePreset, brushName, category, description]+ );++ const handleSaveAsNewPreset = async (suffix: string = '') => {+ const live = useToolStore.getState().brushSettings;+ const baseName = (brushName || live.brushName || 'Custom Brush').trim();+ const finalName = suffix ? `${baseName} ${suffix}` : baseName;+ const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;+ const exported = buildExportableBrush(activePreset, getCachedCustomBrushes(), live);+ const newBrush: CspBrush = {+ ...exported,+ id,+ name: finalName,+ category,+ desc: description || exported.desc,+ badge: 'Studio',+ importedAt: Date.now(),+ };+ await saveCustomBrush(newBrush);+ saveActivePresetId(newBrush.id);+ const prepared = await prepareBrushSettingsForCsp(newBrush);+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...prepared,+ preset: newBrush.id,+ });+ showToast?.(`Saved preset "${finalName}"`);+ };++ const handleResetDefault = () => {+ const restored = resetBrushSettingsToDefault(activePreset, getCachedCustomBrushes());+ toolStoreActions.updateBrushSettings({+ ...NEUTRAL_BRUSH_DEFAULTS,+ ...restored,+ preset: activePreset,+ });+ showToast?.('Brush reset to default');+ };++ const handleExportInkb = async () => {+ try {+ const live = useToolStore.getState().brushSettings;+ const exportBrush: CspBrush = {+ ...buildExportableBrush(activePreset, getCachedCustomBrushes(), live),+ name: brushName || live.brushName || activePreset,+ category,+ desc: description,+ };+ const res = await exportBrushToInkbFile(exportBrush);+ if (res.exported) showToast?.(`Exported ${res.fileName}`);+ } catch (err) {+ showToast?.(err instanceof Error ? err.message : 'Export failed');+ }+ };++ const handleImportInkb = async (file: File) => {+ try {+ const parsed = await importBrushFile(file);+ saveActivePresetId(parsed.id);+ showToast?.(`Imported "${parsed.name}"`);+ } catch (err) {+ showToast?.(err instanceof Error ? err.message : 'Import failed');+ }+ };++ if (!isOpen) return null;++ return (+ <div+ className="fixed inset-0 z-50 bg-black/70 backdrop-blur-xs flex items-center justify-center p-4"+ onPointerDown={(e) => {+ if (e.target === e.currentTarget) onClose();+ }}+ >+ <div className="w-full max-w-[1060px] h-[min(86vh,720px)] bg-[#202020] border border-white/12 rounded-xl shadow-2xl flex flex-col overflow-hidden text-[#e5e5e5]">+ {/* Header */}+ <div className="px-4 py-2.5 bg-[#191919] border-b border-white/[0.08] flex items-center justify-between gap-3 shrink-0">+ <div className="flex items-center gap-2 min-w-0">+ <Paintbrush className="w-4 h-4 text-[var(--accent)] shrink-0" />+ <h2 className="text-[13px] font-semibold tracking-tight truncate">+ Brush Studio — {brushName}+ </h2>+ <span className="text-[10px] px-1.5 py-0.5 rounded bg-white/[0.06] text-[#a3a3a3] uppercase">+ {brushSettings.renderMode ?? 'stamp'}+ </span>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() => handleSaveAsNewPreset()}+ className="px-2.5 py-1 rounded bg-[var(--accent)] hover:opacity-90 text-[11px] font-medium text-white cursor-pointer"+ >+ Save New Preset+ </button>+ <button+ type="button"+ onClick={onClose}+ title="Close Brush Studio (Esc)"+ className="p-1 rounded text-[#8a8a8a] hover:text-white hover:bg-white/10 cursor-pointer"+ >+ <X className="w-4 h-4" />+ </button>+ </div>+ </div>++ {/* Main 3-Column Layout: Tabs | Scratchpad | Inspector */}+ <div className="flex-1 flex min-h-0">+ {/* Left Tab Rail */}+ <nav className="w-[156px] bg-[#181818] border-r border-white/[0.08] p-2 space-y-0.5 shrink-0 overflow-y-auto">+ {STUDIO_TABS.map((tab) => {+ const selected = activeTab === tab.id;+ return (+ <button+ key={tab.id}+ type="button"+ onClick={() => setActiveTab(tab.id)}+ className={`w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-[11px] transition-colors cursor-pointer ${+ selected+ ? 'bg-[#2c2c2c] text-white font-medium border border-white/[0.08]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-white/[0.04]'+ }`}+ >+ <span className={selected ? 'text-[var(--accent)]' : 'opacity-75'}>+ {tab.icon}+ </span>+ <span className="truncate">{tab.label}</span>+ </button>+ );+ })}+ </nav>++ {/* Center Interactive Live Scratchpad */}+ <div className="flex-1 min-w-[320px] flex flex-col">+ <BrushStudioScratchpad brushSettings={brushSettings} />+ </div>++ {/* Right Parameter Inspector */}+ <div className="w-[370px] bg-[#1e1e1e] p-3.5 overflow-y-auto shrink-0">+ {activeTab === 'shape' && (+ <ShapeBristlesTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'stroke' && (+ <StrokeTaperTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'texture' && (+ <TextureGrainTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'dual' && (+ <DualBrushTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'mixing' && (+ <NaturalPaintMixingTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'impasto' && (+ <ImpastoWetEdgeTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'dynamics' && (+ <DynamicsSensorMatrixTab bs={brushSettings} onPatch={handlePatchSettings} />+ )}+ {activeTab === 'about' && (+ <AboutPresetsTab+ bs={brushSettings}+ onPatch={handlePatchSettings}+ brushName={brushName}+ onBrushNameChange={(name) => {+ setBrushName(name);+ handlePatchSettings({ brushName: name });+ }}+ category={category}+ onCategoryChange={setCategory}+ description={description}+ onDescriptionChange={setDescription}+ onResetDefault={handleResetDefault}+ onSaveAsNewPreset={() => handleSaveAsNewPreset()}+ onDuplicateBrush={() => handleSaveAsNewPreset('Copy')}+ onExportInkb={handleExportInkb}+ onImportInkb={handleImportInkb}+ />+ )}+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsxindex 8009aa5..b862a2b 100644--- a/src/components/CanvasArea.tsx+++ b/src/components/CanvasArea.tsx@@ -1,7 +1,6 @@import React, { useState, useRef } from 'react';import { globalTileGrid } from '../utils/tileEngine';import { FloatingBrushPill } from './FloatingBrushPill';-import { ModifierAction } from '../types/settings';import {CanvasAreaProps,extractCoalescedEvents,@@ -29,6 +28,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {flipY = false,navigation,isSpaceDown,+ heldModifierAction = 'none',isRotateModifier,isPanning,isRotating,@@ -50,6 +50,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {tool = 'brush',liquifySettings,onUpdateLiquifySettings,+ retouchSettings,+ onUpdateRetouchSettings,primaryColor = '#000000',onSwapColors,showCursorCoordinates = false,@@ -79,7 +81,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {const liveFlipY = liveCamera.flipY;// Dynamic on-canvas brush resizing via configured modifier (default Ctrl + Alt + Drag or Shift + Alt + Drag)- const [heldModifierAction, setHeldModifierAction] = useState<ModifierAction>('none');const [isResizingBrush, setIsResizingBrush] = useState(false);const [quickPalettePos, setQuickPalettePos] = useState<{ x: number; y: number } | null>(null);const resizeOriginRef = useRef<{ clientX: number; clientY: number }>({ clientX: 0, clientY: 0 });@@ -107,6 +108,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {onUpdateBrushSettings,liquifySettings,onUpdateLiquifySettings,+ retouchSettings,+ onUpdateRetouchSettings,tool,liveZoom,liveRotation,@@ -121,7 +124,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {showCursorCoordinates,showPressureInStatusBar,heldModifierAction,- setHeldModifierAction,isResizingBrush,setIsResizingBrush,quickPalettePos,@@ -174,6 +176,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {dimensions,brushSettings,liquifySettings,+ retouchSettings,tool,navigation,pan,@@ -232,6 +235,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {tool === 'brush' ||tool === 'eraser' ||tool === 'liquify' ||+ tool === 'retouch' ||tool === 'select-pen' ||tool === 'select-eraser';@@ -255,6 +259,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo((props) => {onUpdateBrushSettings={onUpdateBrushSettings}liquifySettings={liquifySettings}onUpdateLiquifySettings={onUpdateLiquifySettings}+ retouchSettings={retouchSettings}+ onUpdateRetouchSettings={onUpdateRetouchSettings}primaryColor={primaryColor}onSwapColors={onSwapColors}zoom={zoom}diff --git a/src/components/CloseConfirmModal.tsx b/src/components/CloseConfirmModal.tsxnew file mode 100644index 0000000..2849550--- /dev/null+++ b/src/components/CloseConfirmModal.tsx@@ -0,0 +1,291 @@+import React, { useCallback, useEffect } from 'react';+import { HelpCircle, Loader2, X } from 'lucide-react';+import { uiStoreActions, useDocumentStore, useUiStore } from '../stores';+import {+ SaveDocumentResult,+ cancelAppClose,+ finalizeAppClose,+ findNextPendingDirtyIndex,+ formatCanvasDisplayName,+} from '../utils/appCloseFlow';++export interface CloseConfirmModalProps {+ onSaveDocumentById: (docId: string) => Promise<SaveDocumentResult>;+ onFinalizeClose?: () => Promise<void>;+}++export const CloseConfirmModal: React.FC<CloseConfirmModalProps> = React.memo(+ ({ onSaveDocumentById, onFinalizeClose }) => {+ const prompt = useUiStore((s) => s.appClosePrompt);+ const documents = useDocumentStore((s) => s.documents);++ const runFinalize = useCallback(async () => {+ if (onFinalizeClose) {+ await onFinalizeClose();+ } else {+ await finalizeAppClose();+ }+ }, [onFinalizeClose]);++ const handleCancel = useCallback(() => {+ cancelAppClose();+ }, []);++ useEffect(() => {+ if (!prompt.isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && !useUiStore.getState().appClosePrompt.isBusy) {+ e.preventDefault();+ e.stopPropagation();+ cancelAppClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [prompt.isOpen]);++ const advanceOrFinalize = useCallback(+ async (afterIndex: number, pendingDocIds: string[]) => {+ const latestDocs = useDocumentStore.getState().documents;+ const nextIdx = findNextPendingDirtyIndex(pendingDocIds, afterIndex, latestDocs);+ if (nextIdx >= 0) {+ uiStoreActions.setAppClosePrompt((prev) => ({+ ...prev,+ step: 'per-canvas',+ currentIndex: nextIdx,+ isBusy: false,+ }));+ } else {+ await runFinalize();+ }+ },+ [runFinalize]+ );++ const handleConfirmChanges = useCallback(async () => {+ const state = useUiStore.getState().appClosePrompt;+ if (state.isBusy) return;+ const latestDocs = useDocumentStore.getState().documents;+ const stillDirtyIds = state.pendingDocIds.filter((id) =>+ latestDocs.some((d) => d.id === id && d.isDirty)+ );+ if (stillDirtyIds.length === 0) {+ await runFinalize();+ return;+ }+ uiStoreActions.setAppClosePrompt({+ isOpen: true,+ step: 'per-canvas',+ pendingDocIds: stillDirtyIds,+ currentIndex: 0,+ isBusy: false,+ });+ }, [runFinalize]);++ const handleDiscardAll = useCallback(async () => {+ if (useUiStore.getState().appClosePrompt.isBusy) return;+ await runFinalize();+ }, [runFinalize]);++ const handleSaveCurrent = useCallback(async () => {+ const state = useUiStore.getState().appClosePrompt;+ if (state.isBusy || state.step !== 'per-canvas') return;++ const targetDocId = state.pendingDocIds[state.currentIndex];+ if (!targetDocId) {+ await runFinalize();+ return;+ }++ uiStoreActions.setAppClosePrompt((prev) => ({ ...prev, isBusy: true }));+ const result = await onSaveDocumentById(targetDocId);+ if (result === 'saved') {+ await advanceOrFinalize(state.currentIndex, state.pendingDocIds);+ } else {+ // Keep modal open on the same canvas if user canceled the Save dialog or save failed.+ uiStoreActions.setAppClosePrompt((prev) =>+ prev.isOpen ? { ...prev, isBusy: false } : prev+ );+ }+ }, [advanceOrFinalize, onSaveDocumentById, runFinalize]);++ const handleDoNotSaveCurrent = useCallback(async () => {+ const state = useUiStore.getState().appClosePrompt;+ if (state.isBusy || state.step !== 'per-canvas') return;+ await advanceOrFinalize(state.currentIndex, state.pendingDocIds);+ }, [advanceOrFinalize]);++ if (!prompt.isOpen) return null;++ const currentDocId = prompt.pendingDocIds[prompt.currentIndex];+ const currentDoc = currentDocId ? documents.find((d) => d.id === currentDocId) : undefined;+ const currentDocName = formatCanvasDisplayName(currentDoc?.name);+ const totalPending = prompt.pendingDocIds.length;+ const stepKey = `${prompt.step}-${prompt.currentIndex}`;++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="close-confirm-modal-title"+ data-testid="close-confirm-modal"+ className="fixed inset-0 z-[60] flex items-center justify-center bg-black/70 p-4 select-none"+ >+ <div className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.85)] w-full max-w-[430px] overflow-hidden text-xs text-[#e5e5e5] border border-[#2c2c2c]">+ {/* Title Bar */}+ <div className="h-9 px-3.5 flex items-center justify-between bg-[#161616] border-b border-[#2c2c2c]">+ <div className="flex items-center gap-2 min-w-0">+ <span+ id="close-confirm-modal-title"+ className="text-xs font-medium text-[#e5e5e5] tracking-wide"+ >+ Ink Studio+ </span>+ {prompt.step === 'per-canvas' && totalPending > 1 && (+ <span className="text-[10px] font-mono text-[#8a8a8a] bg-[#262626] px-1.5 py-0.5 rounded">+ {prompt.currentIndex + 1} / {totalPending}+ </span>+ )}+ </div>+ {!prompt.isBusy && (+ <button+ type="button"+ onClick={handleCancel}+ aria-label="Cancel close"+ title="Cancel (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ )}+ </div>++ {/* Body */}+ <div className="px-5 py-5 flex items-start gap-3.5">+ <div className="w-9 h-9 rounded-full bg-[#2a2a2a] border border-[#3a3a3a] flex items-center justify-center shrink-0 mt-0.5 text-[#bdbdbd]">+ <HelpCircle className="w-5 h-5" />+ </div>++ <div className="flex-1 min-w-0 space-y-1 text-[12.5px] leading-relaxed text-[#e5e5e5]">+ {prompt.step === 'confirm-quit' && (+ <p>Are you sure you want to close Ink Studio?</p>+ )}++ {prompt.step === 'summary' && (+ <>+ <p>+ There are <span className="font-semibold text-white">{totalPending}</span>{' '}+ canvases with unsaved changes.+ </p>+ <p className="text-[#c8c8c8]">+ Do you want to confirm these changes before closing?+ </p>+ </>+ )}++ {prompt.step === 'per-canvas' && (+ <p className="break-words">+ <span className="font-semibold text-white">{currentDocName}</span> has been+ changed. Do you want to save it?+ </p>+ )}+ </div>+ </div>++ {/* Actions */}+ <div+ key={stepKey}+ className="px-4 py-3 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-end gap-2"+ >+ {prompt.step === 'confirm-quit' && (+ <>+ <button+ type="button"+ autoFocus+ disabled={prompt.isBusy}+ onClick={() => void handleDiscardAll()}+ className="px-3.5 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 disabled:opacity-50 font-medium transition-opacity cursor-pointer inline-flex items-center gap-1.5"+ >+ {prompt.isBusy && <Loader2 className="w-3.5 h-3.5 animate-spin" />}+ <span>Close</span>+ </button>+ <button+ type="button"+ disabled={prompt.isBusy}+ onClick={handleCancel}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] disabled:opacity-50 text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Cancel+ </button>+ </>+ )}++ {prompt.step === 'summary' && (+ <>+ <button+ type="button"+ autoFocus+ disabled={prompt.isBusy}+ onClick={() => void handleConfirmChanges()}+ className="px-3.5 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 disabled:opacity-50 font-medium transition-opacity cursor-pointer"+ >+ Confirm changes...+ </button>+ <button+ type="button"+ disabled={prompt.isBusy}+ onClick={() => void handleDiscardAll()}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] disabled:opacity-50 text-[#e5e5e5] transition-colors cursor-pointer inline-flex items-center gap-1.5"+ >+ {prompt.isBusy && <Loader2 className="w-3.5 h-3.5 animate-spin" />}+ <span>Discard changes</span>+ </button>+ <button+ type="button"+ disabled={prompt.isBusy}+ onClick={handleCancel}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] disabled:opacity-50 text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Cancel+ </button>+ </>+ )}++ {prompt.step === 'per-canvas' && (+ <>+ <button+ type="button"+ autoFocus+ disabled={prompt.isBusy}+ onClick={() => void handleSaveCurrent()}+ className="px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 disabled:opacity-50 font-medium transition-opacity cursor-pointer inline-flex items-center gap-1.5"+ >+ {prompt.isBusy && <Loader2 className="w-3.5 h-3.5 animate-spin" />}+ <span>{prompt.isBusy ? 'Saving...' : 'Save'}</span>+ </button>+ <button+ type="button"+ disabled={prompt.isBusy}+ onClick={() => void handleDoNotSaveCurrent()}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] disabled:opacity-50 text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Do Not Save+ </button>+ <button+ type="button"+ disabled={prompt.isBusy}+ onClick={handleCancel}+ className="px-3.5 py-1.5 rounded bg-[#2a2a2a] hover:bg-[#363636] disabled:opacity-50 text-[#e5e5e5] transition-colors cursor-pointer"+ >+ Cancel+ </button>+ </>+ )}+ </div>+ </div>+ </div>+ );+ }+);++CloseConfirmModal.displayName = 'CloseConfirmModal';diff --git a/src/components/ColorPanel.tsx b/src/components/ColorPanel.tsxindex 4443286..d20e6f1 100644--- a/src/components/ColorPanel.tsx+++ b/src/components/ColorPanel.tsx@@ -1,7 +1,13 @@-import React, { useState } from 'react';+import React, { useState, useCallback, useRef } from 'react';import { Disc, SlidersHorizontal, ArrowLeftRight } from 'lucide-react';import { ColorWheel } from './ColorWheel';import { ColorSlider } from './ColorSlider';+import {+ SphereColorPicker,+ SphereColorPickerModal,+ SpherePickerSharedState,+ createInitialSphereState,+} from './SphereColorPicker';import { ToolType, CanvasColorMode } from '../types/editor';import { isValidHex, enforceColorMode } from '../utils/colorUtils';import { safeLocalStorageSetItem } from '../utils/safeStorage';@@ -20,6 +26,8 @@ export interface ColorPanelProps {containerHeight?: number;}+type ColorPanelTab = 'wheel' | 'slider' | 'sphere';+export const ColorPanel: React.FC<ColorPanelProps> = ({primaryColor,secondaryColor,@@ -33,24 +41,52 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({containerWidth = 180,containerHeight,}) => {- const [activeTab, setActiveTab] = useState<'wheel' | 'slider'>(() => {+ const [activeTab, setActiveTab] = useState<ColorPanelTab>(() => {try {const saved = localStorage.getItem('ink_color_tab');- if (saved === 'wheel' || saved === 'slider') return saved;+ if (saved === 'wheel' || saved === 'slider' || saved === 'sphere') return saved;} catch {// ignore}return 'wheel';});+ const lastNonSphereTabRef = useRef<'wheel' | 'slider'>(+ activeTab === 'slider' ? 'slider' : 'wheel'+ );+const [activeTarget, setActiveTarget] = useState<'primary' | 'secondary'>('primary');const activeColor = activeTarget === 'primary' ? primaryColor : secondaryColor;+ const isMonoCanvas = colorMode === 'grayscale' || colorMode === 'monochrome';- const toggleTab = () => {- const next = activeTab === 'wheel' ? 'slider' : 'wheel';+ const [isSphereFloating, setIsSphereFloating] = useState(false);+ const [sphereState, setSphereState] = useState<SpherePickerSharedState>(() =>+ createInitialSphereState(primaryColor, isMonoCanvas)+ );++ const selectTab = useCallback((next: ColorPanelTab) => {+ if (next !== 'sphere') {+ lastNonSphereTabRef.current = next;+ } else {+ // Dock back when explicitly selecting the Sphere tab+ setIsSphereFloating(false);+ }setActiveTab(next);safeLocalStorageSetItem('ink_color_tab', next, 'color panel preference');- };+ }, []);++ const handleUnpinSphere = useCallback(() => {+ setIsSphereFloating(true);+ const fallback = lastNonSphereTabRef.current;+ setActiveTab(fallback);+ safeLocalStorageSetItem('ink_color_tab', fallback, 'color panel preference');+ }, []);++ const handlePinSphere = useCallback(() => {+ setIsSphereFloating(false);+ setActiveTab('sphere');+ safeLocalStorageSetItem('ink_color_tab', 'sphere', 'color panel preference');+ }, []);const handleHexChange = (raw: string) => {const clean = raw.trim();@@ -66,9 +102,22 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({}};+ const handleSphereColorChange = useCallback(+ ({ hex }: { hex: string }, commit?: boolean) => {+ const finalHex =+ colorMode && colorMode !== 'color' ? enforceColorMode(hex, colorMode) : hex;+ if (activeTarget === 'primary') {+ onPrimaryColorChange(finalHex, commit);+ } else {+ onSecondaryColorChange(finalHex, commit);+ }+ },+ [activeTarget, colorMode, onPrimaryColorChange, onSecondaryColorChange]+ );+return (<div className="flex flex-col h-full w-full select-none bg-[#202020] text-[#e5e5e5] overflow-hidden">- {/* Compact Header Strip: Swatches + Hex + Recent Dots + Mode Toggle */}+ {/* Compact Header Strip: Swatches + Hex + Recent Dots + Swap + Mode Switchers */}<div className="h-6 px-2 pt-1 flex items-center justify-between gap-1 shrink-0"><div className="flex items-center gap-1.5 min-w-0">{/* Primary / Secondary Swatch Pair */}@@ -108,9 +157,9 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({/></div>- {/* Recent Micro Swatches (when wide) + Swap + Wheel/Slider Toggle */}+ {/* Recent Micro Swatches + Swap + Wheel / Sliders / 3D Sphere Tabs */}<div className="flex items-center gap-0.5 shrink-0">- {containerWidth >= 220 && (+ {containerWidth >= 236 && (<div className="flex items-center gap-0.5 mr-0.5">{recentColors.slice(0, 3).map((c, idx) => (<button@@ -140,20 +189,70 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({<buttontype="button"- onClick={toggleTab}- title={activeTab === 'wheel' ? 'Switch to Sliders' : 'Switch to Color Wheel'}- className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"+ onClick={() => selectTab('wheel')}+ title="Color Wheel"+ aria-pressed={activeTab === 'wheel'}+ className={`w-5 h-5 rounded flex items-center justify-center cursor-pointer transition-colors ${+ activeTab === 'wheel'+ ? 'bg-[#2f2f32] text-white'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Disc className="w-3 h-3" />+ </button>++ <button+ type="button"+ onClick={() => selectTab('slider')}+ title="Color Sliders"+ aria-pressed={activeTab === 'slider'}+ className={`w-5 h-5 rounded flex items-center justify-center cursor-pointer transition-colors ${+ activeTab === 'slider'+ ? 'bg-[#2f2f32] text-white'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <SlidersHorizontal className="w-3 h-3" />+ </button>++ <button+ type="button"+ onClick={() => {+ if (activeTab === 'sphere' && !isSphereFloating) {+ handleUnpinSphere();+ } else if (isSphereFloating) {+ handlePinSphere();+ } else {+ selectTab('sphere');+ }+ }}+ title={+ isSphereFloating+ ? '3D Sphere (Floating — click to dock)'+ : activeTab === 'sphere'+ ? '3D Sphere (Docked — click to unpin & float)'+ : '3D Sphere Color Picker'+ }+ aria-label="3D Sphere Color Picker"+ aria-pressed={activeTab === 'sphere' || isSphereFloating}+ className={`w-5 h-5 rounded flex items-center justify-center cursor-pointer transition-colors ${+ activeTab === 'sphere' || isSphereFloating+ ? 'bg-[#2f2f32] ring-1 ring-white/25'+ : 'hover:bg-[#2c2c2c]'+ }`}>- {activeTab === 'wheel' ? (- <SlidersHorizontal className="w-3 h-3" />- ) : (- <Disc className="w-3 h-3" />- )}+ <span+ className="w-3 h-3 rounded-full block"+ style={{+ background:+ 'radial-gradient(circle at 32% 30%, #f5f5f5 0%, #9ca3af 48%, #2e3440 100%)',+ }}+ /></button></div></div>- {/* Wheel or Compact Sliders */}+ {/* Docked Content: Wheel, Sliders, or Inline 3D Sphere */}<div className="flex-1 min-h-0 overflow-y-auto flex flex-col">{activeTab === 'wheel' ? (<ColorWheel@@ -172,7 +271,7 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({onActiveTargetChange={setActiveTarget}hideHeader={true}/>- ) : (+ ) : activeTab === 'slider' ? (<ColorSliderprimaryColor={primaryColor}secondaryColor={secondaryColor}@@ -189,8 +288,33 @@ export const ColorPanel: React.FC<ColorPanelProps> = ({onActiveTargetChange={setActiveTarget}hideHeader={true}/>+ ) : (+ <SphereColorPicker+ variant="docked"+ isPinned={true}+ onTogglePin={handleUnpinSphere}+ initialColor={activeColor}+ monochromeDefault={isMonoCanvas}+ sharedState={sphereState}+ onSharedStateChange={setSphereState}+ onColorChange={handleSphereColorChange}+ onEyedropper={onSelectTool ? () => onSelectTool('pipette') : undefined}+ />)}</div>++ {/* Unpinned Non-Blocking Draggable Floating 3D Sphere */}+ <SphereColorPickerModal+ isOpen={isSphereFloating}+ onClose={() => setIsSphereFloating(false)}+ onTogglePin={handlePinSphere}+ initialColor={activeColor}+ monochromeDefault={isMonoCanvas}+ sharedState={sphereState}+ onSharedStateChange={setSphereState}+ onColorChange={handleSphereColorChange}+ onEyedropper={onSelectTool ? () => onSelectTool('pipette') : undefined}+ /></div>);};diff --git a/src/components/CrashRecoveryModal.tsx b/src/components/CrashRecoveryModal.tsxindex f6d64b8..9afd5a0 100644--- a/src/components/CrashRecoveryModal.tsx+++ b/src/components/CrashRecoveryModal.tsx@@ -1,10 +1,12 @@-import React, { useState } from 'react';+import React, { useEffect, useState } from 'react';import {RotateCcw,Trash2,AlertTriangle,FileText,Layers,+ Loader2,+ X,} from 'lucide-react';import { CrashedSessionInfo } from '../services/recoveryService';@@ -16,28 +18,61 @@ interface CrashRecoveryModalProps {onClose?: () => void;}+interface ParsedSessionManifest {+ documentName?: string;+ width?: number;+ height?: number;+ dpi?: number;+ colorMode?: string;+ layers?: unknown[];+}++function parseSessionManifest(manifestJson?: string | null): ParsedSessionManifest | null {+ if (!manifestJson) return null;+ try {+ return JSON.parse(manifestJson) as ParsedSessionManifest;+ } catch {+ return null;+ }+}+export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({isOpen,sessions,onRestore,onDiscard,+ onClose,}) => {const [selectedIndex, setSelectedIndex] = useState<number>(0);const [isRestoring, setIsRestoring] = useState<boolean>(false);const [isDiscarding, setIsDiscarding] = useState<boolean>(false);- if (!isOpen || sessions.length === 0) return null;-- const currentSession = sessions[selectedIndex] || sessions[0];+ const isBusy = isRestoring || isDiscarding;- let manifestData: any = null;- if (currentSession.manifest_json) {- try {- manifestData = JSON.parse(currentSession.manifest_json);- } catch {- manifestData = null;+ useEffect(() => {+ if (sessions.length > 0 && selectedIndex >= sessions.length) {+ setSelectedIndex(sessions.length - 1);}- }+ }, [sessions.length, selectedIndex]);++ useEffect(() => {+ if (!isOpen || !onClose) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && !isBusy) {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKeyDown, true);+ return () => window.removeEventListener('keydown', handleKeyDown, true);+ }, [isOpen, isBusy, onClose]);++ if (!isOpen || sessions.length === 0) return null;++ const safeIndex = Math.min(selectedIndex, sessions.length - 1);+ const currentSession = sessions[safeIndex] || sessions[0];+ const manifestData = parseSessionManifest(currentSession.manifest_json);const documentName = manifestData?.documentName || 'Untitled Document';const width = manifestData?.width || 3000;@@ -54,6 +89,7 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({: 'Unknown';const handleRestoreClick = async () => {+ if (isBusy) return;setIsRestoring(true);try {await onRestore(currentSession);@@ -63,6 +99,7 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({};const handleDiscardClick = async () => {+ if (isBusy) return;setIsDiscarding(true);try {await onDiscard(currentSession);@@ -76,122 +113,180 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({role="dialog"aria-modal="true"aria-labelledby="crash-recovery-title"- className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-xs p-4 select-none animate-in fade-in duration-150"+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 select-none">- <div className="bg-[#202020] border border-white/[0.1] rounded-lg shadow-2xl w-full max-w-2xl flex flex-col overflow-hidden text-xs text-[#e5e5e5]">+ <div className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] border border-[#2c2c2c] w-full max-w-[660px] flex flex-col overflow-hidden text-xs text-[#e5e5e5]">{/* Header Bar */}- <div className="flex items-center justify-between px-5 py-3.5 bg-[#1a1a1a] border-b border-white/[0.06]">- <div className="flex items-center space-x-3">- <div className="w-7 h-7 rounded-md bg-[#2c2c2c] flex items-center justify-center text-amber-400">- <AlertTriangle className="w-4 h-4" />- </div>- <div>- <h2 id="crash-recovery-title" className="text-sm font-medium text-[#e5e5e5] flex items-center gap-2">- Restore Unsaved Session?- <span className="px-2 py-0.5 rounded text-[10px] font-medium bg-[#161616] text-[var(--accent)] border border-[var(--accent-border)]">- WAL Protected- </span>- </h2>- <p className="text-[11px] text-[#8a8a8a] mt-0.5">- Ink Studio detected an unexpected shutdown. Your progress can be restored.- </p>- </div>+ <div className="h-10 px-4 flex items-center justify-between gap-3 bg-[#161616] border-b border-[#2c2c2c] shrink-0">+ <div className="flex items-center gap-2 min-w-0">+ <AlertTriangle className="w-3.5 h-3.5 text-amber-400 shrink-0" />+ <h2+ id="crash-recovery-title"+ className="text-xs font-medium text-[#e5e5e5] truncate"+ >+ Restore Unsaved Session+ </h2>+ <span className="inline-flex items-center gap-1.5 font-mono text-[10px] px-1.5 py-0.5 rounded bg-[#202020] border border-[#2c2c2c] text-[#a0a0a0] shrink-0">+ <span className="w-1.5 h-1.5 rounded-full bg-[var(--accent)]" />+ WAL Protected+ </span></div>- </div>- {/* Multiple Sessions Selector (if > 1 session detected) */}- {sessions.length > 1 && (- <div className="px-6 py-2 bg-[#1e1e20] border-b border-[#323235] flex items-center gap-2 overflow-x-auto">- <span className="text-[10px] text-[#888888] font-semibold uppercase tracking-wider shrink-0">- Sessions:- </span>- {sessions.map((s, idx) => (+ <div className="flex items-center gap-2 shrink-0">+ {sessions.length > 1 && (+ <span className="text-[10px] font-mono text-[#8a8a8a] bg-[#262626] px-1.5 py-0.5 rounded">+ {safeIndex + 1} / {sessions.length}+ </span>+ )}+ {onClose && !isBusy && (<button- key={s.session_id}- onClick={() => setSelectedIndex(idx)}- className={`px-3 py-1 rounded text-xs transition-colors border ${- idx === selectedIndex- ? 'bg-[#007acc] border-[#007acc] text-white font-medium'- : 'bg-[#29292c] border-[#38383c] text-[#a0a0a0] hover:text-white'- }`}+ type="button"+ onClick={onClose}+ aria-label="Close recovery dialog"+ title="Close (Esc)"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer">- Session {idx + 1}+ <X className="w-3.5 h-3.5" /></button>- ))}+ )}+ </div>+ </div>++ {/* Multiple Sessions Selector */}+ {sessions.length > 1 && (+ <div className="px-4 py-2 bg-[#1a1a1a] border-b border-[#2c2c2c] flex items-center gap-3 overflow-x-auto no-scrollbar shrink-0">+ <span className="text-[10px] text-[#8a8a8a] font-medium uppercase tracking-wider shrink-0">+ Sessions+ </span>+ <div className="inline-flex items-center gap-0.5 bg-[#161616] p-0.5 rounded border border-[#2c2c2c]">+ {sessions.map((s, idx) => {+ const isActive = idx === safeIndex;+ const sessionManifest = parseSessionManifest(s.manifest_json);+ const sessionTitle = sessionManifest?.documentName || `Session ${idx + 1}`;+ return (+ <button+ key={s.session_id}+ type="button"+ disabled={isBusy}+ title={sessionTitle}+ onClick={() => setSelectedIndex(idx)}+ className={`px-2.5 py-1 rounded text-[11px] transition-colors cursor-pointer shrink-0 inline-flex items-center gap-1.5 disabled:opacity-50 ${+ isActive+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {isActive && (+ <span className="w-1.5 h-1.5 rounded-full bg-[var(--accent)] shrink-0" />+ )}+ <span>Session {idx + 1}</span>+ </button>+ );+ })}+ </div></div>)}{/* Modal Main Content */}- <div className="p-6 space-y-5">- {/* Document Preview & Metadata Card */}- <div className="bg-[#1b1b1d] border border-[#323235] rounded-lg p-4 grid grid-cols-1 md:grid-cols-12 gap-5">+ <div className="p-5 space-y-4 bg-[#202020]">+ <p className="text-[11px] text-[#8a8a8a] leading-relaxed">+ Ink Studio detected an unexpected shutdown. Your progress can be restored from the recovery journal below.+ </p>++ {/* Document Preview & Metadata Grid */}+ <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-stretch">{/* Visual Thumbnail Preview (5 cols) */}- <div className="md:col-span-5 flex flex-col items-center justify-center">- <div className="w-full aspect-square max-w-[210px] bg-[#141416] border border-[#38383c] rounded-md overflow-hidden relative flex items-center justify-center shadow-inner group">+ <div className="md:col-span-5 flex flex-col">+ <div+ className="w-full aspect-square bg-[#161616] border border-[#2c2c2c] rounded overflow-hidden relative flex items-center justify-center"+ style={+ currentSession.thumbnail_data_url+ ? {+ backgroundImage:+ 'conic-gradient(#1f1f1f 90deg, #161616 90deg 180deg, #1f1f1f 180deg 270deg, #161616 270deg)',+ backgroundSize: '12px 12px',+ }+ : undefined+ }+ >{currentSession.thumbnail_data_url ? (<imgsrc={currentSession.thumbnail_data_url}alt="Document preview"- className="w-full h-full object-contain p-1"+ className="w-full h-full object-contain p-1.5"/>) : (- <div className="flex flex-col items-center justify-center text-[#666666] p-4 text-center">- <Layers className="w-10 h-10 mb-2 opacity-50 text-[#888888]" />- <span className="text-[11px] font-medium text-[#888888]">No Snapshot Preview</span>- <span className="text-[10px] text-[#555555]">WAL journal entries intact</span>+ <div className="flex flex-col items-center justify-center p-4 text-center">+ <Layers className="w-8 h-8 mb-2 text-[#525252]" />+ <span className="text-[11px] font-medium text-[#8a8a8a]">+ No Snapshot Preview+ </span>+ <span className="text-[10px] text-[#737373] mt-0.5">+ WAL journal entries intact+ </span></div>)}- <div className="absolute bottom-2 left-2 bg-black/75 px-1.5 py-0.5 rounded text-[10px] font-mono text-[#aaaaaa] border border-white/10">+ <div className="absolute bottom-2 left-2 bg-[#161616]/90 border border-[#2c2c2c] px-1.5 py-0.5 rounded text-[10px] font-mono text-[#b5b5b5]">{width} × {height}</div></div></div>{/* Metadata Fields (7 cols) */}- <div className="md:col-span-7 flex flex-col justify-between space-y-3">- <div>- <div className="flex items-center gap-2">- <FileText className="w-4 h-4 text-sky-400 shrink-0" />- <h3 className="text-sm font-semibold text-white truncate" title={documentName}>+ <div className="md:col-span-7 flex flex-col justify-between gap-3 min-w-0">+ <div className="min-w-0">+ <div className="flex items-center gap-2 min-w-0">+ <FileText className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ <h3+ className="text-sm font-semibold text-[#e5e5e5] truncate"+ title={documentName}+ >{documentName}</h3></div>- <p className="text-[11px] text-[#777777] font-mono mt-0.5 truncate">+ <p+ className="text-[10px] text-[#737373] font-mono mt-0.5 truncate select-text"+ title={currentSession.session_id}+ >ID: {currentSession.session_id}</p></div>- <div className="grid grid-cols-2 gap-2 text-xs">- <div className="bg-[#161616] border border-white/[0.06] rounded p-2">+ <div className="grid grid-cols-2 gap-1.5">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded px-2.5 py-2"><span className="text-[10px] text-[#8a8a8a] block">Canvas Size</span>- <span className="font-medium text-[#e5e5e5]">{width} × {height}</span>+ <span className="text-xs font-medium font-mono text-[#e5e5e5]">+ {width} × {height}+ </span></div>- <div className="bg-[#161616] border border-white/[0.06] rounded p-2">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded px-2.5 py-2"><span className="text-[10px] text-[#8a8a8a] block">Resolution</span>- <span className="font-medium text-[#e5e5e5]">{dpi} DPI</span>+ <span className="text-xs font-medium font-mono text-[#e5e5e5]">{dpi} DPI</span></div>- <div className="bg-[#161616] border border-white/[0.06] rounded p-2">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded px-2.5 py-2"><span className="text-[10px] text-[#8a8a8a] block">Layer Tree</span>- <span className="font-medium text-[#e5e5e5]">{layerCount} {layerCount === 1 ? 'Layer' : 'Layers'}</span>+ <span className="text-xs font-medium text-[#e5e5e5]">+ {layerCount} {layerCount === 1 ? 'Layer' : 'Layers'}+ </span></div>- <div className="bg-[#161616] border border-white/[0.06] rounded p-2">+ <div className="bg-[#161616] border border-[#2c2c2c] rounded px-2.5 py-2"><span className="text-[10px] text-[#8a8a8a] block">Color Mode</span>- <span className="font-medium text-[#e5e5e5] capitalize">{colorMode}</span>+ <span className="text-xs font-medium text-[#e5e5e5] capitalize">{colorMode}</span></div></div>{/* Timestamp & Process Info */}- <div className="bg-[#161616] border border-white/[0.06] rounded p-2 text-[11px] space-y-1">- <div className="flex items-center justify-between text-[#8a8a8a]">- <span>Terminated At</span>- <span className="text-[#e5e5e5] font-mono">{crashDate}</span>+ <div className="bg-[#161616] rounded border border-[#2c2c2c] divide-y divide-[#252525] text-[11px]">+ <div className="px-2.5 py-1.5 flex items-center justify-between gap-2">+ <span className="text-[#8a8a8a]">Terminated At</span>+ <span className="text-[#d4d4d4] font-mono">{crashDate}</span></div>- <div className="flex items-center justify-between text-[#8a8a8a]">- <span>Previous PID</span>- <span className="text-[#cccccc] font-mono">{currentSession.pid}</span>+ <div className="px-2.5 py-1.5 flex items-center justify-between gap-2">+ <span className="text-[#8a8a8a]">Previous PID</span>+ <span className="text-[#a0a0a0] font-mono">{currentSession.pid}</span></div></div></div>@@ -199,24 +294,33 @@ export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({</div>{/* Modal Action Footer */}- <div className="flex items-center justify-between px-6 py-4 bg-[#202022] border-t border-[#343438]">+ <div className="px-4 py-3 bg-[#161616] border-t border-[#2c2c2c] flex items-center justify-between gap-2 shrink-0"><buttontype="button"- disabled={isRestoring || isDiscarding}+ disabled={isBusy}onClick={handleDiscardClick}- className="flex items-center gap-2 px-4 py-2 rounded-md text-xs font-medium bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 transition-colors disabled:opacity-50 cursor-pointer"+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded text-xs font-medium bg-[#202020] hover:bg-red-500/15 border border-[#2c2c2c] hover:border-red-500/30 text-red-400/90 hover:text-red-300 transition-colors disabled:opacity-50 cursor-pointer">- <Trash2 className="w-3.5 h-3.5" />+ {isDiscarding ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <Trash2 className="w-3.5 h-3.5" />+ )}<span>{isDiscarding ? 'Discarding...' : 'Discard & Start Fresh'}</span></button><buttontype="button"- disabled={isRestoring || isDiscarding}+ autoFocus+ disabled={isBusy}onClick={handleRestoreClick}- className="flex items-center gap-2 px-5 py-2 rounded-md text-xs font-semibold bg-[#007acc] hover:bg-[#008ae6] text-white shadow-md shadow-sky-950/40 border border-[#0090f0]/30 transition-all disabled:opacity-50 cursor-pointer active:scale-98"+ className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded text-xs font-medium bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 disabled:opacity-50 transition-opacity cursor-pointer">- <RotateCcw className={`w-3.5 h-3.5 ${isRestoring ? 'animate-spin' : ''}`} />+ {isRestoring ? (+ <Loader2 className="w-3.5 h-3.5 animate-spin" />+ ) : (+ <RotateCcw className="w-3.5 h-3.5" />+ )}<span>{isRestoring ? 'Restoring Canvas...' : 'Restore Session'}</span></button></div>diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsxindex 2845437..bbd2af0 100644--- a/src/components/DockWorkspace.tsx+++ b/src/components/DockWorkspace.tsx@@ -169,6 +169,12 @@ export interface DockWorkspaceProps {// Tool / selection callbacksonDeselect?: () => void;onTransformSelection?: () => void;+ onClearSelection?: () => void;+ onDeleteOutsideSelection?: () => void;+ onCutSelection?: () => void;+ onCopySelection?: () => void;+ onPasteSelection?: () => void;+ onMoveSelectionToNewLayer?: () => void;onExpandSelection?: (pixels: number) => void;onContractSelection?: (pixels: number) => void;onFeatherSelection?: (radius: number) => void;@@ -798,6 +804,12 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({commandHandlers,onDeselect,onTransformSelection,+ onClearSelection,+ onDeleteOutsideSelection,+ onCutSelection,+ onCopySelection,+ onPasteSelection,+ onMoveSelectionToNewLayer,onExpandSelection,onContractSelection,onFeatherSelection,@@ -880,6 +892,12 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({setCustomBrushes={setCustomBrushes}onDeselect={onDeselect}onTransformSelection={onTransformSelection}+ onClearSelection={onClearSelection}+ onDeleteOutsideSelection={onDeleteOutsideSelection}+ onCutSelection={onCutSelection}+ onCopySelection={onCopySelection}+ onPasteSelection={onPasteSelection}+ onMoveSelectionToNewLayer={onMoveSelectionToNewLayer}onExpandSelection={onExpandSelection}onContractSelection={onContractSelection}onFeatherSelection={onFeatherSelection}@@ -939,11 +957,17 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({customBrushes,layerSidebarProps,navigatorProps,+ onClearSelection,onContractSelection,+ onCopySelection,+ onCutSelection,+ onDeleteOutsideSelection,onDeselect,onExpandSelection,onFeatherSelection,onInvertSelection,+ onMoveSelectionToNewLayer,+ onPasteSelection,onToggleTransparentColor,onTransformSelection,setCustomBrushes,diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex 3db0963..6f7f79b 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -33,6 +33,40 @@ import {useUiStore,} from '../stores';import { PushHistoryStepFn } from '../hooks/drawing';+import { isTauriEnvironment } from '../hooks/useMultiplayer';+import {+ SaveDocumentResult,+ isFinalizingAppClose,+ requestAppClose,+} from '../utils/appCloseFlow';++function computeEffectiveOpacityForLayers(allLayers: LayerItem[], layer: LayerItem): number {+ let opacity = layer.opacity;+ let parentId = layer.parentId;+ const visited = new Set<string>([layer.id]);+ while (parentId && !visited.has(parentId)) {+ visited.add(parentId);+ const parent = allLayers.find((l) => l.id === parentId);+ if (!parent) break;+ opacity *= parent.opacity;+ parentId = parent.parentId;+ }+ return opacity;+}++function computeLayerVisibleForLayers(allLayers: LayerItem[], layer: LayerItem): boolean {+ if (!layer.visible) return false;+ let parentId = layer.parentId;+ const visited = new Set<string>([layer.id]);+ while (parentId && !visited.has(parentId)) {+ visited.add(parentId);+ const parent = allLayers.find((l) => l.id === parentId);+ if (!parent) break;+ if (!parent.visible) return false;+ parentId = parent.parentId;+ }+ return true;+}interface FileWithOptionalPath extends File {path?: string;@@ -71,7 +105,13 @@ export interface UseDocumentLifecycleParams {) => void;resizeCanvas: (newDims: CanvasDimensions, options: ResizeCanvasOptions) => void;copyLayer: (id: string) => LayerItem | null;- pasteLayer: () => Promise<{ success: boolean; layerName?: string }>;+ pasteLayer: () => Promise<{+ success: boolean;+ layerId?: string;+ layerName?: string;+ tileDeltas?: import('../types/editor').TileDelta[];+ }>;+ onDeselectAfterPaste?: () => void;deleteLayer: (id: string) => void;pasteLayerFromFile: (file: File) => Promise<string>;resetZoomAndCenter: (dims?: CanvasDimensions) => void;@@ -95,6 +135,7 @@ export function useDocumentLifecycle({resizeCanvas,copyLayer,pasteLayer,+ onDeselectAfterPaste,deleteLayer,pasteLayerFromFile,resetZoomAndCenter,@@ -102,7 +143,6 @@ export function useDocumentLifecycle({pushHistoryStep,showToast,}: UseDocumentLifecycleParams) {- const documents = useDocumentStore((s) => s.documents);const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);const dimensions = useDocumentStore((s) => s.dimensions);const colorMode = useDocumentStore((s) => s.colorMode);@@ -114,6 +154,8 @@ export function useDocumentLifecycle({const import3DFileInputRef = useRef<HTMLInputElement>(null);const needsAdaptiveFitRef = useRef<boolean>(true);const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);+ const layersRef = useRef<LayerItem[]>(layers);+ layersRef.current = layers;const handleViewportReady = useCallback((viewport: HTMLDivElement) => {@@ -203,11 +245,23 @@ export function useDocumentLifecycle({const handlePasteSelectedLayer = useCallback(async () => {const res = await pasteLayer();if (res.success && res.layerName) {- showToast(`Pasted layer "${res.layerName}"`);+ if (res.layerId && res.tileDeltas && res.tileDeltas.length > 0) {+ pushHistoryStep(+ 'selection-move',+ `Paste "${res.layerName}"`,+ null,+ null,+ res.layerId,+ undefined,+ res.tileDeltas+ );+ }+ onDeselectAfterPaste?.();+ showToast(`Pasted into "${res.layerName}"`);} else {showToast('Clipboard is empty');}- }, [pasteLayer, showToast]);+ }, [onDeselectAfterPaste, pasteLayer, pushHistoryStep, showToast]);const handleDeleteSelectedLayer = useCallback(() => {const rasterCount = layers.filter((l) => l.type === 'raster').length;@@ -230,6 +284,7 @@ export function useDocumentLifecycle({if (file) {try {const layerName = await pasteLayerFromFile(file);+ documentStoreActions.markDocumentDirty(useDocumentStore.getState().activeDocumentId, true);showToast(`Pasted "${layerName}" from file`);} catch (err: unknown) {console.error('Failed to paste from file:', err);@@ -274,6 +329,7 @@ export function useDocumentLifecycle({resizeCanvas(newDims, options);documentStoreActions.setDimensions(newDims);+ documentStoreActions.markDocumentDirty(useDocumentStore.getState().activeDocumentId, true);pendingFitDimsRef.current = newDims;needsAdaptiveFitRef.current = true;resetZoomAndCenter(newDims);@@ -396,11 +452,12 @@ export function useDocumentLifecycle({const handleSelectDocument = useCallback((id: string) => {- if (id === activeDocumentId) {+ const storeState = useDocumentStore.getState();+ if (id === storeState.activeDocumentId) {uiStoreActions.setAppView('workspace');return;}- const doc = documents.find((d) => d.id === id);+ const doc = storeState.documents.find((d) => d.id === id);if (!doc) return;uiStoreActions.setAppView('workspace');documentStoreActions.setDimensions(doc.dimensions);@@ -426,7 +483,7 @@ export function useDocumentLifecycle({pendingFitDimsRef.current = doc.dimensions;resetZoomAndCenter(doc.dimensions);},- [activeDocumentId, documents, resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]+ [resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]);const handleCloseDocument = useCallback(@@ -521,6 +578,7 @@ export function useDocumentLifecycle({const restoredDoc: DocumentTab = {id: session.session_id,name: manifest.documentName,+ isDirty: true,dimensions: restoredDims,colorMode: manifest.colorMode,layers: manifest.layers,@@ -644,99 +702,148 @@ export function useDocumentLifecycle({]);- const handleSave = useCallback(async () => {- const onProgress = (p: SaveProgress) => {- uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);- };- const docData = buildSaveData(onProgress);+ const handleSaveDocumentById = useCallback(+ async (docId: string): Promise<SaveDocumentResult> => {+ const storeState = useDocumentStore.getState();+ const targetDoc = storeState.documents.find((d) => d.id === docId);+ if (!targetDoc) return 'error';++ const isActive = storeState.activeDocumentId === docId;+ const docLayers = isActive ? layersRef.current : targetDoc.layers;+ const docSavedInfo = isActive+ ? storeState.savedFileInfo ?? targetDoc.savedFileInfo ?? null+ : targetDoc.savedFileInfo ?? null;+ const docTileGrid =+ documentStore.getSession(docId)?.tileGrid ?? documentStore.getActiveTileGrid();+ const cleanNameForSave = targetDoc.name.replace(/\*+$/, '') || 'Untitled';+ const tlStats = globalTimelapseManager.getStats(docId);++ const onProgress = (p: SaveProgress) => {+ uiStoreActions.setLoading(true, `${p.message} (${p.percent}%)`);+ };++ const docData: SaveDocumentData = {+ name: cleanNameForSave,+ dimensions: targetDoc.dimensions,+ colorMode: targetDoc.colorMode,+ layers: docLayers,+ tileGrid: docTileGrid,+ getEffectiveOpacity: (layer) => computeEffectiveOpacityForLayers(docLayers, layer),+ isLayerEffectivelyVisible: (layer) => computeLayerVisibleForLayers(docLayers, layer),+ tabId: docId,+ perspectiveRuler: isActive+ ? storeState.perspectiveRuler+ : targetDoc.perspectiveRuler ?? null,+ animationTimeline:+ targetDoc.animation !== undefined+ ? targetDoc.animation+ : isActive+ ? storeState.animationTimeline+ : null,+ timelapse:+ tlStats.enabled || tlStats.frameCount > 0+ ? { enabled: tlStats.enabled, frameCount: tlStats.frameCount }+ : null,+ onProgress,+ };- const preferredExt =- savedFileInfo?.extension && savedFileInfo.extension.toLowerCase() !== '.sora'- ? savedFileInfo.extension- : '.ink';+ const preferredExt =+ docSavedInfo?.extension && docSavedInfo.extension.toLowerCase() !== '.sora'+ ? docSavedInfo.extension+ : '.ink';- if (!savedFileInfo?.handle || savedFileInfo.extension?.toLowerCase() === '.sora') {- try {- const info = await promptSaveAs(docData, preferredExt);- documentStoreActions.setSavedFileInfo(info);- documentStoreActions.setDocumentName(info.name);+ const applySavedMetadata = (+ info: { name: string; handle?: any; extension: string; size?: number; previewDataUrl?: string },+ updateHandle: boolean+ ) => {+ const latestActiveId = useDocumentStore.getState().activeDocumentId;+ if (latestActiveId === docId) {+ if (updateHandle) {+ documentStoreActions.setSavedFileInfo(info);+ }+ documentStoreActions.setDocumentName(info.name);+ }documentStoreActions.setDocuments((prev) =>prev.map((d) =>- d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d+ d.id === docId+ ? {+ ...d,+ name: info.name,+ ...(updateHandle ? { savedFileInfo: info } : {}),+ isDirty: false,+ }+ : d));saveRecentDocument({- id: activeDocumentId || `doc-${Date.now()}`,+ id: docId,title: info.name,path: `InkStudio\\${info.name}`,size: info.size || 1572864,- coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,+ coverUrl: info.previewDataUrl || docLayers[0]?.thumbnailUrl,isStarred: false,fileType: info.extension,isSaved: true,}).catch(console.warn);showToast(`Saved to ${info.name}`);- } catch (err: unknown) {- const msg = err instanceof Error ? err.message : String(err);- if (msg !== 'Save canceled') {+ };++ if (!docSavedInfo?.handle || docSavedInfo.extension?.toLowerCase() === '.sora') {+ try {+ const info = await promptSaveAs(docData, preferredExt);+ applySavedMetadata(info, true);+ return 'saved';+ } catch (err: unknown) {+ const msg = err instanceof Error ? err.message : String(err);+ if (msg === 'Save canceled') {+ return 'canceled';+ }alert('Failed to save file: ' + msg);+ return 'error';+ } finally {+ uiStoreActions.setLoading(false, '');}- } finally {- uiStoreActions.setLoading(false, '');}- } else {+try {- const saveRes = await saveToExistingHandle(docData, savedFileInfo);- documentStoreActions.setDocumentName(savedFileInfo.name);- documentStoreActions.setDocuments((prev) =>- prev.map((d) =>- d.id === activeDocumentId ? { ...d, name: savedFileInfo.name, isDirty: false } : d- )+ const saveRes = await saveToExistingHandle(docData, docSavedInfo);+ applySavedMetadata(+ {+ name: docSavedInfo.name,+ handle: docSavedInfo.handle,+ extension: docSavedInfo.extension,+ size: saveRes.size,+ previewDataUrl: saveRes.previewDataUrl,+ },+ false);- saveRecentDocument({- id: activeDocumentId || `doc-${Date.now()}`,- title: savedFileInfo.name,- path: `InkStudio\\${savedFileInfo.name}`,- size: saveRes.size || 1572864,- coverUrl: saveRes.previewDataUrl || layers[0]?.thumbnailUrl,- isStarred: false,- fileType: savedFileInfo.extension,- isSaved: true,- }).catch(console.warn);- showToast(`Saved to ${savedFileInfo.name}`);+ return 'saved';} catch (err: unknown) {console.warn('Direct handle save failed, prompting with Save As:', err);try {const info = await promptSaveAs(docData, preferredExt);- documentStoreActions.setSavedFileInfo(info);- documentStoreActions.setDocumentName(info.name);- documentStoreActions.setDocuments((prev) =>- prev.map((d) =>- d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d- )- );- saveRecentDocument({- id: activeDocumentId || `doc-${Date.now()}`,- title: info.name,- path: `InkStudio\\${info.name}`,- size: info.size || 1572864,- coverUrl: info.previewDataUrl || layers[0]?.thumbnailUrl,- isStarred: false,- fileType: info.extension,- isSaved: true,- }).catch(console.warn);- showToast(`Saved to ${info.name}`);+ applySavedMetadata(info, true);+ return 'saved';} catch (e: unknown) {const msg = e instanceof Error ? e.message : String(e);- if (msg !== 'Save canceled') {- alert('Failed to save file: ' + msg);+ if (msg === 'Save canceled') {+ return 'canceled';}+ alert('Failed to save file: ' + msg);+ return 'error';}} finally {uiStoreActions.setLoading(false, '');}- }- }, [activeDocumentId, buildSaveData, layers, savedFileInfo, showToast]);+ },+ [showToast]+ );++ const handleSave = useCallback(async () => {+ const currentId = useDocumentStore.getState().activeDocumentId;+ if (!currentId) return;+ await handleSaveDocumentById(currentId);+ }, [handleSaveDocumentById]);const handleSaveAs = useCallback(async () => {const onProgress = (p: SaveProgress) => {@@ -859,6 +966,7 @@ export function useDocumentLifecycle({handleTriggerOpenFile,handleFileInputChange,handleSave,+ handleSaveDocumentById,handleSaveAs,handleExportImage,handleSelectWelcomeDocument,@@ -879,12 +987,13 @@ export interface DocumentLifecycleManagerProps {) => { layers: LayerItem[]; activeLayerId: string };resetZoomAndCenter: (dims?: CanvasDimensions) => void;resetHistory: (targetDocumentId?: string) => void;+ onSelectDocument: (id: string) => void;}/*** Headless lifecycle coordinator: handles startup crash recovery detection,* initial canvas creation, WAL checkpointing, tile memory budget sync,- * and active document tab metadata synchronization.+ * active document tab metadata synchronization, and app close confirmation guard.*/export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> = React.memo(({@@ -895,6 +1004,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =resetToNewCanvas,resetZoomAndCenter,resetHistory,+ onSelectDocument,}) => {const documents = useDocumentStore((s) => s.documents);const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);@@ -902,6 +1012,7 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =const colorMode = useDocumentStore((s) => s.colorMode);const documentName = useDocumentStore((s) => s.documentName);const appSettings = useUiStore((s) => s.appSettings);+ const appClosePrompt = useUiStore((s) => s.appClosePrompt);// 1. Scan for unfinalized crashed WAL sessions on launchuseEffect(() => {@@ -1072,6 +1183,60 @@ export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> =});}, [layers, activeLayerId, activeDocumentId]);+ // 6. Intercept OS/window close requests (Alt+F4, taskbar close, WM close) and show quit confirmation+ useEffect(() => {+ if (isTauriEnvironment()) {+ let disposed = false;+ let unlisten: (() => void) | undefined;++ void import('@tauri-apps/api/window')+ .then(({ getCurrentWindow }) =>+ getCurrentWindow().onCloseRequested((event) => {+ if (isFinalizingAppClose()) return;+ event.preventDefault();+ requestAppClose();+ })+ )+ .then((fn) => {+ if (disposed) {+ fn();+ } else {+ unlisten = fn;+ }+ })+ .catch((err) => {+ console.warn('Failed to register Tauri close-requested guard:', err);+ });++ return () => {+ disposed = true;+ if (unlisten) unlisten();+ };+ }++ // Browser fallback: warn via native beforeunload dialog when closing tab with unsaved work+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {+ if (isFinalizingAppClose()) return;+ const hasDirty = useDocumentStore.getState().documents.some((d) => Boolean(d.isDirty));+ if (hasDirty) {+ e.preventDefault();+ e.returnValue = '';+ }+ };+ window.addEventListener('beforeunload', handleBeforeUnload);+ return () => window.removeEventListener('beforeunload', handleBeforeUnload);+ }, []);++ // 7. Focus the canvas currently being confirmed during the per-canvas save prompt+ const pendingCloseDocId =+ appClosePrompt.isOpen && appClosePrompt.step === 'per-canvas'+ ? appClosePrompt.pendingDocIds[appClosePrompt.currentIndex] ?? null+ : null;+ useEffect(() => {+ if (!pendingCloseDocId) return;+ onSelectDocument(pendingCloseDocId);+ }, [pendingCloseDocId, onSelectDocument]);+return null;});diff --git a/src/components/FloatingBrushPill.tsx b/src/components/FloatingBrushPill.tsxindex 1a7881f..34d01a7 100644--- a/src/components/FloatingBrushPill.tsx+++ b/src/components/FloatingBrushPill.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useCallback } from 'react';-import { ToolType, BrushSettings, LiquifySettings } from '../types/editor';+import { ToolType, BrushSettings, LiquifySettings, RetouchSettings } from '../types/editor';interface FloatingBrushPillProps {tool: ToolType;@@ -7,6 +7,8 @@ interface FloatingBrushPillProps {onUpdateBrushSettings: (patch: Partial<BrushSettings>) => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (patch: Partial<LiquifySettings>) => void;+ retouchSettings?: RetouchSettings;+ onUpdateRetouchSettings?: (patch: Partial<RetouchSettings>) => void;primaryColor?: string;onSwapColors?: () => void;zoom?: number;@@ -33,6 +35,8 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({onUpdateBrushSettings,liquifySettings,onUpdateLiquifySettings,+ retouchSettings,+ onUpdateRetouchSettings,primaryColor = '#000000',onSwapColors,zoom = 1,@@ -43,13 +47,21 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({const opacityTrackRef = useRef<HTMLDivElement>(null);const isLiquify = tool === 'liquify';- const minSize = isLiquify ? 5 : MIN_BRUSH_SIZE;- const maxSize = isLiquify ? 500 : MAX_BRUSH_SIZE;-- const currentSize = isLiquify ? (liquifySettings?.size ?? 80) : brushSettings.size;+ const isRetouch = tool === 'retouch';+ const usesStrength = isLiquify || isRetouch;+ const minSize = isLiquify ? 5 : isRetouch ? 2 : MIN_BRUSH_SIZE;+ const maxSize = isLiquify ? 500 : isRetouch ? 300 : MAX_BRUSH_SIZE;++ const currentSize = isLiquify+ ? (liquifySettings?.size ?? 80)+ : isRetouch+ ? (retouchSettings?.size ?? 40)+ : brushSettings.size;const currentOpacity = isLiquify? (liquifySettings?.strength ?? 50) / 100- : (brushSettings.opacity ?? 1);+ : isRetouch+ ? (retouchSettings?.strength ?? 50) / 100+ : (brushSettings.opacity ?? 1);const sizeRatio = sizeToRatio(currentSize, minSize, maxSize);const opacityRatio = Math.max(0.01, Math.min(1, currentOpacity));@@ -63,11 +75,13 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({const nextSize = ratioToSize(ratio, minSize, maxSize);if (isLiquify) {onUpdateLiquifySettings?.({ size: nextSize });+ } else if (isRetouch) {+ onUpdateRetouchSettings?.({ size: Math.round(nextSize) });} else {onUpdateBrushSettings({ size: nextSize });}},- [isLiquify, maxSize, minSize, onUpdateBrushSettings, onUpdateLiquifySettings]+ [isLiquify, isRetouch, maxSize, minSize, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]);const updateOpacityFromPointer = useCallback(@@ -78,11 +92,13 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({const ratio = Math.max(0.01, Math.min(1, 1 - (clientY - rect.top) / rect.height));if (isLiquify) {onUpdateLiquifySettings?.({ strength: Math.round(ratio * 100) });+ } else if (isRetouch) {+ onUpdateRetouchSettings?.({ strength: Math.round(ratio * 100) });} else {onUpdateBrushSettings({ opacity: Math.round(ratio * 100) / 100 });}},- [isLiquify, onUpdateBrushSettings, onUpdateLiquifySettings]+ [isLiquify, isRetouch, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings]);const showSizeHud = activeDrag === 'size' || hoveredTrack === 'size';@@ -197,7 +213,7 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({}}}onPointerCancel={() => setActiveDrag(null)}- title={`${isLiquify ? 'Strength' : 'Opacity'}: ${Math.round(opacityRatio * 100)}%`}+ title={`${usesStrength ? 'Strength' : 'Opacity'}: ${Math.round(opacityRatio * 100)}%`}className="relative w-4 h-28 flex items-center justify-center cursor-ns-resize touch-none group"><div className="w-1.5 h-full rounded-full bg-[#161616] group-hover:bg-[#2c2c2c] relative overflow-hidden transition-colors">@@ -221,7 +237,7 @@ export const FloatingBrushPill: React.FC<FloatingBrushPillProps> = React.memo(({{showOpacityHud && (<div className="pointer-events-none absolute left-8 top-1/2 -translate-y-1/2 px-2 py-1 rounded bg-[#202020] shadow-[0_4px_16px_rgba(0,0,0,0.6)] whitespace-nowrap flex items-center gap-1.5"><span className="text-[10px] text-[#8a8a8a]">- {isLiquify ? 'Strength' : 'Opacity'}+ {usesStrength ? 'Strength' : 'Opacity'}</span><span className="text-[11px] font-mono text-[#e5e5e5] font-medium">{Math.round(opacityRatio * 100)}%diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsxindex 8d06685..338e0ab 100644--- a/src/components/GlobalShortcutListener.tsx+++ b/src/components/GlobalShortcutListener.tsx@@ -54,8 +54,12 @@ export interface GlobalShortcutListenerProps {handleSave: () => void;handleSaveAs: () => void;duplicateLayer: (layerId: string) => void;+ handleCutSelection: () => void;+ handleCopySelection: () => void;handleCopySelectedLayer: () => void;handlePasteSelectedLayer: () => void;+ handleMoveSelectionToNewLayer: () => void;+ handleCopySelectionToNewLayer: () => void;handleGroupSelectedLayers: () => void;handleStartTransform: () => void;handleSelectAll: () => void;@@ -177,12 +181,24 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReaMath.min(500, Math.round(stepBrushSizePreset(toolState.liquifySettings.size, dir))));toolStoreActions.updateLiquifySettings({ size: nextSize });+ } else if (toolState.tool === 'retouch') {+ const nextSize = Math.max(+ 2,+ Math.min(300, Math.round(stepBrushSizePreset(toolState.retouchSettings.size, dir)))+ );+ toolStoreActions.updateRetouchSettings({ size: nextSize });} else if (toolState.tool === 'shape') {const nextWidth = Math.max(1,Math.min(120, Math.round(stepBrushSizePreset(toolState.shapeSettings.strokeWidth, dir))));toolStoreActions.updateShapeSettings({ strokeWidth: nextWidth });+ } else if (toolState.tool === 'pen') {+ const nextWidth = Math.max(+ 1,+ Math.min(100, Math.round(stepBrushSizePreset(toolState.penSettings.strokeWidth, dir)))+ );+ toolStoreActions.updatePenSettings({ strokeWidth: nextWidth });} else {const nextSize = stepBrushSizePreset(toolState.brushSettings.size, dir);toolStoreActions.updateBrushSettings({ size: nextSize });@@ -237,13 +253,31 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaif (!p.hasOpenDocument || p.transformSession?.active) return;p.redo();},+ 'edit.cut': () => {+ const p = propsRef.current;+ if (!p.hasOpenDocument) return;+ if (p.selection) {+ p.handleCutSelection();+ } else {+ p.handleCopySelectedLayer();+ }+ },'edit.copy': () => {- if (!propsRef.current.hasOpenDocument) return;- propsRef.current.handleCopySelectedLayer();+ const p = propsRef.current;+ if (!p.hasOpenDocument) return;+ if (p.selection) {+ p.handleCopySelection();+ } else {+ p.handleCopySelectedLayer();+ }},'edit.paste': () => {if (propsRef.current.hasOpenDocument) propsRef.current.handlePasteSelectedLayer();},+ 'edit.moveSelectionToNewLayer': () => {+ const p = propsRef.current;+ if (p.hasOpenDocument && p.selection) p.handleMoveSelectionToNewLayer();+ },'edit.delete': () => {const p = propsRef.current;if (!p.hasOpenDocument) return;@@ -293,7 +327,12 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea},'layer.duplicate': () => {const p = propsRef.current;- if (p.hasOpenDocument && p.activeLayer) p.duplicateLayer(p.activeLayerId);+ if (!p.hasOpenDocument || !p.activeLayer) return;+ if (p.selection) {+ p.handleCopySelectionToNewLayer();+ } else {+ p.duplicateLayer(p.activeLayerId);+ }},'layer.group': () => {if (propsRef.current.hasOpenDocument) propsRef.current.handleGroupSelectedLayers();@@ -409,9 +448,18 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaconst tempTool = modifierActionToTempTool(action);if (tempTool && modKey) {+ const curState = useToolStore.getState();+ const reserveAltForActiveTool =+ modKey === 'Alt' &&+ tempTool === 'pipette' &&+ ((curState.tool === 'retouch' && curState.retouchSettings.mode === 'clone-stamp') ||+ curState.tool === 'pen');+ if (reserveAltForActiveTool) {+ return;+ }if (modKey === 'Alt') e.preventDefault();if (!activeModHoldRef.current && !e.repeat) {- const currentTool = useToolStore.getState().tool;+ const currentTool = curState.tool;if (currentTool !== tempTool) {activeModHoldRef.current = { modKey, prevTool: currentTool, tempTool };if (modKey === 'Alt') {@@ -428,6 +476,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaif (activeModHoldRef.current &&(e.code === 'Space' ||+ e.key === ' ' ||(activeModHoldRef.current.modKey === 'Alt' && (e.ctrlKey || e.metaKey || e.shiftKey)) ||(activeModHoldRef.current.modKey === 'Control' && (e.altKey || e.shiftKey)) ||(activeModHoldRef.current.modKey === 'Shift' && (e.ctrlKey || e.metaKey || e.altKey)))@@ -442,7 +491,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaif (matched) {// Guard special contextual exceptions before preventDefault- if (matched.id === 'edit.copy') {+ if (matched.id === 'edit.copy' || matched.id === 'edit.cut') {const textSel = window.getSelection()?.toString();if (textSel && textSel.length > 0) return;}diff --git a/src/components/GradientOverlay.tsx b/src/components/GradientOverlay.tsxnew file mode 100644index 0000000..6e0d447--- /dev/null+++ b/src/components/GradientOverlay.tsx@@ -0,0 +1,247 @@+import React, { useEffect, useRef } from 'react';+import type {+ CanvasDimensions,+ GradientDragPreview,+ GradientMeshState,+} from '../types/editor';+import { rasterizeMeshGradientToRgba } from '../utils/gradientEngine';++export interface GradientOverlayProps {+ dimensions: CanvasDimensions;+ zoom: number;+ flipX: boolean;+ flipY: boolean;+ dragPreview: GradientDragPreview | null;+ mesh: GradientMeshState | null;+ opacity: number;+ onApplyMesh?: () => void;+ onCancelMesh?: () => void;+}++const MAX_PREVIEW_DIM = 384;++export const GradientOverlay: React.FC<GradientOverlayProps> = React.memo(+ ({+ dimensions,+ zoom,+ flipX,+ flipY,+ dragPreview,+ mesh,+ opacity,+ onApplyMesh,+ onCancelMesh,+ }) => {+ const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const invZoom = 1 / Math.max(0.05, zoom);++ useEffect(() => {+ const canvas = previewCanvasRef.current;+ if (!canvas || !mesh) return;+ const scale = Math.min(+ 1,+ MAX_PREVIEW_DIM / Math.max(1, dimensions.width, dimensions.height)+ );+ const pw = Math.max(1, Math.round(dimensions.width * scale));+ const ph = Math.max(1, Math.round(dimensions.height * scale));+ if (canvas.width !== pw || canvas.height !== ph) {+ canvas.width = pw;+ canvas.height = ph;+ }+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ const rgba = rasterizeMeshGradientToRgba(mesh, 0, 0, pw, ph, scale, scale, false, 6);+ const img = new ImageData(new Uint8ClampedArray(rgba.buffer as ArrayBuffer), pw, ph);+ ctx.clearRect(0, 0, pw, ph);+ ctx.putImageData(img, 0, 0);+ }, [dimensions.height, dimensions.width, mesh]);++ if (!dragPreview && !mesh) return null;++ return (+ <>+ {dragPreview && (() => {+ const { start, end, type } = dragPreview;+ const dx = end.x - start.x;+ const dy = end.y - start.y;+ const dist = Math.hypot(dx, dy);+ const angleDeg = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;+ return (+ <>+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ {type === 'radial' && dist > 1 && (+ <circle+ cx={start.x}+ cy={start.y}+ r={dist}+ fill="none"+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.5 * invZoom}+ strokeDasharray={`${6 * invZoom} ${4 * invZoom}`}+ />+ )}+ <line+ x1={start.x}+ y1={start.y}+ x2={end.x}+ y2={end.y}+ stroke="#000000"+ strokeOpacity={0.7}+ strokeWidth={3 * invZoom}+ />+ <line+ x1={start.x}+ y1={start.y}+ x2={end.x}+ y2={end.y}+ stroke="#ffffff"+ strokeWidth={1.5 * invZoom}+ />+ <circle+ cx={start.x}+ cy={start.y}+ r={5 * invZoom}+ fill="#ffffff"+ stroke="#000000"+ strokeWidth={1.5 * invZoom}+ />+ <circle+ cx={end.x}+ cy={end.y}+ r={5 * invZoom}+ fill="var(--accent, #38bdf8)"+ stroke="#000000"+ strokeWidth={1.5 * invZoom}+ />+ </svg>+ <div+ className="absolute pointer-events-none z-35 px-1.5 py-0.5 rounded bg-[#161616]/90 border border-white/15 text-[#e5e5e5] font-mono text-[10px] whitespace-nowrap"+ style={{+ left: `${end.x}px`,+ top: `${end.y}px`,+ transform: `translate(${10 * invZoom}px, ${10 * invZoom}px) scale(${+ (flipX ? -1 : 1) * invZoom+ }, ${(flipY ? -1 : 1) * invZoom})`,+ transformOrigin: 'top left',+ }}+ >+ {Math.round(dist)}px · {Math.round(angleDeg)}°+ </div>+ </>+ );+ })()}++ {mesh && (+ <>+ <canvas+ ref={previewCanvasRef}+ className="absolute inset-0 w-full h-full pointer-events-none z-30"+ style={{ opacity: Math.max(0.05, Math.min(1, opacity)) }}+ />+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ {/* Horizontal mesh wires */}+ {Array.from({ length: mesh.rows }).map((_, r) =>+ Array.from({ length: mesh.cols - 1 }).map((__, c) => {+ const a = mesh.nodes[r * mesh.cols + c];+ const b = mesh.nodes[r * mesh.cols + c + 1];+ if (!a || !b) return null;+ return (+ <line+ key={`mh-${r}-${c}`}+ x1={a.x}+ y1={a.y}+ x2={b.x}+ y2={b.y}+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ );+ })+ )}+ {/* Vertical mesh wires */}+ {Array.from({ length: mesh.rows - 1 }).map((_, r) =>+ Array.from({ length: mesh.cols }).map((__, c) => {+ const a = mesh.nodes[r * mesh.cols + c];+ const b = mesh.nodes[(r + 1) * mesh.cols + c];+ if (!a || !b) return null;+ return (+ <line+ key={`mv-${r}-${c}`}+ x1={a.x}+ y1={a.y}+ x2={b.x}+ y2={b.y}+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ );+ })+ )}+ {/* Draggable control nodes */}+ {mesh.nodes.map((node, idx) => {+ const isSelected = mesh.selectedNodeIndex === idx;+ return (+ <g key={`mn-${idx}`}>+ <circle+ cx={node.x}+ cy={node.y}+ r={(isSelected ? 8 : 6) * invZoom}+ fill={node.color}+ stroke={isSelected ? '#38bdf8' : '#ffffff'}+ strokeWidth={(isSelected ? 2.5 : 1.75) * invZoom}+ />+ </g>+ );+ })}+ </svg>++ {/* Floating Mesh Commit / Cancel Action Bar */}+ {mesh.nodes.length > 0 && (+ <div+ onPointerDown={(e) => e.stopPropagation()}+ className="absolute z-40 flex items-center gap-1 px-1.5 py-1 rounded bg-[#181818]/95 border border-white/15 shadow-lg"+ style={{+ left: `${mesh.nodes[0].x}px`,+ top: `${Math.max(8, mesh.nodes[0].y - 36 * invZoom)}px`,+ transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,+ transformOrigin: 'top left',+ }}+ >+ <span className="text-[10px] text-[#8a8a8a] px-1">+ Mesh ({mesh.cols}×{mesh.rows})+ </span>+ <button+ type="button"+ onClick={onApplyMesh}+ className="px-2 py-0.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer"+ >+ Apply+ </button>+ <button+ type="button"+ onClick={onCancelMesh}+ className="px-2 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ >+ Cancel+ </button>+ </div>+ )}+ </>+ )}+ </>+ );+ }+);++GradientOverlay.displayName = 'GradientOverlay';diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsxindex 519a168..1c57b76 100644--- a/src/components/LeftPanel.tsx+++ b/src/components/LeftPanel.tsx@@ -14,6 +14,12 @@ import { ToolPropertyInspector } from './ToolPropertyInspector';export interface LeftPanelProps {onDeselect?: () => void;onTransformSelection?: () => void;+ onClearSelection?: () => void;+ onDeleteOutsideSelection?: () => void;+ onCutSelection?: () => void;+ onCopySelection?: () => void;+ onPasteSelection?: () => void;+ onMoveSelectionToNewLayer?: () => void;onExpandSelection?: (pixels: number) => void;onContractSelection?: (pixels: number) => void;onFeatherSelection?: (radius: number) => void;@@ -25,6 +31,12 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({onDeselect,onTransformSelection,+ onClearSelection,+ onDeleteOutsideSelection,+ onCutSelection,+ onCopySelection,+ onPasteSelection,+ onMoveSelectionToNewLayer,onExpandSelection,onContractSelection,onFeatherSelection,@@ -113,6 +125,12 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(setCustomBrushes={setCustomBrushes}onDeselect={onDeselect}onTransformSelection={onTransformSelection}+ onClearSelection={onClearSelection}+ onDeleteOutsideSelection={onDeleteOutsideSelection}+ onCutSelection={onCutSelection}+ onCopySelection={onCopySelection}+ onPasteSelection={onPasteSelection}+ onMoveSelectionToNewLayer={onMoveSelectionToNewLayer}onExpandSelection={onExpandSelection}onContractSelection={onContractSelection}onFeatherSelection={onFeatherSelection}diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsxindex c8e70f8..82ddc05 100644--- a/src/components/ModalHost.tsx+++ b/src/components/ModalHost.tsx@@ -33,6 +33,9 @@ import { WebtoonExportModal } from './WebtoonExportModal';import { TimelapseExportModal } from './TimelapseExportModal';import { UpdateModal } from './UpdateModal';import { UpdateToast } from './UpdateToast';+import { BrushStudioModal } from './BrushStudioModal';+import { CloseConfirmModal } from './CloseConfirmModal';+import { SaveDocumentResult } from '../utils/appCloseFlow';export type InviteLinkPayload = ParsedInviteLink;@@ -105,6 +108,7 @@ export interface ModalHostProps {) => Promise<boolean>;onCaptureTimelapseNow?: () => void;handleSave?: () => void;+ handleSaveDocumentById: (docId: string) => Promise<SaveDocumentResult>;showToast: (msg: string) => void;}@@ -153,6 +157,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(joinRoom,onCaptureTimelapseNow,handleSave,+ handleSaveDocumentById,showToast,}) => {const dimensions = useDocumentStore((s) => s.dimensions);@@ -173,6 +178,7 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(const isMangaEffectsModalOpen = useUiStore((s) => s.isMangaEffectsModalOpen);const isWebtoonExportModalOpen = useUiStore((s) => s.isWebtoonExportModalOpen);const isTimelapseExportModalOpen = useUiStore((s) => s.isTimelapseExportModalOpen);+ const isBrushStudioModalOpen = useUiStore((s) => s.isBrushStudioModalOpen);const isLoadingFile = useUiStore((s) => s.isLoadingFile);const loadingStatus = useUiStore((s) => s.loadingStatus);const toastMessage = useUiStore((s) => s.toastMessage);@@ -252,6 +258,12 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(showToast={showToast}/>+ <BrushStudioModal+ isOpen={isBrushStudioModalOpen}+ onClose={() => uiStoreActions.setBrushStudioModalOpen(false)}+ showToast={showToast}+ />+<TonalCorrectionModalisOpen={tonalModalState.isOpen}type={tonalModalState.type}@@ -399,6 +411,8 @@ export const ModalHost: React.FC<ModalHostProps> = React.memo(/><UpdateToast />++ <CloseConfirmModal onSaveDocumentById={handleSaveDocumentById} /></>);}diff --git a/src/components/PenPathOverlay.tsx b/src/components/PenPathOverlay.tsxnew file mode 100644index 0000000..0a3b799--- /dev/null+++ b/src/components/PenPathOverlay.tsx@@ -0,0 +1,221 @@+import React from 'react';+import type {+ CanvasDimensions,+ PenPathSession,+ PenToolSettings,+} from '../types/editor';+import { buildBezierSvgPath } from '../utils/bezierEngine';++export interface PenPathOverlayProps {+ dimensions: CanvasDimensions;+ zoom: number;+ flipX: boolean;+ flipY: boolean;+ session: PenPathSession;+ settings: PenToolSettings;+ primaryColor: string;+ secondaryColor: string;+ onCommit?: () => void;+ onCancel?: () => void;+ onToggleClose?: () => void;+}++export const PenPathOverlay: React.FC<PenPathOverlayProps> = React.memo(+ ({+ dimensions,+ zoom,+ flipX,+ flipY,+ session,+ settings,+ primaryColor,+ secondaryColor,+ onCommit,+ onCancel,+ onToggleClose,+ }) => {+ const { knots, closed, selectedAnchorIndex, hoverPoint } = session;+ if (knots.length === 0) return null;++ const invZoom = 1 / Math.max(0.05, zoom);+ const mainD = buildBezierSvgPath(knots, closed);+ const fillColor =+ settings.fillEnabled && closed+ ? settings.fillColorMode === 'primary'+ ? primaryColor+ : settings.fillColorMode === 'secondary'+ ? secondaryColor+ : settings.customFillColor+ : 'none';++ // Live rubber-band cubic Bézier preview from last anchor to cursor in draw mode+ let rubberD = '';+ if (+ settings.mode === 'draw' &&+ settings.rubberBandPreview &&+ !closed &&+ hoverPoint &&+ knots.length >= 1+ ) {+ const last = knots[knots.length - 1];+ const c1 = last.handleOut || last;+ rubberD = `M ${last.x} ${last.y} C ${c1.x} ${c1.y}, ${hoverPoint.x} ${hoverPoint.y}, ${hoverPoint.x} ${hoverPoint.y}`;+ }++ const first = knots[0];+ const barX = first.x;+ const barY = Math.max(8, first.y - 38 * invZoom);++ return (+ <>+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ {/* Rendered stroke/fill preview */}+ {knots.length >= 2 && (+ <path+ d={mainD}+ fill={fillColor}+ stroke={settings.strokeEnabled ? primaryColor || '#000000' : 'none'}+ strokeWidth={Math.max(0.5, settings.strokeWidth)}+ strokeLinecap="round"+ strokeLinejoin="round"+ opacity={Math.max(0.05, Math.min(1, settings.opacity))}+ />+ )}++ {/* Crisp vector wireframe centerline */}+ {knots.length >= 2 && (+ <path+ d={mainD}+ fill="none"+ stroke="#38bdf8"+ strokeWidth={1.35 * invZoom}+ />+ )}++ {/* Live rubber-band preview curve */}+ {rubberD && (+ <path+ d={rubberD}+ fill="none"+ stroke="#38bdf8"+ strokeOpacity={0.7}+ strokeWidth={1.25 * invZoom}+ strokeDasharray={`${5 * invZoom} ${4 * invZoom}`}+ />+ )}++ {/* Tangent handle bars and handle tip circles */}+ {knots.map((k, idx) => (+ <g key={`bh-${idx}`}>+ {k.handleIn && (+ <>+ <line+ x1={k.x}+ y1={k.y}+ x2={k.handleIn.x}+ y2={k.handleIn.y}+ stroke="#f59e0b"+ strokeWidth={1.2 * invZoom}+ />+ <circle+ cx={k.handleIn.x}+ cy={k.handleIn.y}+ r={4 * invZoom}+ fill="#fbbf24"+ stroke="#000000"+ strokeWidth={1 * invZoom}+ />+ </>+ )}+ {k.handleOut && (+ <>+ <line+ x1={k.x}+ y1={k.y}+ x2={k.handleOut.x}+ y2={k.handleOut.y}+ stroke="#f59e0b"+ strokeWidth={1.2 * invZoom}+ />+ <circle+ cx={k.handleOut.x}+ cy={k.handleOut.y}+ r={4 * invZoom}+ fill="#fbbf24"+ stroke="#000000"+ strokeWidth={1 * invZoom}+ />+ </>+ )}+ </g>+ ))}++ {/* Anchor point markers */}+ {knots.map((k, idx) => {+ const isSelected = selectedAnchorIndex === idx;+ const isFirst = idx === 0 && !closed && knots.length >= 2;+ const sz = (isSelected ? 8 : 6.5) * invZoom;+ return (+ <rect+ key={`ba-${idx}`}+ x={k.x - sz * 0.5}+ y={k.y - sz * 0.5}+ width={sz}+ height={sz}+ fill={isSelected ? '#38bdf8' : isFirst ? '#22c55e' : '#ffffff'}+ stroke="#000000"+ strokeWidth={1.25 * invZoom}+ />+ );+ })}+ </svg>++ {/* Floating Bézier Path Action Bar */}+ <div+ onPointerDown={(e) => e.stopPropagation()}+ className="absolute z-40 flex items-center gap-1 px-1.5 py-1 rounded bg-[#181818]/95 border border-white/15 shadow-lg"+ style={{+ left: `${barX}px`,+ top: `${barY}px`,+ transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,+ transformOrigin: 'top left',+ }}+ >+ <span className="text-[10px] text-[#8a8a8a] px-1 font-mono">+ {knots.length}pt{closed ? ' · Closed' : ''}+ </span>+ {knots.length >= 2 && (+ <button+ type="button"+ onClick={onToggleClose}+ className="px-1.5 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ >+ {closed ? 'Open' : 'Close'}+ </button>+ )}+ {knots.length >= 2 && (+ <button+ type="button"+ onClick={onCommit}+ className="px-2 py-0.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer"+ >+ Commit+ </button>+ )}+ <button+ type="button"+ onClick={onCancel}+ className="px-1.5 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ >+ Cancel+ </button>+ </div>+ </>+ );+ }+);++PenPathOverlay.displayName = 'PenPathOverlay';diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsxindex 01e9eeb..6f37f14 100644--- a/src/components/SelectionOverlay.tsx+++ b/src/components/SelectionOverlay.tsx@@ -8,6 +8,14 @@ import {X,Trash2,RotateCcw,+ Scissors,+ Copy,+ ClipboardPaste,+ Layers,+ Crop,+ Maximize2,+ Minimize2,+ Feather,} from 'lucide-react';import { maskToSvgPath } from '../utils/selectionUtils';@@ -22,6 +30,11 @@ interface SelectionOverlayProps {onFillScreentone: () => void;onFillColor: () => void;onClearSelection: () => void;+ onDeleteOutsideSelection?: () => void;+ onCutSelection?: () => void;+ onCopySelection?: () => void;+ onPasteSelection?: () => void;+ onMoveSelectionToNewLayer?: () => void;onInvertSelection: () => void;onExpandSelection?: (pixels: number) => void;onContractSelection?: (pixels: number) => void;@@ -31,14 +44,16 @@ interface SelectionOverlayProps {export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({selection,dimensions,- zoom,- flipX = false,- flipY = false,onDeselect,onTransformSelection,onFillScreentone,onFillColor,onClearSelection,+ onDeleteOutsideSelection,+ onCutSelection,+ onCopySelection,+ onPasteSelection,+ onMoveSelectionToNewLayer,onInvertSelection,onExpandSelection,onContractSelection,@@ -78,10 +93,6 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({if (!selection || !bounds) return null;- const invZoom = zoom > 0 ? 1 / zoom : 1;- const fx = flipX ? -1 : 1;- const fy = flipY ? -1 : 1;-return (<>{/* 1. Floating Selected Pixels Canvas */}@@ -135,124 +146,160 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({)}</svg>- {/* 3. Floating Quick-Action Bar directly above active selection */}- <div- className="absolute z-26 pointer-events-auto select-none"- style={{- left: `${bounds.x + bounds.width / 2}px`,- top: `${bounds.y}px`,- transform: `translate(-50%, calc(-100% - ${8 * invZoom}px)) scale(${fx * invZoom}, ${fy * invZoom})`,- transformOrigin: 'bottom center',- }}- onPointerDown={(e) => e.stopPropagation()}- >- <div className="bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl px-1.5 py-1 flex items-center space-x-1 whitespace-nowrap text-[11px] text-[#e5e5e5]">+ {/* 3. Unified Selection Action Bar (Single viewport-anchored launcher) */}+ {createPortal(+ <div+ className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 max-w-[95vw] bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl px-2 py-1 flex flex-wrap items-center justify-center gap-1 select-none text-[11px] text-[#e5e5e5]"+ onPointerDown={(e) => e.stopPropagation()}+ ><button+ type="button"+ onClick={onDeselect}+ title="Deselect (Ctrl+D)"+ className="px-1.5 py-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ <span>Deselect</span>+ </button>++ <button+ type="button"+ onClick={onInvertSelection}+ title="Invert Selection (Ctrl+Shift+I)"+ className="px-1.5 py-1 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <RotateCcw className="w-3.5 h-3.5" />+ <span>Invert</span>+ </button>++ <button+ type="button"onClick={() => onExpandSelection?.(5)}title="Expand Selection (+5px)"- className="px-1.5 py-0.5 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded cursor-pointer transition-colors"+ className="p-1 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer">- Expand+ <Maximize2 className="w-3.5 h-3.5" /></button><button+ type="button"onClick={() => onContractSelection?.(5)}title="Contract Selection (-5px)"- className="px-1.5 py-0.5 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded cursor-pointer transition-colors"+ className="p-1 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer">- Contract+ <Minimize2 className="w-3.5 h-3.5" /></button><button+ type="button"onClick={() => onFeatherSelection?.(5)}title="Feather Selection (5px)"- className="px-1.5 py-0.5 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded cursor-pointer transition-colors"+ className="p-1 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer">- Feather+ <Feather className="w-3.5 h-3.5" /></button>- <div className="w-px h-3.5 bg-white/[0.08]" />+ <div className="w-px h-4 bg-white/[0.08]" />- <button- onClick={onInvertSelection}- title="Invert Selection (Ctrl+Shift+I)"- className="px-1.5 py-0.5 text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded cursor-pointer transition-colors"- >- Invert- </button>+ {onCutSelection && (+ <button+ type="button"+ onClick={onCutSelection}+ title="Cut Selection (Ctrl+X)"+ className="px-1.5 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <Scissors className="w-3.5 h-3.5" />+ <span>Cut</span>+ </button>+ )}- <button- onClick={onTransformSelection}- title="Transform Selection (Ctrl+T)"- className="px-1.5 py-0.5 text-[var(--accent)] hover:bg-[#2c2c2c] rounded font-medium cursor-pointer transition-colors"- >- Transform- </button>+ {onCopySelection && (+ <button+ type="button"+ onClick={onCopySelection}+ title="Copy Selection (Ctrl+C)"+ className="px-1.5 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <Copy className="w-3.5 h-3.5" />+ <span>Copy</span>+ </button>+ )}- <button- onClick={onDeselect}- title="Deselect (Ctrl+D)"- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded cursor-pointer transition-colors"- >- <X className="w-3.5 h-3.5" />- </button>- </div>- </div>+ {onPasteSelection && (+ <button+ type="button"+ onClick={onPasteSelection}+ title="Paste to New Layer (Ctrl+V)"+ className="px-1.5 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <ClipboardPaste className="w-3.5 h-3.5" />+ <span>Paste</span>+ </button>+ )}- {/* 4. Selection Launcher Bar (Fixed at bottom center of viewport) */}- {createPortal(- <div- className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-md shadow-2xl px-2 py-1 flex items-center space-x-1.5 select-none text-[11px]"- onPointerDown={(e) => e.stopPropagation()}- >- <button- onClick={onDeselect}- title="Deselect (Ctrl+D)"- className="px-2 py-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"- >- Deselect- </button>+ {onMoveSelectionToNewLayer && (+ <button+ type="button"+ onClick={onMoveSelectionToNewLayer}+ title="Move Selected Section to New Layer (Ctrl+Shift+J)"+ className="px-1.5 py-1 text-[var(--accent)] hover:bg-[#2c2c2c] rounded flex items-center gap-1 font-medium transition-colors cursor-pointer"+ >+ <Layers className="w-3.5 h-3.5" />+ <span>To Layer</span>+ </button>+ )}<div className="w-px h-4 bg-white/[0.08]" /><button- onClick={onFillScreentone}- title="Fill Screentone into New Layer"- className="px-2 py-1 bg-[var(--accent-subtle)] hover:bg-[#2c2c2c] text-[var(--accent)] border border-[var(--accent-border)] rounded transition-colors cursor-pointer font-medium"+ type="button"+ onClick={onClearSelection}+ title="Delete Selected Section (Del)"+ className="px-1.5 py-1 text-[#cccccc] hover:text-rose-400 hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer">- Screentone+ <Trash2 className="w-3.5 h-3.5" />+ <span>Delete</span></button>- <button- onClick={onTransformSelection}- title="Transform Selection (Ctrl+T)"- className="px-2 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"- >- Transform- </button>+ {onDeleteOutsideSelection && (+ <button+ type="button"+ onClick={onDeleteOutsideSelection}+ title="Delete Outside Selected Section"+ className="px-1.5 py-1 text-[#cccccc] hover:text-rose-400 hover:bg-[#2c2c2c] rounded flex items-center gap-1 transition-colors cursor-pointer"+ >+ <Crop className="w-3.5 h-3.5" />+ <span>Del Outside</span>+ </button>+ )}++ <div className="w-px h-4 bg-white/[0.08]" /><button+ type="button"onClick={onFillColor}- title="Fill with Foreground Color (Alt+Del)"+ title="Fill with Foreground Color"className="px-2 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer">Fill</button><button- onClick={onClearSelection}- title="Clear / Delete Selected Pixels (Del)"- className="p-1 text-[#8a8a8a] hover:text-rose-400 hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ type="button"+ onClick={onFillScreentone}+ title="Fill Screentone into New Layer"+ className="px-2 py-1 bg-[var(--accent-subtle)] hover:bg-[#2c2c2c] text-[var(--accent)] border border-[var(--accent-border)] rounded transition-colors cursor-pointer font-medium">- <Trash2 className="w-3.5 h-3.5" />+ Screentone</button><button- onClick={onInvertSelection}- title="Invert Selection (Ctrl+Shift+I)"- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ type="button"+ onClick={onTransformSelection}+ title="Transform Selection (Ctrl+T)"+ className="px-2 py-1 text-[#e5e5e5] hover:bg-[#2c2c2c] rounded font-medium transition-colors cursor-pointer">- <RotateCcw className="w-3.5 h-3.5" />+ Transform</button></div>,document.bodydiff --git a/src/components/SphereColorPicker.tsx b/src/components/SphereColorPicker.tsxnew file mode 100644index 0000000..f4039a0--- /dev/null+++ b/src/components/SphereColorPicker.tsx@@ -0,0 +1,1591 @@+import React, { useState, useRef, useEffect, useCallback, useMemo, useId } from 'react';+import { createPortal } from 'react-dom';+import {+ Settings,+ Pipette,+ Moon,+ Droplet,+ Sun,+ X,+ RotateCcw,+ Copy,+ Check,+ Pin,+ PinOff,+ Compass,+ Sparkles,+} from 'lucide-react';+import {+ HSV,+ RGB,+ hexToHsv,+ hexToRgb,+ hsvToHex,+ rgbToHex,+ isValidHex,+} from '../utils/colorUtils';+import {+ SphereColorResult,+ SphereColorSlot,+ SphereLightingConfig,+ SphereMarkerPosition,+ SphereSlotsState,+ SphereRenderLut,+ DEFAULT_SPHERE_LIGHTING,+ DEFAULT_SPHERE_SLOTS,+ SPHERE_LIGHTING_PRESETS,+ buildSphereGeometryLut,+ updateSphereLightingLut,+ renderSphereFromLut,+ evaluateSphereColor,+ clampMarkerPosition,+ projectSphereMarker,+ getLightVectors,+} from '../utils/sphereColorMath';+import { safeLocalStorageSetItem } from '../utils/safeStorage';++export interface SpherePickerSharedState {+ slots: SphereSlotsState;+ activeSlot: SphereColorSlot;+ lighting: SphereLightingConfig;+ marker: SphereMarkerPosition;+}++export interface SphereColorPickerProps {+ /** Initial / previous color shown on the left side of the top preview bar. */+ initialColor?: string;+ /** Fired whenever the sampled sphere color changes. Returns both HEX and RGB. */+ onColorChange?: (color: SphereColorResult, commit?: boolean) => void;+ /** Optional eyedropper callback (e.g. activates host app eyedropper tool). Falls back to browser EyeDropper API. */+ onEyedropper?: () => void;+ /** Optional close handler (renders close button in floating titlebar). */+ onClose?: () => void;+ /** Toggle between docked (inside ColorPanel) and floating (unpinned draggable) modes. */+ isPinned?: boolean;+ onTogglePin?: () => void;+ /** Layout variant: 'docked' fits narrow sidebar containers; 'floating' renders standalone studio palette. */+ variant?: 'docked' | 'floating';+ /** Auto-desaturate to B&W when true (e.g., grayscale/monochrome canvas). */+ monochromeDefault?: boolean;+ /** Diameter of the sphere viewport in CSS pixels (floating mode). Auto-measured in docked mode. */+ sphereSize?: number;+ /** Optional shared state so pin/unpin transitions preserve slots, light, and marker seamlessly. */+ sharedState?: SpherePickerSharedState;+ onSharedStateChange?: (state: SpherePickerSharedState) => void;+ /** Pointer down handler on the titlebar (used by floating draggable wrapper). */+ onHeaderDragStart?: (e: React.PointerEvent<HTMLDivElement>) => void;+ /** Additional container classes. */+ className?: string;+}++interface BrowserEyeDropper {+ open: () => Promise<{ sRGBHex: string }>;+}++const SPHERE_RADIUS_RATIO = 0.465;++const DEFAULT_RIM_SLOT: HSV = DEFAULT_SPHERE_SLOTS.rim ?? { h: 200, s: 0.28, v: 0.82 };++function getGeomLightKey(lighting: SphereLightingConfig): string {+ return `${lighting.lightAzimuth}|${lighting.lightElevation}|${lighting.roughness}|${lighting.specularStrength}|${lighting.bounceIntensity}|${lighting.shadowDepth}|${lighting.rimIntensity ?? DEFAULT_SPHERE_LIGHTING.rimIntensity}|${lighting.subsurface ?? DEFAULT_SPHERE_LIGHTING.subsurface}`;+}++export function buildHarmonizedSlots(initialHex?: string): SphereSlotsState {+ if (!initialHex || !isValidHex(initialHex)) {+ return {+ shadow: { ...DEFAULT_SPHERE_SLOTS.shadow },+ base: { ...DEFAULT_SPHERE_SLOTS.base },+ light: { ...DEFAULT_SPHERE_SLOTS.light },+ rim: { ...DEFAULT_RIM_SLOT },+ };+ }+ const baseHsv = hexToHsv(initialHex);+ const hasChroma = baseHsv.s > 0.05 && baseHsv.v > 0.08;+ const h = hasChroma ? baseHsv.h : DEFAULT_SPHERE_SLOTS.base.h;+ return {+ base: {+ h,+ s: hasChroma ? Math.max(0.08, Math.min(1, baseHsv.s)) : DEFAULT_SPHERE_SLOTS.base.s,+ v: hasChroma ? Math.max(0.22, Math.min(0.98, baseHsv.v)) : DEFAULT_SPHERE_SLOTS.base.v,+ },+ shadow: {+ h: (h + 38) % 360,+ s: hasChroma ? Math.min(0.75, Math.max(0.24, baseHsv.s * 0.85)) : DEFAULT_SPHERE_SLOTS.shadow.s,+ v: 0.42,+ },+ light: {+ h: (h + 332) % 360,+ s: hasChroma ? Math.min(0.42, Math.max(0.1, baseHsv.s * 0.48)) : DEFAULT_SPHERE_SLOTS.light.s,+ v: 0.96,+ },+ rim: {+ h: (h + 344) % 360,+ s: hasChroma ? Math.min(0.88, Math.max(0.28, baseHsv.s * 0.92)) : DEFAULT_RIM_SLOT.s,+ v: 0.92,+ },+ };+}++export function createInitialSphereState(+ initialColor?: string,+ monochromeDefault = false+): SpherePickerSharedState {+ return {+ slots: buildHarmonizedSlots(initialColor),+ activeSlot: 'base',+ lighting: {+ ...DEFAULT_SPHERE_LIGHTING,+ saturation: monochromeDefault ? 0 : DEFAULT_SPHERE_LIGHTING.saturation,+ },+ marker: { x: -0.22, y: 0.28 },+ };+}++function darkenRgb(rgb: RGB, factor: number): string {+ return rgbToHex(rgb.r * factor, rgb.g * factor, rgb.b * factor);+}++function lightenRgb(rgb: RGB, amount: number): string {+ return rgbToHex(+ rgb.r + (255 - rgb.r) * amount,+ rgb.g + (255 - rgb.g) * amount,+ rgb.b + (255 - rgb.b) * amount+ );+}++/** Studio-styled 60fps pointer-captured linear slider matching Ink Studio's flat dark palette */+interface MiniBarSliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ displayValue: string;+ gradient: string;+ onChange: (value: number, commit?: boolean) => void;+ rightAction?: React.ReactNode;+ compact?: boolean;+ testId?: string;+}++const MiniBarSlider: React.FC<MiniBarSliderProps> = ({+ label,+ value,+ min,+ max,+ displayValue,+ gradient,+ onChange,+ rightAction,+ compact = false,+ testId,+}) => {+ const trackRef = useRef<HTMLDivElement | null>(null);+ const draggingRef = useRef(false);++ const emitFromX = (clientX: number, commit: boolean) => {+ const el = trackRef.current;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ if (rect.width <= 0) return;+ const ratio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));+ onChange(min + ratio * (max - min), commit);+ };++ const percent = Math.max(0, Math.min(100, ((value - min) / (max - min)) * 100));++ return (+ <div className="flex items-center gap-1.5">+ <span+ className={`${compact ? 'w-7 text-[9.5px]' : 'w-11 text-[10px]'} text-[#8a8a8a] shrink-0`}+ >+ {label}+ </span>+ <div+ role="slider"+ tabIndex={0}+ aria-label={label}+ aria-valuemin={min}+ aria-valuemax={max}+ aria-valuenow={Math.round(value * 100) / 100}+ data-testid={testId}+ onPointerDown={(e) => {+ e.preventDefault();+ draggingRef.current = true;+ e.currentTarget.setPointerCapture(e.pointerId);+ emitFromX(e.clientX, false);+ }}+ onPointerMove={(e) => {+ if (!draggingRef.current) return;+ emitFromX(e.clientX, false);+ }}+ onPointerUp={(e) => {+ if (!draggingRef.current) return;+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {+ e.currentTarget.releasePointerCapture(e.pointerId);+ }+ draggingRef.current = false;+ emitFromX(e.clientX, true);+ }}+ onPointerCancel={(e) => {+ if (!draggingRef.current) return;+ draggingRef.current = false;+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {+ e.currentTarget.releasePointerCapture(e.pointerId);+ }+ }}+ onKeyDown={(e) => {+ const step = (max - min) * (e.shiftKey ? 0.1 : 0.02);+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {+ e.preventDefault();+ onChange(Math.min(max, value + step), true);+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {+ e.preventDefault();+ onChange(Math.max(min, value - step), true);+ }+ }}+ className="flex-1 h-4 flex items-center cursor-pointer touch-none outline-none focus-visible:ring-1 focus-visible:ring-[var(--accent-border)] rounded-xs px-0.5"+ >+ <div+ ref={trackRef}+ className="relative w-full h-[5px] rounded-[2px] border border-white/[0.08]"+ style={{ background: gradient }}+ >+ <div+ style={{ left: `${percent}%` }}+ className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 w-2.5 h-3 rounded-[2px] bg-[#e5e5e5] border border-[#161616] shadow-[0_1px_3px_rgba(0,0,0,0.75)] pointer-events-none"+ />+ </div>+ </div>+ <span+ className={`${compact ? 'w-7 text-[9.5px]' : 'w-8 text-[10px]'} font-mono text-right text-[#cccccc] tabular-nums shrink-0`}+ >+ {displayValue}+ </span>+ {rightAction}+ </div>+ );+};++export const SphereColorPicker: React.FC<SphereColorPickerProps> = ({+ initialColor = '#85988E',+ onColorChange,+ onEyedropper,+ onClose,+ isPinned = false,+ onTogglePin,+ variant = 'floating',+ monochromeDefault = false,+ sphereSize: sphereSizeProp = 224,+ sharedState,+ onSharedStateChange,+ onHeaderDragStart,+ className = '',+}) => {+ const isDocked = variant === 'docked';++ const [previousColor] = useState<string>(() =>+ isValidHex(initialColor)+ ? initialColor.startsWith('#')+ ? initialColor.toUpperCase()+ : `#${initialColor.toUpperCase()}`+ : '#85988E'+ );++ const [internalState, setInternalState] = useState<SpherePickerSharedState>(() =>+ sharedState ?? createInitialSphereState(initialColor, monochromeDefault)+ );++ const state = sharedState ?? internalState;+ const { slots, activeSlot, lighting, marker } = state;++ const commitState = useCallback(+ (next: SpherePickerSharedState) => {+ if (onSharedStateChange) {+ onSharedStateChange(next);+ } else {+ setInternalState(next);+ }+ },+ [onSharedStateChange]+ );++ const [showSettings, setShowSettings] = useState(false);+ const [lightOrbitMode, setLightOrbitMode] = useState(false);+ const [isOrbitingLight, setIsOrbitingLight] = useState(false);+ const [copiedField, setCopiedField] = useState<'hex' | 'rgb' | null>(null);+ const lastNonZeroSatRef = useRef<number>(lighting.saturation > 0.05 ? lighting.saturation : 1.0);+ const shadowFilterId = useId();++ const rootRef = useRef<HTMLDivElement | null>(null);+ const [measuredWidth, setMeasuredWidth] = useState<number>(isDocked ? 200 : sphereSizeProp + 48);++ useEffect(() => {+ if (!isDocked) return;+ const el = rootRef.current;+ if (!el) return;+ const ro = new ResizeObserver((entries) => {+ for (const entry of entries) {+ if (entry.contentRect.width > 0) {+ setMeasuredWidth(Math.round(entry.contentRect.width));+ }+ }+ });+ ro.observe(el);+ return () => ro.disconnect();+ }, [isDocked]);++ const compact = isDocked && measuredWidth < 245;+ const effectiveSphereSize = isDocked+ ? Math.max(108, Math.min(212, measuredWidth - (compact ? 20 : 32)))+ : sphereSizeProp;++ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const lutRef = useRef<SphereRenderLut | null>(null);+ const hueTrackRef = useRef<HTMLDivElement | null>(null);+ const dragModeRef = useRef<'marker' | 'light' | null>(null);+ const hueDraggingRef = useRef(false);+ const rafRenderRef = useRef<number | null>(null);++ const stateRef = useRef(state);+ stateRef.current = state;++ const prevGeomLightKeyRef = useRef<string>('');++ const sampledColor = useMemo<SphereColorResult>(+ () => evaluateSphereColor(marker, slots, lighting),+ [marker, slots, lighting]+ );++ const projectedMarker = useMemo(+ () => projectSphereMarker(marker, effectiveSphereSize, SPHERE_RADIUS_RATIO, lighting),+ [marker, effectiveSphereSize, lighting]+ );++ // Build geometry LUT on resize / DPR change+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const dpr = Math.min(window.devicePixelRatio || 1, 2);+ const pxSize = Math.max(108, Math.round(effectiveSphereSize * dpr));+ canvas.width = pxSize;+ canvas.height = pxSize;++ const lut = buildSphereGeometryLut(pxSize, pxSize, SPHERE_RADIUS_RATIO);+ updateSphereLightingLut(lut, stateRef.current.lighting);+ lutRef.current = lut;+ prevGeomLightKeyRef.current = getGeomLightKey(stateRef.current.lighting);++ const ctx = canvas.getContext('2d');+ if (ctx) {+ renderSphereFromLut(ctx, lut, stateRef.current.slots, stateRef.current.lighting);+ }+ }, [effectiveSphereSize]);++ // Recompute lighting LUT only when geometric lighting params change+ useEffect(() => {+ const lut = lutRef.current;+ if (!lut) return;+ const key = getGeomLightKey(lighting);+ if (key !== prevGeomLightKeyRef.current) {+ prevGeomLightKeyRef.current = key;+ updateSphereLightingLut(lut, lighting);+ }+ }, [lighting]);++ // Schedule 60fps redraw on slot or lighting changes (NOT on marker drag)+ useEffect(() => {+ if (rafRenderRef.current !== null) {+ cancelAnimationFrame(rafRenderRef.current);+ }+ rafRenderRef.current = requestAnimationFrame(() => {+ rafRenderRef.current = null;+ const canvas = canvasRef.current;+ const lut = lutRef.current;+ if (!canvas || !lut) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ renderSphereFromLut(ctx, lut, slots, lighting);+ });+ return () => {+ if (rafRenderRef.current !== null) {+ cancelAnimationFrame(rafRenderRef.current);+ rafRenderRef.current = null;+ }+ };+ }, [slots, lighting]);++ const emitColor = useCallback(+ (nextState: SpherePickerSharedState, commit = false) => {+ if (!onColorChange) return;+ const result = evaluateSphereColor(nextState.marker, nextState.slots, nextState.lighting);+ onColorChange(result, commit);+ },+ [onColorChange]+ );++ const computeSphereCoords = useCallback((clientX: number, clientY: number) => {+ const canvas = canvasRef.current;+ if (!canvas) return null;+ const rect = canvas.getBoundingClientRect();+ const radius = rect.width * SPHERE_RADIUS_RATIO;+ if (radius <= 0) return null;+ const cx = rect.left + rect.width * 0.5;+ const cy = rect.top + rect.height * 0.5;+ return {+ x: (clientX - cx) / radius,+ y: (cy - clientY) / radius,+ };+ }, []);++ const updateLightFromCoords = useCallback(+ (x: number, y: number, commit = false) => {+ const clamped = clampMarkerPosition(x, y, 0.96);+ const z = Math.sqrt(Math.max(0.01, 1 - clamped.x * clamped.x - clamped.y * clamped.y));+ const lightElevation = Math.round(+ (Math.asin(Math.max(-0.98, Math.min(0.98, clamped.y))) * 180) / Math.PI+ );+ const lightAzimuth = Math.round((Math.atan2(clamped.x, z) * 180) / Math.PI);+ const prev = stateRef.current;+ const next: SpherePickerSharedState = {+ ...prev,+ lighting: { ...prev.lighting, lightAzimuth, lightElevation },+ };+ commitState(next);+ emitColor(next, commit);+ },+ [commitState, emitColor]+ );++ const handleSpherePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {+ e.preventDefault();+ const canvas = canvasRef.current;+ if (!canvas) return;+ canvas.setPointerCapture(e.pointerId);++ const coords = computeSphereCoords(e.clientX, e.clientY);+ if (!coords) return;++ if (lightOrbitMode || e.button === 2 || e.shiftKey) {+ dragModeRef.current = 'light';+ setIsOrbitingLight(true);+ updateLightFromCoords(coords.x, coords.y, false);+ return;+ }++ dragModeRef.current = 'marker';+ const prev = stateRef.current;+ const next: SpherePickerSharedState = {+ ...prev,+ marker: clampMarkerPosition(coords.x, coords.y),+ };+ commitState(next);+ emitColor(next, false);+ };++ const handleSpherePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {+ if (!dragModeRef.current) return;+ const coords = computeSphereCoords(e.clientX, e.clientY);+ if (!coords) return;++ if (dragModeRef.current === 'light') {+ updateLightFromCoords(coords.x, coords.y, false);+ } else {+ const prev = stateRef.current;+ const next: SpherePickerSharedState = {+ ...prev,+ marker: clampMarkerPosition(coords.x, coords.y),+ };+ commitState(next);+ emitColor(next, false);+ }+ };++ const handleSpherePointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {+ if (!dragModeRef.current) return;+ const canvas = canvasRef.current;+ if (canvas && canvas.hasPointerCapture(e.pointerId)) {+ canvas.releasePointerCapture(e.pointerId);+ }+ dragModeRef.current = null;+ setIsOrbitingLight(false);+ emitColor(stateRef.current, true);+ };++ const updateActiveSlot = useCallback(+ (patch: Partial<HSV>, commit = false) => {+ const prev = stateRef.current;+ const currentHsv =+ prev.activeSlot === 'rim'+ ? (prev.slots.rim ?? DEFAULT_RIM_SLOT)+ : prev.slots[prev.activeSlot];+ const next: SpherePickerSharedState = {+ ...prev,+ slots: {+ ...prev.slots,+ [prev.activeSlot]: { ...currentHsv, ...patch },+ },+ };+ commitState(next);+ emitColor(next, commit);+ },+ [commitState, emitColor]+ );++ const applyPreset = useCallback(+ (presetId: string) => {+ const preset = SPHERE_LIGHTING_PRESETS.find((p) => p.id === presetId);+ if (!preset) return;+ const prev = stateRef.current;+ const nextLighting: SphereLightingConfig = { ...prev.lighting, ...preset.lighting };+ const nextSlots: SphereSlotsState = preset.slots+ ? {+ shadow: preset.slots.shadow ? { ...preset.slots.shadow } : prev.slots.shadow,+ base: preset.slots.base ? { ...preset.slots.base } : prev.slots.base,+ light: preset.slots.light ? { ...preset.slots.light } : prev.slots.light,+ rim: preset.slots.rim ? { ...preset.slots.rim } : (prev.slots.rim ?? { ...DEFAULT_RIM_SLOT }),+ }+ : prev.slots;+ const nextState: SpherePickerSharedState = {+ ...prev,+ lighting: nextLighting,+ slots: nextSlots,+ };+ commitState(nextState);+ emitColor(nextState, true);+ },+ [commitState, emitColor]+ );++ const updateLighting = useCallback(+ (patch: Partial<SphereLightingConfig>, commit = false) => {+ const prev = stateRef.current;+ if (patch.saturation !== undefined && patch.saturation > 0.05) {+ lastNonZeroSatRef.current = patch.saturation;+ }+ const next: SpherePickerSharedState = {+ ...prev,+ lighting: { ...prev.lighting, ...patch },+ };+ commitState(next);+ emitColor(next, commit);+ },+ [commitState, emitColor]+ );++ const updateHueFromClientX = useCallback(+ (clientX: number, commit = false) => {+ const track = hueTrackRef.current;+ if (!track) return;+ const rect = track.getBoundingClientRect();+ if (rect.width <= 0) return;+ const ratio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));+ const hue = Math.round(ratio * 359);+ updateActiveSlot({ h: hue }, commit);+ },+ [updateActiveSlot]+ );++ const handleHuePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {+ e.preventDefault();+ hueDraggingRef.current = true;+ e.currentTarget.setPointerCapture(e.pointerId);+ updateHueFromClientX(e.clientX, false);+ };++ const handleHuePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!hueDraggingRef.current) return;+ updateHueFromClientX(e.clientX, false);+ };++ const handleHuePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!hueDraggingRef.current) return;+ if (e.currentTarget.hasPointerCapture(e.pointerId)) {+ e.currentTarget.releasePointerCapture(e.pointerId);+ }+ hueDraggingRef.current = false;+ updateHueFromClientX(e.clientX, true);+ };++ const handleHueKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {+ const step = e.shiftKey ? 10 : 1;+ const currentSlot = activeSlot === 'rim' ? (slots.rim ?? DEFAULT_RIM_SLOT) : slots[activeSlot];+ const currentHue = Math.round(currentSlot.h);+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {+ e.preventDefault();+ updateActiveSlot({ h: (currentHue + step) % 360 }, true);+ } else if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {+ e.preventDefault();+ updateActiveSlot({ h: (currentHue - step + 360) % 360 }, true);+ }+ };++ const handleEyedropperClick = async () => {+ if (onEyedropper) {+ onEyedropper();+ return;+ }+ const win = window as unknown as { EyeDropper?: new () => BrowserEyeDropper };+ if (typeof win.EyeDropper === 'function') {+ try {+ const dropper = new win.EyeDropper();+ const result = await dropper.open();+ if (result?.sRGBHex && isValidHex(result.sRGBHex)) {+ const pickedHsv = hexToHsv(result.sRGBHex);+ updateActiveSlot(pickedHsv, true);+ }+ } catch {+ // User cancelled native eyedropper+ }+ }+ };++ const handleRevertToPrevious = () => {+ const prev = stateRef.current;+ const next: SpherePickerSharedState = {+ ...prev,+ slots: buildHarmonizedSlots(previousColor),+ };+ commitState(next);+ if (onColorChange) {+ const rgb = hexToRgb(previousColor);+ onColorChange({ hex: rgbToHex(rgb.r, rgb.g, rgb.b), rgb }, true);+ }+ };++ const handleToggleBw = () => {+ const isBw = lighting.saturation <= 0.01;+ updateLighting({ saturation: isBw ? lastNonZeroSatRef.current || 1.0 : 0 }, true);+ };++ const handleCopy = (field: 'hex' | 'rgb') => {+ const text =+ field === 'hex'+ ? sampledColor.hex+ : `rgb(${sampledColor.rgb.r}, ${sampledColor.rgb.g}, ${sampledColor.rgb.b})`;+ navigator.clipboard?.writeText(text).catch(() => {});+ setCopiedField(field);+ setTimeout(() => setCopiedField((prev) => (prev === field ? null : prev)), 1200);+ };++ const rimSlotHsv = slots.rim ?? DEFAULT_RIM_SLOT;+ const activeSlotHsv = activeSlot === 'rim' ? rimSlotHsv : slots[activeSlot];+ const activeHue = Math.round(((activeSlotHsv.h % 360) + 360) % 360);+ const huePercent = (activeHue / 359) * 100;++ const shadowHex = hsvToHex(slots.shadow.h, slots.shadow.s, slots.shadow.v);+ const baseHex = hsvToHex(slots.base.h, slots.base.s, slots.base.v);+ const lightHex = hsvToHex(slots.light.h, slots.light.s, slots.light.v);+ const rimHex = hsvToHex(rimSlotHsv.h, rimSlotHsv.s, rimSlotHsv.v);+ const activeSlotHex = hsvToHex(activeSlotHsv.h, activeSlotHsv.s, activeSlotHsv.v);++ const puckTopHex = sampledColor.hex;+ const puckSideHex = darkenRgb(sampledColor.rgb, 0.64);+ const puckRimHex = lightenRgb(sampledColor.rgb, 0.28);++ const isBwMode = lighting.saturation <= 0.01;+ const satGradient = `linear-gradient(to right, #6e6e6e 0%, ${hsvToHex(slots.base.h, 0.72, 0.78)} 68%, ${hsvToHex(slots.base.h, 1, 0.92)} 100%)`;+ const lightGradient = `linear-gradient(to right, #161616 0%, ${lightHex} 55%, #ffffff 100%)`;+ const ambientGradient = `linear-gradient(to right, #101010 0%, ${baseHex} 55%, #f5f5f5 100%)`;+ const slotSatGradient = `linear-gradient(to right, ${hsvToHex(activeHue, 0, Math.max(0.25, activeSlotHsv.v))} 0%, ${hsvToHex(activeHue, 1, Math.max(0.35, activeSlotHsv.v))} 100%)`;+ const slotValGradient = `linear-gradient(to right, #080808 0%, ${hsvToHex(activeHue, activeSlotHsv.s, 1)} 100%)`;++ const ambientVal = lighting.ambientIntensity ?? DEFAULT_SPHERE_LIGHTING.ambientIntensity ?? 0.08;+ const lightTintVal = lighting.lightTint ?? DEFAULT_SPHERE_LIGHTING.lightTint ?? 0.28;+ const rimIntensityVal = lighting.rimIntensity ?? DEFAULT_SPHERE_LIGHTING.rimIntensity ?? 0.14;+ const subsurfaceVal = lighting.subsurface ?? DEFAULT_SPHERE_LIGHTING.subsurface ?? 0.16;++ const lightVec = useMemo(() => getLightVectors(lighting), [lighting]);+ const sphereR = effectiveSphereSize * SPHERE_RADIUS_RATIO;+ const lightReticleX = effectiveSphereSize * 0.5 + lightVec.lx * sphereR * 0.88;+ const lightReticleY = effectiveSphereSize * 0.5 - lightVec.ly * sphereR * 0.88;++ return (+ <div+ ref={rootRef}+ className={+ isDocked+ ? `w-full h-full flex flex-col bg-[#202020] text-[#e5e5e5] select-none overflow-y-auto overflow-x-hidden ${className}`+ : `bg-[#202020]/96 backdrop-blur-md text-[#e5e5e5] rounded-lg border border-white/[0.1] shadow-[0_12px_36px_rgba(0,0,0,0.65)] select-none overflow-hidden flex flex-col ${className}`+ }+ onPointerDown={(e) => e.stopPropagation()}+ >+ {/* Floating Studio Palette Title Bar (matches DockWorkspace h-6 #1a1a1a chrome) */}+ {!isDocked && (+ <div+ onPointerDown={onHeaderDragStart}+ title="Drag to move palette"+ className="h-6 px-2 flex items-center justify-between bg-[#1a1a1a] border-b border-white/[0.06] cursor-grab active:cursor-grabbing shrink-0"+ >+ <div className="flex items-center gap-1.5 min-w-0">+ <span+ className="w-2.5 h-2.5 rounded-full shrink-0"+ style={{+ background:+ 'radial-gradient(circle at 32% 30%, #f5f5f5 0%, #9ca3af 50%, #262930 100%)',+ }}+ />+ <span className="text-[10px] font-medium text-[#e5e5e5] tracking-wide truncate">+ Color Sphere+ </span>+ </div>++ <div+ className="flex items-center gap-0.5 shrink-0"+ onPointerDown={(e) => e.stopPropagation()}+ >+ {onTogglePin && (+ <button+ type="button"+ onClick={onTogglePin}+ data-testid="sphere-pin-toggle"+ title={isPinned ? 'Unpin & Float Palette' : 'Pin back to Color Panel'}+ aria-label={isPinned ? 'Unpin panel' : 'Pin panel'}+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ {isPinned ? <PinOff className="w-3 h-3" /> : <Pin className="w-3 h-3" />}+ </button>+ )}+ {onClose && (+ <button+ type="button"+ onClick={onClose}+ title="Close (Esc)"+ aria-label="Close"+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ <X className="w-3 h-3" />+ </button>+ )}+ </div>+ </div>+ )}++ {/* Top Controls Bar: Gear + Light Orbit | Split Preview Bar | Eyedropper (+ Unpin when docked) */}+ <div+ className={`${compact ? 'px-2 pt-1.5 pb-1 gap-1.5' : 'px-2.5 pt-2 pb-1.5 gap-2'} flex items-center justify-between border-b border-white/[0.06] shrink-0`}+ >+ <div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ onClick={() => setShowSettings((s) => !s)}+ title="Lighting & Surface Settings"+ aria-label="Lighting Settings"+ aria-expanded={showSettings}+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${+ showSettings+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Settings className="w-3.5 h-3.5" />+ </button>++ <button+ type="button"+ onClick={() => setLightOrbitMode((m) => !m)}+ title={+ lightOrbitMode+ ? 'Light Orbit Active (drag sphere to angle light)'+ : 'Rotate Light Source (or Shift+drag on sphere)'+ }+ aria-label="Toggle Light Orbit Mode"+ aria-pressed={lightOrbitMode}+ className={`w-6 h-6 rounded flex items-center justify-center transition-colors cursor-pointer ${+ lightOrbitMode+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Compass className="w-3.5 h-3.5" />+ </button>+ </div>++ {/* Split Preview Bar: Left = previous color, Right = live picked 3D sphere color */}+ <div className="flex-1 h-5 rounded-sm overflow-hidden flex border border-white/[0.1] bg-[#161616] min-w-[44px]">+ <button+ type="button"+ onClick={handleRevertToPrevious}+ title={`Previous: ${previousColor} (Click to revert)`}+ aria-label={`Previous color ${previousColor}`}+ className="flex-1 h-full cursor-pointer transition-opacity hover:opacity-90"+ style={{ backgroundColor: previousColor }}+ />+ <div+ data-testid="sphere-live-preview"+ title={`Current: ${sampledColor.hex} | rgb(${sampledColor.rgb.r}, ${sampledColor.rgb.g}, ${sampledColor.rgb.b})`}+ className="flex-1 h-full border-l border-black/35"+ style={{ backgroundColor: sampledColor.hex }}+ />+ </div>++ <div className="flex items-center gap-0.5 shrink-0">+ <button+ type="button"+ onClick={handleEyedropperClick}+ title="Eyedropper"+ aria-label="Eyedropper"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ <Pipette className="w-3.5 h-3.5" />+ </button>++ {isDocked && onTogglePin && (+ <button+ type="button"+ onClick={onTogglePin}+ data-testid="sphere-pin-toggle"+ title="Unpin & Float Palette"+ aria-label="Unpin panel"+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"+ >+ <PinOff className="w-3.5 h-3.5" />+ </button>+ )}+ </div>+ </div>++ {/* Collapsible Lighting & Surface Fine-Tune Drawer */}+ {showSettings && (+ <div+ className={`${compact ? 'mx-2 p-2' : 'mx-2.5 p-2'} mt-1.5 rounded-md bg-[#161616] border border-white/[0.06] space-y-2 text-[10px] shrink-0`}+ >+ <div className="flex items-center justify-between border-b border-white/[0.06] pb-1">+ <span className="text-[10px] font-medium text-[#cccccc]">Lighting & Surface</span>+ <button+ type="button"+ onClick={() => {+ const resetState = createInitialSphereState(previousColor, monochromeDefault);+ commitState(resetState);+ emitColor(resetState, true);+ }}+ title="Reset Lighting"+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer transition-colors"+ >+ <RotateCcw className="w-2.5 h-2.5" />+ <span>Reset</span>+ </button>+ </div>++ <div className="grid grid-cols-2 gap-1">+ {SPHERE_LIGHTING_PRESETS.map((preset) => (+ <button+ key={preset.id}+ type="button"+ data-testid={`sphere-preset-${preset.id}`}+ onClick={() => applyPreset(preset.id)}+ className="flex items-center gap-1.5 px-1.5 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] text-left truncate cursor-pointer transition-colors"+ >+ {preset.swatch && (+ <span+ className="w-2 h-2 rounded-full shrink-0 ring-1 ring-white/20"+ style={{ backgroundColor: preset.swatch }}+ />+ )}+ <span className="truncate">{preset.label}</span>+ </button>+ ))}+ </div>++ <div className="pt-1 border-t border-white/[0.06] space-y-1">+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Key Tint</span>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(lightTintVal * 100)}+ onChange={(e) => updateLighting({ lightTint: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Key Light Color Tint"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(lightTintVal * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Rim Glow</span>+ <input+ type="range"+ min={0}+ max={150}+ value={Math.round(rimIntensityVal * 100)}+ onChange={(e) => updateLighting({ rimIntensity: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Rim Light Intensity"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(rimIntensityVal * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Gloss</span>+ <input+ type="range"+ min={5}+ max={95}+ value={Math.round((1 - lighting.roughness) * 100)}+ onChange={(e) => updateLighting({ roughness: 1 - Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Surface Gloss"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round((1 - lighting.roughness) * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Specular</span>+ <input+ type="range"+ min={0}+ max={150}+ value={Math.round(lighting.specularStrength * 100)}+ onChange={(e) => updateLighting({ specularStrength: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Specular Strength"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(lighting.specularStrength * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">SSS Glow</span>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(subsurfaceVal * 100)}+ onChange={(e) => updateLighting({ subsurface: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Subsurface Terminator Glow"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(subsurfaceVal * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Bounce</span>+ <input+ type="range"+ min={0}+ max={120}+ value={Math.round(lighting.bounceIntensity * 100)}+ onChange={(e) => updateLighting({ bounceIntensity: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Bounce Light Intensity"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(lighting.bounceIntensity * 100)}+ </span>+ </div>+ <div className="flex items-center justify-between gap-2">+ <span className="text-[10px] text-[#8a8a8a] w-14">Shadow</span>+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(lighting.shadowDepth * 100)}+ onChange={(e) => updateLighting({ shadowDepth: Number(e.target.value) / 100 }, true)}+ className="flex-1"+ aria-label="Shadow Depth"+ />+ <span className="font-mono text-[10px] w-7 text-right text-[#e5e5e5]">+ {Math.round(lighting.shadowDepth * 100)}+ </span>+ </div>+ </div>+ </div>+ )}++ {/* Central Area: Illuminated 3D Sphere + Perspective 3D Disc Marker */}+ <div className={`${compact ? 'px-2 py-1' : 'px-3 py-1.5'} flex items-center justify-center shrink-0`}>+ <div+ className="relative flex items-center justify-center"+ style={{ width: effectiveSphereSize, height: effectiveSphereSize }}+ >+ <canvas+ ref={canvasRef}+ data-testid="sphere-canvas"+ style={{ width: effectiveSphereSize, height: effectiveSphereSize }}+ onPointerDown={handleSpherePointerDown}+ onPointerMove={handleSpherePointerMove}+ onPointerUp={handleSpherePointerUp}+ onPointerCancel={handleSpherePointerUp}+ onContextMenu={(e) => e.preventDefault()}+ className={`block touch-none ${lightOrbitMode || isOrbitingLight ? 'cursor-grab active:cursor-grabbing' : 'cursor-crosshair'}`}+ />++ <svg+ width={effectiveSphereSize}+ height={effectiveSphereSize}+ viewBox={`0 0 ${effectiveSphereSize} ${effectiveSphereSize}`}+ className="absolute inset-0 pointer-events-none overflow-visible"+ aria-hidden="true"+ >+ <defs>+ <filter id={shadowFilterId} x="-50%" y="-50%" width="200%" height="200%">+ <feGaussianBlur stdDeviation="2.2" />+ </filter>+ </defs>++ {(lightOrbitMode || isOrbitingLight) && (+ <g>+ <line+ x1={effectiveSphereSize * 0.5}+ y1={effectiveSphereSize * 0.5}+ x2={lightReticleX}+ y2={lightReticleY}+ stroke="rgba(229, 229, 229, 0.55)"+ strokeWidth={1.25}+ strokeDasharray="3 2.5"+ />+ <circle+ cx={lightReticleX}+ cy={lightReticleY}+ r={5}+ fill="#e5e5e5"+ stroke="#161616"+ strokeWidth={1.5}+ />+ </g>+ )}++ <g+ data-testid="sphere-marker"+ transform={`translate(${projectedMarker.baseX.toFixed(2)}, ${projectedMarker.baseY.toFixed(2)}) rotate(${projectedMarker.rotateDeg.toFixed(2)})`}+ >+ <ellipse+ cx={projectedMarker.shadowLocalX}+ cy={projectedMarker.shadowLocalY}+ rx={projectedMarker.rx * 1.07}+ ry={projectedMarker.ry * 1.07}+ fill="rgba(0, 0, 0, 0.36)"+ filter={`url(#${shadowFilterId})`}+ />++ <ellipse+ cx={0}+ cy={0}+ rx={projectedMarker.rx}+ ry={projectedMarker.ry}+ fill={puckSideHex}+ />+ {projectedMarker.extrudeShift > 0.15 && (+ <rect+ x={-projectedMarker.rx}+ y={0}+ width={projectedMarker.rx * 2}+ height={projectedMarker.extrudeShift}+ fill={puckSideHex}+ />+ )}++ <ellipse+ cx={0}+ cy={projectedMarker.extrudeShift}+ rx={projectedMarker.rx}+ ry={projectedMarker.ry}+ fill={puckTopHex}+ stroke={puckRimHex}+ strokeOpacity={0.55}+ strokeWidth={1}+ />+ </g>+ </svg>+ </div>+ </div>++ {/* Lighting Color Slots Panel (Shadow | Base | Light | Rim) */}+ <div+ className={`${compact ? 'px-2 pb-1.5' : 'px-2.5 pb-1.5'} grid grid-cols-4 gap-1 shrink-0`}+ >+ {(+ [+ { id: 'shadow', label: 'Shadow', hex: shadowHex, Icon: Moon },+ { id: 'base', label: 'Base', hex: baseHex, Icon: Droplet },+ { id: 'light', label: 'Light', hex: lightHex, Icon: Sun },+ { id: 'rim', label: 'Rim', hex: rimHex, Icon: Sparkles },+ ] as const+ ).map(({ id, label, hex, Icon }) => {+ const isActive = activeSlot === id;+ return (+ <button+ key={id}+ type="button"+ data-testid={`slot-${id}`}+ aria-pressed={isActive}+ onClick={() => commitState({ ...state, activeSlot: id })}+ title={`${label} Color (${hex})`}+ className={`flex items-center justify-center gap-1 px-1 py-1 rounded cursor-pointer transition-colors ${+ isActive ? 'bg-[#2c2c2c] ring-1 ring-white/[0.16]' : 'hover:bg-[#262626]'+ }`}+ >+ <Icon+ className={`${compact ? 'w-3 h-3' : 'w-3.5 h-3.5'} shrink-0 transition-colors ${+ isActive ? 'text-[#e5e5e5]' : 'text-[#8a8a8a]'+ }`}+ />+ <span+ className={`rounded-full transition-all block shrink-0 ${+ isActive+ ? compact+ ? 'w-3.5 h-3.5 ring-1 ring-[var(--accent)] ring-offset-1 ring-offset-[#2c2c2c]'+ : 'w-4 h-4 ring-1 ring-[var(--accent)] ring-offset-1 ring-offset-[#2c2c2c]'+ : 'w-3.5 h-3.5 ring-1 ring-white/20'+ }`}+ style={{ backgroundColor: hex }}+ />+ </button>+ );+ })}+ </div>++ {/* Active Slot Color Editor: Hue + Exact Swatch Picker + Sat & Val */}+ <div+ className={`${compact ? 'mx-2 mb-1.5 p-1.5' : 'mx-2.5 mb-1.5 p-2'} rounded bg-[#161616] border border-white/[0.06] space-y-1.5 shrink-0`}+ >+ <div className="flex items-center gap-1.5">+ <div+ role="slider"+ tabIndex={0}+ aria-label={`${activeSlot} hue`}+ aria-valuemin={0}+ aria-valuemax={359}+ aria-valuenow={activeHue}+ data-testid="sphere-hue-slider"+ onPointerDown={handleHuePointerDown}+ onPointerMove={handleHuePointerMove}+ onPointerUp={handleHuePointerUp}+ onPointerCancel={handleHuePointerUp}+ onKeyDown={handleHueKeyDown}+ className={`relative flex-1 h-6 px-3 flex items-center cursor-pointer touch-none outline-none focus-visible:ring-1 focus-visible:ring-[var(--accent-border)] rounded bg-[#202020] border border-white/[0.06] ${isBwMode ? 'opacity-45' : ''}`}+ >+ <div+ ref={hueTrackRef}+ className="relative w-full h-1.5 rounded-[2px]"+ style={{+ background:+ 'linear-gradient(to right, #ff1e42 0%, #ffea00 17%, #00e640 33%, #00e5ff 50%, #2952ff 67%, #d500f9 83%, #ff1e42 100%)',+ }}+ >+ <div+ data-testid="sphere-hue-thumb"+ style={{ left: `${huePercent}%` }}+ className="absolute top-1/2 -translate-x-1/2 -translate-y-1/2 min-w-[24px] h-[18px] px-1 rounded bg-[#e5e5e5] text-[#161616] shadow-[0_2px_6px_rgba(0,0,0,0.65)] border border-black/25 flex items-center justify-center font-semibold text-[9.5px] font-mono tabular-nums pointer-events-none"+ >+ {activeHue}+ </div>+ </div>+ </div>++ <label+ title={`Pick exact ${activeSlot} color (${activeSlotHex})`}+ className="relative w-6 h-6 rounded border border-white/[0.14] shrink-0 cursor-pointer overflow-hidden"+ style={{ backgroundColor: activeSlotHex }}+ >+ <input+ type="color"+ aria-label={`Pick ${activeSlot} color`}+ data-testid="sphere-slot-color-input"+ value={activeSlotHex}+ onChange={(e) => {+ const hex = e.target.value;+ if (isValidHex(hex)) {+ updateActiveSlot(hexToHsv(hex), true);+ }+ }}+ className="absolute inset-0 opacity-0 w-full h-full cursor-pointer"+ />+ </label>+ </div>++ <MiniBarSlider+ label={compact ? 'Chm' : 'Chroma'}+ value={activeSlotHsv.s}+ min={0}+ max={1}+ displayValue={`${Math.round(activeSlotHsv.s * 100)}%`}+ gradient={slotSatGradient}+ onChange={(v, commit) => updateActiveSlot({ s: v }, commit)}+ compact={compact}+ testId="sphere-slot-sat-slider"+ />++ <MiniBarSlider+ label={compact ? 'Val' : 'Value'}+ value={activeSlotHsv.v}+ min={0}+ max={1}+ displayValue={`${Math.round(activeSlotHsv.v * 100)}%`}+ gradient={slotValGradient}+ onChange={(v, commit) => updateActiveSlot({ v }, commit)}+ compact={compact}+ testId="sphere-slot-val-slider"+ />+ </div>++ {/* Scene Lighting Presets, Exposure, Ambient Fill, Contrast & Saturation */}+ <div+ className={`${compact ? 'mx-2 mb-1.5 p-1.5' : 'mx-2.5 mb-2 p-2'} rounded bg-[#161616] border border-white/[0.06] space-y-1.5 shrink-0`}+ >+ <div className="flex items-center gap-1.5 pb-0.5">+ <select+ aria-label="Lighting Preset"+ data-testid="sphere-preset-select"+ defaultValue=""+ onChange={(e) => {+ if (e.target.value) {+ applyPreset(e.target.value);+ e.target.value = '';+ }+ }}+ className="flex-1 min-w-0 h-5 px-1.5 rounded bg-[#202020] hover:bg-[#262626] border border-white/[0.08] text-[10px] text-[#cccccc] outline-none cursor-pointer"+ >+ <option value="" disabled>+ Lighting Mood Preset...+ </option>+ {SPHERE_LIGHTING_PRESETS.map((preset) => (+ <option key={preset.id} value={preset.id} className="bg-[#202020] text-[#e5e5e5]">+ {preset.label}+ </option>+ ))}+ </select>+ <button+ type="button"+ onClick={() => {+ const resetState = createInitialSphereState(previousColor, monochromeDefault);+ commitState(resetState);+ emitColor(resetState, true);+ }}+ title="Reset Lighting & Colors"+ aria-label="Reset Lighting"+ className="w-5 h-5 rounded flex items-center justify-center bg-[#202020] hover:bg-[#2c2c2c] border border-white/[0.06] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer shrink-0 transition-colors"+ >+ <RotateCcw className="w-2.5 h-2.5" />+ </button>+ </div>++ <MiniBarSlider+ label="Light"+ value={lighting.lightIntensity}+ min={0.1}+ max={2.8}+ displayValue={`${Math.round(lighting.lightIntensity * 100)}%`}+ gradient={lightGradient}+ onChange={(v, commit) => updateLighting({ lightIntensity: v }, commit)}+ compact={compact}+ testId="sphere-light-slider"+ />++ <MiniBarSlider+ label={compact ? 'Amb' : 'Ambient'}+ value={ambientVal}+ min={0}+ max={1.0}+ displayValue={`${Math.round(ambientVal * 100)}%`}+ gradient={ambientGradient}+ onChange={(v, commit) => updateLighting({ ambientIntensity: v }, commit)}+ compact={compact}+ testId="sphere-ambient-slider"+ />++ <MiniBarSlider+ label={compact ? 'Ctr' : 'Contrast'}+ value={lighting.contrast}+ min={0.4}+ max={2.2}+ displayValue={`${Math.round(lighting.contrast * 100)}%`}+ gradient="linear-gradient(to right, #6e6e6e 0%, #3a3a3a 48%, #101010 72%, #e5e5e5 100%)"+ onChange={(v, commit) => updateLighting({ contrast: v }, commit)}+ compact={compact}+ testId="sphere-contrast-slider"+ />++ <MiniBarSlider+ label="Sat"+ value={lighting.saturation}+ min={0}+ max={1.8}+ displayValue={`${Math.round(lighting.saturation * 100)}%`}+ gradient={satGradient}+ onChange={(v, commit) => updateLighting({ saturation: v }, commit)}+ compact={compact}+ testId="sphere-sat-slider"+ rightAction={+ <button+ type="button"+ onClick={handleToggleBw}+ data-testid="sphere-bw-toggle"+ title={isBwMode ? 'Restore Color Saturation' : 'Black & White / Grayscale Mode (0% Sat)'}+ className={`px-1.5 py-0.5 rounded-xs text-[9px] font-mono font-semibold cursor-pointer transition-colors shrink-0 ${+ isBwMode+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)]'+ : 'bg-[#262626] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ B&W+ </button>+ }+ />+ </div>++ {/* Compact Studio HEX & RGB Output Footer */}+ <div+ className={`${compact ? 'px-2 pb-1.5 gap-1' : 'px-2.5 pb-2 gap-1.5'} flex items-center justify-between text-[10px] font-mono shrink-0`}+ >+ <button+ type="button"+ onClick={() => handleCopy('hex')}+ title="Copy HEX"+ data-testid="sphere-output-hex"+ className="flex items-center gap-1.5 px-2 py-0.5 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[#e5e5e5] cursor-pointer transition-colors"+ >+ <span>{sampledColor.hex}</span>+ {copiedField === 'hex' ? (+ <Check className="w-2.5 h-2.5 text-emerald-400" />+ ) : (+ <Copy className="w-2.5 h-2.5 text-[#8a8a8a]" />+ )}+ </button>++ <button+ type="button"+ onClick={() => handleCopy('rgb')}+ title="Copy RGB"+ data-testid="sphere-output-rgb"+ className="flex items-center gap-1.5 px-2 py-0.5 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer transition-colors truncate"+ >+ <span className="truncate">+ {sampledColor.rgb.r}, {sampledColor.rgb.g}, {sampledColor.rgb.b}+ </span>+ {copiedField === 'rgb' ? (+ <Check className="w-2.5 h-2.5 text-emerald-400 shrink-0" />+ ) : (+ <Copy className="w-2.5 h-2.5 text-[#8a8a8a] shrink-0" />+ )}+ </button>+ </div>+ </div>+ );+};++export interface SphereColorPickerModalProps extends SphereColorPickerProps {+ isOpen: boolean;+ onClose: () => void;+ /** When false (default), renders as a non-blocking draggable floating studio palette. */+ blocking?: boolean;+}++const FLOAT_POS_STORAGE_KEY = 'ink_sphere_float_pos';+const FLOAT_WIDTH_STORAGE_KEY = 'ink_sphere_float_width';++function loadSavedFloatPos(panelWidth: number): { x: number; y: number } {+ const vw = typeof window !== 'undefined' ? window.innerWidth : 1280;+ const vh = typeof window !== 'undefined' ? window.innerHeight : 800;+ try {+ const raw = localStorage.getItem(FLOAT_POS_STORAGE_KEY);+ if (raw) {+ const parsed = JSON.parse(raw);+ if (typeof parsed?.x === 'number' && typeof parsed?.y === 'number') {+ return {+ x: Math.max(8, Math.min(vw - panelWidth - 8, parsed.x)),+ y: Math.max(8, Math.min(vh - 120, parsed.y)),+ };+ }+ }+ } catch {+ // ignore storage errors+ }+ return {+ x: Math.max(16, vw - panelWidth - 260),+ y: Math.max(48, Math.round(vh * 0.14)),+ };+}++function loadSavedFloatWidth(): number {+ try {+ const raw = localStorage.getItem(FLOAT_WIDTH_STORAGE_KEY);+ const n = raw ? parseInt(raw, 10) : NaN;+ if (!isNaN(n)) return Math.max(240, Math.min(360, n));+ } catch {+ // ignore+ }+ return 276;+}++/**+ * Unpinned, freely draggable, resizable, non-blocking floating 3D Sphere Color Picker.+ */+export const SphereColorPickerModal: React.FC<SphereColorPickerModalProps> = ({+ isOpen,+ onClose,+ blocking = false,+ ...pickerProps+}) => {+ const [panelWidth, setPanelWidth] = useState<number>(() => loadSavedFloatWidth());+ const [pos, setPos] = useState<{ x: number; y: number }>(() => loadSavedFloatPos(panelWidth));+ const dragOriginRef = useRef<{ startX: number; startY: number; origX: number; origY: number } | null>(+ null+ );+ const resizeOriginRef = useRef<{ startX: number; origWidth: number } | null>(null);++ useEffect(() => {+ if (!isOpen) return;+ const onKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [isOpen, onClose]);++ useEffect(() => {+ if (!isOpen || blocking) return;+ const onResize = () => {+ setPos((prev) => ({+ x: Math.max(8, Math.min(window.innerWidth - panelWidth - 8, prev.x)),+ y: Math.max(8, Math.min(window.innerHeight - 100, prev.y)),+ }));+ };+ window.addEventListener('resize', onResize);+ return () => window.removeEventListener('resize', onResize);+ }, [isOpen, blocking, panelWidth]);++ const handleHeaderDragStart = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ if (blocking || e.button !== 0) return;+ e.preventDefault();+ e.stopPropagation();+ dragOriginRef.current = {+ startX: e.clientX,+ startY: e.clientY,+ origX: pos.x,+ origY: pos.y,+ };++ const onMove = (ev: PointerEvent) => {+ const origin = dragOriginRef.current;+ if (!origin) return;+ const nextX = Math.max(+ 8,+ Math.min(window.innerWidth - panelWidth - 8, origin.origX + (ev.clientX - origin.startX))+ );+ const nextY = Math.max(+ 8,+ Math.min(window.innerHeight - 80, origin.origY + (ev.clientY - origin.startY))+ );+ setPos({ x: Math.round(nextX), y: Math.round(nextY) });+ };++ const onUp = (ev: PointerEvent) => {+ const origin = dragOriginRef.current;+ if (origin) {+ const finalX = Math.max(+ 8,+ Math.min(window.innerWidth - panelWidth - 8, origin.origX + (ev.clientX - origin.startX))+ );+ const finalY = Math.max(+ 8,+ Math.min(window.innerHeight - 80, origin.origY + (ev.clientY - origin.startY))+ );+ safeLocalStorageSetItem(+ FLOAT_POS_STORAGE_KEY,+ JSON.stringify({ x: Math.round(finalX), y: Math.round(finalY) }),+ 'sphere floating position'+ );+ }+ dragOriginRef.current = null;+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ },+ [blocking, pos.x, pos.y, panelWidth]+ );++ const handleResizeStart = useCallback(+ (e: React.PointerEvent<HTMLDivElement>) => {+ e.preventDefault();+ e.stopPropagation();+ resizeOriginRef.current = { startX: e.clientX, origWidth: panelWidth };++ const onMove = (ev: PointerEvent) => {+ const origin = resizeOriginRef.current;+ if (!origin) return;+ const nextW = Math.max(240, Math.min(360, Math.round(origin.origWidth + (ev.clientX - origin.startX))));+ setPanelWidth(nextW);+ };++ const onUp = (ev: PointerEvent) => {+ const origin = resizeOriginRef.current;+ if (origin) {+ const finalW = Math.max(240, Math.min(360, Math.round(origin.origWidth + (ev.clientX - origin.startX))));+ safeLocalStorageSetItem(FLOAT_WIDTH_STORAGE_KEY, String(finalW), 'sphere floating width');+ }+ resizeOriginRef.current = null;+ window.removeEventListener('pointermove', onMove);+ window.removeEventListener('pointerup', onUp);+ };++ window.addEventListener('pointermove', onMove);+ window.addEventListener('pointerup', onUp);+ },+ [panelWidth]+ );++ if (!isOpen) return null;++ const computedSphereSize = Math.max(176, panelWidth - 48);++ const content = blocking ? (+ <div+ className="fixed inset-0 z-[120] flex items-center justify-center bg-black/50 backdrop-blur-[2px]"+ onPointerDown={onClose}+ role="dialog"+ aria-modal="true"+ aria-label="3D Sphere Color Picker"+ >+ <SphereColorPicker+ {...pickerProps}+ variant="floating"+ sphereSize={computedSphereSize}+ onClose={onClose}+ className="w-[276px]"+ />+ </div>+ ) : (+ <div+ style={{ left: pos.x, top: pos.y, width: panelWidth }}+ role="dialog"+ aria-modal="false"+ aria-label="3D Sphere Color Picker"+ className="fixed z-[95] pointer-events-auto"+ >+ <div className="relative">+ <SphereColorPicker+ {...pickerProps}+ variant="floating"+ isPinned={false}+ sphereSize={computedSphereSize}+ onClose={onClose}+ onHeaderDragStart={handleHeaderDragStart}+ className="w-full"+ />+ <div+ onPointerDown={handleResizeStart}+ title="Drag to resize"+ className="absolute bottom-0.5 right-0.5 w-3 h-3 cursor-nwse-resize opacity-35 hover:opacity-80 transition-opacity"+ style={{+ background:+ 'linear-gradient(135deg, transparent 45%, #8a8a8a 45%, #8a8a8a 58%, transparent 58%, transparent 72%, #8a8a8a 72%, #8a8a8a 85%, transparent 85%)',+ }}+ />+ </div>+ </div>+ );++ return typeof document !== 'undefined' ? createPortal(content, document.body) : content;+};diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsxindex 3070485..227825d 100644--- a/src/components/SubToolList.tsx+++ b/src/components/SubToolList.tsx@@ -1,15 +1,18 @@import React, { useState, useRef } from 'react';import {Paintbrush,+ Palette,PenTool,Pencil,Plus,+ Copy,Download,Trash2,Loader2,FolderDown,ChevronDown,ChevronRight,+ Sliders,} from 'lucide-react';import { BrushCategory, BrushPresetId, CspBrush } from '../types/editor';import {@@ -21,6 +24,7 @@ import {import {deleteCustomBrush,prepareBrushSettingsForCsp,+ saveCustomBrush,} from '../utils/brushStorage';import {BUILTIN_BRUSHES,@@ -34,7 +38,7 @@ import {getSavedBrushSettings,saveActivePresetId,} from '../utils/brushPresetManager';-import { useToolStore, toolStoreActions } from '../stores';+import { useToolStore, toolStoreActions, uiStoreActions } from '../stores';export interface SubToolListProps {customBrushes: CspBrush[];@@ -44,6 +48,7 @@ export interface SubToolListProps {function renderBuiltinIcon(icon: BuiltinBrushDefinition['icon']) {if (icon === 'pen') return <PenTool className="w-3 h-3 shrink-0 opacity-80" />;if (icon === 'pencil') return <Pencil className="w-3 h-3 shrink-0 opacity-80" />;+ if (icon === 'palette') return <Palette className="w-3 h-3 shrink-0 text-rose-300/85" />;return <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />;}@@ -129,30 +134,92 @@ export const SubToolList: React.FC<SubToolListProps> = React.memo(}};+ const handleCreateNewBrush = async () => {+ const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;+ const base = buildExportableBrush('impasto-bristle-oil', customBrushes);+ const newBrush: CspBrush = {+ ...base,+ id,+ name: 'New Natural Brush',+ category: 'natural-paint',+ badge: 'Studio',+ importedAt: Date.now(),+ };+ await saveCustomBrush(newBrush);+ setCustomBrushes((prev) => [newBrush, ...prev]);+ await handleSelectCustomBrush(newBrush);+ uiStoreActions.setBrushStudioModalOpen(true);+ };++ const handleDuplicateActiveBrush = async () => {+ const sourceId = activePreset || DEFAULT_BRUSH_PRESET_ID;+ const liveSettings = useToolStore.getState().brushSettings;+ const exported = buildExportableBrush(sourceId, customBrushes, liveSettings);+ const id = `inkb-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;+ const dupBrush: CspBrush = {+ ...exported,+ id,+ name: `${exported.name} Copy`,+ badge: 'Studio',+ importedAt: Date.now(),+ };+ await saveCustomBrush(dupBrush);+ setCustomBrushes((prev) => [dupBrush, ...prev]);+ await handleSelectCustomBrush(dupBrush);+ uiStoreActions.setBrushStudioModalOpen(true);+ };+const brushesByCategory = (cat: BrushCategory) =>BUILTIN_BRUSHES.filter((b) => b.category === cat);return (<>- <div className="px-1.5 py-1 flex items-center justify-end gap-1 shrink-0">- <button- type="button"- onClick={() => sutInputRef.current?.click()}- title="Import Brush (.inkb, .sut)"- className="h-5 px-1.5 rounded flex items-center gap-1 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"- >- <Plus className="w-3 h-3" />- <span>Import</span>- </button>- <button- type="button"- onClick={() => handleExportBrush(activePreset || DEFAULT_BRUSH_PRESET_ID)}- title="Export Active Brush (.inkb)"- className="h-5 px-1.5 rounded flex items-center gap-1 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"- >- <Download className="w-3 h-3" />- <span>Export</span>- </button>+ <div className="px-1.5 py-1 flex items-center justify-between gap-0.5 shrink-0">+ <div className="flex items-center gap-0.5">+ <button+ type="button"+ onClick={handleCreateNewBrush}+ title="Create New Brush in Brush Studio"+ className="h-5 px-1 rounded flex items-center gap-0.5 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"+ >+ <Plus className="w-3 h-3" />+ <span>New</span>+ </button>+ <button+ type="button"+ onClick={handleDuplicateActiveBrush}+ title="Duplicate Active Brush"+ className="h-5 px-1 rounded flex items-center text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"+ >+ <Copy className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}+ title="Edit Active Brush in Brush Studio"+ className="h-5 px-1 rounded flex items-center text-[10px] text-[#8a8a8a] hover:text-[var(--accent)] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"+ >+ <Sliders className="w-2.5 h-2.5" />+ </button>+ </div>+ <div className="flex items-center gap-0.5">+ <button+ type="button"+ onClick={() => sutInputRef.current?.click()}+ title="Import Brush (.inkb, .sut)"+ className="h-5 px-1 rounded flex items-center gap-0.5 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"+ >+ <FolderDown className="w-2.5 h-2.5" />+ </button>+ <button+ type="button"+ onClick={() => handleExportBrush(activePreset || DEFAULT_BRUSH_PRESET_ID)}+ title="Export Active Brush (.inkb)"+ className="h-5 px-1 rounded flex items-center gap-0.5 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"+ >+ <Download className="w-2.5 h-2.5" />+ </button>+ </div></div><inputdiff --git a/src/components/SubViewPanel.tsx b/src/components/SubViewPanel.tsxindex e02a970..e31c562 100644--- a/src/components/SubViewPanel.tsx+++ b/src/components/SubViewPanel.tsx@@ -256,18 +256,24 @@ export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(return;}const onKeyDown = (e: KeyboardEvent) => {- if (e.code === 'Space') setIsSpaceHeld(true);+ if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(true);if (e.key === 'Alt') setIsAltHeld(true);};const onKeyUp = (e: KeyboardEvent) => {- if (e.code === 'Space') setIsSpaceHeld(false);+ if (e.code === 'Space' || e.key === ' ') setIsSpaceHeld(false);if (e.key === 'Alt') setIsAltHeld(false);};+ const onBlur = () => {+ setIsSpaceHeld(false);+ setIsAltHeld(false);+ };window.addEventListener('keydown', onKeyDown);- window.addEventListener('keyup', onKeyUp);+ window.addEventListener('keyup', onKeyUp, true);+ window.addEventListener('blur', onBlur);return () => {window.removeEventListener('keydown', onKeyDown);- window.removeEventListener('keyup', onKeyUp);+ window.removeEventListener('keyup', onKeyUp, true);+ window.removeEventListener('blur', onBlur);};}, [isHoveringStage]);diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsxindex 6945143..fb51911 100644--- a/src/components/ToolPropertyInspector.tsx+++ b/src/components/ToolPropertyInspector.tsx@@ -7,6 +7,13 @@ import {Minimize2,RotateCcw,Feather,+ Sliders,+ Scissors,+ Copy,+ ClipboardPaste,+ Layers,+ Trash2,+ Crop,} from 'lucide-react';import {BrushSettings,@@ -24,8 +31,16 @@ import {ShapeKind,ShapeDrawMode,ShapeFillColorMode,+ GradientType,+ GradientRepeatMode,+ GradientBlendMode,+ RetouchMode,+ RetouchTonalRange,+ CloneSampleMode,+ PenToolMode,} from '../types/editor';import { isOpenShape } from '../utils/shapeEngine';+import { GRADIENT_PRESETS, resolveGradientStops } from '../utils/gradientEngine';import { saveCustomBrushDebounced } from '../utils/brushStorage';import { resolveBrushTipImage } from '../utils/brushOutline';import { BUILTIN_BRUSHES } from '../utils/presetBrushes';@@ -36,7 +51,13 @@ import {} from '../utils/brushPresetManager';import { renderBrushStrokePreview } from '../utils/brushPreview';import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/BrushEngine';-import { useToolStore, toolStoreActions, useUiStore, uiStoreActions } from '../stores';+import {+ useToolStore,+ toolStoreActions,+ interactiveToolBridge,+ useUiStore,+ uiStoreActions,+} from '../stores';interface CompactSliderProps {label: string;@@ -112,6 +133,12 @@ export interface ToolPropertyInspectorProps {setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;onDeselect?: () => void;onTransformSelection?: () => void;+ onClearSelection?: () => void;+ onDeleteOutsideSelection?: () => void;+ onCutSelection?: () => void;+ onCopySelection?: () => void;+ onPasteSelection?: () => void;+ onMoveSelectionToNewLayer?: () => void;onExpandSelection?: (pixels: number) => void;onContractSelection?: (pixels: number) => void;onFeatherSelection?: (radius: number) => void;@@ -125,6 +152,12 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = ReactsetCustomBrushes,onDeselect,onTransformSelection,+ onClearSelection,+ onDeleteOutsideSelection,+ onCutSelection,+ onCopySelection,+ onPasteSelection,+ onMoveSelectionToNewLayer,onExpandSelection,onContractSelection,onFeatherSelection,@@ -137,6 +170,17 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reactconst frameSettings = useToolStore((s) => s.frameSettings);const liquifySettings = useToolStore((s) => s.liquifySettings);const shapeSettings = useToolStore((s) => s.shapeSettings);+ const gradientSettings = useToolStore((s) => s.gradientSettings);+ const activeGradientMesh = useToolStore((s) => s.activeGradientMesh);+ const retouchSettings = useToolStore((s) => s.retouchSettings);+ const isPickingCloneSource = useToolStore((s) => s.isPickingCloneSource);+ const cloneSourceAnchor = useToolStore((s) => s.cloneSourceAnchor);+ const penSettings = useToolStore((s) => s.penSettings);+ const activePenPointCount = useToolStore((s) => s.activePenPointCount);+ const activePenClosed = useToolStore((s) => s.activePenClosed);+ const activePenSelectedAnchor = useToolStore((s) => s.activePenSelectedAnchor);+ const primaryColor = useToolStore((s) => s.primaryColor);+ const secondaryColor = useToolStore((s) => s.secondaryColor);const balloonSettings = useToolStore((s) => s.balloonSettings);const vectorEditSettings = useToolStore((s) => s.vectorEditSettings);const wandSettings = useToolStore((s) => s.wandSettings);@@ -201,6 +245,12 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = ReactdensityOfPaint: brushSettings.densityOfPaint,colorStretch: brushSettings.colorStretch,wetEdge: brushSettings.wetEdge,+ renderMode: brushSettings.renderMode,+ bristle: brushSettings.bristle,+ naturalPaint: brushSettings.naturalPaint,+ impasto: brushSettings.impasto,+ surfaceTextureId: brushSettings.surfaceTextureId,+ grainMappingMode: brushSettings.grainMappingMode,},true);@@ -366,6 +416,692 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React);}+ if (currentTool === 'gradient') {+ const resolvedStops = resolveGradientStops(gradientSettings, primaryColor, secondaryColor);+ const cssStops = (gradientSettings.reverse ? [...resolvedStops].reverse() : resolvedStops)+ .map((s) => {+ const pct = Math.round((gradientSettings.reverse ? 1 - s.offset : s.offset) * 100);+ return `rgba(${Math.round(s.r)},${Math.round(s.g)},${Math.round(s.b)},${(s.a / 255).toFixed(2)}) ${pct}%`;+ })+ .join(', ');++ const selectedMeshNode =+ activeGradientMesh && activeGradientMesh.selectedNodeIndex !== null+ ? activeGradientMesh.nodes[activeGradientMesh.selectedNodeIndex]+ : null;++ return (+ <div className="p-2 space-y-3 overflow-y-auto flex-1">+ <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Gradient</div>++ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['linear', 'Linear'],+ ['radial', 'Radial'],+ ['mesh', 'Mesh'],+ ] as Array<[GradientType, string]>+ ).map(([t, lbl]) => (+ <button+ key={t}+ type="button"+ onClick={() => toolStoreActions.updateGradientSettings({ type: t })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ gradientSettings.type === t+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>++ {gradientSettings.type !== 'mesh' ? (+ <>+ <div+ className="h-5 rounded border border-white/10"+ style={{+ backgroundImage: `linear-gradient(90deg, ${cssStops}), repeating-conic-gradient(#555 0% 25%, #888 0% 50%)`,+ backgroundSize: '100% 100%, 8px 8px',+ }}+ />++ <div className="grid grid-cols-2 gap-1">+ {GRADIENT_PRESETS.map((preset) => (+ <button+ key={preset.id}+ type="button"+ onClick={() =>+ toolStoreActions.updateGradientSettings({+ useForegroundBackground: Boolean(preset.useForegroundBackground),+ stops: preset.stops.map((s, idx) => ({+ id: `stop-${preset.id}-${idx}`,+ offset: s.offset,+ color: s.color,+ opacity: s.opacity,+ })),+ })+ }+ className="px-1.5 py-1 rounded text-[10px] text-left bg-[#161616] text-[#bdbdbd] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer truncate"+ >+ {preset.name}+ </button>+ ))}+ </div>++ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Use FG / BG</span>+ <input+ type="checkbox"+ checked={gradientSettings.useForegroundBackground}+ onChange={(e) =>+ toolStoreActions.updateGradientSettings({+ useForegroundBackground: e.target.checked,+ })+ }+ />+ </label>++ {/* Color Stops Editor */}+ <div className="space-y-1.5 pt-1 border-t border-[#2c2c2c]">+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">+ <span>Stops ({gradientSettings.stops.length})</span>+ <button+ type="button"+ onClick={() => {+ const nextStops = [+ ...gradientSettings.stops,+ {+ id: `stop-${Date.now()}`,+ offset: 0.5,+ color: primaryColor || '#38bdf8',+ opacity: 1,+ },+ ];+ toolStoreActions.updateGradientSettings({+ useForegroundBackground: false,+ stops: nextStops,+ });+ }}+ className="px-1.5 py-0.5 rounded bg-[#2c2c2c] text-[#e5e5e5] hover:bg-[#3a3a3a] cursor-pointer"+ >+ + Add+ </button>+ </div>+ <div className="space-y-1 max-h-32 overflow-y-auto pr-0.5">+ {gradientSettings.stops.map((stop, idx) => (+ <div key={stop.id} className="flex items-center gap-1 text-[10px]">+ <input+ type="color"+ value={stop.color}+ onChange={(e) => {+ const next = gradientSettings.stops.map((s, i) =>+ i === idx ? { ...s, color: e.target.value } : s+ );+ toolStoreActions.updateGradientSettings({+ useForegroundBackground: false,+ stops: next,+ });+ }}+ className="w-5 h-4 bg-transparent border-0 cursor-pointer shrink-0"+ />+ <input+ type="range"+ min={0}+ max={100}+ value={Math.round(stop.offset * 100)}+ onChange={(e) => {+ const next = gradientSettings.stops.map((s, i) =>+ i === idx ? { ...s, offset: Number(e.target.value) / 100 } : s+ );+ toolStoreActions.updateGradientSettings({ stops: next });+ }}+ className="flex-1 min-w-0"+ title={`Position: ${Math.round(stop.offset * 100)}%`}+ />+ <input+ type="number"+ min={0}+ max={100}+ value={Math.round(stop.opacity * 100)}+ onChange={(e) => {+ const val = Math.max(0, Math.min(100, Number(e.target.value))) / 100;+ const next = gradientSettings.stops.map((s, i) =>+ i === idx ? { ...s, opacity: val } : s+ );+ toolStoreActions.updateGradientSettings({ stops: next });+ }}+ className="w-9 px-1 py-0.5 bg-[#161616] text-[#e5e5e5] rounded font-mono text-right"+ title="Stop Opacity %"+ />+ {gradientSettings.stops.length > 2 && (+ <button+ type="button"+ onClick={() =>+ toolStoreActions.updateGradientSettings({+ stops: gradientSettings.stops.filter((_, i) => i !== idx),+ })+ }+ className="text-[#8a8a8a] hover:text-red-400 px-0.5 cursor-pointer"+ title="Remove Stop"+ >+ ×+ </button>+ )}+ </div>+ ))}+ </div>+ </div>++ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#8a8a8a]">Repeat</span>+ <select+ value={gradientSettings.repeat}+ onChange={(e) =>+ toolStoreActions.updateGradientSettings({+ repeat: e.target.value as GradientRepeatMode,+ })+ }+ className="px-1.5 py-0.5 text-[11px] bg-[#161616] text-[#e5e5e5] rounded cursor-pointer"+ >+ <option value="clamp">None</option>+ <option value="repeat">Repeat</option>+ <option value="reflect">Reflect</option>+ </select>+ </div>++ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Reverse</span>+ <input+ type="checkbox"+ checked={gradientSettings.reverse}+ onChange={(e) =>+ toolStoreActions.updateGradientSettings({ reverse: e.target.checked })+ }+ />+ </label>+ </>+ ) : (+ <div className="space-y-2 pt-1 border-t border-[#2c2c2c]">+ <CompactSlider+ label="Columns"+ valueLabel={`${gradientSettings.meshCols}`}+ min={2}+ max={6}+ value={gradientSettings.meshCols}+ onChange={(v) => toolStoreActions.updateGradientSettings({ meshCols: v })}+ />+ <CompactSlider+ label="Rows"+ valueLabel={`${gradientSettings.meshRows}`}+ min={2}+ max={6}+ value={gradientSettings.meshRows}+ onChange={(v) => toolStoreActions.updateGradientSettings({ meshRows: v })}+ />++ {selectedMeshNode && activeGradientMesh?.selectedNodeIndex !== null && (+ <div className="space-y-1.5 p-1.5 rounded bg-[#161616]">+ <div className="flex items-center justify-between text-[10px]">+ <span className="text-[#8a8a8a]">+ Node #{activeGradientMesh!.selectedNodeIndex! + 1}+ </span>+ <input+ type="color"+ value={selectedMeshNode.color}+ onChange={(e) =>+ toolStoreActions.updateActiveGradientMeshNode(+ activeGradientMesh!.selectedNodeIndex!,+ { color: e.target.value }+ )+ }+ className="w-6 h-5 bg-transparent border-0 cursor-pointer"+ />+ </div>+ <CompactSlider+ label="Node Opacity"+ valueLabel={`${Math.round(selectedMeshNode.opacity * 100)}%`}+ min={0}+ max={100}+ value={Math.round(selectedMeshNode.opacity * 100)}+ onChange={(v) =>+ toolStoreActions.updateActiveGradientMeshNode(+ activeGradientMesh!.selectedNodeIndex!,+ { opacity: v / 100 }+ )+ }+ />+ </div>+ )}++ <div className="grid grid-cols-2 gap-1">+ <button+ type="button"+ onClick={() => interactiveToolBridge.initGradientMesh?.()}+ className="py-1 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] hover:bg-[#3a3a3a] cursor-pointer"+ >+ {activeGradientMesh ? 'Reset Mesh' : 'Create Mesh'}+ </button>+ {activeGradientMesh && (+ <button+ type="button"+ onClick={() => interactiveToolBridge.applyGradientMesh?.()}+ className="py-1 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium cursor-pointer"+ >+ Apply (Enter)+ </button>+ )}+ </div>+ {activeGradientMesh && (+ <button+ type="button"+ onClick={() => interactiveToolBridge.cancelGradientMesh?.()}+ className="w-full py-1 rounded bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] text-[10px] cursor-pointer"+ >+ Cancel (Esc)+ </button>+ )}+ </div>+ )}++ <div className="space-y-2 pt-1 border-t border-[#2c2c2c]">+ <CompactSlider+ label="Opacity"+ valueLabel={`${Math.round(gradientSettings.opacity * 100)}%`}+ min={5}+ max={100}+ value={Math.round(gradientSettings.opacity * 100)}+ onChange={(v) => toolStoreActions.updateGradientSettings({ opacity: v / 100 })}+ />+ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#8a8a8a]">Blend</span>+ <select+ value={gradientSettings.blendMode}+ onChange={(e) =>+ toolStoreActions.updateGradientSettings({+ blendMode: e.target.value as GradientBlendMode,+ })+ }+ className="px-1.5 py-0.5 text-[11px] bg-[#161616] text-[#e5e5e5] rounded cursor-pointer"+ >+ <option value="normal">Normal</option>+ <option value="multiply">Multiply</option>+ <option value="screen">Screen</option>+ <option value="overlay">Overlay</option>+ </select>+ </div>+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Dither</span>+ <input+ type="checkbox"+ checked={gradientSettings.dither}+ onChange={(e) =>+ toolStoreActions.updateGradientSettings({ dither: e.target.checked })+ }+ />+ </label>+ </div>+ </div>+ );+ }++ if (currentTool === 'retouch') {+ const retouchModes: Array<{ id: RetouchMode; label: string }> = [+ { id: 'smudge', label: 'Smudge' },+ { id: 'blur', label: 'Blur' },+ { id: 'dodge', label: 'Dodge' },+ { id: 'burn', label: 'Burn' },+ { id: 'clone-stamp', label: 'Clone Stamp' },+ ];+ const strengthLabel =+ retouchSettings.mode === 'dodge' || retouchSettings.mode === 'burn'+ ? 'Exposure'+ : retouchSettings.mode === 'clone-stamp'+ ? 'Opacity'+ : 'Strength';+ return (+ <div className="p-2 space-y-3 overflow-y-auto flex-1">+ <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Retouch</div>+ <div className="space-y-0.5">+ {retouchModes.map((m) => (+ <button+ key={m.id}+ type="button"+ onClick={() => toolStoreActions.updateRetouchSettings({ mode: m.id })}+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${+ retouchSettings.mode === m.id+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'+ }`}+ >+ {m.label}+ </button>+ ))}+ </div>++ <CompactSlider+ label="Size"+ valueLabel={`${retouchSettings.size}px`}+ min={2}+ max={300}+ value={retouchSettings.size}+ onChange={(v) => toolStoreActions.updateRetouchSettings({ size: v })}+ />+ <CompactSlider+ label={strengthLabel}+ valueLabel={`${retouchSettings.strength}%`}+ min={1}+ max={100}+ value={retouchSettings.strength}+ onChange={(v) => toolStoreActions.updateRetouchSettings({ strength: v })}+ />+ <CompactSlider+ label="Hardness"+ valueLabel={`${retouchSettings.hardness}%`}+ min={0}+ max={100}+ value={retouchSettings.hardness}+ onChange={(v) => toolStoreActions.updateRetouchSettings({ hardness: v })}+ />+ <CompactSlider+ label="Spacing"+ valueLabel={`${Math.round(retouchSettings.spacing * 100)}%`}+ min={5}+ max={50}+ value={Math.round(retouchSettings.spacing * 100)}+ onChange={(v) => toolStoreActions.updateRetouchSettings({ spacing: v / 100 })}+ />++ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Pressure</span>+ <input+ type="checkbox"+ checked={retouchSettings.usePressure}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({ usePressure: e.target.checked })+ }+ />+ </label>++ {retouchSettings.mode === 'smudge' && (+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1 border-t border-[#2c2c2c]">+ <span>Finger Painting</span>+ <input+ type="checkbox"+ checked={retouchSettings.smudgeFingerPainting}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({+ smudgeFingerPainting: e.target.checked,+ })+ }+ />+ </label>+ )}++ {(retouchSettings.mode === 'dodge' || retouchSettings.mode === 'burn') && (+ <div className="space-y-2 pt-1 border-t border-[#2c2c2c]">+ <div className="space-y-1">+ <div className="text-[11px] text-[#8a8a8a]">Range</div>+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['shadows', 'Shadows'],+ ['midtones', 'Mid'],+ ['highlights', 'High'],+ ] as Array<[RetouchTonalRange, string]>+ ).map(([r, lbl]) => (+ <button+ key={r}+ type="button"+ onClick={() => toolStoreActions.updateRetouchSettings({ tonalRange: r })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ retouchSettings.tonalRange === r+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ </div>+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Protect Tones</span>+ <input+ type="checkbox"+ checked={retouchSettings.protectTones}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({ protectTones: e.target.checked })+ }+ />+ </label>+ </div>+ )}++ {retouchSettings.mode === 'clone-stamp' && (+ <div className="space-y-2 pt-1 border-t border-[#2c2c2c]">+ <button+ type="button"+ onClick={() => toolStoreActions.setIsPickingCloneSource(!isPickingCloneSource)}+ className={`w-full py-1 rounded text-[11px] transition-colors cursor-pointer ${+ isPickingCloneSource+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'bg-[#2c2c2c] text-[#e5e5e5] hover:bg-[#3a3a3a]'+ }`}+ >+ {isPickingCloneSource ? 'Click Canvas to Set Origin...' : 'Pick Source (Alt+Click)'}+ </button>+ <div className="text-[10px] font-mono text-[#8a8a8a]">+ {cloneSourceAnchor+ ? `Origin: ${Math.round(cloneSourceAnchor.x)}, ${Math.round(cloneSourceAnchor.y)}`+ : 'No source set'}+ </div>+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Aligned</span>+ <input+ type="checkbox"+ checked={retouchSettings.cloneAligned}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({ cloneAligned: e.target.checked })+ }+ />+ </label>+ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#8a8a8a]">Sample</span>+ <select+ value={retouchSettings.cloneSampleMode}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({+ cloneSampleMode: e.target.value as CloneSampleMode,+ })+ }+ className="px-1.5 py-0.5 text-[11px] bg-[#161616] text-[#e5e5e5] rounded cursor-pointer"+ >+ <option value="active">Active Layer</option>+ <option value="all-visible">All Visible</option>+ </select>+ </div>+ </div>+ )}+ </div>+ );+ }++ if (currentTool === 'pen') {+ return (+ <div className="p-2 space-y-3 overflow-y-auto flex-1">+ <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Bézier Pen</div>++ <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['draw', 'Draw'],+ ['edit', 'Edit Nodes'],+ ] as Array<[PenToolMode, string]>+ ).map(([m, lbl]) => (+ <button+ key={m}+ type="button"+ onClick={() => toolStoreActions.updatePenSettings({ mode: m })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ penSettings.mode === m+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>++ <CompactSlider+ label="Stroke Width"+ valueLabel={`${penSettings.strokeWidth}px`}+ min={1}+ max={100}+ value={penSettings.strokeWidth}+ onChange={(v) => toolStoreActions.updatePenSettings({ strokeWidth: v })}+ />+ <CompactSlider+ label="Opacity"+ valueLabel={`${Math.round(penSettings.opacity * 100)}%`}+ min={5}+ max={100}+ value={Math.round(penSettings.opacity * 100)}+ onChange={(v) => toolStoreActions.updatePenSettings({ opacity: v / 100 })}+ />++ <div className="space-y-1.5 pt-1 border-t border-[#2c2c2c]">+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Stroke Path</span>+ <input+ type="checkbox"+ checked={penSettings.strokeEnabled}+ onChange={(e) =>+ toolStoreActions.updatePenSettings({ strokeEnabled: e.target.checked })+ }+ />+ </label>+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Fill Closed Path</span>+ <input+ type="checkbox"+ checked={penSettings.fillEnabled}+ onChange={(e) =>+ toolStoreActions.updatePenSettings({ fillEnabled: e.target.checked })+ }+ />+ </label>+ {penSettings.fillEnabled && (+ <div className="space-y-1.5">+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['primary', 'Primary'],+ ['secondary', 'Sub'],+ ['custom', 'Custom'],+ ] as const+ ).map(([m, lbl]) => (+ <button+ key={m}+ type="button"+ onClick={() => toolStoreActions.updatePenSettings({ fillColorMode: m })}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ penSettings.fillColorMode === m+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ {penSettings.fillColorMode === 'custom' && (+ <div className="flex items-center justify-between">+ <span className="text-[10px] font-mono text-[#8a8a8a]">+ {penSettings.customFillColor}+ </span>+ <input+ type="color"+ value={penSettings.customFillColor}+ onChange={(e) =>+ toolStoreActions.updatePenSettings({ customFillColor: e.target.value })+ }+ className="w-6 h-5 bg-transparent border-0 cursor-pointer"+ />+ </div>+ )}+ </div>+ )}+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">+ <span>Rubber Band</span>+ <input+ type="checkbox"+ checked={penSettings.rubberBandPreview}+ onChange={(e) =>+ toolStoreActions.updatePenSettings({ rubberBandPreview: e.target.checked })+ }+ />+ </label>+ </div>++ {activePenPointCount > 0 && (+ <div className="space-y-1.5 pt-1 border-t border-[#2c2c2c]">+ <div className="text-[10px] font-mono text-[#8a8a8a]">+ Path: {activePenPointCount} anchor{activePenPointCount === 1 ? '' : 's'}+ {activePenClosed ? ' (Closed)' : ''}+ </div>+ <div className="grid grid-cols-2 gap-1">+ <button+ type="button"+ onClick={() => interactiveToolBridge.toggleClosePenPath?.()}+ disabled={activePenPointCount < 2}+ className="py-1 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] disabled:opacity-40 cursor-pointer"+ >+ {activePenClosed ? 'Open Path' : 'Close Path'}+ </button>+ <button+ type="button"+ onClick={() => interactiveToolBridge.toggleSelectedPenAnchorSmooth?.()}+ disabled={activePenSelectedAnchor === null}+ className="py-1 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] disabled:opacity-40 cursor-pointer"+ >+ Smooth / Corner+ </button>+ <button+ type="button"+ onClick={() => interactiveToolBridge.deleteSelectedPenAnchor?.()}+ className="py-1 rounded bg-[#2c2c2c] text-[#e5e5e5] text-[10px] cursor-pointer"+ >+ Delete Node+ </button>+ <button+ type="button"+ onClick={() => interactiveToolBridge.commitPenPath?.()}+ disabled={activePenPointCount < 2}+ className="py-1 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[10px] font-medium disabled:opacity-40 cursor-pointer"+ >+ Commit (Enter)+ </button>+ </div>+ <button+ type="button"+ onClick={() => interactiveToolBridge.cancelPenPath?.()}+ className="w-full py-1 rounded bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] text-[10px] cursor-pointer"+ >+ Cancel (Esc)+ </button>+ </div>+ )}++ <div className="text-[10px] text-[#707070] leading-relaxed pt-1 border-t border-[#2c2c2c]">+ Click: corner · Drag: handles · Alt+Drag: break · Ctrl: edit nodes · Click curve in Edit: split+ </div>+ </div>+ );+ }+if (currentTool === 'shape') {const openShape = isOpenShape(shapeSettings.shape);const shapeOptions: Array<{ id: ShapeKind; label: string }> = [@@ -824,6 +1560,62 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React<Feather className="w-3 h-3" /></button></div>+ <div className="grid grid-cols-3 gap-1 pt-1">+ <button+ type="button"+ onClick={onCutSelection}+ title="Cut Selection (Ctrl+X)"+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center gap-1 cursor-pointer"+ >+ <Scissors className="w-3 h-3" />+ <span>Cut</span>+ </button>+ <button+ type="button"+ onClick={onCopySelection}+ title="Copy Selection (Ctrl+C)"+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center gap-1 cursor-pointer"+ >+ <Copy className="w-3 h-3" />+ <span>Copy</span>+ </button>+ <button+ type="button"+ onClick={onPasteSelection}+ title="Paste to New Layer (Ctrl+V)"+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center gap-1 cursor-pointer"+ >+ <ClipboardPaste className="w-3 h-3" />+ <span>Paste</span>+ </button>+ </div>+ <button+ type="button"+ onClick={onMoveSelectionToNewLayer}+ title="Move Selected Section to New Layer (Ctrl+Shift+J)"+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[var(--accent)] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"+ >+ <Layers className="w-3 h-3" />+ <span>Move to New Layer</span>+ </button>+ <button+ type="button"+ onClick={onClearSelection}+ title="Delete Selected Section (Del)"+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-rose-400 flex items-center gap-1.5 cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ <span>Delete Section</span>+ </button>+ <button+ type="button"+ onClick={onDeleteOutsideSelection}+ title="Delete Outside Selected Section"+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-rose-400 flex items-center gap-1.5 cursor-pointer"+ >+ <Crop className="w-3 h-3" />+ <span>Delete Outside</span>+ </button><buttontype="button"onClick={onInvertSelection}@@ -1178,7 +1970,20 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React<>{/* Live S-Curve Stroke Preview + Quick Size/Opacity Bar */}<div className="shrink-0 bg-[#1b1b1b] border-t border-[#2a2a2a] px-2 py-1.5 space-y-1.5">- <canvas ref={previewCanvasRef} className="w-full h-8 rounded bg-[#161616] block" />+ <div className="flex items-center gap-1">+ <canvas ref={previewCanvasRef} className="flex-1 h-8 rounded bg-[#161616] block min-w-0" />+ {currentTool === 'brush' && (+ <button+ type="button"+ onClick={() => uiStoreActions.setBrushStudioModalOpen(true)}+ title="Open Brush Studio"+ className="h-8 px-1.5 rounded bg-[#262626] hover:bg-[#333333] border border-white/[0.08] text-[#d4d4d4] hover:text-white flex items-center gap-1 text-[10px] shrink-0 cursor-pointer"+ >+ <Sliders className="w-3 h-3 text-[var(--accent)]" />+ <span className="hidden sm:inline">Studio</span>+ </button>+ )}+ </div><CompactSliderlabel="Brush Size ([ / ])"valueLabel={`${brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size)}px`}@@ -1627,20 +2432,32 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React<inputtype="checkbox"checked={Boolean(brushSettings.colorMixing)}- onChange={(e) =>- handleUpdateBrushSettings({ colorMixing: e.target.checked })- }+ onChange={(e) => {+ const enabled = e.target.checked;+ handleUpdateBrushSettings({+ colorMixing: enabled,+ ...(brushSettings.naturalPaint+ ? { naturalPaint: { ...brushSettings.naturalPaint, spatialMixing: enabled } }+ : {}),+ });+ }}/></label>{brushSettings.colorMixing && (<>- <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">- {(- [- { id: 'blend', label: 'Blend' },- { id: 'running_color', label: 'Running' },- { id: 'smear', label: 'Smear' },- ] as const+ <div className={`grid ${brushSettings.naturalPaint?.enabled ? 'grid-cols-4' : 'grid-cols-3'} gap-0.5 bg-[#161616] p-0.5 rounded`}>+ {(brushSettings.naturalPaint?.enabled+ ? ([+ { id: 'blend', label: 'Blend' },+ { id: 'running_color', label: 'Running' },+ { id: 'impasto_mix', label: 'Impasto' },+ { id: 'smear', label: 'Smear' },+ ] as const)+ : ([+ { id: 'blend', label: 'Blend' },+ { id: 'running_color', label: 'Running' },+ { id: 'smear', label: 'Smear' },+ ] as const)).map((m) => (<buttonkey={m.id}@@ -1668,11 +2485,19 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React</label><CompactSliderlabel="Amount of Paint"- valueLabel={`${Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}%`}+ valueLabel={`${Math.round((brushSettings.amountOfPaint ?? brushSettings.naturalPaint?.paintLoad ?? 0.7) * 100)}%`}min={0}max={100}- value={Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}- onChange={(v) => handleUpdateBrushSettings({ amountOfPaint: v / 100 })}+ value={Math.round((brushSettings.amountOfPaint ?? brushSettings.naturalPaint?.paintLoad ?? 0.7) * 100)}+ onChange={(v) => {+ const next = v / 100;+ handleUpdateBrushSettings({+ amountOfPaint: next,+ ...(brushSettings.naturalPaint+ ? { naturalPaint: { ...brushSettings.naturalPaint, paintLoad: next } }+ : {}),+ });+ }}/><CompactSliderlabel="Density of Paint"diff --git a/src/components/ToolStrip.tsx b/src/components/ToolStrip.tsxindex da33129..4d8c4c2 100644--- a/src/components/ToolStrip.tsx+++ b/src/components/ToolStrip.tsx@@ -19,6 +19,9 @@ import {MousePointer2,Shapes,Ruler,+ Blend,+ Droplets,+ Feather,} from 'lucide-react';import { ToolType } from '../types/editor';import { LiquifyIcon } from './LiquifyIcon';@@ -82,6 +85,11 @@ export const ToolStrip: React.FC<ToolStripProps> = React.memo(id: 'liquify',label: 'Liquify (J)',icon: <LiquifyIcon className="w-3.5 h-3.5" />,+ },+ {+ id: 'retouch',+ label: 'Retouch: Smudge / Blur / Dodge / Burn / Clone (S)',+ icon: <Droplets className="w-3.5 h-3.5" />,dividerAfter: true,},{@@ -103,7 +111,9 @@ export const ToolStrip: React.FC<ToolStripProps> = React.memo(dividerAfter: true,},{ id: 'fill', label: 'Fill (G)', icon: <PaintBucket className="w-3.5 h-3.5" /> },+ { id: 'gradient', label: 'Gradient: Linear / Radial / Mesh (Shift+G)', icon: <Blend className="w-3.5 h-3.5" /> },{ id: 'shape', label: 'Shapes (U)', icon: <Shapes className="w-3.5 h-3.5" /> },+ { id: 'pen', label: 'Bézier Pen (P)', icon: <Feather className="w-3.5 h-3.5" /> },{ id: 'object', label: 'Object (O)', icon: <MousePointer2 className="w-3.5 h-3.5" /> },{ id: 'text', label: 'Text (T)', icon: <Type className="w-3.5 h-3.5" /> },{ id: 'frame', label: 'Frame Border (F)', icon: <Frame className="w-3.5 h-3.5" /> },diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsxindex 22ee545..06d047f 100644--- a/src/components/TransformOverlay.tsx+++ b/src/components/TransformOverlay.tsx@@ -10,7 +10,9 @@ import {renderMeshWarp,createDefaultPerspectiveQuad,createDefaultMeshPoints,+ computeMeshSubdivisions,getPointsBounds,+ getMeshSurfaceBounds,evaluateMeshSurface,} from '../utils/transformEngine';@@ -75,11 +77,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({return getPointsBounds(quad);}if (mode === 'mesh') {- const flat: Point2D[] = [];- for (const row of meshPoints) {- for (const pt of row) flat.push(pt);- }- return getPointsBounds(flat);+ return getMeshSurfaceBounds(meshPoints, 6);}if (session.rotation) {const cx = session.x + session.width / 2;@@ -136,8 +134,8 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({const ctx = canvas.getContext('2d');if (!ctx) return;- const bw = Math.max(10, nonAffineBounds.width);- const bh = Math.max(10, nonAffineBounds.height);+ const bw = Math.max(1, nonAffineBounds.width);+ const bh = Math.max(1, nonAffineBounds.height);if (canvas.width !== bw) canvas.width = bw;if (canvas.height !== bh) canvas.height = bh;ctx.clearRect(0, 0, bw, bh);@@ -150,7 +148,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({{ x: quad[3].x - nonAffineBounds.minX, y: quad[3].y - nonAffineBounds.minY },];- renderPerspectiveQuad(ctx, session.sourceCanvas, localQuad, 16);+ renderPerspectiveQuad(ctx, session.sourceCanvas, localQuad, 24);} else {const localMesh: Point2D[][] = meshPoints.map((row) =>row.map((pt) => ({@@ -159,7 +157,13 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({})));- renderMeshWarp(ctx, session.sourceCanvas, localMesh, 4);+ const subPerCell = computeMeshSubdivisions(+ session.sourceCanvas.width,+ session.sourceCanvas.height,+ localMesh,+ false+ );+ renderMeshWarp(ctx, session.sourceCanvas, localMesh, subPerCell);}}, [mode, session.sourceCanvas, nonAffineBounds, quad, meshPoints]);@@ -195,9 +199,9 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({const row: Point2D[] = [];for (let c = 0; c < size; c++) {const u = size > 1 ? c / (size - 1) : 0;- // Resample position from existing surface+ // Resample position from existing surface without integer rounding distortionconst evaluated = evaluateMeshSurface(existingMesh, u, v);- row.push({ x: Math.round(evaluated.x), y: Math.round(evaluated.y) });+ row.push({ x: evaluated.x, y: evaluated.y });}newMesh.push(row);}@@ -551,7 +555,11 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({height: `${nonAffineBounds.height}px`,}}>- <canvas ref={previewCanvasRef} className="w-full h-full block" />+ <canvas+ ref={previewCanvasRef}+ className="w-full h-full block"+ style={{ imageRendering: zoom > 1 ? 'pixelated' : 'auto' }}+ /></div>{/* SVG Overlay for Quad or Mesh Lattice Lines */}diff --git a/src/components/WindowControls.tsx b/src/components/WindowControls.tsxindex 4ce4641..38b0230 100644--- a/src/components/WindowControls.tsx+++ b/src/components/WindowControls.tsx@@ -1,6 +1,7 @@import React, { useState, useEffect, useCallback } from 'react';import { isTauriEnvironment } from '../hooks/useMultiplayer';import { ThemePreset } from '../types/settings';+import { requestAppClose } from '../utils/appCloseFlow';interface WindowControlsProps {themePreset?: ThemePreset;@@ -125,22 +126,10 @@ export const WindowControls: React.FC<WindowControlsProps> = () => {[isTauri]);- const handleClose = useCallback(- async (e: React.MouseEvent) => {- e.stopPropagation();- try {- if (isTauri) {- const { getCurrentWindow } = await import('@tauri-apps/api/window');- await getCurrentWindow().close();- } else {- window.close();- }- } catch (err) {- console.error('Failed to close window:', err);- }- },- [isTauri]- );+ const handleClose = useCallback((e: React.MouseEvent) => {+ e.stopPropagation();+ requestAppClose();+ }, []);return (<divdiff --git a/src/components/brushStudio/BrushStudioControls.tsx b/src/components/brushStudio/BrushStudioControls.tsxnew file mode 100644index 0000000..528ceaa--- /dev/null+++ b/src/components/brushStudio/BrushStudioControls.tsx@@ -0,0 +1,126 @@+import React from 'react';++export interface StudioSliderProps {+ label: string;+ value: number;+ min: number;+ max: number;+ step?: number;+ valueLabel?: string;+ onChange: (value: number) => void;+}++export const StudioSlider: React.FC<StudioSliderProps> = ({+ label,+ value,+ min,+ max,+ step = 1,+ valueLabel,+ onChange,+}) => (+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[11px]">+ <span className="text-[#a3a3a3]">{label}</span>+ <span className="font-mono text-[10px] text-[#e5e5e5]">{valueLabel ?? String(value)}</span>+ </div>+ <input+ type="range"+ min={min}+ max={max}+ step={step}+ value={value}+ onChange={(e) => onChange(Number(e.target.value))}+ className="w-full accent-[var(--accent)]"+ />+ </div>+);++export interface StudioToggleProps {+ label: string;+ description?: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}++export const StudioToggle: React.FC<StudioToggleProps> = ({+ label,+ description,+ checked,+ onChange,+}) => (+ <label className="flex items-center justify-between gap-2 py-1 cursor-pointer select-none">+ <div className="min-w-0">+ <div className="text-[11px] text-[#e5e5e5]">{label}</div>+ {description && <div className="text-[10px] text-[#737373] truncate">{description}</div>}+ </div>+ <input+ type="checkbox"+ checked={checked}+ onChange={(e) => onChange(e.target.checked)}+ className="accent-[var(--accent)] shrink-0"+ />+ </label>+);++export interface StudioSegmentedProps<T extends string> {+ label: string;+ value: T;+ options: Array<{ id: T; label: string }>;+ onChange: (val: T) => void;+}++export function StudioSegmented<T extends string>({+ label,+ value,+ options,+ onChange,+}: StudioSegmentedProps<T>) {+ return (+ <div className="space-y-1">+ <div className="text-[11px] text-[#a3a3a3]">{label}</div>+ <div className="flex flex-wrap gap-1 bg-[#141414] p-1 rounded border border-white/[0.06]">+ {options.map((opt) => (+ <button+ key={opt.id}+ type="button"+ onClick={() => onChange(opt.id)}+ className={`flex-1 min-w-[60px] px-2 py-1 rounded text-[10px] transition-colors cursor-pointer ${+ value === opt.id+ ? 'bg-[#2c2c2c] text-[#f5f5f5] font-medium border border-white/10'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-white/[0.04]'+ }`}+ >+ {opt.label}+ </button>+ ))}+ </div>+ </div>+ );+}++export function readImageFileAsDataUrl(file: File): Promise<{+ dataUrl: string;+ image: HTMLImageElement;+ width: number;+ height: number;+}> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onerror = () => reject(new Error('Failed to read image file.'));+ reader.onload = () => {+ const dataUrl = String(reader.result || '');+ const img = new Image();+ img.onload = () =>+ resolve({+ dataUrl,+ image: img,+ width: img.naturalWidth || img.width || 128,+ height: img.naturalHeight || img.height || 128,+ });+ img.onerror = () => reject(new Error('Unsupported or corrupted image file.'));+ img.src = dataUrl;+ };+ reader.readAsDataURL(file);+ });+}diff --git a/src/components/brushStudio/BrushStudioScratchpad.tsx b/src/components/brushStudio/BrushStudioScratchpad.tsxnew file mode 100644index 0000000..76bdf62--- /dev/null+++ b/src/components/brushStudio/BrushStudioScratchpad.tsx@@ -0,0 +1,395 @@+import React, { useRef, useState, useEffect, useCallback } from 'react';+import { Eraser, Droplets, Sun, Moon, Square } from 'lucide-react';+import type { BrushSettings, Point } from '../../types/editor';+import {+ buildBrushRenderOptions,+ centripetalCatmullRomToBezier,+ drawBrushCubicBezierSegment,+ drawBrushDot,+} from '../../engine/BrushEngine';+import {+ isNaturalPaintBrush,+ NaturalPaintStrokeSession,+} from '../../engine/NaturalPaintRenderer';+import {+ cleanDirtyBrush,+ LayerPixelSampler,+ PaintReservoir,+} from '../../utils/colorMixingEngine';++type ScratchpadBg = 'white' | 'gray' | 'dark';++const BG_COLORS: Record<ScratchpadBg, string> = {+ white: '#f6f4ef',+ gray: '#525252',+ dark: '#1c1c1e',+};++const QUICK_SWATCHES = [+ { label: 'Cadmium Yellow', hex: '#facc15' },+ { label: 'Ultramarine Violet', hex: '#6d28d9' },+ { label: 'Prussian Blue', hex: '#1d4ed8' },+ { label: 'Vermilion Red', hex: '#dc2626' },+];++export interface BrushStudioScratchpadProps {+ brushSettings: BrushSettings;+}++export const BrushStudioScratchpad: React.FC<BrushStudioScratchpadProps> = ({+ brushSettings,+}) => {+ const baseCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const draftCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const [bgMode, setBgMode] = useState<ScratchpadBg>('white');+ const [testColor, setTestColor] = useState<string>(brushSettings.color || '#1d4ed8');+ const [useActiveColor, setUseActiveColor] = useState<boolean>(true);+ const strokeSeedRef = useRef<number>(2026);++ const activeColor = useActiveColor ? brushSettings.color || '#1d4ed8' : testColor;++ const sessionRef = useRef<{+ drawing: boolean;+ pointerId: number;+ points: Point[];+ natSession: NaturalPaintStrokeSession | null;+ sampler: LayerPixelSampler | null;+ reservoir: PaintReservoir | null;+ remainderDist: number;+ dabCounter: { count: number };+ totalDist: number;+ }>({+ drawing: false,+ pointerId: -1,+ points: [],+ natSession: null,+ sampler: null,+ reservoir: null,+ remainderDist: 0,+ dabCounter: { count: 0 },+ totalDist: 0,+ });++ const clearScratchpad = useCallback(() => {+ const base = baseCanvasRef.current;+ const draft = draftCanvasRef.current;+ if (base) {+ const ctx = base.getContext('2d');+ ctx?.clearRect(0, 0, base.width, base.height);+ }+ if (draft) {+ const ctx = draft.getContext('2d');+ ctx?.clearRect(0, 0, draft.width, draft.height);+ }+ }, []);++ useEffect(() => {+ return () => {+ if (sessionRef.current.natSession) {+ sessionRef.current.natSession.finishAndDispose();+ sessionRef.current.natSession = null;+ }+ };+ }, []);++ const toCanvasPoint = (e: React.PointerEvent<HTMLCanvasElement>): Point => {+ const canvas = draftCanvasRef.current!;+ const rect = canvas.getBoundingClientRect();+ const scaleX = canvas.width / Math.max(1, rect.width);+ const scaleY = canvas.height / Math.max(1, rect.height);+ const x = (e.clientX - rect.left) * scaleX;+ const y = (e.clientY - rect.top) * scaleY;+ const pressure =+ e.pointerType === 'mouse' ? 0.72 : Math.max(0.05, Math.min(1, e.pressure || 0.5));+ const minFactor = brushSettings.minSizeFactor ?? 0.25;+ const baseSize = Math.min(110, Math.max(2, brushSettings.size || 24));+ const width =+ brushSettings.usePressure !== false+ ? baseSize * (minFactor + (1 - minFactor) * pressure)+ : baseSize;+ return {+ x,+ y,+ pressure,+ width,+ tiltX: e.tiltX ?? 0,+ tiltY: e.tiltY ?? 0,+ twist: e.twist ?? 0,+ timestamp: e.timeStamp,+ };+ };++ const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {+ if (e.button !== 0) return;+ e.preventDefault();+ const base = baseCanvasRef.current;+ const draft = draftCanvasRef.current;+ if (!base || !draft) return;+ const dCtx = draft.getContext('2d');+ if (!dCtx) return;++ draft.setPointerCapture(e.pointerId);+ dCtx.clearRect(0, 0, draft.width, draft.height);++ const pt = toCanvasPoint(e);+ const s = sessionRef.current;+ s.drawing = true;+ s.pointerId = e.pointerId;+ s.points = [pt];+ s.remainderDist = 0;+ s.dabCounter.count = 0;+ s.totalDist = 0;++ const naturalMode = isNaturalPaintBrush(brushSettings);+ const needsSampler = Boolean(+ brushSettings.colorMixing !== false &&+ (brushSettings.colorMixing || (naturalMode && brushSettings.naturalPaint?.spatialMixing))+ );+ s.sampler = needsSampler ? new LayerPixelSampler(base) : null;+ s.reservoir = brushSettings.colorMixing ? new PaintReservoir(activeColor) : null;++ if (naturalMode) {+ strokeSeedRef.current = (strokeSeedRef.current + 7919) & 0x7fffffff;+ const previewBs: BrushSettings = {+ ...brushSettings,+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),+ };+ s.natSession = new NaturalPaintStrokeSession(+ previewBs,+ activeColor,+ undefined,+ strokeSeedRef.current+ );+ s.natSession.stampInitialPoint(dCtx, pt, s.sampler || undefined, true);+ } else {+ s.natSession = null;+ const opts = buildBrushRenderOptions(brushSettings, {+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),+ opacity: 1.0,+ underlyingCanvas: base,+ sampler: s.sampler || undefined,+ reservoir: s.reservoir || undefined,+ useGpu: false,+ });+ drawBrushDot(dCtx, pt, activeColor, opts);+ }+ };++ const handlePointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {+ const s = sessionRef.current;+ if (!s.drawing || e.pointerId !== s.pointerId) return;+ const base = baseCanvasRef.current;+ const draft = draftCanvasRef.current;+ if (!base || !draft) return;+ const dCtx = draft.getContext('2d');+ if (!dCtx) return;++ const pt = toCanvasPoint(e);+ const prev = s.points[s.points.length - 1];+ const dist = Math.hypot(pt.x - prev.x, pt.y - prev.y);+ if (dist < 1.2) return;++ s.points.push(pt);+ const len = s.points.length;+ const p0 = s.points[Math.max(0, len - 3)];+ const p1 = s.points[len - 2];+ const p2 = s.points[len - 1];+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p1, p2, p2);++ if (s.natSession) {+ s.natSession.drawCubicSegment(dCtx, p1, c1, c2, p2, s.sampler || undefined, true);+ } else {+ const opts = buildBrushRenderOptions(brushSettings, {+ size: Math.min(110, Math.max(2, brushSettings.size || 24)),+ opacity: 1.0,+ underlyingCanvas: base,+ sampler: s.sampler || undefined,+ reservoir: s.reservoir || undefined,+ currentStrokeDist: s.totalDist,+ useGpu: false,+ });+ s.remainderDist = drawBrushCubicBezierSegment(+ dCtx,+ p1,+ c1,+ c2,+ p2,+ activeColor,+ opts,+ s.remainderDist,+ s.dabCounter+ );+ }+ s.totalDist += dist;+ };++ const finishStroke = (e?: React.PointerEvent<HTMLCanvasElement>) => {+ const s = sessionRef.current;+ if (!s.drawing) return;+ s.drawing = false;++ const base = baseCanvasRef.current;+ const draft = draftCanvasRef.current;+ if (draft && e) {+ try {+ draft.releasePointerCapture(e.pointerId);+ } catch {+ // ignore+ }+ }++ if (base && draft) {+ const bCtx = base.getContext('2d');+ const dCtx = draft.getContext('2d');+ if (bCtx && dCtx) {+ if (s.natSession) {+ s.natSession.flushPendingTapIfNeeded(s.sampler || undefined);+ const tapBounds = s.natSession.getDirtyBounds();+ if (tapBounds && s.points.length <= 1) {+ s.natSession.flushDirtyRectToContext(dCtx, tapBounds, true, 1.0, 'source-over');+ }+ }+ bCtx.save();+ bCtx.globalAlpha = Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0));+ bCtx.drawImage(draft, 0, 0);+ bCtx.restore();+ dCtx.clearRect(0, 0, draft.width, draft.height);+ }+ }++ if (s.natSession) {+ s.natSession.finishAndDispose();+ s.natSession = null;+ }+ s.sampler = null;+ s.reservoir = null;+ s.points = [];+ };++ return (+ <div className="flex flex-col h-full bg-[#161616] border-r border-white/[0.08]">+ {/* Scratchpad Toolbar */}+ <div className="px-2.5 py-2 border-b border-white/[0.08] flex items-center justify-between gap-2 bg-[#1c1c1c]">+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={() => setUseActiveColor(true)}+ title="Use active foreground color"+ className={`w-5 h-5 rounded-full border cursor-pointer transition-transform ${+ useActiveColor ? 'border-white scale-110 ring-1 ring-[var(--accent)]' : 'border-white/30'+ }`}+ style={{ backgroundColor: brushSettings.color || '#1d4ed8' }}+ />+ <div className="w-px h-3.5 bg-white/10 mx-0.5" />+ {QUICK_SWATCHES.map((sw) => {+ const selected = !useActiveColor && testColor === sw.hex;+ return (+ <button+ key={sw.hex}+ type="button"+ onClick={() => {+ setUseActiveColor(false);+ setTestColor(sw.hex);+ }}+ title={`Test color: ${sw.label}`}+ className={`w-4 h-4 rounded-full border cursor-pointer transition-transform ${+ selected ? 'border-white scale-110 ring-1 ring-[var(--accent)]' : 'border-white/20 hover:scale-105'+ }`}+ style={{ backgroundColor: sw.hex }}+ />+ );+ })}+ </div>++ <div className="flex items-center gap-1">+ <div className="flex items-center bg-[#141414] rounded p-0.5 border border-white/[0.06]">+ <button+ type="button"+ onClick={() => setBgMode('white')}+ title="White Canvas"+ className={`p-1 rounded cursor-pointer ${+ bgMode === 'white' ? 'bg-[#2c2c2c] text-white' : 'text-[#8a8a8a] hover:text-white'+ }`}+ >+ <Sun className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => setBgMode('gray')}+ title="Neutral Gray"+ className={`p-1 rounded cursor-pointer ${+ bgMode === 'gray' ? 'bg-[#2c2c2c] text-white' : 'text-[#8a8a8a] hover:text-white'+ }`}+ >+ <Square className="w-3 h-3" />+ </button>+ <button+ type="button"+ onClick={() => setBgMode('dark')}+ title="Dark Canvas"+ className={`p-1 rounded cursor-pointer ${+ bgMode === 'dark' ? 'bg-[#2c2c2c] text-white' : 'text-[#8a8a8a] hover:text-white'+ }`}+ >+ <Moon className="w-3 h-3" />+ </button>+ </div>++ {brushSettings.naturalPaint?.autoClean === false && (+ <button+ type="button"+ onClick={() => cleanDirtyBrush(brushSettings.preset)}+ title="Wash dirty pigment off bristles"+ className="px-1.5 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-sky-300 flex items-center gap-1 cursor-pointer"+ >+ <Droplets className="w-3 h-3" />+ <span>Clean</span>+ </button>+ )}++ <button+ type="button"+ onClick={clearScratchpad}+ title="Clear Scratchpad"+ className="px-1.5 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#d4d4d4] flex items-center gap-1 cursor-pointer"+ >+ <Eraser className="w-3 h-3" />+ <span>Clear</span>+ </button>+ </div>+ </div>++ {/* Interactive Dual-Canvas Live Painting Surface */}+ <div+ className="relative flex-1 overflow-hidden select-none touch-none"+ style={{ backgroundColor: BG_COLORS[bgMode] }}+ >+ <canvas+ ref={baseCanvasRef}+ width={560}+ height={440}+ className="absolute inset-0 w-full h-full pointer-events-none"+ />+ <canvas+ ref={draftCanvasRef}+ width={560}+ height={440}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={finishStroke}+ onPointerCancel={finishStroke}+ style={{ opacity: Math.max(0.01, Math.min(1, brushSettings.opacity ?? 1.0)) }}+ className="absolute inset-0 w-full h-full cursor-crosshair"+ />+ <div className="absolute bottom-2 left-2.5 right-2.5 flex items-center justify-between pointer-events-none">+ <span className="text-[10px] px-2 py-0.5 rounded bg-black/45 text-white/80 backdrop-blur-sm">+ Live Scratchpad — Draw & overlap colors to test mixing & impasto+ </span>+ <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-black/45 text-white/80">+ {Math.round(brushSettings.size)}px+ </span>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/brushStudio/BrushStudioTabsPrimary.tsx b/src/components/brushStudio/BrushStudioTabsPrimary.tsxnew file mode 100644index 0000000..0df28f1--- /dev/null+++ b/src/components/brushStudio/BrushStudioTabsPrimary.tsx@@ -0,0 +1,852 @@+import React, { useMemo, useRef } from 'react';+import { Upload, Trash2, Plus } from 'lucide-react';+import type {+ BristleProfilePreset,+ BristleSettings,+ BrushRenderMode,+ BrushSettings,+ CspAngleDynamicsMode,+ CspPaperTextureMode,+ CspTaperSettings,+ CspTipFlipMode,+ GrainMappingMode,+ SurfaceTextureId,+} from '../../types/editor';+import {+ DEFAULT_BRISTLE_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+} from '../../types/editor';+import {+ generateNaturalTipByProfile,+ getSurfaceTextureDataUrl,+ SURFACE_TEXTURE_CATALOG,+} from '../../utils/proceduralBrushTips';+import { getPreloadedBuiltinTipImage } from '../../utils/presetBrushes';+import { PressureCurveEditor } from '../PressureCurveEditor';+import {+ readImageFileAsDataUrl,+ StudioSegmented,+ StudioSlider,+ StudioToggle,+} from './BrushStudioControls';++export interface BrushStudioTabProps {+ bs: BrushSettings;+ onPatch: (patch: Partial<BrushSettings>) => void;+}++const DEFAULT_TAPER: CspTaperSettings = {+ useIn: false,+ inLength: 24,+ inRatio: 0.9,+ useOut: false,+ outLength: 32,+ outRatio: 0.9,+ startingSharpness: 0.8,+ endingSharpness: 0.8,+ affectSize: true,+ affectDensity: false,+ affectOpacity: false,+ affectLoad: true,+};++export const ShapeBristlesTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const tipInputRef = useRef<HTMLInputElement>(null);+ const subTipInputRef = useRef<HTMLInputElement>(null);+ const bristle: BristleSettings = { ...DEFAULT_BRISTLE_SETTINGS, ...(bs.bristle || {}) };+ const renderMode: BrushRenderMode = bs.renderMode ?? 'stamp';++ const patchBristle = (p: Partial<BristleSettings>) => {+ onPatch({ bristle: { ...bristle, ...p } });+ };++ const applyProfilePreset = (profile: BristleProfilePreset) => {+ if (profile === 'custom') {+ patchBristle({ profile: 'custom' });+ return;+ }+ const url = generateNaturalTipByProfile(profile);+ const img = url ? getPreloadedBuiltinTipImage(url) : undefined;+ onPatch({+ bristle: { ...bristle, profile },+ customTipDataUrl: url || bs.customTipDataUrl,+ customTipImage: img || bs.customTipImage,+ });+ };++ const handleUploadTip = async (file: File) => {+ try {+ const res = await readImageFileAsDataUrl(file);+ onPatch({+ customTipDataUrl: res.dataUrl,+ customTipImage: res.image,+ bristle: { ...bristle, profile: 'custom' },+ });+ } catch {+ // ignore invalid image+ }+ };++ const handleAddSubTip = async (file: File) => {+ try {+ const res = await readImageFileAsDataUrl(file);+ const nextSubs = [+ ...(bs.subTips || []),+ { dataUrl: res.dataUrl, width: res.width, height: res.height, isColor: false },+ ].slice(0, 16);+ const nextImgs = [...(bs.subTipImages || []), res.image].slice(0, 16);+ onPatch({+ subTips: nextSubs,+ subTipImages: nextImgs,+ customTipDataUrl: bs.customTipDataUrl || res.dataUrl,+ customTipImage: bs.customTipImage || res.image,+ });+ } catch {+ // ignore+ }+ };++ const removeSubTip = (idx: number) => {+ const nextSubs = (bs.subTips || []).filter((_, i) => i !== idx);+ const nextImgs = (bs.subTipImages || []).filter((_, i) => i !== idx);+ onPatch({+ subTips: nextSubs.length > 0 ? nextSubs : undefined,+ subTipImages: nextImgs.length > 0 ? nextImgs : undefined,+ });+ };++ return (+ <div className="space-y-4">+ <StudioSegmented<BrushRenderMode>+ label="Render Mode"+ value={renderMode}+ options={[+ { id: 'stamp', label: 'Stamp' },+ { id: 'bristle-ribbon', label: 'Bristle Ribbon' },+ { id: 'bristle-hybrid', label: 'Bristle Hybrid' },+ ]}+ onChange={(mode) =>+ onPatch({+ renderMode: mode,+ naturalPaint:+ mode !== 'stamp'+ ? { ...DEFAULT_NATURAL_PAINT_SETTINGS, ...(bs.naturalPaint || {}), enabled: true }+ : bs.naturalPaint,+ })+ }+ />++ <StudioSegmented<BristleProfilePreset>+ label="Brush Tip Profile"+ value={bristle.profile}+ options={[+ { id: 'round', label: 'Round' },+ { id: 'flat', label: 'Flat' },+ { id: 'filbert', label: 'Filbert' },+ { id: 'fan', label: 'Fan' },+ { id: 'rake', label: 'Rake' },+ { id: 'knife', label: 'Knife' },+ { id: 'custom', label: 'Custom' },+ ]}+ onChange={applyProfilePreset}+ />++ {/* Primary Tip Preview & Upload */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] flex items-center gap-3">+ <div className="w-12 h-12 rounded bg-[#0f0f0f] border border-white/10 flex items-center justify-center overflow-hidden shrink-0">+ {bs.customTipDataUrl ? (+ <img src={bs.customTipDataUrl} alt="Tip" className="w-10 h-10 object-contain" />+ ) : (+ <div className="w-7 h-7 rounded-full bg-white/80" />+ )}+ </div>+ <div className="flex-1 min-w-0 space-y-1.5">+ <div className="text-[11px] text-[#e5e5e5] font-medium">Primary Tip Shape</div>+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={() => tipInputRef.current?.click()}+ className="px-2 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] flex items-center gap-1 cursor-pointer"+ >+ <Upload className="w-3 h-3" />+ <span>Upload PNG</span>+ </button>+ {bs.customTipDataUrl && (+ <button+ type="button"+ onClick={() => onPatch({ customTipDataUrl: undefined, customTipImage: undefined })}+ className="px-2 py-1 rounded bg-[#242424] hover:bg-red-500/20 text-[10px] text-[#a3a3a3] hover:text-red-300 cursor-pointer"+ >+ Clear+ </button>+ )}+ </div>+ </div>+ <input+ ref={tipInputRef}+ type="file"+ accept="image/png,image/webp,image/jpeg"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) handleUploadTip(f);+ e.target.value = '';+ }}+ />+ </div>++ {/* Multi-Tip List */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-medium text-[#e5e5e5]">+ Multi-Tip Atlas ({bs.subTips?.length ?? 0})+ </span>+ <button+ type="button"+ onClick={() => subTipInputRef.current?.click()}+ className="px-2 py-0.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] flex items-center gap-1 cursor-pointer"+ >+ <Plus className="w-3 h-3" />+ <span>Add Tip</span>+ </button>+ <input+ ref={subTipInputRef}+ type="file"+ accept="image/png,image/webp,image/jpeg"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) handleAddSubTip(f);+ e.target.value = '';+ }}+ />+ </div>+ {bs.subTips && bs.subTips.length > 0 && (+ <>+ <div className="flex flex-wrap gap-1.5">+ {bs.subTips.map((st, idx) => (+ <div+ key={idx}+ className="relative group w-9 h-9 rounded bg-[#0f0f0f] border border-white/10 flex items-center justify-center overflow-hidden"+ >+ <img src={st.dataUrl} alt="" className="w-7 h-7 object-contain" />+ <button+ type="button"+ onClick={() => removeSubTip(idx)}+ className="absolute inset-0 bg-black/70 opacity-0 group-hover:opacity-100 flex items-center justify-center text-red-400 cursor-pointer"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ </div>+ ))}+ </div>+ <StudioSegmented<'random' | 'sequential' | 'direction' | 'reverse'>+ label="Sub-Tip Order"+ value={bs.subTipOrder ?? 'sequential'}+ options={[+ { id: 'sequential', label: 'Sequential' },+ { id: 'random', label: 'Random' },+ { id: 'direction', label: 'Direction' },+ { id: 'reverse', label: 'Reverse' },+ ]}+ onChange={(order) => onPatch({ subTipOrder: order })}+ />+ </>+ )}+ </div>++ {/* Procedural Bristle Parameters */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Procedural Bristle Architecture</div>+ <StudioSlider+ label="Bristle Count"+ value={bristle.count}+ min={4}+ max={64}+ valueLabel={`${bristle.count} strands`}+ onChange={(v) => patchBristle({ count: v })}+ />+ <StudioSlider+ label="Bristle Clumping"+ value={Math.round(bristle.clumping * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(bristle.clumping * 100)}%`}+ onChange={(v) => patchBristle({ clumping: v / 100 })}+ />+ <StudioSlider+ label="Stiffness"+ value={Math.round(bristle.stiffness * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(bristle.stiffness * 100)}%`}+ onChange={(v) => patchBristle({ stiffness: v / 100 })}+ />+ <StudioSlider+ label="Pressure / Tilt Splay"+ value={Math.round(bristle.splay * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(bristle.splay * 100)}%`}+ onChange={(v) => patchBristle({ splay: v / 100 })}+ />+ <StudioSlider+ label="Strand Irregularity"+ value={Math.round(bristle.irregularity * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(bristle.irregularity * 100)}%`}+ onChange={(v) => patchBristle({ irregularity: v / 100 })}+ />+ <StudioSlider+ label="Edge Ridge Buildup"+ value={Math.round((bristle.edgeRidge ?? 0.2) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bristle.edgeRidge ?? 0.2) * 100)}%`}+ onChange={(v) => patchBristle({ edgeRidge: v / 100 })}+ />+ </div>++ {/* Geometry & Orientation */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Tip Geometry</div>+ <StudioSlider+ label="Hardness"+ value={Math.round((bs.hardness ?? 0.9) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bs.hardness ?? 0.9) * 100)}%`}+ onChange={(v) => onPatch({ hardness: v / 100 })}+ />+ <StudioSlider+ label="Thickness (Aspect)"+ value={Math.round((bs.thickness ?? 1.0) * 100)}+ min={5}+ max={100}+ valueLabel={`${Math.round((bs.thickness ?? 1.0) * 100)}%`}+ onChange={(v) => onPatch({ thickness: v / 100 })}+ />+ <StudioSlider+ label="Tip Angle"+ value={Math.round(bs.customTipAngle ?? 0)}+ min={-180}+ max={180}+ valueLabel={`${Math.round(bs.customTipAngle ?? 0)}°`}+ onChange={(v) => onPatch({ customTipAngle: v })}+ />+ <StudioSegmented<CspAngleDynamicsMode>+ label="Angle Dynamics"+ value={bs.customTipAngleDynamics ?? 'none'}+ options={[+ { id: 'none', label: 'Fixed' },+ { id: 'direction', label: 'Stroke' },+ { id: 'tilt', label: 'Tilt' },+ { id: 'twist', label: 'Twist' },+ { id: 'random', label: 'Random' },+ ]}+ onChange={(v) => onPatch({ customTipAngleDynamics: v })}+ />+ <div className="grid grid-cols-2 gap-2">+ <StudioSegmented<CspTipFlipMode>+ label="Flip Horizontal"+ value={bs.flipH ?? 'none'}+ options={[+ { id: 'none', label: 'Off' },+ { id: 'alternate', label: 'Alt' },+ { id: 'random', label: 'Rand' },+ ]}+ onChange={(v) => onPatch({ flipH: v })}+ />+ <StudioSegmented<CspTipFlipMode>+ label="Flip Vertical"+ value={bs.flipV ?? 'none'}+ options={[+ { id: 'none', label: 'Off' },+ { id: 'alternate', label: 'Alt' },+ { id: 'random', label: 'Rand' },+ ]}+ onChange={(v) => onPatch({ flipV: v })}+ />+ </div>+ </div>+ </div>+ );+};++export const StrokeTaperTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const taper: CspTaperSettings = { ...DEFAULT_TAPER, ...(bs.taper || {}) };+ const patchTaper = (p: Partial<CspTaperSettings>) => onPatch({ taper: { ...taper, ...p } });++ return (+ <div className="space-y-4">+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Stroke Path & Smoothing</div>+ <StudioSlider+ label="Spacing"+ value={Math.round((bs.spacing ?? 0.06) * 100)}+ min={2}+ max={100}+ valueLabel={`${Math.round((bs.spacing ?? 0.06) * 100)}%`}+ onChange={(v) => onPatch({ spacing: v / 100 })}+ />+ <StudioSlider+ label="Streamline / Stabilization"+ value={Math.round(bs.stabilization ?? 10)}+ min={0}+ max={50}+ valueLabel={`${Math.round(bs.stabilization ?? 10)}`}+ onChange={(v) => onPatch({ stabilization: v })}+ />+ <StudioSlider+ label="Post-Correction"+ value={Math.round(bs.postCorrection ?? 0)}+ min={0}+ max={5}+ valueLabel={`${Math.round(bs.postCorrection ?? 0)}`}+ onChange={(v) => onPatch({ postCorrection: v })}+ />+ <StudioToggle+ label="Sharp Angles"+ description="Preserve crisp corners instead of rounding"+ checked={bs.sharpCorners !== false}+ onChange={(v) => onPatch({ sharpCorners: v })}+ />+ </div>++ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Taper In & Taper Out</div>+ <StudioToggle+ label="Enable Taper In"+ checked={Boolean(taper.useIn)}+ onChange={(v) => patchTaper({ useIn: v })}+ />+ {taper.useIn && (+ <>+ <StudioSlider+ label="Taper In Length"+ value={Math.round(taper.inLength)}+ min={4}+ max={200}+ valueLabel={`${Math.round(taper.inLength)}px`}+ onChange={(v) => patchTaper({ inLength: v })}+ />+ <StudioSlider+ label="Start Sharpness"+ value={Math.round((taper.startingSharpness ?? 0.8) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((taper.startingSharpness ?? 0.8) * 100)}%`}+ onChange={(v) => patchTaper({ startingSharpness: v / 100 })}+ />+ </>+ )}++ <StudioToggle+ label="Enable Taper Out"+ checked={Boolean(taper.useOut)}+ onChange={(v) => patchTaper({ useOut: v })}+ />+ {taper.useOut && (+ <>+ <StudioSlider+ label="Taper Out Length"+ value={Math.round(taper.outLength)}+ min={4}+ max={250}+ valueLabel={`${Math.round(taper.outLength)}px`}+ onChange={(v) => patchTaper({ outLength: v })}+ />+ <StudioSlider+ label="End Sharpness"+ value={Math.round((taper.endingSharpness ?? 0.8) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((taper.endingSharpness ?? 0.8) * 100)}%`}+ onChange={(v) => patchTaper({ endingSharpness: v / 100 })}+ />+ </>+ )}++ <div className="pt-1 border-t border-white/[0.06] space-y-1">+ <StudioToggle+ label="Affect Size"+ checked={taper.affectSize !== false}+ onChange={(v) => patchTaper({ affectSize: v })}+ />+ <StudioToggle+ label="Affect Density / Opacity"+ checked={Boolean(taper.affectDensity || taper.affectOpacity)}+ onChange={(v) => patchTaper({ affectDensity: v, affectOpacity: v })}+ />+ <StudioToggle+ label="Affect Paint Load (Dry Tail)"+ checked={taper.affectLoad !== false}+ onChange={(v) => patchTaper({ affectLoad: v })}+ />+ </div>+ </div>+ </div>+ );+};++export const TextureGrainTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const texInputRef = useRef<HTMLInputElement>(null);+ const natural = { ...DEFAULT_NATURAL_PAINT_SETTINGS, ...(bs.naturalPaint || {}) };++ const thumbnails = useMemo(+ () =>+ SURFACE_TEXTURE_CATALOG.map((meta) => ({+ ...meta,+ url: getSurfaceTextureDataUrl(meta.id),+ })),+ []+ );++ const selectBuiltinTexture = (id: SurfaceTextureId) => {+ const url = getSurfaceTextureDataUrl(id);+ const img = url ? getPreloadedBuiltinTipImage(url) : undefined;+ onPatch({+ surfaceTextureId: id,+ paperTexture: url || undefined,+ paperTextureImage: img,+ grain: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.35),+ textureDensity: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.35),+ });+ };++ const handleUploadTexture = async (file: File) => {+ try {+ const res = await readImageFileAsDataUrl(file);+ onPatch({+ paperTexture: res.dataUrl,+ paperTextureImage: res.image,+ grain: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.45),+ textureDensity: Math.max(bs.grain ?? bs.textureDensity ?? 0, 0.45),+ });+ } catch {+ // ignore+ }+ };++ return (+ <div className="space-y-4">+ {/* Built-in 512x512 Seamless Surface Texture Gallery */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2">+ <div className="flex items-center justify-between">+ <span className="text-[11px] font-medium text-[#e5e5e5]">Surface Texture Library (512×512)</span>+ <button+ type="button"+ onClick={() => texInputRef.current?.click()}+ className="px-2 py-0.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] flex items-center gap-1 cursor-pointer"+ >+ <Upload className="w-3 h-3" />+ <span>Import PNG/WebP</span>+ </button>+ <input+ ref={texInputRef}+ type="file"+ accept="image/png,image/webp,image/jpeg"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) handleUploadTexture(f);+ e.target.value = '';+ }}+ />+ </div>++ <div className="grid grid-cols-4 gap-1.5">+ {thumbnails.map((tex) => {+ const active = bs.surfaceTextureId === tex.id;+ return (+ <button+ key={tex.id}+ type="button"+ onClick={() => selectBuiltinTexture(tex.id)}+ title={tex.desc}+ className={`p-1 rounded border text-left transition-colors cursor-pointer ${+ active+ ? 'border-[var(--accent)] bg-[#2c2c2c]'+ : 'border-white/[0.08] bg-[#121212] hover:border-white/25'+ }`}+ >+ <div className="w-full aspect-square rounded overflow-hidden bg-[#1e1e1e] mb-1">+ {tex.url && (+ <img src={tex.url} alt={tex.label} className="w-full h-full object-cover" />+ )}+ </div>+ <div className="text-[9px] text-[#e5e5e5] truncate">{tex.label}</div>+ </button>+ );+ })}+ </div>+ </div>++ <StudioSegmented<GrainMappingMode>+ label="Spatial Grain Mapping"+ value={bs.grainMappingMode ?? 'canvas-locked'}+ options={[+ { id: 'canvas-locked', label: 'Canvas-Locked' },+ { id: 'brush-aligned', label: 'Brush-Aligned' },+ { id: 'stroke-flow', label: 'Stroke-Flow' },+ { id: 'random-per-stroke', label: 'Random' },+ ]}+ onChange={(m) => onPatch({ grainMappingMode: m })}+ />++ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <StudioSlider+ label="Grain Depth / Intensity"+ value={Math.round((bs.grain ?? bs.textureDensity ?? 0) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bs.grain ?? bs.textureDensity ?? 0) * 100)}%`}+ onChange={(v) => onPatch({ grain: v / 100, textureDensity: v / 100 })}+ />+ <StudioSlider+ label="Dry-Brush Valley Cutoff"+ value={Math.round(natural.dryBrush * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(natural.dryBrush * 100)}%`}+ onChange={(v) => onPatch({ naturalPaint: { ...natural, dryBrush: v / 100 } })}+ />+ <StudioSlider+ label="Scale"+ value={Math.round((bs.paperTextureScale ?? 1.0) * 100)}+ min={20}+ max={300}+ valueLabel={`${Math.round((bs.paperTextureScale ?? 1.0) * 100)}%`}+ onChange={(v) => onPatch({ paperTextureScale: v / 100 })}+ />+ <StudioSlider+ label="Rotation"+ value={Math.round(bs.paperTextureRotate ?? 0)}+ min={-180}+ max={180}+ valueLabel={`${Math.round(bs.paperTextureRotate ?? 0)}°`}+ onChange={(v) => onPatch({ paperTextureRotate: v })}+ />+ <StudioSlider+ label="Contrast"+ value={Math.round(bs.paperTextureContrast ?? 0)}+ min={-80}+ max={80}+ valueLabel={`${Math.round(bs.paperTextureContrast ?? 0)}`}+ onChange={(v) => onPatch({ paperTextureContrast: v })}+ />+ <StudioSlider+ label="Brightness"+ value={Math.round(bs.paperTextureBrightness ?? 0)}+ min={-50}+ max={50}+ valueLabel={`${Math.round(bs.paperTextureBrightness ?? 0)}`}+ onChange={(v) => onPatch({ paperTextureBrightness: v })}+ />+ <StudioSegmented<CspPaperTextureMode>+ label="Texture Blend Mode"+ value={bs.paperTextureMode ?? 'compare'}+ options={[+ { id: 'compare', label: 'Compare' },+ { id: 'multiply', label: 'Multiply' },+ { id: 'subtract', label: 'Subtract' },+ { id: 'overlay', label: 'Overlay' },+ { id: 'outline', label: 'Outline' },+ ]}+ onChange={(v) => onPatch({ paperTextureMode: v })}+ />+ <StudioToggle+ label="Invert Texture"+ checked={Boolean(bs.paperTextureInverted)}+ onChange={(v) => onPatch({ paperTextureInverted: v })}+ />+ </div>++ {/* Dual Grain Secondary Surface */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Secondary Dual Grain</div>+ <select+ value={bs.dualSurfaceTextureId || ''}+ onChange={(e) =>+ onPatch({+ dualSurfaceTextureId: (e.target.value || undefined) as SurfaceTextureId | undefined,+ })+ }+ className="w-full px-2 py-1 rounded bg-[#121212] border border-white/10 text-[11px] text-[#e5e5e5]"+ >+ <option value="">None</option>+ {SURFACE_TEXTURE_CATALOG.map((t) => (+ <option key={t.id} value={t.id}>+ {t.label}+ </option>+ ))}+ </select>+ {bs.dualSurfaceTextureId && (+ <StudioSlider+ label="Dual Grain Depth"+ value={Math.round((bs.dualGrainDepth ?? 0.35) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bs.dualGrainDepth ?? 0.35) * 100)}%`}+ onChange={(v) => onPatch({ dualGrainDepth: v / 100 })}+ />+ )}+ </div>++ {/* Pressure-to-Penetration Curve */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Pressure-to-Valley Penetration Curve</div>+ <PressureCurveEditor+ value={{+ enabled: true,+ preset: 'custom',+ points: natural.penetrationCurve ?? [+ [0, 0],+ [1, 1],+ ],+ }}+ onChange={(next) =>+ onPatch({+ naturalPaint: {+ ...natural,+ penetrationCurve: next.points,+ },+ })+ }+ />+ </div>+ </div>+ );+};++export const DualBrushTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const dualInputRef = useRef<HTMLInputElement>(null);++ const handleUploadDualTip = async (file: File) => {+ try {+ const res = await readImageFileAsDataUrl(file);+ onPatch({+ dualBrush: true,+ dualTipDataUrl: res.dataUrl,+ dualTipImage: res.image,+ });+ } catch {+ // ignore+ }+ };++ return (+ <div className="space-y-4">+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-3">+ <StudioToggle+ label="Enable Dual Brush Compositing"+ description="Modulate primary tip with a secondary tip shape"+ checked={Boolean(bs.dualBrush)}+ onChange={(v) => onPatch({ dualBrush: v })}+ />++ {bs.dualBrush && (+ <>+ <div className="flex items-center gap-3 pt-1">+ <div className="w-12 h-12 rounded bg-[#0f0f0f] border border-white/10 flex items-center justify-center overflow-hidden shrink-0">+ {bs.dualTipDataUrl ? (+ <img src={bs.dualTipDataUrl} alt="Dual Tip" className="w-10 h-10 object-contain" />+ ) : (+ <span className="text-[9px] text-[#6e6e6e]">None</span>+ )}+ </div>+ <div className="space-y-1.5">+ <div className="flex items-center gap-1.5">+ <button+ type="button"+ onClick={() => dualInputRef.current?.click()}+ className="px-2 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] flex items-center gap-1 cursor-pointer"+ >+ <Upload className="w-3 h-3" />+ <span>Upload Secondary Tip</span>+ </button>+ <button+ type="button"+ onClick={() => {+ const url = generateNaturalTipByProfile('rake');+ const img = url ? getPreloadedBuiltinTipImage(url) : undefined;+ onPatch({ dualTipDataUrl: url, dualTipImage: img });+ }}+ className="px-2 py-1 rounded bg-[#242424] hover:bg-[#323232] text-[10px] text-[#cccccc] cursor-pointer"+ >+ Use Rake Tip+ </button>+ </div>+ </div>+ <input+ ref={dualInputRef}+ type="file"+ accept="image/png,image/webp,image/jpeg"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) handleUploadDualTip(f);+ e.target.value = '';+ }}+ />+ </div>++ <StudioSegmented<'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen'>+ label="Composite Blend Mode"+ value={+ ((bs.dualBrushCompositeMode as+ | 'multiply'+ | 'subtract'+ | 'darken'+ | 'overlay'+ | 'screen') || 'multiply')+ }+ options={[+ { id: 'multiply', label: 'Multiply' },+ { id: 'subtract', label: 'Subtract' },+ { id: 'darken', label: 'Darken' },+ { id: 'overlay', label: 'Overlay' },+ { id: 'screen', label: 'Screen' },+ ]}+ onChange={(v) => onPatch({ dualBrushCompositeMode: v })}+ />++ <StudioSlider+ label="Dual Scale"+ value={Math.round((bs.dualScale ?? 1.0) * 100)}+ min={20}+ max={300}+ valueLabel={`${Math.round((bs.dualScale ?? 1.0) * 100)}%`}+ onChange={(v) => onPatch({ dualScale: v / 100 })}+ />+ <StudioSlider+ label="Dual Angle"+ value={Math.round(bs.dualAngle ?? 0)}+ min={-180}+ max={180}+ valueLabel={`${Math.round(bs.dualAngle ?? 0)}°`}+ onChange={(v) => onPatch({ dualAngle: v })}+ />+ <StudioSlider+ label="Dual Scatter"+ value={Math.round((bs.dualScatter ?? 0) * 100)}+ min={0}+ max={200}+ valueLabel={`${Math.round((bs.dualScatter ?? 0) * 100)}%`}+ onChange={(v) => onPatch({ dualScatter: v / 100 })}+ />+ <StudioSlider+ label="Dual Spacing"+ value={Math.round((bs.dualSpacing ?? 0.1) * 100)}+ min={2}+ max={100}+ valueLabel={`${Math.round((bs.dualSpacing ?? 0.1) * 100)}%`}+ onChange={(v) => onPatch({ dualSpacing: v / 100 })}+ />+ </>+ )}+ </div>+ </div>+ );+};diff --git a/src/components/brushStudio/BrushStudioTabsSecondary.tsx b/src/components/brushStudio/BrushStudioTabsSecondary.tsxnew file mode 100644index 0000000..283331c--- /dev/null+++ b/src/components/brushStudio/BrushStudioTabsSecondary.tsx@@ -0,0 +1,630 @@+import React, { useState, useRef } from 'react';+import { Droplets, Download, Upload, RotateCcw, Copy, Save } from 'lucide-react';+import type {+ BrushCategory,+ BrushDynamics,+ BrushSettings,+ CspSensorConfig,+ ImpastoSettings,+ NaturalMixingMode,+ NaturalPaintSettings,+} from '../../types/editor';+import {+ DEFAULT_BRUSH_DYNAMICS,+ DEFAULT_IMPASTO_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+} from '../../types/editor';+import { cleanDirtyBrush } from '../../utils/colorMixingEngine';+import { LightSourceWidget } from '../LightSourceWidget';+import { PressureCurveEditor } from '../PressureCurveEditor';+import {+ StudioSegmented,+ StudioSlider,+ StudioToggle,+} from './BrushStudioControls';+import type { BrushStudioTabProps } from './BrushStudioTabsPrimary';++export const NaturalPaintMixingTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const np: NaturalPaintSettings = {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ ...(bs.naturalPaint || {}),+ };++ const patchNp = (p: Partial<NaturalPaintSettings>) => {+ onPatch({+ naturalPaint: { ...np, ...p },+ colorMixing: p.enabled !== undefined ? p.enabled : bs.colorMixing,+ });+ };++ return (+ <div className="space-y-4">+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <StudioToggle+ label="Enable Natural Paint & Wet Mixing"+ description="Physical per-bristle pigment mixing, load capacity & dry-brush"+ checked={Boolean(np.enabled || bs.colorMixing)}+ onChange={(v) =>+ onPatch({+ colorMixing: v,+ naturalPaint: { ...np, enabled: v },+ renderMode: v && (bs.renderMode ?? 'stamp') === 'stamp' ? 'bristle-ribbon' : bs.renderMode,+ })+ }+ />++ <StudioSegmented<NaturalMixingMode>+ label="Mixing Mode"+ value={bs.mixingMode ?? 'impasto_mix'}+ options={[+ { id: 'blend', label: 'Blend' },+ { id: 'running_color', label: 'Running' },+ { id: 'smear', label: 'Smear' },+ { id: 'impasto_mix', label: 'Impasto Mix' },+ ]}+ onChange={(m) => onPatch({ mixingMode: m })}+ />++ <StudioToggle+ label="Per-Bristle Spatial Mixing"+ description="Each bristle picks up & drags its own local canvas color streak"+ checked={np.spatialMixing}+ onChange={(v) => patchNp({ spatialMixing: v })}+ />+ </div>++ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Pigment & Reservoir Physics</div>+ <StudioSlider+ label="Kubelka-Munk Pigment Strength"+ value={Math.round(np.pigmentMixingStrength * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.pigmentMixingStrength * 100)}%`}+ onChange={(v) => patchNp({ pigmentMixingStrength: v / 100 })}+ />+ <StudioSlider+ label="Paint Load (0% = Pure Blender)"+ value={Math.round(np.paintLoad * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.paintLoad * 100)}%`}+ onChange={(v) =>+ onPatch({+ amountOfPaint: v / 100,+ naturalPaint: { ...np, paintLoad: v / 100 },+ })+ }+ />+ <StudioSlider+ label="Depletion Rate (Dry-Brush Exhaustion)"+ value={Math.round(np.depletionRate * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.depletionRate * 100)}%`}+ onChange={(v) => patchNp({ depletionRate: v / 100 })}+ />+ <StudioSlider+ label="Wetness / Canvas Pickup"+ value={Math.round(np.wetness * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.wetness * 100)}%`}+ onChange={(v) => patchNp({ wetness: v / 100 })}+ />+ <StudioSlider+ label="Viscosity (Mixing Resistance)"+ value={Math.round(np.viscosity * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.viscosity * 100)}%`}+ onChange={(v) => patchNp({ viscosity: v / 100 })}+ />+ <StudioSlider+ label="Color Stretch"+ value={Math.round((bs.colorStretch ?? 0.65) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bs.colorStretch ?? 0.65) * 100)}%`}+ onChange={(v) => onPatch({ colorStretch: v / 100 })}+ />+ <StudioSlider+ label="Charge per Pressure"+ value={Math.round(np.chargePerPressure * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(np.chargePerPressure * 100)}%`}+ onChange={(v) => patchNp({ chargePerPressure: v / 100 })}+ />++ <div className="pt-1 border-t border-white/[0.06] flex items-center justify-between gap-2">+ <div className="flex-1">+ <StudioToggle+ label="Auto-Clean Brush After Stroke"+ description="Off = dirty brush keeps picked-up pigment across strokes"+ checked={np.autoClean}+ onChange={(v) => patchNp({ autoClean: v })}+ />+ </div>+ {!np.autoClean && (+ <button+ type="button"+ onClick={() => cleanDirtyBrush(bs.preset)}+ className="px-2 py-1 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-sky-300 flex items-center gap-1 cursor-pointer shrink-0"+ >+ <Droplets className="w-3 h-3" />+ <span>Clean Now</span>+ </button>+ )}+ </div>+ </div>+ </div>+ );+};++export const ImpastoWetEdgeTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const imp: ImpastoSettings = { ...DEFAULT_IMPASTO_SETTINGS, ...(bs.impasto || {}) };+ const np: NaturalPaintSettings = {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ ...(bs.naturalPaint || {}),+ };++ const patchImp = (p: Partial<ImpastoSettings>) => {+ onPatch({ impasto: { ...imp, ...p } });+ };++ return (+ <div className="space-y-4">+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <StudioToggle+ label="Enable 3D Impasto Relief"+ description="Real-time paint heightmap with directional lighting & specular sheen"+ checked={imp.enabled}+ onChange={(v) => patchImp({ enabled: v })}+ />++ <StudioSlider+ label="Impasto Depth"+ value={Math.round(imp.depth * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(imp.depth * 100)}%`}+ onChange={(v) => patchImp({ depth: v / 100 })}+ />+ <StudioSlider+ label="Bristle Groove Relief"+ value={Math.round(imp.bristleRelief * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(imp.bristleRelief * 100)}%`}+ onChange={(v) => patchImp({ bristleRelief: v / 100 })}+ />+ <StudioSlider+ label="Gloss / Oil Sheen"+ value={Math.round(imp.gloss * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(imp.gloss * 100)}%`}+ onChange={(v) => patchImp({ gloss: v / 100 })}+ />+ <StudioSlider+ label="Relief Lighting Contrast"+ value={Math.round(imp.reliefContrast * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(imp.reliefContrast * 100)}%`}+ onChange={(v) => patchImp({ reliefContrast: v / 100 })}+ />+ </div>++ {/* Directional Light Gizmo (Reuses InkStudio LightSourceWidget) */}+ <div className="space-y-2">+ <LightSourceWidget+ embedded+ settings={{+ azimuth: imp.lightAzimuth,+ elevation: imp.lightElevation,+ intensity: 1.2,+ ambientIntensity: 0.7,+ color: '#ffffff',+ isBacklit: false,+ }}+ onChange={(next) =>+ patchImp({+ lightAzimuth: Math.max(0, Math.min(360, next.azimuth)),+ lightElevation: Math.max(5, Math.min(85, next.elevation)),+ })+ }+ onReset={() => patchImp({ lightAzimuth: 315, lightElevation: 42 })}+ />+ </div>++ {/* Watercolor Wet Edge & Paper-Valley Granulation */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Watercolor Wet Edge & Granulation</div>+ <StudioSlider+ label="Wet Edge Strength"+ value={Math.round((bs.wetEdge ?? 0) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((bs.wetEdge ?? 0) * 100)}%`}+ onChange={(v) => onPatch({ wetEdge: v / 100 })}+ />+ <StudioSlider+ label="Wet Edge Radius"+ value={Number((bs.wetEdgeRadius ?? 3.0).toFixed(1))}+ min={1}+ max={8}+ step={0.5}+ valueLabel={`${(bs.wetEdgeRadius ?? 3.0).toFixed(1)}px`}+ onChange={(v) => onPatch({ wetEdgeRadius: v })}+ />+ <StudioSlider+ label="Paper-Valley Granulation"+ value={Math.round((np.granulation ?? 0) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((np.granulation ?? 0) * 100)}%`}+ onChange={(v) => onPatch({ naturalPaint: { ...np, granulation: v / 100 } })}+ />+ </div>+ </div>+ );+};++type SensorTargetKey =+ | 'sizeSensor'+ | 'opacitySensor'+ | 'densitySensor'+ | 'bristleSplaySensor'+ | 'paintLoadSensor'+ | 'grainPenetrationSensor'+ | 'angleSensor'+ | 'scatterSensor';++const SENSOR_TARGETS: Array<{ key: SensorTargetKey; label: string }> = [+ { key: 'sizeSensor', label: 'Size' },+ { key: 'opacitySensor', label: 'Opacity' },+ { key: 'densitySensor', label: 'Flow / Density' },+ { key: 'bristleSplaySensor', label: 'Bristle Splay' },+ { key: 'paintLoadSensor', label: 'Paint Load' },+ { key: 'grainPenetrationSensor', label: 'Grain Penetration' },+ { key: 'angleSensor', label: 'Angle' },+ { key: 'scatterSensor', label: 'Scatter' },+];++export const DynamicsSensorMatrixTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const [selectedTarget, setSelectedTarget] = useState<SensorTargetKey>('sizeSensor');+ const dyn: BrushDynamics = { ...DEFAULT_BRUSH_DYNAMICS, ...(bs.dynamics || {}) };+ const sensor: CspSensorConfig = bs[selectedTarget] || {};++ const patchSensor = (p: Partial<CspSensorConfig>) => {+ onPatch({ [selectedTarget]: { ...sensor, ...p } } as Partial<BrushSettings>);+ };++ const patchDyn = (p: Partial<BrushDynamics>) => {+ onPatch({ dynamics: { ...dyn, ...p } });+ };++ return (+ <div className="space-y-4">+ {/* Unified Sensor Matrix Target Selector */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Sensor-to-Property Matrix</div>+ <div className="grid grid-cols-2 gap-1">+ {SENSOR_TARGETS.map((t) => {+ const cfg = bs[t.key];+ const activeCount = cfg+ ? [+ cfg.usePressure,+ cfg.useTilt,+ cfg.useBarrelTwist,+ cfg.useVelocity,+ cfg.useDistance,+ cfg.useRandom,+ ].filter(Boolean).length+ : 0;+ return (+ <button+ key={t.key}+ type="button"+ onClick={() => setSelectedTarget(t.key)}+ className={`px-2 py-1 rounded text-[10px] flex items-center justify-between cursor-pointer ${+ selectedTarget === t.key+ ? 'bg-[#2c2c2c] text-[#f5f5f5] border border-[var(--accent)]/60'+ : 'bg-[#121212] text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ <span>{t.label}</span>+ {activeCount > 0 && (+ <span className="px-1 rounded bg-[var(--accent)]/25 text-[9px] text-[#e5e5e5]">+ {activeCount}+ </span>+ )}+ </button>+ );+ })}+ </div>++ <div className="pt-2 border-t border-white/[0.06] space-y-2">+ <StudioToggle+ label="Stylus Pressure"+ checked={Boolean(sensor.usePressure)}+ onChange={(v) => patchSensor({ usePressure: v })}+ />+ {sensor.usePressure && (+ <StudioSlider+ label="Minimum at Zero Pressure"+ value={Math.round((sensor.pressureMin ?? 0) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((sensor.pressureMin ?? 0) * 100)}%`}+ onChange={(v) => patchSensor({ pressureMin: v / 100 })}+ />+ )}++ <StudioToggle+ label="Tilt Altitude"+ checked={Boolean(sensor.useTilt)}+ onChange={(v) => {+ patchSensor({ useTilt: v });+ if (v && !bs.useTilt) onPatch({ useTilt: true });+ }}+ />+ <StudioToggle+ label="Tilt Azimuth"+ checked={Boolean(sensor.useTiltAzimuth)}+ onChange={(v) => patchSensor({ useTiltAzimuth: v })}+ />+ <StudioToggle+ label="Barrel Twist"+ checked={Boolean(sensor.useBarrelTwist)}+ onChange={(v) => patchSensor({ useBarrelTwist: v })}+ />+ <StudioToggle+ label="Stroke Velocity"+ checked={Boolean(sensor.useVelocity)}+ onChange={(v) => patchSensor({ useVelocity: v })}+ />+ <StudioToggle+ label="Stroke Distance"+ checked={Boolean(sensor.useDistance)}+ onChange={(v) => patchSensor({ useDistance: v })}+ />+ <StudioToggle+ label="Random Variance"+ checked={Boolean(sensor.useRandom)}+ onChange={(v) => patchSensor({ useRandom: v })}+ />+ </div>++ <div className="pt-2 border-t border-white/[0.06]">+ <div className="text-[10px] text-[#8a8a8a] mb-1.5">Response Curve</div>+ <PressureCurveEditor+ value={{+ enabled: true,+ preset: 'custom',+ points: sensor.pressureCurve ?? bs.pressureCurve ?? [+ [0, 0],+ [1, 1],+ ],+ }}+ onChange={(next) => {+ patchSensor({ pressureCurve: next.points });+ if (selectedTarget === 'sizeSensor') {+ onPatch({ pressureCurve: next.points });+ }+ }}+ />+ </div>+ </div>++ {/* Jitter & Color Dynamics */}+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2.5">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Stamp & Color Jitter</div>+ <StudioSlider+ label="Size Jitter"+ value={Math.round(dyn.sizeJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.sizeJitter * 100)}%`}+ onChange={(v) => patchDyn({ sizeJitter: v / 100 })}+ />+ <StudioSlider+ label="Angle Jitter"+ value={Math.round(dyn.angleJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.angleJitter * 100)}%`}+ onChange={(v) => patchDyn({ angleJitter: v / 100 })}+ />+ <StudioSlider+ label="Scatter"+ value={Math.round(dyn.scatter * 100)}+ min={0}+ max={250}+ valueLabel={`${Math.round(dyn.scatter * 100)}%`}+ onChange={(v) => patchDyn({ scatter: v / 100 })}+ />+ <StudioToggle+ label="Enable Color Dynamics"+ checked={dyn.colorJitterEnabled}+ onChange={(v) => patchDyn({ colorJitterEnabled: v })}+ />+ {dyn.colorJitterEnabled && (+ <>+ <StudioSlider+ label="Hue Jitter"+ value={Math.round(dyn.hueJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.hueJitter * 100)}%`}+ onChange={(v) => patchDyn({ hueJitter: v / 100 })}+ />+ <StudioSlider+ label="Saturation Jitter"+ value={Math.round(dyn.saturationJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.saturationJitter * 100)}%`}+ onChange={(v) => patchDyn({ saturationJitter: v / 100 })}+ />+ <StudioSlider+ label="Lightness Jitter"+ value={Math.round(dyn.brightnessJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.brightnessJitter * 100)}%`}+ onChange={(v) => patchDyn({ brightnessJitter: v / 100 })}+ />+ <StudioSlider+ label="Temperature (Warm / Cool) Jitter"+ value={Math.round((dyn.temperatureJitter ?? 0) * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round((dyn.temperatureJitter ?? 0) * 100)}%`}+ onChange={(v) => patchDyn({ temperatureJitter: v / 100 })}+ />+ <StudioSlider+ label="Foreground / Background Mix"+ value={Math.round(dyn.foregroundBackgroundJitter * 100)}+ min={0}+ max={100}+ valueLabel={`${Math.round(dyn.foregroundBackgroundJitter * 100)}%`}+ onChange={(v) => patchDyn({ foregroundBackgroundJitter: v / 100 })}+ />+ </>+ )}+ </div>+ </div>+ );+};++export interface AboutPresetsTabProps extends BrushStudioTabProps {+ brushName: string;+ onBrushNameChange: (name: string) => void;+ category: BrushCategory | 'custom';+ onCategoryChange: (cat: BrushCategory | 'custom') => void;+ description: string;+ onDescriptionChange: (desc: string) => void;+ onResetDefault: () => void;+ onSaveAsNewPreset: () => void;+ onDuplicateBrush: () => void;+ onExportInkb: () => void;+ onImportInkb: (file: File) => void;+}++export const AboutPresetsTab: React.FC<AboutPresetsTabProps> = ({+ brushName,+ onBrushNameChange,+ category,+ onCategoryChange,+ description,+ onDescriptionChange,+ onResetDefault,+ onSaveAsNewPreset,+ onDuplicateBrush,+ onExportInkb,+ onImportInkb,+}) => {+ const importRef = useRef<HTMLInputElement>(null);++ return (+ <div className="space-y-4">+ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-3">+ <div className="space-y-1">+ <label className="text-[11px] text-[#a3a3a3]">Brush Name</label>+ <input+ type="text"+ value={brushName}+ onChange={(e) => onBrushNameChange(e.target.value)}+ className="w-full px-2.5 py-1.5 rounded bg-[#111111] border border-white/10 text-[12px] text-[#f5f5f5] focus:outline-none focus:border-[var(--accent)]"+ />+ </div>++ <div className="space-y-1">+ <label className="text-[11px] text-[#a3a3a3]">Category</label>+ <select+ value={category}+ onChange={(e) => onCategoryChange(e.target.value as BrushCategory | 'custom')}+ className="w-full px-2.5 py-1.5 rounded bg-[#111111] border border-white/10 text-[12px] text-[#f5f5f5]"+ >+ <option value="natural-paint">Natural Paint</option>+ <option value="brush">Brush</option>+ <option value="sketch">Sketch</option>+ <option value="pen">Pen</option>+ <option value="custom">Custom</option>+ </select>+ </div>++ <div className="space-y-1">+ <label className="text-[11px] text-[#a3a3a3]">Description</label>+ <textarea+ rows={3}+ value={description}+ onChange={(e) => onDescriptionChange(e.target.value)}+ placeholder="Describe this brush's physical feel, bristle setup, or surface interaction..."+ className="w-full px-2.5 py-1.5 rounded bg-[#111111] border border-white/10 text-[11px] text-[#e5e5e5] resize-none focus:outline-none focus:border-[var(--accent)]"+ />+ </div>+ </div>++ <div className="p-2.5 rounded bg-[#181818] border border-white/[0.06] space-y-2">+ <div className="text-[11px] font-medium text-[#e5e5e5]">Preset Actions</div>+ <div className="grid grid-cols-2 gap-2">+ <button+ type="button"+ onClick={onSaveAsNewPreset}+ className="px-2.5 py-1.5 rounded bg-[var(--accent)] hover:opacity-90 text-[11px] font-medium text-white flex items-center justify-center gap-1.5 cursor-pointer"+ >+ <Save className="w-3.5 h-3.5" />+ <span>Save as New Preset</span>+ </button>+ <button+ type="button"+ onClick={onDuplicateBrush}+ className="px-2.5 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[11px] text-[#e5e5e5] flex items-center justify-center gap-1.5 cursor-pointer"+ >+ <Copy className="w-3.5 h-3.5" />+ <span>Duplicate</span>+ </button>+ <button+ type="button"+ onClick={onExportInkb}+ className="px-2.5 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[11px] text-[#e5e5e5] flex items-center justify-center gap-1.5 cursor-pointer"+ >+ <Download className="w-3.5 h-3.5" />+ <span>Export .inkb v2</span>+ </button>+ <button+ type="button"+ onClick={() => importRef.current?.click()}+ className="px-2.5 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[11px] text-[#e5e5e5] flex items-center justify-center gap-1.5 cursor-pointer"+ >+ <Upload className="w-3.5 h-3.5" />+ <span>Import .inkb / .sut</span>+ </button>+ <input+ ref={importRef}+ type="file"+ accept=".inkb,.sut"+ className="hidden"+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) onImportInkb(f);+ e.target.value = '';+ }}+ />+ </div>+ <button+ type="button"+ onClick={onResetDefault}+ className="w-full px-2.5 py-1.5 rounded bg-[#242424] hover:bg-red-500/20 text-[11px] text-[#a3a3a3] hover:text-red-300 flex items-center justify-center gap-1.5 cursor-pointer"+ >+ <RotateCcw className="w-3.5 h-3.5" />+ <span>Reset Active Brush to Default</span>+ </button>+ </div>+ </div>+ );+};diff --git a/src/components/canvasArea/CanvasArtboardOverlays.tsx b/src/components/canvasArea/CanvasArtboardOverlays.tsxindex 15c1096..7fc5efb 100644--- a/src/components/canvasArea/CanvasArtboardOverlays.tsx+++ b/src/components/canvasArea/CanvasArtboardOverlays.tsx@@ -5,6 +5,8 @@ import { TransformOverlay } from '../TransformOverlay';import { TextEditorOverlay } from '../TextEditorOverlay';import { SpeechBalloonOverlay } from '../SpeechBalloonOverlay';import { Local3DContainer } from '../Local3DContainer';+import { GradientOverlay } from '../GradientOverlay';+import { PenPathOverlay } from '../PenPathOverlay';import { CanvasAreaProps, formatArtboardTransform } from './types';export interface CanvasArtboardOverlaysProps {@@ -53,6 +55,11 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onFillScreentone,onFillColor,onClearSelection,+ onDeleteOutsideSelection,+ onCutSelection,+ onCopySelection,+ onPasteSelection,+ onMoveSelectionToNewLayer,onInvertSelection,onExpandSelection,onContractSelection,@@ -72,6 +79,19 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onDeleteBalloon,frameDragPreview = null,shapeDragPreview = null,+ gradientDragPreview = null,+ gradientMesh = null,+ gradientSettings,+ onApplyGradientMesh,+ onCancelGradientMesh,+ retouchSettings,+ cloneSourceIndicator = null,+ penSession = null,+ penSettings,+ onCommitPenPath,+ onCancelPenPath,+ onToggleClosePenPath,+ tool = 'brush',primaryColor = '#000000',secondaryColor = '#ffffff',is3DLayerOpen = false,@@ -195,6 +215,11 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({onFillScreentone={onFillScreentone || (() => {})}onFillColor={onFillColor || (() => {})}onClearSelection={onClearSelection || (() => {})}+ onDeleteOutsideSelection={onDeleteOutsideSelection}+ onCutSelection={onCutSelection}+ onCopySelection={onCopySelection}+ onPasteSelection={onPasteSelection}+ onMoveSelectionToNewLayer={onMoveSelectionToNewLayer}onInvertSelection={onInvertSelection || (() => {})}onExpandSelection={onExpandSelection}onContractSelection={onContractSelection}@@ -361,6 +386,81 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({);})()}+ {/* Live Gradient Guide & Interactive Mesh Gradient Overlay */}+ {(gradientDragPreview || gradientMesh) && (+ <GradientOverlay+ dimensions={dimensions}+ zoom={liveZoom}+ flipX={liveFlipX}+ flipY={liveFlipY}+ dragPreview={gradientDragPreview}+ mesh={gradientMesh}+ opacity={gradientSettings?.opacity ?? 1}+ onApplyMesh={onApplyGradientMesh}+ onCancelMesh={onCancelGradientMesh}+ />+ )}++ {/* Clone Stamp Source Anchor & Live Sample Crosshair */}+ {tool === 'retouch' &&+ retouchSettings?.mode === 'clone-stamp' &&+ cloneSourceIndicator &&+ cloneSourceIndicator.anchor.x > -9000 && (() => {+ const invZoom = 1 / Math.max(0.05, liveZoom);+ const pt = cloneSourceIndicator.liveSamplePos || cloneSourceIndicator.anchor;+ const r = Math.max(6 * invZoom, (retouchSettings.size * 0.5));+ return (+ <svg+ className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"+ viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}+ >+ <circle+ cx={pt.x}+ cy={pt.y}+ r={r}+ fill="none"+ stroke="#ffffff"+ strokeOpacity={0.75}+ strokeWidth={1.2 * invZoom}+ strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}+ />+ <line+ x1={pt.x - 8 * invZoom}+ y1={pt.y}+ x2={pt.x + 8 * invZoom}+ y2={pt.y}+ stroke="#38bdf8"+ strokeWidth={1.6 * invZoom}+ />+ <line+ x1={pt.x}+ y1={pt.y - 8 * invZoom}+ x2={pt.x}+ y2={pt.y + 8 * invZoom}+ stroke="#38bdf8"+ strokeWidth={1.6 * invZoom}+ />+ </svg>+ );+ })()}++ {/* True Cubic Bézier Pen Tool Interactive Overlay */}+ {penSession && penSettings && (+ <PenPathOverlay+ dimensions={dimensions}+ zoom={liveZoom}+ flipX={liveFlipX}+ flipY={liveFlipY}+ session={penSession}+ settings={penSettings}+ primaryColor={primaryColor}+ secondaryColor={secondaryColor}+ onCommit={onCommitPenPath}+ onCancel={onCancelPenPath}+ onToggleClose={onToggleClosePenPath}+ />+ )}+{/* Local-Only 3D Viewport Ghost Layer (Strictly Client-Side Isolated State) */}{is3DLayerOpen && onClose3DLayer && onInsertRasterLayer && (<Local3DContainerdiff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.tsindex 79140f5..92d2ded 100644--- a/src/components/canvasArea/types.ts+++ b/src/components/canvasArea/types.ts@@ -12,8 +12,15 @@ import {SoftProofSettings,CanvasColorMode,ShapeDragPreview,+ GradientDragPreview,+ GradientMeshState,+ GradientSettings,+ RetouchSettings,+ PenPathSession,+ PenToolSettings,AnimationTimeline as AnimationTimelineType,} from '../../types/editor';+import type { CloneSourceIndicator } from '../../hooks/drawing/useRetouchTool';import { ROTATE_CURSOR_CSS, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../types/perspective';import { SparseTileGrid } from '../../utils/tileEngine';@@ -34,6 +41,7 @@ export interface CanvasAreaProps {navigation?: CanvasNavigationHandle;isSpaceDown: boolean;isShiftDown: boolean;+ heldModifierAction?: ModifierAction;isRotateModifier: boolean;isPanning: boolean;isRotating: boolean;@@ -71,6 +79,11 @@ export interface CanvasAreaProps {onFillScreentone?: () => void;onFillColor?: () => void;onClearSelection?: () => void;+ onDeleteOutsideSelection?: () => void;+ onCutSelection?: () => void;+ onCopySelection?: () => void;+ onPasteSelection?: () => void;+ onMoveSelectionToNewLayer?: () => void;onInvertSelection?: () => void;onExpandSelection?: (pixels: number) => void;onContractSelection?: (pixels: number) => void;@@ -110,6 +123,19 @@ export interface CanvasAreaProps {onDeleteBalloon?: () => void;frameDragPreview?: { mode: 'create' | 'divide'; start: { x: number; y: number }; end: { x: number; y: number } } | null;shapeDragPreview?: ShapeDragPreview | null;+ gradientDragPreview?: GradientDragPreview | null;+ gradientMesh?: GradientMeshState | null;+ gradientSettings?: GradientSettings;+ onApplyGradientMesh?: () => void;+ onCancelGradientMesh?: () => void;+ retouchSettings?: RetouchSettings;+ onUpdateRetouchSettings?: (newSettings: Partial<RetouchSettings>) => void;+ cloneSourceIndicator?: CloneSourceIndicator | null;+ penSession?: PenPathSession | null;+ penSettings?: PenToolSettings;+ onCommitPenPath?: () => void;+ onCancelPenPath?: () => void;+ onToggleClosePenPath?: () => void;secondaryColor?: string;animationTimeline?: AnimationTimelineType | null;onUpdateAnimationTimeline?: (timeline: AnimationTimelineType) => void;@@ -247,10 +273,19 @@ export function getCursorStyle({if (tool === 'text') {return { cursor: 'text' };}- if (tool === 'select-rect' || tool === 'select-lasso' || tool === 'select-wand' || tool === 'fill' || tool === 'frame' || tool === 'shape') {+ if (+ tool === 'select-rect' ||+ tool === 'select-lasso' ||+ tool === 'select-wand' ||+ tool === 'fill' ||+ tool === 'gradient' ||+ tool === 'frame' ||+ tool === 'shape' ||+ tool === 'pen'+ ) {return { cursor: 'crosshair' };}- if (tool === 'liquify') {+ if (tool === 'liquify' || tool === 'retouch') {return { cursor: isOverCanvas ? 'none' : 'default' };}if (tool === 'transform') {diff --git a/src/components/canvasArea/useCanvasEffects.ts b/src/components/canvasArea/useCanvasEffects.tsindex b27256b..afcf592 100644--- a/src/components/canvasArea/useCanvasEffects.ts+++ b/src/components/canvasArea/useCanvasEffects.ts@@ -1,10 +1,9 @@import React, { useEffect, useRef, useState } from 'react';-import { BrushSettings, LiquifySettings, ToolType } from '../../types/editor';+import { BrushSettings, LiquifySettings, RetouchSettings, ToolType } from '../../types/editor';import { ModifierAction } from '../../types/settings';import { getBrushTipOutline, resolveBrushTipImage, TipOutline } from '../../utils/brushOutline';import { preloadTipImage } from '../../utils/brushStorage';-import { resolveHeldKeyModifierAction } from '../../utils/shortcutManager';-import { useUiStore } from '../../stores';+import { subscribeNativeTablet } from '../../utils/nativeTabletInput';import { CursorConfig, formatCursorRingTransform } from './types';export interface UseCanvasEffectsParams {@@ -13,6 +12,8 @@ export interface UseCanvasEffectsParams {onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;liquifySettings?: LiquifySettings;onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;+ retouchSettings?: RetouchSettings;+ onUpdateRetouchSettings?: (newSettings: Partial<RetouchSettings>) => void;tool: ToolType;liveZoom: number;liveRotation: number;@@ -27,7 +28,6 @@ export interface UseCanvasEffectsParams {showCursorCoordinates: boolean;showPressureInStatusBar: boolean;heldModifierAction: ModifierAction;- setHeldModifierAction: React.Dispatch<React.SetStateAction<ModifierAction>>;isResizingBrush: boolean;setIsResizingBrush: React.Dispatch<React.SetStateAction<boolean>>;quickPalettePos: { x: number; y: number } | null;@@ -42,6 +42,8 @@ export function useCanvasEffects({onUpdateBrushSettings,liquifySettings,onUpdateLiquifySettings,+ retouchSettings,+ onUpdateRetouchSettings,tool,liveZoom,liveRotation,@@ -56,7 +58,6 @@ export function useCanvasEffects({showCursorCoordinates,showPressureInStatusBar,heldModifierAction,- setHeldModifierAction,isResizingBrush,setIsResizingBrush,quickPalettePos,@@ -113,7 +114,12 @@ export function useCanvasEffects({const isSquare = brushSettings.preset === 'square-digital' && !tipOutline;const tipAspect = isCustomTip && tipOutline ? tipOutline.height / tipOutline.width : 1.0;- const activeToolSize = tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size;+ const activeToolSize =+ tool === 'liquify' && liquifySettings+ ? liquifySettings.size+ : tool === 'retouch' && retouchSettings+ ? retouchSettings.size+ : brushSettings.size;const cursorBaseWidth = Math.max(4, activeToolSize * liveZoom);const thicknessRatio = tool === 'brush' ? (brushSettings.thickness ?? 1.0) : 1.0;const thicknessVertical = Boolean(brushSettings.thicknessVertical && tool === 'brush');@@ -201,69 +207,92 @@ export function useCanvasEffects({const viewport = viewportRef.current;if (!viewport) return;+ const shouldHideCursorRing =+ isSpaceDown ||+ isPanning ||+ isRotating ||+ isZoomDragging ||+ isRotateModifier ||+ isResizingBrush ||+ heldModifierAction === 'brush-size' ||+ heldModifierAction === 'pan' ||+ heldModifierAction === 'rotate' ||+ heldModifierAction === 'zoom-drag' ||+ (tool !== 'brush' &&+ tool !== 'eraser' &&+ tool !== 'liquify' &&+ tool !== 'retouch' &&+ tool !== 'select-pen' &&+ tool !== 'select-eraser');+let cachedRect: DOMRect | null = viewport.getBoundingClientRect();const updateRect = () => {if (viewport) cachedRect = viewport.getBoundingClientRect();};+ const showRingAtLocalPos = (x: number, y: number) => {+ const ring = cursorRingRef.current;+ if (!ring) return;+ const cfg = cursorConfigRef.current;+ ring.style.transform = formatCursorRingTransform(+ x,+ y,+ cfg.rotation,+ cfg.flipX,+ cfg.flipY,+ cfg.tipAngleDeg+ );+ if (ring.style.display !== 'block') {+ ring.style.display = 'block';+ }+ };++ // Immediately sync brush cursor ring visibility when Space/panning/tool state changes+ if (cursorRingRef.current) {+ if (shouldHideCursorRing) {+ cursorRingRef.current.style.display = 'none';+ } else if (lastPointerPosRef.current) {+ showRingAtLocalPos(lastPointerPosRef.current.x, lastPointerPosRef.current.y);+ }+ }+window.addEventListener('resize', updateRect);window.addEventListener('scroll', updateRect, true);const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(updateRect) : null;ro?.observe(viewport);- const updateCursorRingPos = (e: PointerEvent, forceRefreshRect: boolean = false) => {+ const updateCursorRingCoords = (clientX: number, clientY: number, forceRefreshRect: boolean = false) => {const ring = cursorRingRef.current;if (!ring) return;- if (- isSpaceDown ||- isPanning ||- isRotating ||- isZoomDragging ||- isRotateModifier ||- isResizingBrush ||- heldModifierAction === 'brush-size' ||- heldModifierAction === 'pan' ||- heldModifierAction === 'rotate' ||- heldModifierAction === 'zoom-drag' ||- (tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify' && tool !== 'select-pen' && tool !== 'select-eraser')- ) {- ring.style.display = 'none';- return;- }-if (forceRefreshRect || !cachedRect) updateRect();if (!cachedRect) return;- const x = e.clientX - cachedRect.left;- const y = e.clientY - cachedRect.top;+ const x = clientX - cachedRect.left;+ const y = clientY - cachedRect.top;if (x < 0 || x > cachedRect.width || y < 0 || y > cachedRect.height) {+ lastPointerPosRef.current = null;ring.style.display = 'none';return;}lastPointerPosRef.current = { x, y };- const cfg = cursorConfigRef.current;- ring.style.transform = formatCursorRingTransform(- x,- y,- cfg.rotation,- cfg.flipX,- cfg.flipY,- cfg.tipAngleDeg- );- if (ring.style.display !== 'block') {- ring.style.display = 'block';++ if (shouldHideCursorRing) {+ ring.style.display = 'none';+ return;}++ showRingAtLocalPos(x, y);};const handleWindowPointerMove = (e: PointerEvent) => {- updateCursorRingPos(e, false);+ updateCursorRingCoords(e.clientX, e.clientY, false);};const handleViewportPointerEnterOrDown = (e: PointerEvent) => {- updateCursorRingPos(e, true);+ updateCursorRingCoords(e.clientX, e.clientY, true);};const handlePointerLeave = () => {@@ -278,7 +307,19 @@ export function useCanvasEffects({viewport.addEventListener('pointerenter', handleViewportPointerEnterOrDown, { passive: true });viewport.addEventListener('pointerleave', handlePointerLeave, { passive: true });+ // Keep brush ring in sync with native WinTab / Windows Ink packets (XP-Pen / Wacom)+ const unsubscribeNativeTablet = subscribeNativeTablet((batch) => {+ if (batch.length === 0) return;+ const last = batch[batch.length - 1];+ if (last.phase === 4) {+ handlePointerLeave();+ return;+ }+ updateCursorRingCoords(last.clientX, last.clientY, false);+ });+return () => {+ unsubscribeNativeTablet();window.removeEventListener('resize', updateRect);window.removeEventListener('scroll', updateRect, true);ro?.disconnect();@@ -289,47 +330,34 @@ export function useCanvasEffects({};}, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, hasOpenDocument]);- // Track held modifier key combinations globally according to Modifier Key Settings+ // Dismiss quick palette on Escape and reset transient UI state on window blur / tab hideuseEffect(() => {- const syncHeldAction = (e: KeyboardEvent, spaceOverride?: boolean) => {- const action = resolveHeldKeyModifierAction(- {- ctrl: e.ctrlKey || e.metaKey,- shift: e.shiftKey,- alt: e.altKey,- space: spaceOverride !== undefined ? spaceOverride : isSpaceDown,- },- useUiStore.getState().appSettings.modifierKeys- );- setHeldModifierAction(action);- };-const handleKeyDown = (e: KeyboardEvent) => {if (e.key === 'Escape' && quickPalettePos) {setQuickPalettePos(null);}- syncHeldAction(e, e.code === 'Space' ? true : undefined);- };-- const handleKeyUp = (e: KeyboardEvent) => {- syncHeldAction(e, e.code === 'Space' ? false : undefined);};const handleBlur = () => {- setHeldModifierAction('none');setIsResizingBrush(false);setQuickPalettePos(null);};+ const handleVisibilityChange = () => {+ if (document.hidden) {+ handleBlur();+ }+ };+window.addEventListener('keydown', handleKeyDown);- window.addEventListener('keyup', handleKeyUp);window.addEventListener('blur', handleBlur);+ document.addEventListener('visibilitychange', handleVisibilityChange);return () => {window.removeEventListener('keydown', handleKeyDown);- window.removeEventListener('keyup', handleKeyUp);window.removeEventListener('blur', handleBlur);+ document.removeEventListener('visibilitychange', handleVisibilityChange);};- }, [isSpaceDown, quickPalettePos]);+ }, [quickPalettePos, setIsResizingBrush, setQuickPalettePos]);// Handle active brush resizing window drag listenersuseEffect(() => {@@ -343,12 +371,29 @@ export function useCanvasEffects({rafId = null;if (tool === 'liquify' && onUpdateLiquifySettings) {onUpdateLiquifySettings({ size: Math.round(pendingSize) });+ } else if (tool === 'retouch' && onUpdateRetouchSettings) {+ onUpdateRetouchSettings({+ size: Math.max(2, Math.min(300, Math.round(pendingSize))),+ hardness: Math.round(pendingHardness * 100),+ });} else {onUpdateBrushSettings({ size: pendingSize, hardness: pendingHardness });}};+ const finishResize = () => {+ if (rafId !== null) {+ cancelAnimationFrame(rafId);+ commitResize();+ }+ setIsResizingBrush(false);+ };+const handleWindowPointerMove = (e: PointerEvent) => {+ if (typeof e.buttons === 'number' && e.buttons === 0) {+ finishResize();+ return;+ }const dx = e.clientX - resizeOriginRef.current.clientX;const dy = resizeOriginRef.current.clientY - e.clientY;@@ -371,32 +416,30 @@ export function useCanvasEffects({}};- const handleWindowPointerUp = () => {- if (rafId !== null) {- cancelAnimationFrame(rafId);- commitResize();+ const handleWindowMouseUp = (e: MouseEvent) => {+ if (typeof e.buttons !== 'number' || e.buttons === 0) {+ finishResize();}- setIsResizingBrush(false);};window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });- window.addEventListener('pointerup', handleWindowPointerUp);- window.addEventListener('pointercancel', handleWindowPointerUp);+ window.addEventListener('pointerup', finishResize, true);+ window.addEventListener('pointercancel', finishResize, true);+ window.addEventListener('mouseup', handleWindowMouseUp, true);- const prevCursor = document.body.style.cursor;- const prevUserSelect = document.body.style.userSelect;document.body.style.cursor = 'ew-resize';document.body.style.userSelect = 'none';return () => {if (rafId !== null) cancelAnimationFrame(rafId);window.removeEventListener('pointermove', handleWindowPointerMove);- window.removeEventListener('pointerup', handleWindowPointerUp);- window.removeEventListener('pointercancel', handleWindowPointerUp);- document.body.style.cursor = prevCursor;- document.body.style.userSelect = prevUserSelect;+ window.removeEventListener('pointerup', finishResize, true);+ window.removeEventListener('pointercancel', finishResize, true);+ window.removeEventListener('mouseup', handleWindowMouseUp, true);+ document.body.style.cursor = '';+ document.body.style.userSelect = '';};- }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, tool]);+ }, [isResizingBrush, onUpdateBrushSettings, onUpdateLiquifySettings, onUpdateRetouchSettings, tool, setIsResizingBrush]);return {tipOutline,diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex 3d00e58..86a8580 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -3,6 +3,7 @@ import {BrushSettings,CanvasDimensions,LiquifySettings,+ RetouchSettings,ToolType,} from '../../types/editor';import { ModifierAction } from '../../types/settings';@@ -18,6 +19,7 @@ export interface UseCanvasPointerHandlersParams {dimensions: CanvasDimensions;brushSettings: BrushSettings;liquifySettings?: LiquifySettings;+ retouchSettings?: RetouchSettings;tool: ToolType;navigation?: CanvasNavigationHandle;pan: { x: number; y: number };@@ -47,6 +49,7 @@ export function useCanvasPointerHandlers({dimensions,brushSettings,liquifySettings,+ retouchSettings,tool,navigation,pan,@@ -89,8 +92,16 @@ export function useCanvasPointerHandlers({setIsResizingBrush(true);resizeOriginRef.current = { clientX: e.clientX, clientY: e.clientY };resizeStartSettingsRef.current = {- size: tool === 'liquify' && liquifySettings ? liquifySettings.size : brushSettings.size,- hardness: brushSettings.hardness ?? 1.0,+ size:+ tool === 'liquify' && liquifySettings+ ? liquifySettings.size+ : tool === 'retouch' && retouchSettings+ ? retouchSettings.size+ : brushSettings.size,+ hardness:+ tool === 'retouch' && retouchSettings+ ? retouchSettings.hardness / 100+ : (brushSettings.hardness ?? 1.0),};};@@ -156,13 +167,16 @@ export function useCanvasPointerHandlers({): boolean => {switch (action) {case 'pan':+ e.stopPropagation();onStartPan(e);return true;case 'rotate':+ e.stopPropagation();onStartRotate(e);return true;case 'zoom-drag':if (onStartZoomDrag) {+ e.stopPropagation();onStartZoomDrag(e);return true;}@@ -171,6 +185,14 @@ export function useCanvasPointerHandlers({startBrushResize(e);return true;case 'eyedropper':+ if (+ allowDrawingPassThrough &&+ e.button === 0 &&+ e.altKey &&+ ((tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') || tool === 'pen')+ ) {+ return false;+ }if (e.button !== 0 || !allowDrawingPassThrough) {startModifierEyedropper(e);return true;diff --git a/src/engine/BristleRibbonEngine.ts b/src/engine/BristleRibbonEngine.tsnew file mode 100644index 0000000..563d812--- /dev/null+++ b/src/engine/BristleRibbonEngine.ts@@ -0,0 +1,905 @@+/**+ * BristleRibbonEngine.ts+ * Continuous Multi-Strand Bristle & Rake Frame Generator for InkStudio's Natural Paint Engine.+ *+ * Tracks a continuous parallel-transported local brush frame (tangent, normal, curvature,+ * accumulated arcLength, stylus tilt altitude/azimuth, barrel twist) along spline trajectories,+ * advancing up to 64 independent bristle strands without discrete-stamp blurring or+ * tight-turn self-intersection glitches.+ */++import type {+ BristleSettings,+ BrushSettings,+ NaturalMixingMode,+ NaturalPaintSettings,+ Point,+} from '../types/editor';+import {+ DEFAULT_BRISTLE_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+} from '../types/editor';+import {+ BristleStepOutput,+ LayerPixelSampler,+ MAX_BRISTLE_CHANNELS,+ RgbaColor,+ SpatialBristleReservoir,+} from '../utils/colorMixingEngine';++/**+ * Stride (in floats) of one continuous bristle strand segment in BristleStrandBuffer:+ * [0] x0, [1] y0, [2] x1, [3] y1,+ * [4] r0, [5] g0, [6] b0, [7] a0,+ * [8] r1, [9] g1, [10] b1, [11] a1,+ * [12] radius0, [13] radius1,+ * [14] load0, [15] load1,+ * [16] height0, [17] height1,+ * [18] arcU0, [19] arcU1,+ * [20] acrossV, [21] pressure,+ * [22] tiltMag, [23] bristleIdx+ */+export const BRISTLE_SEG_STRIDE = 24;++export interface BristleStrandBatch {+ data: Float32Array;+ count: number;+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+}++export interface BristleStrokeConfig {+ color: string;+ size: number;+ minSizeFactor: number;+ flow: number;+ opacity: number;+ spacing: number;+ angleDeg: number;+ usePressure: boolean;+ useTilt: boolean;+ tiltScale: number;+ mixingMode: NaturalMixingMode;+ amountOfPaint: number;+ densityOfPaint: number;+ colorStretch: number;+ bristle: BristleSettings;+ naturalPaint: NaturalPaintSettings;+ presetKey?: string;+ strokeSeed?: number;+ totalLength?: number;+ taperInLength?: number;+ taperOutLength?: number;+ taperAffectSize?: boolean;+ taperAffectLoad?: boolean;+}++export function extractBristleStrokeConfig(+ bs: BrushSettings,+ strokeColor: string,+ totalLength?: number,+ strokeSeed?: number+): BristleStrokeConfig {+ const bristle: BristleSettings = {+ ...DEFAULT_BRISTLE_SETTINGS,+ ...(bs.bristle || {}),+ };+ const resolvedPaintLoad =+ bs.amountOfPaint !== undefined+ ? Math.max(0, Math.min(1, bs.amountOfPaint))+ : Math.max(0, Math.min(1, bs.naturalPaint?.paintLoad ?? DEFAULT_NATURAL_PAINT_SETTINGS.paintLoad));+ const resolvedSpatialMixing =+ bs.colorMixing === false+ ? false+ : bs.naturalPaint?.spatialMixing ?? DEFAULT_NATURAL_PAINT_SETTINGS.spatialMixing;+ const naturalPaint: NaturalPaintSettings = {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ ...(bs.naturalPaint || {}),+ enabled: bs.naturalPaint?.enabled ?? (bs.renderMode === 'bristle-ribbon' || bs.renderMode === 'bristle-hybrid'),+ paintLoad: resolvedPaintLoad,+ spatialMixing: resolvedSpatialMixing,+ };+ return {+ color: strokeColor,+ size: Math.max(1, bs.size || 24),+ minSizeFactor: Math.max(0.02, Math.min(1, bs.minSizeFactor ?? 0.25)),+ flow: Math.max(0.01, Math.min(1, bs.brushDensity ?? bs.flow ?? 0.92)),+ opacity: Math.max(0.01, Math.min(1, bs.opacity ?? 1.0)),+ spacing: Math.max(0.02, Math.min(0.5, bs.spacing ?? 0.06)),+ angleDeg: bs.customTipAngle ?? 0,+ usePressure: bs.usePressure !== false,+ useTilt: Boolean(bs.useTilt),+ tiltScale: bs.tiltScale ?? 1.0,+ mixingMode: bs.mixingMode ?? 'impasto_mix',+ amountOfPaint: resolvedPaintLoad,+ densityOfPaint: bs.densityOfPaint ?? 0.9,+ colorStretch: bs.colorStretch ?? 0.7,+ bristle,+ naturalPaint,+ presetKey: bs.preset,+ strokeSeed: strokeSeed ?? 1337,+ totalLength,+ taperInLength: bs.taper?.useIn ? bs.taper.inLength || 0 : 0,+ taperOutLength: bs.taper?.useOut ? bs.taper.outLength || 0 : 0,+ taperAffectSize: bs.taper?.affectSize !== false,+ taperAffectLoad: bs.taper?.affectLoad ?? true,+ };+}++export class BristleRibbonEngine {+ public readonly reservoir: SpatialBristleReservoir;+ public readonly config: BristleStrokeConfig;+ public arcLength: number = 0;+ public strokeSeed: number = 1337;++ private initialized: boolean = false;+ private hasDirection: boolean = false;+ private tx: number = 1;+ private ty: number = 0;+ private nx: number = 0;+ private ny: number = 1;+ private prevCenterX: number = 0;+ private prevCenterY: number = 0;+ private prevAngle: number = 0;++ // Previous slice per-bristle state (SoA, zero GC)+ private readonly prevX = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevY = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevR = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevG = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevB = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevA = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevRadius = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevLoad = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevHeight = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly prevArcU = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly bristleLagX = new Float32Array(MAX_BRISTLE_CHANNELS);+ private readonly bristleLagY = new Float32Array(MAX_BRISTLE_CHANNELS);++ // 7-band flat-ribbon cohesive under-bed state (zero circular endcap halo + spatial color fidelity!)+ private static readonly BED_BANDS = 7;+ private readonly prevBedX = new Float32Array(7);+ private readonly prevBedY = new Float32Array(7);+ private readonly prevBedR = new Float32Array(7);+ private readonly prevBedG = new Float32Array(7);+ private readonly prevBedB = new Float32Array(7);+ private readonly prevBedA = new Float32Array(7);+ private readonly prevBedLoad = new Float32Array(7);+ private readonly prevBedRad = new Float32Array(7);+ private bedInitialized: boolean = false;++ // Reusable segment output buffer+ private segBuffer: Float32Array = new Float32Array(2048 * BRISTLE_SEG_STRIDE);+ private readonly scratchSample: RgbaColor = { r: 255, g: 255, b: 255, a: 0 };+ private readonly scratchStep: BristleStepOutput = {+ r: 0,+ g: 0,+ b: 0,+ alpha: 0,+ load: 0,+ height: 0,+ };++ constructor(config: BristleStrokeConfig, existingReservoir?: SpatialBristleReservoir) {+ this.config = config;+ this.strokeSeed = config.strokeSeed ?? 1337;+ this.reservoir =+ existingReservoir ??+ new SpatialBristleReservoir(+ config.color,+ config.bristle,+ config.naturalPaint,+ config.presetKey+ );+ if (existingReservoir) {+ this.reservoir.reset(+ config.color,+ config.bristle,+ config.naturalPaint,+ config.presetKey,+ this.strokeSeed+ );+ }+ }++ public getCurrentFrame(): { tx: number; ty: number; nx: number; ny: number; arcLength: number } {+ return {+ tx: this.tx,+ ty: this.ty,+ nx: this.nx,+ ny: this.ny,+ arcLength: this.arcLength,+ };+ }++ private ensureSegCapacity(count: number): void {+ const needed = count * BRISTLE_SEG_STRIDE;+ if (this.segBuffer.length < needed) {+ const next = new Float32Array(Math.max(needed, this.segBuffer.length * 2));+ next.set(this.segBuffer);+ this.segBuffer = next;+ }+ }++ /**+ * Computes taper multipliers for width and load at the current arc length.+ */+ private evaluateTaper(arcU: number): { widthScale: number; loadScale: number } {+ let widthScale = 1.0;+ let loadScale = 1.0;+ const inLen = this.config.taperInLength ?? 0;+ if (inLen > 0 && arcU < inLen) {+ const f = Math.max(0.08, Math.min(1.0, arcU / inLen));+ if (this.config.taperAffectSize !== false) widthScale *= f;+ if (this.config.taperAffectLoad !== false) loadScale *= 0.35 + 0.65 * f;+ }+ const total = this.config.totalLength ?? 0;+ const outLen = this.config.taperOutLength ?? 0;+ if (total > 0 && outLen > 0) {+ const distFromEnd = total - arcU;+ if (distFromEnd < outLen) {+ const f = Math.max(0.06, Math.min(1.0, distFromEnd / outLen));+ if (this.config.taperAffectSize !== false) widthScale *= f;+ if (this.config.taperAffectLoad !== false) loadScale *= f;+ }+ }+ return { widthScale, loadScale };+ }++ /**+ * Initializes the bristle frame at pointer-down.+ * When `initialDir` is provided (completed stroke bake), aligns bristles directly along+ * the true stroke tangent so there is zero detached stub. For live pointer-down before+ * movement, anchors the frame and emits a soft cohesive touch only when `emitDot` is true.+ */+ public emitInitialStamp(+ pt: Point,+ sampler?: LayerPixelSampler,+ initialDir?: { dx: number; dy: number },+ emitDot: boolean = true+ ): BristleStrandBatch {+ let baseAngleRad = (this.config.angleDeg * Math.PI) / 180;+ if (initialDir && Math.hypot(initialDir.dx, initialDir.dy) > 1e-3) {+ baseAngleRad = Math.atan2(initialDir.dy, initialDir.dx);+ this.hasDirection = true;+ } else {+ this.hasDirection = false;+ }+ this.tx = Math.cos(baseAngleRad);+ this.ty = Math.sin(baseAngleRad);+ this.nx = -this.ty;+ this.ny = this.tx;+ this.prevAngle = baseAngleRad;+ this.prevCenterX = pt.x;+ this.prevCenterY = pt.y;+ this.arcLength = 0;++ const pressure = Math.max(0.05, Math.min(1.0, pt.pressure || 0.5));+ const tiltX = this.config.useTilt ? pt.tiltX ?? 0 : 0;+ const tiltY = this.config.useTilt ? pt.tiltY ?? 0 : 0;+ const tiltDeg = Math.min(90, Math.hypot(tiltX, tiltY));+ const tiltMag = Math.sin((tiltDeg * Math.PI) / 180);+ const splay = this.computeSplay(pressure, tiltMag);+ const width = Math.max(1.5, pt.width > 0 ? pt.width : this.config.size);+ const halfW = width * 0.5 * splay;++ const n = this.reservoir.count;+ this.ensureSegCapacity(n + 1);+ const out = this.segBuffer;+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ let segCount = 0;++ const twistRad = ((pt.twist ?? 0) * Math.PI) / 180;+ const cosTw = Math.cos(twistRad);+ const sinTw = Math.sin(twistRad);+ const rNx = this.nx * cosTw - this.ny * sinTw;+ const rNy = this.nx * sinTw + this.ny * cosTw;+ const isKnife = this.config.bristle.profile === 'knife';++ for (let i = 0; i < n; i++) {+ const off = this.reservoir.offsets[i];+ const absOff = Math.abs(off);+ const stagger = this.reservoir.startDelay[i];+ const longOff = (stagger - 0.35) * width * (isKnife ? 0.04 : 0.25);+ const bx = pt.x + rNx * (off * halfW) + this.tx * longOff;+ const by = pt.y + rNy * (off * halfW) + this.ty * longOff;+ const strandRad = Math.max(0.85, this.reservoir.radii[i] * halfW * 1.45);++ if (sampler && this.config.naturalPaint.spatialMixing) {+ sampler.samplePointFast(bx, by, strandRad, this.scratchSample);+ } else {+ this.scratchSample.a = 0;+ }++ const stepOut = this.reservoir.stepBristle(+ i,+ this.scratchSample,+ 0,+ pressure,+ this.config.naturalPaint,+ this.config.mixingMode,+ this.config.colorStretch,+ this.config.amountOfPaint,+ this.config.densityOfPaint,+ this.config.flow,+ this.scratchStep+ );++ const entryFade = isKnife ? 1.0 : Math.max(0.15, 1.0 - stagger * 0.65);+ const flankFade = isKnife ? 1.0 : 1.0 - Math.pow(Math.max(0, absOff - 0.55) / 0.45, 1.5) * 0.55;+ const initAlpha = stepOut.alpha * entryFade * flankFade;+ const initLoad = stepOut.load * entryFade * flankFade;++ this.prevX[i] = bx;+ this.prevY[i] = by;+ this.bristleLagX[i] = bx;+ this.bristleLagY[i] = by;+ this.prevR[i] = stepOut.r;+ this.prevG[i] = stepOut.g;+ this.prevB[i] = stepOut.b;+ // For continuous strokes (!emitDot), start bristles cleanly at 0 so they fade IN at their+ // staggered startGate instead of painting a detached ghost dot at arcLength = 0!+ const startAtZero = !emitDot && !isKnife;+ this.prevA[i] = startAtZero ? 0 : initAlpha;+ this.prevRadius[i] = strandRad * (0.7 + 0.3 * entryFade);+ this.prevLoad[i] = startAtZero ? 0 : initLoad;+ this.prevHeight[i] = startAtZero ? 0 : stepOut.height * entryFade;+ this.prevArcU[i] = 0;++ // Only emit a single-tap dot if explicitly requested (avoids detached start stub before drag!)+ if (emitDot && initAlpha > 0.01 && !initialDir) {+ const dabHalfLen = Math.max(0.5, strandRad * 0.55);+ const sx0 = bx - this.tx * dabHalfLen;+ const sy0 = by - this.ty * dabHalfLen;+ const sx1 = bx + this.tx * dabHalfLen;+ const sy1 = by + this.ty * dabHalfLen;+ const base = segCount * BRISTLE_SEG_STRIDE;+ out[base + 0] = sx0;+ out[base + 1] = sy0;+ out[base + 2] = sx1;+ out[base + 3] = sy1;+ out[base + 4] = stepOut.r;+ out[base + 5] = stepOut.g;+ out[base + 6] = stepOut.b;+ out[base + 7] = initAlpha * 0.7;+ out[base + 8] = stepOut.r;+ out[base + 9] = stepOut.g;+ out[base + 10] = stepOut.b;+ out[base + 11] = initAlpha * 0.7;+ out[base + 12] = this.prevRadius[i] * 0.85;+ out[base + 13] = this.prevRadius[i] * 0.85;+ out[base + 14] = initLoad;+ out[base + 15] = initLoad;+ out[base + 16] = stepOut.height * entryFade * 0.65;+ out[base + 17] = stepOut.height * entryFade * 0.65;+ out[base + 18] = 0;+ out[base + 19] = dabHalfLen * 2;+ out[base + 20] = off;+ out[base + 21] = pressure;+ out[base + 22] = tiltMag;+ out[base + 23] = i;+ segCount++;++ const pad = strandRad + 2;+ if (Math.min(sx0, sx1) - pad < minX) minX = Math.min(sx0, sx1) - pad;+ if (Math.min(sy0, sy1) - pad < minY) minY = Math.min(sy0, sy1) - pad;+ if (Math.max(sx0, sx1) + pad > maxX) maxX = Math.max(sx0, sx1) + pad;+ if (Math.max(sy0, sy1) + pad > maxY) maxY = Math.max(sy0, sy1) + pad;+ }+ }++ this.initialized = true;+ this.bedInitialized = false;++ return {+ data: out,+ count: segCount,+ minX,+ minY,+ maxX,+ maxY,+ };+ }++ private computeSplay(pressure: number, tiltMag: number): number {+ const splayStrength = Math.max(0, Math.min(1, this.config.bristle.splay));+ const stiffness = Math.max(0, Math.min(1, this.config.bristle.stiffness));+ const flex = 1.0 - stiffness * 0.45;+ const pSplay = 1.0 + (pressure - 0.5) * splayStrength * 0.65 * flex;+ const tiltSplay = this.config.useTilt ? tiltMag * (this.config.tiltScale || 1.0) * (0.45 + splayStrength * 0.8) : 0;+ return Math.max(0.45, Math.min(2.6, pSplay + tiltSplay));+ }++ /**+ * Advances all bristle strands continuously along a cubic Bézier curve segment,+ * using parallel-transported frames and signed-curvature fold clamping.+ */+ public emitCubicSegment(+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,+ sampler?: LayerPixelSampler+ ): BristleStrandBatch {+ // Estimate curve arc length+ const polyLen =+ Math.hypot(c1.x - p0.x, c1.y - p0.y) ++ Math.hypot(c2.x - c1.x, c2.y - c1.y) ++ Math.hypot(p3.x - c2.x, p3.y - c2.y);++ if (polyLen < 0.08) {+ return { data: this.segBuffer, count: 0, minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };+ }++ if (!this.initialized) {+ this.emitInitialStamp(p0, sampler);+ }++ const avgW = Math.max(2, (p0.width + p3.width) * 0.5 || this.config.size);+ // Fine high-DPI continuous ribbon stepping: razor-smooth curves even on large 80-120px brushes+ const targetStep = Math.max(1.0, Math.min(3.2, avgW * Math.max(0.035, this.config.spacing * 0.55)));+ const slices = Math.max(1, Math.min(64, Math.ceil(polyLen / targetStep)));++ const n = this.reservoir.count;+ const stiffness = Math.max(0.05, Math.min(1.0, this.config.bristle.stiffness));+ // Higher stiffness follows brush frame crisply; lower stiffness trails gently like long soft hair+ const followRate = 0.42 + stiffness * 0.58;+ const baseAngleRad = (this.config.angleDeg * Math.PI) / 180;++ let segCount = 0;+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (let s = 1; s <= slices; s++) {+ const t = s / slices;+ const it = 1 - t;+ const it2 = it * it;+ const it3 = it2 * it;+ const t2 = t * t;+ const t3 = t2 * t;+ const b1 = 3 * it2 * t;+ const b2 = 3 * it * t2;++ const cx = it3 * p0.x + b1 * c1.x + b2 * c2.x + t3 * p3.x;+ const cy = it3 * p0.y + b1 * c1.y + b2 * c2.y + t3 * p3.y;+ const dx = cx - this.prevCenterX;+ const dy = cy - this.prevCenterY;+ const stepDist = Math.hypot(dx, dy);+ if (stepDist < 0.12) continue;++ this.arcLength += stepDist;+ const pressure = Math.max(+ 0.05,+ Math.min(1.0, it3 * p0.pressure + b1 * c1.pressure + b2 * c2.pressure + t3 * p3.pressure)+ );+ const rawW = it3 * p0.width + b1 * c1.width + b2 * c2.width + t3 * p3.width;+ const { widthScale, loadScale } = this.evaluateTaper(this.arcLength);+ const width = Math.max(1.2, (rawW > 0 ? rawW : this.config.size) * widthScale);++ const tiltX = this.config.useTilt ? it * (p0.tiltX ?? 0) + t * (p3.tiltX ?? 0) : 0;+ const tiltY = this.config.useTilt ? it * (p0.tiltY ?? 0) + t * (p3.tiltY ?? 0) : 0;+ const tiltDeg = Math.min(90, Math.hypot(tiltX, tiltY));+ const tiltMag = Math.sin((tiltDeg * Math.PI) / 180);+ const twistDeg = it * (p0.twist ?? 0) + t * (p3.twist ?? 0);++ // Physical hand-held brush head orientation:+ // Smoothly follows gentle curves without whipping into radial pinwheel fans on sharp zig-zag reversals!+ const instTx = dx / stepDist;+ const instTy = dy / stepDist;+ const instAngle = Math.atan2(instTy, instTx);+ const isKnife = this.config.bristle.profile === 'knife';+ const entryZone = isKnife ? width * 0.2 : Math.max(18, width * 0.95);++ let signedTurn = 0;+ if (!this.hasDirection) {+ this.tx = instTx;+ this.ty = instTy;+ this.prevAngle = instAngle;+ this.hasDirection = true;++ // Re-align initial bristle anchors to the established stroke direction with organic longitudinal stagger+ const initNx = -this.ty;+ const initNy = this.tx;+ const initHalfW = Math.max(1, p0.width || this.config.size) * 0.5;+ for (let i = 0; i < n; i++) {+ const off = this.reservoir.offsets[i];+ const longStagger = isKnife ? 0 : (this.reservoir.startDelay[i] - 0.35) * width * 0.38;+ this.prevX[i] = this.prevCenterX + initNx * (off * initHalfW) + this.tx * longStagger;+ this.prevY[i] = this.prevCenterY + initNy * (off * initHalfW) + this.ty * longStagger;+ this.bristleLagX[i] = this.prevX[i];+ this.bristleLagY[i] = this.prevY[i];+ }+ } else {+ // Compute smallest angular difference to either forward or reversed stroke axis.+ // When an artist pulls back in a zig-zag (Photo 2!), the hand doesn't spin the brush 180° —+ // it glides smoothly across the reversed axis, completely eliminating radial pinwheel corners!+ let dTheta = instAngle - this.prevAngle;+ while (dTheta > Math.PI) dTheta -= Math.PI * 2;+ while (dTheta < -Math.PI) dTheta += Math.PI * 2;++ if (Math.abs(dTheta) > Math.PI * 0.58) {+ // Sharp reversal: align gently to the opposite parallel axis (keeps normal continuous, zero pinwheel!)+ const flippedTarget = dTheta > 0 ? dTheta - Math.PI : dTheta + Math.PI;+ const maxStepTurn = Math.min(0.28, (stepDist / Math.max(12, width * 0.75)) * 0.55);+ signedTurn = Math.max(-maxStepTurn, Math.min(maxStepTurn, flippedTarget * 0.35));+ } else {+ // Normal curve: physical arc-length damped angular tracking+ const maxStepTurn = Math.min(0.35, (stepDist / Math.max(8, width * 0.45)) * (0.45 + stiffness * 0.45));+ signedTurn = Math.max(-maxStepTurn, Math.min(maxStepTurn, dTheta * (0.45 + stiffness * 0.4)));+ }++ const nextAngle = this.prevAngle + signedTurn;+ this.prevAngle = nextAngle;+ this.tx = Math.cos(nextAngle);+ this.ty = Math.sin(nextAngle);+ }++ // Base perpendicular normal (rotated by optional brush angle / barrel twist / tilt azimuth)+ let frameRot = baseAngleRad + (twistDeg * Math.PI) / 180;+ if (this.config.useTilt && tiltMag > 0.12) {+ const tiltAz = Math.atan2(tiltY, tiltX);+ let relTilt = tiltAz - this.prevAngle;+ while (relTilt > Math.PI) relTilt -= Math.PI * 2;+ while (relTilt < -Math.PI) relTilt += Math.PI * 2;+ frameRot += relTilt * tiltMag * 0.45;+ }++ const cosR = Math.cos(frameRot);+ const sinR = Math.sin(frameRot);+ const baseNx = -this.ty;+ const baseNy = this.tx;+ this.nx = baseNx * cosR - baseNy * sinR;+ this.ny = baseNx * sinR + baseNy * cosR;++ const splay = this.computeSplay(pressure, tiltMag);+ const halfW = width * 0.5 * splay;++ // Signed curvature kappa = dTheta / ds -> clamp inner-turn normal offset to prevent fold-over+ const kappa = signedTurn / Math.max(0.5, stepDist);+ const absKappa = Math.abs(kappa);+ const maxInnerRadius = absKappa > 1e-4 ? Math.max(3.0, 0.85 / absKappa) : Infinity;+ const irreg = this.config.bristle.irregularity;++ const BED_BANDS = BristleRibbonEngine.BED_BANDS;+ this.ensureSegCapacity(segCount + n + BED_BANDS);+ const out = this.segBuffer;+ const profile = this.config.bristle.profile;+ const isRake = profile === 'rake';+ const isFan = profile === 'fan';+ // Wider overlapping tuft base for lush cohesive oil/filbert/acrylic bodies;+ // crisp expressive strands for rake/fan with richer clumped center for Prussian blue overlaps (Photo 2!)+ const tuftWidthBoost = isRake ? 1.38 : isFan ? 1.24 : isKnife ? 1.85 : 1.82;+ const hasUnderBed = !isRake && !isFan && stepDist > 0.05;+ const bedSlotStart = hasUnderBed ? segCount : -1;+ if (hasUnderBed) segCount += BED_BANDS;++ // Accumulate local spatial color & load per under-bed band so yellow+purple NEVER muddy together!+ const bandR = [0, 0, 0, 0, 0, 0, 0];+ const bandG = [0, 0, 0, 0, 0, 0, 0];+ const bandB = [0, 0, 0, 0, 0, 0, 0];+ const bandLoad = [0, 0, 0, 0, 0, 0, 0];+ const bandAlpha = [0, 0, 0, 0, 0, 0, 0];+ const bandCount = [0, 0, 0, 0, 0, 0, 0];++ for (let i = 0; i < n; i++) {+ const rawOff = this.reservoir.offsets[i];+ const absOff = Math.abs(rawOff);++ // Organic bristle hair meander along arc length (like hand-painted oil strands in Photo 1!)+ const meander = isKnife+ ? 0+ : Math.sin(this.arcLength * this.reservoir.wanderFreq[i] + this.reservoir.wanderPhase[i]) *+ (0.032 + irreg * 0.068);+ let localSpan = Math.max(-1.05, Math.min(1.05, rawOff + meander)) * halfW;++ // If bristle lies on the inside of a tight curve, clamp its radial span smoothly+ if (kappa * localSpan > 0 && Math.abs(localSpan) > maxInnerRadius) {+ const excess = Math.abs(localSpan) - maxInnerRadius;+ const compressed = maxInnerRadius + excess * 0.12;+ localSpan = Math.sign(localSpan) * Math.min(Math.abs(localSpan), compressed);+ }++ // Longitudinal brush tuft stagger so start/end & edge hairs sit naturally forward/back+ const longOffset = isKnife ? 0 : (this.reservoir.startDelay[i] - 0.45) * width * (isRake ? 0.36 : 0.24);+ const targetX = cx + this.nx * localSpan + this.tx * longOffset;+ const targetY = cy + this.ny * localSpan + this.ty * longOffset;++ // Bristle flexibility lag: outer/longer hairs follow with subtle organic sweep+ const bx = this.bristleLagX[i] + (targetX - this.bristleLagX[i]) * followRate;+ const by = this.bristleLagY[i] + (targetY - this.bristleLagY[i]) * followRate;+ this.bristleLagX[i] = bx;+ this.bristleLagY[i] = by;++ const strandDist = Math.hypot(bx - this.prevX[i], by - this.prevY[i]);+ // Natural bristle width undulation along stroke length+ const widthBreath = isKnife+ ? 1.0+ : 0.88 + 0.18 * Math.sin(this.arcLength * 0.035 + this.reservoir.wanderPhase[i] * 1.7);+ // For rake, inner bristles form richer bold clumped tracks while outer hairs stay fine & separated (Photo 2!)+ const rakeCenterBoost = isRake ? (absOff < 0.58 ? 1.24 : 0.86) : 1.0;+ const strandRad = Math.max(+ 0.75,+ this.reservoir.radii[i] * halfW * tuftWidthBoost * rakeCenterBoost * widthBreath+ );++ if (sampler && this.config.naturalPaint.spatialMixing) {+ sampler.samplePointFast(bx, by, strandRad, this.scratchSample);+ } else {+ this.scratchSample.a = 0;+ }++ const stepOut = this.reservoir.stepBristle(+ i,+ this.scratchSample,+ strandDist,+ pressure,+ this.config.naturalPaint,+ this.config.mixingMode,+ this.config.colorStretch,+ this.config.amountOfPaint,+ this.config.densityOfPaint,+ this.config.flow,+ this.scratchStep+ );++ // Staggered organic entry feathering: each bristle enters at its own arcLength+ const startGate = this.reservoir.startDelay[i] * entryZone * (isRake ? 0.65 : 0.52);+ let entryRamp = 1.0;+ if (!isKnife && this.arcLength < startGate + entryZone * 0.48) {+ const tEntry = (this.arcLength - startGate) / Math.max(4, entryZone * 0.48);+ entryRamp = tEntry <= 0 ? 0 : tEntry >= 1 ? 1 : tEntry * tEntry * (3 - 2 * tEntry);+ }++ // Physical pressure-driven bristle lift-off: softer threshold so light strokes smoothly+ // glaze/blend across underlying paint while dry-brush presets still lift outer hairs+ const liftThresh =+ (1.0 - this.reservoir.lengthFactors[i]) * (0.28 + this.config.naturalPaint.dryBrush * 0.34);+ const contactLift = isKnife+ ? 1.0+ : Math.max(0.0, Math.min(1.0, (pressure - liftThresh) / 0.36));+ const smoothLift = contactLift * contactLift * (3.0 - 2.0 * contactLift);++ // Outer-flank dry-brush feathering: outer edges naturally reveal woven linen tooth (Photo 1 & 2!)+ const flankDrop = isKnife+ ? 1.0+ : 1.0 - Math.pow(Math.max(0, absOff - 0.62) / 0.38, 1.5) * (isRake ? 0.5 : 0.68);++ // Subtle along-stroke ridge modulation so 3D paint crests breathe organically+ const ridgeBreath = isKnife+ ? 1.0+ : 0.84 + 0.22 * Math.sin(this.arcLength * 0.042 + this.reservoir.wanderPhase[i]);++ const contactEnv = entryRamp * smoothLift;+ const effAlpha = stepOut.alpha * loadScale * contactEnv * (0.50 + 0.50 * flankDrop);+ const effLoad = stepOut.load * loadScale * contactEnv * flankDrop;+ const effRad = strandRad * (0.58 + 0.42 * contactEnv);+ const effHeight = stepOut.height * contactEnv * ridgeBreath;++ if (hasUnderBed && absOff < 0.84) {+ const normBand = ((rawOff / 0.84) * 0.5 + 0.5) * (BED_BANDS - 1);+ const bi = Math.max(0, Math.min(BED_BANDS - 1, Math.round(normBand)));+ bandR[bi] += stepOut.r;+ bandG[bi] += stepOut.g;+ bandB[bi] += stepOut.b;+ bandLoad[bi] += effLoad;+ bandAlpha[bi] += effAlpha;+ bandCount[bi]++;+ }++ if ((effAlpha > 0.003 || this.prevA[i] > 0.003) && strandDist > 0.05) {+ const base = segCount * BRISTLE_SEG_STRIDE;+ out[base + 0] = this.prevX[i];+ out[base + 1] = this.prevY[i];+ out[base + 2] = bx;+ out[base + 3] = by;+ out[base + 4] = this.prevR[i];+ out[base + 5] = this.prevG[i];+ out[base + 6] = this.prevB[i];+ out[base + 7] = this.prevA[i];+ out[base + 8] = stepOut.r;+ out[base + 9] = stepOut.g;+ out[base + 10] = stepOut.b;+ out[base + 11] = effAlpha;+ out[base + 12] = this.prevRadius[i];+ out[base + 13] = effRad;+ out[base + 14] = this.prevLoad[i];+ out[base + 15] = effLoad;+ out[base + 16] = this.prevHeight[i];+ out[base + 17] = effHeight;+ out[base + 18] = this.prevArcU[i];+ out[base + 19] = this.arcLength;+ out[base + 20] = rawOff;+ out[base + 21] = pressure;+ out[base + 22] = tiltMag;+ out[base + 23] = i;+ segCount++;++ const pad = Math.max(this.prevRadius[i], effRad) + 2;+ const xMin = Math.min(this.prevX[i], bx) - pad;+ const yMin = Math.min(this.prevY[i], by) - pad;+ const xMax = Math.max(this.prevX[i], bx) + pad;+ const yMax = Math.max(this.prevY[i], by) + pad;+ if (xMin < minX) minX = xMin;+ if (yMin < minY) minY = yMin;+ if (xMax > maxX) maxX = xMax;+ if (yMax > maxY) maxY = yMax;++ // Deposit behind the bristle's 5-tap sample cross so forward motion reads true underlying+ // canvas pigment without self-dilution, while loops/reversals pick up earlier passes+ if (sampler && this.config.naturalPaint.spatialMixing && effAlpha > 0.02 && strandDist > 0.45) {+ const depRad = Math.max(1, effRad * 0.35);+ const trailOff = Math.min(6, effRad * 0.65) + depRad + 0.5;+ const sTx = (bx - this.prevX[i]) / strandDist;+ const sTy = (by - this.prevY[i]) / strandDist;+ sampler.depositPointFast(+ this.prevX[i] - sTx * trailOff,+ this.prevY[i] - sTy * trailOff,+ depRad,+ stepOut.r,+ stepOut.g,+ stepOut.b,+ effAlpha * 0.35+ );+ }+ }++ this.prevX[i] = bx;+ this.prevY[i] = by;+ this.prevR[i] = stepOut.r;+ this.prevG[i] = stepOut.g;+ this.prevB[i] = stepOut.b;+ this.prevA[i] = effAlpha;+ this.prevRadius[i] = effRad;+ this.prevLoad[i] = effLoad;+ this.prevHeight[i] = effHeight;+ this.prevArcU[i] = this.arcLength;+ }++ // Fill reserved 7-band flat-ribbon under-bed slots (rasterize BEFORE the slice's bristles!)+ // Eliminates circular endcap halos & muddying while creating a solid spatial oil body!+ if (bedSlotStart >= 0) {+ const bedSpanMax = isKnife ? 0.88 : 0.72;+ const bandRad = Math.max(1.2, halfW * (isKnife ? 0.22 : 0.19));+ for (let b = 0; b < BED_BANDS; b++) {+ const uBand = (b / (BED_BANDS - 1)) * 2 - 1; // [-1..+1]+ const rawBandOff = uBand * bedSpanMax;+ let localBandSpan = rawBandOff * halfW;+ if (kappa * localBandSpan > 0 && Math.abs(localBandSpan) > maxInnerRadius) {+ const excess = Math.abs(localBandSpan) - maxInnerRadius;+ localBandSpan = Math.sign(localBandSpan) * Math.min(Math.abs(localBandSpan), maxInnerRadius + excess * 0.12);+ }+ const bx = cx + this.nx * localBandSpan;+ const by = cy + this.ny * localBandSpan;++ // Fallback to neighbor band if a band has zero bristles due to strong clumping+ let cnt = bandCount[b];+ let br = bandR[b];+ let bg = bandG[b];+ let bb = bandB[b];+ let bl = bandLoad[b];+ let ba = bandAlpha[b];+ if (cnt === 0) {+ for (let off = 1; off < BED_BANDS; off++) {+ if (b - off >= 0 && bandCount[b - off] > 0) {+ cnt = bandCount[b - off];+ br = bandR[b - off];+ bg = bandG[b - off];+ bb = bandB[b - off];+ bl = bandLoad[b - off];+ ba = bandAlpha[b - off];+ break;+ }+ if (b + off < BED_BANDS && bandCount[b + off] > 0) {+ cnt = bandCount[b + off];+ br = bandR[b + off];+ bg = bandG[b + off];+ bb = bandB[b + off];+ bl = bandLoad[b + off];+ ba = bandAlpha[b + off];+ break;+ }+ }+ }++ const invC = cnt > 0 ? 1 / cnt : 0;+ const rCur = br * invC;+ const gCur = bg * invC;+ const bCur = bb * invC;+ const lCur = bl * invC;+ const bandEntryDelay = Math.abs(uBand) * 0.28;+ const bedEntry = isKnife+ ? 1.0+ : Math.min(1.0, Math.max(0.0, (this.arcLength - entryZone * (0.25 + bandEntryDelay)) / Math.max(8, entryZone * 0.55)));+ // Under-bed lifts off smoothly as stylus pressure drops so light strokes blend softly+ // while medium/firm strokes layer opaquely without harsh gaps+ const bedPressureLift = isKnife+ ? 1.0+ : Math.max(0.0, Math.min(1.0, (pressure - (0.18 + Math.abs(uBand) * 0.14)) / 0.3));+ const aCur = Math.min(0.98, ba * invC * (isKnife ? 0.98 : 0.94) * bedEntry * bedPressureLift);+ const base = (bedSlotStart + b) * BRISTLE_SEG_STRIDE;++ if (!this.bedInitialized) {+ this.prevBedX[b] = this.prevCenterX + this.nx * localBandSpan;+ this.prevBedY[b] = this.prevCenterY + this.ny * localBandSpan;+ this.prevBedR[b] = rCur;+ this.prevBedG[b] = gCur;+ this.prevBedB[b] = bCur;+ this.prevBedA[b] = isKnife ? aCur : 0;+ this.prevBedLoad[b] = isKnife ? lCur : 0;+ this.prevBedRad[b] = bandRad;+ }++ if (cnt > 0 && (aCur > 0.02 || this.prevBedA[b] > 0.02) && lCur > 0.04) {+ out[base + 0] = this.prevBedX[b];+ out[base + 1] = this.prevBedY[b];+ out[base + 2] = bx;+ out[base + 3] = by;+ out[base + 4] = this.prevBedR[b];+ out[base + 5] = this.prevBedG[b];+ out[base + 6] = this.prevBedB[b];+ out[base + 7] = this.prevBedA[b];+ out[base + 8] = rCur;+ out[base + 9] = gCur;+ out[base + 10] = bCur;+ out[base + 11] = aCur;+ out[base + 12] = this.prevBedRad[b];+ out[base + 13] = bandRad;+ out[base + 14] = this.prevBedLoad[b];+ out[base + 15] = lCur;+ out[base + 16] = this.prevBedLoad[b] * 0.36;+ out[base + 17] = lCur * 0.36;+ out[base + 18] = Math.max(0, this.arcLength - stepDist);+ out[base + 19] = this.arcLength;+ out[base + 20] = rawBandOff;+ out[base + 21] = pressure;+ out[base + 22] = tiltMag;+ out[base + 23] = -1; // Cohesive flat-ribbon under-bed marker++ const pad = bandRad + 2;+ if (Math.min(this.prevBedX[b], bx) - pad < minX) minX = Math.min(this.prevBedX[b], bx) - pad;+ if (Math.min(this.prevBedY[b], by) - pad < minY) minY = Math.min(this.prevBedY[b], by) - pad;+ if (Math.max(this.prevBedX[b], bx) + pad > maxX) maxX = Math.max(this.prevBedX[b], bx) + pad;+ if (Math.max(this.prevBedY[b], by) + pad > maxY) maxY = Math.max(this.prevBedY[b], by) + pad;+ } else {+ out[base + 7] = 0;+ out[base + 11] = 0;+ out[base + 23] = -1;+ }++ this.prevBedX[b] = bx;+ this.prevBedY[b] = by;+ this.prevBedR[b] = rCur;+ this.prevBedG[b] = gCur;+ this.prevBedB[b] = bCur;+ this.prevBedA[b] = aCur;+ this.prevBedLoad[b] = lCur;+ this.prevBedRad[b] = bandRad;+ }+ this.bedInitialized = true;+ }++ this.prevCenterX = cx;+ this.prevCenterY = cy;+ }++ return {+ data: this.segBuffer,+ count: segCount,+ minX,+ minY,+ maxX,+ maxY,+ };+ }++ public finishStroke(): void {+ this.reservoir.persistDirtyStateIfNeeded();+ }+}diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.tsindex 5afd505..9bbed89 100644--- a/src/engine/BrushEngine.ts+++ b/src/engine/BrushEngine.ts@@ -11,6 +11,13 @@ import {Point,BrushSettings,BrushDynamics,+ BrushRenderMode,+ BristleSettings,+ GrainMappingMode,+ ImpastoSettings,+ NaturalMixingMode,+ NaturalPaintSettings,+ SurfaceTextureId,ToolType,CanvasColorMode,CspSensorConfig,@@ -31,6 +38,7 @@ import {rgbToHex,} from '../utils/colorMixingEngine';import { GpuDab, WebGlBrushEngine } from './WebGlBrushEngine';+import { isNaturalPaintBrush, renderCompleteNaturalPaintStroke } from './NaturalPaintRenderer';// ============================================================================// 1. Types & Unified Brush Render Options@@ -65,6 +73,11 @@ export interface BrushRenderOptions {sizeSensor?: CspSensorConfig;opacitySensor?: CspSensorConfig;densitySensor?: CspSensorConfig;+ bristleSplaySensor?: CspSensorConfig;+ paintLoadSensor?: CspSensorConfig;+ grainPenetrationSensor?: CspSensorConfig;+ angleSensor?: CspSensorConfig;+ scatterSensor?: CspSensorConfig;subTips?: CspSubTip[];subTipOrder?: 'random' | 'sequential' | 'direction' | 'reverse';subTipImages?: HTMLImageElement[];@@ -75,13 +88,15 @@ export interface BrushRenderOptions {amountOfPaint?: number;densityOfPaint?: number;colorStretch?: number;- mixingMode?: 'blend' | 'running_color' | 'smear';+ mixingMode?: NaturalMixingMode;wetEdge?: number;wetEdgeRadius?: number;wetEdgeAlphaPower?: number;wetEdgeValuePower?: number;grain?: number;textureDensity?: number;+ surfaceTextureId?: SurfaceTextureId;+ grainMappingMode?: GrainMappingMode;paperTextureMode?: CspPaperTextureMode;paperTextureBrightness?: number;paperTextureContrast?: number;@@ -92,6 +107,15 @@ export interface BrushRenderOptions {dualBrush?: boolean;dualTipImage?: HTMLImageElement;dualBrushCompositeMode?: string;+ dualScale?: number;+ dualAngle?: number;+ dualScatter?: number;+ dualSurfaceTextureId?: SurfaceTextureId;+ dualGrainDepth?: number;+ renderMode?: BrushRenderMode;+ bristle?: BristleSettings;+ naturalPaint?: NaturalPaintSettings;+ impasto?: ImpastoSettings;useGpu?: boolean;underlyingCanvas?: HTMLCanvasElement;sampler?: LayerPixelSampler;@@ -456,7 +480,9 @@ export function evaluateCspSensor(pressure: number,tiltMagnitude: number,speedPxPerMs: number,- randomVal: number+ randomVal: number,+ twistDeg: number = 0,+ strokeDistPx: number = 0): number {if (!sensor) return 1.0;@@ -472,12 +498,23 @@ export function evaluateCspSensor(const tMin = Math.max(0, Math.min(1, sensor.tiltMin ?? 0));factor *= tMin + (1.0 - tMin) * Math.max(0, Math.min(1, tiltMagnitude));}+ if (sensor.useBarrelTwist) {+ const twMin = Math.max(0, Math.min(1, sensor.twistMin ?? 0));+ const twNorm = (((twistDeg % 360) + 360) % 360) / 360;+ factor *= twMin + (1.0 - twMin) * twNorm;+ }if (sensor.useVelocity) {const vMin = Math.max(0, Math.min(1, sensor.velocityMin ?? 0));const vNorm = Math.max(0, Math.min(1, speedPxPerMs / 3.5));const vVal = sensor.invertVelocity !== false ? 1.0 - vNorm : vNorm;factor *= vMin + (1.0 - vMin) * vVal;}+ if (sensor.useDistance) {+ const dMin = Math.max(0, Math.min(1, sensor.distanceMin ?? 0));+ const maxDist = Math.max(10, sensor.distanceMaxPx ?? 600);+ const dNorm = Math.max(0, Math.min(1, 1.0 - strokeDistPx / maxDist));+ factor *= dMin + (1.0 - dMin) * dNorm;+ }if (sensor.useRandom) {const rMin = Math.max(0, Math.min(1, sensor.randomMin ?? 0));factor *= rMin + (1.0 - rMin) * Math.max(0, Math.min(1, randomVal));@@ -833,6 +870,12 @@ export function applyColorDynamics([r, g, b] = hsvToRgb(h, s, v);}+ if (dynamics.temperatureJitter && dynamics.temperatureJitter > 0) {+ const shift = (rng() * 2 - 1) * dynamics.temperatureJitter * 0.22;+ r = Math.max(0, Math.min(1, r + shift));+ b = Math.max(0, Math.min(1, b - shift));+ }+r = Math.max(0, Math.min(1, r));g = Math.max(0, Math.min(1, g));b = Math.max(0, Math.min(1, b));@@ -1318,6 +1361,25 @@ export function drawSingleStamp(if (antiAlias === 0 && prevSmooth !== false) ctx.imageSmoothingEnabled = prevSmooth;}+function selectTipIndex(+ tipImages: HTMLImageElement[] | undefined,+ order: 'random' | 'sequential' | 'direction' | 'reverse' = 'sequential',+ dabIndex: number = 0,+ tangentAngle: number = 0,+ x: number = 0,+ y: number = 0+): number {+ if (!tipImages || tipImages.length <= 1) return 0;+ const count = tipImages.length;+ if (order === 'random') return Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count;+ if (order === 'reverse') return (count - 1 - (dabIndex % count)) % count;+ if (order === 'direction') {+ const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);+ return Math.floor((normAngle / (2 * Math.PI)) * count) % count;+ }+ return dabIndex % count;+}+function selectTipImage(tipImages: HTMLImageElement[] | undefined,fallbackTip: HTMLImageElement,@@ -1330,14 +1392,8 @@ function selectTipImage(if (!tipImages || tipImages.length <= 1) {return tipImages && tipImages.length === 1 ? tipImages[0] : fallbackTip;}- const count = tipImages.length;- if (order === 'random') return tipImages[Math.floor(dabHashFloat(x, y, dabIndex, 97) * count) % count];- if (order === 'reverse') return tipImages[(count - 1 - (dabIndex % count)) % count];- if (order === 'direction') {- const normAngle = ((tangentAngle % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);- return tipImages[Math.floor((normAngle / (2 * Math.PI)) * count) % count];- }- return tipImages[dabIndex % count];+ const idx = selectTipIndex(tipImages, order, dabIndex, tangentAngle, x, y);+ return tipImages[idx] ?? fallbackTip;}let _invertedGrainCanvas: HTMLCanvasElement | null = null;@@ -1471,7 +1527,14 @@ export function canUseWebGlForBrush(options?: BrushRenderOptions): boolean {if (options.useGpu === false) return false;if (options.colorMixing) return false;if ((options.antiAlias ?? 2) === 0) return false;- if (options.tipImage && options.subTipImages && options.subTipImages.length > 1) return false;+ if (+ options.renderMode === 'bristle-ribbon' ||+ options.renderMode === 'bristle-hybrid' ||+ options.naturalPaint?.enabled ||+ options.impasto?.enabled+ ) {+ return false;+ }return WebGlBrushEngine.getInstance().isAvailable();}@@ -1503,6 +1566,8 @@ export function flushGpuDabs(wetEdge: options.wetEdge ?? 0,grain: options.grain ?? options.textureDensity ?? 0,textureDensity: options.textureDensity,+ surfaceTextureId: options.surfaceTextureId,+ grainMappingMode: options.grainMappingMode,paperTextureMode: options.paperTextureMode,paperTextureBrightness: options.paperTextureBrightness,paperTextureContrast: options.paperTextureContrast,@@ -1513,9 +1578,14 @@ export function flushGpuDabs(customTipImage: options.tipImage,isColorTip: options.isColorTip,subTips: options.subTips,+ subTipImages: options.subTipImages,dualBrush: options.dualBrush,dualTipImage: options.dualTipImage,dualBrushCompositeMode: options.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode'],+ dualScale: options.dualScale,+ dualAngle: options.dualAngle,+ dualScatter: options.dualScatter,+ naturalPaint: options.naturalPaint,colorMixing: false,isTransparentInk: Boolean(options.isTransparentInk),alphaLocked: Boolean(options.alphaLocked),@@ -1573,7 +1643,10 @@ function sampleAndMixColor(pressure: number,flow: number,stepDist: number,- options: BrushRenderOptions+ options: BrushRenderOptions,+ spacingRatio: number = 0.08,+ dirX: number = 0,+ dirY: number = 0): { colorHex: string; alpha: number; r: number; g: number; b: number } {const reservoir = options.reservoir!;let sampled = { r: 255, g: 255, b: 255, a: 0 };@@ -1587,6 +1660,10 @@ function sampleAndMixColor(}}+ const pressureAlreadyApplied = Boolean(+ options.opacitySensor?.usePressure || options.densitySensor?.usePressure+ );+const mixed = reservoir.mixWithCanvas(sampled,options.amountOfPaint ?? 0.65,@@ -1596,13 +1673,28 @@ function sampleAndMixColor(pressure,flow,stepDist,- options.perceptualMixing !== false+ options.perceptualMixing !== false,+ pressureAlreadyApplied);- if (options.sampler && mixed.alpha > 0.002) {- options.sampler.depositDab(x, y, radius, mixed.r, mixed.g, mixed.b, mixed.alpha);+ // Spacing-aware alpha normalization for dense mixing strokes: prevents hard opaque walls+ // at low/medium density or light pressure so transitions glaze & blend smoothly!+ let effectiveAlpha = mixed.alpha;+ if (stepDist > 0 && effectiveAlpha > 0.002 && effectiveAlpha < 0.99 && spacingRatio < 0.2) {+ const overlapExp = Math.max(0.18, Math.min(1.0, spacingRatio * 4.5));+ effectiveAlpha = Math.max(0.004, Math.min(1.0, 1.0 - Math.pow(1.0 - effectiveAlpha, overlapExp)));}- return mixed;++ // Deposit strictly behind the sample radius so forward motion reads true underlying canvas+ // (never bulldozing paint ahead or faking canvas alpha on blank canvas), while loops/reversals mix cleanly+ if (options.sampler && effectiveAlpha > 0.002 && (dirX !== 0 || dirY !== 0)) {+ const depRad = Math.max(1, radius * 0.32);+ const trailOffset = radius + depRad + 0.5;+ const depX = x - dirX * trailOffset;+ const depY = y - dirY * trailOffset;+ options.sampler.depositDab(depX, depY, depRad, mixed.r, mixed.g, mixed.b, effectiveAlpha * 0.45);+ }+ return { ...mixed, alpha: effectiveAlpha };}/**@@ -2007,7 +2099,21 @@ export function drawBrushCubicBezierSegment(if (isColorMixing && options.reservoir) {const prelimStep = Math.max(0.15, curWidth * spacingRatio);- const mixed = sampleAndMixColor(ctx, pt.x, pt.y, curWidth * 0.45, effPressure, dabAlpha, prelimStep, options);+ const dirX = pt.speed > 0.001 ? pt.dx / pt.speed : 0;+ const dirY = pt.speed > 0.001 ? pt.dy / pt.speed : 0;+ const mixed = sampleAndMixColor(+ ctx,+ pt.x,+ pt.y,+ curWidth * 0.45,+ effPressure,+ dabAlpha,+ prelimStep,+ options,+ spacingRatio,+ dirX,+ dirY+ );dabColor = mixed.colorHex;dabAlpha = mixed.alpha;if (gpuDabs) {@@ -2030,6 +2136,9 @@ export function drawBrushCubicBezierSegment();}+ const activeTipIdx = tipImage+ ? selectTipIndex(options.subTipImages, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y)+ : 0;const activeTip = tipImage? selectTipImage(options.subTipImages, tipImage, options.subTipOrder, dabSeq, stampAngle, pt.x, pt.y): undefined;@@ -2148,7 +2257,7 @@ export function drawBrushCubicBezierSegment(gpuDabs.push({x: spX, y: spY, width: spW, height: spH, angle: curDabAngle,r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,- strokeDist, flipX: flips.signX, flipY: flips.signY,+ strokeDist, flipX: flips.signX, flipY: flips.signY, tipIndex: activeTipIdx,});} else if (curMaster) {drawSingleStamp(@@ -2162,7 +2271,7 @@ export function drawBrushCubicBezierSegment(gpuDabs.push({x: curDabX, y: curDabY, width: finalW, height: finalH, angle: curDabAngle,r: dabR, g: dabG, b: dabB, alpha: curDabAlpha, pressure: grainPressure,- strokeDist, flipX: flips.signX, flipY: flips.signY,+ strokeDist, flipX: flips.signX, flipY: flips.signY, tipIndex: activeTipIdx,});} else if (curMaster) {drawSingleStamp(@@ -2259,6 +2368,11 @@ export function buildBrushRenderOptions(sizeSensor: bs.sizeSensor,opacitySensor: bs.opacitySensor,densitySensor: bs.densitySensor,+ bristleSplaySensor: bs.bristleSplaySensor,+ paintLoadSensor: bs.paintLoadSensor,+ grainPenetrationSensor: bs.grainPenetrationSensor,+ angleSensor: bs.angleSensor,+ scatterSensor: bs.scatterSensor,subTips: bs.subTips,subTipOrder: bs.subTipOrder,subTipImages: bs.subTipImages,@@ -2276,6 +2390,8 @@ export function buildBrushRenderOptions(wetEdgeValuePower: bs.wetEdgeValuePower,grain: bs.grain ?? bs.textureDensity,textureDensity: bs.textureDensity,+ surfaceTextureId: bs.surfaceTextureId,+ grainMappingMode: bs.grainMappingMode,paperTextureMode: bs.paperTextureMode,paperTextureBrightness: bs.paperTextureBrightness,paperTextureContrast: bs.paperTextureContrast,@@ -2286,6 +2402,15 @@ export function buildBrushRenderOptions(dualBrush: bs.dualBrush,dualTipImage: bs.dualTipImage,dualBrushCompositeMode: bs.dualBrushCompositeMode,+ dualScale: bs.dualScale,+ dualAngle: bs.dualAngle,+ dualScatter: bs.dualScatter,+ dualSurfaceTextureId: bs.dualSurfaceTextureId,+ dualGrainDepth: bs.dualGrainDepth,+ renderMode: bs.renderMode,+ bristle: bs.bristle,+ naturalPaint: bs.naturalPaint,+ impasto: bs.impasto,useGpu: bs.useGpu !== false,isTransparentInk: Boolean(bs.isTransparentInk),dynamics: bs.dynamics,@@ -2328,6 +2453,28 @@ export function renderCompleteStroke(const isEraser = tool === 'eraser';const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(resolvedSettings.color, colorMode);++ // Route Natural Paint / Bristle Ribbon / Impasto brushes through the dedicated Natural Paint core+ if (!isEraser && !isBgEraser && !isMono && !resolvedSettings.isTransparentInk && isNaturalPaintBrush(resolvedSettings)) {+ const effectiveUnderlying = underlyingCanvas || ctx.canvas;+ const natSampler =+ resolvedSettings.colorMixing !== false &&+ (resolvedSettings.colorMixing || resolvedSettings.naturalPaint?.spatialMixing)+ ? explicitSampler || (effectiveUnderlying ? new LayerPixelSampler(effectiveUnderlying) : undefined)+ : undefined;+ const compOp: GlobalCompositeOperation = alphaLocked ? 'source-atop' : 'source-over';+ renderCompleteNaturalPaintStroke(+ ctx,+ effectivePoints,+ resolvedSettings,+ strokeColor,+ natSampler,+ Math.max(0.01, Math.min(1.0, resolvedSettings.opacity ?? 1.0)),+ compOp+ );+ return;+ }+const strokeHardness = isMono ? 1.0 : resolvedSettings.hardness ?? 1.0;const strokeFlow = isMono ? 1.0 : resolvedSettings.flow ?? 1.0;const strokeSpacing = resolvedSettings.spacing ?? 0.08;diff --git a/src/engine/NaturalPaintRenderer.ts b/src/engine/NaturalPaintRenderer.tsnew file mode 100644index 0000000..cb6481b--- /dev/null+++ b/src/engine/NaturalPaintRenderer.ts@@ -0,0 +1,1287 @@+/**+ * NaturalPaintRenderer.ts+ * Sparse Dual-Channel (RGBA + Paint Heightmap) Natural Paint & Impasto Relief Engine.+ *+ * Implements:+ * 1. Continuous bristle strand capsule rasterization with cross-section groove profiles.+ * 2. Physical Paint-to-Canvas-Tooth interaction (valley fill at high load/pressure vs.+ * crisp valley-skipping dry-brush at low load/light pressure/tilt) across all 4+ * spatial grain mapping modes (`canvas-locked`, `brush-aligned`, `stroke-flow`, `random-per-stroke`).+ * 3. 3D Impasto Micro-Relief shading (3x3 Sobel normal derivation, directional diffuse ridge+ * lighting, Blinn-Phong gloss specular, valley micro-AO, and watercolor granulation/wet-edge).+ * 4. Identical live draft & pointer-up tile commit parity (zero visual pop on pointer-up).+ */++import type {+ BrushSettings,+ GrainMappingMode,+ ImpastoSettings,+ NaturalPaintSettings,+ Point,+ SurfaceTextureId,+} from '../types/editor';+import {+ DEFAULT_IMPASTO_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+} from '../types/editor';+import {+ getSurfaceTextureHeightField,+ sampleSurfaceTextureGrad,+ SURFACE_TEXELS_PER_PX,+ SURFACE_TEXTURE_SIZE,+} from '../utils/proceduralBrushTips';+import { LayerPixelSampler } from '../utils/colorMixingEngine';+import {+ BRISTLE_SEG_STRIDE,+ BristleRibbonEngine,+ BristleStrandBatch,+ extractBristleStrokeConfig,+} from './BristleRibbonEngine';+import { centripetalCatmullRomToBezier, evaluateFastSpline } from './BrushEngine';++const CHUNK_SIZE = 256;+const CHUNK_SHIFT = 8;+const CHUNK_MASK = CHUNK_SIZE - 1;+const CHUNK_PIXELS = CHUNK_SIZE * CHUNK_SIZE;++// Weak cache extracting luminance height fields from custom uploaded paper textures+const customTextureHeightCache = new WeakMap<+ HTMLImageElement,+ { data: Uint8Array; width: number; height: number }+>();++function getCustomTextureHeightField(+ img?: HTMLImageElement+): { data: Uint8Array; width: number; height: number } | null {+ if (!img || img.complete === false) return null;+ const w = img.naturalWidth || img.width || 0;+ const h = img.naturalHeight || img.height || 0;+ if (w <= 0 || h <= 0) return null;++ const hit = customTextureHeightCache.get(img);+ if (hit) return hit;++ if (typeof document === 'undefined') return null;+ try {+ const c = document.createElement('canvas');+ c.width = w;+ c.height = h;+ const ctx = c.getContext('2d', { willReadFrequently: true });+ if (!ctx) return null;+ ctx.drawImage(img, 0, 0, w, h);+ const pixels = ctx.getImageData(0, 0, w, h).data;+ const lum = new Uint8Array(w * h);+ for (let i = 0; i < w * h; i++) {+ const p = i * 4;+ const a = pixels[p + 3];+ const y = Math.round(pixels[p] * 0.299 + pixels[p + 1] * 0.587 + pixels[p + 2] * 0.114);+ lum[i] = a < 250 ? 255 - a : y;+ }+ const entry = { data: lum, width: w, height: h };+ customTextureHeightCache.set(img, entry);+ return entry;+ } catch {+ return null;+ }+}++export interface GrainSampleParams {+ mappingMode: GrainMappingMode;+ surfaceId: SurfaceTextureId;+ customTex: { data: Uint8Array; width: number; height: number } | null;+ dualSurfaceId?: SurfaceTextureId;+ dualGrainDepth: number;+ grainDepth: number;+ scale: number;+ rotateRad: number;+ contrast: number;+ brightness: number;+ inverted: boolean;+ strokeOffsetX: number;+ strokeOffsetY: number;+ strokeCos: number;+ strokeSin: number;+}++/**+ * Samples the surface elevation H_canvas in [0..1] for any spatial mapping mode.+ */+export function evaluateMappedSurfaceHeight(+ params: GrainSampleParams,+ worldX: number,+ worldY: number,+ arcU: number,+ acrossV: number,+ brushHalfWidth: number,+ segCos: number,+ segSin: number+): number {+ let sx = worldX;+ let sy = worldY;++ switch (params.mappingMode) {+ case 'brush-aligned': {+ // Map into brush-local coordinates aligned with the segment tangent/normal+ const lx = worldX * segCos + worldY * segSin;+ const ly = -worldX * segSin + worldY * segCos;+ sx = lx;+ sy = ly;+ break;+ }+ case 'stroke-flow': {+ // Continuous stroke UV: u = arcLength, v = across-width in pixels+ sx = arcU;+ sy = acrossV * Math.max(8, brushHalfWidth);+ break;+ }+ case 'random-per-stroke': {+ const rx = worldX * params.strokeCos - worldY * params.strokeSin + params.strokeOffsetX;+ const ry = worldX * params.strokeSin + worldY * params.strokeCos + params.strokeOffsetY;+ sx = rx;+ sy = ry;+ break;+ }+ case 'canvas-locked':+ default:+ break;+ }++ const invScale = 1.0 / Math.max(0.05, params.scale);+ let tx = sx * invScale;+ let ty = sy * invScale;++ if (Math.abs(params.rotateRad) > 1e-4) {+ const c = Math.cos(params.rotateRad);+ const s = Math.sin(params.rotateRad);+ const rx = tx * c - ty * s;+ const ry = tx * s + ty * c;+ tx = rx;+ ty = ry;+ }++ let g: number;+ if (params.customTex) {+ const { data, width, height } = params.customTex;+ const fx = Math.floor(tx);+ const fy = Math.floor(ty);+ const ix0 = ((fx % width) + width) % width;+ const iy0 = ((fy % height) + height) % height;+ const ix1 = (ix0 + 1) % width;+ const iy1 = (iy0 + 1) % height;+ const u = tx - fx;+ const v = ty - fy;+ const v00 = data[iy0 * width + ix0];+ const v10 = data[iy0 * width + ix1];+ const v01 = data[iy1 * width + ix0];+ const v11 = data[iy1 * width + ix1];+ g = (v00 + (v10 - v00) * u + ((v01 + (v11 - v01) * u) - (v00 + (v10 - v00) * u)) * v) / 255.0;+ } else {+ // High-DPI 2x oversampled texel coordinates with 2-tap rotated-grid anti-aliasing (zero moire!)+ const field = getSurfaceTextureHeightField(params.surfaceId);+ const mask = SURFACE_TEXTURE_SIZE - 1;+ const htx = tx * SURFACE_TEXELS_PER_PX;+ const hty = ty * SURFACE_TEXELS_PER_PX;++ // Sample tap A (-0.32, +0.24) and tap B (+0.32, -0.24) in 1024x1024 high-DPI space+ const ax = htx - 0.32;+ const ay = hty + 0.24;+ const afx = Math.floor(ax);+ const afy = Math.floor(ay);+ const au = ax - afx;+ const av = ay - afy;+ const ax0 = afx & mask;+ const ay0 = afy & mask;+ const ax1 = (afx + 1) & mask;+ const ay1 = (afy + 1) & mask;+ const rA0 = ay0 * SURFACE_TEXTURE_SIZE;+ const rA1 = ay1 * SURFACE_TEXTURE_SIZE;+ const a00 = field[rA0 + ax0];+ const a10 = field[rA0 + ax1];+ const a01 = field[rA1 + ax0];+ const a11 = field[rA1 + ax1];+ const gA = a00 + (a10 - a00) * au + ((a01 + (a11 - a01) * au) - (a00 + (a10 - a00) * au)) * av;++ const bx = htx + 0.32;+ const by = hty - 0.24;+ const bfx = Math.floor(bx);+ const bfy = Math.floor(by);+ const bu = bx - bfx;+ const bv = by - bfy;+ const bx0 = bfx & mask;+ const by0 = bfy & mask;+ const bx1 = (bfx + 1) & mask;+ const by1 = (bfy + 1) & mask;+ const rB0 = by0 * SURFACE_TEXTURE_SIZE;+ const rB1 = by1 * SURFACE_TEXTURE_SIZE;+ const b00 = field[rB0 + bx0];+ const b10 = field[rB0 + bx1];+ const b01 = field[rB1 + bx0];+ const b11 = field[rB1 + bx1];+ const gB = b00 + (b10 - b00) * bu + ((b01 + (b11 - b01) * bu) - (b00 + (b10 - b00) * bu)) * bv;++ g = (gA + gB) * (0.5 / 255.0);+ }++ if (params.dualSurfaceId && params.dualGrainDepth > 0.01) {+ const dualField = getSurfaceTextureHeightField(params.dualSurfaceId);+ const mask = SURFACE_TEXTURE_SIZE - 1;+ const dtx = tx * SURFACE_TEXELS_PER_PX * 1.35;+ const dty = ty * SURFACE_TEXELS_PER_PX * 1.35;+ const dx = Math.floor(dtx) & mask;+ const dy = Math.floor(dty) & mask;+ const dg = dualField[dy * SURFACE_TEXTURE_SIZE + dx] / 255.0;+ g = g * (1.0 - params.dualGrainDepth * 0.5) + dg * (params.dualGrainDepth * 0.5);+ }++ if (params.inverted) g = 1.0 - g;+ if (params.brightness !== 0) g += params.brightness / 100.0;+ if (params.contrast !== 0) {+ const cf = Math.pow(Math.max(0.05, 1.0 + params.contrast / 100.0), 2);+ g = (g - 0.5) * cf + 0.5;+ }+ return g <= 0 ? 0 : g >= 1 ? 1 : g;+}++/**+ * Physical "Paint <-> Canvas Tooth" contact evaluation.+ * - High paintLoad + strong pressure -> fills canvas valleys opaquely.+ * - Low paintLoad / light pressure / high tilt / dryBrush -> skips valleys and deposits+ * pigment only on raised weave crowns!+ */+export function evaluatePaintCanvasContact(+ canvasHeight: number,+ paintLoad: number,+ pressure: number,+ tiltMag: number,+ grainDepth: number,+ dryBrush: number,+ penetrationCurve?: [number, number][]+): number {+ if (grainDepth <= 0.005 && dryBrush <= 0.005) return 1.0;++ const curvedP = penetrationCurve+ ? evaluateFastSpline(pressure, penetrationCurve)+ : Math.max(0, Math.min(1, pressure));+ const load = Math.max(0, Math.min(1, paintLoad));++ // Heavy paint load & firm pressure push pigment deep into canvas valleys;+ // exhausted bristles, light pressure, or tilted strokes skim across peaks.+ const tiltReduction = 1.0 - Math.max(0, Math.min(1, tiltMag)) * 0.45;+ const penetration = Math.max(+ 0,+ Math.min(1, (curvedP * 0.50 + load * 0.50) * (0.38 + 0.62 * load) * tiltReduction)+ );++ // Soft, woven dry-brush transition across fine canvas threads (no harsh blocky checkerboard)+ const effectiveDry = Math.max(dryBrush, grainDepth * 0.68);+ const cutoff = effectiveDry * (1.0 - penetration * 0.84) * 0.76;+ const softness = 0.14 + (1.0 - effectiveDry) * 0.22;+ const t = Math.max(0, Math.min(1, (canvasHeight - cutoff) / Math.max(0.06, softness)));+ const smooth = t * t * (3.0 - 2.0 * t);++ // At high load & firm pressure, pigment cleanly fills canvas valleys for solid layering;+ // on dry edges/light strokes, weave peaks still catch crisp dry-brush texture+ const maskStrength = Math.max(+ 0,+ Math.min(1, grainDepth * (1.0 - penetration * 0.92) + dryBrush * (1.0 - load * 0.94))+ );+ return 1.0 - maskStrength + maskStrength * smooth;+}++interface PaintChunk {+ cx: number;+ cy: number;+ // Straight RGBA stored in Float32 for banding-free accumulation+ r: Float32Array;+ g: Float32Array;+ b: Float32Array;+ a: Float32Array;+ height: Float32Array;+ tooth: Float32Array;+ lastArcU: Float32Array;+ lastBristle: Int16Array;+}++const chunkPool: PaintChunk[] = [];+const MAX_CHUNK_POOL = 24;++function acquireChunk(cx: number, cy: number): PaintChunk {+ const recycled = chunkPool.pop();+ if (recycled) {+ recycled.cx = cx;+ recycled.cy = cy;+ recycled.r.fill(0);+ recycled.g.fill(0);+ recycled.b.fill(0);+ recycled.a.fill(0);+ recycled.height.fill(0);+ recycled.tooth.fill(0.5);+ recycled.lastArcU.fill(-9999);+ recycled.lastBristle.fill(-1);+ return recycled;+ }+ const tooth = new Float32Array(CHUNK_PIXELS);+ tooth.fill(0.5);+ const lastArcU = new Float32Array(CHUNK_PIXELS);+ lastArcU.fill(-9999);+ const lastBristle = new Int16Array(CHUNK_PIXELS);+ lastBristle.fill(-1);+ return {+ cx,+ cy,+ r: new Float32Array(CHUNK_PIXELS),+ g: new Float32Array(CHUNK_PIXELS),+ b: new Float32Array(CHUNK_PIXELS),+ a: new Float32Array(CHUNK_PIXELS),+ height: new Float32Array(CHUNK_PIXELS),+ tooth,+ lastArcU,+ lastBristle,+ };+}++function releaseChunk(chunk: PaintChunk): void {+ if (chunkPool.length < MAX_CHUNK_POOL) {+ chunkPool.push(chunk);+ }+}++/**+ * Checks whether a BrushSettings configuration should use the Natural Paint / Bristle Ribbon core.+ */+export function isNaturalPaintBrush(bs: Partial<BrushSettings> | undefined): boolean {+ if (!bs) return false;+ return Boolean(+ bs.renderMode === 'bristle-ribbon' ||+ bs.renderMode === 'bristle-hybrid' ||+ bs.naturalPaint?.enabled ||+ bs.impasto?.enabled+ );+}++/**+ * Computes directional 3D light unit vector from azimuth & elevation degrees.+ */+export function computeImpastoLightVector(+ azimuthDeg: number,+ elevationDeg: number+): { lx: number; ly: number; lz: number } {+ const az = (azimuthDeg * Math.PI) / 180;+ const el = (Math.max(5, Math.min(85, elevationDeg)) * Math.PI) / 180;+ const cosEl = Math.cos(el);+ const lx = Math.cos(az) * cosEl;+ const ly = Math.sin(az) * cosEl;+ const lz = Math.sin(el);+ const len = Math.hypot(lx, ly, lz) || 1;+ return { lx: lx / len, ly: ly / len, lz: lz / len };+}++/**+ * Stroke-scoped Natural Paint accumulator & relief shader.+ * Shared identically by live stroke streaming (draftCanvas), pointer-up tile commit,+ * Brush Studio scratchpad, and brush preview thumbnails.+ */+export class NaturalPaintStrokeSession {+ public readonly engine: BristleRibbonEngine;+ public readonly settings: BrushSettings;+ public readonly strokeColor: string;+ public readonly grainParams: GrainSampleParams;+ public readonly impasto: ImpastoSettings;+ public readonly natural: NaturalPaintSettings;+ public readonly wetEdge: number;+ public readonly granulation: number;++ private readonly chunks = new Map<number, PaintChunk>();+ private readonly chunkStrideX = 65536;+ private scratchCanvas: HTMLCanvasElement | null = null;+ private scratchCtx: CanvasRenderingContext2D | null = null;+ private pendingTapPoint: Point | null = null;+ private hasEmittedSegment: boolean = false;+ // Reusable Float32 scratch grids for smooth Sobel impasto relief & 3D cast-shadow ray-marching (zero GC!)+ private hGridRaw: Float32Array = new Float32Array(0);+ private hGridTmp: Float32Array = new Float32Array(0);+ private hGridSmooth: Float32Array = new Float32Array(0);+ private toothGrid: Float32Array = new Float32Array(0);++ public minX: number = Infinity;+ public minY: number = Infinity;+ public maxX: number = -Infinity;+ public maxY: number = -Infinity;++ constructor(+ settings: BrushSettings,+ strokeColor: string,+ totalLength?: number,+ strokeSeed: number = 1337+ ) {+ this.settings = settings;+ this.strokeColor = strokeColor;+ const cfg = extractBristleStrokeConfig(settings, strokeColor, totalLength, strokeSeed);+ this.engine = new BristleRibbonEngine(cfg);+ this.impasto = {+ ...DEFAULT_IMPASTO_SETTINGS,+ ...(settings.impasto || {}),+ };+ this.natural = {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ ...(settings.naturalPaint || {}),+ };+ this.wetEdge = Math.max(0, Math.min(1, settings.wetEdge ?? 0));+ this.granulation = Math.max(0, Math.min(1, settings.naturalPaint?.granulation ?? 0));++ // Deterministic per-stroke offset/rotation for 'random-per-stroke' grain mapping+ const s1 = ((strokeSeed * 1664525 + 1013904223) >>> 0) / 4294967296;+ const s2 = ((strokeSeed * 22695477 + 1) >>> 0) / 4294967296;+ const s3 = ((strokeSeed * 1103515245 + 12345) >>> 0) / 4294967296;+ const randRot = s3 * Math.PI * 2;++ this.grainParams = {+ mappingMode: settings.grainMappingMode ?? 'canvas-locked',+ surfaceId: settings.surfaceTextureId ?? 'linen-canvas',+ customTex: getCustomTextureHeightField(settings.paperTextureImage),+ dualSurfaceId: settings.dualSurfaceTextureId,+ dualGrainDepth: Math.max(0, Math.min(1, settings.dualGrainDepth ?? 0)),+ grainDepth: Math.max(0, Math.min(1, settings.grain ?? settings.textureDensity ?? 0)),+ scale: Math.max(0.1, settings.paperTextureScale ?? 1.0),+ rotateRad: ((settings.paperTextureRotate ?? 0) * Math.PI) / 180,+ contrast: settings.paperTextureContrast ?? 0,+ brightness: settings.paperTextureBrightness ?? 0,+ inverted: Boolean(settings.paperTextureInverted),+ strokeOffsetX: s1 * SURFACE_TEXTURE_SIZE,+ strokeOffsetY: s2 * SURFACE_TEXTURE_SIZE,+ strokeCos: Math.cos(randRot),+ strokeSin: Math.sin(randRot),+ };+ }++ private getOrCreateChunk(cx: number, cy: number): PaintChunk {+ const key = cy * this.chunkStrideX + cx;+ let ch = this.chunks.get(key);+ if (!ch) {+ ch = acquireChunk(cx, cy);+ this.chunks.set(key, ch);+ }+ return ch;+ }++ private getChunk(cx: number, cy: number): PaintChunk | undefined {+ return this.chunks.get(cy * this.chunkStrideX + cx);+ }++ private sampleAccumHeight(x: number, y: number): { hPaint: number; tooth: number; alpha: number } {+ const cx = x >> CHUNK_SHIFT;+ const cy = y >> CHUNK_SHIFT;+ const ch = this.getChunk(cx, cy);+ if (!ch) return { hPaint: 0, tooth: 0.5, alpha: 0 };+ const idx = ((y & CHUNK_MASK) << CHUNK_SHIFT) + (x & CHUNK_MASK);+ return { hPaint: ch.height[idx], tooth: ch.tooth[idx], alpha: ch.a[idx] };+ }++ /**+ * Rasterizes a batch of continuous bristle strand capsules into the sparse RGBA + Height chunks.+ */+ public rasterizeBatch(batch: BristleStrandBatch): { minX: number; minY: number; maxX: number; maxY: number } | null {+ if (batch.count <= 0) return null;+ const data = batch.data;+ const grainDepth = this.grainParams.grainDepth;+ const dryBrush = this.natural.dryBrush;+ const penCurve = this.natural.penetrationCurve;+ const bristleRelief = this.impasto.enabled ? this.impasto.bristleRelief : 0.4;+ const halfBrushW = Math.max(2, (this.settings.size || 24) * 0.5);++ let dMinX = Infinity;+ let dMinY = Infinity;+ let dMaxX = -Infinity;+ let dMaxY = -Infinity;++ for (let s = 0; s < batch.count; s++) {+ const base = s * BRISTLE_SEG_STRIDE;+ const a0 = data[base + 7];+ const a1 = data[base + 11];+ if (a0 <= 0.002 && a1 <= 0.002) continue;++ const x0 = data[base + 0];+ const y0 = data[base + 1];+ const x1 = data[base + 2];+ const y1 = data[base + 3];+ const r0 = data[base + 4];+ const g0 = data[base + 5];+ const b0 = data[base + 6];+ const r1 = data[base + 8];+ const g1 = data[base + 9];+ const b1 = data[base + 10];+ const rad0 = data[base + 12];+ const rad1 = data[base + 13];+ const load0 = data[base + 14];+ const load1 = data[base + 15];+ const h0 = data[base + 16];+ const h1 = data[base + 17];+ const arcU0 = data[base + 18];+ const arcU1 = data[base + 19];+ const acrossV = data[base + 20];+ const pressure = data[base + 21];+ const tiltMag = data[base + 22];+ const bristleIdx = data[base + 23] | 0;+ const isUnderBed = bristleIdx < 0;++ const maxRad = Math.max(rad0, rad1, 0.75);+ const pad = Math.ceil(maxRad + 1.5);+ const bx0 = Math.floor(Math.min(x0, x1) - pad);+ const by0 = Math.floor(Math.min(y0, y1) - pad);+ const bx1 = Math.ceil(Math.max(x0, x1) + pad);+ const by1 = Math.ceil(Math.max(y0, y1) + pad);++ if (bx0 < dMinX) dMinX = bx0;+ if (by0 < dMinY) dMinY = by0;+ if (bx1 > dMaxX) dMaxX = bx1;+ if (by1 > dMaxY) dMaxY = by1;++ const sdx = x1 - x0;+ const sdy = y1 - y0;+ const lenSq = sdx * sdx + sdy * sdy;+ const segLen = Math.sqrt(lenSq);+ const invLenSq = lenSq > 1e-6 ? 1.0 / lenSq : 0;+ const segCos = segLen > 1e-4 ? sdx / segLen : 1;+ const segSin = segLen > 1e-4 ? sdy / segLen : 0;+ const selfPassWindow = Math.max(14, halfBrushW * 0.9);++ for (let py = by0; py <= by1; py++) {+ const cy = py >> CHUNK_SHIFT;+ const lyOff = (py & CHUNK_MASK) << CHUNK_SHIFT;+ const dy0 = py + 0.5 - y0;++ for (let px = bx0; px <= bx1; px++) {+ const dx0 = px + 0.5 - x0;+ let t = lenSq > 1e-6 ? (dx0 * sdx + dy0 * sdy) * invLenSq : 0;+ if (t < 0) t = 0;+ else if (t > 1) t = 1;++ const cxPt = x0 + sdx * t;+ const cyPt = y0 + sdy * t;+ const dist = Math.hypot(px + 0.5 - cxPt, py + 0.5 - cyPt);+ const rad = rad0 + (rad1 - rad0) * t;+ if (dist >= rad + 0.85) continue;++ const normD = dist / Math.max(0.5, rad);+ const load = load0 + (load1 - load0) * t;+ const arcU = arcU0 + (arcU1 - arcU0) * t;++ let baseAlpha: number;+ let grooveCrown: number;+ let troughCarve = 0;+ let effLoadForTooth = load;++ if (isUnderBed) {+ // Cohesive creamy paint cushion: opaque inside core (normD < 0.68), feathered softly across linen flanks+ const flankT = Math.max(0, Math.min(1, (normD - 0.62) / 0.38));+ const coreEnv = 1.0 - flankT * flankT * (3.0 - 2.0 * flankT);+ baseAlpha = (a0 + (a1 - a0) * t) * coreEnv;+ grooveCrown = 0.55 + 0.45 * coreEnv;+ effLoadForTooth = load * (0.28 + 0.72 * coreEnv);+ } else {+ // Sculpted rounded cylindrical bristle ridge + recessed outer furrow carving!+ // Low-relief brushes get slightly wider creamy edge feathering for seamless blending+ const edgeSoft = Math.max(1.25, Math.min(2.5, 1.4 + (1.0 - bristleRelief) * 1.0));+ const aaEdge = 1.0 - Math.max(0, Math.min(1, (dist - (rad - edgeSoft * 0.5)) / edgeSoft));+ grooveCrown = Math.pow(Math.max(0, 1.0 - normD * normD), 0.72);+ // Outer shoulder of a bristle (0.62 < normD < 0.98) gently carves a 3D furrow into the wet paint bed+ if (normD > 0.6 && normD < 0.98) {+ const tt = (normD - 0.6) / 0.38;+ troughCarve = Math.sin(tt * Math.PI) * bristleRelief * 0.42;+ }+ baseAlpha = (a0 + (a1 - a0) * t) * aaEdge;+ }+ if (baseAlpha <= 0.002) continue;++ // Sample spatial canvas tooth height H_canvas(x, y)+ const hCanvas = evaluateMappedSurfaceHeight(+ this.grainParams,+ px + 0.5,+ py + 0.5,+ arcU,+ acrossV,+ halfBrushW,+ segCos,+ segSin+ );++ const toothContact = evaluatePaintCanvasContact(+ hCanvas,+ effLoadForTooth,+ pressure,+ tiltMag,+ grainDepth,+ dryBrush,+ penCurve+ );++ const srcA = baseAlpha * toothContact;+ if (srcA <= 0.002) continue;++ const ch = this.getOrCreateChunk(px >> CHUNK_SHIFT, cy);+ const idx = lyOff + (px & CHUNK_MASK);++ const sr = r0 + (r1 - r0) * t;+ const sg = g0 + (g1 - g0) * t;+ const sb = b0 + (b1 - b0) * t;++ const prevArc = ch.lastArcU[idx];+ const prevBr = ch.lastBristle[idx];+ const isSamePass = prevArc > -9000 && Math.abs(arcU - prevArc) < selfPassWindow;+ const isSameBristle = isSamePass && prevBr === bristleIdx;++ // Continuous strand height: under-bed lays flat cushion; bristles pile thick sculpted crests on top!+ const rawH = h0 + (h1 - h0) * t;+ const strandH = isUnderBed+ ? rawH * grooveCrown * (0.45 + 0.55 * toothContact)+ : rawH * (0.12 + 1.05 * grooveCrown * (0.42 + 0.58 * bristleRelief)) * (0.35 + 0.65 * toothContact);++ const dstA = ch.a[idx];+ if (isUnderBed) {+ if (isSamePass) {+ // Under-bed never overwrites individual bristle colors or tall sculpted ridges on the same pass!+ if (srcA > dstA) {+ const fillW = (srcA - dstA) / Math.max(0.001, srcA);+ if (prevBr < 0) {+ ch.r[idx] = sr;+ ch.g[idx] = sg;+ ch.b[idx] = sb;+ } else {+ ch.r[idx] = ch.r[idx] * (1 - fillW) + sr * fillW;+ ch.g[idx] = ch.g[idx] * (1 - fillW) + sg * fillW;+ ch.b[idx] = ch.b[idx] * (1 - fillW) + sb * fillW;+ }+ ch.a[idx] = srcA;+ }+ if (strandH > ch.height[idx]) {+ ch.height[idx] = strandH;+ }+ } else {+ // Fresh pass under-bed lays down a fresh wet paint cushion over any older stroke+ const depositA = Math.min(1.0, srcA * 0.94);+ const outA = depositA + dstA * (1.0 - depositA);+ if (outA > 0.0005) {+ const invOut = 1.0 / outA;+ ch.r[idx] = (sr * depositA + ch.r[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.g[idx] = (sg * depositA + ch.g[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.b[idx] = (sb * depositA + ch.b[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.a[idx] = outA;+ }+ ch.height[idx] = ch.height[idx] * (1.0 - depositA * 0.72) + strandH * (0.28 + depositA * 0.72);+ ch.lastBristle[idx] = -1;+ }+ } else if (isSameBristle) {+ // Same bristle continuing across consecutive slice joint -> strictly max envelope (zero dots!)+ if (srcA > dstA) {+ ch.r[idx] = sr;+ ch.g[idx] = sg;+ ch.b[idx] = sb;+ ch.a[idx] = srcA;+ }+ if (strandH > ch.height[idx]) {+ ch.height[idx] = strandH;+ }+ } else if (isSamePass) {+ // Individual bristle writing over the under-bed (prevBr === -1) or neighboring tuft in same sweep!+ const overBed = prevBr < 0;+ const targetA = Math.min(1.0, Math.max(dstA, srcA) + Math.min(dstA, srcA) * (overBed ? 0.35 : 0.25));+ if (targetA > 0.0005) {+ // Bristle's spatially-picked-up color dominates cleanly over the generic under-bed average!+ const blendW = overBed+ ? Math.min(0.92, srcA * 1.15)+ : srcA / Math.max(0.001, srcA + dstA);+ ch.r[idx] = ch.r[idx] * (1 - blendW) + sr * blendW;+ ch.g[idx] = ch.g[idx] * (1 - blendW) + sg * blendW;+ ch.b[idx] = ch.b[idx] * (1 - blendW) + sb * blendW;+ ch.a[idx] = targetA;+ }+ if (overBed) {+ // Pile sculpted crest up above the cushion, OR carve a recessed furrow along the bristle's shoulder!+ const sculptedH =+ troughCarve > 0.01+ ? Math.max(ch.height[idx] * (1.0 - troughCarve), strandH)+ : Math.max(ch.height[idx], ch.height[idx] * 0.42 + strandH);+ ch.height[idx] = sculptedH;+ if (grooveCrown > 0.25) ch.lastBristle[idx] = bristleIdx;+ } else {+ if (troughCarve > 0.01 && strandH < ch.height[idx]) {+ ch.height[idx] *= 1.0 - troughCarve * 0.35;+ } else if (strandH > ch.height[idx]) {+ ch.height[idx] = strandH;+ ch.lastBristle[idx] = bristleIdx;+ }+ }+ } else {+ // Fresh brush pass crossing over an earlier stroke pass -> carve fresh 3D ridges on top!+ const depositA = Math.min(1.0, srcA * 0.94);+ const outA = depositA + dstA * (1.0 - depositA);+ if (outA > 0.0005) {+ const invOut = 1.0 / outA;+ ch.r[idx] = (sr * depositA + ch.r[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.g[idx] = (sg * depositA + ch.g[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.b[idx] = (sb * depositA + ch.b[idx] * dstA * (1.0 - depositA)) * invOut;+ ch.a[idx] = outA;+ }+ ch.height[idx] = ch.height[idx] * (1.0 - depositA * 0.78) + strandH * (0.22 + depositA * 0.85);+ ch.lastBristle[idx] = bristleIdx;+ }++ ch.lastArcU[idx] = arcU;+ ch.tooth[idx] = hCanvas;+ }+ }+ }++ if (dMinX < this.minX) this.minX = dMinX;+ if (dMinY < this.minY) this.minY = dMinY;+ if (dMaxX > this.maxX) this.maxX = dMaxX;+ if (dMaxY > this.maxY) this.maxY = dMaxY;++ return { minX: dMinX, minY: dMinY, maxX: dMaxX, maxY: dMaxY };+ }++ /**+ * Shades a rectangular region of the stroke buffer into RGBA `ImageData` applying:+ * - Pre-smoothed Float32 height grid (silky, sculptural oil ridges with zero pixel grit!)+ * - 3D Impasto Relief Lighting (3x3 Sobel normals, directional diffuse, rich chromatic shadows,+ * 2-lobe oil gloss specular, warm studio key lift for dark pigments, and bristle-valley micro-AO)+ * - Canvas weave buried under thick oil and revealed crisply on thin outer fringes / dry-brush+ * - Watercolor paper-valley granulation & wet-edge rim darkening+ */+ public shadeRectToBuffer(+ rx: number,+ ry: number,+ rw: number,+ rh: number,+ outRgba: Uint8ClampedArray+ ): void {+ const impastoOn = this.impasto.enabled && this.impasto.depth > 0.01;+ const impDepth = this.impasto.depth;+ const impGloss = this.impasto.gloss;+ const impContrast = this.impasto.reliefContrast;+ const grainDepth = this.grainParams.grainDepth;+ const granStrength = this.granulation;+ const wetEdgeStrength = this.wetEdge;++ const { lx, ly, lz } = computeImpastoLightVector(+ this.impasto.lightAzimuth,+ this.impasto.lightElevation+ );+ // Blinn-Phong half-vector for view V = (0, 0, 1)+ const hx = lx;+ const hy = ly;+ const hz = lz + 1.0;+ const hLen = Math.hypot(hx, hy, hz) || 1;+ const nhx = hx / hLen;+ const nhy = hy / hLen;+ const nhz = hz / hLen;++ const reliefScale = 4.6 + impDepth * 9.2;+ const toothReliefScale = (2.2 + grainDepth * 5.2) * (0.55 + impContrast * 0.65);+ const satinExp = 10 + impGloss * 11;+ const glossExp = 30 + impGloss * 46;+ const satinAmp = (0.12 + impGloss * 0.24) * (0.45 + impDepth * 0.6);+ const glossAmp = impGloss * (0.24 + impDepth * 0.44);+ const diffAmp = 0.36 + impContrast * 0.52;++ // Horizontal directional light unit vector & calibrated raking ray slope for real 3D heightfield cast shadows!+ const horizLen = Math.hypot(lx, ly) || 1;+ const dlx = lx / horizLen;+ const dly = ly / horizLen;+ // Lower raking ray slope lets 3D impasto ridges physically cast crisp 2-9px shadows into grooves & onto canvas!+ const raySlope = (lz / horizLen) * 0.088;++ // Pre-build dual-frequency Float32 grids (gw x gh with 10px border for 8-tap directional cast shadow reach!)+ const border = impastoOn ? 10 : 2;+ const gw = rw + border * 2;+ const gh = rh + border * 2;+ let smoothPaintH: Float32Array | null = null;+ let rawToothGrid: Float32Array | null = null;+ if (impastoOn) {+ const needed = gw * gh;+ if (this.hGridRaw.length < needed) {+ this.hGridRaw = new Float32Array(needed);+ this.hGridTmp = new Float32Array(needed);+ this.hGridSmooth = new Float32Array(needed);+ this.toothGrid = new Float32Array(needed);+ }+ const rawH = this.hGridRaw;+ const tmpH = this.hGridTmp;+ smoothPaintH = this.hGridSmooth;+ rawToothGrid = this.toothGrid;++ // Stage 1: Single-lookup dual-channel extraction:+ // - rawH: pure sculptural paint thickness (zero weave blur contamination!)+ // - rawToothGrid: unblurred high-DPI surface weave fallback+ for (let gy = 0; gy < gh; gy++) {+ const wy = ry + gy - border;+ const cy = wy >> CHUNK_SHIFT;+ const lyOff = (wy & CHUNK_MASK) << CHUNK_SHIFT;+ const rowOff = gy * gw;+ for (let gx = 0; gx < gw; gx++) {+ const wx = rx + gx - border;+ const ch = this.getChunk(wx >> CHUNK_SHIFT, cy);+ if (!ch) {+ rawH[rowOff + gx] = 0;+ rawToothGrid[rowOff + gx] = 0.5;+ continue;+ }+ const idx = lyOff + (wx & CHUNK_MASK);+ const a = ch.a[idx];+ rawToothGrid[rowOff + gx] = ch.tooth[idx];+ if (a <= 0.002) {+ rawH[rowOff + gx] = 0;+ continue;+ }+ // Pure volumetric paint height (thick oil ridges rise high, edges taper naturally to canvas)+ rawH[rowOff + gx] = ch.height[idx] * impDepth * 1.75 * Math.min(1.0, a * 1.45);+ }+ }++ // Stage 2: 1 gentle separable pass [0.22, 0.56, 0.22] on PURE paint volume ONLY!+ for (let gy = 0; gy < gh; gy++) {+ const row = gy * gw;+ tmpH[row] = rawH[row];+ tmpH[row + gw - 1] = rawH[row + gw - 1];+ for (let gx = 1; gx < gw - 1; gx++) {+ tmpH[row + gx] =+ rawH[row + gx - 1] * 0.22 + rawH[row + gx] * 0.56 + rawH[row + gx + 1] * 0.22;+ }+ }+ for (let gx = 0; gx < gw; gx++) {+ smoothPaintH[gx] = tmpH[gx];+ smoothPaintH[(gh - 1) * gw + gx] = tmpH[(gh - 1) * gw + gx];+ }+ for (let gy = 1; gy < gh - 1; gy++) {+ const rowU = (gy - 1) * gw;+ const rowC = gy * gw;+ const rowD = (gy + 1) * gw;+ for (let gx = 0; gx < gw; gx++) {+ smoothPaintH[rowC + gx] =+ tmpH[rowU + gx] * 0.22 + tmpH[rowC + gx] * 0.56 + tmpH[rowD + gx] * 0.22;+ }+ }+ }++ // Fast bilinear height sampler inside smoothPaintH for smooth diagonal directional cast-shadow rays+ const sampleSmoothBilinear = (fx: number, fy: number): number => {+ if (!smoothPaintH) return 0;+ const ix = fx | 0;+ const iy = fy | 0;+ if (ix < 0 || iy < 0 || ix >= gw - 1 || iy >= gh - 1) return 0;+ const tx = fx - ix;+ const ty = fy - iy;+ const r0 = iy * gw + ix;+ const r1 = r0 + gw;+ const v00 = smoothPaintH[r0];+ const v10 = smoothPaintH[r0 + 1];+ const v01 = smoothPaintH[r1];+ const v11 = smoothPaintH[r1 + 1];+ const top = v00 + (v10 - v00) * tx;+ const bot = v01 + (v11 - v01) * tx;+ return top + (bot - top) * ty;+ };++ const marchCastShadow = (gxIdx: number, gyIdx: number, h0: number): number => {+ let maxOcc = 0;+ // 8 physical horizon-shadow taps marching toward the directional light source (1.0px .. 8.0px)+ for (let step = 1; step <= 8; step++) {+ const dist = step * 1.0;+ const hS = sampleSmoothBilinear(gxIdx + dlx * dist, gyIdx + dly * dist);+ const occ = hS - (h0 + raySlope * dist);+ if (occ > 0) {+ // Crisp hugging contact shadow near the paint rim, softening naturally into a delicate penumbra+ const distFade = Math.max(0, 1.0 - dist * 0.115);+ const soft = occ * distFade * distFade * 1.25;+ if (soft > maxOcc) maxOcc = soft;+ }+ }+ return Math.min(1.0, maxOcc * (1.55 + impContrast * 1.45));+ };++ // Use true 2x-DPI analytical surface gradients for built-in canvas-locked / random-per-stroke textures+ const canUseAnalyticalToothGrad =+ !this.grainParams.customTex &&+ (this.grainParams.mappingMode === 'canvas-locked' ||+ this.grainParams.mappingMode === 'random-per-stroke');+ const gradScratch = { gx: 0, gy: 0 };++ for (let y = 0; y < rh; y++) {+ const wy = ry + y;+ const cy = wy >> CHUNK_SHIFT;+ const lyOff = (wy & CHUNK_MASK) << CHUNK_SHIFT;+ const rowOut = y * rw * 4;+ const gyIdx = y + border;+ const gRowU = (gyIdx - 1) * gw;+ const gRowC = gyIdx * gw;+ const gRowD = (gyIdx + 1) * gw;++ for (let x = 0; x < rw; x++) {+ const wx = rx + x;+ const ch = this.getChunk(wx >> CHUNK_SHIFT, cy);+ const outIdx = rowOut + x * 4;+ const gxIdx = x + border;++ const idx = ch ? lyOff + (wx & CHUNK_MASK) : -1;+ let alpha = ch ? ch.a[idx] : 0;++ // Bare canvas / lower-layer pixel: check if a genuinely thick impasto ridge casts a subtle shadow+ if (alpha <= 0.003) {+ if (impastoOn && impDepth > 0.25 && smoothPaintH) {+ const castS = marchCastShadow(gxIdx, gyIdx, 0);+ if (castS > 0.08) {+ const shadowAlpha = Math.min(0.18, Math.pow(castS, 1.35) * (0.08 + impDepth * 0.14));+ outRgba[outIdx] = 26;+ outRgba[outIdx + 1] = 22;+ outRgba[outIdx + 2] = 34;+ outRgba[outIdx + 3] = Math.round(shadowAlpha * 255);+ continue;+ }+ }+ outRgba[outIdx] = 0;+ outRgba[outIdx + 1] = 0;+ outRgba[outIdx + 2] = 0;+ outRgba[outIdx + 3] = 0;+ continue;+ }++ let r = ch!.r[idx];+ let g = ch!.g[idx];+ let b = ch!.b[idx];+ const tooth = ch!.tooth[idx];+ const hp = ch!.height[idx];++ // Watercolor granulation: pigment particles settle into recessed paper valleys+ if (granStrength > 0.01) {+ const valley = 1.0 - tooth;+ const granDark = 1.0 - valley * granStrength * 0.34;+ r *= granDark;+ g *= granDark;+ b *= granDark;+ alpha = Math.min(1.0, alpha * (0.82 + valley * granStrength * 0.42));+ }++ // Watercolor wet-edge rim pooling at paint-alpha transition boundaries+ if (wetEdgeStrength > 0.01) {+ const aL = this.sampleAccumHeight(wx - 2, wy).alpha;+ const aR = this.sampleAccumHeight(wx + 2, wy).alpha;+ const aU = this.sampleAccumHeight(wx, wy - 2).alpha;+ const aD = this.sampleAccumHeight(wx, wy + 2).alpha;+ const avgNeighbor = (aL + aR + aU + aD) * 0.25;+ const rim = Math.max(0, alpha - avgNeighbor) * 2.5;+ if (rim > 0.02) {+ const rimDark = Math.max(0.45, 1.0 - rim * wetEdgeStrength * 0.42);+ r *= rimDark;+ g *= rimDark;+ b *= rimDark;+ alpha = Math.min(1.0, alpha * (1.0 + rim * wetEdgeStrength * 0.55));+ }+ }++ // 3D Sculptural Impasto Relief + 2x-DPI Analytical Canvas Weave Normals + Real 8-Tap Directional Cast Shadows!+ if (impastoOn && smoothPaintH && rawToothGrid) {+ const hTL = smoothPaintH[gRowU + gxIdx - 1];+ const hT = smoothPaintH[gRowU + gxIdx];+ const hTR = smoothPaintH[gRowU + gxIdx + 1];+ const hL = smoothPaintH[gRowC + gxIdx - 1];+ const hC = smoothPaintH[gRowC + gxIdx];+ const hR = smoothPaintH[gRowC + gxIdx + 1];+ const hBL = smoothPaintH[gRowD + gxIdx - 1];+ const hB = smoothPaintH[gRowD + gxIdx];+ const hBR = smoothPaintH[gRowD + gxIdx + 1];++ // Macro sculptural oil paint gradients+ const gxPaint = (hTR + 2 * hR + hBR) - (hTL + 2 * hL + hBL);+ const gyPaint = (hBL + 2 * hB + hBR) - (hTL + 2 * hT + hTR);++ // True 2x-DPI analytical surface weave micro-normals (silky & crisp even at 300% zoom!)+ const paintCover = Math.min(1.0, hp * 1.22);+ const weaveWeight = (Math.pow(1.0 - paintCover, 1.45) * 0.85 + 0.14) * grainDepth;+ let gxTooth = 0;+ let gyTooth = 0;+ if (weaveWeight > 0.01) {+ if (canUseAnalyticalToothGrad) {+ let sx = wx + 0.5;+ let sy = wy + 0.5;+ if (this.grainParams.mappingMode === 'random-per-stroke') {+ const rxp = sx * this.grainParams.strokeCos - sy * this.grainParams.strokeSin + this.grainParams.strokeOffsetX;+ const ryp = sx * this.grainParams.strokeSin + sy * this.grainParams.strokeCos + this.grainParams.strokeOffsetY;+ sx = rxp;+ sy = ryp;+ }+ sampleSurfaceTextureGrad(+ this.grainParams.surfaceId,+ sx,+ sy,+ this.grainParams.scale,+ this.grainParams.rotateRad,+ gradScratch+ );+ const invSign = this.grainParams.inverted ? -1 : 1;+ gxTooth = gradScratch.gx * weaveWeight * invSign * 2.2;+ gyTooth = gradScratch.gy * weaveWeight * invSign * 2.2;+ } else {+ const rawH = this.hGridRaw;+ const tC = rawToothGrid[gRowC + gxIdx];+ const tL = rawH[gRowC + gxIdx - 1] > 0.0001 ? rawToothGrid[gRowC + gxIdx - 1] : tC;+ const tR = rawH[gRowC + gxIdx + 1] > 0.0001 ? rawToothGrid[gRowC + gxIdx + 1] : tC;+ const tU = rawH[gRowU + gxIdx] > 0.0001 ? rawToothGrid[gRowU + gxIdx] : tC;+ const tD = rawH[gRowD + gxIdx] > 0.0001 ? rawToothGrid[gRowD + gxIdx] : tC;+ gxTooth = (tR - tL) * weaveWeight;+ gyTooth = (tD - tU) * weaveWeight;+ }+ }++ const nx = -(gxPaint * reliefScale + gxTooth * toothReliefScale);+ const ny = -(gyPaint * reliefScale + gyTooth * toothReliefScale);+ const nz = 1.0;+ const nLen = Math.hypot(nx, ny, nz) || 1;+ const nnx = nx / nLen;+ const nny = ny / nLen;+ const nnz = nz / nLen;++ const gradMag = Math.hypot(gxPaint, gyPaint) + Math.hypot(gxTooth, gyTooth) * 0.45;+ const slopeMask = Math.min(1.0, gradMag * 2.8);++ // Centered directional diffuse: flat paint (0,0,1) produces delta=0 (preserves true pigment hue!)+ const nDotL = nnx * lx + nny * ly + nnz * lz;+ const rawDiff = nDotL - lz;+ const diffuseDelta = rawDiff * diffAmp;++ // Real directional 3D cast self-shadow from neighboring taller bristle ridges!+ const castShadow = marchCastShadow(gxIdx, gyIdx, hC);+ const castDarken = castShadow * (0.30 + impContrast * 0.26);++ // Deep bristle-valley micro-AO + crisp micro-interstice weave AO+ const avgH = (hT + hB + hL + hR + (hTL + hTR + hBL + hBR) * 0.5) / 6.0;+ const concavity = Math.max(0, avgH - hC);+ const weaveCreviceAO = (1.0 - tooth) * weaveWeight * 0.14;+ const baseLum = (r * 0.299 + g * 0.587 + b * 0.114) / 255.0;+ // Physical oil subsurface scattering: light translucent pigments hold rich luminous shadows!+ const sssFloor = 0.44 + baseLum * 0.18;+ const ao = Math.min(0.28, concavity * (1.0 + impContrast * 1.5)) + weaveCreviceAO;++ const shadeMult = Math.max(sssFloor, Math.min(1.28, 1.0 + diffuseDelta - ao - castDarken));++ // Chromatic richness in shadows: real oil crevices & cast shadows deepen in chroma instead of muddying!+ const shadowAmt = Math.max(0, 1.0 - shadeMult);+ if (shadowAmt > 0.02) {+ const lum = r * 0.299 + g * 0.587 + b * 0.114;+ const satBoost = 1.0 + shadowAmt * 0.50;+ r = Math.max(0, Math.min(255, lum + (r - lum) * satBoost));+ g = Math.max(0, Math.min(255, lum + (g - lum) * satBoost));+ b = Math.max(0, Math.min(255, lum + (b - lum) * satBoost));+ }++ // Physically suppress specular reflections inside real directional cast shadows!+ const specVis = Math.max(0.06, 1.0 - castShadow * 0.88);+ const oilThicknessMask = Math.min(1.0, 0.24 + hp * 1.15) * specVis;++ // Adaptive sheen: dark/black oil gets crisp sculptural studio sheen; bright oil gets soft creamy luster!+ const darkSheenBoost = 1.55 - baseLum * 0.94;+ const litSlope = Math.max(0, rawDiff) * slopeMask * oilThicknessMask;+ const keyLift = litSlope * (0.20 + impGloss * 0.30) * (0.45 + impContrast * 0.55) * 110 * darkSheenBoost;++ // Two-lobe oil sheen (broad satin wrap + crisp glossy crest catchlights)+ const nDotH = Math.max(0, nnx * nhx + nny * nhy + nnz * nhz);+ const satinSpec = Math.pow(nDotH, satinExp) * satinAmp * slopeMask * oilThicknessMask * 124 * darkSheenBoost;+ const crispSpec = Math.pow(nDotH, glossExp) * glossAmp * slopeMask * oilThicknessMask * 195 * darkSheenBoost;+ const totalSpec = keyLift + satinSpec + crispSpec;++ // Warm studio light tint on highlights (#fffbf2) + rich sculpted shadows+ r = Math.max(0, Math.min(255, r * shadeMult + totalSpec * 1.0));+ g = Math.max(0, Math.min(255, g * shadeMult + totalSpec * 0.985));+ b = Math.max(0, Math.min(255, b * shadeMult + totalSpec * 0.955));++ // Subtle under-edge cast shadow only on thick impasto ridges (never darkens thin blended edges)+ if (alpha < 0.98 && impDepth > 0.25 && castShadow > 0.08) {+ const underShadowA = Math.min(0.18, Math.pow(castShadow, 1.35) * (0.08 + impDepth * 0.14));+ const outA = alpha + underShadowA * (1.0 - alpha);+ if (outA > 0.001) {+ const invOut = 1.0 / outA;+ const bgW = underShadowA * (1.0 - alpha);+ r = (r * alpha + 26 * bgW) * invOut;+ g = (g * alpha + 22 * bgW) * invOut;+ b = (b * alpha + 34 * bgW) * invOut;+ alpha = outA;+ }+ }+ }++ outRgba[outIdx] = Math.round(r);+ outRgba[outIdx + 1] = Math.round(g);+ outRgba[outIdx + 2] = Math.round(b);+ outRgba[outIdx + 3] = Math.round(Math.max(0, Math.min(1, alpha)) * 255);+ }+ }+ }++ /**+ * Blits a shaded dirty region onto a target Canvas2D context using full Float32 height+ * precision so live draft rendering and pointer-up tile commits are 100% pixel-identical+ * with zero 8-bit height banding and zero clip seams.+ */+ public flushDirtyRectToContext(+ ctx: CanvasRenderingContext2D,+ dirty: { minX: number; minY: number; maxX: number; maxY: number },+ replaceRegion: boolean = false,+ opacity: number = 1.0,+ compositeOp: GlobalCompositeOperation = 'source-over'+ ): void {+ // Expand by 11px when impasto cast shadows are active so 9.6px directional drop shadows never clip!+ const impastoOn = this.impasto.enabled && this.impasto.depth > 0.01;+ const pad = impastoOn ? 11 : this.wetEdge > 0.01 ? 4 : 3;+ const rx = Math.floor(dirty.minX) - pad;+ const ry = Math.floor(dirty.minY) - pad;+ const rw = Math.ceil(dirty.maxX) + pad - rx;+ const rh = Math.ceil(dirty.maxY) + pad - ry;+ if (rw <= 0 || rh <= 0) return;++ if (typeof document === 'undefined') return;+ if (!this.scratchCanvas) {+ this.scratchCanvas = document.createElement('canvas');+ this.scratchCtx = this.scratchCanvas.getContext('2d');+ }+ if (!this.scratchCanvas || !this.scratchCtx) return;++ if (this.scratchCanvas.width < rw || this.scratchCanvas.height < rh) {+ this.scratchCanvas.width = Math.max(this.scratchCanvas.width, rw);+ this.scratchCanvas.height = Math.max(this.scratchCanvas.height, rh);+ }++ const imgData = this.scratchCtx.createImageData(rw, rh);+ this.shadeRectToBuffer(rx, ry, rw, rh, imgData.data);+ this.scratchCtx.putImageData(imgData, 0, 0);++ ctx.save();+ if (replaceRegion) {+ ctx.clearRect(rx, ry, rw, rh);+ }+ ctx.globalCompositeOperation = compositeOp;+ ctx.globalAlpha = Math.max(0, Math.min(1, opacity));+ ctx.drawImage(this.scratchCanvas, 0, 0, rw, rh, rx, ry, rw, rh);+ ctx.restore();+ }++ public stampInitialPoint(+ ctx: CanvasRenderingContext2D,+ pt: Point,+ sampler?: LayerPixelSampler,+ replaceRegion: boolean = true+ ): void {+ // Anchor the bristle frame without emitting an arbitrarily-oriented start bar (zero detached stub!)+ this.pendingTapPoint = pt;+ this.hasEmittedSegment = false;+ const batch = this.engine.emitInitialStamp(pt, sampler, undefined, false);+ const dirty = this.rasterizeBatch(batch);+ if (dirty) {+ this.flushDirtyRectToContext(ctx, dirty, replaceRegion, 1.0, 'source-over');+ }+ }++ public flushPendingTapIfNeeded(sampler?: LayerPixelSampler): void {+ if (!this.hasEmittedSegment && this.pendingTapPoint) {+ const tapBatch = this.engine.emitInitialStamp(this.pendingTapPoint, sampler, undefined, true);+ this.rasterizeBatch(tapBatch);+ this.pendingTapPoint = null;+ }+ }++ public drawCubicSegment(+ ctx: CanvasRenderingContext2D,+ p0: Point,+ c1: Point,+ c2: Point,+ p3: Point,+ sampler?: LayerPixelSampler,+ replaceRegion: boolean = true+ ): void {+ this.hasEmittedSegment = true;+ this.pendingTapPoint = null;+ const batch = this.engine.emitCubicSegment(p0, c1, c2, p3, sampler);+ const dirty = this.rasterizeBatch(batch);+ if (dirty) {+ this.flushDirtyRectToContext(ctx, dirty, replaceRegion, 1.0, 'source-over');+ }+ }++ public getDirtyBounds(): { minX: number; minY: number; maxX: number; maxY: number } | null {+ if (!Number.isFinite(this.minX) || !Number.isFinite(this.maxX)) return null;+ return { minX: this.minX, minY: this.minY, maxX: this.maxX, maxY: this.maxY };+ }++ public finishAndDispose(): void {+ this.engine.finishStroke();+ for (const ch of this.chunks.values()) {+ releaseChunk(ch);+ }+ this.chunks.clear();+ }+}++/**+ * Renders an entire completed Natural Paint stroke deterministically onto `ctx`+ * (used by pointer-up bake, Brush Studio scratchpad, brush previews, and headless tests).+ */+export function renderCompleteNaturalPaintStroke(+ ctx: CanvasRenderingContext2D,+ points: Point[],+ settings: BrushSettings,+ strokeColor: string,+ sampler?: LayerPixelSampler,+ opacity: number = 1.0,+ compositeOp: GlobalCompositeOperation = 'source-over',+ strokeSeed: number = 1337+): { minX: number; minY: number; maxX: number; maxY: number } | null {+ if (!points || points.length === 0) return null;++ let totalLen = 0;+ for (let i = 1; i < points.length; i++) {+ totalLen += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);+ }++ const session = new NaturalPaintStrokeSession(settings, strokeColor, totalLen, strokeSeed);++ let initialDir: { dx: number; dy: number } | undefined;+ if (points.length >= 2) {+ for (let i = 1; i < points.length; i++) {+ const dx = points[i].x - points[0].x;+ const dy = points[i].y - points[0].y;+ if (Math.hypot(dx, dy) > 0.5) {+ initialDir = { dx, dy };+ break;+ }+ }+ }++ // Emit tap dot only for single-point taps; multi-point strokes start cleanly along initialDir!+ const initBatch = session.engine.emitInitialStamp(points[0], sampler, initialDir, !initialDir);+ session.rasterizeBatch(initBatch);++ if (points.length === 2) {+ const p0 = points[0];+ const p1 = points[1];+ const { c1, c2 } = centripetalCatmullRomToBezier(p0, p0, p1, p1);+ const b = session.engine.emitCubicSegment(p0, c1, c2, p1, sampler);+ session.rasterizeBatch(b);+ } else if (points.length >= 3) {+ const first = centripetalCatmullRomToBezier(points[0], points[0], points[1], points[2]);+ session.rasterizeBatch(session.engine.emitCubicSegment(points[0], first.c1, first.c2, points[1], sampler));++ for (let i = 2; i < points.length - 1; i++) {+ const seg = centripetalCatmullRomToBezier(points[i - 2], points[i - 1], points[i], points[i + 1]);+ session.rasterizeBatch(session.engine.emitCubicSegment(points[i - 1], seg.c1, seg.c2, points[i], sampler));+ }++ const n = points.length;+ const last = centripetalCatmullRomToBezier(points[n - 3], points[n - 2], points[n - 1], points[n - 1]);+ session.rasterizeBatch(session.engine.emitCubicSegment(points[n - 2], last.c1, last.c2, points[n - 1], sampler));+ }++ const bounds = session.getDirtyBounds();+ if (bounds) {+ session.flushDirtyRectToContext(ctx, bounds, false, opacity, compositeOp);+ }+ session.finishAndDispose();+ return bounds;+}diff --git a/src/engine/WebGlBrushEngine.ts b/src/engine/WebGlBrushEngine.tsindex 2e22e21..a66e9ac 100644--- a/src/engine/WebGlBrushEngine.ts+++ b/src/engine/WebGlBrushEngine.ts@@ -1,4 +1,5 @@-import { Point, BrushSettings, ToolType } from '../types/editor';+import { Point, BrushSettings, ToolType, SurfaceTextureId, ImpastoSettings } from '../types/editor';+import { getSurfaceTextureHeightField, SURFACE_TEXTURE_SIZE } from '../utils/proceduralBrushTips';export interface GpuInfo {isSupported: boolean;@@ -21,6 +22,7 @@ export interface GpuDab {strokeDist: number;flipX?: number;flipY?: number;+ tipIndex?: number;}const VERTEX_SHADER_SRC = `@@ -35,6 +37,7 @@ attribute float a_alpha;attribute float a_pressure;attribute float a_strokeDist;attribute vec2 a_flip;+attribute float a_tipIndex;uniform vec2 u_canvasResolution;uniform vec2 u_dirtyOffset;@@ -47,6 +50,8 @@ varying float v_pressure;varying float v_strokeDist;varying vec2 v_worldPos;varying vec2 v_size;+varying float v_angle;+varying float v_tipIndex;void main() {vec2 flipSign = vec2(a_flip.x == 0.0 ? 1.0 : a_flip.x, a_flip.y == 0.0 ? 1.0 : a_flip.y);@@ -57,6 +62,8 @@ void main() {v_pressure = a_pressure;v_strokeDist = a_strokeDist;v_size = a_size;+ v_angle = a_angle;+ v_tipIndex = a_tipIndex;float cosA = cos(a_angle);float sinA = sin(a_angle);@@ -87,14 +94,20 @@ varying float v_pressure;varying float v_strokeDist;varying vec2 v_worldPos;varying vec2 v_size;+varying float v_angle;+varying float v_tipIndex;uniform bool u_hasTipTexture;uniform bool u_isColorTip;uniform sampler2D u_tipTexture;+uniform vec2 u_tipAtlasGrid;uniform bool u_hasDualTipTexture;uniform sampler2D u_dualTipTexture;uniform int u_dualBlendMode;+uniform float u_dualScale;+uniform float u_dualRotRad;+uniform float u_dualScatter;uniform int u_antiAlias;uniform float u_hardness;@@ -102,6 +115,11 @@ uniform float u_wetEdge;uniform float u_paperGrain;uniform float u_grainScale;uniform float u_grainRotateRad;+uniform int u_grainMappingMode;+uniform vec2 u_grainRandomOffset;+uniform float u_grainRandomRot;+uniform float u_dryBrush;+uniform float u_paintLoad;uniform int u_paperMode;uniform float u_paperBrightness;uniform float u_paperContrast;@@ -123,10 +141,24 @@ uniform bool u_isEraser;uniform bool u_isBgEraser;float samplePaperTooth(vec2 worldPos) {+ vec2 baseP = worldPos;+ if (u_grainMappingMode == 1) {+ // brush-aligned: rotate & scale with local dab coordinates+ baseP = v_localPos * max(v_size.x, v_size.y) * 0.5;+ } else if (u_grainMappingMode == 2) {+ // stroke-flow: u = arcLength, v = across-width+ baseP = vec2(v_strokeDist + v_localPos.x * v_size.x * 0.5, v_localPos.y * v_size.y * 0.5);+ } else if (u_grainMappingMode == 3) {+ // random-per-stroke: deterministic random offset + rotation+ float rc = cos(u_grainRandomRot);+ float rs = sin(u_grainRandomRot);+ baseP = vec2(worldPos.x * rc - worldPos.y * rs, worldPos.x * rs + worldPos.y * rc) + u_grainRandomOffset;+ }+float invScale = 1.0 / max(0.05, u_grainScale);float c = cos(u_grainRotateRad);float s = sin(u_grainRotateRad);- vec2 rotP = vec2(worldPos.x * c - worldPos.y * s, worldPos.x * s + worldPos.y * c) * invScale;+ vec2 rotP = vec2(baseP.x * c - baseP.y * s, baseP.x * s + baseP.y * c) * invScale;float g = 0.5;if (u_hasPaperTex) {@@ -184,7 +216,18 @@ void main() {float tipAlpha = 1.0;if (u_hasTipTexture) {- vec4 tex = texture2D(u_tipTexture, v_uv);+ vec2 sampleUv = v_uv;+ if (u_tipAtlasGrid.x > 1.0 || u_tipAtlasGrid.y > 1.0) {+ float cols = max(1.0, u_tipAtlasGrid.x);+ float rows = max(1.0, u_tipAtlasGrid.y);+ float idx = floor(max(0.0, v_tipIndex) + 0.5);+ float col = mod(idx, cols);+ float row = floor(idx / cols);+ vec2 cellSize = vec2(1.0 / cols, 1.0 / rows);+ vec2 inset = cellSize * 0.004;+ sampleUv = vec2(col, row) * cellSize + inset + clamp(v_uv, 0.0, 1.0) * (cellSize - inset * 2.0);+ }+ vec4 tex = texture2D(u_tipTexture, sampleUv);tipAlpha = tex.a;if (u_isColorTip) {rgb = tex.rgb;@@ -213,8 +256,19 @@ void main() {}if (u_hasDualTipTexture) {- vec4 dualTex = texture2D(u_dualTipTexture, v_uv);- float dualA = dualTex.a;+ vec2 centered = (v_uv - 0.5) / max(0.1, u_dualScale);+ float dc = cos(u_dualRotRad);+ float ds = sin(u_dualRotRad);+ vec2 dRot = vec2(centered.x * dc - centered.y * ds, centered.x * ds + centered.y * dc);+ if (u_dualScatter > 0.001) {+ float sHash = fract(sin(v_strokeDist * 0.137 + v_angle * 12.9898) * 43758.5453);+ float sHash2 = fract(sin(v_strokeDist * 0.271 + v_angle * 78.233) * 24634.6345);+ dRot += (vec2(sHash, sHash2) - 0.5) * u_dualScatter * 0.5;+ }+ vec2 dualUv = dRot + 0.5;+ float dualA = (dualUv.x >= 0.0 && dualUv.x <= 1.0 && dualUv.y >= 0.0 && dualUv.y <= 1.0)+ ? texture2D(u_dualTipTexture, dualUv).a+ : 0.0;if (u_dualBlendMode == 1) {tipAlpha = max(0.0, tipAlpha - (1.0 - dualA));} else if (u_dualBlendMode == 2) {@@ -232,14 +286,18 @@ void main() {discard;}- if (u_paperGrain > 0.001) {+ if (u_paperGrain > 0.001 || u_dryBrush > 0.001) {float g = samplePaperTooth(v_worldPos);float p = clamp(v_pressure, 0.0, 1.0);float heavyExcess = max(0.0, (p - 0.52) / 0.48);- float penetration = min(0.92, p * 0.28 + heavyExcess * heavyExcess * 0.64);- float effDensity = u_paperGrain * (1.0 - penetration * 0.85);-- if (u_paperMode == 1) {+ float penetration = min(0.92, (p * 0.28 + heavyExcess * heavyExcess * 0.64) * (0.45 + 0.55 * clamp(u_paintLoad, 0.0, 1.0)));+ float effDensity = max(u_paperGrain, u_dryBrush * 0.85) * (1.0 - penetration * 0.85);++ if (u_dryBrush > 0.01) {+ float cutoff = u_dryBrush * (1.0 - penetration * 0.86) * 0.78;+ float tooth = smoothstep(cutoff - 0.06, cutoff + 0.14, g);+ tipAlpha *= mix(1.0, tooth, clamp(u_dryBrush + u_paperGrain * 0.5, 0.0, 1.0));+ } else if (u_paperMode == 1) {tipAlpha *= (1.0 - effDensity * (1.0 - g));} else if (u_paperMode == 2) {float contactHeight = g * (0.22 + 0.78 * tipAlpha);@@ -270,7 +328,9 @@ void main() {if (canvasColor.a > 0.02) {float stretchDistLimit = max(20.0, u_colorStretch * 600.0);float stretchDecay = exp(-v_strokeDist / stretchDistLimit);- float effectiveAmount = clamp(u_amountOfPaint * (1.0 - stretchDecay * 0.7), 0.04, 0.98);+ float effectiveAmount = u_amountOfPaint >= 0.995+ ? 1.0+ : clamp(mix(u_amountOfPaint, 1.0, (1.0 - stretchDecay) * 0.35), 0.02, 1.0);if (u_perceptualMixing) {rgb = mixPigmentsGpu(canvasColor.rgb, rgb, effectiveAmount);} else {@@ -296,6 +356,114 @@ void main() {}`;+const IMPASTO_VERTEX_SHADER_SRC = `+precision highp float;+attribute vec2 a_pos;+varying vec2 v_uv;+void main() {+ v_uv = a_pos * 0.5 + 0.5;+ gl_Position = vec4(a_pos, 0.0, 1.0);+}+`;++const IMPASTO_FRAGMENT_SHADER_SRC = `+precision highp float;++varying vec2 v_uv;++uniform sampler2D u_colorTex;+uniform sampler2D u_heightTex;+uniform vec2 u_texelSize;+uniform vec3 u_lightDir;+uniform float u_depth;+uniform float u_gloss;+uniform float u_contrast;+uniform float u_granulation;+uniform float u_wetEdge;++float sampleH(vec2 uv) {+ return texture2D(u_heightTex, clamp(uv, vec2(0.0), vec2(1.0))).r;+}++void main() {+ vec4 base = texture2D(u_colorTex, v_uv);+ float alpha = base.a;+ if (alpha <= 0.003) {+ discard;+ }++ vec3 rgb = base.rgb;+ vec4 hCenter = texture2D(u_heightTex, v_uv);+ float hC = hCenter.r;+ float tooth = hCenter.g;++ if (u_granulation > 0.01) {+ float valley = 1.0 - tooth;+ rgb *= (1.0 - valley * u_granulation * 0.34);+ alpha = min(1.0, alpha * (0.82 + valley * u_granulation * 0.42));+ }++ if (u_wetEdge > 0.01) {+ vec2 step2 = u_texelSize * 2.0;+ float avgA = (+ texture2D(u_colorTex, v_uv + vec2(-step2.x, 0.0)).a ++ texture2D(u_colorTex, v_uv + vec2(step2.x, 0.0)).a ++ texture2D(u_colorTex, v_uv + vec2(0.0, -step2.y)).a ++ texture2D(u_colorTex, v_uv + vec2(0.0, step2.y)).a+ ) * 0.25;+ float rim = max(0.0, alpha - avgA) * 2.5;+ if (rim > 0.02) {+ rgb *= max(0.45, 1.0 - rim * u_wetEdge * 0.42);+ alpha = min(1.0, alpha * (1.0 + rim * u_wetEdge * 0.55));+ }+ }++ if (u_depth > 0.01) {+ float tx = u_texelSize.x;+ float ty = u_texelSize.y;++ float hTL = sampleH(v_uv + vec2(-tx, -ty));+ float hT = sampleH(v_uv + vec2(0.0, -ty));+ float hTR = sampleH(v_uv + vec2(tx, -ty));+ float hL = sampleH(v_uv + vec2(-tx, 0.0));+ float hR = sampleH(v_uv + vec2(tx, 0.0));+ float hBL = sampleH(v_uv + vec2(-tx, ty));+ float hB = sampleH(v_uv + vec2(0.0, ty));+ float hBR = sampleH(v_uv + vec2(tx, ty));++ float gx = (hTR + 2.0 * hR + hBR) - (hTL + 2.0 * hL + hBL);+ float gy = (hBL + 2.0 * hB + hBR) - (hTL + 2.0 * hT + hTR);++ float reliefScale = 3.8 + u_depth * 8.6;+ vec3 N = normalize(vec3(-gx * reliefScale, -gy * reliefScale, 1.0));+ vec3 L = normalize(u_lightDir);++ float slopeMask = min(1.0, length(vec2(gx, gy)) * 2.6);+ float diffAmp = 0.34 + u_contrast * 0.58;+ float rawDiff = dot(N, L) - L.z;+ float diffuseDelta = rawDiff * diffAmp;++ float avgH = (hT + hB + hL + hR + (hTL + hTR + hBL + hBR) * 0.5) / 6.0;+ float concavity = max(0.0, avgH - hC);+ float ao = min(0.42, concavity * (1.1 + u_contrast * 1.9));+ float shadeMult = clamp(1.0 + diffuseDelta - ao, 0.46, 1.42);++ float litSlope = max(0.0, rawDiff) * slopeMask;+ float keyLift = litSlope * (0.22 + u_gloss * 0.34) * (0.45 + u_contrast * 0.55) * 0.45;++ vec3 H = normalize(L + vec3(0.0, 0.0, 1.0));+ float nDotH = max(0.0, dot(N, H));+ float satinSpec = pow(nDotH, 10.0 + u_gloss * 10.0) * (0.12 + u_gloss * 0.24) * (0.45 + u_depth * 0.65) * slopeMask * 0.55;+ float crispSpec = pow(nDotH, 36.0 + u_gloss * 56.0) * u_gloss * (0.28 + u_depth * 0.56) * slopeMask;+ float totalSpec = keyLift + satinSpec + crispSpec;++ rgb = clamp(rgb * shadeMult + vec3(totalSpec, totalSpec * 0.985, totalSpec * 0.95), 0.0, 1.0);+ }++ gl_FragColor = vec4(rgb * alpha, alpha);+}+`;+const RIBBON_VERTEX_SHADER_SRC = `precision highp float;@@ -359,6 +527,7 @@ export class WebGlBrushEngine {private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;private program: WebGLProgram | null = null;private ribbonProgram: WebGLProgram | null = null;+ private impastoProgram: WebGLProgram | null = null;private isGpuAvailable = false;private gpuInfo: GpuInfo = {isSupported: false,@@ -376,6 +545,7 @@ export class WebGlBrushEngine {private aPressureLoc = -1;private aStrokeDistLoc = -1;private aFlipLoc = -1;+ private aTipIndexLoc = -1;private uCanvasResolutionLoc: WebGLUniformLocation | null = null;private uDocResolutionLoc: WebGLUniformLocation | null = null;@@ -383,15 +553,24 @@ export class WebGlBrushEngine {private uHasTipTextureLoc: WebGLUniformLocation | null = null;private uIsColorTipLoc: WebGLUniformLocation | null = null;private uTipTextureLoc: WebGLUniformLocation | null = null;+ private uTipAtlasGridLoc: WebGLUniformLocation | null = null;private uHasDualTipTextureLoc: WebGLUniformLocation | null = null;private uDualTipTextureLoc: WebGLUniformLocation | null = null;private uDualBlendModeLoc: WebGLUniformLocation | null = null;+ private uDualScaleLoc: WebGLUniformLocation | null = null;+ private uDualRotRadLoc: WebGLUniformLocation | null = null;+ private uDualScatterLoc: WebGLUniformLocation | null = null;private uAntiAliasLoc: WebGLUniformLocation | null = null;private uHardnessLoc: WebGLUniformLocation | null = null;private uWetEdgeLoc: WebGLUniformLocation | null = null;private uPaperGrainLoc: WebGLUniformLocation | null = null;private uGrainScaleLoc: WebGLUniformLocation | null = null;private uGrainRotateRadLoc: WebGLUniformLocation | null = null;+ private uGrainMappingModeLoc: WebGLUniformLocation | null = null;+ private uGrainRandomOffsetLoc: WebGLUniformLocation | null = null;+ private uGrainRandomRotLoc: WebGLUniformLocation | null = null;+ private uDryBrushLoc: WebGLUniformLocation | null = null;+ private uPaintLoadLoc: WebGLUniformLocation | null = null;private uPaperModeLoc: WebGLUniformLocation | null = null;private uPaperBrightnessLoc: WebGLUniformLocation | null = null;private uPaperContrastLoc: WebGLUniformLocation | null = null;@@ -416,9 +595,29 @@ export class WebGlBrushEngine {private aRibbonColorLoc = -1;private aRibbonWidthLoc = -1;+ // Impasto Relief Post-Pass locations & resources+ private aImpastoPosLoc = -1;+ private uImpastoColorTexLoc: WebGLUniformLocation | null = null;+ private uImpastoHeightTexLoc: WebGLUniformLocation | null = null;+ private uImpastoTexelSizeLoc: WebGLUniformLocation | null = null;+ private uImpastoLightDirLoc: WebGLUniformLocation | null = null;+ private uImpastoDepthLoc: WebGLUniformLocation | null = null;+ private uImpastoGlossLoc: WebGLUniformLocation | null = null;+ private uImpastoContrastLoc: WebGLUniformLocation | null = null;+ private uImpastoGranulationLoc: WebGLUniformLocation | null = null;+ private uImpastoWetEdgeLoc: WebGLUniformLocation | null = null;+ private fullQuadBuffer: WebGLBuffer | null = null;+ private impastoColorTex: WebGLTexture | null = null;+ private impastoHeightTex: WebGLTexture | null = null;+private tipTexturesMap = new Map<string, WebGLTexture>();+ private multiTipAtlasCache = new Map<string, { tex: WebGLTexture; cols: number; rows: number }>();+ private surfaceTexturesMap = new Map<SurfaceTextureId, WebGLTexture>();private builtinPaperTexture: WebGLTexture | null = null;private canvasLayerTexture: WebGLTexture | null = null;+ private canvasLayerWidth = 0;+ private canvasLayerHeight = 0;+ private canvasLayerSource: HTMLCanvasElement | null = null;private dabFbo: WebGLFramebuffer | null = null;private dabFboTex: WebGLTexture | null = null;@@ -431,7 +630,7 @@ export class WebGlBrushEngine {vertexAttribDivisor: (index: number, divisor: number) => void;} | null = null;private instanceBuffer: WebGLBuffer | null = null;- private instanceArray: Float32Array = new Float32Array(4096 * 14);+ private instanceArray: Float32Array = new Float32Array(4096 * 15);private ribbonBuffer: WebGLBuffer | null = null;private ribbonArray: Float32Array = new Float32Array(1024 * 8);@@ -455,8 +654,15 @@ export class WebGlBrushEngine {ev.preventDefault();this.isGpuAvailable = false;this.tipTexturesMap.clear();+ this.multiTipAtlasCache.clear();+ this.surfaceTexturesMap.clear();this.builtinPaperTexture = null;this.canvasLayerTexture = null;+ this.canvasLayerWidth = 0;+ this.canvasLayerHeight = 0;+ this.canvasLayerSource = null;+ this.impastoColorTex = null;+ this.impastoHeightTex = null;this.dabFbo = null;this.dabFboTex = null;this.dabFboWidth = 0;@@ -538,6 +744,7 @@ export class WebGlBrushEngine {this.aPressureLoc = gl.getAttribLocation(program, 'a_pressure');this.aStrokeDistLoc = gl.getAttribLocation(program, 'a_strokeDist');this.aFlipLoc = gl.getAttribLocation(program, 'a_flip');+ this.aTipIndexLoc = gl.getAttribLocation(program, 'a_tipIndex');this.uCanvasResolutionLoc = gl.getUniformLocation(program, 'u_canvasResolution');this.uDocResolutionLoc = gl.getUniformLocation(program, 'u_docResolution');@@ -545,15 +752,24 @@ export class WebGlBrushEngine {this.uHasTipTextureLoc = gl.getUniformLocation(program, 'u_hasTipTexture');this.uIsColorTipLoc = gl.getUniformLocation(program, 'u_isColorTip');this.uTipTextureLoc = gl.getUniformLocation(program, 'u_tipTexture');+ this.uTipAtlasGridLoc = gl.getUniformLocation(program, 'u_tipAtlasGrid');this.uHasDualTipTextureLoc = gl.getUniformLocation(program, 'u_hasDualTipTexture');this.uDualTipTextureLoc = gl.getUniformLocation(program, 'u_dualTipTexture');this.uDualBlendModeLoc = gl.getUniformLocation(program, 'u_dualBlendMode');+ this.uDualScaleLoc = gl.getUniformLocation(program, 'u_dualScale');+ this.uDualRotRadLoc = gl.getUniformLocation(program, 'u_dualRotRad');+ this.uDualScatterLoc = gl.getUniformLocation(program, 'u_dualScatter');this.uAntiAliasLoc = gl.getUniformLocation(program, 'u_antiAlias');this.uHardnessLoc = gl.getUniformLocation(program, 'u_hardness');this.uWetEdgeLoc = gl.getUniformLocation(program, 'u_wetEdge');this.uPaperGrainLoc = gl.getUniformLocation(program, 'u_paperGrain');this.uGrainScaleLoc = gl.getUniformLocation(program, 'u_grainScale');this.uGrainRotateRadLoc = gl.getUniformLocation(program, 'u_grainRotateRad');+ this.uGrainMappingModeLoc = gl.getUniformLocation(program, 'u_grainMappingMode');+ this.uGrainRandomOffsetLoc = gl.getUniformLocation(program, 'u_grainRandomOffset');+ this.uGrainRandomRotLoc = gl.getUniformLocation(program, 'u_grainRandomRot');+ this.uDryBrushLoc = gl.getUniformLocation(program, 'u_dryBrush');+ this.uPaintLoadLoc = gl.getUniformLocation(program, 'u_paintLoad');this.uPaperModeLoc = gl.getUniformLocation(program, 'u_paperMode');this.uPaperBrightnessLoc = gl.getUniformLocation(program, 'u_paperBrightness');this.uPaperContrastLoc = gl.getUniformLocation(program, 'u_paperContrast');@@ -606,6 +822,38 @@ export class WebGlBrushEngine {gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);gl.bufferData(gl.ARRAY_BUFFER, quadVertices, gl.STATIC_DRAW);+ const iVs = this.compileShader(gl.VERTEX_SHADER, IMPASTO_VERTEX_SHADER_SRC);+ const iFs = this.compileShader(gl.FRAGMENT_SHADER, IMPASTO_FRAGMENT_SHADER_SRC);+ if (iVs && iFs) {+ const iProgram = gl.createProgram();+ if (iProgram) {+ gl.attachShader(iProgram, iVs);+ gl.attachShader(iProgram, iFs);+ gl.linkProgram(iProgram);+ if (gl.getProgramParameter(iProgram, gl.LINK_STATUS)) {+ this.impastoProgram = iProgram;+ this.aImpastoPosLoc = gl.getAttribLocation(iProgram, 'a_pos');+ this.uImpastoColorTexLoc = gl.getUniformLocation(iProgram, 'u_colorTex');+ this.uImpastoHeightTexLoc = gl.getUniformLocation(iProgram, 'u_heightTex');+ this.uImpastoTexelSizeLoc = gl.getUniformLocation(iProgram, 'u_texelSize');+ this.uImpastoLightDirLoc = gl.getUniformLocation(iProgram, 'u_lightDir');+ this.uImpastoDepthLoc = gl.getUniformLocation(iProgram, 'u_depth');+ this.uImpastoGlossLoc = gl.getUniformLocation(iProgram, 'u_gloss');+ this.uImpastoContrastLoc = gl.getUniformLocation(iProgram, 'u_contrast');+ this.uImpastoGranulationLoc = gl.getUniformLocation(iProgram, 'u_granulation');+ this.uImpastoWetEdgeLoc = gl.getUniformLocation(iProgram, 'u_wetEdge');+ }+ }+ }++ this.fullQuadBuffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, this.fullQuadBuffer);+ gl.bufferData(+ gl.ARRAY_BUFFER,+ new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),+ gl.STATIC_DRAW+ );+this.ribbonBuffer = gl.createBuffer();if ('drawArraysInstanced' in gl) {@@ -768,7 +1016,111 @@ export class WebGlBrushEngine {return tex;}- public uploadCanvasTexture(sourceCanvas: HTMLCanvasElement): WebGLTexture | null {+ /**+ * Builds and caches a 2D texture atlas packing up to 32 sub-tips so multi-tip brushes+ * render in a single GPU instanced draw call via `a_tipIndex`.+ */+ public getOrCreateMultiTipAtlas(+ images: HTMLImageElement[]+ ): { tex: WebGLTexture; cols: number; rows: number } | null {+ if (!this.gl || !images || images.length <= 1 || typeof document === 'undefined') return null;+ const ready = images.filter((im) => im && im.complete !== false && (im.naturalWidth || im.width) > 0).slice(0, 32);+ if (ready.length <= 1) return null;++ const key = ready.map((im) => `${im.naturalWidth || im.width}x${im.naturalHeight || im.height}:${im.src.slice(-24)}`).join('|');+ const cached = this.multiTipAtlasCache.get(key);+ if (cached) return cached;++ const count = ready.length;+ const cols = Math.ceil(Math.sqrt(count));+ const rows = Math.ceil(count / cols);+ const cellSize = 128;++ const atlasCanvas = document.createElement('canvas');+ atlasCanvas.width = cols * cellSize;+ atlasCanvas.height = rows * cellSize;+ const aCtx = atlasCanvas.getContext('2d');+ if (!aCtx) return null;++ for (let i = 0; i < count; i++) {+ const col = i % cols;+ const row = Math.floor(i / cols);+ aCtx.drawImage(ready[i], col * cellSize, row * cellSize, cellSize, cellSize);+ }++ const gl = this.gl;+ if (this.multiTipAtlasCache.size >= 16) {+ const oldestKey = this.multiTipAtlasCache.keys().next().value;+ if (oldestKey) {+ const old = this.multiTipAtlasCache.get(oldestKey);+ if (old) gl.deleteTexture(old.tex);+ this.multiTipAtlasCache.delete(oldestKey);+ }+ }++ const tex = gl.createTexture();+ if (!tex) return null;+ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, atlasCanvas);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);++ const entry = { tex, cols, rows };+ this.multiTipAtlasCache.set(key, entry);+ return entry;+ }++ /**+ * Uploads and caches one of the 7 built-in 512x512 seamless surface heightmaps as a repeat-wrapped GPU texture.+ */+ public getOrCreateSurfaceTexture(id: SurfaceTextureId): WebGLTexture | null {+ if (!this.gl) return null;+ const cached = this.surfaceTexturesMap.get(id);+ if (cached) return cached;++ const gl = this.gl;+ const field = getSurfaceTextureHeightField(id);+ const tex = gl.createTexture();+ if (!tex) return null;++ gl.activeTexture(gl.TEXTURE3);+ gl.bindTexture(gl.TEXTURE_2D, tex);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.texImage2D(+ gl.TEXTURE_2D,+ 0,+ gl.LUMINANCE,+ SURFACE_TEXTURE_SIZE,+ SURFACE_TEXTURE_SIZE,+ 0,+ gl.LUMINANCE,+ gl.UNSIGNED_BYTE,+ field+ );+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);++ this.surfaceTexturesMap.set(id, tex);+ return tex;+ }++ /**+ * Uploads or incrementally updates the underlying canvas texture for GPU wet mixing.+ * When dirty bounds are supplied and dimensions match, updates ONLY the dirty sub-rect+ * via `texSubImage2D` (avoiding full-4K `texImage2D` uploads per frame).+ */+ public uploadCanvasTexture(+ sourceCanvas: HTMLCanvasElement,+ dirtyRect?: { x: number; y: number; width: number; height: number }+ ): WebGLTexture | null {if (!this.gl) return null;const gl = this.gl;@@ -778,18 +1130,167 @@ export class WebGlBrushEngine {const tex = this.canvasLayerTexture;if (!tex) return null;- gl.activeTexture(gl.TEXTURE0);+ gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D, tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);++ const dimsMatch =+ this.canvasLayerSource === sourceCanvas &&+ this.canvasLayerWidth === sourceCanvas.width &&+ this.canvasLayerHeight === sourceCanvas.height;++ if (+ dimsMatch &&+ dirtyRect &&+ dirtyRect.width > 0 &&+ dirtyRect.height > 0 &&+ dirtyRect.width < sourceCanvas.width * 0.65 &&+ dirtyRect.height < sourceCanvas.height * 0.65 &&+ typeof document !== 'undefined'+ ) {+ const rx = Math.max(0, Math.floor(dirtyRect.x));+ const ry = Math.max(0, Math.floor(dirtyRect.y));+ const rw = Math.min(sourceCanvas.width - rx, Math.ceil(dirtyRect.width));+ const rh = Math.min(sourceCanvas.height - ry, Math.ceil(dirtyRect.height));+ if (rw > 0 && rh > 0) {+ const subCanvas = document.createElement('canvas');+ subCanvas.width = rw;+ subCanvas.height = rh;+ const sCtx = subCanvas.getContext('2d');+ if (sCtx) {+ sCtx.drawImage(sourceCanvas, rx, ry, rw, rh, 0, 0, rw, rh);+ gl.texSubImage2D(gl.TEXTURE_2D, 0, rx, ry, gl.RGBA, gl.UNSIGNED_BYTE, subCanvas);+ return tex;+ }+ }+ }+gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ this.canvasLayerSource = sourceCanvas;+ this.canvasLayerWidth = sourceCanvas.width;+ this.canvasLayerHeight = sourceCanvas.height;+return tex;}+ /**+ * Executes the WebGL 3D Impasto Relief Shading Post-Pass (3x3 Sobel normals, directional+ * diffuse ridge shading, Blinn-Phong gloss specular, micro-AO, and watercolor granulation)+ * over a dirty rectangle and composites it onto `targetCtx`.+ */+ public applyImpastoReliefGpu(+ targetCtx: CanvasRenderingContext2D,+ rx: number,+ ry: number,+ rw: number,+ rh: number,+ colorRgba: Uint8Array,+ heightToothRgba: Uint8Array,+ impasto: ImpastoSettings,+ granulation: number = 0,+ wetEdge: number = 0,+ replaceRegion: boolean = false,+ opacity: number = 1.0,+ compositeOp: GlobalCompositeOperation = 'source-over'+ ): boolean {+ const canvas = this.canvas;+ const gl = this.gl;+ if (+ !this.isAvailable() ||+ !gl ||+ !canvas ||+ !this.impastoProgram ||+ !this.fullQuadBuffer ||+ rw <= 0 ||+ rh <= 0 ||+ rw > MAX_TILE_CHUNK ||+ rh > MAX_TILE_CHUNK+ ) {+ return false;+ }++ if (canvas.width < rw || canvas.height < rh) {+ canvas.width = Math.max(canvas.width, rw, 512);+ canvas.height = Math.max(canvas.height, rh, 512);+ }++ if (!this.impastoColorTex) this.impastoColorTex = gl.createTexture();+ if (!this.impastoHeightTex) this.impastoHeightTex = gl.createTexture();+ if (!this.impastoColorTex || !this.impastoHeightTex) return false;++ gl.activeTexture(gl.TEXTURE0);+ gl.bindTexture(gl.TEXTURE_2D, this.impastoColorTex);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, rw, rh, 0, gl.RGBA, gl.UNSIGNED_BYTE, colorRgba);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);++ gl.activeTexture(gl.TEXTURE1);+ gl.bindTexture(gl.TEXTURE_2D, this.impastoHeightTex);+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, rw, rh, 0, gl.RGBA, gl.UNSIGNED_BYTE, heightToothRgba);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);++ const viewY = Math.max(0, canvas.height - rh);+ gl.viewport(0, viewY, rw, rh);+ if (typeof gl.scissor === 'function') {+ gl.enable(gl.SCISSOR_TEST);+ gl.scissor(0, viewY, rw, rh);+ }+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);++ gl.useProgram(this.impastoProgram);+ gl.uniform1i(this.uImpastoColorTexLoc, 0);+ gl.uniform1i(this.uImpastoHeightTexLoc, 1);+ gl.uniform2f(this.uImpastoTexelSizeLoc, 1.0 / rw, 1.0 / rh);++ const az = (impasto.lightAzimuth * Math.PI) / 180;+ const el = (Math.max(5, Math.min(85, impasto.lightElevation)) * Math.PI) / 180;+ gl.uniform3f(+ this.uImpastoLightDirLoc,+ Math.cos(az) * Math.cos(el),+ Math.sin(az) * Math.cos(el),+ Math.sin(el)+ );+ gl.uniform1f(this.uImpastoDepthLoc, impasto.enabled ? impasto.depth : 0.0);+ gl.uniform1f(this.uImpastoGlossLoc, impasto.gloss);+ gl.uniform1f(this.uImpastoContrastLoc, impasto.reliefContrast);+ gl.uniform1f(this.uImpastoGranulationLoc, granulation);+ gl.uniform1f(this.uImpastoWetEdgeLoc, wetEdge);++ gl.bindBuffer(gl.ARRAY_BUFFER, this.fullQuadBuffer);+ gl.enableVertexAttribArray(this.aImpastoPosLoc);+ gl.vertexAttribPointer(this.aImpastoPosLoc, 2, gl.FLOAT, false, 0, 0);+ gl.drawArrays(gl.TRIANGLES, 0, 6);+ gl.disableVertexAttribArray(this.aImpastoPosLoc);++ if (typeof gl.scissor === 'function') {+ gl.disable(gl.SCISSOR_TEST);+ }++ targetCtx.save();+ if (replaceRegion) {+ targetCtx.clearRect(rx, ry, rw, rh);+ }+ targetCtx.globalCompositeOperation = compositeOp;+ targetCtx.globalAlpha = Math.max(0, Math.min(1, opacity));+ targetCtx.drawImage(canvas, 0, 0, rw, rh, rx, ry, rw, rh);+ targetCtx.restore();+ return true;+ }+public parseColor(color: string): { r: number; g: number; b: number } {if (color.startsWith('#')) {let hex = color.slice(1);@@ -1023,7 +1524,7 @@ export class WebGlBrushEngine {const useOffscreenFbo = this.ensureDabFbo(canvas.width, canvas.height);- const stride = 14;+ const stride = 15;const requiredFloats = dabs.length * stride;if (this.instanceArray.length < requiredFloats) {this.instanceArray = new Float32Array(Math.max(requiredFloats, this.instanceArray.length * 2));@@ -1058,6 +1559,7 @@ export class WebGlBrushEngine {arr[offset + 11] = d.strokeDist;arr[offset + 12] = d.flipX ?? 1.0;arr[offset + 13] = d.flipY ?? 1.0;+ arr[offset + 14] = d.tipIndex ?? 0.0;}if (this.instanceBuffer) {@@ -1080,9 +1582,31 @@ export class WebGlBrushEngine {gl.uniform1f(this.uWetEdgeLoc, settings.wetEdge ?? 0.0);const paperDensity = settings.grain ?? (settings.textureDensity ?? 0.0);+ const dryBrush = settings.naturalPaint?.dryBrush ?? 0.0;+ const paintLoad = settings.naturalPaint?.paintLoad ?? 1.0;gl.uniform1f(this.uPaperGrainLoc, paperDensity);gl.uniform1f(this.uGrainScaleLoc, settings.paperTextureScale ?? 1.0);gl.uniform1f(this.uGrainRotateRadLoc, ((settings.paperTextureRotate ?? 0) * Math.PI) / 180);+ const gmMode =+ settings.grainMappingMode === 'brush-aligned'+ ? 1+ : settings.grainMappingMode === 'stroke-flow'+ ? 2+ : settings.grainMappingMode === 'random-per-stroke'+ ? 3+ : 0;+ if (this.uGrainMappingModeLoc) gl.uniform1i(this.uGrainMappingModeLoc, gmMode);+ if (this.uGrainRandomOffsetLoc) {+ const seed = dabs.length > 0 ? Math.abs(Math.sin(dabs[0].x * 12.9898 + dabs[0].y * 78.233)) : 0;+ gl.uniform2f(this.uGrainRandomOffsetLoc, seed * 256, ((seed * 397) % 1) * 256);+ }+ if (this.uGrainRandomRotLoc) {+ const seedR = dabs.length > 0 ? Math.abs(Math.cos(dabs[0].x * 39.346 + dabs[0].y * 11.135)) * Math.PI * 2 : 0;+ gl.uniform1f(this.uGrainRandomRotLoc, seedR);+ }+ if (this.uDryBrushLoc) gl.uniform1f(this.uDryBrushLoc, dryBrush);+ if (this.uPaintLoadLoc) gl.uniform1f(this.uPaintLoadLoc, paintLoad);+const pMode =settings.paperTextureMode === 'multiply'? 1@@ -1100,7 +1624,7 @@ export class WebGlBrushEngine {gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);- if (paperDensity > 0.001) {+ if (paperDensity > 0.001 || dryBrush > 0.001) {if (!this.builtinPaperTexture && WebGlBrushEngine.builtinGrainTable) {this.uploadBuiltinPaperTexture(gl);}@@ -1111,6 +1635,10 @@ export class WebGlBrushEngine {paperTex = this.getOrCreateTipTexture(settings.paperTextureImage, true);paperW = settings.paperTextureImage.naturalWidth || settings.paperTextureImage.width || paperW;paperH = settings.paperTextureImage.naturalHeight || settings.paperTextureImage.height || paperH;+ } else if (settings.surfaceTextureId) {+ paperTex = this.getOrCreateSurfaceTexture(settings.surfaceTextureId);+ paperW = SURFACE_TEXTURE_SIZE;+ paperH = SURFACE_TEXTURE_SIZE;} else {paperTex = this.builtinPaperTexture;}@@ -1128,10 +1656,23 @@ export class WebGlBrushEngine {}let tipTex: WebGLTexture | null = null;- if (settings.customTipImage) {+ let atlasCols = 1;+ let atlasRows = 1;+ if (settings.subTipImages && settings.subTipImages.length > 1) {+ const atlas = this.getOrCreateMultiTipAtlas(settings.subTipImages);+ if (atlas) {+ tipTex = atlas.tex;+ atlasCols = atlas.cols;+ atlasRows = atlas.rows;+ }+ }+ if (!tipTex && settings.customTipImage) {tipTex = this.getOrCreateTipTexture(settings.customTipImage, false);}const isColorTip = Boolean(settings.isColorTip || (settings.subTips && settings.subTips[0]?.isColor));+ if (this.uTipAtlasGridLoc) {+ gl.uniform2f(this.uTipAtlasGridLoc, atlasCols, atlasRows);+ }if (tipTex) {gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, tipTex);@@ -1163,6 +1704,9 @@ export class WebGlBrushEngine {? 4: 0;gl.uniform1i(this.uDualBlendModeLoc, dualMode);+ if (this.uDualScaleLoc) gl.uniform1f(this.uDualScaleLoc, settings.dualScale ?? 1.0);+ if (this.uDualRotRadLoc) gl.uniform1f(this.uDualRotRadLoc, ((settings.dualAngle ?? 0) * Math.PI) / 180);+ if (this.uDualScatterLoc) gl.uniform1f(this.uDualScatterLoc, settings.dualScatter ?? 0.0);} else {gl.uniform1i(this.uHasDualTipTextureLoc, 0);}@@ -1172,7 +1716,12 @@ export class WebGlBrushEngine {gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);if (enableColorMix && underlyingCanvas) {- const canvasTex = this.uploadCanvasTexture(underlyingCanvas);+ const canvasTex = this.uploadCanvasTexture(underlyingCanvas, {+ x: fullDirtyX,+ y: fullDirtyY,+ width: totalW,+ height: totalH,+ });if (canvasTex) {gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D, canvasTex);@@ -1230,6 +1779,11 @@ export class WebGlBrushEngine {gl.vertexAttribPointer(this.aFlipLoc, 2, gl.FLOAT, false, byteStride, 12 * 4);this.extInstanced.vertexAttribDivisor(this.aFlipLoc, 1);}+ if (this.aTipIndexLoc >= 0) {+ gl.enableVertexAttribArray(this.aTipIndexLoc);+ gl.vertexAttribPointer(this.aTipIndexLoc, 1, gl.FLOAT, false, byteStride, 14 * 4);+ this.extInstanced.vertexAttribDivisor(this.aTipIndexLoc, 1);+ }}const compositeOp: GlobalCompositeOperation = isBgEraser@@ -1348,6 +1902,9 @@ export class WebGlBrushEngine {if (this.aFlipLoc >= 0) {gl.vertexAttrib2f(this.aFlipLoc, arr[offset + 12], arr[offset + 13]);}+ if (this.aTipIndexLoc >= 0) {+ gl.vertexAttrib1f(this.aTipIndexLoc, arr[offset + 14]);+ }gl.drawArrays(gl.TRIANGLES, 0, 6);}}@@ -1382,6 +1939,10 @@ export class WebGlBrushEngine {this.extInstanced.vertexAttribDivisor(this.aFlipLoc, 0);gl.disableVertexAttribArray(this.aFlipLoc);}+ if (this.aTipIndexLoc >= 0) {+ this.extInstanced.vertexAttribDivisor(this.aTipIndexLoc, 0);+ gl.disableVertexAttribArray(this.aTipIndexLoc);+ }gl.disableVertexAttribArray(this.aCenterLoc);gl.disableVertexAttribArray(this.aSizeLoc);gl.disableVertexAttribArray(this.aAngleLoc);diff --git a/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.tsindex 7c6514c..e525210 100644--- a/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts+++ b/src/hooks/drawing/brushStrokeSession/liveSegmentEmitter.ts@@ -69,6 +69,19 @@ export function emitLiveSegmentToDraft(return;}+ if (state.naturalPaintSession) {+ state.naturalPaintSession.drawCubicSegment(+ draftCtx,+ sStart,+ c1Pt,+ c2Pt,+ sEnd,+ state.layerPixelSampler || undefined,+ true+ );+ return;+ }+const liveColor =(isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;const draftCanvas = params.effectiveDraftCanvasRef?.current as@@ -115,7 +128,14 @@ export function renderPredictedStrokeOverlay(): void {helpers.clearPredictedCanvas();const bs = helpers.getBrushSettings();- if (helpers.getTool() === 'eraser' || bs.isTransparentInk || bs.colorMixing) return;+ if (+ helpers.getTool() === 'eraser' ||+ bs.isTransparentInk ||+ bs.colorMixing ||+ state.naturalPaintSession+ ) {+ return;+ }const pipeline = state.strokePipeline;if (pipeline.getKnotCount() < 2) return;const pCanvas = helpers.getPredictedCanvas();diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.tsindex dac6a9b..db06700 100644--- a/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerDownHandler.ts@@ -2,6 +2,10 @@ import React from 'react';import { Point } from '../../../types/editor';import { calculateStrokeWidth, get2DContext } from '../../../utils/canvasUtils';import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';+import {+ isNaturalPaintBrush,+ NaturalPaintStrokeSession,+} from '../../../engine/NaturalPaintRenderer';import { useUiStore } from '../../../stores';import { recoveryService } from '../../../services/recoveryService';import { isLinearPressureCurve } from '../../../utils/pressureCurve';@@ -316,10 +320,25 @@ export function runPointerDown(state.dirtyRect.maxY);- const isWetColor = !isEraser && Boolean(bs.colorMixing);+ const isNaturalBrush =+ !isEraser &&+ !isBgEraser &&+ !isMonochrome &&+ !bs.isTransparentInk &&+ !isVectorOrMask &&+ isNaturalPaintBrush(bs);+ const isWetColor =+ !isEraser &&+ bs.colorMixing !== false &&+ (Boolean(bs.colorMixing) || (isNaturalBrush && Boolean(bs.naturalPaint?.spatialMixing)));state.isWetColorStroke = isWetColor;state.liveNeedsNotify = false;+ if (state.naturalPaintSession) {+ state.naturalPaintSession.finishAndDispose();+ state.naturalPaintSession = null;+ }+if (isWetColor) {state.layerPixelSampler = new LayerPixelSampler(maskCanvas || dims,@@ -332,6 +351,16 @@ export function runPointerDown(state.activeReservoir = null;}+ if (isNaturalBrush) {+ state.naturalStrokeSeed = (state.naturalStrokeSeed + 9973) & 0x7fffffff;+ state.naturalPaintSession = new NaturalPaintStrokeSession(+ bs,+ strokeColor,+ undefined,+ state.naturalStrokeSeed+ );+ }+const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;state.currentStrokeId = strokeId;params.onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);diff --git a/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.tsindex 6916f21..bcf07de 100644--- a/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerDownInitialStamp.ts@@ -142,6 +142,16 @@ export function renderInitialStrokeDot(return;}+ if (state.naturalPaintSession) {+ state.naturalPaintSession.stampInitialPoint(+ draftCtx,+ firstDotPoint,+ state.layerPixelSampler || undefined,+ true+ );+ return;+ }+const liveColor =(isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;const liveAA = helpers.resolveLiveAntiAlias(bs, isMonochrome, draftScale);diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.tsindex e9b8ca1..33a2e17 100644--- a/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerUpHandler.ts@@ -334,6 +334,10 @@ export function runPointerUp(state.isShiftLineStroke = false;state.layerPixelSampler = null;state.activeReservoir = null;+ if (state.naturalPaintSession) {+ state.naturalPaintSession.finishAndDispose();+ state.naturalPaintSession = null;+ }state.snapSession.endStroke();state.straightSnapSession.endStroke();helpers.emitConstraintAxisChange(null);diff --git a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.tsindex 0090d26..76dbbbe 100644--- a/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts+++ b/src/hooks/drawing/brushStrokeSession/pointerUpRasterCommit.ts@@ -147,6 +147,70 @@ export function commitRasterStrokeToTiles(helpers.markTouchedTiles(sx, sy, sx + dw, sy + dh);}+ // Zero-pop Natural Paint commit: flush remaining tail segments into the exact live+ // NaturalPaintStrokeSession and composite its shaded RGBA directly into the sparse tiles.+ if (state.naturalPaintSession) {+ const natSession = state.naturalPaintSession;+ state.naturalPaintSession = null;++ for (let i = 0; i < tailSegments.length; i++) {+ const seg = tailSegments[i];+ const batch = natSession.engine.emitCubicSegment(+ seg.p0,+ seg.c1,+ seg.c2,+ seg.p3,+ state.layerPixelSampler || undefined+ );+ natSession.rasterizeBatch(batch);+ }+ if (tailSegments.length === 0) {+ natSession.flushPendingTapIfNeeded(state.layerPixelSampler || undefined);+ }++ const beforeSnapshot = new Map<+ string,+ { format: TileFormat; data: Uint8Array | null }+ >();+ const spans = helpers.buildTouchedTileSpans(sx, sy, dw, dh);+ for (let i = 0; i < spans.length; i++) {+ const sp = spans[i];+ const rgba = new Uint8ClampedArray(sp.width * sp.height * 4);+ natSession.shadeRectToBuffer(sp.x, sp.y, sp.width, sp.height, rgba);+ const spanData =+ typeof ImageData !== 'undefined'+ ? new ImageData(rgba, sp.width, sp.height)+ : ({ data: rgba, width: sp.width, height: sp.height } as ImageData);+ grid.compositeStrokeToTiles({+ layerId: currentLayerId,+ strokeData: spanData,+ destX: sp.x,+ destY: sp.y,+ format: targetFormat,+ compositeOp,+ opacity: bs.opacity ?? 1.0,+ monochrome: monoOpts,+ selectionMask: selMaskOpts,+ snapshotOut: beforeSnapshot,+ suppressNotify: true,+ });+ }++ natSession.finishAndDispose();++ return createRasterPostPresentWork(+ grid,+ beforeSnapshot,+ currentLayerId,+ dirtyRect,+ toolForHistory,+ label,+ strokeIdForHistory,+ enqueueHistoryTask,+ pushHistoryStep+ );+ }+if (canDirectDraftCommit && draftCanvas && draftCtx && draftDocRect) {return commitDirectDraftToTiles({state,diff --git a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts b/src/hooks/drawing/brushStrokeSession/strokeHelpers.tsindex 586db4f..cd3fb31 100644--- a/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts+++ b/src/hooks/drawing/brushStrokeSession/strokeHelpers.ts@@ -193,6 +193,10 @@ export function abortActiveStrokeSession(state.isShiftLineStroke = false;state.layerPixelSampler = null;state.activeReservoir = null;+ if (state.naturalPaintSession) {+ state.naturalPaintSession.finishAndDispose();+ state.naturalPaintSession = null;+ }state.snapSession.endStroke();state.straightSnapSession.endStroke();emitConstraintAxisChange(null);diff --git a/src/hooks/drawing/brushStrokeSession/types.ts b/src/hooks/drawing/brushStrokeSession/types.tsindex 789f092..8b0b644 100644--- a/src/hooks/drawing/brushStrokeSession/types.ts+++ b/src/hooks/drawing/brushStrokeSession/types.ts@@ -15,6 +15,7 @@ import { StrokePipeline } from '../../../engine/StrokePipeline';import { CubicBezierSegment } from '../../../engine/SplineGenerator';import { BrushRenderOptions } from '../../../engine/BrushEngine';import { GpuDab } from '../../../engine/WebGlBrushEngine';+import { NaturalPaintStrokeSession } from '../../../engine/NaturalPaintRenderer';import { PaintReservoir, LayerPixelSampler } from '../../../utils/colorMixingEngine';import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../../../types/perspective';import { PerspectiveSnapSession } from '../../../utils/perspectiveSnapping';@@ -147,6 +148,8 @@ export interface StrokeSessionState {liveDabCounter: { count: number };activeReservoir: PaintReservoir | null;layerPixelSampler: LayerPixelSampler | null;+ naturalPaintSession: NaturalPaintStrokeSession | null;+ naturalStrokeSeed: number;isWetColorStroke: boolean;liveNeedsNotify: boolean;isShiftLineStroke: boolean;@@ -192,6 +195,8 @@ export function createInitialStrokeSessionState(): StrokeSessionState {liveDabCounter: { count: 0 },activeReservoir: null,layerPixelSampler: null,+ naturalPaintSession: null,+ naturalStrokeSeed: 1337,isWetColorStroke: false,liveNeedsNotify: false,isShiftLineStroke: false,diff --git a/src/hooks/drawing/index.ts b/src/hooks/drawing/index.tsindex 0b4305e..a4d0b85 100644--- a/src/hooks/drawing/index.ts+++ b/src/hooks/drawing/index.ts@@ -4,3 +4,7 @@ export { useBrushStrokeSession } from './useBrushStrokeSession';export { useVectorDrawing, commitVectorStrokeOrErase } from './useVectorDrawing';export { useSelectionTools } from './useSelectionTools';export { useShapeAndFillTools } from './useShapeAndFillTools';+export { useGradientTool } from './useGradientTool';+export { useRetouchTool } from './useRetouchTool';+export type { CloneSourceIndicator } from './useRetouchTool';+export { usePenTool } from './usePenTool';diff --git a/src/hooks/drawing/types.ts b/src/hooks/drawing/types.tsindex 59ecec3..b4985d7 100644--- a/src/hooks/drawing/types.ts+++ b/src/hooks/drawing/types.ts@@ -9,6 +9,7 @@ import {CanvasColorMode,DirtyRect,LayerItem,+ LayerTreeDelta,TileDelta,VectorStroke,} from '../../types/editor';@@ -41,6 +42,16 @@ export interface LastStrokeEndState {layerId: string;}+export type ApplyLayerTreeDeltaFn = (+ delta: LayerTreeDelta,+ direction: 'undo' | 'redo'+) => {+ nextLayers: LayerItem[];+ nextActiveLayerId: string | null;+ removedLayerIds: string[];+ addedLayers: LayerItem[];+};+export type PushHistoryStepFn = (actionType: HistoryActionType,label: string,@@ -52,7 +63,8 @@ export type PushHistoryStepFn = (vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },peerId?: string | number,strokeId?: string,- isMaskEdit?: boolean+ isMaskEdit?: boolean,+ layerTreeDelta?: LayerTreeDelta) => void;export interface UseCanvasDrawingProps {@@ -74,6 +86,7 @@ export interface UseCanvasDrawingProps {activeLayerVisible?: boolean;layers?: LayerItem[];onUpdateLayerThumbnail: (layerId: string) => void;+ onApplyLayerTreeDelta?: ApplyLayerTreeDeltaFn;isMaskMode?: boolean;onUpdateMaskThumbnail?: (layerId: string) => void;draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.tsindex e5e2a55..892dc48 100644--- a/src/hooks/drawing/useBrushStrokeSession.ts+++ b/src/hooks/drawing/useBrushStrokeSession.ts@@ -461,7 +461,11 @@ export function useBrushStrokeSession(if (s.phase === 1) {// Pen down- if (isBrushOrEraser && isPointOverCanvasViewport(s.clientX, s.clientY)) {+ if (+ !paramsRef.current.disabled &&+ isBrushOrEraser &&+ isPointOverCanvasViewport(s.clientX, s.clientY)+ ) {const isTailEraser = (s.buttons & 8) !== 0;if (isTailEraser && curTool !== 'eraser') {prevToolBeforeEraserFlip = curTool;diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.tsindex 1d6bb00..1472888 100644--- a/src/hooks/drawing/useDrawingHistory.ts+++ b/src/hooks/drawing/useDrawingHistory.ts@@ -7,6 +7,7 @@ import {HistoryItem,HistoryItemMeta,LayerItem,+ LayerTreeDelta,TileDelta,VectorStroke,} from '../../types/editor';@@ -22,7 +23,12 @@ import { multiplayerService } from '../../services/multiplayerService';import { recoveryService } from '../../services/recoveryService';import { renderVectorLayer } from '../../utils/vectorEngine';import { createCanvasThumbnail, formatTime, get2DContext } from '../../utils/canvasUtils';-import { isBackgroundLayerId, LastStrokeEndState, PushHistoryStepFn } from './types';+import {+ ApplyLayerTreeDeltaFn,+ isBackgroundLayerId,+ LastStrokeEndState,+ PushHistoryStepFn,+} from './types';type IdleCallbackWindow = Window & {requestIdleCallback?: (cb: () => void, options?: { timeout: number }) => number;@@ -40,6 +46,7 @@ export interface UseDrawingHistoryParams {colorModeRef: React.MutableRefObject<CanvasColorMode>;layersRef: React.MutableRefObject<LayerItem[] | undefined>;onUpdateLayerThumbnail: (layerId: string) => void;+ onApplyLayerTreeDeltaRef?: React.MutableRefObject<ApplyLayerTreeDeltaFn | undefined>;onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;isDrawingRef: React.MutableRefObject<boolean>;lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;@@ -86,6 +93,7 @@ export function useDrawingHistory({colorModeRef,layersRef,onUpdateLayerThumbnail,+ onApplyLayerTreeDeltaRef,onUpdateMaskThumbnailRef,isDrawingRef,lastStrokeEndRef,@@ -198,7 +206,8 @@ export function useDrawingHistory({vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },peerId?: string | number,strokeId?: string,- isMaskEdit?: boolean+ isMaskEdit?: boolean,+ layerTreeDelta?: LayerTreeDelta) => {ensureInitialHistory();const now = Date.now();@@ -278,6 +287,7 @@ export function useDrawingHistory({dirtyRect: effectiveDirtyRect,tileDeltas: hasDeltas ? tileDeltas : undefined,vectorStrokesDelta: vectorDelta,+ layerTreeDelta,peerId,strokeId,isMaskEdit,@@ -431,7 +441,21 @@ export function useDrawingHistory({const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);const deltas = await undoCache.resolveDeltas(item);- if (item.isMaskEdit && targetLayer?.maskCanvas) {+ if (item.layerTreeDelta) {+ if (deltas && deltas.length > 0) {+ grid.applyTileDeltas(deltas, 'undo');+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });+ }+ }+ const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'undo');+ if (applied) {+ layersRef.current = applied.nextLayers;+ if (applied.nextActiveLayerId !== null) {+ activeLayerIdRef.current = applied.nextActiveLayerId;+ }+ }+ } else if (item.isMaskEdit && targetLayer?.maskCanvas) {const mCtx = get2DContext(targetLayer.maskCanvas);if (mCtx && item.beforeImageData) {const mx =@@ -563,7 +587,30 @@ export function useDrawingHistory({const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);const deltas = await undoCache.resolveDeltas(item);- if (item.isMaskEdit && targetLayer?.maskCanvas) {+ if (item.layerTreeDelta) {+ const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'redo');+ if (applied) {+ layersRef.current = applied.nextLayers;+ if (applied.nextActiveLayerId !== null) {+ activeLayerIdRef.current = applied.nextActiveLayerId;+ }+ }+ if (deltas && deltas.length > 0) {+ grid.applyTileDeltas(deltas, 'redo');+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(deltas, grid, { force: true });+ }+ const affectedLayerIds = new Set<string>();+ for (const d of deltas) {+ affectedLayerIds.add(parseTileKey(d.key).layerId);+ }+ for (const lid of affectedLayerIds) {+ if (lid !== targetLayerId) {+ onUpdateLayerThumbnail(lid);+ }+ }+ }+ } else if (item.isMaskEdit && targetLayer?.maskCanvas) {const mCtx = get2DContext(targetLayer.maskCanvas);if (mCtx && dataToApply) {const mx =@@ -701,11 +748,13 @@ export function useDrawingHistory({[abortActiveStrokeRef,activeLayerId,+ activeLayerIdRef,colorModeRef,dimensionsRef,flushPendingHistoryTasks,isDrawingRef,layersRef,+ onApplyLayerTreeDeltaRef,onUpdateLayerThumbnail,onUpdateMaskThumbnailRef,persistSessionHistory,@@ -788,7 +837,22 @@ export function useDrawingHistory({let syncedRemotely = false;const isLocalUndo = !peerIdToUndo || peerIdToUndo === 'local';- if (item.isMaskEdit && targetLayer?.maskCanvas) {+ if (item.layerTreeDelta) {+ resolvedDeltas = await undoCache.resolveDeltas(item);+ if (resolvedDeltas && resolvedDeltas.length > 0) {+ grid.applyTileDeltas(resolvedDeltas, 'undo');+ }+ const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'undo');+ if (applied) {+ layersRef.current = applied.nextLayers;+ if (applied.nextActiveLayerId !== null) {+ activeLayerIdRef.current = applied.nextActiveLayerId;+ }+ }+ if (isLocalUndo && multiplayerService.isConnected()) {+ syncedRemotely = true;+ }+ } else if (item.isMaskEdit && targetLayer?.maskCanvas) {const mCtx = get2DContext(targetLayer.maskCanvas);if (mCtx && item.beforeImageData) {const mx =@@ -918,11 +982,13 @@ export function useDrawingHistory({[abortActiveStrokeRef,activeLayerId,+ activeLayerIdRef,colorModeRef,dimensionsRef,flushPendingHistoryTasks,isDrawingRef,layersRef,+ onApplyLayerTreeDeltaRef,onUpdateLayerThumbnail,onUpdateMaskThumbnailRef,persistSessionHistory,diff --git a/src/hooks/drawing/useGradientTool.ts b/src/hooks/drawing/useGradientTool.tsnew file mode 100644index 0000000..7c49c96--- /dev/null+++ b/src/hooks/drawing/useGradientTool.ts@@ -0,0 +1,449 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import type {+ CanvasColorMode,+ CanvasDimensions,+ CanvasSelection,+ GradientDragPreview,+ GradientMeshState,+ LayerItem,+ Point2D,+} from '../../types/editor';+import {+ constrainGradientEndpoint,+ createDefaultGradientMesh,+ renderGradientToTileGrid,+} from '../../utils/gradientEngine';+import { documentStore } from '../../utils/documentStore';+import { TileFormat } from '../../utils/tileEngine';+import { multiplayerService } from '../../services/multiplayerService';+import { interactiveToolBridge, toolStoreActions, useToolStore } from '../../stores';+import type { PushHistoryStepFn } from './types';++export interface UseGradientToolParams {+ dimensions: CanvasDimensions;+ colorMode: CanvasColorMode;+ activeLayer: LayerItem | undefined;+ activeLayerId: string;+ selection: CanvasSelection | null;+ zoomRef: React.MutableRefObject<number>;+ flushPendingHistoryTasks?: () => void;+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;+ getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => Point2D;+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;+ pushHistoryStep: PushHistoryStepFn;+ showToast?: (msg: string) => void;+}++export interface UseGradientToolResult {+ gradientDragPreview: GradientDragPreview | null;+ gradientMesh: GradientMeshState | null;+ setGradientMesh: React.Dispatch<React.SetStateAction<GradientMeshState | null>>;+ handleInitGradientMesh: () => void;+ handleApplyGradientMesh: () => void;+ handleCancelGradientMesh: () => void;+ handleUpdateMeshNode: (index: number, patch: { color?: string; opacity?: number }) => void;+ handleGradientPointerDown: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;+ handleGradientPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;+ handleGradientPointerUp: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;+}++export function useGradientTool({+ dimensions,+ colorMode,+ activeLayer,+ activeLayerId,+ selection,+ zoomRef,+ flushPendingHistoryTasks,+ isLayerEffectivelyVisible,+ getCanvasCoords,+ updateLayerThumbnail,+ pushHistoryStep,+ showToast,+}: UseGradientToolParams): UseGradientToolResult {+ const [gradientDragPreview, setGradientDragPreview] = useState<GradientDragPreview | null>(null);+ const gradientMesh = useToolStore((s) => s.activeGradientMesh);+ const setGradientMesh: React.Dispatch<React.SetStateAction<GradientMeshState | null>> =+ useCallback((updater) => {+ toolStoreActions.setActiveGradientMesh(updater);+ }, []);++ const dragRef = useRef<{ start: Point2D; end: Point2D; type: 'linear' | 'radial' } | null>(null);+ const draggingMeshNodeRef = useRef<number | null>(null);+ const meshRectDragRef = useRef<{ start: Point2D; end: Point2D } | null>(null);+ const gradientMeshRef = useRef<GradientMeshState | null>(null);+ gradientMeshRef.current = gradientMesh;++ const canPaintActiveLayer = useCallback((): boolean => {+ if (+ !activeLayer ||+ activeLayer.type !== 'raster' ||+ activeLayer.locked ||+ !isLayerEffectivelyVisible(activeLayer)+ ) {+ showToast?.('Select an unlocked, visible raster layer to apply gradients');+ return false;+ }+ return true;+ }, [activeLayer, isLayerEffectivelyVisible, showToast]);++ const resolveLayerFormat = useCallback((): TileFormat => {+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');+ const isMono =+ !isBg && (colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome');+ return isMono ? 'monochrome-1bit' : 'color-32bit';+ }, [activeLayer?.expressionColor, activeLayerId, colorMode]);++ const handleInitGradientMesh = useCallback(() => {+ const { gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();+ const bounds = selection+ ? selection.bounds+ : {+ x: dimensions.width * 0.1,+ y: dimensions.height * 0.1,+ width: dimensions.width * 0.8,+ height: dimensions.height * 0.8,+ };+ setGradientMesh(+ createDefaultGradientMesh(+ bounds,+ gradientSettings.meshCols,+ gradientSettings.meshRows,+ primaryColor,+ secondaryColor,+ gradientSettings.stops+ )+ );+ }, [dimensions.height, dimensions.width, selection]);++ const handleApplyGradientMesh = useCallback(() => {+ const mesh = gradientMeshRef.current;+ if (!mesh) return;+ if (!canPaintActiveLayer()) return;++ flushPendingHistoryTasks?.();+ const { gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();+ const grid = documentStore.getActiveTileGrid();+ const res = renderGradientToTileGrid({+ grid,+ layerId: activeLayerId,+ dimensions,+ targetFormat: resolveLayerFormat(),+ settings: { ...gradientSettings, type: 'mesh' },+ primaryColor,+ secondaryColor,+ mesh,+ selection,+ alphaLock: Boolean(activeLayer?.alphaLocked),+ });++ if (res.modified && res.tileDeltas.length > 0) {+ pushHistoryStep(+ 'gradient',+ 'Mesh Gradient',+ null,+ null,+ activeLayerId,+ res.dirtyRect ?? undefined,+ res.tileDeltas+ );+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(res.tileDeltas, grid);+ }+ updateLayerThumbnail(activeLayerId, true);+ }+ setGradientMesh(null);+ }, [+ activeLayer?.alphaLocked,+ activeLayerId,+ canPaintActiveLayer,+ dimensions,+ flushPendingHistoryTasks,+ pushHistoryStep,+ resolveLayerFormat,+ selection,+ updateLayerThumbnail,+ ]);++ const handleCancelGradientMesh = useCallback(() => {+ dragRef.current = null;+ draggingMeshNodeRef.current = null;+ meshRectDragRef.current = null;+ setGradientDragPreview(null);+ setGradientMesh(null);+ }, []);++ const handleUpdateMeshNode = useCallback(+ (index: number, patch: { color?: string; opacity?: number }) => {+ setGradientMesh((prev) => {+ if (!prev || index < 0 || index >= prev.nodes.length) return prev;+ const nextNodes = prev.nodes.map((n, i) => (i === index ? { ...n, ...patch } : n));+ return { ...prev, nodes: nextNodes };+ });+ },+ []+ );++ // Clear preview / mesh when switching away from gradient tool or changing away from mesh type+ useEffect(() => {+ let prevTool = useToolStore.getState().tool;+ let prevType = useToolStore.getState().gradientSettings.type;+ return useToolStore.subscribe(() => {+ const s = useToolStore.getState();+ if (prevTool === 'gradient' && s.tool !== 'gradient') {+ handleCancelGradientMesh();+ } else if (prevType === 'mesh' && s.gradientSettings.type !== 'mesh') {+ setGradientMesh(null);+ }+ prevTool = s.tool;+ prevType = s.gradientSettings.type;+ });+ }, [handleCancelGradientMesh]);++ // Register bridge callbacks so ToolPropertyInspector can invoke mesh actions without prop drilling+ useEffect(() => {+ interactiveToolBridge.initGradientMesh = handleInitGradientMesh;+ interactiveToolBridge.applyGradientMesh = handleApplyGradientMesh;+ interactiveToolBridge.cancelGradientMesh = handleCancelGradientMesh;+ return () => {+ interactiveToolBridge.initGradientMesh = undefined;+ interactiveToolBridge.applyGradientMesh = undefined;+ interactiveToolBridge.cancelGradientMesh = undefined;+ };+ }, [handleApplyGradientMesh, handleCancelGradientMesh, handleInitGradientMesh]);++ // Enter commits mesh, Escape cancels drag or mesh+ useEffect(() => {+ if (!gradientMesh && !gradientDragPreview) return;+ const onKeyDown = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape') {+ ev.preventDefault();+ handleCancelGradientMesh();+ } else if (ev.key === 'Enter' && gradientMeshRef.current) {+ ev.preventDefault();+ handleApplyGradientMesh();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [gradientDragPreview, gradientMesh, handleApplyGradientMesh, handleCancelGradientMesh]);++ const handleGradientPointerDown = useCallback(+ (e: React.PointerEvent<HTMLElement>, pt: Point2D): boolean => {+ const { tool, gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();+ if (tool !== 'gradient') return false;+ e.preventDefault();++ if (!canPaintActiveLayer()) return true;++ try {+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ } catch {+ // Ignore capture errors+ }++ if (gradientSettings.type === 'mesh') {+ const mesh = gradientMeshRef.current;+ if (mesh) {+ const hitRadius = 14 / Math.max(0.1, zoomRef.current || 1);+ let hitIdx = -1;+ let bestDist = hitRadius;+ for (let i = 0; i < mesh.nodes.length; i++) {+ const d = Math.hypot(mesh.nodes[i].x - pt.x, mesh.nodes[i].y - pt.y);+ if (d <= bestDist) {+ bestDist = d;+ hitIdx = i;+ }+ }+ if (hitIdx >= 0) {+ draggingMeshNodeRef.current = hitIdx;+ setGradientMesh((prev) => (prev ? { ...prev, selectedNodeIndex: hitIdx } : prev));+ return true;+ }+ }+ // Start dragging a new mesh bounding box (or click to initialize default bounds)+ meshRectDragRef.current = { start: pt, end: pt };+ const initial = createDefaultGradientMesh(+ { x: pt.x, y: pt.y, width: 1, height: 1 },+ gradientSettings.meshCols,+ gradientSettings.meshRows,+ primaryColor,+ secondaryColor,+ gradientSettings.stops+ );+ setGradientMesh(initial);+ return true;+ }++ const mode = gradientSettings.type === 'radial' ? 'radial' : 'linear';+ dragRef.current = { start: pt, end: pt, type: mode };+ setGradientDragPreview({+ type: mode,+ start: pt,+ end: pt,+ settings: gradientSettings,+ });+ return true;+ },+ [canPaintActiveLayer, zoomRef]+ );++ const handleGradientPointerMove = useCallback(+ (e: React.PointerEvent<HTMLElement>): boolean => {+ const { tool, gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();+ if (tool !== 'gradient') return false;++ if (draggingMeshNodeRef.current !== null && gradientMeshRef.current) {+ const pt = getCanvasCoords(e);+ const nodeIdx = draggingMeshNodeRef.current;+ setGradientMesh((prev) => {+ if (!prev || nodeIdx < 0 || nodeIdx >= prev.nodes.length) return prev;+ const nextNodes = prev.nodes.map((n, i) =>+ i === nodeIdx ? { ...n, x: pt.x, y: pt.y } : n+ );+ return { ...prev, nodes: nextNodes };+ });+ return true;+ }++ if (meshRectDragRef.current) {+ const pt = getCanvasCoords(e);+ meshRectDragRef.current.end = pt;+ const s = meshRectDragRef.current.start;+ const x = Math.min(s.x, pt.x);+ const y = Math.min(s.y, pt.y);+ const w = Math.max(4, Math.abs(pt.x - s.x));+ const h = Math.max(4, Math.abs(pt.y - s.y));+ setGradientMesh(+ createDefaultGradientMesh(+ { x, y, width: w, height: h },+ gradientSettings.meshCols,+ gradientSettings.meshRows,+ primaryColor,+ secondaryColor,+ gradientSettings.stops+ )+ );+ return true;+ }++ if (dragRef.current) {+ const rawPt = getCanvasCoords(e);+ const pt = e.shiftKey ? constrainGradientEndpoint(dragRef.current.start, rawPt) : rawPt;+ dragRef.current.end = pt;+ setGradientDragPreview({+ type: dragRef.current.type,+ start: dragRef.current.start,+ end: pt,+ settings: gradientSettings,+ });+ return true;+ }++ return false;+ },+ [getCanvasCoords]+ );++ const handleGradientPointerUp = useCallback(+ (e: React.PointerEvent<HTMLElement>, pt: Point2D): boolean => {+ const { tool, gradientSettings, primaryColor, secondaryColor } = useToolStore.getState();+ if (tool !== 'gradient') return false;++ try {+ if ((e.target as HTMLElement).hasPointerCapture?.(e.pointerId)) {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ }+ } catch {+ // Ignore capture release errors+ }++ if (draggingMeshNodeRef.current !== null) {+ draggingMeshNodeRef.current = null;+ return true;+ }++ if (meshRectDragRef.current) {+ const start = meshRectDragRef.current.start;+ meshRectDragRef.current = null;+ if (Math.hypot(pt.x - start.x, pt.y - start.y) < 12) {+ handleInitGradientMesh();+ }+ return true;+ }++ if (dragRef.current) {+ const start = dragRef.current.start;+ const end = e.shiftKey ? constrainGradientEndpoint(start, pt) : pt;+ const dragType = dragRef.current.type;+ dragRef.current = null;+ setGradientDragPreview(null);++ if (Math.hypot(end.x - start.x, end.y - start.y) < 2) {+ return true;+ }+ if (!canPaintActiveLayer()) return true;++ flushPendingHistoryTasks?.();+ const grid = documentStore.getActiveTileGrid();+ const res = renderGradientToTileGrid({+ grid,+ layerId: activeLayerId,+ dimensions,+ targetFormat: resolveLayerFormat(),+ settings: { ...gradientSettings, type: dragType },+ primaryColor,+ secondaryColor,+ start,+ end,+ selection,+ alphaLock: Boolean(activeLayer?.alphaLocked),+ });++ if (res.modified && res.tileDeltas.length > 0) {+ pushHistoryStep(+ 'gradient',+ dragType === 'radial' ? 'Radial Gradient' : 'Linear Gradient',+ null,+ null,+ activeLayerId,+ res.dirtyRect ?? undefined,+ res.tileDeltas+ );+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(res.tileDeltas, grid);+ }+ updateLayerThumbnail(activeLayerId, true);+ }+ return true;+ }++ return false;+ },+ [+ activeLayer?.alphaLocked,+ activeLayerId,+ canPaintActiveLayer,+ dimensions,+ flushPendingHistoryTasks,+ handleInitGradientMesh,+ pushHistoryStep,+ resolveLayerFormat,+ selection,+ updateLayerThumbnail,+ ]+ );++ return {+ gradientDragPreview,+ gradientMesh,+ setGradientMesh,+ handleInitGradientMesh,+ handleApplyGradientMesh,+ handleCancelGradientMesh,+ handleUpdateMeshNode,+ handleGradientPointerDown,+ handleGradientPointerMove,+ handleGradientPointerUp,+ };+}diff --git a/src/hooks/drawing/usePenTool.ts b/src/hooks/drawing/usePenTool.tsnew file mode 100644index 0000000..3beed09--- /dev/null+++ b/src/hooks/drawing/usePenTool.ts@@ -0,0 +1,725 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import type {+ CanvasColorMode,+ CanvasDimensions,+ CanvasSelection,+ LayerItem,+ PenPathSession,+ Point2D,+ VectorKnot,+ VectorStroke,+} from '../../types/editor';+import {+ computeBezierPathBounds,+ findClosestPointOnBezierPath,+ insertBezierAnchorAt,+ moveBezierAnchor,+ moveBezierHandle,+ toggleBezierAnchorSmooth,+} from '../../utils/bezierEngine';+import { renderVectorLayer, renderVectorStroke } from '../../utils/vectorEngine';+import { createSelectionMask } from '../../utils/tonalEngine';+import { documentStore } from '../../utils/documentStore';+import { TileFormat, TileSnapshotEntry, releaseTemporaryCanvas } from '../../utils/tileEngine';+import { get2DContext } from '../../utils/canvasUtils';+import { multiplayerService } from '../../services/multiplayerService';+import { interactiveToolBridge, toolStoreActions, useToolStore } from '../../stores';+import type { PushHistoryStepFn } from './types';++export interface UsePenToolParams {+ dimensions: CanvasDimensions;+ colorMode: CanvasColorMode;+ activeLayer: LayerItem | undefined;+ activeLayerId: string;+ selection: CanvasSelection | null;+ zoomRef: React.MutableRefObject<number>;+ flushPendingHistoryTasks?: () => void;+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;+ getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => Point2D;+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;+ pushHistoryStep: PushHistoryStepFn;+ showToast?: (msg: string) => void;+}++export interface UsePenToolResult {+ penSession: PenPathSession | null;+ setPenSession: React.Dispatch<React.SetStateAction<PenPathSession | null>>;+ handleCommitPenPath: () => void;+ handleCancelPenPath: () => void;+ handleClosePenPath: () => void;+ handleDeleteSelectedAnchor: () => void;+ handleToggleSelectedAnchorSmooth: () => void;+ handlePenPointerDown: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;+ handlePenPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;+ handlePenPointerUp: (e: React.PointerEvent<HTMLElement>) => boolean;+}++type PenDragState =+ | { kind: 'placing-handle'; anchorIndex: number; origin: Point2D }+ | { kind: 'move-anchor'; anchorIndex: number }+ | { kind: 'move-handle'; anchorIndex: number; which: 'in' | 'out' }+ | null;++function resolvePenFillColor(+ fillEnabled: boolean,+ fillColorMode: 'primary' | 'secondary' | 'custom',+ customFillColor: string,+ primaryColor: string,+ secondaryColor: string+): string | null {+ if (!fillEnabled) return null;+ if (fillColorMode === 'primary') return primaryColor || '#000000';+ if (fillColorMode === 'secondary') return secondaryColor || '#ffffff';+ return customFillColor || '#ffffff';+}++export function usePenTool({+ dimensions,+ colorMode,+ activeLayer,+ activeLayerId,+ selection,+ zoomRef,+ flushPendingHistoryTasks,+ isLayerEffectivelyVisible,+ getCanvasCoords,+ updateLayerThumbnail,+ pushHistoryStep,+ showToast,+}: UsePenToolParams): UsePenToolResult {+ const [penSession, setPenSession] = useState<PenPathSession | null>(null);+ const penSessionRef = useRef<PenPathSession | null>(null);+ penSessionRef.current = penSession;++ const dragRef = useRef<PenDragState>(null);+ const lastClickRef = useRef<{ time: number; x: number; y: number }>({ time: 0, x: 0, y: 0 });++ const handleCancelPenPath = useCallback(() => {+ dragRef.current = null;+ setPenSession(null);+ }, []);++ const handleClosePenPath = useCallback(() => {+ setPenSession((prev) => {+ if (!prev || prev.knots.length < 2) return prev;+ return { ...prev, closed: !prev.closed };+ });+ }, []);++ const handleDeleteSelectedAnchor = useCallback(() => {+ setPenSession((prev) => {+ if (!prev || prev.knots.length === 0) return null;+ const targetIdx =+ prev.selectedAnchorIndex !== null &&+ prev.selectedAnchorIndex >= 0 &&+ prev.selectedAnchorIndex < prev.knots.length+ ? prev.selectedAnchorIndex+ : prev.knots.length - 1;+ const nextKnots = prev.knots.filter((_, i) => i !== targetIdx);+ if (nextKnots.length === 0) return null;+ return {+ ...prev,+ knots: nextKnots,+ closed: nextKnots.length < 2 ? false : prev.closed,+ selectedAnchorIndex: Math.min(targetIdx, nextKnots.length - 1),+ };+ });+ }, []);++ const handleToggleSelectedAnchorSmooth = useCallback(() => {+ setPenSession((prev) => {+ if (!prev || prev.selectedAnchorIndex === null) return prev;+ return {+ ...prev,+ knots: toggleBezierAnchorSmooth(prev.knots, prev.selectedAnchorIndex, prev.closed),+ };+ });+ }, []);++ const handleCommitPenPath = useCallback(() => {+ const session = penSessionRef.current;+ if (!session || session.knots.length < 2) {+ setPenSession(null);+ return;+ }++ if (+ !activeLayer ||+ (activeLayer.type !== 'raster' && activeLayer.type !== 'vector') ||+ activeLayer.locked ||+ !isLayerEffectivelyVisible(activeLayer)+ ) {+ showToast?.('Select an unlocked, visible Raster or Vector layer to commit Bézier path');+ return;+ }++ const { penSettings, primaryColor, secondaryColor } = useToolStore.getState();+ const strokeColor = penSettings.strokeEnabled ? primaryColor || '#000000' : 'none';+ const fillColor = resolvePenFillColor(+ penSettings.fillEnabled && session.closed,+ penSettings.fillColorMode,+ penSettings.customFillColor,+ primaryColor,+ secondaryColor+ );++ if (strokeColor === 'none' && !fillColor) {+ showToast?.('Enable Stroke or Fill (closed path) before committing');+ return;+ }++ const strokeWidth = Math.max(0.5, penSettings.strokeWidth || 4);+ const syncedKnots: VectorKnot[] = session.knots.map((k) => ({+ ...k,+ width: strokeWidth,+ handleIn: k.handleIn ? { ...k.handleIn } : null,+ handleOut: k.handleOut ? { ...k.handleOut } : null,+ }));+ const bounds = computeBezierPathBounds(syncedKnots, session.closed);++ const strokeId =+ session.editingStrokeId ||+ `bezier-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;++ const bezierStroke: VectorStroke = {+ id: strokeId,+ layerId: activeLayerId,+ tool: 'pen',+ curveType: 'bezier',+ closed: session.closed,+ fillColor,+ knots: syncedKnots,+ color: strokeColor,+ baseWidth: penSettings.strokeEnabled ? strokeWidth : 0,+ opacity: Math.max(0.05, Math.min(1, penSettings.opacity ?? 1)),+ bounds,+ };++ flushPendingHistoryTasks?.();+ const grid = documentStore.getActiveTileGrid();+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');+ const isMono =+ !isBg && (colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome');+ const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';++ if (activeLayer.type === 'vector') {+ const prevStrokes = [...(activeLayer.vectorStrokes || [])];+ const existingIdx = session.editingStrokeId+ ? prevStrokes.findIndex((s) => s.id === session.editingStrokeId)+ : -1;+ const updatedStrokes =+ existingIdx >= 0+ ? prevStrokes.map((s, idx) => (idx === existingIdx ? bezierStroke : s))+ : [...prevStrokes, bezierStroke];++ activeLayer.vectorStrokes = updatedStrokes;++ // Re-render affected bounding region from authoritative vector strokes+ let minX = bounds.minX;+ let minY = bounds.minY;+ let maxX = bounds.maxX;+ let maxY = bounds.maxY;+ if (existingIdx >= 0 && prevStrokes[existingIdx]?.bounds) {+ const pb = prevStrokes[existingIdx].bounds;+ minX = Math.min(minX, pb.minX);+ minY = Math.min(minY, pb.minY);+ maxX = Math.max(maxX, pb.maxX);+ maxY = Math.max(maxY, pb.maxY);+ }+ const pad = Math.ceil(Math.max(16, strokeWidth * 2));+ const vx = Math.max(0, Math.floor(minX - pad));+ const vy = Math.max(0, Math.floor(minY - pad));+ const vw = Math.max(0, Math.min(dimensions.width, Math.ceil(maxX + pad)) - vx);+ const vh = Math.max(0, Math.min(dimensions.height, Math.ceil(maxY + pad)) - vy);++ if (vw > 0 && vh > 0) {+ const temp = document.createElement('canvas');+ temp.width = vw;+ temp.height = vh;+ const ctx = get2DContext(temp);+ if (ctx) {+ ctx.save();+ ctx.translate(-vx, -vy);+ renderVectorLayer(ctx, updatedStrokes);+ ctx.restore();+ const subData = ctx.getImageData(0, 0, vw, vh);+ grid.writeImageData(activeLayerId, subData, vx, vy, targetFormat);+ }+ releaseTemporaryCanvas(temp);+ }++ pushHistoryStep(+ 'pen',+ existingIdx >= 0 ? 'Edit Bézier Path' : 'Bézier Pen Path',+ null,+ null,+ activeLayerId,+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : undefined,+ undefined,+ { before: prevStrokes, after: updatedStrokes },+ undefined,+ strokeId+ );+ if (multiplayerService.isConnected()) {+ multiplayerService.sendLayerUpdate(activeLayerId, { vectorStrokes: updatedStrokes });+ }+ updateLayerThumbnail(activeLayerId, true);+ setPenSession(null);+ return;+ }++ // Raster layer commit: render crisp native cubic Bézier path directly into SparseTileGrid ROI+ const pad = Math.ceil(Math.max(16, strokeWidth * 2));+ const vx = Math.max(0, Math.floor(bounds.minX - pad));+ const vy = Math.max(0, Math.floor(bounds.minY - pad));+ const vw = Math.max(0, Math.min(dimensions.width, Math.ceil(bounds.maxX + pad)) - vx);+ const vh = Math.max(0, Math.min(dimensions.height, Math.ceil(bounds.maxY + pad)) - vy);++ if (vw > 0 && vh > 0) {+ const dirtyRect = { x: vx, y: vy, width: vw, height: vh };+ const beforeSnapshot: Map<string, TileSnapshotEntry> = grid.snapshotTilesInRect(+ activeLayerId,+ dirtyRect+ );++ const overlay = document.createElement('canvas');+ overlay.width = vw;+ overlay.height = vh;+ const oCtx = get2DContext(overlay);+ if (oCtx) {+ oCtx.save();+ oCtx.translate(-vx, -vy);+ renderVectorStroke(oCtx, bezierStroke);+ oCtx.restore();++ const pathImg = oCtx.getImageData(0, 0, vw, vh);+ const selMask = selection+ ? createSelectionMask(selection, dimensions.width, dimensions.height)+ : null;+ if (selMask) {+ const pData = pathImg.data;+ for (let ly = 0; ly < vh; ly++) {+ const row = (vy + ly) * dimensions.width + vx;+ for (let lx = 0; lx < vw; lx++) {+ const m = selMask[row + lx];+ if (m < 255) {+ const idx = (ly * vw + lx) * 4 + 3;+ pData[idx] = Math.round((pData[idx] * m) / 255);+ }+ }+ }+ }++ // Composite onto existing region pixels respecting alphaLock+ const existing = grid.readImageData(activeLayerId, vx, vy, vw, vh);+ const dst = existing.data;+ const src = pathImg.data;+ const alphaLock = Boolean(activeLayer.alphaLocked);+ for (let i = 0; i < src.length; i += 4) {+ const sa = src[i + 3] / 255;+ if (sa <= 0) continue;+ const da = dst[i + 3] / 255;+ if (alphaLock && da <= 0) continue;+ if (alphaLock) {+ const inv = 1 - sa;+ dst[i] = Math.round(dst[i] * inv + src[i] * sa);+ dst[i + 1] = Math.round(dst[i + 1] * inv + src[i + 1] * sa);+ dst[i + 2] = Math.round(dst[i + 2] * inv + src[i + 2] * sa);+ } else {+ const outA = sa + da * (1 - sa);+ if (outA > 1e-6) {+ const invOut = 1 / outA;+ dst[i] = Math.round((src[i] * sa + dst[i] * da * (1 - sa)) * invOut);+ dst[i + 1] = Math.round((src[i + 1] * sa + dst[i + 1] * da * (1 - sa)) * invOut);+ dst[i + 2] = Math.round((src[i + 2] * sa + dst[i + 2] * da * (1 - sa)) * invOut);+ dst[i + 3] = Math.round(outA * 255);+ }+ }+ }++ grid.writeImageData(activeLayerId, existing, vx, vy, targetFormat);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, activeLayerId, dirtyRect);+ if (tileDeltas.length > 0) {+ pushHistoryStep(+ 'pen',+ 'Bézier Pen Path',+ null,+ null,+ activeLayerId,+ dirtyRect,+ tileDeltas+ );+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(tileDeltas, grid);+ }+ updateLayerThumbnail(activeLayerId, true);+ }+ }+ releaseTemporaryCanvas(overlay);+ }++ setPenSession(null);+ }, [+ activeLayer,+ activeLayerId,+ colorMode,+ dimensions.height,+ dimensions.width,+ flushPendingHistoryTasks,+ isLayerEffectivelyVisible,+ pushHistoryStep,+ selection,+ showToast,+ updateLayerThumbnail,+ ]);++ // Sync lightweight pen session metadata & action callbacks for ToolPropertyInspector+ useEffect(() => {+ toolStoreActions.setActivePenSessionMeta(+ penSession?.knots.length ?? 0,+ Boolean(penSession?.closed),+ penSession?.selectedAnchorIndex ?? null+ );+ }, [penSession?.knots.length, penSession?.closed, penSession?.selectedAnchorIndex]);++ useEffect(() => {+ interactiveToolBridge.commitPenPath = handleCommitPenPath;+ interactiveToolBridge.cancelPenPath = handleCancelPenPath;+ interactiveToolBridge.toggleClosePenPath = handleClosePenPath;+ interactiveToolBridge.deleteSelectedPenAnchor = handleDeleteSelectedAnchor;+ interactiveToolBridge.toggleSelectedPenAnchorSmooth = handleToggleSelectedAnchorSmooth;+ return () => {+ interactiveToolBridge.commitPenPath = undefined;+ interactiveToolBridge.cancelPenPath = undefined;+ interactiveToolBridge.toggleClosePenPath = undefined;+ interactiveToolBridge.deleteSelectedPenAnchor = undefined;+ interactiveToolBridge.toggleSelectedPenAnchorSmooth = undefined;+ };+ }, [+ handleCancelPenPath,+ handleClosePenPath,+ handleCommitPenPath,+ handleDeleteSelectedAnchor,+ handleToggleSelectedAnchorSmooth,+ ]);++ // Clear uncommitted path when switching away from pen tool+ useEffect(() => {+ let prevTool = useToolStore.getState().tool;+ return useToolStore.subscribe(() => {+ const curTool = useToolStore.getState().tool;+ if (prevTool === 'pen' && curTool !== 'pen') {+ handleCancelPenPath();+ }+ prevTool = curTool;+ });+ }, [handleCancelPenPath]);++ // Keyboard bindings for active pen path (Enter = commit, Esc = cancel, Backspace/Delete = remove anchor)+ useEffect(() => {+ if (!penSession) return;+ const onKeyDown = (ev: KeyboardEvent) => {+ const target = ev.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT')+ ) {+ return;+ }+ if (ev.key === 'Enter') {+ ev.preventDefault();+ handleCommitPenPath();+ } else if (ev.key === 'Escape') {+ ev.preventDefault();+ handleCancelPenPath();+ } else if (ev.key === 'Backspace' || ev.key === 'Delete') {+ ev.preventDefault();+ ev.stopPropagation();+ handleDeleteSelectedAnchor();+ }+ };+ window.addEventListener('keydown', onKeyDown, true);+ return () => window.removeEventListener('keydown', onKeyDown, true);+ }, [penSession, handleCancelPenPath, handleCommitPenPath, handleDeleteSelectedAnchor]);++ const handlePenPointerDown = useCallback(+ (e: React.PointerEvent<HTMLElement>, pt: Point2D): boolean => {+ const { tool, penSettings } = useToolStore.getState();+ if (tool !== 'pen') return false;+ e.preventDefault();++ if (+ !activeLayer ||+ (activeLayer.type !== 'raster' && activeLayer.type !== 'vector') ||+ activeLayer.locked ||+ !isLayerEffectivelyVisible(activeLayer)+ ) {+ showToast?.('Select an unlocked, visible Raster or Vector layer to use the Pen Tool');+ return true;+ }++ try {+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ } catch {+ // Ignore capture errors+ }++ const invZoom = 1 / Math.max(0.1, zoomRef.current || 1);+ const hitRadius = 11 * invZoom;+ const session = penSessionRef.current;+ const isEditInteraction = penSettings.mode === 'edit' || e.ctrlKey || e.metaKey;++ // 1. Check handle & anchor hits in edit mode (or Ctrl+click override)+ if (session && isEditInteraction) {+ // Test handles first so overlapping handles take priority when selected+ for (let i = 0; i < session.knots.length; i++) {+ const k = session.knots[i];+ if (k.handleIn && Math.hypot(k.handleIn.x - pt.x, k.handleIn.y - pt.y) <= hitRadius) {+ dragRef.current = { kind: 'move-handle', anchorIndex: i, which: 'in' };+ setPenSession((prev) => (prev ? { ...prev, selectedAnchorIndex: i } : prev));+ return true;+ }+ if (k.handleOut && Math.hypot(k.handleOut.x - pt.x, k.handleOut.y - pt.y) <= hitRadius) {+ dragRef.current = { kind: 'move-handle', anchorIndex: i, which: 'out' };+ setPenSession((prev) => (prev ? { ...prev, selectedAnchorIndex: i } : prev));+ return true;+ }+ }++ // Test anchors+ for (let i = 0; i < session.knots.length; i++) {+ const k = session.knots[i];+ if (Math.hypot(k.x - pt.x, k.y - pt.y) <= hitRadius) {+ if (e.altKey) {+ setPenSession((prev) =>+ prev+ ? {+ ...prev,+ knots: toggleBezierAnchorSmooth(prev.knots, i, prev.closed),+ selectedAnchorIndex: i,+ }+ : prev+ );+ return true;+ }+ dragRef.current = { kind: 'move-anchor', anchorIndex: i };+ setPenSession((prev) => (prev ? { ...prev, selectedAnchorIndex: i } : prev));+ return true;+ }+ }++ // Test curve segment hit -> exact de Casteljau anchor insertion+ if (session.knots.length >= 2) {+ const closest = findClosestPointOnBezierPath(session.knots, pt, session.closed);+ if (closest && closest.distance <= hitRadius) {+ const { knots: nextKnots, insertedIndex } = insertBezierAnchorAt(+ session.knots,+ closest.segmentIndex,+ closest.t,+ session.closed+ );+ if (insertedIndex >= 0) {+ setPenSession((prev) =>+ prev+ ? {+ ...prev,+ knots: nextKnots,+ selectedAnchorIndex: insertedIndex,+ }+ : prev+ );+ dragRef.current = { kind: 'move-anchor', anchorIndex: insertedIndex };+ return true;+ }+ }+ }+ return true;+ }++ // 2. If no active session & in Edit mode on a vector layer, try loading an existing Bézier stroke+ if (!session && penSettings.mode === 'edit' && activeLayer.type === 'vector' && activeLayer.vectorStrokes) {+ let bestStroke: VectorStroke | null = null;+ let bestDist = hitRadius * 1.4;+ for (const st of activeLayer.vectorStrokes) {+ if (st.deleted || st.knots.length < 2) continue;+ const hit = findClosestPointOnBezierPath(st.knots, pt, Boolean(st.closed));+ if (hit && hit.distance < bestDist) {+ bestDist = hit.distance;+ bestStroke = st;+ }+ }+ if (bestStroke) {+ setPenSession({+ editingStrokeId: bestStroke.id,+ knots: bestStroke.knots.map((k) => ({+ ...k,+ handleIn: k.handleIn ? { ...k.handleIn } : null,+ handleOut: k.handleOut ? { ...k.handleOut } : null,+ })),+ closed: Boolean(bestStroke.closed),+ selectedAnchorIndex: 0,+ hoverPoint: pt,+ });+ showToast?.('Loaded vector path for Bézier editing');+ return true;+ }+ showToast?.('Click a vector path to edit, or switch to Draw mode to plot a new Bézier path');+ return true;+ }++ // 3. Draw mode: double-click finishes open path cleanly+ const now = Date.now();+ const isDoubleClick =+ session &&+ session.knots.length >= 2 &&+ now - lastClickRef.current.time < 300 &&+ Math.hypot(pt.x - lastClickRef.current.x, pt.y - lastClickRef.current.y) <= hitRadius * 1.5;+ lastClickRef.current = { time: now, x: pt.x, y: pt.y };++ if (isDoubleClick) {+ handleCommitPenPath();+ return true;+ }++ // Closing path by clicking on first anchor+ if (session && !session.closed && session.knots.length >= 2) {+ const first = session.knots[0];+ if (Math.hypot(first.x - pt.x, first.y - pt.y) <= hitRadius) {+ setPenSession((prev) =>+ prev ? { ...prev, closed: true, selectedAnchorIndex: 0 } : prev+ );+ dragRef.current = { kind: 'placing-handle', anchorIndex: 0, origin: { x: first.x, y: first.y } };+ return true;+ }+ }++ // Append a new anchor knot+ const newKnot: VectorKnot = {+ x: pt.x,+ y: pt.y,+ pressure: 1,+ width: Math.max(0.5, penSettings.strokeWidth || 4),+ timestamp: now,+ handleIn: null,+ handleOut: null,+ handleType: 'corner',+ };++ const nextIndex = session ? session.knots.length : 0;+ setPenSession((prev) =>+ prev+ ? {+ ...prev,+ knots: [...prev.knots, newKnot],+ selectedAnchorIndex: nextIndex,+ hoverPoint: pt,+ }+ : {+ editingStrokeId: null,+ knots: [newKnot],+ closed: false,+ selectedAnchorIndex: 0,+ hoverPoint: pt,+ }+ );+ dragRef.current = { kind: 'placing-handle', anchorIndex: nextIndex, origin: { x: pt.x, y: pt.y } };+ return true;+ },+ [activeLayer, handleCommitPenPath, isLayerEffectivelyVisible, showToast, zoomRef]+ );++ const handlePenPointerMove = useCallback(+ (e: React.PointerEvent<HTMLElement>): boolean => {+ const { tool } = useToolStore.getState();+ if (tool !== 'pen') return false;++ const pt = getCanvasCoords(e);+ const drag = dragRef.current;++ if (!drag) {+ if (penSessionRef.current) {+ setPenSession((prev) => (prev ? { ...prev, hoverPoint: pt } : prev));+ }+ return true;+ }++ if (drag.kind === 'placing-handle') {+ const dist = Math.hypot(pt.x - drag.origin.x, pt.y - drag.origin.y);+ if (dist > 2) {+ const breakSym = e.altKey;+ setPenSession((prev) => {+ if (!prev || drag.anchorIndex >= prev.knots.length) return prev;+ const nextKnots = prev.knots.map((k, idx) => {+ if (idx !== drag.anchorIndex) return k;+ const dx = pt.x - k.x;+ const dy = pt.y - k.y;+ return {+ ...k,+ handleType: breakSym ? ('corner' as const) : ('symmetric' as const),+ handleOut: { x: pt.x, y: pt.y },+ handleIn: breakSym ? k.handleIn ?? null : { x: k.x - dx, y: k.y - dy },+ };+ });+ return { ...prev, knots: nextKnots, hoverPoint: pt };+ });+ }+ return true;+ }++ if (drag.kind === 'move-anchor') {+ setPenSession((prev) => {+ if (!prev || drag.anchorIndex >= prev.knots.length) return prev;+ const nextKnots = prev.knots.map((k, idx) =>+ idx === drag.anchorIndex ? moveBezierAnchor(k, pt) : k+ );+ return { ...prev, knots: nextKnots, hoverPoint: pt };+ });+ return true;+ }++ if (drag.kind === 'move-handle') {+ const breakSym = e.altKey;+ setPenSession((prev) => {+ if (!prev || drag.anchorIndex >= prev.knots.length) return prev;+ const nextKnots = prev.knots.map((k, idx) =>+ idx === drag.anchorIndex ? moveBezierHandle(k, drag.which, pt, breakSym) : k+ );+ return { ...prev, knots: nextKnots, hoverPoint: pt };+ });+ return true;+ }++ return true;+ },+ [getCanvasCoords]+ );++ const handlePenPointerUp = useCallback((e: React.PointerEvent<HTMLElement>): boolean => {+ const { tool } = useToolStore.getState();+ if (tool !== 'pen' && !dragRef.current) return false;++ try {+ if ((e.target as HTMLElement).hasPointerCapture?.(e.pointerId)) {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ }+ } catch {+ // Ignore capture errors+ }++ dragRef.current = null;+ return true;+ }, []);++ return {+ penSession,+ setPenSession,+ handleCommitPenPath,+ handleCancelPenPath,+ handleClosePenPath,+ handleDeleteSelectedAnchor,+ handleToggleSelectedAnchorSmooth,+ handlePenPointerDown,+ handlePenPointerMove,+ handlePenPointerUp,+ };+}diff --git a/src/hooks/drawing/useRetouchTool.ts b/src/hooks/drawing/useRetouchTool.tsnew file mode 100644index 0000000..c1a14ef--- /dev/null+++ b/src/hooks/drawing/useRetouchTool.ts@@ -0,0 +1,318 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import type {+ CanvasColorMode,+ CanvasDimensions,+ CanvasSelection,+ LayerItem,+ Point2D,+} from '../../types/editor';+import {+ RetouchStrokeSession,+ applyRetouchStrokeSegment,+ createRetouchStrokeSession,+} from '../../utils/retouchEngine';+import { createSelectionMask } from '../../utils/tonalEngine';+import { documentStore } from '../../utils/documentStore';+import { TileFormat } from '../../utils/tileEngine';+import { multiplayerService } from '../../services/multiplayerService';+import { toolStoreActions, useToolStore } from '../../stores';+import type { PushHistoryStepFn } from './types';++export interface CloneSourceIndicator {+ anchor: Point2D;+ liveSamplePos: Point2D | null;+ isPicking: boolean;+}++export interface UseRetouchToolParams {+ dimensions: CanvasDimensions;+ colorMode: CanvasColorMode;+ layers: LayerItem[];+ activeLayer: LayerItem | undefined;+ activeLayerId: string;+ selection: CanvasSelection | null;+ flushPendingHistoryTasks?: () => void;+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;+ getEffectiveOpacity: (layer: LayerItem) => number;+ getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => Point2D;+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;+ pushHistoryStep: PushHistoryStepFn;+ showToast?: (msg: string) => void;+}++export interface UseRetouchToolResult {+ cloneSourceIndicator: CloneSourceIndicator | null;+ isPickingCloneSource: boolean;+ setIsPickingCloneSource: React.Dispatch<React.SetStateAction<boolean>>;+ handleRetouchPointerDown: (e: React.PointerEvent<HTMLElement>, pt: Point2D) => boolean;+ handleRetouchPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;+ handleRetouchPointerUp: (e: React.PointerEvent<HTMLElement>) => boolean;+}++const MODE_LABELS: Record<string, string> = {+ smudge: 'Smudge',+ blur: 'Blur',+ dodge: 'Dodge',+ burn: 'Burn',+ 'clone-stamp': 'Clone Stamp',+};++export function useRetouchTool({+ dimensions,+ colorMode,+ layers,+ activeLayer,+ activeLayerId,+ selection,+ flushPendingHistoryTasks,+ isLayerEffectivelyVisible,+ getEffectiveOpacity,+ getCanvasCoords,+ updateLayerThumbnail,+ pushHistoryStep,+ showToast,+}: UseRetouchToolParams): UseRetouchToolResult {+ const cloneAnchor = useToolStore((s) => s.cloneSourceAnchor);+ const isPickingCloneSource = useToolStore((s) => s.isPickingCloneSource);+ const [liveSamplePos, setLiveSamplePos] = useState<Point2D | null>(null);++ const setCloneAnchor = useCallback((anchor: Point2D | null) => {+ toolStoreActions.setCloneSourceAnchor(anchor);+ }, []);+ const setIsPickingCloneSource: React.Dispatch<React.SetStateAction<boolean>> = useCallback(+ (next) => {+ const val =+ typeof next === 'function' ? next(useToolStore.getState().isPickingCloneSource) : next;+ toolStoreActions.setIsPickingCloneSource(val);+ },+ []+ );++ const isActiveRef = useRef<boolean>(false);+ const sessionRef = useRef<RetouchStrokeSession | null>(null);+ const alignedOffsetRef = useRef<Point2D | null>(null);+ const cloneAnchorRef = useRef<Point2D | null>(null);+ cloneAnchorRef.current = cloneAnchor;+ const isPickingRef = useRef<boolean>(false);+ isPickingRef.current = isPickingCloneSource;++ useEffect(() => {+ let prevTool = useToolStore.getState().tool;+ return useToolStore.subscribe(() => {+ const curTool = useToolStore.getState().tool;+ if (prevTool === 'retouch' && curTool !== 'retouch') {+ setIsPickingCloneSource(false);+ setLiveSamplePos(null);+ }+ prevTool = curTool;+ });+ }, []);++ const handleRetouchPointerDown = useCallback(+ (e: React.PointerEvent<HTMLElement>, pt: Point2D): boolean => {+ const { tool, retouchSettings, primaryColor } = useToolStore.getState();+ if (tool !== 'retouch') return false;+ e.preventDefault();++ // Alt+Click or armed Pick button sets Clone Stamp source point+ if (retouchSettings.mode === 'clone-stamp' && (e.altKey || isPickingRef.current)) {+ setCloneAnchor({ x: pt.x, y: pt.y });+ setLiveSamplePos(null);+ alignedOffsetRef.current = null;+ setIsPickingCloneSource(false);+ showToast?.(`Clone source set (${Math.round(pt.x)}, ${Math.round(pt.y)})`);+ return true;+ }++ if (+ !activeLayer ||+ activeLayer.type !== 'raster' ||+ activeLayer.locked ||+ !isLayerEffectivelyVisible(activeLayer)+ ) {+ showToast?.('Select an unlocked, visible raster layer to use Retouch tools');+ return true;+ }++ let cloneOffset: Point2D | null = null;+ if (retouchSettings.mode === 'clone-stamp') {+ const anchor = cloneAnchorRef.current;+ if (!anchor) {+ showToast?.('Alt+Click on canvas (or click Pick Source) to set Clone Stamp origin');+ return true;+ }+ if (retouchSettings.cloneAligned && alignedOffsetRef.current) {+ cloneOffset = { ...alignedOffsetRef.current };+ } else {+ cloneOffset = { x: anchor.x - pt.x, y: anchor.y - pt.y };+ if (retouchSettings.cloneAligned) {+ alignedOffsetRef.current = { ...cloneOffset };+ }+ }+ setLiveSamplePos({ x: pt.x + cloneOffset.x, y: pt.y + cloneOffset.y });+ }++ flushPendingHistoryTasks?.();+ const grid = documentStore.getActiveTileGrid();+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');+ const isMono =+ !isBg && (colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome');+ const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';+ const selMask = selection+ ? createSelectionMask(selection, dimensions.width, dimensions.height)+ : null;++ const session = createRetouchStrokeSession({+ mode: retouchSettings.mode,+ layerId: activeLayerId,+ targetFormat,+ alphaLock: Boolean(activeLayer.alphaLocked),+ dimensions,+ selectionMask: selMask,+ cloneOffset,+ visibleLayers: layers,+ isLayerVisible: isLayerEffectivelyVisible,+ getEffectiveOpacity,+ });++ sessionRef.current = session;+ isActiveRef.current = true;++ try {+ (e.target as HTMLElement).setPointerCapture(e.pointerId);+ } catch {+ // Ignore capture errors+ }++ const dirty = applyRetouchStrokeSegment({+ grid,+ session,+ pt,+ pressure: e.pressure || 1.0,+ settings: retouchSettings,+ primaryColor,+ });+ if (dirty) {+ grid.notifyChange(true);+ }+ return true;+ },+ [+ activeLayer,+ activeLayerId,+ colorMode,+ dimensions,+ flushPendingHistoryTasks,+ getEffectiveOpacity,+ isLayerEffectivelyVisible,+ layers,+ selection,+ showToast,+ ]+ );++ const handleRetouchPointerMove = useCallback(+ (e: React.PointerEvent<HTMLElement>): boolean => {+ const { tool, retouchSettings, primaryColor } = useToolStore.getState();+ if (tool !== 'retouch') return false;+ if (!isActiveRef.current || !sessionRef.current) return true;++ const pt = getCanvasCoords(e);+ const session = sessionRef.current;+ const grid = documentStore.getActiveTileGrid();++ if (session.mode === 'clone-stamp' && session.cloneOffset) {+ setLiveSamplePos({+ x: pt.x + session.cloneOffset.x,+ y: pt.y + session.cloneOffset.y,+ });+ }++ const dirty = applyRetouchStrokeSegment({+ grid,+ session,+ pt,+ pressure: e.pressure || 1.0,+ settings: retouchSettings,+ primaryColor,+ });+ if (dirty) {+ grid.notifyChange(true);+ }+ return true;+ },+ [getCanvasCoords]+ );++ const handleRetouchPointerUp = useCallback(+ (e: React.PointerEvent<HTMLElement>): boolean => {+ const { tool } = useToolStore.getState();+ if (tool !== 'retouch' && !isActiveRef.current) return false;+ if (!isActiveRef.current || !sessionRef.current) return tool === 'retouch';++ try {+ if ((e.target as HTMLElement).hasPointerCapture?.(e.pointerId)) {+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);+ }+ } catch {+ // Ignore capture release errors+ }++ isActiveRef.current = false;+ const session = sessionRef.current;+ sessionRef.current = null;+ setLiveSamplePos(null);++ if (session.dirtyRect && session.beforeSnapshot.size > 0) {+ const grid = documentStore.getActiveTileGrid();+ const tileDeltas = grid.computeDeltasFromSnapshot(+ session.beforeSnapshot,+ session.layerId,+ session.dirtyRect+ );+ if (tileDeltas.length > 0) {+ pushHistoryStep(+ 'retouch',+ MODE_LABELS[session.mode] || 'Retouch',+ null,+ null,+ session.layerId,+ session.dirtyRect,+ tileDeltas+ );+ if (multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(tileDeltas, grid);+ }+ updateLayerThumbnail(session.layerId, true);+ }+ }++ session.cloneSourceTileCache.clear();+ return true;+ },+ [pushHistoryStep, updateLayerThumbnail]+ );++ const cloneSourceIndicator: CloneSourceIndicator | null = cloneAnchor+ ? {+ anchor: cloneAnchor,+ liveSamplePos,+ isPicking: isPickingCloneSource,+ }+ : isPickingCloneSource+ ? {+ anchor: { x: -9999, y: -9999 },+ liveSamplePos: null,+ isPicking: true,+ }+ : null;++ return {+ cloneSourceIndicator,+ isPickingCloneSource,+ setIsPickingCloneSource,+ handleRetouchPointerDown,+ handleRetouchPointerMove,+ handleRetouchPointerUp,+ };+}diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.tsindex 35705dc..e262242 100644--- a/src/hooks/drawing/useSelectionTools.ts+++ b/src/hooks/drawing/useSelectionTools.ts@@ -1,10 +1,12 @@import React, { useState, useRef, useCallback } from 'react';import {+ BlendMode,CanvasColorMode,CanvasDimensions,CanvasSelection,DirtyRect,LayerItem,+ TileDelta,TransformSession,} from '../../types/editor';import { documentStore } from '../../utils/documentStore';@@ -19,6 +21,8 @@ import {computePolygonBounds,floodSelectWandOnTileGrid,clearSelectionInTileGrid,+ clearOutsideSelectionInTileGrid,+ extractSelectionTileSnapshot,fillSelectionInTileGrid,liftSelectionFromTileGrid,commitFloatingSelectionToTileGrid,@@ -29,12 +33,15 @@ import {selectionToMask,maskToBounds,maskToSvgPath,+ SelectionTileSnapshot,} from '../../utils/selectionUtils';import {renderPerspectiveQuad,renderMeshWarp,createDefaultPerspectiveQuad,createDefaultMeshPoints,+ computeMeshSubdivisions,+ getMeshSurfaceBounds,} from '../../utils/transformEngine';import { get2DContext } from '../../utils/canvasUtils';import { useToolStore, toolStoreActions } from '../../stores';@@ -60,9 +67,9 @@ function computeTransformDestRect(if (session.mode === 'perspective' && session.perspectiveQuad) {for (const p of session.perspectiveQuad) includePt(p.x, p.y);} else if (session.mode === 'mesh' && session.meshPoints) {- for (const row of session.meshPoints) {- for (const p of row) includePt(p.x, p.y);- }+ const sb = getMeshSurfaceBounds(session.meshPoints, 6);+ includePt(sb.minX, sb.minY);+ includePt(sb.maxX, sb.maxY);} else {const cx = session.x + session.width / 2;const cy = session.y + session.height / 2;@@ -126,12 +133,22 @@ function compositeTransformedIntoTileGrid(cCtx.setTransform(1, 0, 0, 1, 0, 0);cCtx.clearRect(0, 0, cw, ch);cCtx.save();+ cCtx.imageSmoothingEnabled = true;+ if ('imageSmoothingQuality' in cCtx) {+ cCtx.imageSmoothingQuality = 'high';+ }cCtx.translate(-cx, -cy);if (session.mode === 'perspective' && session.perspectiveQuad) {- renderPerspectiveQuad(cCtx, sourceCanvas, session.perspectiveQuad, 24);+ renderPerspectiveQuad(cCtx, sourceCanvas, session.perspectiveQuad, 32);} else if (session.mode === 'mesh' && session.meshPoints) {- renderMeshWarp(cCtx, sourceCanvas, session.meshPoints, 6);+ const subPerCell = computeMeshSubdivisions(+ sourceCanvas.width,+ sourceCanvas.height,+ session.meshPoints,+ true+ );+ renderMeshWarp(cCtx, sourceCanvas, session.meshPoints, subPerCell);} else {const midX = session.x + session.width / 2;const midY = session.y + session.height / 2;@@ -181,6 +198,20 @@ export interface UseSelectionToolsParams {updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;pushHistoryStep: PushHistoryStepFn;showToast: (msg: string) => void;+ copySelectionToClipboard?: (+ selection: CanvasSelection,+ targetId?: string+ ) => { copied: boolean; empty?: boolean; layerName?: string; snapshot?: SelectionTileSnapshot };+ createLayerFromTileSnapshot?: (+ tileSnapshot: {+ format: TileFormat;+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;+ },+ layerName: string,+ blendMode?: BlendMode,+ opacity?: number,+ layerOverrides?: Partial<LayerItem>+ ) => { id: string; name: string; tileDeltas: TileDelta[] };}export interface UseSelectionToolsResult {@@ -192,6 +223,11 @@ export interface UseSelectionToolsResult {handleCommitFloatingSelection: () => void;handleDeselect: () => void;handleClearSelection: () => void;+ handleDeleteOutsideSelection: () => void;+ handleCopySelection: () => void;+ handleCutSelection: () => void;+ handleMoveSelectionToNewLayer: () => void;+ handleCopySelectionToNewLayer: () => void;handleFillSelectionColor: () => void;handleExpandSelection: (pixels?: number) => void;handleContractSelection: (pixels?: number) => void;@@ -221,6 +257,8 @@ export function useSelectionTools({updateLayerThumbnail,pushHistoryStep,showToast,+ copySelectionToClipboard,+ createLayerFromTileSnapshot,}: UseSelectionToolsParams): UseSelectionToolsResult {const [selection, setSelection] = useState<CanvasSelection | null>(null);const [transformSession, setTransformSession] = useState<TransformSession | null>(null);@@ -314,6 +352,10 @@ export function useSelectionTools({const handleClearSelection = useCallback(() => {if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {+ showToast('Select an unlocked raster layer');+ return;+ }flushPendingHistoryTasks?.();const grid = getGrid();@@ -327,7 +369,7 @@ export function useSelectionTools({if (tileDeltas.length > 0) {pushHistoryStep('clear',- 'Clear Selection',+ 'Delete Selection',null,null,targetLayerId,@@ -357,7 +399,7 @@ export function useSelectionTools({if (tileDeltas.length > 0) {pushHistoryStep('clear',- 'Clear Selection',+ 'Delete Selection',null,null,activeLayerId,@@ -368,13 +410,325 @@ export function useSelectionTools({updateLayerThumbnail(activeLayerId, true);}, [selection,+ activeLayer,+ showToast,+ flushPendingHistoryTasks,+ getGrid,+ activeLayerId,+ dimensions,+ resolveLayerFormat,+ updateLayerThumbnail,+ pushHistoryStep,+ ]);++ const handleDeleteOutsideSelection = useCallback(() => {+ if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {+ showToast('Select an unlocked raster layer');+ return;+ }+ flushPendingHistoryTasks?.();+ const grid = getGrid();+ const targetLayerId = selection.floating?.layerId || activeLayerId;+ const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');+ const targetFormat = resolveLayerFormat(targetLayerId);++ const { dirtyRect, tileDeltas } = clearOutsideSelectionInTileGrid({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ isBackground: isBg,+ targetFormat,+ });++ if (selection.floating) {+ releaseTemporaryCanvas(selection.floating.canvas);+ setSelection((prev) => (prev ? { ...prev, floating: null } : null));+ }++ if (tileDeltas.length > 0) {+ pushHistoryStep(+ 'clear',+ 'Delete Outside Selection',+ null,+ null,+ targetLayerId,+ dirtyRect ?? undefined,+ tileDeltas+ );+ showToast('Deleted outside selection');+ } else {+ showToast('Nothing outside selection to delete');+ }+ updateLayerThumbnail(targetLayerId, true);+ }, [+ selection,+ activeLayer,+ showToast,flushPendingHistoryTasks,getGrid,activeLayerId,+ resolveLayerFormat,+ dimensions,+ pushHistoryStep,+ updateLayerThumbnail,+ ]);++ const handleCopySelection = useCallback(() => {+ if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster') {+ showToast('Select a raster layer to copy selection');+ return;+ }+ if (!copySelectionToClipboard) return;+ const targetLayerId = selection.floating?.layerId || activeLayerId;+ const res = copySelectionToClipboard(selection, targetLayerId);+ if (res.copied) {+ showToast(`Copied selection from "${res.layerName || activeLayer.name}"`);+ } else if (res.empty) {+ showToast('Selected area is empty');+ }+ }, [selection, activeLayer, activeLayerId, copySelectionToClipboard, showToast]);++ const handleCutSelection = useCallback(() => {+ if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {+ showToast('Select an unlocked raster layer to cut');+ return;+ }+ if (!copySelectionToClipboard) return;++ flushPendingHistoryTasks?.();+ const targetLayerId = selection.floating?.layerId || activeLayerId;+ const copyRes = copySelectionToClipboard(selection, targetLayerId);+ if (!copyRes.copied) {+ showToast(copyRes.empty ? 'Selected area is empty' : 'Failed to cut selection');+ return;+ }++ const grid = getGrid();+ if (selection.floating) {+ if (selection.floating.beforeTileSnapshot) {+ const tileDeltas = grid.computeDeltasFromSnapshot(+ selection.floating.beforeTileSnapshot,+ targetLayerId+ );+ if (tileDeltas.length > 0) {+ pushHistoryStep(+ 'clear',+ 'Cut Selection',+ null,+ null,+ targetLayerId,+ selection.bounds,+ tileDeltas+ );+ }+ }+ releaseTemporaryCanvas(selection.floating.canvas);+ grid.notifyChange(true);+ updateLayerThumbnail(targetLayerId, true);+ setSelection(null);+ showToast(`Cut selection from "${activeLayer.name}"`);+ return;+ }++ const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');+ const targetFormat = resolveLayerFormat(targetLayerId);+ const { dirtyRect, tileDeltas } = clearSelectionInTileGrid({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ isBackground: isBg,+ targetFormat,+ });++ if (tileDeltas.length > 0) {+ pushHistoryStep(+ 'clear',+ 'Cut Selection',+ null,+ null,+ targetLayerId,+ dirtyRect ?? undefined,+ tileDeltas+ );+ }+ updateLayerThumbnail(targetLayerId, true);+ setSelection(null);+ showToast(`Cut selection from "${activeLayer.name}"`);+ }, [+ selection,+ activeLayer,+ activeLayerId,+ copySelectionToClipboard,+ flushPendingHistoryTasks,+ getGrid,+ resolveLayerFormat,dimensions,+ pushHistoryStep,+ updateLayerThumbnail,+ showToast,+ ]);++ const handleMoveSelectionToNewLayer = useCallback(() => {+ if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {+ showToast('Select an unlocked raster layer');+ return;+ }+ if (!createLayerFromTileSnapshot) return;++ flushPendingHistoryTasks?.();+ const grid = getGrid();+ const targetLayerId = selection.floating?.layerId || activeLayerId;+ const targetFormat = resolveLayerFormat(targetLayerId);+ const snapshot = extractSelectionTileSnapshot({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ targetFormat,+ });++ if (!snapshot || snapshot.tiles.length === 0) {+ showToast('Selected area is empty');+ return;+ }++ let srcDeltas: TileDelta[] = [];+ let dirtyRect: DirtyRect | undefined = snapshot.bounds;++ if (selection.floating) {+ if (selection.floating.beforeTileSnapshot) {+ srcDeltas = grid.computeDeltasFromSnapshot(+ selection.floating.beforeTileSnapshot,+ targetLayerId+ );+ }+ releaseTemporaryCanvas(selection.floating.canvas);+ } else {+ const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');+ const cleared = clearSelectionInTileGrid({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ isBackground: isBg,+ targetFormat,+ });+ srcDeltas = cleared.tileDeltas;+ if (cleared.dirtyRect) dirtyRect = cleared.dirtyRect;+ }++ const overrides = activeLayer.expressionColor+ ? { expressionColor: activeLayer.expressionColor }+ : undefined;+ const created = createLayerFromTileSnapshot(+ snapshot,+ `${activeLayer.name} (Cut)`,+ activeLayer.blendMode,+ activeLayer.opacity,+ overrides+ );++ const combinedDeltas = [...srcDeltas, ...created.tileDeltas];+ if (combinedDeltas.length > 0) {+ pushHistoryStep(+ 'selection-move',+ 'Move Selection to New Layer',+ null,+ null,+ created.id,+ dirtyRect,+ combinedDeltas+ );+ }++ updateLayerThumbnail(targetLayerId, true);+ setSelection(null);+ showToast(`Moved selection to "${created.name}"`);+ }, [+ selection,+ activeLayer,+ activeLayerId,+ createLayerFromTileSnapshot,+ flushPendingHistoryTasks,+ getGrid,resolveLayerFormat,+ dimensions,+ pushHistoryStep,updateLayerThumbnail,+ showToast,+ ]);++ const handleCopySelectionToNewLayer = useCallback(() => {+ if (!selection) return;+ if (!activeLayer || activeLayer.type !== 'raster') {+ showToast('Select a raster layer');+ return;+ }+ if (!createLayerFromTileSnapshot) return;++ flushPendingHistoryTasks?.();+ const grid = getGrid();+ const targetLayerId = selection.floating?.layerId || activeLayerId;+ const targetFormat = resolveLayerFormat(targetLayerId);+ const snapshot = extractSelectionTileSnapshot({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ targetFormat,+ });++ if (!snapshot || snapshot.tiles.length === 0) {+ showToast('Selected area is empty');+ return;+ }++ const overrides = activeLayer.expressionColor+ ? { expressionColor: activeLayer.expressionColor }+ : undefined;+ const created = createLayerFromTileSnapshot(+ snapshot,+ `${activeLayer.name} (Copy)`,+ activeLayer.blendMode,+ activeLayer.opacity,+ overrides+ );++ if (created.tileDeltas.length > 0) {+ pushHistoryStep(+ 'selection-move',+ 'Copy Selection to New Layer',+ null,+ null,+ created.id,+ snapshot.bounds,+ created.tileDeltas+ );+ }++ if (selection.floating) {+ handleCommitFloatingSelection();+ }+ setSelection(null);+ showToast(`Copied selection to "${created.name}"`);+ }, [+ selection,+ activeLayer,+ activeLayerId,+ createLayerFromTileSnapshot,+ flushPendingHistoryTasks,+ getGrid,+ resolveLayerFormat,+ dimensions,pushHistoryStep,+ handleCommitFloatingSelection,+ showToast,]);const handleFillSelectionColor = useCallback(() => {@@ -1272,6 +1626,11 @@ export function useSelectionTools({handleCommitFloatingSelection,handleDeselect,handleClearSelection,+ handleDeleteOutsideSelection,+ handleCopySelection,+ handleCutSelection,+ handleMoveSelectionToNewLayer,+ handleCopySelectionToNewLayer,handleFillSelectionColor,handleExpandSelection,handleContractSelection,diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.tsindex c351e37..0b67256 100644--- a/src/hooks/drawing/useShapeAndFillTools.ts+++ b/src/hooks/drawing/useShapeAndFillTools.ts@@ -6,6 +6,7 @@ import {ComicFrame,FrameDivideMode,LayerItem,+ LayerTreeDelta,ShapeDragPreview,SpeechBalloon,TextLayerData,@@ -13,19 +14,19 @@ import {TileDelta,} from '../../types/editor';import { documentStore } from '../../utils/documentStore';-import { TileFormat, TileSnapshotEntry } from '../../utils/tileEngine';+import { SparseTileGrid, TileFormat, TileSnapshotEntry } from '../../utils/tileEngine';import {executeFloodFillOnTileGridAsync,executeLassoFillOnTileGrid,} from '../../utils/floodFill';import {- applyLiquifyStepOnTileGrid,- applyLiquifyStepOnTileGridAsync,+ LiquifySubStep,+ LiquifyWarpField,createLiquifySelectionMask,+ resampleLayerFromWarpField,resolveLiquifyTargetLayers,DirtyRect,} from '../../utils/liquifyEngine';-import { isNativeRustAvailable } from '../../utils/nativeBackend';import { rasterizeShapeToTileGrid, resolveShapeFillColor } from '../../utils/shapeEngine';import { createSelectionMask } from '../../utils/tonalEngine';import { sampleCompositedColor } from '../../utils/canvasUtils';@@ -74,14 +75,14 @@ export interface UseShapeAndFillToolsParams {frames: ComicFrame[],customName?: string,addInitialChildLayer?: boolean- ) => { folder: LayerItem; childLayer: LayerItem | null };+ ) => { folder: LayerItem; childLayer: LayerItem | null; layerTreeDelta: LayerTreeDelta };divideFrameFolder: (folderId: string,cutStart: Point2D,cutEnd: Point2D,dpi?: number,mode?: FrameDivideMode- ) => boolean;+ ) => { divided: boolean; layerTreeDelta?: LayerTreeDelta; tileDeltas?: TileDelta[] };deleteLayer?: (id: string) => void;updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;pushHistoryStep: PushHistoryStepFn;@@ -118,9 +119,18 @@ interface LiquifyLayerSession {layerId: string;targetFormat: TileFormat;beforeTileSnapshot: Map<string, TileSnapshotEntry>;+ origRgbaCache: Map<number, Uint8ClampedArray | null>;dirtyRect: DirtyRect | null;}+interface PersistentLiquifyWarpSession {+ grid: SparseTileGrid;+ width: number;+ height: number;+ warpField: LiquifyWarpField;+ layers: Map<string, { origRgbaCache: Map<number, Uint8ClampedArray | null>; lastVersion: number }>;+}+function mergeDirtyRects(a: DirtyRect | null, b: DirtyRect | null): DirtyRect | null {if (!a) return b ? { ...b } : null;if (!b) return a;@@ -160,7 +170,7 @@ export function useShapeAndFillTools({const [shapeDragPreview, setShapeDragPreview] = useState<ShapeDragPreview | null>(null);const isPipetteSamplingRef = useRef<boolean>(false);- const liquifyInFlightRef = useRef<boolean>(false);+ const liquifyPersistentRef = useRef<PersistentLiquifyWarpSession | null>(null);const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);const frameStartRef = useRef<{ x: number; y: number } | null>(null);const shapeDragRef = useRef<{@@ -275,6 +285,28 @@ export function useShapeAndFillTools({} | null>(null);const liquifySelectionMaskRef = useRef<Uint8Array | null>(null);+ useEffect(() => {+ const clearPersistent = () => {+ if (liquifyPersistentRef.current) {+ liquifyPersistentRef.current.warpField.clear();+ liquifyPersistentRef.current.layers.clear();+ liquifyPersistentRef.current = null;+ }+ };+ let prevTool = useToolStore.getState().tool;+ const unsub = useToolStore.subscribe(() => {+ const curTool = useToolStore.getState().tool;+ if (prevTool === 'liquify' && curTool !== 'liquify') {+ clearPersistent();+ }+ prevTool = curTool;+ });+ return () => {+ unsub();+ clearPersistent();+ };+ }, []);+const handleSampleColor = useCallback((pt: { x: number; y: number }) => {const sampled = sampleCompositedColor(@@ -355,9 +387,11 @@ export function useShapeAndFillTools({if (liquifyRafIdRef.current) cancelAnimationFrame(liquifyRafIdRef.current);const tick = () => {+ const persistent = liquifyPersistentRef.current;if (!isLiquifyingRef.current ||!liquifyLastPointerPosRef.current ||+ !persistent ||liquifySessionsRef.current.length === 0) {liquifyRafIdRef.current = null;@@ -367,68 +401,34 @@ export function useShapeAndFillTools({const liquifySettings = useToolStore.getState().liquifySettings;const grid = documentStore.getActiveTileGrid();- if (isNativeRustAvailable()) {- if (!liquifyInFlightRef.current) {- liquifyInFlightRef.current = true;- const sessions = liquifySessionsRef.current.slice();- void (async () => {- try {- let anyDirty = false;- for (const session of sessions) {- const dirty = await applyLiquifyStepOnTileGridAsync({- grid,- layerId: session.layerId,- dimensions,- targetFormat: session.targetFormat,- cx: pt.x,- cy: pt.y,- prevX: pt.x,- prevY: pt.y,- settings: liquifySettings,- pressure,- beforeTileSnapshot: session.beforeTileSnapshot,- selectionMask: liquifySelectionMaskRef.current,- });- if (dirty) {- session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);- anyDirty = true;- }- }- if (anyDirty) grid.notifyChange(true);- } finally {- liquifyInFlightRef.current = false;- }- })();- }- liquifyRafIdRef.current = requestAnimationFrame(tick);- return;- }-- let anyDirty = false;+ const stepDirty = persistent.warpField.applySubSteps(+ [{ cx: pt.x, cy: pt.y, prevX: pt.x, prevY: pt.y, pressure }],+ dimensions,+ liquifySettings,+ liquifySelectionMaskRef.current+ );- for (const session of liquifySessionsRef.current) {- const dirty = applyLiquifyStepOnTileGrid({- grid,- layerId: session.layerId,- dimensions,- targetFormat: session.targetFormat,- cx: pt.x,- cy: pt.y,- prevX: pt.x,- prevY: pt.y,- settings: liquifySettings,- pressure,- beforeTileSnapshot: session.beforeTileSnapshot,- selectionMask: liquifySelectionMaskRef.current,- });- if (dirty) {- session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);- anyDirty = true;+ if (stepDirty) {+ let anyDirty = false;+ for (const session of liquifySessionsRef.current) {+ const dirty = resampleLayerFromWarpField({+ grid,+ layerId: session.layerId,+ dimensions,+ targetFormat: session.targetFormat,+ warpField: persistent.warpField,+ dirtyRect: stepDirty,+ beforeTileSnapshot: session.beforeTileSnapshot,+ origRgbaCache: session.origRgbaCache,+ });+ if (dirty) {+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);+ anyDirty = true;+ }+ }+ if (anyDirty) {+ grid.notifyChange(true);}- }-- if (anyDirty) {- grid.notifyChange(true);}liquifyRafIdRef.current = requestAnimationFrame(tick);@@ -510,20 +510,63 @@ export function useShapeAndFillTools({}const grid = documentStore.getActiveTileGrid();- const sessions: LiquifyLayerSession[] = [];+ const eligibleLayers = targetLayers.filter((l) => grid.hasLayerTiles(l.id));+ if (eligibleLayers.length === 0) return true;++ // Reuse persistent warp field across consecutive Liquify strokes while layers remain+ // untouched by external edits/undo/redo, guaranteeing single-pass bicubic quality+ // and ghost-free cross-stroke Reconstruct.+ let persistent = liquifyPersistentRef.current;+ const canReuse =+ persistent !== null &&+ persistent.grid === grid &&+ persistent.width === dimensions.width &&+ persistent.height === dimensions.height &&+ persistent.layers.size === eligibleLayers.length &&+ eligibleLayers.every((l) => {+ const entry = persistent!.layers.get(l.id);+ return entry !== undefined && grid.getLayerVersion(l.id) === entry.lastVersion;+ });- for (const layer of targetLayers) {+ if (!canReuse) {+ if (persistent) {+ persistent.warpField.clear();+ persistent.layers.clear();+ }+ const layerEntries = new Map<+ string,+ { origRgbaCache: Map<number, Uint8ClampedArray | null>; lastVersion: number }+ >();+ for (const layer of eligibleLayers) {+ layerEntries.set(layer.id, {+ origRgbaCache: new Map<number, Uint8ClampedArray | null>(),+ lastVersion: grid.getLayerVersion(layer.id),+ });+ }+ persistent = {+ grid,+ width: dimensions.width,+ height: dimensions.height,+ warpField: new LiquifyWarpField(),+ layers: layerEntries,+ };+ liquifyPersistentRef.current = persistent;+ }++ const sessions: LiquifyLayerSession[] = [];+ for (const layer of eligibleLayers) {const targetId = layer.id;- if (!grid.hasLayerTiles(targetId)) continue;const isBg = targetId === 'layer-bg' || targetId.startsWith('layer-bg');const isMono = !isBg && (colorMode === 'monochrome' || layer.expressionColor === 'monochrome');const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';+ const persistentEntry = persistent!.layers.get(targetId)!;sessions.push({layer,layerId: targetId,targetFormat,beforeTileSnapshot: new Map<string, TileSnapshotEntry>(),+ origRgbaCache: persistentEntry.origRgbaCache,dirtyRect: null,});}@@ -554,29 +597,33 @@ export function useShapeAndFillTools({mode === 'twirl-ccw' ||mode === 'reconstruct') {- let anyDirty = false;- for (const session of sessions) {- const dirty = applyLiquifyStepOnTileGrid({- grid,- layerId: session.layerId,- dimensions,- targetFormat: session.targetFormat,- cx: pt.x,- cy: pt.y,- prevX: pt.x,- prevY: pt.y,- settings: liquifySettings,- pressure: e.pressure || 1.0,- beforeTileSnapshot: session.beforeTileSnapshot,- selectionMask: liquifySelectionMaskRef.current,- });- if (dirty) {- session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);- anyDirty = true;+ const stepDirty = persistent!.warpField.applySubSteps(+ [{ cx: pt.x, cy: pt.y, prevX: pt.x, prevY: pt.y, pressure: e.pressure || 1.0 }],+ dimensions,+ liquifySettings,+ liquifySelectionMaskRef.current+ );+ if (stepDirty) {+ let anyDirty = false;+ for (const session of sessions) {+ const dirty = resampleLayerFromWarpField({+ grid,+ layerId: session.layerId,+ dimensions,+ targetFormat: session.targetFormat,+ warpField: persistent!.warpField,+ dirtyRect: stepDirty,+ beforeTileSnapshot: session.beforeTileSnapshot,+ origRgbaCache: session.origRgbaCache,+ });+ if (dirty) {+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);+ anyDirty = true;+ }+ }+ if (anyDirty) {+ grid.notifyChange(true);}- }- if (anyDirty) {- grid.notifyChange(true);}startLiquifyLoop();}@@ -776,7 +823,10 @@ export function useShapeAndFillTools({}if (tool === 'liquify') {- if (!isLiquifyingRef.current || liquifySessionsRef.current.length === 0) return true;+ const persistent = liquifyPersistentRef.current;+ if (!isLiquifyingRef.current || !persistent || liquifySessionsRef.current.length === 0) {+ return true;+ }const pt = getCanvasCoords(e);const pressure = e.pressure || 1.0;liquifyLastPointerPosRef.current = { pt, pressure };@@ -787,94 +837,51 @@ export function useShapeAndFillTools({const numSteps = Math.max(1, Math.ceil(dist / stepDist));const grid = documentStore.getActiveTileGrid();- if (isNativeRustAvailable()) {- if (!liquifyInFlightRef.current) {- liquifyInFlightRef.current = true;- const sessions = liquifySessionsRef.current.slice();- prevLiquifyPointRef.current = pt;- void (async () => {- try {- let anyDirty = false;- for (const session of sessions) {- let layerDirty: DirtyRect | null = null;- for (let i = 1; i <= numSteps; i++) {- const t = i / numSteps;- const cx = prev.x + (pt.x - prev.x) * t;- const cy = prev.y + (pt.y - prev.y) * t;- const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);- const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);- const dirty = await applyLiquifyStepOnTileGridAsync({- grid,- layerId: session.layerId,- dimensions,- targetFormat: session.targetFormat,- cx,- cy,- prevX: px,- prevY: py,- settings: liquifySettings,- pressure,- beforeTileSnapshot: session.beforeTileSnapshot,- selectionMask: liquifySelectionMaskRef.current,- });- if (dirty) layerDirty = mergeDirtyRects(layerDirty, dirty);- }- if (layerDirty) {- session.dirtyRect = mergeDirtyRects(session.dirtyRect, layerDirty);- anyDirty = true;- }- }- if (anyDirty) grid.notifyChange(true);- } finally {- liquifyInFlightRef.current = false;- }- })();- }- return true;+ // Accumulate all sub-steps in float32 warp space, then resample pixels ONCE+ const subSteps: LiquifySubStep[] = new Array(numSteps);+ for (let i = 1; i <= numSteps; i++) {+ const t = i / numSteps;+ const tPrev = (i - 1) / numSteps;+ subSteps[i - 1] = {+ cx: prev.x + (pt.x - prev.x) * t,+ cy: prev.y + (pt.y - prev.y) * t,+ prevX: prev.x + (pt.x - prev.x) * tPrev,+ prevY: prev.y + (pt.y - prev.y) * tPrev,+ pressure,+ };}- let anyDirty = false;+ const batchDirty = persistent.warpField.applySubSteps(+ subSteps,+ dimensions,+ liquifySettings,+ liquifySelectionMaskRef.current+ );- for (const session of liquifySessionsRef.current) {- let layerDirty: DirtyRect | null = null;- for (let i = 1; i <= numSteps; i++) {- const t = i / numSteps;- const cx = prev.x + (pt.x - prev.x) * t;- const cy = prev.y + (pt.y - prev.y) * t;- const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);- const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);-- const dirty = applyLiquifyStepOnTileGrid({+ prevLiquifyPointRef.current = pt;++ if (batchDirty) {+ let anyDirty = false;+ for (const session of liquifySessionsRef.current) {+ const dirty = resampleLayerFromWarpField({grid,layerId: session.layerId,dimensions,targetFormat: session.targetFormat,- cx,- cy,- prevX: px,- prevY: py,- settings: liquifySettings,- pressure,+ warpField: persistent.warpField,+ dirtyRect: batchDirty,beforeTileSnapshot: session.beforeTileSnapshot,- selectionMask: liquifySelectionMaskRef.current,+ origRgbaCache: session.origRgbaCache,});-if (dirty) {- layerDirty = mergeDirtyRects(layerDirty, dirty);+ session.dirtyRect = mergeDirtyRects(session.dirtyRect, dirty);+ anyDirty = true;}}-- if (layerDirty) {- session.dirtyRect = mergeDirtyRects(session.dirtyRect, layerDirty);- anyDirty = true;+ if (anyDirty) {+ grid.notifyChange(true);}}-- prevLiquifyPointRef.current = pt;-- if (anyDirty) {- grid.notifyChange(true);- }return true;}@@ -1008,7 +1015,12 @@ export function useShapeAndFillTools({let modifiedCount = 0;let primaryTargetId = activeLayerId;+ const persistent = liquifyPersistentRef.current;for (const session of sessions) {+ if (persistent) {+ const entry = persistent.layers.get(session.layerId);+ if (entry) entry.lastVersion = grid.getLayerVersion(session.layerId);+ }if (!session.dirtyRect) continue;modifiedCount++;primaryTargetId = session.layerId;@@ -1126,14 +1138,22 @@ export function useShapeAndFillTools({}const divideMode = frameSettings.divideMode ?? 'same-folder';- const ok = divideFrameFolder(targetFolder.id, s, pt, dpi, divideMode);- if (ok) {+ flushPendingHistoryTasks?.();+ const res = divideFrameFolder(targetFolder.id, s, pt, dpi, divideMode);+ if (res.divided) {pushHistoryStep('frame',divideMode === 'split-folders' ? 'Divide Frame Folder' : 'Divide Frame Border',null,null,- targetFolder.id+ targetFolder.id,+ undefined,+ res.tileDeltas,+ undefined,+ undefined,+ undefined,+ undefined,+ res.layerTreeDelta);showToast?.(divideMode === 'split-folders'@@ -1153,6 +1173,7 @@ export function useShapeAndFillTools({const h = Math.ceil(Math.abs(pt.y - s.y));if (w >= 8 && h >= 8) {+ flushPendingHistoryTasks?.();const rectFrame = createRectFrame('', minX, minY, w, h, {dpi,borderWidth: frameSettings.thickness || 4,@@ -1168,8 +1189,21 @@ export function useShapeAndFillTools({fillColor: frameSettings.fillColor || '#ffffff',strokeColor: frameSettings.strokeColor || primaryColor || '#000000',});- const { folder } = createFrameFolder([rectFrame], undefined, true);- pushHistoryStep('frame', 'Create Frame Folder', null, null, folder.id);+ const { folder, layerTreeDelta } = createFrameFolder([rectFrame], undefined, true);+ pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );showToast?.('Created Frame Border Folder (child layers auto-clip)');}return true;diff --git a/src/hooks/layerManager/layerTreeOps.ts b/src/hooks/layerManager/layerTreeOps.tsindex 2f797d1..b34d740 100644--- a/src/hooks/layerManager/layerTreeOps.ts+++ b/src/hooks/layerManager/layerTreeOps.ts@@ -1,4 +1,4 @@-import { LayerItem, isFolderLikeLayer } from '../../types/editor';+import { ComicFrame, LayerItem, LayerTreeDelta, isFolderLikeLayer } from '../../types/editor';export function isBackgroundLayerId(id: string): boolean {return id === 'layer-bg' || id.startsWith('layer-bg');@@ -330,3 +330,126 @@ export function computeBatchLock(const selectedSet = new Set(selectedIds);return layers.map((l) => (selectedSet.has(l.id) ? { ...l, locked: newLocked } : l));}++export function cloneComicFrames(frames: ComicFrame[]): ComicFrame[] {+ return frames.map((f) => ({+ ...f,+ polygon: f.polygon.map((p) => ({ x: p.x, y: p.y })),+ }));+}++export function cloneLayerItemForHistory(layer: LayerItem): LayerItem {+ return {+ ...layer,+ comicFrames: layer.comicFrames ? cloneComicFrames(layer.comicFrames) : undefined,+ vectorStrokes: layer.vectorStrokes ? JSON.parse(JSON.stringify(layer.vectorStrokes)) : undefined,+ textData: layer.textData ? JSON.parse(JSON.stringify(layer.textData)) : undefined,+ balloonData: layer.balloonData ? JSON.parse(JSON.stringify(layer.balloonData)) : undefined,+ balloons: layer.balloons ? JSON.parse(JSON.stringify(layer.balloons)) : undefined,+ adjustmentData: layer.adjustmentData ? JSON.parse(JSON.stringify(layer.adjustmentData)) : undefined,+ styles: layer.styles ? JSON.parse(JSON.stringify(layer.styles)) : undefined,+ };+}++export interface ApplyLayerTreeDeltaResult {+ nextLayers: LayerItem[];+ nextActiveLayerId: string | null;+ removedLayerIds: string[];+ addedLayers: LayerItem[];+}++// Pure undo/redo application of a targeted LayerTreeDelta (e.g. create/divide frame border folder)+export function applyLayerTreeDelta(+ layers: LayerItem[],+ currentActiveLayerId: string,+ delta: LayerTreeDelta,+ direction: 'undo' | 'redo'+): ApplyLayerTreeDeltaResult {+ let nextLayers = [...layers];+ const removedLayerIds: string[] = [];+ const addedLayers: LayerItem[] = [];++ if (direction === 'undo') {+ if (delta.updatedLayers && delta.updatedLayers.length > 0) {+ const updateMap = new Map(delta.updatedLayers.map((u) => [u.layerId, u]));+ nextLayers = nextLayers.map((l) => {+ const upd = updateMap.get(l.id);+ if (!upd) return l;+ return {+ ...l,+ comicFrames: upd.beforeComicFrames ? cloneComicFrames(upd.beforeComicFrames) : undefined,+ };+ });+ }++ if (delta.addedLayers && delta.addedLayers.length > 0) {+ const addedIdSet = new Set(delta.addedLayers.map((l) => l.id));+ for (const l of nextLayers) {+ if (addedIdSet.has(l.id)) {+ removedLayerIds.push(l.id);+ }+ }+ if (removedLayerIds.length > 0) {+ const removedSet = new Set(removedLayerIds);+ nextLayers = nextLayers+ .filter((l) => !removedSet.has(l.id))+ .map((l) => (l.parentId && removedSet.has(l.parentId) ? { ...l, parentId: null } : l));+ }+ }++ let nextActiveLayerId: string | null = null;+ if (delta.beforeActiveLayerId && nextLayers.some((l) => l.id === delta.beforeActiveLayerId)) {+ nextActiveLayerId = delta.beforeActiveLayerId;+ } else if (+ removedLayerIds.includes(currentActiveLayerId) ||+ (currentActiveLayerId && !nextLayers.some((l) => l.id === currentActiveLayerId))+ ) {+ const fallback = nextLayers.find((l) => l.type === 'raster') || nextLayers[0];+ nextActiveLayerId = fallback ? fallback.id : '';+ }++ return { nextLayers, nextActiveLayerId, removedLayerIds, addedLayers };+ }++ // direction === 'redo'+ if (delta.updatedLayers && delta.updatedLayers.length > 0) {+ const updateMap = new Map(delta.updatedLayers.map((u) => [u.layerId, u]));+ nextLayers = nextLayers.map((l) => {+ const upd = updateMap.get(l.id);+ if (!upd) return l;+ return {+ ...l,+ comicFrames: upd.afterComicFrames ? cloneComicFrames(upd.afterComicFrames) : undefined,+ };+ });+ }++ if (delta.addedLayers && delta.addedLayers.length > 0) {+ const existingIds = new Set(nextLayers.map((l) => l.id));+ const toAdd = delta.addedLayers+ .filter((al) => !existingIds.has(al.id))+ .map(cloneLayerItemForHistory);++ if (toAdd.length > 0) {+ let insertIdx: number;+ if (delta.insertBeforeLayerId) {+ const anchorIdx = nextLayers.findIndex((l) => l.id === delta.insertBeforeLayerId);+ insertIdx =+ anchorIdx >= 0+ ? anchorIdx+ : Math.max(0, Math.min(delta.insertIndex ?? 0, nextLayers.length));+ } else {+ insertIdx = Math.max(0, Math.min(delta.insertIndex ?? 0, nextLayers.length));+ }+ nextLayers.splice(insertIdx, 0, ...toAdd);+ addedLayers.push(...toAdd);+ }+ }++ let nextActiveLayerId: string | null = null;+ if (delta.afterActiveLayerId && nextLayers.some((l) => l.id === delta.afterActiveLayerId)) {+ nextActiveLayerId = delta.afterActiveLayerId;+ }++ return { nextLayers, nextActiveLayerId, removedLayerIds, addedLayers };+}diff --git a/src/hooks/layerManager/useLayerClipboard.ts b/src/hooks/layerManager/useLayerClipboard.tsindex 5c08e9f..b8bb9a6 100644--- a/src/hooks/layerManager/useLayerClipboard.ts+++ b/src/hooks/layerManager/useLayerClipboard.ts@@ -8,8 +8,20 @@ import {import { createCanvasThumbnail } from '../../utils/canvasUtils';import { LayerInsertTarget, sanitizeImportedLayerName } from '../../utils/fileDropImport';import { HalftoneDotShape } from '../../utils/screentoneEngine';-import { fillSelectionInTileGrid } from '../../utils/selectionUtils';-import { TileDelta, TileFormat, releaseTemporaryCanvas } from '../../utils/tileEngine';+import {+ SelectionTileSnapshot,+ extractSelectionTileSnapshot,+ fillSelectionInTileGrid,+} from '../../utils/selectionUtils';+import {+ TILE_SIZE,+ TileDelta,+ TileFormat,+ getTileKey,+ releaseTemporaryCanvas,+ unpack1BitToRGBA,+ unpack8BitToRGBA,+} from '../../utils/tileEngine';import { LayerManagerContext } from './types';export function useLayerClipboard(ctx: LayerManagerContext) {@@ -32,6 +44,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {type: LayerItem['type'];blendMode: BlendMode;opacity: number;+ isSelection?: boolean;+ expressionColor?: LayerItem['expressionColor'];tileSnapshot: {format: TileFormat;tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;@@ -265,6 +279,140 @@ export function useLayerClipboard(ctx: LayerManagerContext) {[activeLayerId, activeTileGridRef, defaultToneFrequencyRef, dimensions, setActiveLayerId, setLayers]);+ // Create a new raster layer directly from a sparse tile snapshot (zero full-doc canvas)+ const createLayerFromTileSnapshot = useCallback(+ (+ tileSnapshot: {+ format: TileFormat;+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;+ },+ layerName: string,+ blendMode: BlendMode = 'normal',+ opacity: number = 1,+ layerOverrides?: Partial<LayerItem>,+ insertTarget?: LayerInsertTarget+ ): { id: string; name: string; tileDeltas: TileDelta[] } => {+ const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ const grid = activeTileGridRef.current;+ grid.pasteLayerTilesSnapshot(newId, tileSnapshot);+ const tileDeltas: TileDelta[] = tileSnapshot.tiles.map((entry) => ({+ key: getTileKey(newId, entry.tileX, entry.tileY, 0),+ format: entry.format,+ beforeData: null,+ afterData: new Uint8Array(entry.data),+ }));+ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dimensionsRef.current }, true);+ const resolvedOverrides: Partial<LayerItem> = {+ ...(tileSnapshot.format === 'monochrome-1bit' ? { expressionColor: 'monochrome' as const } : {}),+ ...layerOverrides,+ };+ insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, resolvedOverrides, insertTarget);+ setActiveLayerId(newId);+ return { id: newId, name: layerName, tileDeltas };+ },+ [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]+ );++ // Copy ONLY the selected pixels from a single layer into the sparse tile clipboard+ const copySelectionToClipboard = useCallback(+ (+ selection: CanvasSelection,+ targetId?: string+ ): { copied: boolean; empty?: boolean; layerName?: string; snapshot?: SelectionTileSnapshot } => {+ const id = targetId || activeLayerId;+ const targetLayer = layers.find((l) => l.id === id);+ if (!targetLayer || targetLayer.type !== 'raster') {+ return { copied: false };+ }++ const grid = activeTileGridRef.current;+ const dims = dimensionsRef.current;+ const snapshot = extractSelectionTileSnapshot({+ grid,+ layerId: id,+ dimensions: dims,+ selection,+ });++ if (!snapshot || snapshot.tiles.length === 0) {+ return { copied: false, empty: true, layerName: targetLayer.name };+ }++ layerClipboardRef.current = {+ name: targetLayer.name,+ type: 'raster',+ blendMode: targetLayer.blendMode,+ opacity: targetLayer.opacity,+ isSelection: true,+ expressionColor: targetLayer.expressionColor,+ tileSnapshot: {+ format: snapshot.format,+ tiles: snapshot.tiles.map((t) => ({+ tileX: t.tileX,+ tileY: t.tileY,+ format: t.format,+ data: new Uint8Array(t.data),+ })),+ },+ };++ // Best-effort export tight cutout to system clipboard+ try {+ const b = snapshot.bounds;+ if (navigator.clipboard && window.isSecureContext && b.width > 0 && b.height > 0 && b.width * b.height <= 4096 * 4096) {+ const temp = document.createElement('canvas');+ temp.width = b.width;+ temp.height = b.height;+ const tCtx = temp.getContext('2d');+ if (tCtx) {+ const outImg = tCtx.createImageData(b.width, b.height);+ const out = outImg.data;+ const scratch = new Uint8ClampedArray(TILE_SIZE * TILE_SIZE * 4);+ for (const entry of snapshot.tiles) {+ let rgba: Uint8ClampedArray;+ if (entry.format === 'color-32bit') {+ rgba = new Uint8ClampedArray(entry.data.buffer, entry.data.byteOffset, entry.data.byteLength);+ } else if (entry.format === 'monochrome-1bit') {+ unpack1BitToRGBA(entry.data, scratch);+ rgba = scratch;+ } else {+ unpack8BitToRGBA(entry.data, scratch);+ rgba = scratch;+ }+ const tx0 = entry.tileX * TILE_SIZE;+ const ty0 = entry.tileY * TILE_SIZE;+ const x0 = Math.max(b.x, tx0);+ const y0 = Math.max(b.y, ty0);+ const x1 = Math.min(b.x + b.width, tx0 + TILE_SIZE);+ const y1 = Math.min(b.y + b.height, ty0 + TILE_SIZE);+ for (let gy = y0; gy < y1; gy++) {+ const srcRow = (gy - ty0) * TILE_SIZE * 4;+ const dstRow = (gy - b.y) * b.width * 4;+ const srcStart = srcRow + (x0 - tx0) * 4;+ const dstStart = dstRow + (x0 - b.x) * 4;+ out.set(rgba.subarray(srcStart, srcStart + (x1 - x0) * 4), dstStart);+ }+ }+ tCtx.putImageData(outImg, 0, 0);+ temp.toBlob((blob) => {+ releaseTemporaryCanvas(temp);+ if (blob && navigator.clipboard && window.isSecureContext) {+ navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]).catch(() => {});+ }+ });+ } else {+ releaseTemporaryCanvas(temp);+ }+ }+ } catch {+ // Ignore clipboard write restrictions+ }++ return { copied: true, layerName: targetLayer.name, snapshot };+ },+ [activeLayerId, activeTileGridRef, dimensionsRef, layers]+ );+// Copy selected layer into sparse tile snapshot (zero retained full-doc HTMLCanvasElement)const copyLayer = useCallback((targetId?: string): LayerItem | null => {@@ -280,6 +428,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {type: targetLayer.type,blendMode: targetLayer.blendMode,opacity: targetLayer.opacity,+ isSelection: false,+ expressionColor: targetLayer.expressionColor,tileSnapshot,};@@ -310,18 +460,25 @@ export function useLayerClipboard(ctx: LayerManagerContext) {);// Paste layer from internal sparse tile clipboard or system clipboard- const pasteLayer = useCallback(async (): Promise<{ success: boolean; layerName?: string }> => {+ const pasteLayer = useCallback(async (): Promise<{+ success: boolean;+ layerId?: string;+ layerName?: string;+ tileDeltas?: TileDelta[];+ }> => {// 1. Check internal tile-backed clipboard (zero full-doc canvas)if (layerClipboardRef.current) {const data = layerClipboardRef.current;- const newName = `${data.name} Copy`;- const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;- const grid = activeTileGridRef.current;- grid.pasteLayerTilesSnapshot(newId, data.tileSnapshot);- const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dimensionsRef.current }, true);- insertNewLayerItem(newId, newName, data.blendMode, data.opacity, thumb);- setActiveLayerId(newId);- return { success: true, layerName: newName };+ const newName = data.isSelection ? `${data.name} (Selection)` : `${data.name} Copy`;+ const overrides = data.expressionColor ? { expressionColor: data.expressionColor } : undefined;+ const created = createLayerFromTileSnapshot(+ data.tileSnapshot,+ newName,+ data.blendMode,+ data.opacity,+ overrides+ );+ return { success: true, layerId: created.id, layerName: created.name, tileDeltas: created.tileDeltas };}// 2. Check system clipboard@@ -360,12 +517,18 @@ export function useLayerClipboard(ctx: LayerManagerContext) {URL.revokeObjectURL(url);releaseTemporaryCanvas(tight);+ const tileDeltas = grid.computeDeltasFromSnapshot(new Map(), newId, {+ x: dx,+ y: dy,+ width: dw,+ height: dh,+ });const newName = 'Pasted Image';const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions }, true);insertNewLayerItem(newId, newName, 'normal', 1, thumb);setActiveLayerId(newId);grid.notifyChange(true);- return { success: true, layerName: newName };+ return { success: true, layerId: newId, layerName: newName, tileDeltas };}}}@@ -374,7 +537,7 @@ export function useLayerClipboard(ctx: LayerManagerContext) {}return { success: false };- }, [activeTileGridRef, dimensions, dimensionsRef, insertNewLayerItem, setActiveLayerId]);+ }, [activeTileGridRef, createLayerFromTileSnapshot, dimensions, insertNewLayerItem, setActiveLayerId]);// Import an image file directly as a centered/fitted raster layer (tight-sized canvas -> tiles)const importImageFileAsLayer = useCallback(@@ -460,6 +623,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {pasteLayerFromCanvas,fillScreentoneSelection,copyLayer,+ copySelectionToClipboard,+ createLayerFromTileSnapshot,pasteLayer,importImageFileAsLayer,pasteLayerFromFile,diff --git a/src/hooks/layerManager/useLayerSpecialLayers.ts b/src/hooks/layerManager/useLayerSpecialLayers.tsindex 69da01b..b06b4df 100644--- a/src/hooks/layerManager/useLayerSpecialLayers.ts+++ b/src/hooks/layerManager/useLayerSpecialLayers.ts@@ -3,15 +3,36 @@ import {ComicFrame,FrameDivideMode,LayerItem,+ LayerTreeDelta,LayerType,SpeechBalloon,TextLayerData,+ TileDelta,hasTileBackedLayer,} from '../../types/editor';import { divideFramesInFolder, Point2D } from '../../utils/frameEngine';+import { getTileKey } from '../../utils/tileEngine';import { syncVectorObjectLayerToGrid } from '../../utils/vectorLayerRenderer';+import {+ ApplyLayerTreeDeltaResult,+ applyLayerTreeDelta as applyLayerTreeDeltaPure,+ cloneComicFrames,+ cloneLayerItemForHistory,+} from './layerTreeOps';import { LayerManagerContext } from './types';+export interface CreateFrameFolderResult {+ folder: LayerItem;+ childLayer: LayerItem | null;+ layerTreeDelta: LayerTreeDelta;+}++export interface DivideFrameFolderActionResult {+ divided: boolean;+ layerTreeDelta?: LayerTreeDelta;+ tileDeltas?: TileDelta[];+}+export function useLayerSpecialLayers(ctx: LayerManagerContext,addLayer: (@@ -26,8 +47,11 @@ export function useLayerSpecialLayers(const {activeTileGridRef,dimensionsRef,+ thumbDebounceTimersRef,setLayers,layersRef,+ setActiveLayerId,+ activeLayerIdRef,} = ctx;// Create or update a non-destructive Vector Text Layer (re-renders crisply into tileGrid)@@ -124,34 +148,115 @@ export function useLayerSpecialLayers(frames: ComicFrame[],customName?: string,addInitialChildLayer = true- ): { folder: LayerItem; childLayer: LayerItem | null } => {- const folder = addLayer('frame-folder', null, customName, undefined, !addInitialChildLayer);+ ): CreateFrameFolderResult => {+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const activeIdx = beforeLayers.findIndex((l) => l.id === beforeActiveLayerId);+ const currentActiveLayer = activeIdx >= 0 ? beforeLayers[activeIdx] : undefined;+ const insertIndex = activeIdx >= 0 ? activeIdx : 0;+ const insertBeforeLayerId = beforeLayers[insertIndex]?.id ?? null;++ const folderId = `frame-folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ let frameCount = 1;+ for (const l of beforeLayers) {+ if (l.type === 'frame-folder' && l.name.startsWith('Frame ')) {+ const num = parseInt(l.name.replace('Frame ', ''), 10);+ if (!isNaN(num) && num >= frameCount) frameCount = num + 1;+ }+ }++ const expressionColor =+ currentActiveLayer?.expressionColor === 'monochrome'+ ? 'monochrome'+ : currentActiveLayer?.expressionColor === 'gray'+ ? 'gray'+ : 'color';+ const monoThreshold = currentActiveLayer?.monoThreshold ?? 128;+ const monoExpressBlack = currentActiveLayer?.monoExpressBlack ?? true;+ const monoExpressWhite = currentActiveLayer?.monoExpressWhite ?? true;+const normalizedFrames = frames.map((f) => ({...f,- layerId: folder.id,+ layerId: folderId,clipChildren: f.clipChildren !== false,+ polygon: f.polygon.map((p) => ({ x: p.x, y: p.y })),}));+const updatedFolder: LayerItem = {- ...folder,+ id: folderId,+ name: customName || `Frame ${frameCount}`,+ type: 'frame-folder',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ thumbnailUrl: '',+ expressionColor,+ monoThreshold,+ monoExpressBlack,+ monoExpressWhite,comicFrames: normalizedFrames,};++ const grid = activeTileGridRef.current;+ let childLayer: LayerItem | null = null;+ if (addInitialChildLayer) {+ const childId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ childLayer = {+ id: childId,+ name: 'Panel Layer',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId: folderId,+ thumbnailUrl: '',+ expressionColor,+ monoThreshold,+ monoExpressBlack,+ monoExpressWhite,+ };+ const isMono = expressionColor === 'monochrome';+ grid.setLayerFormat(childId, isMono ? 'monochrome-1bit' : 'color-32bit');+ grid.markLayerIngested(childId);+ }++ const addedLayers = childLayer ? [updatedFolder, childLayer] : [updatedFolder];+ const syncNext = [...beforeLayers];+ syncNext.splice(insertIndex, 0, ...addedLayers);+ layersRef.current = syncNext;+setLayers((prev) => {- const next = prev.map((l) =>- l.id === folder.id ? { ...l, comicFrames: normalizedFrames } : l- );+ if (prev.some((l) => l.id === folderId)) return prev;+ const anchorIdx = insertBeforeLayerId+ ? prev.findIndex((l) => l.id === insertBeforeLayerId)+ : -1;+ const targetIdx = anchorIdx >= 0 ? anchorIdx : Math.min(insertIndex, prev.length);+ const next = [...prev];+ next.splice(targetIdx, 0, ...addedLayers);layersRef.current = next;return next;});- let childLayer: LayerItem | null = null;- if (addInitialChildLayer) {- childLayer = addLayer('raster', folder.id, 'Panel Layer', undefined, true);- }+ const afterActiveLayerId = childLayer ? childLayer.id : updatedFolder.id;+ setActiveLayerId(afterActiveLayerId);+ grid.notifyChange(true);++ const layerTreeDelta: LayerTreeDelta = {+ addedLayers: addedLayers.map(cloneLayerItemForHistory),+ insertBeforeLayerId,+ insertIndex,+ beforeActiveLayerId,+ afterActiveLayerId,+ };- activeTileGridRef.current.notifyChange(true);- return { folder: updatedFolder, childLayer };+ return { folder: updatedFolder, childLayer, layerTreeDelta };},- [activeTileGridRef, addLayer, layersRef, setLayers]+ [activeLayerIdRef, activeTileGridRef, layersRef, setActiveLayerId, setLayers]);// Divide a Frame Border Folder along a cut line (single folder split polygons or 2 independent folders)@@ -162,21 +267,27 @@ export function useLayerSpecialLayers(cutEnd: Point2D,dpi = 600,mode: FrameDivideMode = 'same-folder'- ): boolean => {+ ): DivideFrameFolderActionResult => {const current = layersRef.current;const folderIdx = current.findIndex((l) => l.id === folderId && l.type === 'frame-folder');- if (folderIdx < 0) return false;+ if (folderIdx < 0) return { divided: false };const folder = current[folderIdx];const frames = folder.comicFrames || [];- if (frames.length === 0) return false;+ if (frames.length === 0) return { divided: false };const result = divideFramesInFolder(frames, cutStart, cutEnd, dpi, mode);- if (!result.divided) return false;+ if (!result.divided) return { divided: false };const grid = activeTileGridRef.current;+ const beforeFrames = cloneComicFrames(frames);+ const currentActiveId = activeLayerIdRef.current;if (mode === 'same-folder' || result.folderGroups.length < 2) {const nextFrames = result.frames.map((f) => ({ ...f, layerId: folder.id }));+ const syncNext = current.map((l) =>+ l.id === folder.id ? { ...l, comicFrames: nextFrames } : l+ );+ layersRef.current = syncNext;setLayers((prev) => {const next = prev.map((l) =>l.id === folder.id ? { ...l, comicFrames: nextFrames } : l@@ -185,28 +296,55 @@ export function useLayerSpecialLayers(return next;});grid.notifyChange(true);- return true;+ return {+ divided: true,+ layerTreeDelta: {+ updatedLayers: [+ {+ layerId: folder.id,+ beforeComicFrames: beforeFrames,+ afterComicFrames: cloneComicFrames(nextFrames),+ },+ ],+ beforeActiveLayerId: currentActiveId,+ afterActiveLayerId: currentActiveId,+ },+ };}// Split into 2 independent frame folders, cloning child layers into the 2nd folder so artwork stays intactconst [group1, group2] = result.folderGroups;const newFolderId = `frame-folder-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;+ const group1Frames = group1.map((f) => ({ ...f, layerId: folder.id }));+ const group2Frames = group2.map((f) => ({ ...f, layerId: newFolderId }));const updatedFolder1: LayerItem = {...folder,- comicFrames: group1.map((f) => ({ ...f, layerId: folder.id })),+ comicFrames: group1Frames,};const newFolder2: LayerItem = {...folder,id: newFolderId,name: `${folder.name} B`,- comicFrames: group2.map((f) => ({ ...f, layerId: newFolderId })),+ comicFrames: group2Frames,};const directChildren = current.filter((l) => l.parentId === folder.id);+ const clonedTileDeltas: TileDelta[] = [];const clonedChildren: LayerItem[] = directChildren.map((child) => {const cloneId = `${child.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;if (hasTileBackedLayer(child)) {grid.cloneLayer(child.id, cloneId);+ for (const tile of grid.getLayerTiles(cloneId, 0)) {+ if (!tile.data) continue;+ const copy = new Uint8Array(tile.data.length);+ copy.set(tile.data);+ clonedTileDeltas.push({+ key: getTileKey(cloneId, tile.tileX, tile.tileY, 0),+ format: tile.format,+ beforeData: null,+ afterData: copy,+ });+ }}return {...child,@@ -218,19 +356,88 @@ export function useLayerSpecialLayers(};});+ const addedLayers = [newFolder2, ...clonedChildren];+ const syncNext = current.map((l) => (l.id === folder.id ? updatedFolder1 : l));+ syncNext.splice(folderIdx, 0, ...addedLayers);+ layersRef.current = syncNext;+setLayers((prev) => {+ if (prev.some((l) => l.id === newFolderId)) return prev;const idx = prev.findIndex((l) => l.id === folder.id);if (idx < 0) return prev;const next = prev.map((l) => (l.id === folder.id ? updatedFolder1 : l));- next.splice(idx, 0, newFolder2, ...clonedChildren);+ next.splice(idx, 0, ...addedLayers);layersRef.current = next;return next;});grid.notifyChange(true);- return true;+ return {+ divided: true,+ layerTreeDelta: {+ addedLayers: addedLayers.map(cloneLayerItemForHistory),+ insertBeforeLayerId: folder.id,+ insertIndex: folderIdx,+ updatedLayers: [+ {+ layerId: folder.id,+ beforeComicFrames: beforeFrames,+ afterComicFrames: cloneComicFrames(group1Frames),+ },+ ],+ beforeActiveLayerId: currentActiveId,+ afterActiveLayerId: currentActiveId,+ },+ tileDeltas: clonedTileDeltas.length > 0 ? clonedTileDeltas : undefined,+ };+ },+ [activeLayerIdRef, activeTileGridRef, layersRef, setLayers]+ );++ // Apply a targeted LayerTreeDelta during Undo/Redo (keeps React state, refs, and SparseTileGrid synchronized)+ const applyLayerTreeDelta = useCallback(+ (delta: LayerTreeDelta, direction: 'undo' | 'redo'): ApplyLayerTreeDeltaResult => {+ const grid = activeTileGridRef.current;+ const syncResult = applyLayerTreeDeltaPure(+ layersRef.current,+ activeLayerIdRef.current,+ delta,+ direction+ );+ layersRef.current = syncResult.nextLayers;++ setLayers((prev) => {+ const nextRes = applyLayerTreeDeltaPure(prev, activeLayerIdRef.current, delta, direction);+ layersRef.current = nextRes.nextLayers;+ return nextRes.nextLayers;+ });++ if (direction === 'undo') {+ for (const delId of syncResult.removedLayerIds) {+ const timer = thumbDebounceTimersRef.current.get(delId);+ if (timer) {+ clearTimeout(timer);+ thumbDebounceTimersRef.current.delete(delId);+ }+ grid.clearLayer(delId);+ }+ } else {+ for (const added of syncResult.addedLayers) {+ if (hasTileBackedLayer(added)) {+ const isMono = added.expressionColor === 'monochrome';+ grid.setLayerFormat(added.id, isMono ? 'monochrome-1bit' : 'color-32bit');+ grid.markLayerIngested(added.id);+ }+ }+ }++ if (syncResult.nextActiveLayerId !== null) {+ setActiveLayerId(syncResult.nextActiveLayerId);+ }++ return syncResult;},- [activeTileGridRef, layersRef, setLayers]+ [activeLayerIdRef, activeTileGridRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);// Rasterize a non-destructive text, balloon, or vector layer into a standard raster layer@@ -274,6 +481,7 @@ export function useLayerSpecialLayers(upsertBalloonLayer,createFrameFolder,divideFrameFolder,+ applyLayerTreeDelta,rasterizeLayer,};}diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsxindex 25abf98..afc1ad4 100644--- a/src/hooks/useAppMenuSections.tsx+++ b/src/hooks/useAppMenuSections.tsx@@ -68,6 +68,11 @@ export interface UseAppMenuSectionsParams {handleSave: () => void;handleSaveAs: () => void;handleExportImage: () => void;+ handleCutSelection: () => void;+ handleCopySelection: () => void;+ handleMoveSelectionToNewLayer: () => void;+ handleClearSelection: () => void;+ handleDeleteOutsideSelection: () => void;handleCopySelectedLayer: () => void;handlePasteSelectedLayer: () => void;handleTriggerPasteFromFile: () => void;@@ -140,6 +145,11 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleSave,handleSaveAs,handleExportImage,+ handleCutSelection,+ handleCopySelection,+ handleMoveSelectionToNewLayer,+ handleClearSelection,+ handleDeleteOutsideSelection,handleCopySelectedLayer,handlePasteSelectedLayer,handleTriggerPasteFromFile,@@ -339,12 +349,19 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioonClick: redo,},{ id: 'edit-div-1', label: '', divider: true },+ {+ id: 'edit-cut',+ label: 'Cut',+ shortcut: 'Ctrl+X',+ disabled: !hasOpenDocument || !activeLayer || !selection,+ onClick: handleCutSelection,+ },{id: 'edit-copy',label: 'Copy',shortcut: 'Ctrl+C',disabled: !hasOpenDocument || !activeLayer,- onClick: handleCopySelectedLayer,+ onClick: selection ? handleCopySelection : handleCopySelectedLayer,},{id: 'edit-paste',@@ -353,6 +370,13 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiodisabled: !hasOpenDocument,onClick: handlePasteSelectedLayer,},+ {+ id: 'edit-move-selection-layer',+ label: 'Move Selection to New Layer',+ shortcut: 'Ctrl+Shift+J',+ disabled: !hasOpenDocument || !activeLayer || !selection,+ onClick: handleMoveSelectionToNewLayer,+ },{id: 'edit-paste-file',label: 'Paste from file...',@@ -530,6 +554,44 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioonClick: () => handleFeatherSelection(5),},{ id: 'select-div-2', label: '', divider: true },+ {+ id: 'select-cut',+ label: 'Cut Selection',+ shortcut: 'Ctrl+X',+ disabled: !hasOpenDocument || !selection,+ onClick: handleCutSelection,+ },+ {+ id: 'select-copy',+ label: 'Copy Selection',+ shortcut: 'Ctrl+C',+ disabled: !hasOpenDocument || !selection,+ onClick: handleCopySelection,+ },+ {+ id: 'select-move-to-layer',+ label: 'Move Selection to New Layer',+ shortcut: 'Ctrl+Shift+J',+ disabled: !hasOpenDocument || !selection,+ onClick: handleMoveSelectionToNewLayer,+ },+ { id: 'select-div-3', label: '', divider: true },+ {+ id: 'select-delete',+ label: 'Delete Selection',+ shortcut: 'Del',+ danger: true,+ disabled: !hasOpenDocument || !selection,+ onClick: handleClearSelection,+ },+ {+ id: 'select-delete-outside',+ label: 'Delete Outside Selection',+ danger: true,+ disabled: !hasOpenDocument || !selection,+ onClick: handleDeleteOutsideSelection,+ },+ { id: 'select-div-4', label: '', divider: true },{id: 'select-transform',label: 'Transform Selection',@@ -1372,9 +1434,13 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleApplyFilter,handleApplyReverseGradient,handleClearActiveLayer,+ handleClearSelection,handleContractSelection,handleConvertLayer,handleCopySelectedLayer,+ handleCopySelection,+ handleCutSelection,+ handleDeleteOutsideSelection,handleDeleteSelectedLayer,handleDeselect,handleExpandSelection,@@ -1383,6 +1449,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleFillSelectionColor,handleInvertSelection,handleMergeDown,+ handleMoveSelectionToNewLayer,handleOpenAdjustmentModal,handleOpenLayerStylesModal,handleOpenTonalModal,diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.tsindex 6c6fc37..0a3cc40 100644--- a/src/hooks/useCanvasDrawing.ts+++ b/src/hooks/useCanvasDrawing.ts@@ -31,6 +31,7 @@ export function useCanvasDrawing({activeLayerVisible = true,layers,onUpdateLayerThumbnail,+ onApplyLayerTreeDelta,isMaskMode = false,onUpdateMaskThumbnail,draftCanvasRef,@@ -74,6 +75,7 @@ export function useCanvasDrawing({const selectionRef = useRef(selection);const isMaskModeRef = useRef(isMaskMode);const layersRef = useRef(layers);+ const onApplyLayerTreeDeltaRef = useRef(onApplyLayerTreeDelta);const onUpdateMaskThumbnailRef = useRef(onUpdateMaskThumbnail);const onCollabStrokeStartRef = useRef(onCollabStrokeStart);const onCollabStrokeChunkRef = useRef(onCollabStrokeChunk);@@ -101,6 +103,7 @@ export function useCanvasDrawing({selectionRef.current = selection;isMaskModeRef.current = isMaskMode;layersRef.current = layers;+ onApplyLayerTreeDeltaRef.current = onApplyLayerTreeDelta;onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;onCollabStrokeStartRef.current = onCollabStrokeStart;onCollabStrokeChunkRef.current = onCollabStrokeChunk;@@ -126,6 +129,7 @@ export function useCanvasDrawing({selection,isMaskMode,layers,+ onApplyLayerTreeDelta,onUpdateMaskThumbnail,onCollabStrokeStart,onCollabStrokeChunk,@@ -157,6 +161,7 @@ export function useCanvasDrawing({colorModeRef,layersRef,onUpdateLayerThumbnail,+ onApplyLayerTreeDeltaRef,onUpdateMaskThumbnailRef,isDrawingRef,lastStrokeEndRef,diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.tsindex 27f1fc8..075005a 100644--- a/src/hooks/useCanvasNavigation.ts+++ b/src/hooks/useCanvasNavigation.ts@@ -71,6 +71,14 @@ export const ROTATE_CURSOR_CSS = `url('${ROTATE_CURSOR_SVG}') 16 16, crosshair`;export const ROTATION_CENTER_DAMP_RADIUS = 64;+/**+ * Matches Space across physical keyboards, IME layouts, and tablet driver synthetic SendInput+ * events (e.g. XP-Pen / Wacom express keys emitting VK_SPACE with empty `code`).+ */+export function isSpaceKeyEvent(e: KeyboardEvent): boolean {+ return e.code === 'Space' || e.key === ' ' || e.key === 'Spacebar' || e.keyCode === 32;+}+/*** Computes a continuous, branch-cut-free signed angular delta (degrees) between two* pointer positions around a pivot, with smooth radial damping near the pivot center@@ -211,6 +219,13 @@ export function useCanvasNavigation({const cameraSubscribersRef = useRef<Set<CameraSubscriber>>(new Set());const cameraBroadcastRafRef = useRef<number | null>(null);const navCommitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const activeDragCleanupRef = useRef<(() => void) | null>(null);++ const setNavBodyCursor = useCallback((cursor: string | null) => {+ if (typeof document === 'undefined') return;+ document.body.style.cursor = cursor ?? '';+ document.body.style.userSelect = cursor ? 'none' : '';+ }, []);const getCameraState = useCallback((): CameraTransformState => {return {@@ -282,6 +297,8 @@ export function useCanvasNavigation({useEffect(() => {return () => {+ activeDragCleanupRef.current?.();+ activeDragCleanupRef.current = null;if (cameraBroadcastRafRef.current !== null) {cancelAnimationFrame(cameraBroadcastRafRef.current);cameraBroadcastRafRef.current = null;@@ -650,63 +667,365 @@ export function useCanvasNavigation({zoomToViewportCenter(target);}, [zoomToViewportCenter]);- const startPan = useCallback((e: React.PointerEvent | PointerEvent) => {- e.preventDefault();- isPanningRef.current = true;- setIsPanning(true);+ const startPan = useCallback(+ (e: React.PointerEvent | PointerEvent) => {+ e.preventDefault();+ activeDragCleanupRef.current?.();+ activeDragCleanupRef.current = null;++ const activePointerId = typeof e.pointerId === 'number' ? e.pointerId : null;+ isPanningRef.current = true;+ panStartRef.current = {+ clientX: e.clientX,+ clientY: e.clientY,+ panX: panRef.current.x,+ panY: panRef.current.y,+ };- panStartRef.current = {- clientX: e.clientX,- clientY: e.clientY,- panX: panRef.current.x,- panY: panRef.current.y,- };- }, []);+ const teardown = () => {+ window.removeEventListener('pointermove', handleWindowPointerMove);+ window.removeEventListener('pointerup', handleWindowPointerUp, true);+ window.removeEventListener('pointercancel', handleWindowPointerUp, true);+ window.removeEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor(null);+ if (activeDragCleanupRef.current === teardown) {+ activeDragCleanupRef.current = null;+ }+ };- const startRotate = useCallback((e: React.PointerEvent | PointerEvent) => {- e.preventDefault();- const viewport = viewportRef.current;- if (!viewport) return;+ const finishPan = () => {+ teardown();+ if (!isPanningRef.current) return;+ isPanningRef.current = false;+ broadcastCameraImmediate();+ setIsPanning(false);+ commitNavStateImmediate();+ };- const rect = viewport.getBoundingClientRect();- const vc = {- x: viewport.clientWidth / 2,- y: viewport.clientHeight / 2,- };+ const handleWindowPointerMove = (ev: PointerEvent) => {+ if (!isPanningRef.current) return;+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId+ ) {+ return;+ }+ // Recover immediately if pen/button lifted without delivering pointerup (XP-Pen / WinTab proximity drop)+ if (typeof ev.buttons === 'number' && ev.buttons === 0) {+ finishPan();+ return;+ }+ const dx = ev.clientX - panStartRef.current.clientX;+ const dy = ev.clientY - panStartRef.current.clientY;+ panRef.current = {+ x: isWebtoonModeRef.current ? panStartRef.current.panX : panStartRef.current.panX + dx,+ y: panStartRef.current.panY + dy,+ };+ scheduleCameraBroadcast();+ };- const px = e.clientX - rect.left;- const py = e.clientY - rect.top;-- rotateStartRef.current = {- lastX: px,- lastY: py,- startCanvasRotation: rotationRef.current,- totalAngleDelta: 0,- targetRotation: rotationRef.current,- startPan: { ...panRef.current },- center: vc,- };+ const handleWindowPointerUp = (ev: PointerEvent) => {+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId &&+ (typeof ev.buttons !== 'number' || ev.buttons !== 0)+ ) {+ return;+ }+ finishPan();+ };- isRotatingRef.current = true;- setIsRotating(true);- }, []);+ const handleWindowMouseUp = (ev: MouseEvent) => {+ if (typeof ev.buttons !== 'number' || ev.buttons === 0) {+ finishPan();+ }+ };- const startZoomDrag = useCallback((e: React.PointerEvent | PointerEvent) => {- e.preventDefault();- const viewport = viewportRef.current;- if (!viewport) return;- const rect = viewport.getBoundingClientRect();- zoomDragStartRef.current = {- clientX: e.clientX,- clientY: e.clientY,- anchorX: e.clientX - rect.left,- anchorY: e.clientY - rect.top,- startZoom: zoomRef.current,- startPan: { ...panRef.current },- };- isZoomDraggingRef.current = true;- setIsZoomDragging(true);- }, []);+ activeDragCleanupRef.current = teardown;+ window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });+ window.addEventListener('pointerup', handleWindowPointerUp, true);+ window.addEventListener('pointercancel', handleWindowPointerUp, true);+ window.addEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor('grabbing');+ setIsPanning(true);+ },+ [broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast, setNavBodyCursor]+ );++ const startRotate = useCallback(+ (e: React.PointerEvent | PointerEvent) => {+ e.preventDefault();+ const viewport = viewportRef.current;+ if (!viewport) return;++ activeDragCleanupRef.current?.();+ activeDragCleanupRef.current = null;++ let cachedRect: DOMRect | null = viewport.getBoundingClientRect();+ const vc = {+ x: viewport.clientWidth / 2,+ y: viewport.clientHeight / 2,+ };++ const px = e.clientX - cachedRect.left;+ const py = e.clientY - cachedRect.top;++ rotateStartRef.current = {+ lastX: px,+ lastY: py,+ startCanvasRotation: rotationRef.current,+ totalAngleDelta: 0,+ targetRotation: rotationRef.current,+ startPan: { ...panRef.current },+ center: vc,+ };++ const activePointerId = typeof e.pointerId === 'number' ? e.pointerId : null;+ let smoothRafId: number | null = null;+ let lastFrameTs = performance.now();++ const applyRotationToCamera = (angleDeg: number) => {+ const { center, startCanvasRotation, startPan } = rotateStartRef.current;+ rotationRef.current = angleDeg;+ const dRad = ((angleDeg - startCanvasRotation) * Math.PI) / 180;+ const cos = Math.cos(dRad);+ const sin = Math.sin(dRad);+ const rx = startPan.x - center.x;+ const ry = startPan.y - center.y;+ panRef.current = {+ x: center.x + rx * cos - ry * sin,+ y: center.y + rx * sin + ry * cos,+ };+ };++ const stepSmoothRotation = (now: number) => {+ smoothRafId = null;+ if (!isRotatingRef.current) return;++ const dt = Math.min(0.05, Math.max(0.001, (now - lastFrameTs) / 1000));+ lastFrameTs = now;++ const target = rotateStartRef.current.targetRotation;+ const current = rotationRef.current;+ const diff = target - current;++ if (Math.abs(diff) < 0.01) {+ if (current !== target) {+ applyRotationToCamera(target);+ emitCameraToSubscribers();+ }+ return;+ }++ const alpha = 1 - Math.exp(-dt * 28);+ applyRotationToCamera(current + diff * alpha);+ emitCameraToSubscribers();+ smoothRafId = requestAnimationFrame(stepSmoothRotation);+ };++ const ensureSmoothLoop = () => {+ if (smoothRafId === null) {+ lastFrameTs = performance.now();+ smoothRafId = requestAnimationFrame(stepSmoothRotation);+ }+ };++ const teardown = () => {+ if (smoothRafId !== null) {+ cancelAnimationFrame(smoothRafId);+ smoothRafId = null;+ }+ window.removeEventListener('pointermove', handleWindowPointerMove);+ window.removeEventListener('pointerup', handleWindowPointerUp, true);+ window.removeEventListener('pointercancel', handleWindowPointerUp, true);+ window.removeEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor(null);+ if (activeDragCleanupRef.current === teardown) {+ activeDragCleanupRef.current = null;+ }+ };++ const finishRotate = () => {+ teardown();+ if (!isRotatingRef.current) return;+ isRotatingRef.current = false;+ applyRotationToCamera(rotateStartRef.current.targetRotation);+ broadcastCameraImmediate();+ setIsRotating(false);+ commitNavStateImmediate();+ };++ const handleWindowPointerMove = (ev: PointerEvent) => {+ if (!isRotatingRef.current) return;+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId+ ) {+ return;+ }+ if (typeof ev.buttons === 'number' && ev.buttons === 0) {+ finishRotate();+ return;+ }+ const vp = viewportRef.current;+ if (!vp) return;+ if (!cachedRect) cachedRect = vp.getBoundingClientRect();+ const center = rotateStartRef.current.center;+ const curX = ev.clientX - cachedRect.left;+ const curY = ev.clientY - cachedRect.top;++ const diff = computeSmoothRotationDelta(+ rotateStartRef.current.lastX,+ rotateStartRef.current.lastY,+ curX,+ curY,+ center.x,+ center.y+ );++ rotateStartRef.current.lastX = curX;+ rotateStartRef.current.lastY = curY;+ rotateStartRef.current.totalAngleDelta += diff;++ let nextTarget =+ rotateStartRef.current.startCanvasRotation + rotateStartRef.current.totalAngleDelta;++ if (ev.altKey || ev.ctrlKey) {+ nextTarget = Math.round(nextTarget / 15) * 15;+ }++ rotateStartRef.current.targetRotation = nextTarget;+ ensureSmoothLoop();+ };++ const handleWindowPointerUp = (ev: PointerEvent) => {+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId &&+ (typeof ev.buttons !== 'number' || ev.buttons !== 0)+ ) {+ return;+ }+ finishRotate();+ };++ const handleWindowMouseUp = (ev: MouseEvent) => {+ if (typeof ev.buttons !== 'number' || ev.buttons === 0) {+ finishRotate();+ }+ };++ isRotatingRef.current = true;+ activeDragCleanupRef.current = teardown;+ window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });+ window.addEventListener('pointerup', handleWindowPointerUp, true);+ window.addEventListener('pointercancel', handleWindowPointerUp, true);+ window.addEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor(ROTATE_CURSOR_CSS);+ setIsRotating(true);+ },+ [broadcastCameraImmediate, commitNavStateImmediate, emitCameraToSubscribers, setNavBodyCursor]+ );++ const startZoomDrag = useCallback(+ (e: React.PointerEvent | PointerEvent) => {+ e.preventDefault();+ const viewport = viewportRef.current;+ if (!viewport) return;++ activeDragCleanupRef.current?.();+ activeDragCleanupRef.current = null;++ const rect = viewport.getBoundingClientRect();+ zoomDragStartRef.current = {+ clientX: e.clientX,+ clientY: e.clientY,+ anchorX: e.clientX - rect.left,+ anchorY: e.clientY - rect.top,+ startZoom: zoomRef.current,+ startPan: { ...panRef.current },+ };++ const activePointerId = typeof e.pointerId === 'number' ? e.pointerId : null;++ const teardown = () => {+ window.removeEventListener('pointermove', handleWindowPointerMove);+ window.removeEventListener('pointerup', handleWindowPointerUp, true);+ window.removeEventListener('pointercancel', handleWindowPointerUp, true);+ window.removeEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor(null);+ if (activeDragCleanupRef.current === teardown) {+ activeDragCleanupRef.current = null;+ }+ };++ const finishZoomDrag = () => {+ teardown();+ if (!isZoomDraggingRef.current) return;+ isZoomDraggingRef.current = false;+ broadcastCameraImmediate();+ setIsZoomDragging(false);+ commitNavStateImmediate();+ };++ const handleWindowPointerMove = (ev: PointerEvent) => {+ if (!isZoomDraggingRef.current) return;+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId+ ) {+ return;+ }+ if (typeof ev.buttons === 'number' && ev.buttons === 0) {+ finishZoomDrag();+ return;+ }+ const dx = ev.clientX - zoomDragStartRef.current.clientX;+ const { anchorX, anchorY, startZoom, startPan } = zoomDragStartRef.current;+ const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, startZoom * Math.exp(dx * 0.007)));+ const ratio = nextZoom / startZoom;+ zoomRef.current = nextZoom;+ panRef.current = {+ x: anchorX - (anchorX - startPan.x) * ratio,+ y: anchorY - (anchorY - startPan.y) * ratio,+ };+ scheduleCameraBroadcast();+ };++ const handleWindowPointerUp = (ev: PointerEvent) => {+ if (+ activePointerId !== null &&+ typeof ev.pointerId === 'number' &&+ ev.pointerId !== activePointerId &&+ (typeof ev.buttons !== 'number' || ev.buttons !== 0)+ ) {+ return;+ }+ finishZoomDrag();+ };++ const handleWindowMouseUp = (ev: MouseEvent) => {+ if (typeof ev.buttons !== 'number' || ev.buttons === 0) {+ finishZoomDrag();+ }+ };++ isZoomDraggingRef.current = true;+ activeDragCleanupRef.current = teardown;+ window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });+ window.addEventListener('pointerup', handleWindowPointerUp, true);+ window.addEventListener('pointercancel', handleWindowPointerUp, true);+ window.addEventListener('mouseup', handleWindowMouseUp, true);+ setNavBodyCursor('zoom-in');+ setIsZoomDragging(true);+ },+ [broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast, setNavBodyCursor]+ );useEffect(() => {hasInitializedCenterRef.current = false;@@ -829,6 +1148,21 @@ export function useCanvasNavigation({// Modifier state tracking (Space, Shift, Ctrl, Alt) for navigation & modifier-key drag modesuseEffect(() => {+ const syncModifierState = (shift: boolean, ctrl: boolean, alt: boolean) => {+ if (isShiftDownRef.current !== shift) {+ isShiftDownRef.current = shift;+ setIsShiftDown(shift);+ }+ if (isCtrlDownRef.current !== ctrl) {+ isCtrlDownRef.current = ctrl;+ setIsCtrlDown(ctrl);+ }+ if (isAltDownRef.current !== alt) {+ isAltDownRef.current = alt;+ setIsAltDown(alt);+ }+ };+const handleKeyDown = (e: KeyboardEvent) => {const targetEl = e.target as HTMLElement | null;if (@@ -841,21 +1175,14 @@ export function useCanvasNavigation({return;}- if (e.key === 'Shift' && !isShiftDownRef.current) {- isShiftDownRef.current = true;- setIsShiftDown(true);- }- if ((e.key === 'Control' || e.key === 'Meta') && !isCtrlDownRef.current) {- isCtrlDownRef.current = true;- setIsCtrlDown(true);- }- if (e.key === 'Alt' && !isAltDownRef.current) {- isAltDownRef.current = true;- setIsAltDown(true);- }+ const nextShift = e.key === 'Shift' ? true : Boolean(e.shiftKey);+ const nextCtrl =+ e.key === 'Control' || e.key === 'Meta' ? true : Boolean(e.ctrlKey || e.metaKey);+ const nextAlt = e.key === 'Alt' ? true : Boolean(e.altKey);+ syncModifierState(nextShift, nextCtrl, nextAlt);// Space key for Pan / Rotate / Scrubby Zoom (skip Alt+Space so Animation playback can use it)- if ((e.code === 'Space' || e.key === ' ') && !e.altKey) {+ if (isSpaceKeyEvent(e) && !e.altKey) {e.preventDefault();if (!isSpaceDownRef.current) {isSpaceDownRef.current = true;@@ -865,264 +1192,66 @@ export function useCanvasNavigation({};const handleKeyUp = (e: KeyboardEvent) => {- if (e.key === 'Shift') {- isShiftDownRef.current = false;- setIsShiftDown(false);- }- if (e.key === 'Control' || e.key === 'Meta') {- isCtrlDownRef.current = false;- setIsCtrlDown(false);- }- if (e.key === 'Alt') {- isAltDownRef.current = false;- setIsAltDown(false);- }- if (e.code === 'Space' || e.key === ' ') {+ const nextShift = e.key === 'Shift' ? false : Boolean(e.shiftKey);+ const nextCtrl =+ e.key === 'Control' || e.key === 'Meta' ? false : Boolean(e.ctrlKey || e.metaKey);+ const nextAlt = e.key === 'Alt' ? false : Boolean(e.altKey);+ syncModifierState(nextShift, nextCtrl, nextAlt);++ if (isSpaceKeyEvent(e) && isSpaceDownRef.current) {isSpaceDownRef.current = false;setIsSpaceDown(false);}};- const handleBlur = () => {+ const resetAllNavState = () => {const wasInteracting =isPanningRef.current || isRotatingRef.current || isZoomDraggingRef.current;- isSpaceDownRef.current = false;- setIsSpaceDown(false);- isShiftDownRef.current = false;- setIsShiftDown(false);- isCtrlDownRef.current = false;- setIsCtrlDown(false);- isAltDownRef.current = false;- setIsAltDown(false);- isPanningRef.current = false;- setIsPanning(false);- isRotatingRef.current = false;- setIsRotating(false);- isZoomDraggingRef.current = false;- setIsZoomDragging(false);- if (wasInteracting) {- broadcastCameraImmediate();- commitNavStateImmediate();+ activeDragCleanupRef.current?.();+ activeDragCleanupRef.current = null;+ setNavBodyCursor(null);+ if (isSpaceDownRef.current) {+ isSpaceDownRef.current = false;+ setIsSpaceDown(false);}- };-- window.addEventListener('keydown', handleKeyDown);- window.addEventListener('keyup', handleKeyUp);- window.addEventListener('blur', handleBlur);-- return () => {- window.removeEventListener('keydown', handleKeyDown);- window.removeEventListener('keyup', handleKeyUp);- window.removeEventListener('blur', handleBlur);- };- }, [broadcastCameraImmediate, commitNavStateImmediate]);-- // Panning pointermove: broadcasts directly to DOM/WebGL via rAF; commits React state only on pointerup- useEffect(() => {- if (!isPanning) return;-- const handleWindowPointerMove = (e: PointerEvent) => {- if (!isPanningRef.current) return;- const dx = e.clientX - panStartRef.current.clientX;- const dy = e.clientY - panStartRef.current.clientY;-- panRef.current = {- x: isWebtoonModeRef.current ? panStartRef.current.panX : panStartRef.current.panX + dx,- y: panStartRef.current.panY + dy,- };- scheduleCameraBroadcast();- };-- const handleWindowPointerUp = () => {- isPanningRef.current = false;- broadcastCameraImmediate();- setIsPanning(false);- commitNavStateImmediate();- };-- window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });- window.addEventListener('pointerup', handleWindowPointerUp);- window.addEventListener('pointercancel', handleWindowPointerUp);-- const prevCursor = document.body.style.cursor;- const prevUserSelect = document.body.style.userSelect;- document.body.style.cursor = 'grabbing';- document.body.style.userSelect = 'none';-- return () => {- window.removeEventListener('pointermove', handleWindowPointerMove);- window.removeEventListener('pointerup', handleWindowPointerUp);- window.removeEventListener('pointercancel', handleWindowPointerUp);- document.body.style.cursor = prevCursor;- document.body.style.userSelect = prevUserSelect;- };- }, [isPanning, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);-- // Rotating pointermove: damped radial delta + frame-rate-independent rAF smoothing across all angles- useEffect(() => {- if (!isRotating) return;-- let cachedRect: DOMRect | null = viewportRef.current- ? viewportRef.current.getBoundingClientRect()- : null;- let smoothRafId: number | null = null;- let lastFrameTs = performance.now();-- const applyRotationToCamera = (angleDeg: number) => {- const { center: vc, startCanvasRotation, startPan } = rotateStartRef.current;- rotationRef.current = angleDeg;- const dRad = ((angleDeg - startCanvasRotation) * Math.PI) / 180;- const cos = Math.cos(dRad);- const sin = Math.sin(dRad);- const rx = startPan.x - vc.x;- const ry = startPan.y - vc.y;- panRef.current = {- x: vc.x + rx * cos - ry * sin,- y: vc.y + rx * sin + ry * cos,- };- };-- const stepSmoothRotation = (now: number) => {- smoothRafId = null;- if (!isRotatingRef.current) return;-- const dt = Math.min(0.05, Math.max(0.001, (now - lastFrameTs) / 1000));- lastFrameTs = now;-- const target = rotateStartRef.current.targetRotation;- const current = rotationRef.current;- const diff = target - current;-- if (Math.abs(diff) < 0.01) {- if (current !== target) {- applyRotationToCamera(target);- emitCameraToSubscribers();- }- return;+ syncModifierState(false, false, false);+ if (isPanningRef.current) {+ isPanningRef.current = false;+ setIsPanning(false);}-- const alpha = 1 - Math.exp(-dt * 28);- applyRotationToCamera(current + diff * alpha);- emitCameraToSubscribers();- smoothRafId = requestAnimationFrame(stepSmoothRotation);- };-- const ensureSmoothLoop = () => {- if (smoothRafId === null) {- lastFrameTs = performance.now();- smoothRafId = requestAnimationFrame(stepSmoothRotation);+ if (isRotatingRef.current) {+ isRotatingRef.current = false;+ setIsRotating(false);}- };-- const handleWindowPointerMove = (e: PointerEvent) => {- if (!isRotatingRef.current) return;- const viewport = viewportRef.current;- if (!viewport) return;-- if (!cachedRect) cachedRect = viewport.getBoundingClientRect();- const vc = rotateStartRef.current.center;- const px = e.clientX - cachedRect.left;- const py = e.clientY - cachedRect.top;-- const diff = computeSmoothRotationDelta(- rotateStartRef.current.lastX,- rotateStartRef.current.lastY,- px,- py,- vc.x,- vc.y- );-- rotateStartRef.current.lastX = px;- rotateStartRef.current.lastY = py;- rotateStartRef.current.totalAngleDelta += diff;-- let nextTarget =- rotateStartRef.current.startCanvasRotation + rotateStartRef.current.totalAngleDelta;-- if (e.altKey || e.ctrlKey) {- nextTarget = Math.round(nextTarget / 15) * 15;+ if (isZoomDraggingRef.current) {+ isZoomDraggingRef.current = false;+ setIsZoomDragging(false);}-- rotateStartRef.current.targetRotation = nextTarget;- ensureSmoothLoop();- };-- const handleWindowPointerUp = () => {- if (smoothRafId !== null) {- cancelAnimationFrame(smoothRafId);- smoothRafId = null;+ if (wasInteracting) {+ broadcastCameraImmediate();+ commitNavStateImmediate();}- isRotatingRef.current = false;- applyRotationToCamera(rotateStartRef.current.targetRotation);- broadcastCameraImmediate();- setIsRotating(false);- commitNavStateImmediate();};- window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });- window.addEventListener('pointerup', handleWindowPointerUp);- window.addEventListener('pointercancel', handleWindowPointerUp);-- const prevCursor = document.body.style.cursor;- const prevUserSelect = document.body.style.userSelect;- document.body.style.cursor = ROTATE_CURSOR_CSS;- document.body.style.userSelect = 'none';-- return () => {- if (smoothRafId !== null) {- cancelAnimationFrame(smoothRafId);+ const handleVisibilityChange = () => {+ if (document.hidden) {+ resetAllNavState();}- window.removeEventListener('pointermove', handleWindowPointerMove);- window.removeEventListener('pointerup', handleWindowPointerUp);- window.removeEventListener('pointercancel', handleWindowPointerUp);- document.body.style.cursor = prevCursor;- document.body.style.userSelect = prevUserSelect;- };- }, [isRotating, emitCameraToSubscribers, broadcastCameraImmediate, commitNavStateImmediate]);-- // Scrubby Zoom pointermove (default Ctrl+Space+Drag): zero-rerender via rAF camera broadcast- useEffect(() => {- if (!isZoomDragging) return;-- const handleWindowPointerMove = (e: PointerEvent) => {- if (!isZoomDraggingRef.current) return;- const dx = e.clientX - zoomDragStartRef.current.clientX;- const { anchorX, anchorY, startZoom, startPan } = zoomDragStartRef.current;- const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, startZoom * Math.exp(dx * 0.007)));- const ratio = nextZoom / startZoom;- zoomRef.current = nextZoom;- panRef.current = {- x: anchorX - (anchorX - startPan.x) * ratio,- y: anchorY - (anchorY - startPan.y) * ratio,- };- scheduleCameraBroadcast();};- const handleWindowPointerUp = () => {- isZoomDraggingRef.current = false;- broadcastCameraImmediate();- setIsZoomDragging(false);- commitNavStateImmediate();- };-- window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });- window.addEventListener('pointerup', handleWindowPointerUp);- window.addEventListener('pointercancel', handleWindowPointerUp);-- const prevCursor = document.body.style.cursor;- const prevUserSelect = document.body.style.userSelect;- document.body.style.cursor = 'zoom-in';- document.body.style.userSelect = 'none';+ window.addEventListener('keydown', handleKeyDown);+ // Capture phase ensures child stopPropagation() cannot swallow Space/modifier keyup+ window.addEventListener('keyup', handleKeyUp, true);+ window.addEventListener('blur', resetAllNavState);+ document.addEventListener('visibilitychange', handleVisibilityChange);return () => {- window.removeEventListener('pointermove', handleWindowPointerMove);- window.removeEventListener('pointerup', handleWindowPointerUp);- window.removeEventListener('pointercancel', handleWindowPointerUp);- document.body.style.cursor = prevCursor;- document.body.style.userSelect = prevUserSelect;+ window.removeEventListener('keydown', handleKeyDown);+ window.removeEventListener('keyup', handleKeyUp, true);+ window.removeEventListener('blur', resetAllNavState);+ document.removeEventListener('visibilitychange', handleVisibilityChange);};- }, [isZoomDragging, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);+ }, [broadcastCameraImmediate, commitNavStateImmediate, setNavBodyCursor]);useEffect(() => {const handleAuxClick = (e: MouseEvent) => {@@ -1176,6 +1305,7 @@ export function useCanvasNavigation({isShiftDown,isCtrlDown,isAltDown,+ heldModifierAction: activeHeldModifierAction,isRotateModifier,isPanning,isRotating,diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex 4cbcd39..b18c64c 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -3,6 +3,7 @@ import { CanvasDimensions, LayerItem } from '../types/editor';import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';import { documentStore } from '../utils/documentStore';import { recoveryService } from '../services/recoveryService';+import { documentStoreActions } from '../stores';import { computeLayerSelection } from './layerManager/layerTreeOps';import { LayerManagerContext, UseLayerManagerProps } from './layerManager/types';import { useLayerCanvasRegistry } from './layerManager/useLayerCanvasRegistry';@@ -24,6 +25,7 @@ export {computeBatchReorderLayers,computeBatchVisibility,computeBatchLock,+ applyLayerTreeDelta,} from './layerManager/layerTreeOps';export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileGrid }: UseLayerManagerProps) {@@ -72,6 +74,10 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile// Track structural layer mutations and log to recovery service WAL (ignore pure thumbnailUrl refreshes)const isInitialLayerMount = useRef(true);const lastLoggedLayersSigRef = useRef<string>('');+ const lastDirtyStructRef = useRef<{ sessionId: string | null; sig: string }>({+ sessionId: null,+ sig: '',+ });useEffect(() => {if (isInitialLayerMount.current) {isInitialLayerMount.current = false;@@ -79,12 +85,28 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile}const sId = activeSessionId || recoveryService.getCurrentSessionId();if (sId && layers.length > 0) {- const sig = `${activeLayerId}|` + layers- .map((l) => `${l.id}:${l.name}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.locked ? 1 : 0}:${l.clipped ? 1 : 0}:${l.alphaLocked ? 1 : 0}:${l.parentId || ''}:${l.expressionColor || ''}:${l.toneEnabled ? 1 : 0}`)+ const structSig = layers+ .map(+ (l) =>+ `${l.id}:${l.name}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.locked ? 1 : 0}:${l.clipped ? 1 : 0}:${l.alphaLocked ? 1 : 0}:${l.parentId || ''}:${l.expressionColor || ''}:${l.toneEnabled ? 1 : 0}:${l.maskCanvas ? 1 : 0}:${l.maskEnabled === false ? 0 : 1}:${l.maskLinked === false ? 0 : 1}`+ ).join(';');++ if (activeSessionId) {+ if (lastDirtyStructRef.current.sessionId !== activeSessionId) {+ lastDirtyStructRef.current = { sessionId: activeSessionId, sig: structSig };+ } else if (lastDirtyStructRef.current.sig && lastDirtyStructRef.current.sig !== structSig) {+ lastDirtyStructRef.current = { sessionId: activeSessionId, sig: structSig };+ documentStoreActions.markDocumentDirty(activeSessionId, true);+ }+ }++ const sig = `${activeLayerId}|${structSig}`;if (sig === lastLoggedLayersSigRef.current) return;lastLoggedLayersSigRef.current = sig;recoveryService.logLayerMutation(sId, 'update', layers, activeLayerId);+ } else if (!activeSessionId) {+ lastDirtyStructRef.current = { sessionId: null, sig: '' };}}, [layers, activeSessionId, activeLayerId]);@@ -193,6 +215,8 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileduplicateLayer: crud.duplicateLayer,deleteLayer: crud.deleteLayer,copyLayer: clipboard.copyLayer,+ copySelectionToClipboard: clipboard.copySelectionToClipboard,+ createLayerFromTileSnapshot: clipboard.createLayerFromTileSnapshot,pasteLayer: clipboard.pasteLayer,pasteLayerFromCanvas: clipboard.pasteLayerFromCanvas,fillScreentoneSelection: clipboard.fillScreentoneSelection,@@ -233,6 +257,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileupsertBalloonLayer: specialLayers.upsertBalloonLayer,createFrameFolder: specialLayers.createFrameFolder,divideFrameFolder: specialLayers.divideFrameFolder,+ applyLayerTreeDelta: specialLayers.applyLayerTreeDelta,rasterizeLayer: specialLayers.rasterizeLayer,};}diff --git a/src/stores/index.ts b/src/stores/index.tsindex 6ad8147..fb16e26 100644--- a/src/stores/index.ts+++ b/src/stores/index.ts@@ -1,8 +1,12 @@export { createStore, shallowEqual } from './createStore';export type { StoreApi, UseBoundStore, StoreListener, StateUpdater, EqualityFn } from './createStore';-export { useToolStore, toolStoreActions } from './useToolStore';-export type { ToolStoreState, QuickModifiersState } from './useToolStore';+export { useToolStore, toolStoreActions, interactiveToolBridge } from './useToolStore';+export type {+ ToolStoreState,+ QuickModifiersState,+ InteractiveToolActionsBridge,+} from './useToolStore';export {useDocumentStore,@@ -12,12 +16,19 @@ export {} from './useDocumentStore';export type { DocumentStoreState } from './useDocumentStore';-export { useUiStore, uiStoreActions, selectIsAnyModalOpen } from './useUiStore';+export {+ useUiStore,+ uiStoreActions,+ selectIsAnyModalOpen,+ INITIAL_APP_CLOSE_PROMPT_STATE,+} from './useUiStore';export type {UiStoreState,TonalModalState,AdjustmentModalState,LayerStylesModalState,+ AppClosePromptStep,+ AppClosePromptState,} from './useUiStore';export { useWorkspaceStore, workspaceStoreActions } from './useWorkspaceStore';diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.tsindex bf92a2b..a943605 100644--- a/src/stores/useToolStore.ts+++ b/src/stores/useToolStore.ts@@ -11,8 +11,15 @@ import {VectorEditSettings,LiquifySettings,ShapeSettings,+ GradientSettings,+ GradientMeshState,+ RetouchSettings,+ PenToolSettings,+ Point2D,} from '../types/editor';import { DEFAULT_SHAPE_SETTINGS } from '../utils/shapeEngine';+import { DEFAULT_GRADIENT_SETTINGS } from '../utils/gradientEngine';+import { DEFAULT_RETOUCH_SETTINGS } from '../utils/retouchEngine';import {saveBrushSettingsDebounced,getEffectiveBrushSettings,@@ -51,6 +58,15 @@ export interface ToolStoreState {vectorEditSettings: VectorEditSettings;liquifySettings: LiquifySettings;shapeSettings: ShapeSettings;+ gradientSettings: GradientSettings;+ retouchSettings: RetouchSettings;+ penSettings: PenToolSettings;+ activeGradientMesh: GradientMeshState | null;+ isPickingCloneSource: boolean;+ cloneSourceAnchor: Point2D | null;+ activePenPointCount: number;+ activePenClosed: boolean;+ activePenSelectedAnchor: number | null;}const DEFAULT_RECENT_COLORS = [@@ -119,6 +135,66 @@ function loadInitialShapeSettings(): ShapeSettings {return { ...DEFAULT_SHAPE_SETTINGS };}+const DEFAULT_PEN_SETTINGS: PenToolSettings = {+ mode: 'draw',+ strokeWidth: 4,+ opacity: 1,+ strokeEnabled: true,+ fillEnabled: false,+ fillColorMode: 'secondary',+ customFillColor: '#ffffff',+ rubberBandPreview: true,+};++function loadInitialGradientSettings(): GradientSettings {+ try {+ if (typeof localStorage !== 'undefined') {+ const saved = localStorage.getItem('ink_studio_gradient_settings');+ if (saved) {+ const parsed = JSON.parse(saved) as Partial<GradientSettings>;+ return {+ ...DEFAULT_GRADIENT_SETTINGS,+ ...parsed,+ stops:+ Array.isArray(parsed.stops) && parsed.stops.length >= 2+ ? parsed.stops+ : DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),+ };+ }+ }+ } catch {+ // Ignore storage errors+ }+ return {+ ...DEFAULT_GRADIENT_SETTINGS,+ stops: DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),+ };+}++function loadInitialRetouchSettings(): RetouchSettings {+ try {+ if (typeof localStorage !== 'undefined') {+ const saved = localStorage.getItem('ink_studio_retouch_settings');+ if (saved) return { ...DEFAULT_RETOUCH_SETTINGS, ...(JSON.parse(saved) as Partial<RetouchSettings>) };+ }+ } catch {+ // Ignore storage errors+ }+ return { ...DEFAULT_RETOUCH_SETTINGS };+}++function loadInitialPenSettings(): PenToolSettings {+ try {+ if (typeof localStorage !== 'undefined') {+ const saved = localStorage.getItem('ink_studio_pen_settings');+ if (saved) return { ...DEFAULT_PEN_SETTINGS, ...(JSON.parse(saved) as Partial<PenToolSettings>) };+ }+ } catch {+ // Ignore storage errors+ }+ return { ...DEFAULT_PEN_SETTINGS };+}+const createInitialToolState = (): ToolStoreState => {const { presetId, brushSettings } = createInitialBrushSettings();return {@@ -188,6 +264,15 @@ const createInitialToolState = (): ToolStoreState => {},liquifySettings: loadInitialLiquifySettings(),shapeSettings: loadInitialShapeSettings(),+ gradientSettings: loadInitialGradientSettings(),+ retouchSettings: loadInitialRetouchSettings(),+ penSettings: loadInitialPenSettings(),+ activeGradientMesh: null,+ isPickingCloneSource: false,+ cloneSourceAnchor: null,+ activePenPointCount: 0,+ activePenClosed: false,+ activePenSelectedAnchor: null,};};@@ -540,4 +625,86 @@ export const toolStoreActions = {return { shapeSettings: next };});},++ updateGradientSettings(patch: Partial<GradientSettings>): void {+ useToolStore.setState((prev) => {+ const next = { ...prev.gradientSettings, ...patch };+ safeLocalStorageSetItem('ink_studio_gradient_settings', JSON.stringify(next), 'gradient settings');+ return { gradientSettings: next };+ });+ },++ updateRetouchSettings(patch: Partial<RetouchSettings>): void {+ useToolStore.setState((prev) => {+ const next = { ...prev.retouchSettings, ...patch };+ safeLocalStorageSetItem('ink_studio_retouch_settings', JSON.stringify(next), 'retouch settings');+ return { retouchSettings: next };+ });+ },++ updatePenSettings(patch: Partial<PenToolSettings>): void {+ useToolStore.setState((prev) => {+ const next = { ...prev.penSettings, ...patch };+ safeLocalStorageSetItem('ink_studio_pen_settings', JSON.stringify(next), 'pen settings');+ return { penSettings: next };+ });+ },++ setActiveGradientMesh(+ updater:+ | GradientMeshState+ | null+ | ((prev: GradientMeshState | null) => GradientMeshState | null)+ ): void {+ useToolStore.setState((prev) => ({+ activeGradientMesh:+ typeof updater === 'function' ? updater(prev.activeGradientMesh) : updater,+ }));+ },++ updateActiveGradientMeshNode(index: number, patch: { color?: string; opacity?: number }): void {+ useToolStore.setState((prev) => {+ const mesh = prev.activeGradientMesh;+ if (!mesh || index < 0 || index >= mesh.nodes.length) return prev;+ return {+ activeGradientMesh: {+ ...mesh,+ nodes: mesh.nodes.map((n, i) => (i === index ? { ...n, ...patch } : n)),+ },+ };+ });+ },++ setIsPickingCloneSource(picking: boolean): void {+ useToolStore.setState({ isPickingCloneSource: picking });+ },++ setCloneSourceAnchor(anchor: Point2D | null): void {+ useToolStore.setState({ cloneSourceAnchor: anchor });+ },++ setActivePenSessionMeta(+ pointCount: number,+ closed: boolean,+ selectedAnchor: number | null+ ): void {+ useToolStore.setState({+ activePenPointCount: pointCount,+ activePenClosed: closed,+ activePenSelectedAnchor: selectedAnchor,+ });+ },};++export interface InteractiveToolActionsBridge {+ initGradientMesh?: () => void;+ applyGradientMesh?: () => void;+ cancelGradientMesh?: () => void;+ commitPenPath?: () => void;+ cancelPenPath?: () => void;+ toggleClosePenPath?: () => void;+ deleteSelectedPenAnchor?: () => void;+ toggleSelectedPenAnchorSmooth?: () => void;+}++export const interactiveToolBridge: InteractiveToolActionsBridge = {};diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.tsindex 68bf146..fc2310b 100644--- a/src/stores/useUiStore.ts+++ b/src/stores/useUiStore.ts@@ -27,6 +27,24 @@ export interface LayerStylesModalState {layerId?: string;}+export type AppClosePromptStep = 'confirm-quit' | 'summary' | 'per-canvas';++export interface AppClosePromptState {+ isOpen: boolean;+ step: AppClosePromptStep;+ pendingDocIds: string[];+ currentIndex: number;+ isBusy: boolean;+}++export const INITIAL_APP_CLOSE_PROMPT_STATE: AppClosePromptState = {+ isOpen: false,+ step: 'confirm-quit',+ pendingDocIds: [],+ currentIndex: 0,+ isBusy: false,+};+export interface UiStoreState {appView: 'home' | 'workspace';leftPanelWidth: number;@@ -47,11 +65,13 @@ export interface UiStoreState {isMangaEffectsModalOpen: boolean;isWebtoonExportModalOpen: boolean;isTimelapseExportModalOpen: boolean;+ isBrushStudioModalOpen: boolean;isRecoveryModalOpen: boolean;crashedSessions: CrashedSessionInfo[];tonalModalState: TonalModalState;adjustmentModalState: AdjustmentModalState;layerStylesModalState: LayerStylesModalState;+ appClosePrompt: AppClosePromptState;// Transient feedbackisLoadingFile: boolean;@@ -103,11 +123,13 @@ const createInitialUiState = (): UiStoreState => ({isMangaEffectsModalOpen: false,isWebtoonExportModalOpen: false,isTimelapseExportModalOpen: false,+ isBrushStudioModalOpen: false,isRecoveryModalOpen: false,crashedSessions: [],tonalModalState: { ...DEFAULT_TONAL_MODAL_STATE },adjustmentModalState: { isOpen: false },layerStylesModalState: { isOpen: false },+ appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE },isLoadingFile: false,loadingStatus: '',@@ -211,6 +233,10 @@ export const uiStoreActions = {useUiStore.setState({ isTimelapseExportModalOpen: open });},+ setBrushStudioModalOpen(open: boolean): void {+ useUiStore.setState({ isBrushStudioModalOpen: open });+ },+setRecoveryModal(open: boolean, sessions?: CrashedSessionInfo[]): void {useUiStore.setState((prev) => ({isRecoveryModalOpen: open,@@ -242,6 +268,18 @@ export const uiStoreActions = {useUiStore.setState({ layerStylesModalState });},+ setAppClosePrompt(+ updater: AppClosePromptState | ((prev: AppClosePromptState) => AppClosePromptState)+ ): void {+ useUiStore.setState((prev) => ({+ appClosePrompt: typeof updater === 'function' ? updater(prev.appClosePrompt) : updater,+ }));+ },++ resetAppClosePrompt(): void {+ useUiStore.setState({ appClosePrompt: { ...INITIAL_APP_CLOSE_PROMPT_STATE } });+ },+setLoading(isLoadingFile: boolean, loadingStatus = ''): void {useUiStore.setState({ isLoadingFile, loadingStatus });},@@ -284,6 +322,7 @@ export function selectIsAnyModalOpen(state.tonalModalState.isOpen ||state.adjustmentModalState.isOpen ||state.layerStylesModalState.isOpen ||+ state.appClosePrompt.isOpen ||isHostModalOpen ||isUpdateModalOpen);diff --git a/src/types/editor.ts b/src/types/editor.tsindex 53a45dc..8b4c3d7 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -8,6 +8,22 @@ export type {ShapeSettings,ShapeDragPreview,} from '../utils/shapeEngine';+export type {+ GradientType,+ GradientRepeatMode,+ GradientBlendMode,+ GradientToolStop,+ GradientMeshNode,+ GradientMeshState,+ GradientSettings,+ GradientDragPreview,+} from '../utils/gradientEngine';+export type {+ RetouchMode,+ RetouchTonalRange,+ CloneSampleMode,+ RetouchSettings,+} from '../utils/retouchEngine';export type ToolType =| 'brush'@@ -20,7 +36,10 @@ export type ToolType =| 'select-pen'| 'select-eraser'| 'fill'+ | 'gradient'+ | 'retouch'| 'shape'+ | 'pen'| 'text'| 'frame'| 'balloon'@@ -40,7 +59,106 @@ export interface Point {isCorner?: boolean;}-export type BrushCategory = 'pen' | 'sketch' | 'brush';+export type BrushCategory = 'pen' | 'sketch' | 'brush' | 'natural-paint';++export type BrushRenderMode = 'stamp' | 'bristle-ribbon' | 'bristle-hybrid';++export type GrainMappingMode =+ | 'canvas-locked'+ | 'brush-aligned'+ | 'stroke-flow'+ | 'random-per-stroke';++export type SurfaceTextureId =+ | 'linen-canvas'+ | 'coarse-burlap'+ | 'fine-cotton'+ | 'cold-press-watercolor'+ | 'rough-pastel'+ | 'gesso-board'+ | 'stipple-grain';++export type BristleProfilePreset =+ | 'round'+ | 'flat'+ | 'filbert'+ | 'fan'+ | 'rake'+ | 'knife'+ | 'custom';++export type NaturalMixingMode = 'blend' | 'running_color' | 'smear' | 'impasto_mix';++export interface BristleSettings {+ profile: BristleProfilePreset;+ count: number; // 4 to 64 independent strands/tufts across brush width+ clumping: number; // 0.0 to 1.0 (groups bristles into natural paint tufts)+ stiffness: number; // 0.0 to 1.0 (flexibility / bend resistance)+ length: number; // 0.2 to 2.0 (relative strand length)+ splay: number; // 0.0 to 1.0 (width spread under pressure / tilt)+ irregularity: number; // 0.0 to 1.0 (strand length, density & spacing variation)+ edgeRidge?: number; // 0.0 to 1.0 (paint ridge buildup along brush edges / palette knife)+}++export const DEFAULT_BRISTLE_SETTINGS: BristleSettings = {+ profile: 'filbert',+ count: 28,+ clumping: 0.35,+ stiffness: 0.6,+ length: 1.0,+ splay: 0.3,+ irregularity: 0.35,+ edgeRidge: 0.2,+};++export interface NaturalPaintSettings {+ enabled: boolean;+ spatialMixing: boolean; // Per-bristle across-width pigment pickup+ pigmentMixingStrength: number; // 0.0 to 1.0 (Kubelka-Munk subtractive strength)+ paintLoad: number; // 0.0 (pure blender) to 1.0 (fully loaded brush)+ depletionRate: number; // 0.0 (infinite) to 1.0 (rapid dry-brush exhaustion)+ wetness: number; // 0.0 to 1.0 (underlying canvas pickup strength)+ viscosity: number; // 0.0 to 1.0 (mixing resistance / thick oil body)+ autoClean: boolean; // true = clean reload on pointer-up; false = dirty brush persists across strokes+ chargePerPressure: number; // 0.0 to 1.0 (heavy pressure squeezes more paint from ferrule)+ dryBrush: number; // 0.0 to 1.0 (canvas valley-skipping sensitivity)+ granulation?: number; // 0.0 to 1.0 (watercolor pigment settling into paper valleys)+ penetrationCurve?: [number, number][]; // Pressure-to-canvas-valley penetration curve+}++export const DEFAULT_NATURAL_PAINT_SETTINGS: NaturalPaintSettings = {+ enabled: false,+ spatialMixing: false,+ pigmentMixingStrength: 0.85,+ paintLoad: 0.85,+ depletionRate: 0.25,+ wetness: 0.5,+ viscosity: 0.5,+ autoClean: true,+ chargePerPressure: 0.45,+ dryBrush: 0.3,+ granulation: 0,+};++export interface ImpastoSettings {+ enabled: boolean;+ depth: number; // 0.0 to 1.0 (overall paint relief thickness)+ bristleRelief: number; // 0.0 to 1.0 (individual bristle groove depth)+ gloss: number; // 0.0 (matte gouache) to 1.0 (glossy wet oil)+ reliefContrast: number; // 0.0 to 1.0 (diffuse lighting & AO contrast)+ lightAzimuth: number; // 0 to 360 degrees+ lightElevation: number; // 5 to 85 degrees+}++export const DEFAULT_IMPASTO_SETTINGS: ImpastoSettings = {+ enabled: false,+ depth: 0.55,+ bristleRelief: 0.6,+ gloss: 0.45,+ reliefContrast: 0.55,+ lightAzimuth: 225,+ lightElevation: 34,+};export type BrushPresetId =// Pen section@@ -63,6 +181,16 @@ export type BrushPresetId =| 'blend-chalk-brush'| 'soft-round'| 'noise-shader'+ // Natural Paint section+ | 'impasto-bristle-oil'+ | 'wet-mixing-filbert'+ | 'dry-bristle-rake'+ | 'heavy-body-acrylic'+ | 'palette-knife-impasto'+ | 'velvet-gouache'+ | 'granulating-watercolor'+ | 'oil-bristle-blender'+ | 'pastel-stick-canvas'| string;export interface CspEffectorCurvePoint {@@ -98,6 +226,7 @@ export interface CspTaperSettings {affectSize?: boolean; // Taper modulates brush size (default true)affectDensity?: boolean; // Taper modulates brush densityaffectOpacity?: boolean; // Taper modulates dab opacity+ affectLoad?: boolean; // Taper modulates Natural Paint load / dry-brush fade}export type CspAntiAliasLevel = 0 | 1 | 2 | 3; // 0: None (Binary), 1: Weak, 2: Medium, 3: Strong@@ -127,9 +256,15 @@ export interface CspSensorConfig {pressureCurve?: [number, number][];useTilt?: boolean;tiltMin?: number; // 0.0 to 1.0+ useTiltAzimuth?: boolean;+ useBarrelTwist?: boolean;+ twistMin?: number; // 0.0 to 1.0useVelocity?: boolean;velocityMin?: number; // 0.0 to 1.0invertVelocity?: boolean;+ useDistance?: boolean;+ distanceMin?: number; // 0.0 to 1.0+ distanceMaxPx?: number; // Arc-length distance over which sensor ramps (default 600)useRandom?: boolean;randomMin?: number; // 0.0 to 1.0}@@ -147,6 +282,7 @@ export interface BrushDynamics {hueJitter: number; // 0.0 to 1.0saturationJitter: number; // 0.0 to 1.0brightnessJitter: number; // 0.0 to 1.0+ temperatureJitter?: number; // 0.0 to 1.0 (warm-cool pigment shift)foregroundBackgroundJitter: number; // 0.0 to 1.0 (mix with secondary color)}@@ -162,12 +298,14 @@ export const DEFAULT_BRUSH_DYNAMICS: BrushDynamics = {hueJitter: 0,saturationJitter: 0,brightnessJitter: 0,+ temperatureJitter: 0,foregroundBackgroundJitter: 0,};export interface CspBrush {id: string; // Unique ID, e.g. "csp-1727256000000-xyz"name: string; // Brush display name, e.g. "G-Pen"+ category?: BrushCategory | 'custom';badge?: string; // Badge text, e.g. "CSP"desc?: string; // Short descriptiontipDataUrl?: string; // Base64 PNG data URL of the primary brush tip@@ -210,18 +348,25 @@ export interface CspBrush {sizeSensor?: CspSensorConfig;opacitySensor?: CspSensorConfig;densitySensor?: CspSensorConfig;+ bristleSplaySensor?: CspSensorConfig;+ paintLoadSensor?: CspSensorConfig;+ grainPenetrationSensor?: CspSensorConfig;+ angleSensor?: CspSensorConfig;+ scatterSensor?: CspSensorConfig;// Advanced CSP Mathematics ParameterscolorMixing?: boolean; // Enable CSP pigment mixingperceptualMixing?: boolean; // OKLab / Kubelka-Munk perceptual pigment mixing (default true)amountOfPaint?: number; // 0.0 to 1.0 (CSP: Amount of Paint)densityOfPaint?: number; // 0.0 to 1.0 (CSP: Density of Paint)colorStretch?: number; // 0.0 to 1.0 (CSP: Color Stretch along stroke length)- mixingMode?: 'blend' | 'running_color' | 'smear'; // CSP Mixing mode+ mixingMode?: NaturalMixingMode; // CSP / Natural Paint mixing modewetEdge?: number; // 0.0 to 1.0 (CSP: Watercolor Wet / Water Edge)wetEdgeRadius?: number;wetEdgeAlphaPower?: number;wetEdgeValuePower?: number;paperTexture?: string; // Paper grain texture data URL+ surfaceTextureId?: SurfaceTextureId; // Built-in 512x512 seamless surface texture ID+ grainMappingMode?: GrainMappingMode; // Spatial grain mapping modetextureDensity?: number; // 0.0 to 1.0 (CSP: Texture / Paper Grain intensity)paperTextureMode?: CspPaperTextureMode;paperTextureBrightness?: number; // -100 to 100@@ -234,6 +379,11 @@ export interface CspBrush {dualBrushCompositeMode?: string;dualSize?: number;dualSpacing?: number;+ dualScatter?: number;+ dualAngle?: number;+ dualScale?: number;+ dualSurfaceTextureId?: SurfaceTextureId;+ dualGrainDepth?: number;spray?: CspSpraySettings;taper?: CspTaperSettings;isRibbon?: boolean;@@ -241,6 +391,11 @@ export interface CspBrush {pressureCurveGamma?: number; // CSP Pressure response curve gammavelocityDynamics?: boolean; // Velocity-based taperdynamics?: BrushDynamics; // Multi-axis jitter matrix+ // Natural Paint Engine (v2)+ renderMode?: BrushRenderMode;+ bristle?: BristleSettings;+ naturalPaint?: NaturalPaintSettings;+ impasto?: ImpastoSettings;importedAt: number;}@@ -276,6 +431,11 @@ export interface BrushSettings {sizeSensor?: CspSensorConfig;opacitySensor?: CspSensorConfig;densitySensor?: CspSensorConfig;+ bristleSplaySensor?: CspSensorConfig;+ paintLoadSensor?: CspSensorConfig;+ grainPenetrationSensor?: CspSensorConfig;+ angleSensor?: CspSensorConfig;+ scatterSensor?: CspSensorConfig;// Custom / CSP brush tip propertiescustomTipDataUrl?: string;customTipImage?: HTMLImageElement;@@ -298,13 +458,15 @@ export interface BrushSettings {amountOfPaint?: number; // 0.0 to 1.0 (default 0.7)densityOfPaint?: number; // 0.0 to 1.0 (default 0.8)colorStretch?: number; // 0.0 to 1.0 (default 0.6)- mixingMode?: 'blend' | 'running_color' | 'smear'; // 'blend', 'running_color', or 'smear'+ mixingMode?: NaturalMixingMode; // 'blend', 'running_color', 'smear', or 'impasto_mix'wetEdge?: number; // 0.0 to 1.0 (CSP Water Edge rim density)wetEdgeRadius?: number;wetEdgeAlphaPower?: number;wetEdgeValuePower?: number;paperTexture?: string; // Optional paper texture data URLpaperTextureImage?: HTMLImageElement; // Preloaded paper grain image+ surfaceTextureId?: SurfaceTextureId; // Built-in 512x512 seamless surface texture ID+ grainMappingMode?: GrainMappingMode; // Spatial grain mapping modetextureDensity?: number; // 0.0 to 1.0 (paper grain tooth)paperTextureMode?: CspPaperTextureMode;paperTextureBrightness?: number;@@ -317,6 +479,11 @@ export interface BrushSettings {dualBrushCompositeMode?: 'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen' | string;dualSize?: number;dualSpacing?: number;+ dualScatter?: number;+ dualAngle?: number;+ dualScale?: number;+ dualSurfaceTextureId?: SurfaceTextureId;+ dualGrainDepth?: number;dualTipDataUrl?: string;dualTipImage?: HTMLImageElement;pressureCurveGamma?: number; // 0.4 (soft) to 2.5 (hard) response curve@@ -324,6 +491,11 @@ export interface BrushSettings {useGpu?: boolean; // Run brush mathematics on GPU video card by defaultisTransparentInk?: boolean; // Transparent Ink mode (CSP 'C' key toggle)dynamics?: BrushDynamics; // Multi-axis jitter matrix+ // Natural Paint Engine (v2)+ renderMode?: BrushRenderMode;+ bristle?: BristleSettings;+ naturalPaint?: NaturalPaintSettings;+ impasto?: ImpastoSettings;}export interface OnionSkinSettings {@@ -387,6 +559,9 @@ export type HistoryActionType =| 'expression-color'| 'layer-convert'| 'liquify'+ | 'gradient'+ | 'retouch'+ | 'pen'| 'filter'| 'auto-action';@@ -615,6 +790,8 @@ export interface DirtyRect {height: number;}+export type BezierHandleType = 'corner' | 'smooth' | 'symmetric';+export interface VectorKnot {x: number;y: number;@@ -622,12 +799,18 @@ export interface VectorKnot {width: number;angle?: number;timestamp: number;+ handleIn?: Point2D | null;+ handleOut?: Point2D | null;+ handleType?: BezierHandleType;}export interface VectorStroke {id: string;layerId: string;- tool: 'brush' | 'pencil' | 'eraser';+ tool: 'brush' | 'pencil' | 'eraser' | 'pen';+ curveType?: 'catmull-rom' | 'bezier';+ closed?: boolean;+ fillColor?: string | null;knots: VectorKnot[];color: string;baseWidth: number;@@ -636,6 +819,27 @@ export interface VectorStroke {deleted?: boolean;}+export type PenToolMode = 'draw' | 'edit';++export interface PenToolSettings {+ mode: PenToolMode;+ strokeWidth: number;+ opacity: number;+ strokeEnabled: boolean;+ fillEnabled: boolean;+ fillColorMode: 'primary' | 'secondary' | 'custom';+ customFillColor: string;+ rubberBandPreview: boolean;+}++export interface PenPathSession {+ editingStrokeId: string | null;+ knots: VectorKnot[];+ closed: boolean;+ selectedAnchorIndex: number | null;+ hoverPoint: Point2D | null;+}+export interface ComicFrame {id: string;layerId: string;@@ -656,6 +860,21 @@ export interface TileDelta {afterData?: Uint8Array | null;}+export interface LayerTreeDeltaUpdate {+ layerId: string;+ beforeComicFrames?: ComicFrame[];+ afterComicFrames?: ComicFrame[];+}++export interface LayerTreeDelta {+ addedLayers?: LayerItem[];+ insertBeforeLayerId?: string | null;+ insertIndex?: number;+ updatedLayers?: LayerTreeDeltaUpdate[];+ beforeActiveLayerId?: string;+ afterActiveLayerId?: string;+}+export interface HistoryItem extends HistoryItemMeta {imageData?: ImageData;beforeImageData?: ImageData | null;@@ -668,6 +887,7 @@ export interface HistoryItem extends HistoryItemMeta {before: VectorStroke[];after: VectorStroke[];};+ layerTreeDelta?: LayerTreeDelta;peerId?: string | number;strokeId?: string;isMaskEdit?: boolean;diff --git a/src/utils/__tests__/appCloseFlow.test.tsx b/src/utils/__tests__/appCloseFlow.test.tsxnew file mode 100644index 0000000..10fb994--- /dev/null+++ b/src/utils/__tests__/appCloseFlow.test.tsx@@ -0,0 +1,505 @@+import { act } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { DocumentTab } from '../../types/editor';+import {+ documentStoreActions,+ selectIsAnyModalOpen,+ uiStoreActions,+ useDocumentStore,+ useUiStore,+} from '../../stores';+import {+ _resetAppCloseFlowForTests,+ cancelAppClose,+ computeInitialClosePromptState,+ finalizeAppClose,+ findNextPendingDirtyIndex,+ formatCanvasDisplayName,+ getUnsavedDocumentIds,+ isFinalizingAppClose,+ requestAppClose,+ SaveDocumentResult,+} from '../appCloseFlow';+import { CloseConfirmModal } from '../../components/CloseConfirmModal';++interface MiniNode {+ nodeType: number;+ nodeName: string;+ parentNode: MiniElement | null;+ ownerDocument: MiniDocument;+}++class MiniTextNode implements MiniNode {+ public nodeType = 3;+ public nodeName = '#text';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniCommentNode implements MiniNode {+ public nodeType = 8;+ public nodeName = '#comment';+ public nodeValue: string;+ public parentNode: MiniElement | null = null;+ public ownerDocument: MiniDocument;++ constructor(text: string, ownerDocument: MiniDocument) {+ this.nodeValue = text;+ this.ownerDocument = ownerDocument;+ }+}++class MiniElement extends EventTarget implements MiniNode {+ public nodeType = 1;+ public nodeName: string;+ public tagName: string;+ public namespaceURI = 'http://www.w3.org/1999/xhtml';+ public ownerDocument: MiniDocument;+ public parentNode: MiniElement | null = null;+ public childNodes: MiniNode[] = [];+ public style: Record<string, string> = {};+ public disabled = false;+ public className = '';+ public isContentEditable = false;+ private attrs = new Map<string, string>();++ constructor(tag: string, ownerDocument: MiniDocument) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = tag.toUpperCase();+ this.ownerDocument = ownerDocument;+ }++ get firstChild(): MiniNode | null {+ return this.childNodes[0] ?? null;+ }++ get textContent(): string {+ return this.childNodes+ .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))+ .join('');+ }++ set textContent(val: string) {+ this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];+ }++ appendChild<T extends MiniNode>(child: T): T {+ if (child.parentNode) child.parentNode.removeChild(child);+ child.parentNode = this;+ this.childNodes.push(child);+ return child;+ }++ removeChild<T extends MiniNode>(child: T): T {+ const idx = this.childNodes.indexOf(child);+ if (idx >= 0) {+ this.childNodes.splice(idx, 1);+ child.parentNode = null;+ }+ return child;+ }++ insertBefore<T extends MiniNode>(newNode: T, refNode: MiniNode | null): T {+ if (newNode.parentNode) newNode.parentNode.removeChild(newNode);+ newNode.parentNode = this;+ if (!refNode) {+ this.childNodes.push(newNode);+ return newNode;+ }+ const idx = this.childNodes.indexOf(refNode);+ if (idx < 0) this.childNodes.push(newNode);+ else this.childNodes.splice(idx, 0, newNode);+ return newNode;+ }++ setAttribute(k: string, v: string) {+ this.attrs.set(k, String(v));+ }+ getAttribute(k: string): string | null {+ return this.attrs.get(k) ?? null;+ }+ removeAttribute(k: string) {+ this.attrs.delete(k);+ }+ hasAttribute(k: string): boolean {+ return this.attrs.has(k);+ }+ focus() {}+ blur() {}+}++class MiniDocument extends EventTarget {+ public nodeType = 9;+ public nodeName = '#document';+ public defaultView: any;+ public body: MiniElement;+ public documentElement: MiniElement;+ public activeElement: MiniElement | null = null;++ constructor(win: any) {+ super();+ this.defaultView = win;+ this.documentElement = new MiniElement('html', this);+ this.body = new MiniElement('body', this);+ this.documentElement.appendChild(this.body);+ }++ createElement(tag: string) {+ return new MiniElement(tag, this);+ }+ createElementNS(_ns: string, tag: string) {+ return new MiniElement(tag, this);+ }+ createTextNode(text: string) {+ return new MiniTextNode(text, this);+ }+ createComment(text: string) {+ return new MiniCommentNode(text, this);+ }+}++function findButtons(root: MiniElement): MiniElement[] {+ const out: MiniElement[] = [];+ const walk = (node: MiniNode) => {+ if (node instanceof MiniElement) {+ if (node.tagName === 'BUTTON') out.push(node);+ for (const child of node.childNodes) walk(child);+ }+ };+ walk(root);+ return out;+}++function clickButtonByText(root: MiniElement, label: string): void {+ const btn = findButtons(root).find((b) => b.textContent.trim() === label);+ if (!btn) {+ const labels = findButtons(root).map((b) => b.textContent.trim());+ throw new Error(`Button "${label}" not found. Available: ${labels.join(', ')}`);+ }+ const ev = new Event('click', { bubbles: true, cancelable: true });+ // Bubble manually up the MiniElement parent chain so React 19 root listener receives it+ Object.defineProperty(ev, 'target', { value: btn, enumerable: true });+ let cur: any = btn;+ while (cur) {+ cur.dispatchEvent(ev);+ cur = cur.parentNode;+ }+}++function makeDoc(id: string, name: string, isDirty: boolean): DocumentTab {+ return {+ id,+ name,+ isDirty,+ dimensions: { width: 800, height: 600, dpi: 300 },+ colorMode: 'color',+ layers: [],+ activeLayerId: '',+ };+}++describe('App Close Confirmation & Multi-Canvas Save Flow', () => {+ let prevWindow: any;+ let prevDocument: any;+ let prevActEnv: any;+ let miniWin: EventTarget & Record<string, any>;+ let miniDoc: MiniDocument;+ let container: MiniElement;+ let root: Root | null = null;++ beforeEach(() => {+ prevWindow = (globalThis as any).window;+ prevDocument = (globalThis as any).document;+ prevActEnv = (globalThis as any).IS_REACT_ACT_ENVIRONMENT;++ miniWin = Object.assign(new EventTarget(), {+ close: vi.fn(),+ HTMLElement: MiniElement,+ HTMLIFrameElement: class HTMLIFrameElement {},+ Element: MiniElement,+ Node: MiniElement,+ });+ miniDoc = new MiniDocument(miniWin);+ miniWin.document = miniDoc;+ (globalThis as any).window = miniWin;+ (globalThis as any).document = miniDoc;+ (globalThis as any).HTMLElement = MiniElement;+ (globalThis as any).HTMLIFrameElement = miniWin.HTMLIFrameElement;+ (globalThis as any).Element = MiniElement;+ (globalThis as any).Node = MiniElement;+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;++ container = miniDoc.createElement('div');+ miniDoc.body.appendChild(container);++ _resetAppCloseFlowForTests();+ useDocumentStore.reset();+ useUiStore.reset();+ });++ afterEach(async () => {+ if (root) {+ await act(async () => {+ root!.unmount();+ });+ root = null;+ }+ _resetAppCloseFlowForTests();+ useDocumentStore.reset();+ useUiStore.reset();+ (globalThis as any).window = prevWindow;+ (globalThis as any).document = prevDocument;+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = prevActEnv;+ });++ it('computes initial prompt step for 0, 1, and multiple unsaved canvases', () => {+ expect(computeInitialClosePromptState([])).toEqual({+ isOpen: true,+ step: 'confirm-quit',+ pendingDocIds: [],+ currentIndex: 0,+ isBusy: false,+ });++ expect(computeInitialClosePromptState(['doc-1'])).toEqual({+ isOpen: true,+ step: 'per-canvas',+ pendingDocIds: ['doc-1'],+ currentIndex: 0,+ isBusy: false,+ });++ expect(computeInitialClosePromptState(['doc-1', 'doc-2'])).toEqual({+ isOpen: true,+ step: 'summary',+ pendingDocIds: ['doc-1', 'doc-2'],+ currentIndex: 0,+ isBusy: false,+ });++ expect(formatCanvasDisplayName('Untitled*')).toBe('Untitled');+ expect(formatCanvasDisplayName('Comic 20261122')).toBe('Comic 20261122');+ expect(formatCanvasDisplayName('***')).toBe('Untitled');+ });++ it('extracts dirty IDs, finds next pending dirty index, and prevents duplicate close prompts', () => {+ const docs = [+ makeDoc('a', 'Clean', false),+ makeDoc('b', 'Dirty 1', true),+ makeDoc('c', 'Dirty 2', true),+ ];+ documentStoreActions.setDocuments(docs);++ expect(getUnsavedDocumentIds(docs)).toEqual(['b', 'c']);+ expect(findNextPendingDirtyIndex(['b', 'c'], 0, docs)).toBe(1);+ expect(findNextPendingDirtyIndex(['b', 'c'], 1, docs)).toBe(-1);++ expect(requestAppClose()).toBe(true);+ expect(useUiStore.getState().appClosePrompt.step).toBe('summary');+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(true);++ // Duplicate close request while modal is open is ignored+ expect(requestAppClose()).toBe(false);++ expect(cancelAppClose()).toBe(true);+ expect(useUiStore.getState().appClosePrompt.isOpen).toBe(false);+ });++ it('asks for quit confirmation even with 0 unsaved canvases and closes only when confirmed', async () => {+ documentStoreActions.setDocuments([makeDoc('clean-1', 'Saved.ink', false)]);+ const onSaveDocumentById = vi.fn(async (): Promise<SaveDocumentResult> => 'saved');+ const onFinalizeClose = vi.fn(async () => {+ uiStoreActions.resetAppClosePrompt();+ });++ await act(async () => {+ root = createRoot(container as unknown as Element);+ root.render(+ <CloseConfirmModal+ onSaveDocumentById={onSaveDocumentById}+ onFinalizeClose={onFinalizeClose}+ />+ );+ requestAppClose();+ });++ expect(container.textContent).toContain('Are you sure you want to close Ink Studio?');++ await act(async () => {+ clickButtonByText(container, 'Cancel');+ });+ expect(onFinalizeClose).not.toHaveBeenCalled();+ expect(useUiStore.getState().appClosePrompt.isOpen).toBe(false);++ await act(async () => {+ requestAppClose();+ });+ await act(async () => {+ clickButtonByText(container, 'Close');+ });+ expect(onFinalizeClose).toHaveBeenCalledTimes(1);+ expect(onSaveDocumentById).not.toHaveBeenCalled();+ });++ it('prompts directly for 1 unsaved canvas and keeps modal open if OS Save picker is canceled', async () => {+ documentStoreActions.setDocuments([makeDoc('d1', 'Comic 20261122*', true)]);+ const saveResults: SaveDocumentResult[] = ['canceled', 'saved'];+ const onSaveDocumentById = vi.fn(async (id: string): Promise<SaveDocumentResult> => {+ const next = saveResults.shift() ?? 'saved';+ if (next === 'saved') {+ documentStoreActions.markDocumentDirty(id, false);+ }+ return next;+ });+ const onFinalizeClose = vi.fn(async () => {+ uiStoreActions.resetAppClosePrompt();+ });++ await act(async () => {+ root = createRoot(container as unknown as Element);+ root.render(+ <CloseConfirmModal+ onSaveDocumentById={onSaveDocumentById}+ onFinalizeClose={onFinalizeClose}+ />+ );+ requestAppClose();+ });++ expect(container.textContent).toContain('Comic 20261122 has been changed. Do you want to save it?');++ // First Save click -> user cancels file picker -> must NOT close+ await act(async () => {+ clickButtonByText(container, 'Save');+ });+ expect(onSaveDocumentById).toHaveBeenCalledTimes(1);+ expect(onSaveDocumentById).toHaveBeenCalledWith('d1');+ expect(onFinalizeClose).not.toHaveBeenCalled();+ expect(useUiStore.getState().appClosePrompt.isOpen).toBe(true);+ expect(useUiStore.getState().appClosePrompt.isBusy).toBe(false);++ // Second Save click -> succeeds -> finalizes close+ await act(async () => {+ clickButtonByText(container, 'Save');+ });+ expect(onSaveDocumentById).toHaveBeenCalledTimes(2);+ expect(onFinalizeClose).toHaveBeenCalledTimes(1);+ });++ it('handles multiple unsaved canvases: summary -> Confirm changes -> per-canvas Save / Do Not Save -> close', async () => {+ documentStoreActions.setDocuments([+ makeDoc('d1', 'Page 01*', true),+ makeDoc('d-clean', 'Cover.ink', false),+ makeDoc('d2', 'Page 02*', true),+ ]);++ const onSaveDocumentById = vi.fn(async (id: string): Promise<SaveDocumentResult> => {+ documentStoreActions.markDocumentDirty(id, false);+ return 'saved';+ });+ const onFinalizeClose = vi.fn(async () => {+ uiStoreActions.resetAppClosePrompt();+ });++ await act(async () => {+ root = createRoot(container as unknown as Element);+ root.render(+ <CloseConfirmModal+ onSaveDocumentById={onSaveDocumentById}+ onFinalizeClose={onFinalizeClose}+ />+ );+ requestAppClose();+ });++ // Step 1: Summary prompt for 2 dirty canvases+ expect(container.textContent).toContain('There are 2 canvases with unsaved changes.');+ expect(container.textContent).toContain('Confirm changes...');+ expect(container.textContent).toContain('Discard changes');++ // Click "Confirm changes..." -> enters per-canvas prompt for Page 01 (1 / 2)+ await act(async () => {+ clickButtonByText(container, 'Confirm changes...');+ });+ expect(container.textContent).toContain('1 / 2');+ expect(container.textContent).toContain('Page 01 has been changed. Do you want to save it?');++ // Save Page 01 -> advances to Page 02 (2 / 2)+ await act(async () => {+ clickButtonByText(container, 'Save');+ });+ expect(onSaveDocumentById).toHaveBeenCalledWith('d1');+ expect(onFinalizeClose).not.toHaveBeenCalled();+ expect(container.textContent).toContain('2 / 2');+ expect(container.textContent).toContain('Page 02 has been changed. Do you want to save it?');++ // Skip saving Page 02 -> finalizes app close+ await act(async () => {+ clickButtonByText(container, 'Do Not Save');+ });+ expect(onSaveDocumentById).toHaveBeenCalledTimes(1);+ expect(onFinalizeClose).toHaveBeenCalledTimes(1);+ });++ it('closes immediately when user clicks Discard changes on multi-canvas summary', async () => {+ documentStoreActions.setDocuments([+ makeDoc('d1', 'Canvas A', true),+ makeDoc('d2', 'Canvas B', true),+ ]);+ const onSaveDocumentById = vi.fn(async (): Promise<SaveDocumentResult> => 'saved');+ const onFinalizeClose = vi.fn(async () => {+ uiStoreActions.resetAppClosePrompt();+ });++ await act(async () => {+ root = createRoot(container as unknown as Element);+ root.render(+ <CloseConfirmModal+ onSaveDocumentById={onSaveDocumentById}+ onFinalizeClose={onFinalizeClose}+ />+ );+ requestAppClose();+ });++ await act(async () => {+ clickButtonByText(container, 'Discard changes');+ });++ expect(onSaveDocumentById).not.toHaveBeenCalled();+ expect(onFinalizeClose).toHaveBeenCalledTimes(1);+ });++ it('finalizeAppClose flushes settings, closes all recovery sessions, and destroys Tauri window', async () => {+ documentStoreActions.setDocuments([+ makeDoc('doc-a', 'A', true),+ makeDoc('doc-b', 'B', false),+ ]);++ const flushBrushSettings = vi.fn();+ const closeRecoverySession = vi.fn(async () => {});+ const destroyTauriWindow = vi.fn(async () => {});++ await finalizeAppClose({+ isTauri: () => true,+ flushBrushSettings,+ closeRecoverySession,+ destroyTauriWindow,+ });++ expect(flushBrushSettings).toHaveBeenCalledTimes(1);+ expect(closeRecoverySession).toHaveBeenCalledTimes(2);+ expect(closeRecoverySession).toHaveBeenCalledWith('doc-a');+ expect(closeRecoverySession).toHaveBeenCalledWith('doc-b');+ expect(destroyTauriWindow).toHaveBeenCalledTimes(1);+ expect(isFinalizingAppClose()).toBe(true);+ });+});diff --git a/src/utils/__tests__/bezierEngine.test.ts b/src/utils/__tests__/bezierEngine.test.tsnew file mode 100644index 0000000..eaebf74--- /dev/null+++ b/src/utils/__tests__/bezierEngine.test.ts@@ -0,0 +1,204 @@+import { describe, it, expect } from 'vitest';+import {+ buildBezierSvgPath,+ computeBezierPathBounds,+ computeBezierSegmentBounds,+ evaluateCubicBezier,+ findClosestPointOnBezierPath,+ insertBezierAnchorAt,+ moveBezierAnchor,+ moveBezierHandle,+ splitCubicBezier,+ toggleBezierAnchorSmooth,+} from '../bezierEngine';+import { computeStrokeBounds, pinchVectorStroke, tessellateStroke } from '../vectorEngine';+import type { VectorKnot, VectorStroke } from '../../types/editor';++describe('True Cubic Bézier Pen Engine & VectorStroke Integration', () => {+ it('evaluates exact cubic Bézier points and derivatives', () => {+ const p0 = { x: 0, y: 0 };+ const c1 = { x: 0, y: 100 };+ const c2 = { x: 100, y: 100 };+ const p3 = { x: 100, y: 0 };++ const start = evaluateCubicBezier(p0, c1, c2, p3, 0);+ expect(start.x).toBeCloseTo(0);+ expect(start.y).toBeCloseTo(0);+ expect(start.dy).toBeCloseTo(300);++ // Exact midpoint for symmetric arch: y = 3/4 * 100 = 75+ const mid = evaluateCubicBezier(p0, c1, c2, p3, 0.5);+ expect(mid.x).toBeCloseTo(50);+ expect(mid.y).toBeCloseTo(75);+ expect(mid.dy).toBeCloseTo(0);+ });++ it('computes exact analytical bounding box extrema (not oversized control-handle box or undersized anchor box)', () => {+ const p0 = { x: 0, y: 0 };+ const c1 = { x: 0, y: 100 };+ const c2 = { x: 100, y: 100 };+ const p3 = { x: 100, y: 0 };++ const bounds = computeBezierSegmentBounds(p0, c1, c2, p3, 0);+ expect(bounds.minX).toBeCloseTo(0);+ expect(bounds.maxX).toBeCloseTo(100);+ expect(bounds.minY).toBeCloseTo(0);+ // Exact peak is 75, NOT 0 (anchors) and NOT 100 (control handles)+ expect(bounds.maxY).toBeCloseTo(75);+ });++ it('performs exact de Casteljau subdivision preserving curve geometry across split', () => {+ const p0 = { x: 10, y: 20 };+ const c1 = { x: 30, y: 150 };+ const c2 = { x: 160, y: -40 };+ const p3 = { x: 200, y: 90 };++ const tSplit = 0.35;+ const split = splitCubicBezier(p0, c1, c2, p3, tSplit);++ // Every sample along left half u in [0,1] must match original at u * tSplit+ for (const u of [0, 0.25, 0.5, 0.75, 1]) {+ const orig = evaluateCubicBezier(p0, c1, c2, p3, u * tSplit);+ const sub = evaluateCubicBezier(p0, split.leftC1, split.leftC2, split.mid, u);+ expect(sub.x).toBeCloseTo(orig.x, 5);+ expect(sub.y).toBeCloseTo(orig.y, 5);+ }++ // Every sample along right half u in [0,1] must match original at tSplit + u * (1 - tSplit)+ for (const u of [0, 0.25, 0.5, 0.75, 1]) {+ const orig = evaluateCubicBezier(p0, c1, c2, p3, tSplit + u * (1 - tSplit));+ const sub = evaluateCubicBezier(split.mid, split.rightC1, split.rightC2, p3, u);+ expect(sub.x).toBeCloseTo(orig.x, 5);+ expect(sub.y).toBeCloseTo(orig.y, 5);+ }+ });++ it('inserts an anchor onto a Bézier path without shifting the curve and locates closest curve points', () => {+ const knots: VectorKnot[] = [+ {+ x: 0,+ y: 0,+ pressure: 1,+ width: 4,+ timestamp: 0,+ handleIn: null,+ handleOut: { x: 0, y: 100 },+ handleType: 'corner',+ },+ {+ x: 100,+ y: 0,+ pressure: 1,+ width: 4,+ timestamp: 1,+ handleIn: { x: 100, y: 100 },+ handleOut: null,+ handleType: 'corner',+ },+ ];++ const hit = findClosestPointOnBezierPath(knots, { x: 50, y: 78 }, false);+ expect(hit).not.toBeNull();+ expect(hit!.segmentIndex).toBe(0);+ expect(hit!.t).toBeCloseTo(0.5, 2);+ expect(hit!.distance).toBeCloseTo(3, 1);++ const { knots: nextKnots, insertedIndex } = insertBezierAnchorAt(knots, 0, 0.5, false);+ expect(insertedIndex).toBe(1);+ expect(nextKnots).toHaveLength(3);+ expect(nextKnots[1].x).toBeCloseTo(50);+ expect(nextKnots[1].y).toBeCloseTo(75);+ expect(nextKnots[1].handleIn).not.toBeNull();+ expect(nextKnots[1].handleOut).not.toBeNull();+ });++ it('supports symmetric, smooth, and broken-corner handle dragging and anchor translation', () => {+ const knot: VectorKnot = {+ x: 50,+ y: 50,+ pressure: 1,+ width: 4,+ timestamp: 0,+ handleIn: { x: 30, y: 50 },+ handleOut: { x: 70, y: 50 },+ handleType: 'symmetric',+ };++ // Symmetric handle mirrors opposite side+ const sym = moveBezierHandle(knot, 'out', { x: 80, y: 70 }, false);+ expect(sym.handleIn?.x).toBeCloseTo(20);+ expect(sym.handleIn?.y).toBeCloseTo(30);++ // Alt break-symmetry leaves opposite handle untouched and converts to corner+ const broken = moveBezierHandle(knot, 'out', { x: 90, y: 90 }, true);+ expect(broken.handleType).toBe('corner');+ expect(broken.handleIn?.x).toBe(30);+ expect(broken.handleIn?.y).toBe(50);++ // Translating anchor shifts both handles by identical delta+ const moved = moveBezierAnchor(knot, { x: 60, y: 65 });+ expect(moved.handleIn).toEqual({ x: 40, y: 65 });+ expect(moved.handleOut).toEqual({ x: 80, y: 65 });++ // Toggling smooth/corner removes handles, toggling again restores auto-tangents+ const toggledCorner = toggleBezierAnchorSmooth([knot], 0, false);+ expect(toggledCorner[0].handleIn).toBeNull();+ expect(toggledCorner[0].handleOut).toBeNull();+ });++ it('integrates true Bézier strokes with VectorStroke bounds, tessellation, SVG path, and pinchVectorStroke', () => {+ const knots: VectorKnot[] = [+ {+ x: 0,+ y: 0,+ pressure: 1,+ width: 4,+ timestamp: 0,+ handleIn: null,+ handleOut: { x: 0, y: 100 },+ handleType: 'corner',+ },+ {+ x: 100,+ y: 0,+ pressure: 1,+ width: 4,+ timestamp: 1,+ handleIn: { x: 100, y: 100 },+ handleOut: null,+ handleType: 'corner',+ },+ ];++ const bounds = computeStrokeBounds(knots, false, 'bezier');+ expect(bounds.maxY).toBeCloseTo(77, 1); // 75 + halfWidth(2)++ const stroke: VectorStroke = {+ id: 'bezier-1',+ layerId: 'vec-1',+ tool: 'pen',+ curveType: 'bezier',+ closed: false,+ knots,+ color: '#000000',+ baseWidth: 4,+ opacity: 1,+ bounds,+ };++ const tess = tessellateStroke(stroke, 8);+ expect(tess.length).toBeGreaterThan(8);+ const maxY = Math.max(...tess.map((p) => p.y));+ expect(maxY).toBeGreaterThan(72);++ const svgD = buildBezierSvgPath(knots, false);+ expect(svgD).toBe('M 0 0 C 0 100, 100 100, 100 0');++ // Pinching knot translates its handleOut along with it+ const pinched = pinchVectorStroke(stroke, { x: 0, y: 0 }, 20, { x: 10, y: 5 });+ expect(pinched.knots[0].x).toBeCloseTo(10);+ expect(pinched.knots[0].handleOut?.x).toBeCloseTo(10);+ expect(pinched.knots[0].handleOut?.y).toBeCloseTo(105);+ expect(computeBezierPathBounds(pinched.knots, false).maxY).toBeGreaterThan(75);+ });+});diff --git a/src/utils/__tests__/brushEngine.test.ts b/src/utils/__tests__/brushEngine.test.tsindex 08986a6..1888f3e 100644--- a/src/utils/__tests__/brushEngine.test.ts+++ b/src/utils/__tests__/brushEngine.test.ts@@ -459,6 +459,37 @@ describe('Brush & Spline Engine (CSP / Photoshop Architectural Parity)', () => {// Dabs were deposited during bakeexpect(bakeCanvas.drawnDabs.length).toBeGreaterThan(10);});++ it('layers cleanly at amountOfPaint=1.0 and maintains step-size-invariant equilibrium in both blend and running_color modes', () => {+ const blueSample = { r: 10, g: 30, b: 220, a: 1.0 };++ // 1. At amountOfPaint=1.0, painting red over blue must stay pure red across 50 fine steps+ for (const mode of ['blend', 'running_color'] as const) {+ const res = new PaintReservoir('#ff0000');+ let last = res.mixWithCanvas(blueSample, 1.0, 0.95, 0.75, mode, 0.85, 1.0, 0, true);+ for (let i = 0; i < 50; i++) {+ last = res.mixWithCanvas(blueSample, 1.0, 0.95, 0.75, mode, 0.85, 1.0, 2.0, true);+ }+ expect(last.r).toBe(255);+ expect(last.g).toBe(0);+ expect(last.b).toBe(0);+ }++ // 2. Step-size invariance: 25 steps of 2px (50px) vs 5 steps of 10px (50px) converge tightly+ const fineRes = new PaintReservoir('#facc15');+ const coarseRes = new PaintReservoir('#facc15');+ for (let i = 0; i < 25; i++) {+ fineRes.mixWithCanvas(blueSample, 0.65, 0.9, 0.65, 'blend', 0.8, 1.0, 2.0, true);+ }+ for (let i = 0; i < 5; i++) {+ coarseRes.mixWithCanvas(blueSample, 0.65, 0.9, 0.65, 'blend', 0.8, 1.0, 10.0, true);+ }+ expect(Math.abs(fineRes.r - coarseRes.r)).toBeLessThan(12);+ expect(Math.abs(fineRes.g - coarseRes.g)).toBeLessThan(12);+ expect(Math.abs(fineRes.b - coarseRes.b)).toBeLessThan(12);+ // Must NOT collapse into underlying dark blue at amountOfPaint=0.65+ expect(fineRes.g).toBeGreaterThan(150);+ });});describe('Alpha Lock (Lock Transparent Pixels) & Transparent Ink Mode', () => {diff --git a/src/utils/__tests__/builtinBrushes.test.ts b/src/utils/__tests__/builtinBrushes.test.tsindex b802ebd..1bd38ae 100644--- a/src/utils/__tests__/builtinBrushes.test.ts+++ b/src/utils/__tests__/builtinBrushes.test.ts@@ -88,12 +88,18 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {};});- it('registers all 17 brushes cleanly across Pen (5), Sketch (5), and Brush (7) sections', () => {- expect(BUILTIN_BRUSH_SECTIONS.map((s) => s.id)).toEqual(['pen', 'sketch', 'brush']);+ it('registers all 26 brushes cleanly across Pen (5), Sketch (5), Brush (7), and Natural Paint (9) sections', () => {+ expect(BUILTIN_BRUSH_SECTIONS.map((s) => s.id)).toEqual([+ 'pen',+ 'sketch',+ 'brush',+ 'natural-paint',+ ]);const penIds = BUILTIN_BRUSHES.filter((b) => b.category === 'pen').map((b) => b.id);const sketchIds = BUILTIN_BRUSHES.filter((b) => b.category === 'sketch').map((b) => b.id);const brushIds = BUILTIN_BRUSHES.filter((b) => b.category === 'brush').map((b) => b.id);+ const naturalIds = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint').map((b) => b.id);expect(penIds).toEqual(['g-pen', 'real-g-pen', 'textured-pen', 'dot-pen', 'calligraphy']);expect(sketchIds).toEqual([@@ -112,6 +118,17 @@ describe('Pre-Installed Standard Brushes & Realistic Physics', () => {'soft-round','noise-shader',]);+ expect(naturalIds).toEqual([+ 'impasto-bristle-oil',+ 'wet-mixing-filbert',+ 'dry-bristle-rake',+ 'heavy-body-acrylic',+ 'palette-knife-impasto',+ 'velvet-gouache',+ 'granulating-watercolor',+ 'oil-bristle-blender',+ 'pastel-stick-canvas',+ ]);});it('generates deterministic non-empty procedural tip and paper PNG data URLs for every configured brush', () => {diff --git a/src/utils/__tests__/changelog.test.ts b/src/utils/__tests__/changelog.test.tsindex 7d17e32..5cae976 100644--- a/src/utils/__tests__/changelog.test.ts+++ b/src/utils/__tests__/changelog.test.ts@@ -8,9 +8,27 @@ import {} from '../changelog';describe('changelog parser', () => {- it('parses bundled CHANGELOG.md including v1.0.1 sections', () => {+ it('parses bundled CHANGELOG.md including v1.0.2 and v1.0.1 sections', () => {const entries = getChangelogEntries();- expect(entries.length).toBeGreaterThan(0);+ expect(entries.length).toBeGreaterThanOrEqual(2);++ const latest = getChangelogForVersion();+ expect(latest?.version).toBe('1.0.2');++ const v102 = getChangelogForVersion('1.0.2');+ expect(v102).toBeDefined();+ expect(v102?.version).toBe('1.0.2');+ expect(v102?.sections.map((s) => s.title)).toEqual([+ 'New',+ 'Improvements',+ 'Bug Fixes',+ ]);+ expect(v102?.sections[0].items).toContain(+ 'Added Auto-Reconnect, Roles, and Access Rights in the Collaborative Room'+ );+ expect(v102?.sections[2].items).toContain(+ 'Fixed bug with hand cursor stays on while drawing'+ );const v101 = getChangelogForVersion('1.0.1');expect(v101).toBeDefined();diff --git a/src/utils/__tests__/cspBrushEngineV2.test.ts b/src/utils/__tests__/cspBrushEngineV2.test.tsindex 13e3b3a..2f3768e 100644--- a/src/utils/__tests__/cspBrushEngineV2.test.ts+++ b/src/utils/__tests__/cspBrushEngineV2.test.ts@@ -168,6 +168,7 @@ describe('CSP Brush Engine V2 - Mathematics, Sensors & Post-Processing', () => {expect(stepBrushSizePreset(0.5, -1)).toBe(0.5);expect(stepBrushSizePreset(2000, 1)).toBe(2000);expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('g-pen');- expect(BUILTIN_BRUSHES.length).toBe(17);+ expect(BUILTIN_BRUSHES.map((b) => b.id)).toContain('impasto-bristle-oil');+ expect(BUILTIN_BRUSHES.length).toBe(26);});});diff --git a/src/utils/__tests__/frameBorderUndo.test.tsx b/src/utils/__tests__/frameBorderUndo.test.tsxnew file mode 100644index 0000000..6c35a85--- /dev/null+++ b/src/utils/__tests__/frameBorderUndo.test.tsx@@ -0,0 +1,653 @@+import { act, useRef } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { useLayerManager, applyLayerTreeDelta } from '../../hooks/useLayerManager';+import { useDrawingHistory } from '../../hooks/drawing/useDrawingHistory';+import { createRectFrame } from '../frameEngine';+import { SparseTileGrid, getTileKey, TILE_SIZE } from '../tileEngine';+import type { CanvasDimensions, LayerItem, LayerTreeDelta, TileDelta } from '../../types/editor';++// Minimal DOM shim for React 19 createRoot in Vitest Node environment+class ShimNode extends EventTarget {+ nodeType = 1;+ nodeName = 'DIV';+ tagName = 'DIV';+ namespaceURI = 'http://www.w3.org/1999/xhtml';+ ownerDocument: any;+ parentNode: any = null;+ childNodes: any[] = [];+ style: Record<string, string> = {};+ constructor(tag = 'DIV', doc?: any) {+ super();+ this.nodeName = tag.toUpperCase();+ this.tagName = this.nodeName;+ this.ownerDocument = doc ?? null;+ }+ appendChild(c: any) {+ c.parentNode = this;+ this.childNodes.push(c);+ return c;+ }+ removeChild(c: any) {+ const i = this.childNodes.indexOf(c);+ if (i >= 0) this.childNodes.splice(i, 1);+ c.parentNode = null;+ return c;+ }+ insertBefore(c: any, ref: any) {+ c.parentNode = this;+ const i = this.childNodes.indexOf(ref);+ if (i >= 0) this.childNodes.splice(i, 0, c);+ else this.childNodes.push(c);+ return c;+ }+ getContext() {+ return null;+ }+}++function installDomShim() {+ const doc: any = new ShimNode('#document');+ doc.nodeType = 9;+ doc.activeElement = null;+ doc.createElement = (tag: string) => new ShimNode(tag, doc);+ doc.createTextNode = (txt: string) => {+ const n: any = new ShimNode('#text', doc);+ n.nodeType = 3;+ n.nodeValue = txt;+ return n;+ };+ doc.documentElement = new ShimNode('HTML', doc);+ doc.body = new ShimNode('BODY', doc);+ const win: any = new EventTarget();+ win.document = doc;+ doc.defaultView = win;+ class HTMLIFrameElementShim extends ShimNode {}+ win.HTMLElement = ShimNode;+ win.HTMLIFrameElement = HTMLIFrameElementShim;+ win.Element = ShimNode;+ win.Node = ShimNode;+ win.requestAnimationFrame = (cb: () => void) => setTimeout(cb, 0);+ win.cancelAnimationFrame = (id: any) => clearTimeout(id);+ win.navigator = {};+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;+ (globalThis as any).window = win;+ (globalThis as any).document = doc;+ (globalThis as any).HTMLElement = ShimNode;+ (globalThis as any).HTMLIFrameElement = HTMLIFrameElementShim;+ (globalThis as any).Element = ShimNode;+ (globalThis as any).Node = ShimNode;+ return doc;+}++function paintTestTile(grid: SparseTileGrid, layerId: string, r: number, g: number, b: number): TileDelta[] {+ const tile = grid.getOrCreateTile(layerId, 0, 0, 'color-32bit', 0);+ const beforeData = tile.data ? new Uint8Array(tile.data) : null;+ if (!tile.data) {+ tile.data = new Uint8Array(TILE_SIZE * TILE_SIZE * 4);+ }+ tile.data[0] = r;+ tile.data[1] = g;+ tile.data[2] = b;+ tile.data[3] = 255;+ tile.dirty = true;+ grid.bumpLayerVersion(layerId);++ return [+ {+ key: getTileKey(layerId, 0, 0, 0),+ format: 'color-32bit',+ beforeData,+ afterData: new Uint8Array(tile.data),+ },+ ];+}++describe('Frame Border Ctrl+Z Undo / Redo', () => {+ describe('applyLayerTreeDelta pure helper', () => {+ it('removes added frame folder and child layer on undo while preserving unrelated layers, and restores on redo', () => {+ const layer1: LayerItem = {+ id: 'layer-1',+ name: 'Layer 1',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ };+ const bg: LayerItem = {+ id: 'layer-bg',+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ };+ const frameFolder: LayerItem = {+ id: 'ff-1',+ name: 'Frame 1',+ type: 'frame-folder',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ comicFrames: [createRectFrame('ff-1', 50, 50, 400, 400)],+ };+ const panelLayer: LayerItem = {+ id: 'raster-panel-1',+ name: 'Panel Layer',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: 'ff-1',+ };+ const userAddedSketch: LayerItem = {+ id: 'layer-sketch',+ name: 'Sketch',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ };+ const userAddedChildInFrame: LayerItem = {+ id: 'layer-extra-in-frame',+ name: 'Extra Panel Art',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: 'ff-1',+ };++ const delta: LayerTreeDelta = {+ addedLayers: [frameFolder, panelLayer],+ insertBeforeLayerId: 'layer-1',+ insertIndex: 0,+ beforeActiveLayerId: 'layer-1',+ afterActiveLayerId: 'raster-panel-1',+ };++ const currentLayers = [+ userAddedSketch,+ frameFolder,+ panelLayer,+ userAddedChildInFrame,+ layer1,+ bg,+ ];++ const undone = applyLayerTreeDelta(currentLayers, 'raster-panel-1', delta, 'undo');+ expect(undone.removedLayerIds).toEqual(['ff-1', 'raster-panel-1']);+ expect(undone.nextLayers.map((l) => l.id)).toEqual([+ 'layer-sketch',+ 'layer-extra-in-frame',+ 'layer-1',+ 'layer-bg',+ ]);+ // Surviving manually-added child must not retain a dangling parentId+ expect(+ undone.nextLayers.find((l) => l.id === 'layer-extra-in-frame')?.parentId+ ).toBeNull();+ expect(undone.nextActiveLayerId).toBe('layer-1');++ // Redo reinserts right before anchor layer-1+ const redone = applyLayerTreeDelta(undone.nextLayers, 'layer-1', delta, 'redo');+ expect(redone.addedLayers.map((l) => l.id)).toEqual(['ff-1', 'raster-panel-1']);+ expect(redone.nextLayers.map((l) => l.id)).toEqual([+ 'layer-sketch',+ 'layer-extra-in-frame',+ 'ff-1',+ 'raster-panel-1',+ 'layer-1',+ 'layer-bg',+ ]);+ expect(redone.nextActiveLayerId).toBe('raster-panel-1');++ // Idempotent redo does not duplicate layers+ const redoneAgain = applyLayerTreeDelta(redone.nextLayers, 'raster-panel-1', delta, 'redo');+ expect(redoneAgain.nextLayers.map((l) => l.id)).toEqual(redone.nextLayers.map((l) => l.id));+ });+ });++ describe('useLayerManager + useDrawingHistory integration', () => {+ let doc: any;+ let container: any;+ let root: Root;+ let grid: SparseTileGrid;+ let latestState: {+ layerMgr: ReturnType<typeof useLayerManager>;+ history: ReturnType<typeof useDrawingHistory>;+ };++ const dims: CanvasDimensions = { width: 1000, height: 1000, dpi: 600 };++ function TestHarness() {+ const layerMgr = useLayerManager({ dimensions: dims, tileGrid: grid });+ const dimensionsRef = useRef(dims);+ dimensionsRef.current = dims;+ const activeLayerIdRef = useRef(layerMgr.activeLayerId);+ activeLayerIdRef.current = layerMgr.activeLayerId;+ const colorModeRef = useRef<'color' | 'grayscale' | 'monochrome'>('color');+ const layersRef = useRef<LayerItem[] | undefined>(layerMgr.layers);+ layersRef.current = layerMgr.layers;+ const onApplyLayerTreeDeltaRef = useRef(layerMgr.applyLayerTreeDelta);+ onApplyLayerTreeDeltaRef.current = layerMgr.applyLayerTreeDelta;+ const onUpdateMaskThumbnailRef = useRef<((id: string) => void) | undefined>(undefined);+ const isDrawingRef = useRef(false);+ const lastStrokeEndRef = useRef(null);+ const abortActiveStrokeRef = useRef(() => {});++ const history = useDrawingHistory({+ tileGrid: grid,+ activeLayerId: layerMgr.activeLayerId,+ activeLayerLocked: false,+ dimensions: dims,+ dimensionsRef,+ activeLayerIdRef,+ colorModeRef,+ layersRef,+ onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,+ onApplyLayerTreeDeltaRef,+ onUpdateMaskThumbnailRef,+ isDrawingRef,+ lastStrokeEndRef,+ abortActiveStrokeRef,+ });++ latestState = { layerMgr, history };+ return null;+ }++ beforeEach(async () => {+ doc = installDomShim();+ container = doc.createElement('div');+ doc.body.appendChild(container);+ grid = new SparseTileGrid();+ root = createRoot(container);+ await act(async () => {+ root.render(<TestHarness />);+ });+ // Seed standard initial canvas layers (Layer 1 + Background)+ await act(async () => {+ latestState.layerMgr.resetToNewCanvas(dims, '#ffffff', 'color');+ });+ await act(async () => {+ latestState.history.resetHistory();+ });+ });++ afterEach(async () => {+ await act(async () => {+ root.unmount();+ });+ });++ it('removes a newly created frame border on Ctrl+Z (undo) and restores it on Ctrl+Y (redo)', async () => {+ const initialLayerIds = latestState.layerMgr.layers.map((l) => l.id);+ const initialActiveId = latestState.layerMgr.activeLayerId;+ expect(initialLayerIds.length).toBeGreaterThanOrEqual(2);++ const frame = createRectFrame('', 100, 100, 600, 600, { borderWidth: 4 });+ let createdFolderId = '';+ let createdChildId = '';++ await act(async () => {+ const { folder, childLayer, layerTreeDelta } = latestState.layerMgr.createFrameFolder(+ [frame],+ undefined,+ true+ );+ createdFolderId = folder.id;+ createdChildId = childLayer!.id;+ latestState.history.pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === createdFolderId)).toBe(true);+ expect(latestState.layerMgr.layers.some((l) => l.id === createdChildId)).toBe(true);+ expect(latestState.layerMgr.activeLayerId).toBe(createdChildId);+ expect(latestState.history.canUndo).toBe(true);++ // Ctrl+Z: undo removes the frame border folder & its panel layer+ await act(async () => {+ latestState.history.undo();+ await Promise.resolve();+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === createdFolderId)).toBe(false);+ expect(latestState.layerMgr.layers.some((l) => l.id === createdChildId)).toBe(false);+ expect(latestState.layerMgr.layers.map((l) => l.id)).toEqual(initialLayerIds);+ expect(latestState.layerMgr.activeLayerId).toBe(initialActiveId);+ expect(latestState.history.canRedo).toBe(true);++ // Ctrl+Y: redo restores the frame border folder & its panel layer+ await act(async () => {+ latestState.history.redo();+ await Promise.resolve();+ });++ const restoredFolder = latestState.layerMgr.layers.find((l) => l.id === createdFolderId);+ expect(restoredFolder).toBeDefined();+ expect(restoredFolder?.comicFrames).toHaveLength(1);+ expect(latestState.layerMgr.layers.some((l) => l.id === createdChildId)).toBe(true);+ expect(latestState.layerMgr.activeLayerId).toBe(createdChildId);+ });++ it('interleaves frame creation with brush strokes across multi-step undo, redo, and history jump', async () => {+ const initialActiveId = latestState.layerMgr.activeLayerId;+ const frame = createRectFrame('', 100, 100, 600, 600);+ let folderId = '';+ let panelId = '';++ await act(async () => {+ const { folder, childLayer, layerTreeDelta } = latestState.layerMgr.createFrameFolder(+ [frame],+ undefined,+ true+ );+ folderId = folder.id;+ panelId = childLayer!.id;+ latestState.history.pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );+ });++ // Draw a stroke inside the panel layer+ await act(async () => {+ const deltas = paintTestTile(grid, panelId, 200, 40, 20);+ latestState.history.pushHistoryStep(+ 'brush',+ 'Pen Stroke',+ null,+ null,+ panelId,+ { x: 0, y: 0, width: TILE_SIZE, height: TILE_SIZE },+ deltas+ );+ });++ expect(grid.getTile(panelId, 0, 0, 0)?.data?.[0]).toBe(200);++ // Jump all the way back to New Document (index 0): undoes stroke AND removes frame border+ await act(async () => {+ await latestState.history.jumpToHistoryIndex(0);+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === folderId)).toBe(false);+ expect(latestState.layerMgr.layers.some((l) => l.id === panelId)).toBe(false);+ expect(latestState.layerMgr.activeLayerId).toBe(initialActiveId);+ expect(grid.getTile(panelId, 0, 0, 0)).toBeNull();++ // Jump all the way forward (index 2): restores frame border, panel layer, AND painted stroke+ await act(async () => {+ await latestState.history.jumpToHistoryIndex(2);+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === folderId)).toBe(true);+ expect(latestState.layerMgr.layers.some((l) => l.id === panelId)).toBe(true);+ expect(grid.getTile(panelId, 0, 0, 0)?.data?.[0]).toBe(200);+ });++ it('undoes and redoes Divide Frame Border in same-folder mode', async () => {+ const frame = createRectFrame('', 100, 100, 800, 800, {+ gutterVerticalPx: 40,+ gutterHorizontalPx: 80,+ });+ let folderId = '';++ await act(async () => {+ const { folder, layerTreeDelta } = latestState.layerMgr.createFrameFolder(+ [frame],+ undefined,+ true+ );+ folderId = folder.id;+ latestState.history.pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );+ });++ await act(async () => {+ const res = latestState.layerMgr.divideFrameFolder(+ folderId,+ { x: 50, y: 500 },+ { x: 950, y: 500 },+ 600,+ 'same-folder'+ );+ expect(res.divided).toBe(true);+ latestState.history.pushHistoryStep(+ 'frame',+ 'Divide Frame Border',+ null,+ null,+ folderId,+ undefined,+ res.tileDeltas,+ undefined,+ undefined,+ undefined,+ undefined,+ res.layerTreeDelta+ );+ });++ expect(+ latestState.layerMgr.layers.find((l) => l.id === folderId)?.comicFrames+ ).toHaveLength(2);++ // 1st Ctrl+Z: reverts divide back to 1 frame+ await act(async () => {+ latestState.history.undo();+ await Promise.resolve();+ });++ expect(+ latestState.layerMgr.layers.find((l) => l.id === folderId)?.comicFrames+ ).toHaveLength(1);++ // 2nd Ctrl+Z: removes the frame folder completely+ await act(async () => {+ latestState.history.undo();+ await Promise.resolve();+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === folderId)).toBe(false);++ // Redo twice: restores folder, then restores 2 divided frames+ await act(async () => {+ await latestState.history.jumpToHistoryIndex(2);+ });++ expect(+ latestState.layerMgr.layers.find((l) => l.id === folderId)?.comicFrames+ ).toHaveLength(2);+ });++ it('undoes and redoes Divide Frame Folder in split-folders mode including cloned child tiles', async () => {+ const frame = createRectFrame('', 100, 100, 800, 800, {+ gutterVerticalPx: 40,+ gutterHorizontalPx: 80,+ });+ let folderId = '';+ let panelId = '';++ await act(async () => {+ const { folder, childLayer, layerTreeDelta } = latestState.layerMgr.createFrameFolder(+ [frame],+ undefined,+ true+ );+ folderId = folder.id;+ panelId = childLayer!.id;+ latestState.history.pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );+ });++ // Paint pixel onto panel layer so split-folders clones actual tile data+ await act(async () => {+ const deltas = paintTestTile(grid, panelId, 33, 144, 255);+ latestState.history.pushHistoryStep(+ 'brush',+ 'Panel Ink',+ null,+ null,+ panelId,+ { x: 0, y: 0, width: TILE_SIZE, height: TILE_SIZE },+ deltas+ );+ });++ let splitFolderBId = '';+ let clonedChildId = '';++ await act(async () => {+ const res = latestState.layerMgr.divideFrameFolder(+ folderId,+ { x: 50, y: 500 },+ { x: 950, y: 500 },+ 600,+ 'split-folders'+ );+ expect(res.divided).toBe(true);+ splitFolderBId = res.layerTreeDelta?.addedLayers?.[0]?.id ?? '';+ clonedChildId = res.layerTreeDelta?.addedLayers?.[1]?.id ?? '';+ latestState.history.pushHistoryStep(+ 'frame',+ 'Divide Frame Folder',+ null,+ null,+ folderId,+ undefined,+ res.tileDeltas,+ undefined,+ undefined,+ undefined,+ undefined,+ res.layerTreeDelta+ );+ });++ expect(splitFolderBId).not.toBe('');+ expect(clonedChildId).not.toBe('');+ expect(latestState.layerMgr.layers.some((l) => l.id === splitFolderBId)).toBe(true);+ expect(grid.getTile(clonedChildId, 0, 0, 0)?.data?.[1]).toBe(144);++ // Undo split-folders: removes Folder B + cloned child, clears cloned tiles, restores original Frame A bounds+ await act(async () => {+ latestState.history.undo();+ await Promise.resolve();+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === splitFolderBId)).toBe(false);+ expect(latestState.layerMgr.layers.some((l) => l.id === clonedChildId)).toBe(false);+ expect(grid.getTile(clonedChildId, 0, 0, 0)).toBeNull();+ const restoredA = latestState.layerMgr.layers.find((l) => l.id === folderId);+ expect(restoredA?.comicFrames?.[0]?.polygon).toEqual(frame.polygon);++ // Redo split-folders: restores Folder B + cloned child + cloned pixel data+ await act(async () => {+ latestState.history.redo();+ await Promise.resolve();+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === splitFolderBId)).toBe(true);+ expect(latestState.layerMgr.layers.some((l) => l.id === clonedChildId)).toBe(true);+ expect(grid.getTile(clonedChildId, 0, 0, 0)?.data?.[1]).toBe(144);+ });++ it('supports collaborative selectiveUndo for removing a created frame border', async () => {+ const initialActiveId = latestState.layerMgr.activeLayerId;+ const frame = createRectFrame('', 100, 100, 500, 500);+ let folderId = '';+ let panelId = '';++ await act(async () => {+ const { folder, childLayer, layerTreeDelta } = latestState.layerMgr.createFrameFolder(+ [frame],+ undefined,+ true+ );+ folderId = folder.id;+ panelId = childLayer!.id;+ latestState.history.pushHistoryStep(+ 'frame',+ 'Create Frame Folder',+ null,+ null,+ folder.id,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ layerTreeDelta+ );+ });++ await act(async () => {+ await latestState.history.selectiveUndo('local');+ });++ expect(latestState.layerMgr.layers.some((l) => l.id === folderId)).toBe(false);+ expect(latestState.layerMgr.layers.some((l) => l.id === panelId)).toBe(false);+ expect(latestState.layerMgr.activeLayerId).toBe(initialActiveId);+ });+ });+});diff --git a/src/utils/__tests__/gradientEngine.test.ts b/src/utils/__tests__/gradientEngine.test.tsnew file mode 100644index 0000000..fc90b74--- /dev/null+++ b/src/utils/__tests__/gradientEngine.test.ts@@ -0,0 +1,184 @@+import { describe, it, expect } from 'vitest';+import {+ DEFAULT_GRADIENT_SETTINGS,+ constrainGradientEndpoint,+ createDefaultGradientMesh,+ rasterizeMeshGradientToRgba,+ renderGradientToTileGrid,+ resolveGradientStops,+ sampleGradientStops,+} from '../gradientEngine';+import { SparseTileGrid } from '../tileEngine';++describe('Gradient Engine (Linear / Radial / Mesh)', () => {+ it('interpolates multi-stop RGBA colors with clamp, repeat, reflect, and reverse', () => {+ const stops = resolveGradientStops(+ {+ ...DEFAULT_GRADIENT_SETTINGS,+ useForegroundBackground: false,+ stops: [+ { id: 'a', offset: 0, color: '#000000', opacity: 1 },+ { id: 'b', offset: 1, color: '#ffffff', opacity: 0.5 },+ ],+ },+ '#ff0000',+ '#00ff00'+ );++ const out: [number, number, number, number] = [0, 0, 0, 0];+ sampleGradientStops(stops, 0.5, 'clamp', false, out);+ expect(out[0]).toBeCloseTo(127.5, 1);+ expect(out[3]).toBeCloseTo(191.25, 1);++ // Clamp outside [0,1]+ sampleGradientStops(stops, 1.5, 'clamp', false, out);+ expect(out[0]).toBe(255);++ // Repeat wraps 1.25 -> 0.25+ sampleGradientStops(stops, 1.25, 'repeat', false, out);+ expect(out[0]).toBeCloseTo(63.75, 1);++ // Reflect bounces 1.25 -> 0.75+ sampleGradientStops(stops, 1.25, 'reflect', false, out);+ expect(out[0]).toBeCloseTo(191.25, 1);++ // Reverse inverts t+ sampleGradientStops(stops, 0.25, 'clamp', true, out);+ expect(out[0]).toBeCloseTo(191.25, 1);+ });++ it('snaps gradient endpoints to 15-degree increments when constrained', () => {+ const snapped = constrainGradientEndpoint({ x: 0, y: 0 }, { x: 100, y: 12 });+ expect(Math.atan2(snapped.y, snapped.x)).toBeCloseTo(0, 5);+ expect(Math.hypot(snapped.x, snapped.y)).toBeCloseTo(Math.hypot(100, 12), 4);+ });++ it('renders linear gradient into SparseTileGrid respecting selection mask and undo tileDeltas', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ const layerId = 'layer-grad';++ const res = renderGradientToTileGrid({+ grid,+ layerId,+ dimensions: dims,+ targetFormat: 'color-32bit',+ settings: {+ ...DEFAULT_GRADIENT_SETTINGS,+ type: 'linear',+ dither: false,+ useForegroundBackground: true,+ },+ primaryColor: '#ff0000',+ secondaryColor: '#0000ff',+ start: { x: 10, y: 50 },+ end: { x: 110, y: 50 },+ selection: {+ type: 'rect',+ bounds: { x: 20, y: 20, width: 80, height: 80 },+ },+ });++ expect(res.modified).toBe(true);+ expect(res.tileDeltas.length).toBeGreaterThan(0);++ // Outside selection must stay transparent+ expect(grid.getPixelRGBA(layerId, 5, 5)[3]).toBe(0);++ // Inside selection: left side reddish, right side bluish+ const leftPx = grid.getPixelRGBA(layerId, 22, 50);+ const rightPx = grid.getPixelRGBA(layerId, 98, 50);+ expect(leftPx[0]).toBeGreaterThan(200);+ expect(leftPx[2]).toBeLessThan(60);+ expect(rightPx[2]).toBeGreaterThan(200);+ expect(rightPx[0]).toBeLessThan(60);++ // Undo restores clean empty layer+ grid.applyTileDeltas(res.tileDeltas, 'undo');+ expect(grid.getPixelRGBA(layerId, 50, 50)[3]).toBe(0);+ });++ it('renders radial gradient centered at start with radius to end and respects alphaLock', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 100, height: 100 };+ const layerId = 'layer-rad';+ // Paint an opaque 40x40 square at (30,30)+ const sq = new Uint8ClampedArray(40 * 40 * 4);+ for (let i = 0; i < sq.length; i += 4) {+ sq[i] = 128;+ sq[i + 1] = 128;+ sq[i + 2] = 128;+ sq[i + 3] = 255;+ }+ grid.writeImageData(layerId, { data: sq, width: 40, height: 40 }, 30, 30, 'color-32bit', true);++ const res = renderGradientToTileGrid({+ grid,+ layerId,+ dimensions: dims,+ targetFormat: 'color-32bit',+ settings: {+ ...DEFAULT_GRADIENT_SETTINGS,+ type: 'radial',+ dither: false,+ useForegroundBackground: true,+ },+ primaryColor: '#ffffff',+ secondaryColor: '#000000',+ start: { x: 50, y: 50 },+ end: { x: 70, y: 50 },+ alphaLock: true,+ });++ expect(res.modified).toBe(true);+ // Transparent pixel outside opaque square stays transparent under alphaLock+ expect(grid.getPixelRGBA(layerId, 10, 10)[3]).toBe(0);+ // Center is bright white, outer edge of circle is dark+ expect(grid.getPixelRGBA(layerId, 50, 50)[0]).toBeGreaterThan(230);+ expect(grid.getPixelRGBA(layerId, 69, 50)[0]).toBeLessThan(35);+ });++ it('renders bicubic Mesh Gradient with displaced nodes cleanly into RGBA and SparseTileGrid', () => {+ const mesh = createDefaultGradientMesh(+ { x: 0, y: 0, width: 64, height: 64 },+ 3,+ 3,+ '#ff0000',+ '#00ff00'+ );+ // Override corners for deterministic verification+ mesh.nodes[0].color = '#ff0000';+ mesh.nodes[2].color = '#00ff00';+ mesh.nodes[6].color = '#0000ff';+ mesh.nodes[8].color = '#ffff00';+ // Displace center node+ mesh.nodes[4].x = 40;+ mesh.nodes[4].y = 40;+ mesh.nodes[4].color = '#ffffff';++ const buf = rasterizeMeshGradientToRgba(mesh, 0, 0, 64, 64, 1, 1, false, 6);+ // Top-left pixel near red+ expect(buf[(2 * 64 + 2) * 4]).toBeGreaterThan(200);+ expect(buf[(2 * 64 + 2) * 4 + 3]).toBe(255);+ // Displaced center node pixel near white+ const cOff = (40 * 64 + 40) * 4;+ expect(buf[cOff]).toBeGreaterThan(220);+ expect(buf[cOff + 1]).toBeGreaterThan(220);+ expect(buf[cOff + 2]).toBeGreaterThan(220);++ // Commit to tile grid+ const grid = new SparseTileGrid();+ const res = renderGradientToTileGrid({+ grid,+ layerId: 'layer-mesh',+ dimensions: { width: 64, height: 64 },+ targetFormat: 'color-32bit',+ settings: { ...DEFAULT_GRADIENT_SETTINGS, type: 'mesh', dither: false },+ primaryColor: '#000000',+ secondaryColor: '#ffffff',+ mesh,+ });+ expect(res.modified).toBe(true);+ expect(grid.getPixelRGBA('layer-mesh', 40, 40)[0]).toBeGreaterThan(220);+ });+});diff --git a/src/utils/__tests__/multiLayerLiquify.test.ts b/src/utils/__tests__/multiLayerLiquify.test.tsindex 3fc17ad..0b38fbd 100644--- a/src/utils/__tests__/multiLayerLiquify.test.ts+++ b/src/utils/__tests__/multiLayerLiquify.test.ts@@ -1,6 +1,11 @@import { describe, it, expect } from 'vitest';import { LayerItem } from '../../types/editor';-import { resolveLiquifyTargetLayers } from '../liquifyEngine';+import {+ LiquifyWarpField,+ resampleLayerFromWarpField,+ resolveLiquifyTargetLayers,+} from '../liquifyEngine';+import { SparseTileGrid, TileSnapshotEntry } from '../tileEngine';function makeLayer(overrides: Partial<LayerItem> & { id: string }): LayerItem {return {@@ -79,3 +84,146 @@ describe('Multi-layer Liquify target resolution', () => {expect(folderMulti.map((l) => l.id)).toEqual(['layer-1', 'layer-2', 'layer-3']);});});++describe('LiquifyWarpField quality (zero dark fringes, single-pass bicubic, exact reconstruct)', () => {+ const dims = { width: 320, height: 320 };++ it('preserves pure brush/smudge RGB on semi-transparent edges with zero black alpha fringing', () => {+ const grid = new SparseTileGrid();+ // Bright yellow stroke (255, 220, 60, 255) on transparent background (0, 0, 0, 0)+ const barW = 12;+ const barH = 40;+ const data = new Uint8ClampedArray(barW * barH * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = 255;+ data[i + 1] = 220;+ data[i + 2] = 60;+ data[i + 3] = 255;+ }+ grid.writeImageData('brush', { data, width: barW, height: barH }, 100, 100, 'color-32bit');++ const warpField = new LiquifyWarpField();+ const beforeSnap = new Map<string, TileSnapshotEntry>();+ const origCache = new Map<number, Uint8ClampedArray | null>();++ // Push across 12 sub-steps (would severely blur and darken edges with iterative straight-alpha bilinear)+ const steps = [];+ for (let i = 0; i < 12; i++) {+ steps.push({ cx: 106 + (i + 1) * 2.3, cy: 120, prevX: 106 + i * 2.3, prevY: 120, pressure: 1 });+ }+ const dirty = warpField.applySubSteps(steps, dims, {+ mode: 'push',+ size: 60,+ strength: 80,+ hardness: 70,+ usePressure: false,+ });+ expect(dirty).not.toBeNull();++ resampleLayerFromWarpField({+ grid,+ layerId: 'brush',+ dimensions: dims,+ targetFormat: 'color-32bit',+ warpField,+ dirtyRect: dirty!,+ beforeTileSnapshot: beforeSnap,+ origRgbaCache: origCache,+ });++ // Check every semi-transparent edge pixel produced by the warp: RGB must stay pure yellow (no black mixing)+ let semiTransparentChecked = 0;+ let maxCoreAlpha = 0;+ for (let x = dirty!.x; x < dirty!.x + dirty!.width; x++) {+ const [r, g, b, a] = grid.getPixelRGBA('brush', x, 120);+ if (a > maxCoreAlpha) maxCoreAlpha = a;+ if (a > 10 && a < 245) {+ semiTransparentChecked++;+ expect(r).toBeGreaterThanOrEqual(250);+ expect(g).toBeGreaterThanOrEqual(215);+ expect(b).toBeGreaterThanOrEqual(55);+ expect(b).toBeLessThanOrEqual(65);+ }+ }+ expect(semiTransparentChecked).toBeGreaterThan(0);+ expect(maxCoreAlpha).toBe(255);+ });++ it('reconstructs warped pixels back to exact original state across strokes without ghosting', () => {+ const grid = new SparseTileGrid();+ // Crisp 4px vertical cyan line straddling tile boundary x=254..257+ const w = 4;+ const h = 40;+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = 40;+ data[i + 1] = 210;+ data[i + 2] = 240;+ data[i + 3] = 255;+ }+ grid.writeImageData('line', { data, width: w, height: h }, 254, 140, 'color-32bit');++ const warpField = new LiquifyWarpField();+ const origCache = new Map<number, Uint8ClampedArray | null>();++ // Stroke 1: push right by 2 steps (4px line at 254..257 shifts right into x >= 262)+ const snap1 = new Map<string, TileSnapshotEntry>();+ const dirty1 = warpField.applySubSteps(+ [+ { cx: 260, cy: 160, prevX: 254, prevY: 160, pressure: 1 },+ { cx: 266, cy: 160, prevX: 260, prevY: 160, pressure: 1 },+ ],+ dims,+ { mode: 'push', size: 64, strength: 100, hardness: 80, usePressure: false }+ );+ expect(dirty1).not.toBeNull();+ resampleLayerFromWarpField({+ grid,+ layerId: 'line',+ dimensions: dims,+ targetFormat: 'color-32bit',+ warpField,+ dirtyRect: dirty1!,+ beforeTileSnapshot: snap1,+ origRgbaCache: origCache,+ });+ let shiftedMaxAlpha = 0;+ for (let x = 262; x <= 275; x++) {+ shiftedMaxAlpha = Math.max(shiftedMaxAlpha, grid.getPixelRGBA('line', x, 160)[3]);+ }+ expect(shiftedMaxAlpha).toBeGreaterThan(200);++ // Stroke 2: reconstruct relaxes displacement field back to 0 -> exact original pixels restored+ const snap2 = new Map<string, TileSnapshotEntry>();+ const reconSteps = Array.from({ length: 30 }, () => ({+ cx: 260,+ cy: 160,+ prevX: 260,+ prevY: 160,+ pressure: 1,+ }));+ const dirty2 = warpField.applySubSteps(reconSteps, dims, {+ mode: 'reconstruct',+ size: 120,+ strength: 100,+ hardness: 100,+ usePressure: false,+ });+ expect(dirty2).not.toBeNull();+ resampleLayerFromWarpField({+ grid,+ layerId: 'line',+ dimensions: dims,+ targetFormat: 'color-32bit',+ warpField,+ dirtyRect: dirty2!,+ beforeTileSnapshot: snap2,+ origRgbaCache: origCache,+ });++ expect(grid.getPixelRGBA('line', 255, 160)).toEqual([40, 210, 240, 255]);+ for (let x = 262; x <= 275; x++) {+ expect(grid.getPixelRGBA('line', x, 160)[3]).toBe(0);+ }+ });+});diff --git a/src/utils/__tests__/naturalPaintEngine.test.ts b/src/utils/__tests__/naturalPaintEngine.test.tsnew file mode 100644index 0000000..4bcf6e3--- /dev/null+++ b/src/utils/__tests__/naturalPaintEngine.test.ts@@ -0,0 +1,696 @@+import { describe, it, expect, beforeEach } from 'vitest';+import type { BrushSettings, CspBrush, Point, SurfaceTextureId } from '../../types/editor';+import {+ DEFAULT_BRISTLE_SETTINGS,+ DEFAULT_IMPASTO_SETTINGS,+ DEFAULT_NATURAL_PAINT_SETTINGS,+} from '../../types/editor';+import {+ getSurfaceTextureDataUrl,+ getSurfaceTextureHeightField,+ sampleSurfaceTextureHeight,+ SURFACE_TEXTURE_CATALOG,+ SURFACE_TEXTURE_SIZE,+} from '../proceduralBrushTips';+import {+ cleanDirtyBrush,+ hasDirtyBrushState,+ LayerPixelSampler,+ SpatialBristleReservoir,+} from '../colorMixingEngine';+import {+ BristleRibbonEngine,+ BRISTLE_SEG_STRIDE,+ extractBristleStrokeConfig,+} from '../../engine/BristleRibbonEngine';+import {+ evaluateMappedSurfaceHeight,+ evaluatePaintCanvasContact,+ NaturalPaintStrokeSession,+ renderCompleteNaturalPaintStroke,+} from '../../engine/NaturalPaintRenderer';+import {+ INKB_VERSION,+ parseInkbFile,+ serializeInkbBrush,+} from '../inkbBrushFormat';+import { BUILTIN_BRUSHES, getBuiltinBrushConfig } from '../presetBrushes';+import { getEffectiveBrushSettings } from '../brushPresetManager';++function createHeadlessCanvas(width: number = 256, height: number = 256) {+ const buf = new Uint8ClampedArray(width * height * 4);+ const ctx: any = {+ canvas: { width, height },+ globalAlpha: 1,+ globalCompositeOperation: 'source-over',+ save: () => {},+ restore: () => {},+ clearRect: (x: number, y: number, w: number, h: number) => {+ const x0 = Math.max(0, Math.floor(x));+ const y0 = Math.max(0, Math.floor(y));+ const x1 = Math.min(width, Math.ceil(x + w));+ const y1 = Math.min(height, Math.ceil(y + h));+ for (let py = y0; py < y1; py++) {+ for (let px = x0; px < x1; px++) {+ const i = (py * width + px) * 4;+ buf[i] = buf[i + 1] = buf[i + 2] = buf[i + 3] = 0;+ }+ }+ },+ createImageData: (w: number, h: number) => ({+ width: w,+ height: h,+ data: new Uint8ClampedArray(w * h * 4),+ }),+ putImageData: (img: ImageData, dx = 0, dy = 0) => {+ for (let y = 0; y < img.height; y++) {+ const ty = dy + y;+ if (ty < 0 || ty >= height) continue;+ for (let x = 0; x < img.width; x++) {+ const tx = dx + x;+ if (tx < 0 || tx >= width) continue;+ const si = (y * img.width + x) * 4;+ const di = (ty * width + tx) * 4;+ buf[di] = img.data[si];+ buf[di + 1] = img.data[si + 1];+ buf[di + 2] = img.data[si + 2];+ buf[di + 3] = img.data[si + 3];+ }+ }+ },+ getImageData: (sx = 0, sy = 0, sw = width, sh = height) => {+ const out = new Uint8ClampedArray(sw * sh * 4);+ for (let y = 0; y < sh; y++) {+ const ty = sy + y;+ if (ty < 0 || ty >= height) continue;+ for (let x = 0; x < sw; x++) {+ const tx = sx + x;+ if (tx < 0 || tx >= width) continue;+ const si = (ty * width + tx) * 4;+ const di = (y * sw + x) * 4;+ out[di] = buf[si];+ out[di + 1] = buf[si + 1];+ out[di + 2] = buf[si + 2];+ out[di + 3] = buf[si + 3];+ }+ }+ return { width: sw, height: sh, data: out };+ },+ drawImage: (+ src: any,+ sx: number,+ sy: number,+ sw: number,+ sh: number,+ dx: number,+ dy: number,+ dw: number,+ dh: number+ ) => {+ const srcBuf: Uint8ClampedArray | undefined = src?.__buf;+ if (!srcBuf) return;+ const srcW = src.width;+ for (let y = 0; y < Math.min(sh, dh); y++) {+ const ty = Math.floor(dy + y);+ const fy = Math.floor(sy + y);+ if (ty < 0 || ty >= height || fy < 0 || fy >= src.height) continue;+ for (let x = 0; x < Math.min(sw, dw); x++) {+ const tx = Math.floor(dx + x);+ const fx = Math.floor(sx + x);+ if (tx < 0 || tx >= width || fx < 0 || fx >= srcW) continue;+ const si = (fy * srcW + fx) * 4;+ const di = (ty * width + tx) * 4;+ const sa = (srcBuf[si + 3] / 255) * ctx.globalAlpha;+ if (sa <= 0) continue;+ const da = buf[di + 3] / 255;+ const outA = sa + da * (1 - sa);+ if (outA > 0) {+ buf[di] = Math.round((srcBuf[si] * sa + buf[di] * da * (1 - sa)) / outA);+ buf[di + 1] = Math.round((srcBuf[si + 1] * sa + buf[di + 1] * da * (1 - sa)) / outA);+ buf[di + 2] = Math.round((srcBuf[si + 2] * sa + buf[di + 2] * da * (1 - sa)) / outA);+ buf[di + 3] = Math.round(Math.min(1, outA) * 255);+ }+ }+ }+ },+ };++ return {+ width,+ height,+ __buf: buf,+ getContext: (type: string) => (type === '2d' ? ctx : null),+ toDataURL: () => `data:image/png;base64,MOCK_${width}x${height}`,+ };+}++describe('Natural Paint Engine — Bristles, Spatial Mixing, Surface Textures & Impasto', () => {+ beforeEach(() => {+ cleanDirtyBrush();+ (globalThis as any).document = {+ createElement: (tag: string) => {+ if (tag === 'canvas') return createHeadlessCanvas(256, 256);+ return {};+ },+ };+ (globalThis as any).Image = class MockImage {+ src = '';+ complete = true;+ naturalWidth = 128;+ naturalHeight = 128;+ width = 128;+ height = 128;+ decode() {+ return Promise.resolve();+ }+ };+ });++ it('generates all 7 seamless 512x512 procedural surface heightmaps with rich tonal range and periodic wrap', () => {+ expect(SURFACE_TEXTURE_CATALOG.length).toBe(7);++ for (const meta of SURFACE_TEXTURE_CATALOG) {+ const field = getSurfaceTextureHeightField(meta.id);+ expect(field.length).toBe(SURFACE_TEXTURE_SIZE * SURFACE_TEXTURE_SIZE);++ let minV = 255;+ let maxV = 0;+ for (let i = 0; i < field.length; i += 17) {+ if (field[i] < minV) minV = field[i];+ if (field[i] > maxV) maxV = field[i];+ }+ expect(maxV - minV).toBeGreaterThan(80);++ // Seamless periodicity: sampling at x and x + 512 must match identically+ const h0 = sampleSurfaceTextureHeight(meta.id, 37.25, 114.5, 1.0, 0);+ const hWrap = sampleSurfaceTextureHeight(+ meta.id,+ 37.25 + SURFACE_TEXTURE_SIZE,+ 114.5 + SURFACE_TEXTURE_SIZE,+ 1.0,+ 0+ );+ expect(Math.abs(h0 - hWrap)).toBeLessThan(1e-5);++ const url = getSurfaceTextureDataUrl(meta.id);+ expect(url).toMatch(/^data:image\/png;base64,/);+ }+ });++ it('performs spatial per-bristle color pickup so only bristles touching purple pick up purple while neighbors stay yellow', () => {+ // Prepare a canvas where left half (x < 100) is opaque purple and right half (x >= 100) is unpainted+ const canvas = createHeadlessCanvas(200, 200);+ for (let y = 0; y < 200; y++) {+ for (let x = 0; x < 100; x++) {+ const i = (y * 200 + x) * 4;+ canvas.__buf[i] = 110;+ canvas.__buf[i + 1] = 35;+ canvas.__buf[i + 2] = 215;+ canvas.__buf[i + 3] = 255;+ }+ }+ const sampler = new LayerPixelSampler(canvas as any);++ const yellowBs: BrushSettings = {+ size: 60,+ minSizeFactor: 0.5,+ color: '#facc15',+ opacity: 1,+ flow: 0.95,+ spacing: 0.05,+ usePressure: true,+ smoothing: true,+ stabilization: 0,+ hardness: 0.9,+ renderMode: 'bristle-ribbon',+ colorMixing: true,+ mixingMode: 'running_color',+ bristle: { ...DEFAULT_BRISTLE_SETTINGS, profile: 'flat', count: 16, clumping: 0.0, irregularity: 0.0 },+ naturalPaint: {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ enabled: true,+ spatialMixing: true,+ paintLoad: 0.85,+ wetness: 0.85,+ viscosity: 0.2,+ depletionRate: 0.1,+ autoClean: true,+ },+ };++ const cfg = extractBristleStrokeConfig(yellowBs, '#facc15');+ const engine = new BristleRibbonEngine(cfg);++ // Stroke straight down along x=100: left bristles (offset < 0) touch purple; right bristles (offset > 0) stay on empty canvas!+ const p0: Point = { x: 100, y: 20, pressure: 0.85, width: 60 };+ const p1: Point = { x: 100, y: 50, pressure: 0.85, width: 60 };+ const p2: Point = { x: 100, y: 80, pressure: 0.85, width: 60 };+ const p3: Point = { x: 100, y: 120, pressure: 0.85, width: 60 };++ engine.emitInitialStamp(p0, sampler);+ engine.emitCubicSegment(p0, p1, p2, p3, sampler);++ // Compare blue channel on bristles touching purple vs bristles on empty canvas+ // Moving downward (tx=0, ty=1) -> normal is (-1, 0), so offset > 0 points LEFT (into purple x < 100)+ // and offset < 0 points RIGHT (into empty x > 100)+ const rightIdx = 0; // offset = -1 -> x ~ 130 (empty)+ const leftIdx = engine.reservoir.count - 1; // offset = +1 -> x ~ 70 (purple)++ // Right bristle stays vibrant yellow (high R, high G, low B)+ expect(engine.reservoir.r[rightIdx]).toBeGreaterThan(220);+ expect(engine.reservoir.g[rightIdx]).toBeGreaterThan(180);+ expect(engine.reservoir.b[rightIdx]).toBeLessThan(40);++ // Left bristle picked up purple (significantly elevated blue channel & lowered green)+ expect(engine.reservoir.b[leftIdx]).toBeGreaterThan(engine.reservoir.b[rightIdx] + 45);+ });++ it('supports paint load depletion, zero-load pure blender, and dirty-brush persistence across strokes', () => {+ const res = new SpatialBristleReservoir(+ '#1d4ed8',+ { ...DEFAULT_BRISTLE_SETTINGS, profile: 'rake', count: 12, irregularity: 0.4 },+ { ...DEFAULT_NATURAL_PAINT_SETTINGS, enabled: true, paintLoad: 0.8, depletionRate: 0.8, autoClean: false },+ 'dirty-test-preset'+ );++ const out = { r: 0, g: 0, b: 0, alpha: 0, load: 0, height: 0 };+ const initialLoad = res.load[0];+ // Step 400px along dry canvas -> paint load must noticeably deplete+ for (let s = 0; s < 40; s++) {+ res.stepBristle(+ 0,+ { r: 255, g: 255, b: 255, a: 0 },+ 10,+ 0.5,+ { enabled: true, spatialMixing: true, paintLoad: 0.8, depletionRate: 0.8, wetness: 0.5, viscosity: 0.5, autoClean: false, chargePerPressure: 0.3, dryBrush: 0.5, pigmentMixingStrength: 0.9 },+ 'blend',+ 0.5,+ 0.8,+ 0.9,+ 0.9,+ out+ );+ }+ expect(res.load[0]).toBeLessThan(initialLoad * 0.45);++ // Pick up red pigment on bristle 2 and persist dirty brush state+ res.stepBristle(+ 2,+ { r: 240, g: 20, b: 20, a: 1.0 },+ 6,+ 0.8,+ { enabled: true, spatialMixing: true, paintLoad: 0.8, depletionRate: 0.1, wetness: 0.9, viscosity: 0.2, autoClean: false, chargePerPressure: 0.3, dryBrush: 0.2, pigmentMixingStrength: 0.9 },+ 'running_color',+ 0.8,+ 0.5,+ 0.9,+ 0.9,+ out+ );+ res.persistDirtyStateIfNeeded();+ expect(hasDirtyBrushState('dirty-test-preset')).toBe(true);++ // Next stroke with same preset retains dirty red tint on bristle 2+ const nextStrokeRes = new SpatialBristleReservoir(+ '#1d4ed8',+ { ...DEFAULT_BRISTLE_SETTINGS, profile: 'rake', count: 12, irregularity: 0.4 },+ { ...DEFAULT_NATURAL_PAINT_SETTINGS, enabled: true, paintLoad: 0.8, depletionRate: 0.8, autoClean: false },+ 'dirty-test-preset'+ );+ expect(nextStrokeRes.r[2]).toBeGreaterThan(nextStrokeRes.r[5] + 20);++ // Cleaning removes dirty state+ cleanDirtyBrush('dirty-test-preset');+ expect(hasDirtyBrushState('dirty-test-preset')).toBe(false);++ // Zero-load blender on empty canvas emits 0 alpha+ const blender = new SpatialBristleReservoir(+ '#ff0000',+ DEFAULT_BRISTLE_SETTINGS,+ { ...DEFAULT_NATURAL_PAINT_SETTINGS, enabled: true, paintLoad: 0.0, spatialMixing: true }+ );+ blender.stepBristle(+ 0,+ { r: 0, g: 0, b: 0, a: 0 },+ 5,+ 0.7,+ { ...DEFAULT_NATURAL_PAINT_SETTINGS, enabled: true, paintLoad: 0.0, spatialMixing: true },+ 'smear',+ 0.8,+ 0,+ 0.9,+ 0.9,+ out+ );+ expect(out.alpha).toBe(0);+ });++ it('curves bristle strands smoothly around tight 180-degree turns with finite coordinates and zero NaN artifacts', () => {+ const bs = getEffectiveBrushSettings('impasto-bristle-oil') as BrushSettings;+ const cfg = extractBristleStrokeConfig({ ...bs, color: '#2563eb' }, '#2563eb');+ const engine = new BristleRibbonEngine(cfg);++ const p0: Point = { x: 40, y: 120, pressure: 0.8, width: 44 };+ const c1: Point = { x: 140, y: 120, pressure: 0.8, width: 44 };+ const c2: Point = { x: 140, y: 100, pressure: 0.8, width: 44 };+ const p3: Point = { x: 40, y: 100, pressure: 0.8, width: 44 };++ const init = engine.emitInitialStamp(p0);+ expect(init.count).toBeGreaterThan(0);++ const batch = engine.emitCubicSegment(p0, c1, c2, p3);+ expect(batch.count).toBeGreaterThan(cfg.bristle.count);+ for (let s = 0; s < batch.count; s++) {+ const base = s * BRISTLE_SEG_STRIDE;+ for (let k = 0; k < BRISTLE_SEG_STRIDE; k++) {+ expect(Number.isFinite(batch.data[base + k])).toBe(true);+ }+ }+ });++ it('evaluates all 4 grainMappingMode spatial modes and physical paint-to-canvas-tooth valley fill vs dry-brush skip', () => {+ const baseParams = {+ surfaceId: 'linen-canvas' as SurfaceTextureId,+ customTex: null,+ dualGrainDepth: 0,+ grainDepth: 0.7,+ scale: 1.0,+ rotateRad: 0,+ contrast: 0,+ brightness: 0,+ inverted: false,+ strokeOffsetX: 117,+ strokeOffsetY: 203,+ strokeCos: Math.cos(1.1),+ strokeSin: Math.sin(1.1),+ };++ const hCanvasLocked = evaluateMappedSurfaceHeight(+ { ...baseParams, mappingMode: 'canvas-locked' },+ 42, 68, 120, 0.3, 24, 0.6, 0.8+ );+ const hBrushAligned = evaluateMappedSurfaceHeight(+ { ...baseParams, mappingMode: 'brush-aligned' },+ 42, 68, 120, 0.3, 24, 0.6, 0.8+ );+ const hStrokeFlow = evaluateMappedSurfaceHeight(+ { ...baseParams, mappingMode: 'stroke-flow' },+ 42, 68, 120, 0.3, 24, 0.6, 0.8+ );+ const hRandom = evaluateMappedSurfaceHeight(+ { ...baseParams, mappingMode: 'random-per-stroke' },+ 42, 68, 120, 0.3, 24, 0.6, 0.8+ );++ for (const h of [hCanvasLocked, hBrushAligned, hStrokeFlow, hRandom]) {+ expect(h).toBeGreaterThanOrEqual(0);+ expect(h).toBeLessThanOrEqual(1);+ }+ // Distinct mapping modes sample distinct spatial coordinates+ expect(new Set([hCanvasLocked.toFixed(4), hBrushAligned.toFixed(4), hStrokeFlow.toFixed(4), hRandom.toFixed(4)]).size).toBeGreaterThan(2);++ // Physical valley-fill vs valley-skip:+ // Recessed valley (H_canvas = 0.15) with low load + light pressure + dryBrush skips valleys+ const dryValley = evaluatePaintCanvasContact(0.15, 0.18, 0.2, 0.0, 0.65, 0.72);+ // Raised crown (H_canvas = 0.90) with same dry settings deposits crisply+ const dryCrown = evaluatePaintCanvasContact(0.90, 0.18, 0.2, 0.0, 0.65, 0.72);+ // Heavy loaded paint + strong pressure fills the recessed valley much more strongly+ const heavyValley = evaluatePaintCanvasContact(0.15, 0.96, 0.96, 0.0, 0.65, 0.72);++ expect(dryCrown).toBeGreaterThan(dryValley + 0.35);+ expect(heavyValley).toBeGreaterThan(dryValley + 0.35);+ });++ it('produces directional 3D impasto relief shading with higher luminance variance than flat matte paint', () => {+ const pts: Point[] = [+ { x: 30, y: 100, pressure: 0.9, width: 42 },+ { x: 80, y: 95, pressure: 0.95, width: 44 },+ { x: 130, y: 105, pressure: 0.9, width: 42 },+ { x: 180, y: 100, pressure: 0.85, width: 40 },+ ];++ const baseBs: BrushSettings = {+ size: 42,+ minSizeFactor: 0.4,+ color: '#3b82f6',+ opacity: 1,+ flow: 0.95,+ spacing: 0.05,+ usePressure: true,+ smoothing: true,+ stabilization: 0,+ hardness: 0.9,+ renderMode: 'bristle-ribbon',+ bristle: { ...DEFAULT_BRISTLE_SETTINGS, count: 24, clumping: 0.35 },+ naturalPaint: { ...DEFAULT_NATURAL_PAINT_SETTINGS, enabled: true, spatialMixing: false, paintLoad: 0.95, dryBrush: 0.1 },+ surfaceTextureId: 'linen-canvas',+ grain: 0.2,+ useGpu: false,+ };++ const flatCanvas = createHeadlessCanvas(220, 200);+ renderCompleteNaturalPaintStroke(+ flatCanvas.getContext('2d')!,+ pts,+ { ...baseBs, impasto: { ...DEFAULT_IMPASTO_SETTINGS, enabled: false, depth: 0, gloss: 0 } },+ '#3b82f6'+ );++ const impastoCanvas = createHeadlessCanvas(220, 200);+ renderCompleteNaturalPaintStroke(+ impastoCanvas.getContext('2d')!,+ pts,+ { ...baseBs, impasto: { ...DEFAULT_IMPASTO_SETTINGS, enabled: true, depth: 0.9, bristleRelief: 0.9, gloss: 0.75, reliefContrast: 0.85 } },+ '#3b82f6'+ );++ // Measure luminance spread across opaque stroke pixels: impasto relief produces crisp lit ridges & shaded valleys+ const measureLumaRange = (buf: Uint8ClampedArray) => {+ let minL = 255;+ let maxL = 0;+ let count = 0;+ for (let i = 0; i < buf.length; i += 4) {+ if (buf[i + 3] > 200) {+ const l = 0.299 * buf[i] + 0.587 * buf[i + 1] + 0.114 * buf[i + 2];+ if (l < minL) minL = l;+ if (l > maxL) maxL = l;+ count++;+ }+ }+ return { range: maxL - minL, count };+ };++ const flatStats = measureLumaRange(flatCanvas.__buf);+ const impStats = measureLumaRange(impastoCanvas.__buf);++ expect(flatStats.count).toBeGreaterThan(200);+ expect(impStats.count).toBeGreaterThan(200);+ expect(impStats.range).toBeGreaterThan(flatStats.range + 25);++ // Also verify live NaturalPaintStrokeSession anchors cleanly without detached stubs+ // and commits single-tap dabs via flushPendingTapIfNeeded()+ const liveSession = new NaturalPaintStrokeSession(+ { ...baseBs, impasto: { ...DEFAULT_IMPASTO_SETTINGS, enabled: true, depth: 0.8 } },+ '#3b82f6',+ undefined,+ 1337+ );+ const liveCanvas = createHeadlessCanvas(220, 200);+ liveSession.stampInitialPoint(liveCanvas.getContext('2d')!, pts[0], undefined, true);+ expect(liveSession.getDirtyBounds()).toBeNull();+ liveSession.flushPendingTapIfNeeded();+ expect(liveSession.getDirtyBounds()).not.toBeNull();+ liveSession.finishAndDispose();+ });++ it('round-trips Natural Paint brushes cleanly through .inkb v2 while remaining 100% compatible with legacy .inkb v1', () => {+ expect(INKB_VERSION).toBe(2);++ const v2Brush: CspBrush = {+ id: 'natural-custom-1',+ name: 'Studio Impasto Oil',+ category: 'natural-paint',+ badge: 'INKB',+ desc: 'Heavy oil with directional relief',+ size: 48,+ minSizeFactor: 0.35,+ opacity: 1,+ flow: 0.94,+ spacing: 0.05,+ hardness: 0.88,+ thickness: 0.9,+ angle: 12,+ usePressure: true,+ smoothing: true,+ stabilization: 10,+ colorMixing: true,+ mixingMode: 'impasto_mix',+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'stroke-flow',+ dualBrush: true,+ dualScale: 1.4,+ dualAngle: 35,+ dualScatter: 0.25,+ dualSurfaceTextureId: 'coarse-burlap',+ dualGrainDepth: 0.4,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'filbert',+ count: 36,+ clumping: 0.42,+ stiffness: 0.7,+ length: 1.1,+ splay: 0.38,+ irregularity: 0.35,+ edgeRidge: 0.45,+ },+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.92,+ paintLoad: 0.88,+ depletionRate: 0.28,+ wetness: 0.65,+ viscosity: 0.58,+ autoClean: false,+ chargePerPressure: 0.5,+ dryBrush: 0.42,+ granulation: 0.15,+ },+ impasto: {+ enabled: true,+ depth: 0.82,+ bristleRelief: 0.85,+ gloss: 0.64,+ reliefContrast: 0.72,+ lightAzimuth: 280,+ lightElevation: 40,+ },+ bristleSplaySensor: { usePressure: true, pressureMin: 0.2, useTilt: true },+ importedAt: Date.now(),+ };++ const bytes = serializeInkbBrush(v2Brush);+ const ab = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;+ const parsed = parseInkbFile(ab, 'Studio Impasto Oil.inkb');++ expect(parsed.category).toBe('natural-paint');+ expect(parsed.renderMode).toBe('bristle-ribbon');+ expect(parsed.mixingMode).toBe('impasto_mix');+ expect(parsed.surfaceTextureId).toBe('linen-canvas');+ expect(parsed.grainMappingMode).toBe('stroke-flow');+ expect(parsed.dualScale).toBe(1.4);+ expect(parsed.dualAngle).toBe(35);+ expect(parsed.dualSurfaceTextureId).toBe('coarse-burlap');+ expect(parsed.bristle?.count).toBe(36);+ expect(parsed.bristle?.edgeRidge).toBe(0.45);+ expect(parsed.naturalPaint?.spatialMixing).toBe(true);+ expect(parsed.naturalPaint?.autoClean).toBe(false);+ expect(parsed.impasto?.enabled).toBe(true);+ expect(parsed.impasto?.lightAzimuth).toBe(280);+ expect(parsed.bristleSplaySensor?.useTilt).toBe(true);++ // Verify legacy .inkb v1 file still parses seamlessly+ const legacyV1Json = JSON.stringify({+ format: 'inkb',+ version: 1,+ exportedAt: Date.now(),+ brush: { name: 'Legacy G-Pen', size: 10, opacity: 1, flow: 1, spacing: 0.05, hardness: 1, thickness: 1, angle: 0, usePressure: true, smoothing: true, stabilization: 15, minSizeFactor: 0.05 },+ });+ const v1Buf = new TextEncoder().encode(legacyV1Json).buffer as ArrayBuffer;+ const parsedV1 = parseInkbFile(v1Buf, 'Legacy G-Pen.inkb');+ expect(parsedV1.name).toBe('Legacy G-Pen');+ expect(parsedV1.size).toBe(10);+ });++ it('provides all 9 calibrated Natural Paint presets with valid surface textures, bristle profiles, and settings', () => {+ const naturalDefs = BUILTIN_BRUSHES.filter((b) => b.category === 'natural-paint');+ expect(naturalDefs.length).toBe(9);++ for (const def of naturalDefs) {+ const cfg = getBuiltinBrushConfig(def.id);+ expect(cfg).not.toBeNull();+ expect(cfg?.naturalPaint?.enabled).toBe(true);+ expect(cfg?.bristle?.count).toBeGreaterThanOrEqual(16);+ expect(cfg?.surfaceTextureId).toBeTruthy();+ expect(cfg?.renderMode === 'bristle-ribbon' || cfg?.renderMode === 'bristle-hybrid').toBe(true);+ }++ // Verify key distinctive calibrations+ const blender = getBuiltinBrushConfig('oil-bristle-blender')!;+ expect(blender.naturalPaint?.paintLoad).toBe(0);++ const gouache = getBuiltinBrushConfig('velvet-gouache')!;+ expect(gouache.impasto?.gloss).toBeLessThan(0.1);++ const watercolor = getBuiltinBrushConfig('granulating-watercolor')!;+ expect(watercolor.wetEdge).toBeGreaterThan(0.4);+ expect(watercolor.naturalPaint?.granulation).toBeGreaterThan(0.5);++ const knife = getBuiltinBrushConfig('palette-knife-impasto')!;+ expect(knife.bristle?.profile).toBe('knife');+ expect(knife.bristle?.edgeRidge).toBeGreaterThan(0.75);++ // Every Natural Paint preset keeps amountOfPaint and naturalPaint.paintLoad synchronized+ for (const def of naturalDefs) {+ const cfg = getBuiltinBrushConfig(def.id)!;+ expect(cfg.amountOfPaint).toBe(cfg.naturalPaint?.paintLoad);+ }+ });++ it('layers fresh pigment cleanly at max amountOfPaint=1.0 over existing paint and blends smoothly at intermediate loads', () => {+ // Solid opaque dark blue canvas+ const blueCanvas = createHeadlessCanvas(200, 200);+ for (let i = 0; i < blueCanvas.__buf.length; i += 4) {+ blueCanvas.__buf[i] = 16;+ blueCanvas.__buf[i + 1] = 32;+ blueCanvas.__buf[i + 2] = 180;+ blueCanvas.__buf[i + 3] = 255;+ }++ const basePreset = getEffectiveBrushSettings('wet-mixing-filbert') as BrushSettings;+ const strokePts: Point[] = [+ { x: 20, y: 100, pressure: 0.9, width: 48 },+ { x: 70, y: 100, pressure: 0.9, width: 48 },+ { x: 120, y: 100, pressure: 0.9, width: 48 },+ { x: 170, y: 100, pressure: 0.9, width: 48 },+ ];++ // 1. Even if naturalPaint.paintLoad is still 0.76 and wetness=0.82, setting amountOfPaint=1.0+ // must cleanly layer pure bright yellow over dark blue without collapsing into blue!+ const maxPaintBs: BrushSettings = {+ ...basePreset,+ color: '#facc15',+ amountOfPaint: 1.0,+ };+ const cfgMax = extractBristleStrokeConfig(maxPaintBs, '#facc15');+ expect(cfgMax.naturalPaint.paintLoad).toBe(1.0);+ const engineMax = new BristleRibbonEngine(cfgMax);+ const samplerMax = new LayerPixelSampler(blueCanvas as any);+ engineMax.emitInitialStamp(strokePts[0], samplerMax);+ engineMax.emitCubicSegment(strokePts[0], strokePts[1], strokePts[2], strokePts[3], samplerMax);++ const midBristle = Math.floor(engineMax.reservoir.count / 2);+ expect(engineMax.reservoir.r[midBristle]).toBeGreaterThan(240);+ expect(engineMax.reservoir.g[midBristle]).toBeGreaterThan(195);+ expect(engineMax.reservoir.b[midBristle]).toBeLessThan(30);++ // 2. At intermediate amountOfPaint=0.72, yellow over blue mixes harmoniously into vibrant green+ // instead of getting swallowed into 95% dark blue!+ const midPaintBs: BrushSettings = {+ ...basePreset,+ color: '#facc15',+ amountOfPaint: 0.72,+ naturalPaint: { ...basePreset.naturalPaint!, paintLoad: 0.72, wetness: 0.65 },+ };+ const cfgMid = extractBristleStrokeConfig(midPaintBs, '#facc15');+ const engineMid = new BristleRibbonEngine(cfgMid);+ const samplerMid = new LayerPixelSampler(blueCanvas as any);+ engineMid.emitInitialStamp(strokePts[0], samplerMid);+ engineMid.emitCubicSegment(strokePts[0], strokePts[1], strokePts[2], strokePts[3], samplerMid);++ // Green dominates both red and blue (subtractive Yellow+Blue = Green, not swallowed into pure blue)+ expect(engineMid.reservoir.g[midBristle]).toBeGreaterThan(120);+ expect(engineMid.reservoir.b[midBristle]).toBeLessThan(150);+ });+});diff --git a/src/utils/__tests__/retouchEngine.test.ts b/src/utils/__tests__/retouchEngine.test.tsnew file mode 100644index 0000000..672a4fc--- /dev/null+++ b/src/utils/__tests__/retouchEngine.test.ts@@ -0,0 +1,219 @@+import { describe, it, expect } from 'vitest';+import {+ DEFAULT_RETOUCH_SETTINGS,+ applyRetouchStrokeSegment,+ computeBrushFalloff,+ createRetouchStrokeSession,+} from '../retouchEngine';+import { SparseTileGrid } from '../tileEngine';++function fillRectRgba(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number,+ w: number,+ h: number,+ r: number,+ g: number,+ b: number,+ a: number+): void {+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = r;+ data[i + 1] = g;+ data[i + 2] = b;+ data[i + 3] = a;+ }+ grid.writeImageData(layerId, { data, width: w, height: h }, x, y, 'color-32bit', true);+}++describe('Retouch Engine (Smudge / Blur / Dodge / Burn / Clone Stamp)', () => {+ it('computes smooth radial brush falloff respecting hardness', () => {+ expect(computeBrushFalloff(0, 0.5)).toBe(1);+ expect(computeBrushFalloff(0.4, 0.5)).toBe(1);+ expect(computeBrushFalloff(1.0, 0.5)).toBe(0);+ const mid = computeBrushFalloff(0.75, 0.5);+ expect(mid).toBeGreaterThan(0.2);+ expect(mid).toBeLessThan(0.8);+ });++ it('Smudge drags pigment into adjacent pixels without dark alpha fringes', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ const layerId = 'layer-smudge';+ fillRectRgba(grid, layerId, 10, 30, 30, 40, 255, 0, 0, 255);++ const session = createRetouchStrokeSession({+ mode: 'smudge',+ layerId,+ targetFormat: 'color-32bit',+ alphaLock: false,+ dimensions: dims,+ selectionMask: null,+ });+ const settings = {+ ...DEFAULT_RETOUCH_SETTINGS,+ mode: 'smudge' as const,+ size: 20,+ strength: 85,+ hardness: 80,+ usePressure: false,+ };++ applyRetouchStrokeSegment({ grid, session, pt: { x: 25, y: 50 }, pressure: 1, settings, primaryColor: '#000000' });+ applyRetouchStrokeSegment({ grid, session, pt: { x: 52, y: 50 }, pressure: 1, settings, primaryColor: '#000000' });++ // Smudged pigment should appear past x=40 with pure red hue (no black fringe)+ const smudged = grid.getPixelRGBA(layerId, 46, 50);+ expect(smudged[3]).toBeGreaterThan(40);+ expect(smudged[0]).toBeGreaterThan(220);+ expect(smudged[1]).toBeLessThan(15);+ expect(smudged[2]).toBeLessThan(15);++ // Undoable tile deltas restore original state+ const deltas = grid.computeDeltasFromSnapshot(session.beforeSnapshot, layerId, session.dirtyRect!);+ expect(deltas.length).toBeGreaterThan(0);+ grid.applyTileDeltas(deltas, 'undo');+ expect(grid.getPixelRGBA(layerId, 46, 50)[3]).toBe(0);+ });++ it('Blur softens sharp color transitions via separable premultiplied pass', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 100, height: 100 };+ const layerId = 'layer-blur';+ fillRectRgba(grid, layerId, 0, 0, 50, 100, 0, 0, 0, 255);+ fillRectRgba(grid, layerId, 50, 0, 50, 100, 255, 255, 255, 255);++ const session = createRetouchStrokeSession({+ mode: 'blur',+ layerId,+ targetFormat: 'color-32bit',+ alphaLock: false,+ dimensions: dims,+ selectionMask: null,+ });+ const settings = {+ ...DEFAULT_RETOUCH_SETTINGS,+ mode: 'blur' as const,+ size: 30,+ strength: 100,+ hardness: 100,+ usePressure: false,+ };++ applyRetouchStrokeSegment({ grid, session, pt: { x: 50, y: 50 }, pressure: 1, settings, primaryColor: '#000000' });++ const edgeLeft = grid.getPixelRGBA(layerId, 49, 50)[0];+ const edgeRight = grid.getPixelRGBA(layerId, 50, 50)[0];+ expect(edgeLeft).toBeGreaterThan(30);+ expect(edgeRight).toBeLessThan(225);+ });++ it('Dodge lightens and Burn darkens pixels while respecting tonal range and transparency', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 100, height: 100 };+ const layerId = 'layer-db';+ fillRectRgba(grid, layerId, 20, 20, 60, 60, 120, 100, 80, 255);++ const dodgeSession = createRetouchStrokeSession({+ mode: 'dodge',+ layerId,+ targetFormat: 'color-32bit',+ alphaLock: false,+ dimensions: dims,+ selectionMask: null,+ });+ applyRetouchStrokeSegment({+ grid,+ session: dodgeSession,+ pt: { x: 40, y: 50 },+ pressure: 1,+ settings: {+ ...DEFAULT_RETOUCH_SETTINGS,+ mode: 'dodge',+ size: 20,+ strength: 80,+ hardness: 100,+ tonalRange: 'midtones',+ usePressure: false,+ },+ primaryColor: '#000000',+ });++ const dodged = grid.getPixelRGBA(layerId, 40, 50);+ expect(dodged[0]).toBeGreaterThan(135);+ expect(dodged[1]).toBeGreaterThan(110);++ const burnSession = createRetouchStrokeSession({+ mode: 'burn',+ layerId,+ targetFormat: 'color-32bit',+ alphaLock: false,+ dimensions: dims,+ selectionMask: null,+ });+ applyRetouchStrokeSegment({+ grid,+ session: burnSession,+ pt: { x: 65, y: 50 },+ pressure: 1,+ settings: {+ ...DEFAULT_RETOUCH_SETTINGS,+ mode: 'burn',+ size: 20,+ strength: 80,+ hardness: 100,+ tonalRange: 'midtones',+ usePressure: false,+ },+ primaryColor: '#000000',+ });++ const burned = grid.getPixelRGBA(layerId, 65, 50);+ expect(burned[0]).toBeLessThan(105);+ // Transparent region stays untouched+ expect(grid.getPixelRGBA(layerId, 5, 5)[3]).toBe(0);+ });++ it('Clone Stamp copies pixels cleanly from offset source anchor without self-feedback', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ const layerId = 'layer-clone';+ fillRectRgba(grid, layerId, 10, 10, 24, 24, 30, 210, 90, 255);++ const session = createRetouchStrokeSession({+ mode: 'clone-stamp',+ layerId,+ targetFormat: 'color-32bit',+ alphaLock: false,+ dimensions: dims,+ selectionMask: null,+ // Source (22,22) -> Dest (80,80) => offset (-58, -58)+ cloneOffset: { x: -58, y: -58 },+ });++ applyRetouchStrokeSegment({+ grid,+ session,+ pt: { x: 80, y: 80 },+ pressure: 1,+ settings: {+ ...DEFAULT_RETOUCH_SETTINGS,+ mode: 'clone-stamp',+ size: 20,+ strength: 100,+ hardness: 100,+ usePressure: false,+ },+ primaryColor: '#000000',+ });++ const cloned = grid.getPixelRGBA(layerId, 80, 80);+ expect(cloned[0]).toBe(30);+ expect(cloned[1]).toBe(210);+ expect(cloned[2]).toBe(90);+ expect(cloned[3]).toBe(255);+ });+});diff --git a/src/utils/__tests__/selectionAndTransform.test.ts b/src/utils/__tests__/selectionAndTransform.test.tsindex f5d4d89..b77b532 100644--- a/src/utils/__tests__/selectionAndTransform.test.ts+++ b/src/utils/__tests__/selectionAndTransform.test.ts@@ -8,14 +8,21 @@ import {maskToSvgPath,floodSelectWand,liftSelectionToFloating,+ clearSelectionInTileGrid,+ clearOutsideSelectionInTileGrid,+ extractSelectionTileSnapshot,} from '../selectionUtils';+import { SparseTileGrid } from '../tileEngine';import {solveUnitSquareToQuad,evaluateHomography,createDefaultPerspectiveQuad,createDefaultMeshPoints,+ computeMeshSubdivisions,evaluateMeshSurface,expandTriangleOutward,+ getPointsBounds,+ getMeshSurfaceBounds,renderMeshWarp,} from '../transformEngine';@@ -162,15 +169,47 @@ describe('Perspective and Mesh Transformation Engine', () => {expect(p01.y).toBeCloseTo(110, 3);});- it('generates bicubic mesh lattice and samples surface', () => {+ it('generates exact identity bicubic mesh lattice without rounding distortion', () => {const quad = createDefaultPerspectiveQuad(0, 0, 100, 100, 0);const mesh = createDefaultMeshPoints(quad, 4, 4);expect(mesh.length).toBe(4);expect(mesh[0].length).toBe(4);- const mid = evaluateMeshSurface(mesh, 0.5, 0.5);- expect(mid.x).toBeCloseTo(50, 1);- expect(mid.y).toBeCloseTo(50, 1);+ // Interior control points must not be rounded (100/3 = 33.333..., not 33)+ expect(mesh[0][1].x).toBeCloseTo(100 / 3, 6);+ expect(mesh[0][2].x).toBeCloseTo(200 / 3, 6);++ for (const u of [0, 0.17, 0.33, 0.5, 0.73, 1]) {+ for (const v of [0, 0.21, 0.5, 0.84, 1]) {+ const pt = evaluateMeshSurface(mesh, u, v);+ expect(pt.x).toBeCloseTo(u * 100, 5);+ expect(pt.y).toBeCloseTo(v * 100, 5);+ }+ }+ });++ it('captures Catmull-Rom overshoot in getMeshSurfaceBounds and avoids 1px clipping in getPointsBounds', () => {+ const b = getPointsBounds([+ { x: 10.6, y: 20.7 },+ { x: 109.2, y: 80.1 },+ ]);+ expect(b.minX).toBe(10);+ expect(b.maxX).toBe(110);+ expect(b.width).toBe(100);+ expect(b.minY).toBe(20);+ expect(b.maxY).toBe(81);+ expect(b.height).toBe(61);++ // Pull inner columns outward so Catmull-Rom bows past outer edge+ const quad = createDefaultPerspectiveQuad(0, 0, 100, 100, 0);+ const mesh = createDefaultMeshPoints(quad, 4, 4);+ mesh[1][1].x -= 40;+ mesh[1][2].x += 40;+ const ctrlBounds = getPointsBounds(mesh.flat());+ const surfBounds = getMeshSurfaceBounds(mesh, 6);+ expect(surfBounds.minX).toBeLessThanOrEqual(ctrlBounds.minX);+ expect(surfBounds.maxX).toBeGreaterThanOrEqual(ctrlBounds.maxX);+ expect(computeMeshSubdivisions(1024, 1024, mesh, true)).toBeGreaterThanOrEqual(10);});it('expands adjacent quad triangles strictly outward across their shared diagonal', () => {@@ -456,3 +495,195 @@ describe('liftSelectionToFloating integrity (no duplication or out-of-bounds art}});});++describe('Tile-Native Lasso Cut/Copy/Paste and Delete Inside/Outside', () => {+ const fillSolidRect = (+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number,+ w: number,+ h: number,+ rgba: [number, number, number, number],+ format: 'color-32bit' | 'monochrome-1bit' = 'color-32bit'+ ) => {+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < w * h; i++) {+ data[i * 4] = rgba[0];+ data[i * 4 + 1] = rgba[1];+ data[i * 4 + 2] = rgba[2];+ data[i * 4 + 3] = rgba[3];+ }+ grid.writeImageData(layerId, { data, width: w, height: h }, x, y, format, true);+ };++ it('cuts a lasso polygon section from a single layer, pastes into a new layer, and atomically undoes', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 512, height: 512 };+ // Paint a 100x100 red block at (10, 10)+ fillSolidRect(grid, 'layer-1', 10, 10, 100, 100, [220, 40, 60, 255]);++ // Lasso triangle inside the block: (20,20) -> (80,20) -> (20,80)+ const lassoSelection = {+ type: 'lasso' as const,+ bounds: { x: 20, y: 20, width: 60, height: 60 },+ polygon: [+ { x: 20, y: 20 },+ { x: 80, y: 20 },+ { x: 20, y: 80 },+ ],+ };++ // 1. Extract selected pixels+ const snapshot = extractSelectionTileSnapshot({+ grid,+ layerId: 'layer-1',+ dimensions: dims,+ selection: lassoSelection,+ });+ expect(snapshot).not.toBeNull();+ expect(snapshot!.tiles.length).toBe(1);++ // 2. Clear selected pixels from source layer (Cut)+ const cleared = clearSelectionInTileGrid({+ grid,+ layerId: 'layer-1',+ dimensions: dims,+ selection: lassoSelection,+ isBackground: false,+ targetFormat: 'color-32bit',+ });+ expect(cleared.tileDeltas.length).toBeGreaterThan(0);++ // 3. Paste snapshot into new layer+ grid.pasteLayerTilesSnapshot('layer-cut', snapshot!);+ const destDeltas = grid.computeDeltasFromSnapshot(new Map(), 'layer-cut', snapshot!.bounds);+ expect(destDeltas.length).toBeGreaterThan(0);++ // Inside triangle (30, 30): erased from source, present in new layer+ expect(grid.getPixelRGBA('layer-1', 30, 30)[3]).toBe(0);+ expect(Array.from(grid.getPixelRGBA('layer-cut', 30, 30))).toEqual([220, 40, 60, 255]);++ // Outside triangle but inside bounds (70, 70): still in source, empty in new layer+ expect(Array.from(grid.getPixelRGBA('layer-1', 70, 70))).toEqual([220, 40, 60, 255]);+ expect(grid.getPixelRGBA('layer-cut', 70, 70)[3]).toBe(0);++ // Atomic undo restores source and clears new layer+ const combined = [...cleared.tileDeltas, ...destDeltas];+ grid.applyTileDeltas(combined, 'undo');+ expect(Array.from(grid.getPixelRGBA('layer-1', 30, 30))).toEqual([220, 40, 60, 255]);+ expect(grid.getPixelRGBA('layer-cut', 30, 30)[3]).toBe(0);++ // Redo reapplies both+ grid.applyTileDeltas(combined, 'redo');+ expect(grid.getPixelRGBA('layer-1', 30, 30)[3]).toBe(0);+ expect(Array.from(grid.getPixelRGBA('layer-cut', 30, 30))).toEqual([220, 40, 60, 255]);+ });++ it('returns null when extracting an empty selection region', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 256, height: 256 };+ fillSolidRect(grid, 'layer-1', 0, 0, 20, 20, [0, 0, 0, 255]);++ const emptySnap = extractSelectionTileSnapshot({+ grid,+ layerId: 'layer-1',+ dimensions: dims,+ selection: { type: 'rect', bounds: { x: 100, y: 100, width: 40, height: 40 } },+ });+ expect(emptySnap).toBeNull();+ });++ it('deletes outside a lasso selection across multiple tiles and restores on undo', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 600, height: 600 };+ // Paint in tile (0,0) and tile (1,1)+ fillSolidRect(grid, 'layer-1', 10, 10, 100, 100, [10, 200, 30, 255]);+ fillSolidRect(grid, 'layer-1', 300, 300, 50, 50, [10, 200, 30, 255]);++ const lassoSelection = {+ type: 'lasso' as const,+ bounds: { x: 20, y: 20, width: 60, height: 60 },+ polygon: [+ { x: 20, y: 20 },+ { x: 80, y: 20 },+ { x: 20, y: 80 },+ ],+ };++ const { tileDeltas } = clearOutsideSelectionInTileGrid({+ grid,+ layerId: 'layer-1',+ dimensions: dims,+ selection: lassoSelection,+ isBackground: false,+ targetFormat: 'color-32bit',+ });++ expect(tileDeltas.length).toBeGreaterThanOrEqual(2);+ // Inside triangle remains intact+ expect(Array.from(grid.getPixelRGBA('layer-1', 30, 30))).toEqual([10, 200, 30, 255]);+ // Outside triangle in same tile is erased+ expect(grid.getPixelRGBA('layer-1', 70, 70)[3]).toBe(0);+ // Separate tile (1,1) completely outside selection is pruned+ expect(grid.getPixelRGBA('layer-1', 310, 310)[3]).toBe(0);+ expect(grid.getTile('layer-1', 1, 1, 0)).toBeNull();++ // Undo restores both tiles+ grid.applyTileDeltas(tileDeltas, 'undo');+ expect(Array.from(grid.getPixelRGBA('layer-1', 70, 70))).toEqual([10, 200, 30, 255]);+ expect(Array.from(grid.getPixelRGBA('layer-1', 310, 310))).toEqual([10, 200, 30, 255]);+ });++ it('fills outside with white on background layer and preserves feathered mask alpha on normal layer', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 64, height: 64 };+ grid.fillLayerSolidWhite('layer-bg', 64, 64, 'color-32bit');+ fillSolidRect(grid, 'layer-bg', 0, 0, 64, 64, [255, 0, 0, 255]);++ const mask = new Uint8Array(64 * 64);+ for (let y = 16; y < 32; y++) {+ for (let x = 16; x < 32; x++) {+ mask[y * 64 + x] = 255;+ }+ }++ clearOutsideSelectionInTileGrid({+ grid,+ layerId: 'layer-bg',+ dimensions: dims,+ selection: {+ type: 'mask',+ bounds: { x: 16, y: 16, width: 16, height: 16 },+ mask,+ maskWidth: 64,+ maskHeight: 64,+ },+ isBackground: true,+ targetFormat: 'color-32bit',+ });++ // Inside mask stays red; outside becomes opaque white+ expect(Array.from(grid.getPixelRGBA('layer-bg', 20, 20))).toEqual([255, 0, 0, 255]);+ expect(Array.from(grid.getPixelRGBA('layer-bg', 5, 5))).toEqual([255, 255, 255, 255]);+ });++ it('preserves 1-bit monochrome format when extracting a selection', () => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ fillSolidRect(grid, 'mono-1', 10, 10, 40, 40, [0, 0, 0, 255], 'monochrome-1bit');++ const snap = extractSelectionTileSnapshot({+ grid,+ layerId: 'mono-1',+ dimensions: dims,+ selection: { type: 'rect', bounds: { x: 15, y: 15, width: 20, height: 20 } },+ });+ expect(snap).not.toBeNull();+ expect(snap!.format).toBe('monochrome-1bit');+ grid.pasteLayerTilesSnapshot('mono-2', snap!);+ expect(grid.getLayerFormat('mono-2')).toBe('monochrome-1bit');+ expect(grid.getPixelRGBA('mono-2', 20, 20)[3]).toBe(255);+ expect(grid.getPixelRGBA('mono-2', 12, 12)[3]).toBe(0);+ });+});diff --git a/src/utils/__tests__/sphereColorPicker.test.ts b/src/utils/__tests__/sphereColorPicker.test.tsnew file mode 100644index 0000000..93f167e--- /dev/null+++ b/src/utils/__tests__/sphereColorPicker.test.ts@@ -0,0 +1,275 @@+import { describe, it, expect, vi } from 'vitest';+import {+ DEFAULT_SPHERE_LIGHTING,+ DEFAULT_SPHERE_SLOTS,+ MAX_MARKER_RADIUS,+ SPHERE_LIGHTING_PRESETS,+ buildSphereGeometryLut,+ clampMarkerPosition,+ evaluateSphereColor,+ projectSphereMarker,+ renderSphereFromLut,+ updateSphereLightingLut,+} from '../sphereColorMath';+import { rgbToHex } from '../colorUtils';++describe('sphereColorMath', () => {+ it('produces bright highlight, base midtone, and painterly chromatic shadow (not black)', () => {+ const slots = {+ shadow: { h: 225, s: 0.65, v: 0.5 }, // vivid cool blue shadow+ base: { h: 150, s: 0.3, v: 0.65 }, // sage base+ light: { h: 45, s: 0.25, v: 0.98 }, // warm highlight+ };++ const highlight = evaluateSphereColor({ x: -0.45, y: 0.55 }, slots, DEFAULT_SPHERE_LIGHTING);+ const midtone = evaluateSphereColor({ x: 0, y: 0 }, slots, DEFAULT_SPHERE_LIGHTING);+ const shadow = evaluateSphereColor({ x: 0.65, y: -0.45 }, slots, DEFAULT_SPHERE_LIGHTING);++ const lum = (c: { r: number; g: number; b: number }) => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+ expect(lum(highlight.rgb)).toBeGreaterThan(lum(midtone.rgb));+ expect(lum(midtone.rgb)).toBeGreaterThan(lum(shadow.rgb));++ // Shadow must be deeply sculpted like reference (not washed out) yet painterly blue-tinted (not black)+ expect(lum(shadow.rgb)).toBeGreaterThan(8);+ expect(lum(shadow.rgb)).toBeLessThan(70);+ expect(shadow.rgb.b).toBeGreaterThan(shadow.rgb.r);++ // HEX and RGB stay strictly synchronized+ expect(highlight.hex).toBe(rgbToHex(highlight.rgb.r, highlight.rgb.g, highlight.rgb.b));+ expect(midtone.hex).toBe(rgbToHex(midtone.rgb.r, midtone.rgb.g, midtone.rgb.b));+ expect(shadow.hex).toBe(rgbToHex(shadow.rgb.r, shadow.rgb.g, shadow.rgb.b));+ });++ it('adds soft bounce light along the bottom shadow edge when enabled', () => {+ const noBounce = evaluateSphereColor(+ { x: 0.25, y: -0.82 },+ DEFAULT_SPHERE_SLOTS,+ { ...DEFAULT_SPHERE_LIGHTING, bounceIntensity: 0 }+ );+ const withBounce = evaluateSphereColor(+ { x: 0.25, y: -0.82 },+ DEFAULT_SPHERE_SLOTS,+ { ...DEFAULT_SPHERE_LIGHTING, bounceIntensity: 0.55 }+ );++ const sum = (c: { r: number; g: number; b: number }) => c.r + c.g + c.b;+ expect(sum(withBounce.rgb)).toBeGreaterThan(sum(noBounce.rgb));+ });++ it('dynamically shifts sphere shading when shadow, base, or light hue changes', () => {+ const warmShadow = evaluateSphereColor(+ { x: 0.68, y: -0.4 },+ { ...DEFAULT_SPHERE_SLOTS, shadow: { h: 10, s: 0.7, v: 0.5 } },+ DEFAULT_SPHERE_LIGHTING+ );+ const coolShadow = evaluateSphereColor(+ { x: 0.68, y: -0.4 },+ { ...DEFAULT_SPHERE_SLOTS, shadow: { h: 220, s: 0.7, v: 0.5 } },+ DEFAULT_SPHERE_LIGHTING+ );+ expect(warmShadow.rgb.r).toBeGreaterThan(coolShadow.rgb.r);+ expect(coolShadow.rgb.b).toBeGreaterThan(warmShadow.rgb.b);+ });++ it('foreshortens the 3D marker disc into an ellipse near edges and clamps drag coordinates', () => {+ const center = projectSphereMarker({ x: 0, y: 0 }, 240, 0.465, DEFAULT_SPHERE_LIGHTING);+ const edge = projectSphereMarker({ x: 0.85, y: 0 }, 240, 0.465, DEFAULT_SPHERE_LIGHTING);++ expect(center.rx).toBeCloseTo(center.ry, 3);+ expect(center.extrudeShift).toBeCloseTo(0, 3);++ expect(edge.ry).toBeLessThan(edge.rx * 0.6);+ expect(edge.extrudeShift).toBeGreaterThan(2);++ const clamped = clampMarkerPosition(2.5, -2.5);+ expect(Math.hypot(clamped.x, clamped.y)).toBeCloseTo(MAX_MARKER_RADIUS, 5);+ });++ it('matches LUT rendered canvas pixels with evaluateSphereColor at center within dither tolerance', () => {+ const size = 120;+ const lut = buildSphereGeometryLut(size, size, 0.465);+ updateSphereLightingLut(lut, DEFAULT_SPHERE_LIGHTING);++ const buffer = new Uint8ClampedArray(size * size * 4);+ const mockCtx = {+ createImageData: vi.fn((w: number, h: number) => ({+ width: w,+ height: h,+ data: buffer,+ })),+ putImageData: vi.fn(),+ } as unknown as CanvasRenderingContext2D;++ renderSphereFromLut(mockCtx, lut, DEFAULT_SPHERE_SLOTS, DEFAULT_SPHERE_LIGHTING);+ expect(mockCtx.putImageData).toHaveBeenCalledTimes(1);++ const cx = Math.floor(size / 2);+ const cy = Math.floor(size / 2);+ const offset = (cy * size + cx) * 4;+ const centerEval = evaluateSphereColor({ x: 0, y: 0 }, DEFAULT_SPHERE_SLOTS, DEFAULT_SPHERE_LIGHTING);++ expect(Math.abs(buffer[offset] - centerEval.rgb.r)).toBeLessThanOrEqual(3);+ expect(Math.abs(buffer[offset + 1] - centerEval.rgb.g)).toBeLessThanOrEqual(3);+ expect(Math.abs(buffer[offset + 2] - centerEval.rgb.b)).toBeLessThanOrEqual(3);+ expect(buffer[offset + 3]).toBe(255);+ });++ it('adjusts light brightness/dimness via lightIntensity across the sphere', () => {+ const dim = evaluateSphereColor(+ { x: -0.25, y: 0.3 },+ DEFAULT_SPHERE_SLOTS,+ { ...DEFAULT_SPHERE_LIGHTING, lightIntensity: 0.25 }+ );+ const neutral = evaluateSphereColor(+ { x: -0.25, y: 0.3 },+ DEFAULT_SPHERE_SLOTS,+ { ...DEFAULT_SPHERE_LIGHTING, lightIntensity: 1.0 }+ );+ const bright = evaluateSphereColor(+ { x: -0.25, y: 0.3 },+ DEFAULT_SPHERE_SLOTS,+ { ...DEFAULT_SPHERE_LIGHTING, lightIntensity: 1.85 }+ );++ const lum = (c: { r: number; g: number; b: number }) => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+ expect(lum(dim.rgb)).toBeLessThan(lum(neutral.rgb));+ expect(lum(neutral.rgb)).toBeLessThan(lum(bright.rgb));+ });++ it('produces pure neutral grayscale across all lighting zones when saturation is 0 (B&W mode)', () => {+ const vividSlots = {+ shadow: { h: 240, s: 0.85, v: 0.45 },+ base: { h: 12, s: 0.8, v: 0.7 },+ light: { h: 55, s: 0.7, v: 0.98 },+ };+ const bwConfig = { ...DEFAULT_SPHERE_LIGHTING, saturation: 0 };++ for (const pt of [+ { x: -0.45, y: 0.5 },+ { x: 0, y: 0 },+ { x: 0.65, y: -0.45 },+ ]) {+ const res = evaluateSphereColor(pt, vividSlots, bwConfig);+ expect(res.rgb.r).toBe(res.rgb.g);+ expect(res.rgb.g).toBe(res.rgb.b);+ }+ });++ it('adjusts tonal spread and shadow depth via contrast', () => {+ const lum = (c: { r: number; g: number; b: number }) => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+ const lowCtrHi = evaluateSphereColor({ x: -0.4, y: 0.5 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ contrast: 0.5,+ });+ const lowCtrSh = evaluateSphereColor({ x: 0.65, y: -0.45 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ contrast: 0.5,+ });+ const highCtrHi = evaluateSphereColor({ x: -0.4, y: 0.5 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ contrast: 1.8,+ });+ const highCtrSh = evaluateSphereColor({ x: 0.65, y: -0.45 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ contrast: 1.8,+ });++ const lowSpread = lum(lowCtrHi.rgb) - lum(lowCtrSh.rgb);+ const highSpread = lum(highCtrHi.rgb) - lum(highCtrSh.rgb);++ expect(lum(highCtrSh.rgb)).toBeLessThan(lum(lowCtrSh.rgb));+ expect(highSpread).toBeGreaterThan(lowSpread);+ });++ it('produces vivid non-dim colored key lighting via lightTint (Crimson Mood)', () => {+ const crimson = SPHERE_LIGHTING_PRESETS.find((p) => p.id === 'crimson-mood');+ expect(crimson).toBeDefined();++ const lighting = { ...DEFAULT_SPHERE_LIGHTING, ...crimson!.lighting };+ const slots = {+ ...DEFAULT_SPHERE_SLOTS,+ ...crimson!.slots,+ };++ const spec = evaluateSphereColor({ x: -0.35, y: 0.3 }, slots, lighting);+ const lit = evaluateSphereColor({ x: -0.5, y: 0.08 }, slots, lighting);+ const shadow = evaluateSphereColor({ x: 0.65, y: -0.45 }, slots, lighting);++ // Crisp bright wet highlight peak+ expect(spec.rgb.r).toBeGreaterThan(230);+ // Vivid saturated red lit diffuse zone (not dim, not washed out gray)+ expect(lit.rgb.r).toBeGreaterThan(175);+ expect(lit.rgb.r - lit.rgb.g).toBeGreaterThan(100);+ // Deep dramatic crimson shadow (low luminance, distinctly red-shifted)+ const lum = (c: { r: number; g: number; b: number }) => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;+ expect(lum(shadow.rgb)).toBeLessThan(45);+ expect(shadow.rgb.r).toBeLessThan(105);+ expect(shadow.rgb.r).toBeGreaterThan(shadow.rgb.b);+ });++ it('lifts dimness via ambientIntensity and illuminates silhouette edges via rim slot', () => {+ const lum = (c: { r: number; g: number; b: number }) => 0.299 * c.r + 0.587 * c.g + 0.114 * c.b;++ const darkAmb = evaluateSphereColor({ x: 0.5, y: -0.35 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ ambientIntensity: 0,+ });+ const brightAmb = evaluateSphereColor({ x: 0.5, y: -0.35 }, DEFAULT_SPHERE_SLOTS, {+ ...DEFAULT_SPHERE_LIGHTING,+ ambientIntensity: 0.75,+ });+ expect(lum(brightAmb.rgb)).toBeGreaterThan(lum(darkAmb.rgb) + 40);++ const cyanRimSlots = {+ ...DEFAULT_SPHERE_SLOTS,+ rim: { h: 185, s: 0.98, v: 1.0 },+ };+ const noRim = evaluateSphereColor({ x: 0.92, y: -0.1 }, cyanRimSlots, {+ ...DEFAULT_SPHERE_LIGHTING,+ rimIntensity: 0,+ });+ const strongRim = evaluateSphereColor({ x: 0.92, y: -0.1 }, cyanRimSlots, {+ ...DEFAULT_SPHERE_LIGHTING,+ rimIntensity: 1.2,+ });+ expect(strongRim.rgb.b).toBeGreaterThan(noRim.rgb.b + 40);+ expect(strongRim.rgb.g).toBeGreaterThan(noRim.rgb.g + 40);+ });++ it('adds warm chromatic glow along the terminator via subsurface and stays LUT-synced', () => {+ const crimson = SPHERE_LIGHTING_PRESETS.find((p) => p.id === 'crimson-mood')!;+ const slots = { ...DEFAULT_SPHERE_SLOTS, ...crimson.slots };+ const noSss = evaluateSphereColor({ x: 0.35, y: -0.2 }, slots, {+ ...DEFAULT_SPHERE_LIGHTING,+ ...crimson.lighting,+ subsurface: 0,+ });+ const withSss = evaluateSphereColor({ x: 0.35, y: -0.2 }, slots, {+ ...DEFAULT_SPHERE_LIGHTING,+ ...crimson.lighting,+ subsurface: 0.9,+ });+ expect(withSss.rgb.r).toBeGreaterThan(noSss.rgb.r);++ // Verify LUT render matches evaluateSphereColor under Crimson Mood (all 7 factors active)+ const size = 120;+ const lighting = { ...DEFAULT_SPHERE_LIGHTING, ...crimson.lighting };+ const lut = buildSphereGeometryLut(size, size, 0.465);+ updateSphereLightingLut(lut, lighting);+ const buffer = new Uint8ClampedArray(size * size * 4);+ const mockCtx = {+ createImageData: vi.fn((w: number, h: number) => ({ width: w, height: h, data: buffer })),+ putImageData: vi.fn(),+ } as unknown as CanvasRenderingContext2D;++ renderSphereFromLut(mockCtx, lut, slots, lighting);+ const cx = Math.floor(size / 2);+ const cy = Math.floor(size / 2);+ const offset = (cy * size + cx) * 4;+ const centerEval = evaluateSphereColor({ x: 0, y: 0 }, slots, lighting);++ expect(Math.abs(buffer[offset] - centerEval.rgb.r)).toBeLessThanOrEqual(3);+ expect(Math.abs(buffer[offset + 1] - centerEval.rgb.g)).toBeLessThanOrEqual(3);+ expect(Math.abs(buffer[offset + 2] - centerEval.rgb.b)).toBeLessThanOrEqual(3);+ });+});diff --git a/src/utils/__tests__/strokePipelineIntegration.test.ts b/src/utils/__tests__/strokePipelineIntegration.test.tsindex 453e6f4..1939c6e 100644--- a/src/utils/__tests__/strokePipelineIntegration.test.ts+++ b/src/utils/__tests__/strokePipelineIntegration.test.ts@@ -420,7 +420,9 @@ describe('WebGlBrushEngine Integration & Canvas 2D Fallback in stampEngine', ()expect(canUseWebGlForBrush({ size: 10, antiAlias: 0, useGpu: true, tipImage: mockTipImage })).toBe(false);expect(canUseWebGlForBrush({ size: 10, colorMixing: true, useGpu: true, tipImage: mockTipImage })).toBe(false);expect(canUseWebGlForBrush({ size: 10, useGpu: false, tipImage: mockTipImage })).toBe(false);- expect(canUseWebGlForBrush({ size: 10, tipImage: mockTipImage, subTipImages: [mockTipImage, mockTipImage], useGpu: true })).toBe(false);+ // Multi-subTip now renders in a single WebGL draw call via texture atlas+ expect(canUseWebGlForBrush({ size: 10, tipImage: mockTipImage, subTipImages: [mockTipImage, mockTipImage], useGpu: true })).toBe(true);+ expect(canUseWebGlForBrush({ size: 10, renderMode: 'bristle-ribbon', useGpu: true })).toBe(false);expect(canUseWebGlForBrush({ antiAlias: 0, useGpu: true })).toBe(false);expect(canUseWebGlForBrush({ colorMixing: true, useGpu: true })).toBe(false);diff --git a/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx b/src/utils/__tests__/viewFlipAndZeroRerender.test.tsxindex 787631c..14676ff 100644--- a/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx+++ b/src/utils/__tests__/viewFlipAndZeroRerender.test.tsx@@ -598,6 +598,118 @@ describe('Zero-Rerender Camera Navigation & Non-Destructive View Flip', () => {expect(exposedNav!.pan.y).toBeCloseTo(510, 5);expect(exposedNav!.rotation).toBeCloseTo(28, 5);});++ it('never leaves Space/pan hand cursor stuck on XP-Pen synthetic Space, fast tap, dropped pointerup, or visibilitychange', () => {+ let exposedNav: ReturnType<typeof useCanvasNavigation> | null = null;+ const dims = { width: 1000, height: 800, dpi: 300 };++ function Host() {+ const nav = useCanvasNavigation({ dimensions: dims, activeDocumentId: 'doc-xppen' });+ exposedNav = nav;+ return <div ref={nav.viewportRef as any} />;+ }++ root = createRoot(env.container as unknown as HTMLElement);+ act(() => {+ root!.render(<Host />);+ });++ // 1. XP-Pen synthetic Space (empty code, key === ' ') keydown + repeat + keyup+ act(() => {+ const down1 = new Event('keydown', { bubbles: true, cancelable: true }) as any;+ down1.key = ' ';+ down1.code = '';+ window.dispatchEvent(down1);+ });+ expect(exposedNav!.isSpaceDown).toBe(true);+ expect(exposedNav!.heldModifierAction).toBe('pan');++ act(() => {+ const repeat = new Event('keydown', { bubbles: true, cancelable: true }) as any;+ repeat.key = ' ';+ repeat.code = '';+ repeat.repeat = true;+ window.dispatchEvent(repeat);+ });+ expect(exposedNav!.isSpaceDown).toBe(true);+ expect(exposedNav!.heldModifierAction).toBe('pan');++ act(() => {+ const up = new Event('keyup', { bubbles: true, cancelable: true }) as any;+ up.key = ' ';+ up.code = '';+ window.dispatchEvent(up);+ });+ expect(exposedNav!.isSpaceDown).toBe(false);+ expect(exposedNav!.heldModifierAction).toBe('none');++ // 2. Fast stylus tap: pointerup fires synchronously BEFORE React commits effect+ act(() => {+ exposedNav!.startPan({+ pointerId: 7,+ clientX: 200,+ clientY: 200,+ buttons: 1,+ preventDefault: () => {},+ } as unknown as PointerEvent);+ const upEv = new Event('pointerup', { bubbles: true }) as any;+ upEv.pointerId = 7;+ upEv.buttons = 0;+ window.dispatchEvent(upEv);+ });+ expect(exposedNav!.isPanning).toBe(false);+ expect(document.body.style.cursor).toBe('');++ // 3. Dropped pointerup (pen lifted out of proximity): next hover pointermove with buttons === 0 ends pan+ act(() => {+ exposedNav!.startPan({+ pointerId: 9,+ clientX: 300,+ clientY: 300,+ buttons: 1,+ preventDefault: () => {},+ } as unknown as PointerEvent);+ });+ expect(exposedNav!.isPanning).toBe(true);+ expect(document.body.style.cursor).toBe('grabbing');++ act(() => {+ const hoverMove = new Event('pointermove', { bubbles: true }) as any;+ hoverMove.pointerId = 9;+ hoverMove.clientX = 320;+ hoverMove.clientY = 310;+ hoverMove.buttons = 0;+ window.dispatchEvent(hoverMove);+ });+ expect(exposedNav!.isPanning).toBe(false);+ expect(document.body.style.cursor).toBe('');++ // 4. Tab/window hidden (visibilitychange) clears stuck Space & active pan+ act(() => {+ const down = new Event('keydown', { bubbles: true, cancelable: true }) as any;+ down.code = 'Space';+ down.key = ' ';+ window.dispatchEvent(down);+ exposedNav!.startPan({+ pointerId: 11,+ clientX: 300,+ clientY: 300,+ buttons: 1,+ preventDefault: () => {},+ } as unknown as PointerEvent);+ });+ expect(exposedNav!.isSpaceDown).toBe(true);+ expect(exposedNav!.isPanning).toBe(true);++ act(() => {+ (document as any).hidden = true;+ document.dispatchEvent(new Event('visibilitychange'));+ });+ expect(exposedNav!.isSpaceDown).toBe(false);+ expect(exposedNav!.isPanning).toBe(false);+ expect(exposedNav!.heldModifierAction).toBe('none');+ expect(document.body.style.cursor).toBe('');+ });});describe('Flipped View Brush Stroke Precision & Non-Destructive Layer Guarantee', () => {diff --git a/src/utils/appCloseFlow.ts b/src/utils/appCloseFlow.tsnew file mode 100644index 0000000..da67918--- /dev/null+++ b/src/utils/appCloseFlow.ts@@ -0,0 +1,160 @@+import { DocumentTab } from '../types/editor';+import { isTauriEnvironment } from '../hooks/useMultiplayer';+import { recoveryService } from '../services/recoveryService';+import {+ AppClosePromptState,+ uiStoreActions,+ useDocumentStore,+ useUiStore,+} from '../stores';+import { flushPendingBrushSettingsSave } from './brushPresetManager';++export type SaveDocumentResult = 'saved' | 'canceled' | 'error';++const RECOVERY_CLEANUP_TIMEOUT_MS = 1500;++let finalizingAppClose = false;++export function getUnsavedDocumentIds(documents: readonly DocumentTab[]): string[] {+ return documents.filter((d) => Boolean(d.isDirty)).map((d) => d.id);+}++export function formatCanvasDisplayName(name: string | undefined | null): string {+ const cleaned = (name || '').replace(/\*+$/, '').trim();+ return cleaned || 'Untitled';+}++export function computeInitialClosePromptState(dirtyDocIds: string[]): AppClosePromptState {+ if (dirtyDocIds.length === 0) {+ return {+ isOpen: true,+ step: 'confirm-quit',+ pendingDocIds: [],+ currentIndex: 0,+ isBusy: false,+ };+ }+ if (dirtyDocIds.length === 1) {+ return {+ isOpen: true,+ step: 'per-canvas',+ pendingDocIds: [dirtyDocIds[0]],+ currentIndex: 0,+ isBusy: false,+ };+ }+ return {+ isOpen: true,+ step: 'summary',+ pendingDocIds: [...dirtyDocIds],+ currentIndex: 0,+ isBusy: false,+ };+}++export function findNextPendingDirtyIndex(+ pendingDocIds: readonly string[],+ afterIndex: number,+ documents: readonly DocumentTab[]+): number {+ for (let i = afterIndex + 1; i < pendingDocIds.length; i++) {+ const id = pendingDocIds[i];+ const doc = documents.find((d) => d.id === id);+ if (doc && doc.isDirty) {+ return i;+ }+ }+ return -1;+}++export function isFinalizingAppClose(): boolean {+ return finalizingAppClose;+}++/**+ * Resets internal shutdown guard (for tests).+ */+export function _resetAppCloseFlowForTests(): void {+ finalizingAppClose = false;+}++/**+ * Initiates the app-close confirmation workflow.+ * No-ops if a close prompt is already open or shutdown is already underway.+ */+export function requestAppClose(): boolean {+ if (finalizingAppClose) return false;+ if (useUiStore.getState().appClosePrompt.isOpen) return false;++ const dirtyIds = getUnsavedDocumentIds(useDocumentStore.getState().documents);+ uiStoreActions.setAppClosePrompt(computeInitialClosePromptState(dirtyIds));+ return true;+}++export function cancelAppClose(): boolean {+ if (finalizingAppClose) return false;+ if (useUiStore.getState().appClosePrompt.isBusy) return false;+ uiStoreActions.resetAppClosePrompt();+ return true;+}++export interface FinalizeAppCloseDeps {+ isTauri?: () => boolean;+ destroyTauriWindow?: () => Promise<void>;+ closeBrowserWindow?: () => void;+ closeRecoverySession?: (docId: string) => Promise<void>;+ flushBrushSettings?: () => void;+}++async function destroyNativeWindow(): Promise<void> {+ const { getCurrentWindow } = await import('@tauri-apps/api/window');+ await getCurrentWindow().destroy();+}++/**+ * Performs clean shutdown: flushes brush settings, closes active recovery sessions+ * (so intentionally closed/discarded canvases do not trigger crash recovery next launch),+ * and destroys the window.+ */+export async function finalizeAppClose(deps: FinalizeAppCloseDeps = {}): Promise<void> {+ if (finalizingAppClose) return;+ finalizingAppClose = true;++ uiStoreActions.setAppClosePrompt((prev) => ({ ...prev, isBusy: true }));++ const flushBrush = deps.flushBrushSettings ?? flushPendingBrushSettingsSave;+ const closeRecovery =+ deps.closeRecoverySession ?? ((id: string) => recoveryService.closeSession(id));+ const checkTauri = deps.isTauri ?? isTauriEnvironment;++ try {+ flushBrush();++ const openDocIds = useDocumentStore.getState().documents.map((d) => d.id);+ if (openDocIds.length > 0) {+ let timerId: ReturnType<typeof setTimeout> | null = null;+ const cleanupAll = Promise.allSettled(openDocIds.map((id) => closeRecovery(id)));+ const timeout = new Promise<void>((resolve) => {+ timerId = setTimeout(resolve, RECOVERY_CLEANUP_TIMEOUT_MS);+ });+ await Promise.race([cleanupAll, timeout]);+ if (timerId !== null) clearTimeout(timerId);+ }++ if (checkTauri()) {+ const destroy = deps.destroyTauriWindow ?? destroyNativeWindow;+ await destroy();+ } else {+ uiStoreActions.resetAppClosePrompt();+ const closeWin = deps.closeBrowserWindow ?? (() => window.close());+ closeWin();+ // In browsers where window.close() is blocked for user-opened tabs, allow future attempts.+ finalizingAppClose = false;+ }+ } catch (err) {+ console.error('Failed to close application window:', err);+ finalizingAppClose = false;+ uiStoreActions.setAppClosePrompt((prev) => ({ ...prev, isBusy: false }));+ uiStoreActions.showToast('Failed to close window');+ }+}diff --git a/src/utils/bezierEngine.ts b/src/utils/bezierEngine.tsnew file mode 100644index 0000000..18380a4--- /dev/null+++ b/src/utils/bezierEngine.ts@@ -0,0 +1,595 @@+/**+ * True Cubic Bézier Curve Engine+ *+ * Implements exact Bernstein evaluation, analytical extrema bounding boxes,+ * de Casteljau subdivision (zero-distortion anchor insertion & splitting),+ * closest-point projection, adaptive tessellation, and handle constraint math.+ */++import type { BezierHandleType, Point2D, VectorKnot, VectorStroke } from '../types/editor';++export interface CubicSegment {+ p0: Point2D;+ c1: Point2D;+ c2: Point2D;+ p3: Point2D;+}++export interface EvaluatedBezierPoint {+ x: number;+ y: number;+ dx: number;+ dy: number;+ pressure: number;+ width: number;+}++export interface BezierSplitResult {+ leftC1: Point2D;+ leftC2: Point2D;+ mid: Point2D;+ rightC1: Point2D;+ rightC2: Point2D;+}++export interface BezierClosestHit {+ segmentIndex: number;+ t: number;+ point: Point2D;+ distance: number;+}++function clamp01(v: number): number {+ return v < 0 ? 0 : v > 1 ? 1 : v;+}++function isFinitePoint(p: Point2D | null | undefined): p is Point2D {+ return Boolean(p && Number.isFinite(p.x) && Number.isFinite(p.y));+}++/**+ * Resolves the 4 cubic Bézier control points between knot `k1` and knot `k2`.+ * Missing handles collapse onto their owning anchor, producing a linear or quadratic-equivalent cubic.+ */+export function getSegmentControlPoints(k1: VectorKnot, k2: VectorKnot): CubicSegment {+ const p0 = { x: k1.x, y: k1.y };+ const p3 = { x: k2.x, y: k2.y };+ const c1 = isFinitePoint(k1.handleOut) ? { x: k1.handleOut.x, y: k1.handleOut.y } : p0;+ const c2 = isFinitePoint(k2.handleIn) ? { x: k2.handleIn.x, y: k2.handleIn.y } : p3;+ return { p0, c1, c2, p3 };+}++/**+ * Evaluates a cubic Bézier curve and its first derivative at parameter t in [0, 1].+ */+export function evaluateCubicBezier(+ p0: Point2D,+ c1: Point2D,+ c2: Point2D,+ p3: Point2D,+ t: number,+ w0 = 2,+ w1 = 2,+ pr0 = 1,+ pr1 = 1+): EvaluatedBezierPoint {+ const u = clamp01(t);+ const inv = 1 - u;+ const inv2 = inv * inv;+ const inv3 = inv2 * inv;+ const u2 = u * u;+ const u3 = u2 * u;++ const x = inv3 * p0.x + 3 * inv2 * u * c1.x + 3 * inv * u2 * c2.x + u3 * p3.x;+ const y = inv3 * p0.y + 3 * inv2 * u * c1.y + 3 * inv * u2 * c2.y + u3 * p3.y;++ const dx =+ 3 * inv2 * (c1.x - p0.x) ++ 6 * inv * u * (c2.x - c1.x) ++ 3 * u2 * (p3.x - c2.x);+ const dy =+ 3 * inv2 * (c1.y - p0.y) ++ 6 * inv * u * (c2.y - c1.y) ++ 3 * u2 * (p3.y - c2.y);++ return {+ x,+ y,+ dx,+ dy,+ width: Math.max(0.5, w0 + (w1 - w0) * u),+ pressure: clamp01(pr0 + (pr1 - pr0) * u),+ };+}++/**+ * Exact de Casteljau subdivision of a cubic Bézier segment at parameter t in [0, 1].+ * Preserves the exact curve geometry across both sub-segments.+ */+export function splitCubicBezier(+ p0: Point2D,+ c1: Point2D,+ c2: Point2D,+ p3: Point2D,+ t: number+): BezierSplitResult {+ const u = clamp01(t);+ const lerp = (a: Point2D, b: Point2D): Point2D => ({+ x: a.x + (b.x - a.x) * u,+ y: a.y + (b.y - a.y) * u,+ });++ const p01 = lerp(p0, c1);+ const p12 = lerp(c1, c2);+ const p23 = lerp(c2, p3);+ const p012 = lerp(p01, p12);+ const p123 = lerp(p12, p23);+ const mid = lerp(p012, p123);++ return {+ leftC1: p01,+ leftC2: p012,+ mid,+ rightC1: p123,+ rightC2: p23,+ };+}++/**+ * Computes analytical extrema of a 1D cubic Bézier coordinate B(t) over t in [0, 1].+ */+function cubicExtrema1D(v0: number, v1: number, v2: number, v3: number): [number, number] {+ let min = Math.min(v0, v3);+ let max = Math.max(v0, v3);++ // B'(t) = 3 * (a*t^2 + 2*b*t + c)+ const a = -v0 + 3 * v1 - 3 * v2 + v3;+ const b = 2 * (v0 - 2 * v1 + v2);+ const c = v1 - v0;++ const evalAt = (t: number) => {+ if (t <= 0 || t >= 1) return;+ const inv = 1 - t;+ const val =+ inv * inv * inv * v0 ++ 3 * inv * inv * t * v1 ++ 3 * inv * t * t * v2 ++ t * t * t * v3;+ if (val < min) min = val;+ if (val > max) max = val;+ };++ if (Math.abs(a) < 1e-9) {+ if (Math.abs(b) > 1e-9) {+ evalAt(-c / b);+ }+ } else {+ const disc = b * b - 4 * a * c;+ if (disc >= 0) {+ const sqrtD = Math.sqrt(disc);+ evalAt((-b + sqrtD) / (2 * a));+ evalAt((-b - sqrtD) / (2 * a));+ }+ }++ return [min, max];+}++/**+ * Computes exact tight axis-aligned bounding box of a single cubic Bézier segment.+ */+export function computeBezierSegmentBounds(+ p0: Point2D,+ c1: Point2D,+ c2: Point2D,+ p3: Point2D,+ halfWidth = 0+): { minX: number; minY: number; maxX: number; maxY: number } {+ const [minX, maxX] = cubicExtrema1D(p0.x, c1.x, c2.x, p3.x);+ const [minY, maxY] = cubicExtrema1D(p0.y, c1.y, c2.y, p3.y);+ const pad = Math.max(0, halfWidth);+ return {+ minX: minX - pad,+ minY: minY - pad,+ maxX: maxX + pad,+ maxY: maxY + pad,+ };+}++/**+ * Computes tight bounding box for a full cubic Bézier path (open or closed).+ */+export function computeBezierPathBounds(+ knots: VectorKnot[],+ closed = false+): { minX: number; minY: number; maxX: number; maxY: number } {+ if (knots.length === 0) {+ return { minX: 0, minY: 0, maxX: 0, maxY: 0 };+ }+ if (knots.length === 1) {+ const k = knots[0];+ const r = (k.width || 2) * 0.5;+ return { minX: k.x - r, minY: k.y - r, maxX: k.x + r, maxY: k.y + r };+ }++ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ const segCount = closed ? knots.length : knots.length - 1;+ for (let i = 0; i < segCount; i++) {+ const k1 = knots[i];+ const k2 = knots[(i + 1) % knots.length];+ const seg = getSegmentControlPoints(k1, k2);+ const halfW = Math.max(k1.width || 2, k2.width || 2) * 0.5;+ const b = computeBezierSegmentBounds(seg.p0, seg.c1, seg.c2, seg.p3, halfW);+ if (b.minX < minX) minX = b.minX;+ if (b.minY < minY) minY = b.minY;+ if (b.maxX > maxX) maxX = b.maxX;+ if (b.maxY > maxY) maxY = b.maxY;+ }++ return { minX, minY, maxX, maxY };+}++/**+ * Tessellates a single cubic Bézier segment based on control polygon length and curvature.+ */+export function tessellateCubicBezierSegment(+ k1: VectorKnot,+ k2: VectorKnot,+ minSteps = 6,+ maxSteps = 48+): VectorKnot[] {+ const { p0, c1, c2, p3 } = getSegmentControlPoints(k1, k2);+ const polyLen =+ Math.hypot(c1.x - p0.x, c1.y - p0.y) ++ Math.hypot(c2.x - c1.x, c2.y - c1.y) ++ Math.hypot(p3.x - c2.x, p3.y - c2.y);++ const isStraight =+ Math.hypot(c1.x - p0.x, c1.y - p0.y) < 1e-4 &&+ Math.hypot(c2.x - p3.x, c2.y - p3.y) < 1e-4;++ const steps = isStraight+ ? Math.max(1, Math.min(8, Math.ceil(polyLen / 40)))+ : Math.max(minSteps, Math.min(maxSteps, Math.ceil(polyLen / 4)));++ const out: VectorKnot[] = [];+ for (let s = 0; s < steps; s++) {+ const t = s / steps;+ const pt = evaluateCubicBezier(p0, c1, c2, p3, t, k1.width, k2.width, k1.pressure, k2.pressure);+ out.push({+ x: pt.x,+ y: pt.y,+ pressure: pt.pressure,+ width: pt.width,+ angle: Math.atan2(pt.dy, pt.dx),+ timestamp: k1.timestamp + (k2.timestamp - k1.timestamp) * t,+ });+ }+ return out;+}++/**+ * Tessellates an entire cubic Bézier VectorStroke into dense points for variable-width rendering or intersection testing.+ */+export function tessellateBezierStroke(stroke: VectorStroke, minSteps = 6): VectorKnot[] {+ const knots = stroke.knots;+ if (knots.length === 0) return [];+ if (knots.length === 1) return [knots[0]];++ const closed = Boolean(stroke.closed && knots.length >= 2);+ const segCount = closed ? knots.length : knots.length - 1;+ const result: VectorKnot[] = [];++ for (let i = 0; i < segCount; i++) {+ const k1 = knots[i];+ const k2 = knots[(i + 1) % knots.length];+ const segPts = tessellateCubicBezierSegment(k1, k2, minSteps);+ for (let j = 0; j < segPts.length; j++) {+ result.push(segPts[j]);+ }+ }++ result.push(closed ? knots[0] : knots[knots.length - 1]);+ return result;+}++/**+ * Inserts a new anchor onto a cubic Bézier path at `(segmentIndex, t)` using exact de Casteljau subdivision.+ * Updates adjacent handles so the curve shape does not move.+ */+export function insertBezierAnchorAt(+ knots: VectorKnot[],+ segmentIndex: number,+ t: number,+ closed = false+): { knots: VectorKnot[]; insertedIndex: number } {+ const n = knots.length;+ const maxSeg = closed ? n - 1 : n - 2;+ if (n < 2 || segmentIndex < 0 || segmentIndex > maxSeg) {+ return { knots: [...knots], insertedIndex: -1 };+ }++ const nextIdx = (segmentIndex + 1) % n;+ const k1 = knots[segmentIndex];+ const k2 = knots[nextIdx];+ const seg = getSegmentControlPoints(k1, k2);+ const u = clamp01(t);+ const split = splitCubicBezier(seg.p0, seg.c1, seg.c2, seg.p3, u);++ const updatedK1: VectorKnot = {+ ...k1,+ handleOut: { ...split.leftC1 },+ };+ const updatedK2: VectorKnot = {+ ...k2,+ handleIn: { ...split.rightC2 },+ };+ const newKnot: VectorKnot = {+ x: split.mid.x,+ y: split.mid.y,+ pressure: k1.pressure + (k2.pressure - k1.pressure) * u,+ width: Math.max(0.5, k1.width + (k2.width - k1.width) * u),+ timestamp: Date.now(),+ handleIn: { ...split.leftC2 },+ handleOut: { ...split.rightC1 },+ handleType: 'smooth',+ };++ const nextKnots: VectorKnot[] = knots.map((k) => ({+ ...k,+ handleIn: k.handleIn ? { ...k.handleIn } : null,+ handleOut: k.handleOut ? { ...k.handleOut } : null,+ }));+ nextKnots[segmentIndex] = updatedK1;+ nextKnots[nextIdx] = updatedK2;++ const insertPos = segmentIndex + 1;+ nextKnots.splice(insertPos, 0, newKnot);+ return { knots: nextKnots, insertedIndex: insertPos };+}++/**+ * Finds the closest point on a cubic Bézier path to `target` using coarse sampling + golden-section refinement.+ */+export function findClosestPointOnBezierPath(+ knots: VectorKnot[],+ target: Point2D,+ closed = false,+ samplesPerSegment = 24+): BezierClosestHit | null {+ const n = knots.length;+ if (n < 2) return null;++ const segCount = closed ? n : n - 1;+ let best: BezierClosestHit | null = null;+ let bestDistSq = Infinity;++ for (let i = 0; i < segCount; i++) {+ const k1 = knots[i];+ const k2 = knots[(i + 1) % n];+ const seg = getSegmentControlPoints(k1, k2);++ // Coarse search+ let localBestT = 0;+ let localBestDistSq = Infinity;+ for (let s = 0; s <= samplesPerSegment; s++) {+ const t = s / samplesPerSegment;+ const pt = evaluateCubicBezier(seg.p0, seg.c1, seg.c2, seg.p3, t);+ const dx = pt.x - target.x;+ const dy = pt.y - target.y;+ const dSq = dx * dx + dy * dy;+ if (dSq < localBestDistSq) {+ localBestDistSq = dSq;+ localBestT = t;+ }+ }++ // Refine with 8 iterations of local ternary/golden narrowing+ let lo = Math.max(0, localBestT - 1 / samplesPerSegment);+ let hi = Math.min(1, localBestT + 1 / samplesPerSegment);+ for (let iter = 0; iter < 8; iter++) {+ const m1 = lo + (hi - lo) / 3;+ const m2 = hi - (hi - lo) / 3;+ const p1 = evaluateCubicBezier(seg.p0, seg.c1, seg.c2, seg.p3, m1);+ const p2 = evaluateCubicBezier(seg.p0, seg.c1, seg.c2, seg.p3, m2);+ const d1 = (p1.x - target.x) ** 2 + (p1.y - target.y) ** 2;+ const d2 = (p2.x - target.x) ** 2 + (p2.y - target.y) ** 2;+ if (d1 < d2) {+ hi = m2;+ } else {+ lo = m1;+ }+ }++ const tRefined = (lo + hi) * 0.5;+ const refined = evaluateCubicBezier(seg.p0, seg.c1, seg.c2, seg.p3, tRefined);+ const rDistSq = (refined.x - target.x) ** 2 + (refined.y - target.y) ** 2;+ if (rDistSq < bestDistSq) {+ bestDistSq = rDistSq;+ best = {+ segmentIndex: i,+ t: tRefined,+ point: { x: refined.x, y: refined.y },+ distance: Math.sqrt(rDistSq),+ };+ }+ }++ return best;+}++/**+ * Translates an anchor point and both of its attached Bézier handles by `(dx, dy)`.+ */+export function moveBezierAnchor(knot: VectorKnot, nextPos: Point2D): VectorKnot {+ const dx = nextPos.x - knot.x;+ const dy = nextPos.y - knot.y;+ return {+ ...knot,+ x: nextPos.x,+ y: nextPos.y,+ handleIn: isFinitePoint(knot.handleIn)+ ? { x: knot.handleIn.x + dx, y: knot.handleIn.y + dy }+ : null,+ handleOut: isFinitePoint(knot.handleOut)+ ? { x: knot.handleOut.x + dx, y: knot.handleOut.y + dy }+ : null,+ };+}++/**+ * Updates one control handle (`in` or `out`) of a knot, enforcing `symmetric`, `smooth`, or `corner` continuity.+ */+export function moveBezierHandle(+ knot: VectorKnot,+ which: 'in' | 'out',+ nextHandlePos: Point2D,+ breakSymmetry = false+): VectorKnot {+ const vx = nextHandlePos.x - knot.x;+ const vy = nextHandlePos.y - knot.y;+ const len = Math.hypot(vx, vy);++ let mode: BezierHandleType = breakSymmetry ? 'corner' : (knot.handleType ?? 'symmetric');+ if (breakSymmetry) {+ mode = 'corner';+ }++ const otherKey = which === 'in' ? 'handleOut' : 'handleIn';+ const existingOther = knot[otherKey];+ let nextOther = isFinitePoint(existingOther) ? { ...existingOther } : null;++ if (mode === 'symmetric') {+ nextOther = { x: knot.x - vx, y: knot.y - vy };+ } else if (mode === 'smooth' && nextOther && len > 1e-4) {+ const otherLen = Math.hypot(nextOther.x - knot.x, nextOther.y - knot.y);+ if (otherLen > 1e-4) {+ nextOther = {+ x: knot.x - (vx / len) * otherLen,+ y: knot.y - (vy / len) * otherLen,+ };+ }+ }++ return {+ ...knot,+ handleType: mode,+ handleIn: which === 'in' ? { x: nextHandlePos.x, y: nextHandlePos.y } : nextOther,+ handleOut: which === 'out' ? { x: nextHandlePos.x, y: nextHandlePos.y } : nextOther,+ };+}++/**+ * Converts an anchor between sharp corner (null handles) and smooth auto-tangent curve point.+ */+export function toggleBezierAnchorSmooth(+ knots: VectorKnot[],+ index: number,+ closed = false+): VectorKnot[] {+ const n = knots.length;+ if (index < 0 || index >= n) return knots;++ const target = knots[index];+ const hasHandles = isFinitePoint(target.handleIn) || isFinitePoint(target.handleOut);++ return knots.map((k, idx) => {+ if (idx !== index) return k;+ if (hasHandles) {+ return {+ ...k,+ handleIn: null,+ handleOut: null,+ handleType: 'corner',+ };+ }+ const prevIdx = idx > 0 ? idx - 1 : closed ? n - 1 : idx;+ const nextIdx = idx < n - 1 ? idx + 1 : closed ? 0 : idx;+ const prev = knots[prevIdx];+ const next = knots[nextIdx];+ const tx = next.x - prev.x;+ const ty = next.y - prev.y;+ const dist = Math.hypot(tx, ty);+ if (dist < 1e-3) {+ return {+ ...k,+ handleIn: { x: k.x - 24, y: k.y },+ handleOut: { x: k.x + 24, y: k.y },+ handleType: 'symmetric',+ };+ }+ const ux = tx / dist;+ const uy = ty / dist;+ const inLen = Math.hypot(k.x - prev.x, k.y - prev.y) * 0.3;+ const outLen = Math.hypot(next.x - k.x, next.y - k.y) * 0.3;+ return {+ ...k,+ handleIn: inLen > 0.5 ? { x: k.x - ux * inLen, y: k.y - uy * inLen } : null,+ handleOut: outLen > 0.5 ? { x: k.x + ux * outLen, y: k.y + uy * outLen } : null,+ handleType: 'smooth',+ };+ });+}++/**+ * Builds an exact SVG path `d` attribute string (`M ... C ... Z`) for a cubic Bézier knot list.+ */+export function buildBezierSvgPath(knots: VectorKnot[], closed = false): string {+ if (knots.length === 0) return '';+ const fmt = (v: number) => Math.round(v * 100) / 100;+ let d = `M ${fmt(knots[0].x)} ${fmt(knots[0].y)}`;+ if (knots.length === 1) return d;++ const segCount = closed ? knots.length : knots.length - 1;+ for (let i = 0; i < segCount; i++) {+ const k1 = knots[i];+ const k2 = knots[(i + 1) % knots.length];+ const { c1, c2, p3 } = getSegmentControlPoints(k1, k2);+ d += ` C ${fmt(c1.x)} ${fmt(c1.y)}, ${fmt(c2.x)} ${fmt(c2.y)}, ${fmt(p3.x)} ${fmt(p3.y)}`;+ }+ if (closed) {+ d += ' Z';+ }+ return d;+}++/**+ * Traces a cubic Bézier path directly onto a Canvas 2D context using native `bezierCurveTo`.+ */+export function traceBezierPathOnContext(+ ctx: CanvasRenderingContext2D,+ knots: VectorKnot[],+ closed = false+): void {+ if (knots.length === 0) return;+ ctx.beginPath();+ ctx.moveTo(knots[0].x, knots[0].y);+ if (knots.length === 1) return;++ const segCount = closed ? knots.length : knots.length - 1;+ for (let i = 0; i < segCount; i++) {+ const k1 = knots[i];+ const k2 = knots[(i + 1) % knots.length];+ const { c1, c2, p3 } = getSegmentControlPoints(k1, k2);+ ctx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, p3.x, p3.y);+ }+ if (closed) {+ ctx.closePath();+ }+}++/**+ * Checks whether all knots of a stroke share effectively uniform width (allowing native `bezierCurveTo` stroking).+ */+export function isUniformWidthBezier(knots: VectorKnot[]): boolean {+ if (knots.length <= 1) return true;+ const w0 = knots[0].width;+ for (let i = 1; i < knots.length; i++) {+ if (Math.abs(knots[i].width - w0) > 0.05) return false;+ }+ return true;+}diff --git a/src/utils/brushPresetManager.ts b/src/utils/brushPresetManager.tsindex 658bfa6..8b52c49 100644--- a/src/utils/brushPresetManager.ts+++ b/src/utils/brushPresetManager.ts@@ -1,5 +1,7 @@import {+ BristleSettings,BrushPresetId,+ BrushRenderMode,BrushSettings,CspBrush,BrushDynamics,@@ -10,6 +12,11 @@ import {CspSpraySettings,CspTaperSettings,CspTipFlipMode,+ GrainMappingMode,+ ImpastoSettings,+ NaturalMixingMode,+ NaturalPaintSettings,+ SurfaceTextureId,} from '../types/editor';import { getBuiltinBrushConfig } from './presetBrushes';import { getPreloadedTipImage, getCachedCustomBrushes } from './brushStorage';@@ -95,12 +102,14 @@ export interface BrushPersistentSettings {amountOfPaint?: number;densityOfPaint?: number;colorStretch?: number;- mixingMode?: 'blend' | 'running_color' | 'smear';+ mixingMode?: NaturalMixingMode;wetEdge?: number;wetEdgeRadius?: number;wetEdgeAlphaPower?: number;wetEdgeValuePower?: number;textureDensity?: number;+ surfaceTextureId?: SurfaceTextureId;+ grainMappingMode?: GrainMappingMode;paperTextureScale?: number;paperTextureRotate?: number;paperTextureMode?: CspPaperTextureMode;@@ -112,9 +121,27 @@ export interface BrushPersistentSettings {sizeSensor?: CspSensorConfig;opacitySensor?: CspSensorConfig;densitySensor?: CspSensorConfig;+ bristleSplaySensor?: CspSensorConfig;+ paintLoadSensor?: CspSensorConfig;+ grainPenetrationSensor?: CspSensorConfig;+ angleSensor?: CspSensorConfig;+ scatterSensor?: CspSensorConfig;spray?: CspSpraySettings;taper?: CspTaperSettings;dynamics?: BrushDynamics;+ dualBrush?: boolean;+ dualBrushCompositeMode?: string;+ dualSize?: number;+ dualSpacing?: number;+ dualScatter?: number;+ dualAngle?: number;+ dualScale?: number;+ dualSurfaceTextureId?: SurfaceTextureId;+ dualGrainDepth?: number;+ renderMode?: BrushRenderMode;+ bristle?: BristleSettings;+ naturalPaint?: NaturalPaintSettings;+ impasto?: ImpastoSettings;}export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {@@ -138,6 +165,11 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {sizeSensor: undefined,opacitySensor: undefined,densitySensor: undefined,+ bristleSplaySensor: undefined,+ paintLoadSensor: undefined,+ grainPenetrationSensor: undefined,+ angleSensor: undefined,+ scatterSensor: undefined,customTipDataUrl: undefined,customTipImage: undefined,customTipAngle: 0,@@ -165,6 +197,8 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {wetEdgeValuePower: undefined,paperTexture: undefined,paperTextureImage: undefined,+ surfaceTextureId: undefined,+ grainMappingMode: 'canvas-locked',paperTextureMode: 'subtract',paperTextureBrightness: 0,paperTextureContrast: 0,@@ -176,9 +210,18 @@ export const NEUTRAL_BRUSH_DEFAULTS: Partial<BrushSettings> = {dualBrushCompositeMode: 'multiply',dualSize: undefined,dualSpacing: undefined,+ dualScatter: 0,+ dualAngle: 0,+ dualScale: 1.0,+ dualSurfaceTextureId: undefined,+ dualGrainDepth: 0,dualTipDataUrl: undefined,dualTipImage: undefined,dynamics: undefined,+ renderMode: 'stamp',+ bristle: undefined,+ naturalPaint: undefined,+ impasto: undefined,useGpu: true,};@@ -276,6 +319,8 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = ['wetEdgeAlphaPower','wetEdgeValuePower','textureDensity',+ 'surfaceTextureId',+ 'grainMappingMode','paperTextureScale','paperTextureRotate','paperTextureMode',@@ -287,9 +332,27 @@ const PERSISTENT_KEYS: (keyof BrushPersistentSettings)[] = ['sizeSensor','opacitySensor','densitySensor',+ 'bristleSplaySensor',+ 'paintLoadSensor',+ 'grainPenetrationSensor',+ 'angleSensor',+ 'scatterSensor','spray','taper','dynamics',+ 'dualBrush',+ 'dualBrushCompositeMode',+ 'dualSize',+ 'dualSpacing',+ 'dualScatter',+ 'dualAngle',+ 'dualScale',+ 'dualSurfaceTextureId',+ 'dualGrainDepth',+ 'renderMode',+ 'bristle',+ 'naturalPaint',+ 'impasto',];function mergeIntoMemoryCache(presetId: string, settings: Partial<BrushSettings>): Record<string, BrushPersistentSettings> {@@ -464,12 +527,17 @@ export function getEffectiveBrushSettings(sizeSensor: cspMatch.sizeSensor,opacitySensor: cspMatch.opacitySensor,densitySensor: cspMatch.densitySensor,+ bristleSplaySensor: cspMatch.bristleSplaySensor,+ paintLoadSensor: cspMatch.paintLoadSensor,+ grainPenetrationSensor: cspMatch.grainPenetrationSensor,+ angleSensor: cspMatch.angleSensor,+ scatterSensor: cspMatch.scatterSensor,smoothing: cspMatch.smoothing ?? true,spray: cspMatch.spray,taper: cspMatch.taper,isRibbon: cspMatch.isRibbon,colorMixing: cspMatch.colorMixing,- perceptualMixing: true,+ perceptualMixing: cspMatch.perceptualMixing ?? true,amountOfPaint: cspMatch.amountOfPaint ?? 0.7,densityOfPaint: cspMatch.densityOfPaint ?? 0.8,colorStretch: cspMatch.colorStretch ?? 0.6,@@ -482,6 +550,8 @@ export function getEffectiveBrushSettings(textureDensity: cspMatch.textureDensity,paperTexture: cspMatch.paperTexture,paperTextureImage,+ surfaceTextureId: cspMatch.surfaceTextureId,+ grainMappingMode: cspMatch.grainMappingMode,paperTextureScale: cspMatch.paperTextureScale,paperTextureRotate: cspMatch.paperTextureRotate,paperTextureMode: cspMatch.paperTextureMode,@@ -490,10 +560,21 @@ export function getEffectiveBrushSettings(paperTextureApplyEachPlot: cspMatch.paperTextureApplyEachPlot,paperTextureInverted: cspMatch.paperTextureInverted,dualBrush: cspMatch.dualBrush,+ dualTipDataUrl: cspMatch.secondaryTipDataUrl,dualTipImage: dualTipImg,dualBrushCompositeMode: (cspMatch.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',dualSize: cspMatch.dualSize,dualSpacing: cspMatch.dualSpacing,+ dualScatter: cspMatch.dualScatter,+ dualAngle: cspMatch.dualAngle,+ dualScale: cspMatch.dualScale,+ dualSurfaceTextureId: cspMatch.dualSurfaceTextureId,+ dualGrainDepth: cspMatch.dualGrainDepth,+ dynamics: cspMatch.dynamics,+ renderMode: cspMatch.renderMode,+ bristle: cspMatch.bristle,+ naturalPaint: cspMatch.naturalPaint,+ impasto: cspMatch.impasto,useGpu: true,...saved,};diff --git a/src/utils/brushPreview.ts b/src/utils/brushPreview.tsindex d829bfc..1d11b28 100644--- a/src/utils/brushPreview.ts+++ b/src/utils/brushPreview.ts@@ -1,12 +1,20 @@import {+ BristleSettings,BrushDynamics,BrushPresetId,+ BrushRenderMode,+ BrushSettings,CspAngleDynamicsMode,CspAntiAliasLevel,CspBlendTipsMode,CspPaperTextureMode,CspSpraySettings,CspTipFlipMode,+ GrainMappingMode,+ ImpastoSettings,+ NaturalPaintSettings,+ Point,+ SurfaceTextureId,} from '../types/editor';import { getBuiltinBrushConfig } from './presetBrushes';import {@@ -21,6 +29,10 @@ import {resolveTipFlipSigns,applyCspPaperTextureAlpha,} from '../engine/BrushEngine';+import {+ isNaturalPaintBrush,+ renderCompleteNaturalPaintStroke,+} from '../engine/NaturalPaintRenderer';export interface BrushPreviewOptions {preset?: BrushPresetId;@@ -59,6 +71,12 @@ export interface BrushPreviewOptions {densityOfPaint?: number;colorStretch?: number;wetEdge?: number;+ renderMode?: BrushRenderMode;+ bristle?: BristleSettings;+ naturalPaint?: NaturalPaintSettings;+ impasto?: ImpastoSettings;+ surfaceTextureId?: SurfaceTextureId;+ grainMappingMode?: GrainMappingMode;}const previewCache = new Map<string, HTMLCanvasElement>();@@ -150,6 +168,12 @@ export function renderBrushStrokePreview(const isEraser = options.tool === 'eraser';const strokeColor = options.color || '#ffffff';const bgColor = options.backgroundColor || 'transparent';+ const renderMode = options.renderMode ?? builtinCfg?.renderMode;+ const bristleCfg = options.bristle ?? builtinCfg?.bristle;+ const naturalCfg = options.naturalPaint ?? builtinCfg?.naturalPaint;+ const impastoCfg = options.impasto ?? builtinCfg?.impasto;+ const surfaceTextureId = options.surfaceTextureId ?? builtinCfg?.surfaceTextureId;+ const grainMappingMode = options.grainMappingMode ?? builtinCfg?.grainMappingMode;const curveSig = options.pressureCurve? options.pressureCurve.map((p) => `${p[0].toFixed(2)},${p[1].toFixed(2)}`).join(';')@@ -178,6 +202,11 @@ export function renderBrushStrokePreview(isEraser ? '1' : '0',options.wetEdge?.toFixed(2) || '0',options.colorMixing ? '1' : '0',+ renderMode || 'stamp',+ bristleCfg ? `${bristleCfg.profile}:${bristleCfg.count}:${bristleCfg.clumping.toFixed(2)}` : 'nb',+ impastoCfg?.enabled ? `imp:${impastoCfg.depth.toFixed(2)}:${impastoCfg.gloss.toFixed(2)}` : 'ni',+ naturalCfg?.enabled ? `np:${naturalCfg.paintLoad.toFixed(2)}:${naturalCfg.dryBrush.toFixed(2)}:${naturalCfg.depletionRate.toFixed(2)}` : 'nn',+ surfaceTextureId || 'std',strokeColor,bgColor,cssWidth,@@ -238,7 +267,74 @@ export function renderBrushStrokePreview(pts.push({ x, y, width: w, pressure, tipAlpha });}- if (isEraser) {+ const isNaturalPreview =+ !isEraser &&+ isNaturalPaintBrush({+ renderMode,+ naturalPaint: naturalCfg,+ impasto: impastoCfg,+ });++ if (isNaturalPreview) {+ // Render authentic Natural Paint bristle-ribbon + impasto S-curve preview+ const previewPts: Point[] = pts.map((p) => ({+ x: p.x,+ y: p.y,+ width: Math.max(3, p.width),+ pressure: p.pressure,+ }));+ const previewNatural: NaturalPaintSettings = {+ enabled: true,+ spatialMixing: false, // Preview on clean swatch uses visible pigment even for zero-load blender+ pigmentMixingStrength: naturalCfg?.pigmentMixingStrength ?? 0.85,+ paintLoad: (naturalCfg?.paintLoad ?? 0.85) <= 0.05 ? 0.55 : (naturalCfg?.paintLoad ?? 0.85),+ depletionRate: naturalCfg?.depletionRate ?? 0.25,+ wetness: naturalCfg?.wetness ?? 0.5,+ viscosity: naturalCfg?.viscosity ?? 0.5,+ autoClean: true,+ chargePerPressure: naturalCfg?.chargePerPressure ?? 0.45,+ dryBrush: naturalCfg?.dryBrush ?? 0.3,+ granulation: naturalCfg?.granulation ?? 0,+ };+ const previewSettings: BrushSettings = {+ size: displayWidth,+ minSizeFactor,+ color: strokeColor,+ opacity,+ flow,+ spacing: Math.max(0.05, spacing),+ usePressure: true,+ smoothing: true,+ stabilization: 0,+ hardness,+ grain,+ textureDensity: grain,+ paperTextureScale: Math.max(0.35, paperScale * 0.65),+ paperTextureContrast: paperContrast,+ paperTextureBrightness: paperBrightness,+ paperTextureInverted: paperInverted,+ wetEdge: options.wetEdge ?? builtinCfg?.wetEdge ?? 0,+ renderMode: renderMode ?? 'bristle-ribbon',+ bristle: bristleCfg+ ? { ...bristleCfg, count: Math.min(24, Math.max(8, bristleCfg.count)) }+ : undefined,+ naturalPaint: previewNatural,+ impasto: impastoCfg,+ surfaceTextureId: surfaceTextureId ?? 'linen-canvas',+ grainMappingMode: grainMappingMode ?? 'canvas-locked',+ useGpu: false, // Deterministic fast CPU shading for tiny preview cards+ };+ renderCompleteNaturalPaintStroke(+ offCtx,+ previewPts,+ previewSettings,+ strokeColor,+ undefined,+ opacity,+ 'source-over',+ 1337+ );+ } else if (isEraser) {offCtx.save();offCtx.fillStyle = 'rgba(255, 255, 255, 0.18)';offCtx.fillRect(padX - 4, centerY - amp - 4, strokeLength + 8, (amp + 4) * 2);diff --git a/src/utils/brushStorage.ts b/src/utils/brushStorage.tsindex 0475d69..4135317 100644--- a/src/utils/brushStorage.ts+++ b/src/utils/brushStorage.ts@@ -422,11 +422,16 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<PartisizeSensor: brush.sizeSensor,opacitySensor: brush.opacitySensor,densitySensor: brush.densitySensor,+ bristleSplaySensor: brush.bristleSplaySensor,+ paintLoadSensor: brush.paintLoadSensor,+ grainPenetrationSensor: brush.grainPenetrationSensor,+ angleSensor: brush.angleSensor,+ scatterSensor: brush.scatterSensor,spray: brush.spray,taper: brush.taper,isRibbon: brush.isRibbon,colorMixing: brush.colorMixing,- perceptualMixing: true,+ perceptualMixing: brush.perceptualMixing ?? true,amountOfPaint: brush.amountOfPaint ?? 0.7,densityOfPaint: brush.densityOfPaint ?? 0.8,colorStretch: brush.colorStretch ?? 0.6,@@ -439,6 +444,8 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<PartitextureDensity: brush.textureDensity,paperTexture: brush.paperTexture,paperTextureImage,+ surfaceTextureId: brush.surfaceTextureId,+ grainMappingMode: brush.grainMappingMode,paperTextureScale: brush.paperTextureScale,paperTextureRotate: brush.paperTextureRotate,paperTextureMode: brush.paperTextureMode,@@ -447,10 +454,21 @@ export async function prepareBrushSettingsForCsp(brush: CspBrush): Promise<PartipaperTextureApplyEachPlot: brush.paperTextureApplyEachPlot,paperTextureInverted: brush.paperTextureInverted,dualBrush: brush.dualBrush,+ dualTipDataUrl: brush.secondaryTipDataUrl,dualTipImage: dualTipImg,dualBrushCompositeMode: (brush.dualBrushCompositeMode as BrushSettings['dualBrushCompositeMode']) || 'multiply',dualSize: brush.dualSize,dualSpacing: brush.dualSpacing,+ dualScatter: brush.dualScatter,+ dualAngle: brush.dualAngle,+ dualScale: brush.dualScale,+ dualSurfaceTextureId: brush.dualSurfaceTextureId,+ dualGrainDepth: brush.dualGrainDepth,+ dynamics: brush.dynamics,+ renderMode: brush.renderMode,+ bristle: brush.bristle,+ naturalPaint: brush.naturalPaint,+ impasto: brush.impasto,useGpu: true,};}diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.tsindex 44e5c68..8c2f27a 100644--- a/src/utils/colorMixingEngine.ts+++ b/src/utils/colorMixingEngine.ts@@ -81,18 +81,29 @@ export function rgbToHex(r: number, g: number, b: number): string {}// --------------------------------------------------------------// Color Science: sRGB <-> Linear RGB <-> OKLab+// Color Science: sRGB <-> Linear RGB <-> OKLab (Fast LUT + Float Precision)// -------------------------------------------------------------+const SRGB_TO_LINEAR_LUT = new Float32Array(256);+for (let i = 0; i < 256; i++) {+ const v = i / 255;+ SRGB_TO_LINEAR_LUT[i] = v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);+}+function srgbToLinear(c: number): number {- const v = c / 255;- return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);+ if (c <= 0) return 0;+ if (c >= 255) return 1;+ const idx = c | 0;+ const frac = c - idx;+ if (idx >= 255) return 1;+ const v0 = SRGB_TO_LINEAR_LUT[idx];+ return frac > 0 ? v0 + (SRGB_TO_LINEAR_LUT[idx + 1] - v0) * frac : v0;}-function linearToSrgb(c: number): number {- const clamped = Math.max(0, Math.min(1, c));+function linearToSrgbFloat(c: number): number {+ const clamped = c <= 0 ? 0 : c >= 1 ? 1 : c;const v = clamped <= 0.0031308 ? 12.92 * clamped : 1.055 * Math.pow(clamped, 1 / 2.4) - 0.055;- return Math.max(0, Math.min(255, Math.round(v * 255)));+ return v <= 0 ? 0 : v >= 1 ? 255 : v * 255;}/**@@ -134,6 +145,7 @@ export function oklabToLinearRgb(L: number, a: number, b: number): { r: number;}import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';+import type { BristleProfilePreset, BristleSettings, NaturalMixingMode, NaturalPaintSettings } from '../types/editor';/*** Subtractive Pigment Mixing (Physical Paint Simulation — CSP Perceptual / Krita Kubelka-Munk).@@ -191,24 +203,70 @@ export function mixSubtractivePigments(subB = Math.max(0.0, subB * (1.0 - ybCross * 0.45));}- // 3. Perceptual Lightness & Chroma preservation via OKLab+ // 3. Perceptual Lightness & Chroma preservation via OKLab with hue-safe gamut clampingconst lab1 = linearRgbToOklab(r1, g1, b1);const lab2 = linearRgbToOklab(r2, g2, b2);const targetLightness = lab1.L * w1 + lab2.L * w2;const subLab = linearRgbToOklab(subR, subG, subB);- const tunedLab = {- L: Math.max(0, targetLightness * 0.72 + subLab.L * 0.28),- a: subLab.a,- b: subLab.b,+ const tunedL = Math.max(0, Math.min(1, targetLightness * 0.68 + subLab.L * 0.32));+ let finalLinear = oklabToLinearRgb(tunedL, subLab.a, subLab.b);++ // If boosting lightness pushed chroma slightly outside sRGB gamut, scale chroma back smoothly+ // instead of hard-clipping individual channels (which twists hues during wet transitions).+ const minCh = Math.min(finalLinear.r, finalLinear.g, finalLinear.b);+ const maxCh = Math.max(finalLinear.r, finalLinear.g, finalLinear.b);+ if (minCh < 0 || maxCh > 1) {+ const lGray = oklabToLinearRgb(tunedL, 0, 0).r;+ let scale = 1.0;+ if (minCh < 0 && lGray > minCh) {+ scale = Math.min(scale, lGray / (lGray - minCh));+ }+ if (maxCh > 1 && maxCh > lGray) {+ scale = Math.min(scale, (1 - lGray) / (maxCh - lGray));+ }+ scale = Math.max(0, Math.min(1, scale));+ finalLinear = oklabToLinearRgb(tunedL, subLab.a * scale, subLab.b * scale);+ }++ return {+ r: linearToSrgbFloat(finalLinear.r),+ g: linearToSrgbFloat(finalLinear.g),+ b: linearToSrgbFloat(finalLinear.b),};+}- const finalLinear = oklabToLinearRgb(tunedLab.L, tunedLab.a, tunedLab.b);+/**+ * Blends two colors with configurable subtractive pigment mixing strength [0..1].+ * 0.0 = standard linear RGB interpolation; 1.0 = full Kubelka-Munk + OKLab subtractive mixing.+ */+export function mixPigmentsWithStrength(+ c1: RgbColor,+ c2: RgbColor,+ weight2: number,+ pigmentStrength: number = 1.0+): RgbColor {+ const w2 = Math.max(0, Math.min(1, weight2));+ if (w2 <= 0.0001) return { r: c1.r, g: c1.g, b: c1.b };+ if (w2 >= 0.9999) return { r: c2.r, g: c2.g, b: c2.b };+ const s = Math.max(0, Math.min(1, pigmentStrength));+ if (s <= 0.01) {+ return {+ r: c1.r + (c2.r - c1.r) * w2,+ g: c1.g + (c2.g - c1.g) * w2,+ b: c1.b + (c2.b - c1.b) * w2,+ };+ }+ const sub = mixSubtractivePigments(c1, c2, w2);+ if (s >= 0.99) return sub;+ const linR = c1.r + (c2.r - c1.r) * w2;+ const linG = c1.g + (c2.g - c1.g) * w2;+ const linB = c1.b + (c2.b - c1.b) * w2;return {- r: linearToSrgb(finalLinear.r),- g: linearToSrgb(finalLinear.g),- b: linearToSrgb(finalLinear.b),+ r: linR + (sub.r - linR) * s,+ g: linG + (sub.g - linG) * s,+ b: linB + (sub.b - linB) * s,};}@@ -485,7 +543,7 @@ export class LayerPixelSampler {/*** Updates in-memory pixel buffer with newly laid paint so subsequent stamps- * along the active stroke immediately pick up freshly mixed color!+ * along the active stroke immediately pick up freshly mixed color without sparse grid gaps.*/public depositDab(cx: number,@@ -496,6 +554,7 @@ export class LayerPixelSampler {b: number,a: number): void {+ if (a <= 0.002 || this.width <= 0 || this.height <= 0) return;const rad = Math.max(1, Math.min(64, Math.round(radius)));const ix = Math.round(cx);const iy = Math.round(cy);@@ -506,64 +565,198 @@ export class LayerPixelSampler {const x1 = Math.min(w - 1, ix + rad);const y0 = Math.max(0, iy - rad);const y1 = Math.min(h - 1, iy + rad);+ if (x0 > x1 || y0 > y1) return;const radSq = rad * rad;const invRadSq = 1 / radSq;- const step = Math.max(1, Math.floor(rad / 4.5));+ // Contiguous pixel fill for <= 14px, dense 2x2 block fill for larger brushes (zero Swiss-cheese gaps!)+ const step = rad > 14 ? 2 : 1;++ const blendPixel = (px: number, py: number, effAlpha: number) => {+ if (this.useLazyTiles) {+ const tile = this.getOrLoadTile(px >> 8, py >> 8);+ const idx = (((py & 255) << 8) + (px & 255)) << 2;+ const dstA = tile[idx + 3] / 255;+ const outA = effAlpha + dstA * (1 - effAlpha);+ if (outA > 0.001) {+ const inv = 1 / outA;+ tile[idx] = Math.round((r * effAlpha + tile[idx] * dstA * (1 - effAlpha)) * inv);+ tile[idx + 1] = Math.round((g * effAlpha + tile[idx + 1] * dstA * (1 - effAlpha)) * inv);+ tile[idx + 2] = Math.round((b * effAlpha + tile[idx + 2] * dstA * (1 - effAlpha)) * inv);+ tile[idx + 3] = Math.round(Math.min(255, outA * 255));+ }+ } else {+ const idx = (py * w + px) << 2;+ const dstA = this.data[idx + 3] / 255;+ const outA = effAlpha + dstA * (1 - effAlpha);+ if (outA > 0.001) {+ const inv = 1 / outA;+ this.data[idx] = Math.round((r * effAlpha + this.data[idx] * dstA * (1 - effAlpha)) * inv);+ this.data[idx + 1] = Math.round((g * effAlpha + this.data[idx + 1] * dstA * (1 - effAlpha)) * inv);+ this.data[idx + 2] = Math.round((b * effAlpha + this.data[idx + 2] * dstA * (1 - effAlpha)) * inv);+ this.data[idx + 3] = Math.round(Math.min(255, outA * 255));+ }+ }+ };- if (this.useLazyTiles) {- for (let y = y0; y <= y1; y += step) {- const dy = y - iy;- const dySq = dy * dy;- const ty = y >> 8;- const lyOffset = (y & 255) << 8;- for (let x = x0; x <= x1; x += step) {- const dx = x - ix;- const dSq = dx * dx + dySq;- if (dSq <= radSq) {- const falloff = 1 - dSq * invRadSq;- const effAlpha = Math.min(1.0, a * falloff);- const tile = this.getOrLoadTile(x >> 8, ty);- const idx = (lyOffset + (x & 255)) << 2;- const dstA = tile[idx + 3] / 255;- const outA = effAlpha + dstA * (1 - effAlpha);- if (outA > 0.001) {- const outR = (r * effAlpha + tile[idx] * dstA * (1 - effAlpha)) / outA;- const outG = (g * effAlpha + tile[idx + 1] * dstA * (1 - effAlpha)) / outA;- const outB = (b * effAlpha + tile[idx + 2] * dstA * (1 - effAlpha)) / outA;-- tile[idx] = Math.round(outR);- tile[idx + 1] = Math.round(outG);- tile[idx + 2] = Math.round(outB);- tile[idx + 3] = Math.round(Math.min(255, outA * 255));- }+ for (let y = y0; y <= y1; y += step) {+ const dy = y - iy;+ const dySq = dy * dy;+ for (let x = x0; x <= x1; x += step) {+ const dx = x - ix;+ const dSq = dx * dx + dySq;+ if (dSq > radSq) continue;+ const falloff = 1 - dSq * invRadSq;+ const effAlpha = Math.min(1.0, a * falloff);+ if (effAlpha <= 0.002) continue;++ blendPixel(x, y, effAlpha);+ if (step === 2) {+ if (x + 1 <= x1) blendPixel(x + 1, y, effAlpha);+ if (y + 1 <= y1) {+ blendPixel(x, y + 1, effAlpha);+ if (x + 1 <= x1) blendPixel(x + 1, y + 1, effAlpha);}}}- return;}+ }- for (let y = y0; y <= y1; y += step) {+ /**+ * Zero-allocation O(1) per-bristle color sample (5-tap cross when radius >= 2, 1-tap otherwise).+ * Writes directly into `out` to eliminate GC churn across 32-64 bristles per step.+ */+ public samplePointFast(cx: number, cy: number, radius: number, out: RgbaColor): RgbaColor {+ const w = this.width;+ const h = this.height;+ const ix = Math.round(cx);+ const iy = Math.round(cy);++ if (w <= 0 || h <= 0 || ix < 0 || ix >= w || iy < 0 || iy >= h) {+ out.r = 255;+ out.g = 255;+ out.b = 255;+ out.a = 0;+ return out;+ }++ const rOff = radius >= 2.2 ? Math.min(6, Math.round(radius * 0.6)) : 0;+ let sumR = 0;+ let sumG = 0;+ let sumB = 0;+ let weightSum = 0;+ let totalSamples = 0;++ const readTap = (px: number, py: number, geomW: number) => {+ if (px < 0 || px >= w || py < 0 || py >= h) return;+ totalSamples += geomW;+ let alpha = 0;+ let tr = 0;+ let tg = 0;+ let tb = 0;+ if (this.useLazyTiles) {+ const tile = this.getOrLoadTile(px >> 8, py >> 8);+ const idx = (((py & 255) << 8) + (px & 255)) << 2;+ tr = tile[idx];+ tg = tile[idx + 1];+ tb = tile[idx + 2];+ alpha = tile[idx + 3];+ } else {+ const idx = (py * w + px) << 2;+ tr = this.data[idx];+ tg = this.data[idx + 1];+ tb = this.data[idx + 2];+ alpha = this.data[idx + 3];+ }+ if (alpha > 4) {+ const aw = geomW * (alpha / 255);+ sumR += tr * aw;+ sumG += tg * aw;+ sumB += tb * aw;+ weightSum += aw;+ }+ };++ readTap(ix, iy, 2.0);+ if (rOff > 0) {+ readTap(ix - rOff, iy, 1.0);+ readTap(ix + rOff, iy, 1.0);+ readTap(ix, iy - rOff, 1.0);+ readTap(ix, iy + rOff, 1.0);+ }++ if (weightSum > 0.001 && totalSamples > 0) {+ out.r = sumR / weightSum;+ out.g = sumG / weightSum;+ out.b = sumB / weightSum;+ out.a = Math.min(1.0, weightSum / totalSamples);+ } else {+ out.r = 255;+ out.g = 255;+ out.b = 255;+ out.a = 0;+ }+ return out;+ }++ /**+ * Lightweight per-bristle pixel deposit so overlapping turns immediately pick up+ * freshly mixed multi-colored streaks laid down earlier in the same stroke.+ */+ public depositPointFast(+ cx: number,+ cy: number,+ radius: number,+ r: number,+ g: number,+ b: number,+ a: number+ ): void {+ if (a <= 0.005 || this.width <= 0 || this.height <= 0) return;+ const w = this.width;+ const h = this.height;+ const ix = Math.round(cx);+ const iy = Math.round(cy);+ const rad = Math.max(0, Math.min(12, Math.round(radius)));+ const x0 = Math.max(0, ix - rad);+ const x1 = Math.min(w - 1, ix + rad);+ const y0 = Math.max(0, iy - rad);+ const y1 = Math.min(h - 1, iy + rad);+ if (x0 > x1 || y0 > y1) return;++ const radSq = Math.max(1, rad * rad);+ for (let y = y0; y <= y1; y++) {const dy = y - iy;const dySq = dy * dy;- const rowOffset = y * w;- for (let x = x0; x <= x1; x += step) {+ const ty = y >> 8;+ const lyOff = (y & 255) << 8;+ const rowOff = y * w;+ for (let x = x0; x <= x1; x++) {const dx = x - ix;const dSq = dx * dx + dySq;- if (dSq <= radSq) {- const falloff = 1 - dSq * invRadSq;- const effAlpha = Math.min(1.0, a * falloff);- const idx = (rowOffset + x) * 4;+ if (dSq > radSq) continue;+ const effA = Math.min(1.0, a * (rad === 0 ? 1.0 : 1.0 - (dSq / (radSq + 1)) * 0.65));+ if (this.useLazyTiles) {+ const tile = this.getOrLoadTile(x >> 8, ty);+ const idx = (lyOff + (x & 255)) << 2;+ const dstA = tile[idx + 3] / 255;+ const outA = effA + dstA * (1 - effA);+ if (outA > 0.001) {+ const inv = 1 / outA;+ tile[idx] = Math.round((r * effA + tile[idx] * dstA * (1 - effA)) * inv);+ tile[idx + 1] = Math.round((g * effA + tile[idx + 1] * dstA * (1 - effA)) * inv);+ tile[idx + 2] = Math.round((b * effA + tile[idx + 2] * dstA * (1 - effA)) * inv);+ tile[idx + 3] = Math.round(Math.min(255, outA * 255));+ }+ } else {+ const idx = (rowOff + x) << 2;const dstA = this.data[idx + 3] / 255;- const outA = effAlpha + dstA * (1 - effAlpha);+ const outA = effA + dstA * (1 - effA);if (outA > 0.001) {- const outR = (r * effAlpha + this.data[idx] * dstA * (1 - effAlpha)) / outA;- const outG = (g * effAlpha + this.data[idx + 1] * dstA * (1 - effAlpha)) / outA;- const outB = (b * effAlpha + this.data[idx + 2] * dstA * (1 - effAlpha)) / outA;-- this.data[idx] = Math.round(outR);- this.data[idx + 1] = Math.round(outG);- this.data[idx + 2] = Math.round(outB);+ const inv = 1 / outA;+ this.data[idx] = Math.round((r * effA + this.data[idx] * dstA * (1 - effA)) * inv);+ this.data[idx + 1] = Math.round((g * effA + this.data[idx + 1] * dstA * (1 - effA)) * inv);+ this.data[idx + 2] = Math.round((b * effA + this.data[idx + 2] * dstA * (1 - effA)) * inv);this.data[idx + 3] = Math.round(Math.min(255, outA * 255));}}@@ -663,23 +856,30 @@ export class PaintReservoir {}/**- * Mixes canvas paint into the brush reservoir and calculates output dab parameters.+ * Mixes canvas paint into the brush reservoir and calculates output dab parameters+ * using step-size-invariant continuous equilibrium blending:+ * - amountOfPaint = 0.0 (or 'smear'): pure smudge / blender (zero fresh pigment injection)+ * - amountOfPaint = 1.0: pure fresh paint layering (zero canvas contamination)+ * - 0 < amountOfPaint < 1: exact distance-normalized equilibrium between canvas & fresh color*/public mixWithCanvas(sampledColor: RgbaColor,amountOfPaint: number, // 0.0 (pure smudge) to 1.0 (fresh pigment only)densityOfPaint: number, // 0.0 to 1.0 (paint deposition opacity)colorStretch: number, // 0.0 to 1.0 (drag length)- mixingMode: 'blend' | 'running_color' | 'smear' = 'blend',+ mixingMode: NaturalMixingMode = 'blend',pressure: number = 0.5,flow: number = 0.85,stepDist: number = 0,- perceptualMixing: boolean = true+ perceptualMixing: boolean = true,+ pressureAlreadyAppliedToFlow: boolean = false): { r: number; g: number; b: number; alpha: number; colorHex: string } {this.cumulativeDistance += stepDist;const clampedAmount = Math.max(0, Math.min(1, amountOfPaint));+ const clampedStretch = Math.max(0, Math.min(1, colorStretch));const isPureSmudge = clampedAmount <= 0.005 || mixingMode === 'smear';+ const isFullFresh = !isPureSmudge && clampedAmount >= 0.995;const canvasAlpha = sampledColor.a;const mixFn = (c1: RgbColor, c2: RgbColor, w2: number): RgbColor => {@@ -694,14 +894,21 @@ export class PaintReservoir {};};- if (canvasAlpha > 0.015) {+ const origColor: RgbColor = {+ r: this.originalR,+ g: this.originalG,+ b: this.originalB,+ };++ if (isFullFresh) {+ // 100% Amount of Paint: clean opaque fresh layering without underlying color bleed+ this.r = this.originalR;+ this.g = this.originalG;+ this.b = this.originalB;+ this.a = 1.0;+ } else if (canvasAlpha > 0.015) {// Contact with existing paint on canvasconst pressureInfluence = pressure * 0.5 + 0.5;- const origColor: RgbColor = {- r: this.originalR,- g: this.originalG,- b: this.originalB,- };const targetColor: RgbColor = {r: sampledColor.r,g: sampledColor.g,@@ -716,7 +923,6 @@ export class PaintReservoir {if (isPureSmudge) {// Pure Smudge / Smear: drags underlying pigment with zero fresh foreground injectionif (!this.isLoadedWithCanvasColor) {- // First contact with painted canvas: snap reservoir cleanly to canvas pigmentthis.r = targetColor.r;this.g = targetColor.g;this.b = targetColor.b;@@ -724,90 +930,68 @@ export class PaintReservoir {this.isLoadedWithCanvasColor = true;this.cumulativeDistance = 0;} else {- const pickupRate = Math.min(0.96, canvasAlpha * (0.35 + (1.0 - colorStretch) * 0.55) * pressureInfluence);- const mixed = mixFn(currentColor, targetColor, pickupRate);+ const smudgeDist = 6 + clampedStretch * 46;+ const stepRate =+ stepDist > 0+ ? 1.0 - Math.exp(-(stepDist * canvasAlpha * pressureInfluence) / smudgeDist)+ : Math.min(0.85, canvasAlpha * (0.45 + (1.0 - clampedStretch) * 0.45) * pressureInfluence);+ const mixed = mixFn(currentColor, targetColor, stepRate);this.r = mixed.r;this.g = mixed.g;this.b = mixed.b;this.a = Math.min(1.0, this.a * 0.72 + canvasAlpha * 0.28);this.cumulativeDistance = 0;}- } else if (mixingMode === 'running_color') {- // Step 1: Absorb underlying canvas pigment into wet bristles (does not self-brighten on own trail)- const pickupScale = stepDist > 0 ? Math.min(1.0, Math.max(0.2, stepDist / 2.5)) : 1.0;- const pickupRate = Math.min(- 0.9,- (1.0 - clampedAmount * 0.6) * canvasAlpha * pressureInfluence * pickupScale * 1.15- );- let mixed = mixFn(currentColor, targetColor, pickupRate);- // Step 2: Distance-normalized fresh pigment feed from bristle ferrule governed by colorStretch- const replenishDist = Math.max(- 24,- (0.15 + colorStretch * 0.85) * (320 / Math.max(0.12, clampedAmount))- );- const feedRate =- stepDist > 0 ? 1.0 - Math.exp(-stepDist / replenishDist) : clampedAmount * 0.35;- mixed = mixFn(mixed, origColor, feedRate);+ } else {+ // Exact continuous-distance equilibrium ODE:+ // dC/ds = kPickup * (C_canvas - C) + kFeed * (C_fg - C)+ // Guarantees step-size invariance and prevents underlying paint from swallowing fresh paint!+ const isRunning = mixingMode === 'running_color';+ const modePickupMult = isRunning ? 1.45 : 1.0;+ const wCanvas = (1.0 - clampedAmount) * modePickupMult * canvasAlpha * (0.65 + 0.35 * pressureInfluence);+ const wFresh = clampedAmount * (isRunning ? 0.85 : 1.0);+ const wTotal = wCanvas + wFresh;+ const eqFreshRatio = wTotal > 1e-4 ? wFresh / wTotal : 1.0;++ const equilibrium = mixFn(targetColor, origColor, eqFreshRatio);+ // Pickup responds crisply on contact; colorStretch governs how far picked-up color drags+ const pickupDist = isRunning+ ? 7 + clampedStretch * 18+ : 9 + clampedStretch * 24;+ const stepRate =+ stepDist > 0+ ? 1.0 - Math.exp(-(stepDist * Math.max(0.55, wTotal)) / pickupDist)+ : Math.min(0.52, (1.0 - eqFreshRatio) * 0.7 * canvasAlpha * pressureInfluence);++ const mixed = mixFn(currentColor, equilibrium, stepRate);this.r = mixed.r;this.g = mixed.g;this.b = mixed.b;this.a = Math.min(1.0, this.a + 0.3);this.isLoadedWithCanvasColor = true;this.cumulativeDistance = 0;- } else {- // CSP Blend mode: Step 1 absorb canvas pigment; Step 2 continuous ferrule replenishment per distance- if (stepDist <= 0) {- const equilibrium = mixFn(targetColor, origColor, clampedAmount);- const mixed = mixFn(currentColor, equilibrium, 0.65 * canvasAlpha * pressureInfluence);- this.r = mixed.r;- this.g = mixed.g;- this.b = mixed.b;- } else {- const stepScale = Math.min(1.0, Math.max(0.18, stepDist / 3.0));- const pickupRate = Math.min(- 0.82,- (1.0 - clampedAmount * 0.72) * canvasAlpha * pressureInfluence * stepScale- );- let mixed = mixFn(currentColor, targetColor, pickupRate);- const replenishDist = Math.max(- 14,- (0.2 + colorStretch * 0.8) * (160 / Math.max(0.12, clampedAmount))- );- const feedRate = 1.0 - Math.exp(-stepDist / replenishDist);- mixed = mixFn(mixed, origColor, feedRate);- this.r = mixed.r;- this.g = mixed.g;- this.b = mixed.b;- }- this.isLoadedWithCanvasColor = true;}} else {// Moving into unpainted / dry area: apply Color Stretch decayif (isPureSmudge && !this.isLoadedWithCanvasColor) {- // Pure blender on untouched transparent canvas must not emit foreground colorthis.a = 0;return { r: 0, g: 0, b: 0, alpha: 0, colorHex: '#000000' };}if (this.isLoadedWithCanvasColor && stepDist > 0) {- const stretchDistanceLimit = Math.max(24, colorStretch * 800);+ const stretchDistanceLimit = Math.max(24, clampedStretch * 720);const decayRate = 1.0 - Math.exp(-stepDist / stretchDistanceLimit);if (isPureSmudge) {- // Pure Smudge runs out of paint when dragging away from painted areas- this.a = Math.max(0, this.a * (1.0 - decayRate * 1.6));+ this.a = Math.max(0, this.a * (1.0 - decayRate * 1.55));} else {- // Smoothly recovers brush's fresh foreground pigment- const origColor: RgbColor = {- r: this.originalR,- g: this.originalG,- b: this.originalB,- };const currColor: RgbColor = {r: this.r,g: this.g,b: this.b,};- const recovered = mixFn(currColor, origColor, Math.min(1.0, decayRate * (0.6 + clampedAmount * 0.8)));+ const recoverDist = Math.max(24, (0.2 + clampedStretch * 0.8) * (280 / Math.max(0.15, clampedAmount)));+ const recoverRate = 1.0 - Math.exp(-stepDist / recoverDist);+ const recovered = mixFn(currColor, origColor, recoverRate);this.r = recovered.r;this.g = recovered.g;this.b = recovered.b;@@ -815,16 +999,12 @@ export class PaintReservoir {}}- // Output dab opacity based on Density of Paint, Flow, and Pressure- let dabAlpha: number;+ // Output dab opacity based on Density of Paint, Flow, and Pressure (avoid double-applying pressure)const effPressure = Math.min(1.0, Math.max(0.05, pressure));- const pressureMod = effPressure * 0.7 + 0.3;-- if (isPureSmudge) {- dabAlpha = flow * pressureMod * densityOfPaint * this.a;- } else {- dabAlpha = flow * pressureMod * densityOfPaint;- }+ const pressureMod = pressureAlreadyAppliedToFlow ? 1.0 : effPressure * 0.65 + 0.35;+ const dabAlpha = isPureSmudge+ ? flow * pressureMod * densityOfPaint * this.a+ : flow * pressureMod * densityOfPaint;const finalR = Math.round(Math.max(0, Math.min(255, this.r)));const finalG = Math.round(Math.max(0, Math.min(255, this.g)));@@ -841,3 +1021,461 @@ export class PaintReservoir {};}}++// -------------------------------------------------------------+// Spatial Per-Bristle Paint Pickup Reservoir (Natural Paint Engine)+// Structure-of-Arrays (SoA) typed buffers for 4..64 independent bristle channels.+// Eliminates single-average-color muddiness so each side of a brush drags its own+// picked-up pigment streaks independently around curves!+// -------------------------------------------------------------++export const MAX_BRISTLE_CHANNELS = 64;++export interface BristleStepOutput {+ r: number;+ g: number;+ b: number;+ alpha: number;+ load: number;+ height: number;+}++interface DirtyBristleSnapshot {+ count: number;+ r: Float32Array;+ g: Float32Array;+ b: Float32Array;+ a: Float32Array;+ load: Float32Array;+ hasCanvas: Uint8Array;+}++const dirtyBrushRegistry = new Map<string, DirtyBristleSnapshot>();++/**+ * Cleans a persistent dirty brush reservoir (or all brushes when key is omitted).+ */+export function cleanDirtyBrush(presetKey?: string): void {+ if (presetKey) {+ dirtyBrushRegistry.delete(presetKey);+ } else {+ dirtyBrushRegistry.clear();+ }+}++/**+ * Returns true if a brush currently carries dirty pigment from a previous stroke.+ */+export function hasDirtyBrushState(presetKey: string): boolean {+ return dirtyBrushRegistry.has(presetKey);+}++function deterministicBristleRand(seed: number): () => number {+ let a = (seed ^ 0x9e3779b9) | 0;+ let b = (seed * 1664525 + 1013904223) | 0;+ let c = (seed ^ 0xb7e15162) | 0;+ let d = (seed ^ 0x8aed2a6b) | 0;+ return () => {+ a |= 0;+ b |= 0;+ c |= 0;+ d |= 0;+ const t = (((a + b) | 0) + d) | 0;+ d = (d + 1) | 0;+ a = b ^ (b >>> 9);+ b = (c + (c << 3)) | 0;+ c = (c << 21) | (c >>> 11);+ c = (c + t) | 0;+ return (t >>> 0) / 4294967296;+ };+}++export class SpatialBristleReservoir {+ public count: number = 28;+ public readonly offsets = new Float32Array(MAX_BRISTLE_CHANNELS); // [-1..+1] across brush normal+ public readonly radii = new Float32Array(MAX_BRISTLE_CHANNELS); // relative strand radius+ public readonly lengthFactors = new Float32Array(MAX_BRISTLE_CHANNELS); // [0.35..1.0] outer strands dry earlier+ public readonly grooveWeights = new Float32Array(MAX_BRISTLE_CHANNELS); // bristle relief height profile+ public readonly startDelay = new Float32Array(MAX_BRISTLE_CHANNELS); // [0..1] staggered bristle touchdown+ public readonly wanderPhase = new Float32Array(MAX_BRISTLE_CHANNELS); // organic strand meander phase+ public readonly wanderFreq = new Float32Array(MAX_BRISTLE_CHANNELS); // organic strand meander spatial freq+ public readonly r = new Float32Array(MAX_BRISTLE_CHANNELS);+ public readonly g = new Float32Array(MAX_BRISTLE_CHANNELS);+ public readonly b = new Float32Array(MAX_BRISTLE_CHANNELS);+ public readonly a = new Float32Array(MAX_BRISTLE_CHANNELS);+ public readonly load = new Float32Array(MAX_BRISTLE_CHANNELS);+ public readonly hasCanvas = new Uint8Array(MAX_BRISTLE_CHANNELS);++ public originalR: number = 0;+ public originalG: number = 0;+ public originalB: number = 0;+ public initialPaintLoad: number = 0.85;+ private presetKey: string | null = null;+ private autoClean: boolean = true;++ private readonly scratchC1: RgbColor = { r: 0, g: 0, b: 0 };+ private readonly scratchC2: RgbColor = { r: 0, g: 0, b: 0 };+ private readonly scratchOrig: RgbColor = { r: 0, g: 0, b: 0 };++ constructor(+ baseColorHex: string = '#000000',+ bristle?: Partial<BristleSettings>,+ natural?: Partial<NaturalPaintSettings>,+ presetKey?: string+ ) {+ this.reset(baseColorHex, bristle, natural, presetKey);+ }++ public reset(+ baseColorHex: string,+ bristle?: Partial<BristleSettings>,+ natural?: Partial<NaturalPaintSettings>,+ presetKey?: string,+ seed: number = 1337+ ): void {+ const rgb = parseColorToRgb(baseColorHex);+ this.originalR = rgb.r;+ this.originalG = rgb.g;+ this.originalB = rgb.b;+ this.presetKey = presetKey ?? null;+ this.autoClean = natural?.autoClean !== false;++ const profile: BristleProfilePreset = bristle?.profile ?? 'filbert';+ const rawCount = Math.round(bristle?.count ?? 28);+ this.count = Math.max(4, Math.min(MAX_BRISTLE_CHANNELS, rawCount));++ const clumping = Math.max(0, Math.min(1, bristle?.clumping ?? 0.35));+ const irregularity = Math.max(0, Math.min(1, bristle?.irregularity ?? 0.35));+ const edgeRidge = Math.max(0, Math.min(1, bristle?.edgeRidge ?? 0.2));+ const initLoad = Math.max(0, Math.min(1, natural?.paintLoad ?? 0.85));+ this.initialPaintLoad = initLoad;++ const rand = deterministicBristleRand(+ seed + this.count * 73 + Math.round(clumping * 1000) * 19 + Math.round(irregularity * 1000) * 31+ );++ // Generate organic macro clump centers so bristles form bold primary oil ribs + fine secondary striations!+ const clumpCount =+ profile === 'rake'+ ? Math.max(4, Math.round(this.count * (0.48 - clumping * 0.24)))+ : Math.max(4, Math.round(6 + (1.0 - clumping) * 7));+ const clumpCenters = new Float32Array(clumpCount);+ const clumpHeights = new Float32Array(clumpCount);+ for (let c = 0; c < clumpCount; c++) {+ const u = clumpCount > 1 ? (c / (clumpCount - 1)) * 2 - 1 : 0;+ clumpCenters[c] = u + (rand() - 0.5) * 0.16 * Math.max(0.25, irregularity);+ // Alternating bold high paint ribs & deeper carved canyons between clumps (Reference Photo 1!)+ clumpHeights[c] = 0.62 + rand() * 0.68;+ }++ const n = this.count;+ for (let i = 0; i < n; i++) {+ const u = n > 1 ? (i / (n - 1)) * 2 - 1 : 0; // [-1, +1]+ const absU = Math.abs(u);++ // Pull toward nearest clump center+ let nearest = u;+ let nearestIdx = 0;+ let bestD = 99;+ for (let c = 0; c < clumpCount; c++) {+ const d = Math.abs(u - clumpCenters[c]);+ if (d < bestD) {+ bestD = d;+ nearest = clumpCenters[c];+ nearestIdx = c;+ }+ }+ const clumpPull = profile === 'rake' ? clumping * 0.54 : profile === 'knife' ? 0 : clumping * 0.72;+ let offset = u + (nearest - u) * clumpPull;+ offset += (rand() - 0.5) * (2.0 / Math.max(4, n)) * (profile === 'rake' ? 0.52 : 0.92) * irregularity;+ this.offsets[i] = Math.max(-1.0, Math.min(1.0, offset));++ // Profile-dependent strand length & density envelope+ let profileEnvelope = 1.0;+ if (profile === 'round') {+ profileEnvelope = Math.sqrt(Math.max(0.18, 1.0 - absU * absU * 0.88));+ } else if (profile === 'filbert') {+ profileEnvelope = Math.pow(Math.max(0.25, 1.0 - Math.pow(absU, 2.6) * 0.72), 0.7);+ } else if (profile === 'fan') {+ profileEnvelope = 0.62 + 0.38 * (1.0 - absU * 0.55);+ } else if (profile === 'rake') {+ profileEnvelope = 0.78 + 0.22 * (1.0 - absU * 0.3);+ } else if (profile === 'knife') {+ profileEnvelope = 1.0;+ } else {+ // flat / custom+ profileEnvelope = 1.0 - Math.pow(absU, 5) * 0.25;+ }++ // Shorter/outer bristles exhaust paint earlier -> organic dry-brush fringes!+ const lenVar = 1.0 - rand() * irregularity * 0.52;+ this.lengthFactors[i] = Math.max(0.32, Math.min(1.0, profileEnvelope * lenVar));++ // Staggered longitudinal entry & organic hair meander (eliminates flat ruler-cut stroke starts!)+ const edgeStagger = profile === 'knife' ? 0.04 : Math.pow(absU, 1.55) * 0.65;+ this.startDelay[i] = Math.max(0, Math.min(1, edgeStagger + rand() * (0.28 + irregularity * 0.48)));+ this.wanderPhase[i] = rand() * Math.PI * 2;+ this.wanderFreq[i] = 0.012 + rand() * 0.022;++ // Relative strand radius (varied organic tufts: bold macro paint ribs + delicate fine hairs!)+ const baseShare = 2.0 / Math.max(4, n);+ const sepFactor =+ profile === 'rake'+ ? 0.54+ : profile === 'fan'+ ? 0.56+ : profile === 'knife'+ ? 1.25+ : 0.84 + clumping * 0.22;+ const sizeMix = 0.52 + Math.pow(rand(), 0.8) * 1.05 * Math.max(0.35, irregularity);+ this.radii[i] = Math.max(0.014, baseShare * sepFactor * sizeMix);++ // Multi-scale sculptural relief: clump macro height + inner strand crown + edge paint ridge!+ const edgeBoost = absU > 0.70 ? Math.pow((absU - 0.70) / 0.30, 1.25) * edgeRidge * 1.35 : 0;+ const clumpCrest = clumpHeights[nearestIdx] * (1.0 - Math.min(0.65, bestD * 2.4));+ const tuftContrast = 0.32 + clumpCrest * 0.55 + Math.pow(rand(), 0.75) * 0.42;+ const strandPeak =+ profile === 'knife'+ ? 0.58 + edgeBoost * 1.35+ : (0.38 + 0.62 * profileEnvelope) * tuftContrast + edgeBoost;+ this.grooveWeights[i] = Math.max(0.20, Math.min(1.85, strandPeak));++ this.r[i] = rgb.r;+ this.g[i] = rgb.g;+ this.b[i] = rgb.b;+ this.a[i] = initLoad > 0.005 ? 1.0 : 0.0;+ this.load[i] = initLoad * (0.82 + 0.18 * this.lengthFactors[i]);+ this.hasCanvas[i] = 0;+ }++ // Restore persistent dirty-brush pigment if autoClean is disabled+ if (!this.autoClean && this.presetKey) {+ const snap = dirtyBrushRegistry.get(this.presetKey);+ if (snap && snap.count === this.count) {+ const reloadMix = initLoad > 0.005 ? 0.25 : 0.0; // Dipping a dirty brush partially refreshes load+ for (let i = 0; i < n; i++) {+ this.r[i] = snap.r[i] * (1 - reloadMix) + rgb.r * reloadMix;+ this.g[i] = snap.g[i] * (1 - reloadMix) + rgb.g * reloadMix;+ this.b[i] = snap.b[i] * (1 - reloadMix) + rgb.b * reloadMix;+ this.a[i] = Math.max(snap.a[i], initLoad > 0.005 ? 0.85 : 0);+ this.load[i] = Math.min(1.0, Math.max(snap.load[i], initLoad * 0.75));+ this.hasCanvas[i] = snap.hasCanvas[i];+ }+ }+ }+ }++ /**+ * Persists current dirty bristle channels when `autoClean === false`.+ */+ public persistDirtyStateIfNeeded(): void {+ if (this.autoClean || !this.presetKey) return;+ dirtyBrushRegistry.set(this.presetKey, {+ count: this.count,+ r: new Float32Array(this.r),+ g: new Float32Array(this.g),+ b: new Float32Array(this.b),+ a: new Float32Array(this.a),+ load: new Float32Array(this.load),+ hasCanvas: new Uint8Array(this.hasCanvas),+ });+ }++ /**+ * Advances a single bristle channel `i` by `stepDist` pixels, performing local spatial+ * canvas pickup, Kubelka-Munk pigment mixing, viscosity damping, and paint load depletion+ * via step-size-invariant equilibrium blending.+ */+ public stepBristle(+ i: number,+ canvasSample: RgbaColor,+ stepDist: number,+ pressure: number,+ natural: Partial<NaturalPaintSettings>,+ mixingMode: NaturalMixingMode,+ colorStretch: number,+ amountOfPaint: number,+ densityOfPaint: number,+ flow: number,+ out: BristleStepOutput+ ): BristleStepOutput {+ const resolvedAmount = Number.isFinite(amountOfPaint)+ ? amountOfPaint+ : natural.paintLoad ?? 0.85;+ const effectiveAmount = Math.max(0, Math.min(1, resolvedAmount));+ const isPureBlender =+ effectiveAmount <= 0.005 ||+ (natural.paintLoad !== undefined && natural.paintLoad <= 0.005 && effectiveAmount <= 0.005) ||+ mixingMode === 'smear';+ const isFullFresh = !isPureBlender && effectiveAmount >= 0.995;+ const wetness = Math.max(0, Math.min(1, natural.wetness ?? (1.0 - effectiveAmount * 0.5)));+ const viscosity = Math.max(0, Math.min(1, natural.viscosity ?? 0.5));+ const depletionRate = Math.max(0, Math.min(1, natural.depletionRate ?? 0.25));+ const chargePerPressure = Math.max(0, Math.min(1, natural.chargePerPressure ?? 0.45));+ const pigmentStrength = Math.max(0, Math.min(1, natural.pigmentMixingStrength ?? 0.85));+ const spatialMixing = natural.spatialMixing !== false;+ const clampedStretch = Math.max(0, Math.min(1, colorStretch));+ const effPressure = Math.max(0.05, Math.min(1.0, pressure));++ // 1. Deplete paint load along arc length (shorter outer bristles exhaust earlier -> dry-brush tail)+ let curLoad = this.load[i];+ if (!isPureBlender && depletionRate > 0.001 && stepDist > 0) {+ const lengthInv = 1.0 / Math.max(0.32, this.lengthFactors[i]);+ // Distance scale: depletionRate=1.0 exhausts around ~160px; depletionRate=0.25 around ~900px+ const exhaustDist = 110 + (1.0 - depletionRate) * 1150;+ // Full paint load depletes slightly slower so layering strokes stay rich across the canvas+ const loadEndurance = 1.0 - effectiveAmount * 0.25;+ const drop =+ (stepDist / exhaustDist) *+ depletionRate *+ lengthInv *+ loadEndurance *+ (1.15 - chargePerPressure * effPressure * 0.45);+ curLoad = Math.max(0.0, curLoad - drop);+ this.load[i] = curLoad;+ }++ // Effective squeezed load under stylus pressure+ const squeezedLoad = isPureBlender+ ? this.a[i]+ : Math.max(0, Math.min(1, curLoad * (1.0 - chargePerPressure * 0.32 + chargePerPressure * 0.62 * effPressure)));++ // 2. Spatial per-bristle pickup from underlying canvas+ const canvasAlpha = spatialMixing ? canvasSample.a : 0;+ const viscosityResist = 1.0 - viscosity * 0.5;++ if (isFullFresh) {+ // 100% Amount of Paint / Paint Load: clean opaque layering with zero canvas color contamination+ this.r[i] = this.originalR;+ this.g[i] = this.originalG;+ this.b[i] = this.originalB;+ this.a[i] = 1.0;+ } else if (canvasAlpha > 0.015 && (wetness > 0.005 || isPureBlender)) {+ this.scratchC1.r = this.r[i];+ this.scratchC1.g = this.g[i];+ this.scratchC1.b = this.b[i];+ this.scratchC2.r = canvasSample.r;+ this.scratchC2.g = canvasSample.g;+ this.scratchC2.b = canvasSample.b;++ if (isPureBlender) {+ if (!this.hasCanvas[i]) {+ this.r[i] = canvasSample.r;+ this.g[i] = canvasSample.g;+ this.b[i] = canvasSample.b;+ this.a[i] = canvasAlpha;+ this.hasCanvas[i] = 1;+ } else {+ const smudgeDist = (7 + clampedStretch * 46) * (0.7 + viscosity * 0.55);+ const pickup =+ stepDist > 0+ ? 1.0 - Math.exp(-(stepDist * canvasAlpha * viscosityResist * (0.55 + 0.45 * effPressure)) / smudgeDist)+ : Math.min(0.75, canvasAlpha * viscosityResist * 0.45);+ const mixed = mixPigmentsWithStrength(this.scratchC1, this.scratchC2, pickup, pigmentStrength);+ this.r[i] = mixed.r;+ this.g[i] = mixed.g;+ this.b[i] = mixed.b;+ this.a[i] = Math.min(1.0, this.a[i] * 0.72 + canvasAlpha * 0.28);+ }+ } else {+ // Loaded brush crossing existing paint:+ // Exact continuous-distance equilibrium between local canvas sample & original brush pigment.+ // Amount of Paint strictly controls how strongly fresh pigment layers over underlying paint!+ const amountAllowance = Math.max(0, 1.0 - Math.pow(effectiveAmount, 1.9));+ const loadRatio = this.initialPaintLoad > 0.05 ? Math.min(1.0, curLoad / this.initialPaintLoad) : 0;+ const depletionPickupBoost = (1.0 - loadRatio) * 0.4 * (1.0 - effectiveAmount * 0.5);+ const modePickupMult =+ mixingMode === 'running_color' ? 1.35 : mixingMode === 'impasto_mix' ? 1.05 : 0.9;++ const wCanvas =+ 2.2 *+ wetness *+ canvasAlpha *+ viscosityResist *+ modePickupMult *+ (amountAllowance + depletionPickupBoost) *+ (0.55 + 0.45 * effPressure);+ const wFresh =+ effectiveAmount *+ (0.45 + 0.55 * curLoad) *+ (mixingMode === 'running_color' ? 0.65 : 1.0);+ const wTotal = wCanvas + wFresh;+ const eqFreshRatio = wTotal > 1e-4 ? wFresh / wTotal : 1.0;++ // Compute equilibrium target color: mix(canvas, original, eqFreshRatio)+ this.scratchOrig.r = this.originalR;+ this.scratchOrig.g = this.originalG;+ this.scratchOrig.b = this.originalB;+ const eqColor = mixPigmentsWithStrength(+ this.scratchC2,+ this.scratchOrig,+ eqFreshRatio,+ pigmentStrength+ );++ // Pickup responds smoothly on contact; colorStretch governs long ribbon carry+ const charDist = (9 + clampedStretch * 24) * (0.7 + viscosity * 0.55);+ const stepRate =+ stepDist > 0+ ? 1.0 - Math.exp(-(stepDist * Math.max(0.45, wTotal)) / charDist)+ : Math.min(0.35, (1.0 - eqFreshRatio) * 0.5 * canvasAlpha);++ const mixed = mixPigmentsWithStrength(this.scratchC1, eqColor, stepRate, pigmentStrength);+ this.r[i] = mixed.r;+ this.g[i] = mixed.g;+ this.b[i] = mixed.b;+ this.a[i] = Math.min(1.0, Math.max(this.a[i], 0.5 + curLoad * 0.5));+ this.hasCanvas[i] = 1;+ }+ } else if (stepDist > 0) {+ // Moving over dry / unpainted canvas+ if (isPureBlender) {+ if (!this.hasCanvas[i]) {+ out.r = 0;+ out.g = 0;+ out.b = 0;+ out.alpha = 0;+ out.load = 0;+ out.height = 0;+ return out;+ }+ const dragDist = Math.max(28, clampedStretch * 720);+ const decay = 1.0 - Math.exp(-stepDist / dragDist);+ this.a[i] = Math.max(0, this.a[i] * (1.0 - decay * 1.45));+ } else if (this.hasCanvas[i] && curLoad > 0.02) {+ // Smoothly recover toward brush's loaded color as picked-up streaks trail off+ const recoverDist = Math.max(24, (0.2 + clampedStretch * 0.8) * (220 / Math.max(0.18, effectiveAmount)));+ const recover = 1.0 - Math.exp(-stepDist / recoverDist);+ this.scratchC1.r = this.r[i];+ this.scratchC1.g = this.g[i];+ this.scratchC1.b = this.b[i];+ this.scratchC2.r = this.originalR;+ this.scratchC2.g = this.originalG;+ this.scratchC2.b = this.originalB;+ const recovered = mixPigmentsWithStrength(this.scratchC1, this.scratchC2, recover, pigmentStrength);+ this.r[i] = recovered.r;+ this.g[i] = recovered.g;+ this.b[i] = recovered.b;+ }+ }++ // 3. Output pigment, alpha & physical impasto groove height+ const loadCoverage = isPureBlender+ ? this.a[i]+ : Math.min(1.0, Math.pow(Math.max(0, squeezedLoad), 0.58) * 1.12);+ // Smooth pressure curve: light strokes softly glaze/blend; firm strokes layer opaquely+ const pressureAlpha = 0.22 + 0.78 * Math.pow(effPressure, 0.85);+ const outAlpha = Math.max(+ 0,+ Math.min(1, flow * densityOfPaint * loadCoverage * pressureAlpha)+ );++ out.r = Math.max(0, Math.min(255, this.r[i]));+ out.g = Math.max(0, Math.min(255, this.g[i]));+ out.b = Math.max(0, Math.min(255, this.b[i]));+ out.alpha = outAlpha;+ out.load = squeezedLoad;+ out.height = this.grooveWeights[i] * (0.28 + 0.72 * squeezedLoad) * (0.45 + 0.55 * effPressure);+ return out;+ }+}diff --git a/src/utils/gradientEngine.ts b/src/utils/gradientEngine.tsnew file mode 100644index 0000000..2e35301--- /dev/null+++ b/src/utils/gradientEngine.ts@@ -0,0 +1,891 @@+/**+ * Professional Gradient Engine — Linear, Radial, and Bicubic Mesh Gradients+ *+ * Tile-native rasterization directly into SparseTileGrid with:+ * - Multi-stop RGBA color interpolation (clamp, repeat, reflect)+ * - 4x4 Bayer ordered dithering to eliminate 8-bit banding+ * - Blend modes (normal, multiply, screen, overlay) + alpha-lock + selection mask clipping+ * - Catmull-Rom / bicubic subdivided Mesh Gradient with Gouraud triangle scanline rasterizer+ */++import type {+ CanvasDimensions,+ CanvasSelection,+ DirtyRect,+ Point2D,+ TileDelta,+} from '../types/editor';+import { createSelectionMask } from './tonalEngine';+import {+ BYTES_32BIT,+ SparseTileGrid,+ TILE_SIZE,+ TileFormat,+ TileSnapshotEntry,+ packRGBATo1Bit,+ packRGBATo8Bit,+ unpack1BitToRGBA,+ unpack8BitToRGBA,+} from './tileEngine';++export type GradientType = 'linear' | 'radial' | 'mesh';+export type GradientRepeatMode = 'clamp' | 'repeat' | 'reflect';+export type GradientBlendMode = 'normal' | 'multiply' | 'screen' | 'overlay';++export interface GradientToolStop {+ id: string;+ offset: number; // 0..1+ color: string; // #rrggbb+ opacity: number; // 0..1+}++export interface GradientMeshNode {+ x: number; // canvas coordinates+ y: number; // canvas coordinates+ color: string; // #rrggbb+ opacity: number; // 0..1+}++export interface GradientMeshState {+ cols: number;+ rows: number;+ nodes: GradientMeshNode[]; // row-major length = rows * cols+ selectedNodeIndex: number | null;+}++export interface GradientSettings {+ type: GradientType;+ stops: GradientToolStop[];+ useForegroundBackground: boolean;+ opacity: number; // 0.01..1+ blendMode: GradientBlendMode;+ repeat: GradientRepeatMode;+ dither: boolean;+ reverse: boolean;+ meshCols: number; // 2..6+ meshRows: number; // 2..6+}++export interface GradientDragPreview {+ type: 'linear' | 'radial';+ start: Point2D;+ end: Point2D;+ settings: GradientSettings;+}++export interface GradientPreset {+ id: string;+ name: string;+ useForegroundBackground?: boolean;+ stops: Array<{ offset: number; color: string; opacity: number }>;+}++export const GRADIENT_PRESETS: readonly GradientPreset[] = [+ {+ id: 'fg-bg',+ name: 'FG to BG',+ useForegroundBackground: true,+ stops: [+ { offset: 0, color: '#000000', opacity: 1 },+ { offset: 1, color: '#ffffff', opacity: 1 },+ ],+ },+ {+ id: 'fg-transparent',+ name: 'FG to Clear',+ useForegroundBackground: false,+ stops: [+ { offset: 0, color: '#000000', opacity: 1 },+ { offset: 1, color: '#000000', opacity: 0 },+ ],+ },+ {+ id: 'sunset',+ name: 'Sunset',+ useForegroundBackground: false,+ stops: [+ { offset: 0, color: '#1e1b4b', opacity: 1 },+ { offset: 0.45, color: '#be185d', opacity: 1 },+ { offset: 0.78, color: '#f97316', opacity: 1 },+ { offset: 1, color: '#fde047', opacity: 1 },+ ],+ },+ {+ id: 'sky',+ name: 'Sky',+ useForegroundBackground: false,+ stops: [+ { offset: 0, color: '#0c4a6e', opacity: 1 },+ { offset: 0.55, color: '#38bdf8', opacity: 1 },+ { offset: 1, color: '#f0f9ff', opacity: 1 },+ ],+ },+ {+ id: 'chrome',+ name: 'Chrome',+ useForegroundBackground: false,+ stops: [+ { offset: 0, color: '#111827', opacity: 1 },+ { offset: 0.35, color: '#e5e7eb', opacity: 1 },+ { offset: 0.52, color: '#374151', opacity: 1 },+ { offset: 0.8, color: '#f9fafb', opacity: 1 },+ { offset: 1, color: '#1f2937', opacity: 1 },+ ],+ },+ {+ id: 'spectrum',+ name: 'Spectrum',+ useForegroundBackground: false,+ stops: [+ { offset: 0, color: '#ef4444', opacity: 1 },+ { offset: 0.2, color: '#f59e0b', opacity: 1 },+ { offset: 0.4, color: '#22c55e', opacity: 1 },+ { offset: 0.6, color: '#06b6d4', opacity: 1 },+ { offset: 0.8, color: '#6366f1', opacity: 1 },+ { offset: 1, color: '#ec4899', opacity: 1 },+ ],+ },+];++export const DEFAULT_GRADIENT_SETTINGS: GradientSettings = {+ type: 'linear',+ stops: [+ { id: 'stop-0', offset: 0, color: '#000000', opacity: 1 },+ { id: 'stop-1', offset: 1, color: '#ffffff', opacity: 1 },+ ],+ useForegroundBackground: true,+ opacity: 1,+ blendMode: 'normal',+ repeat: 'clamp',+ dither: true,+ reverse: false,+ meshCols: 3,+ meshRows: 3,+};++// Normalized 4x4 Bayer matrix in [-0.5, +0.5] for 8-bit anti-banding dither+const BAYER_4X4 = new Float32Array([+ 0 / 16 - 0.5, 8 / 16 - 0.5, 2 / 16 - 0.5, 10 / 16 - 0.5,+ 12 / 16 - 0.5, 4 / 16 - 0.5, 14 / 16 - 0.5, 6 / 16 - 0.5,+ 3 / 16 - 0.5, 11 / 16 - 0.5, 1 / 16 - 0.5, 9 / 16 - 0.5,+ 15 / 16 - 0.5, 7 / 16 - 0.5, 13 / 16 - 0.5, 5 / 16 - 0.5,+]);++export interface ParsedRgbaStop {+ offset: number;+ r: number;+ g: number;+ b: number;+ a: number;+}++export function parseHexRgb(hex: string): [number, number, number] {+ if (typeof hex !== 'string') return [0, 0, 0];+ const cleaned = hex.trim().replace(/^#/, '');+ if (cleaned.length === 3) {+ const r = parseInt(cleaned[0] + cleaned[0], 16);+ const g = parseInt(cleaned[1] + cleaned[1], 16);+ const b = parseInt(cleaned[2] + cleaned[2], 16);+ if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) {+ return [r, g, b];+ }+ } else if (cleaned.length >= 6) {+ const r = parseInt(cleaned.slice(0, 2), 16);+ const g = parseInt(cleaned.slice(2, 4), 16);+ const b = parseInt(cleaned.slice(4, 6), 16);+ if (!Number.isNaN(r) && !Number.isNaN(g) && !Number.isNaN(b)) {+ return [r, g, b];+ }+ }+ return [0, 0, 0];+}++export function resolveGradientStops(+ settings: GradientSettings,+ primaryColor: string,+ secondaryColor: string+): ParsedRgbaStop[] {+ const raw = settings.stops.length >= 2 ? settings.stops : DEFAULT_GRADIENT_SETTINGS.stops;+ const sorted = [...raw]+ .map((s) => ({+ offset: Math.max(0, Math.min(1, Number.isFinite(s.offset) ? s.offset : 0)),+ color: s.color,+ opacity: Math.max(0, Math.min(1, Number.isFinite(s.opacity) ? s.opacity : 1)),+ }))+ .sort((a, b) => a.offset - b.offset);++ if (settings.useForegroundBackground && sorted.length >= 2) {+ sorted[0] = { ...sorted[0], color: primaryColor || '#000000' };+ sorted[sorted.length - 1] = {+ ...sorted[sorted.length - 1],+ color: secondaryColor || '#ffffff',+ };+ }++ return sorted.map((s) => {+ const [r, g, b] = parseHexRgb(s.color);+ return { offset: s.offset, r, g, b, a: s.opacity * 255 };+ });+}++function wrapGradientT(t: number, repeat: GradientRepeatMode, reverse: boolean): number {+ let u = Number.isFinite(t) ? t : 0;+ if (repeat === 'repeat') {+ u = u - Math.floor(u);+ } else if (repeat === 'reflect') {+ const period = u - 2 * Math.floor(u * 0.5);+ u = period <= 1 ? period : 2 - period;+ } else {+ u = u < 0 ? 0 : u > 1 ? 1 : u;+ }+ return reverse ? 1 - u : u;+}++/**+ * Evaluates multi-stop RGBA color at scalar position `t`.+ */+export function sampleGradientStops(+ stops: readonly ParsedRgbaStop[],+ t: number,+ repeat: GradientRepeatMode,+ reverse: boolean,+ out: [number, number, number, number]+): void {+ if (stops.length === 0) {+ out[0] = 0;+ out[1] = 0;+ out[2] = 0;+ out[3] = 0;+ return;+ }+ const u = wrapGradientT(t, repeat, reverse);+ if (u <= stops[0].offset || stops.length === 1) {+ const s = stops[0];+ out[0] = s.r;+ out[1] = s.g;+ out[2] = s.b;+ out[3] = s.a;+ return;+ }+ const last = stops[stops.length - 1];+ if (u >= last.offset) {+ out[0] = last.r;+ out[1] = last.g;+ out[2] = last.b;+ out[3] = last.a;+ return;+ }++ let hi = 1;+ while (hi < stops.length - 1 && stops[hi].offset < u) {+ hi++;+ }+ const s0 = stops[hi - 1];+ const s1 = stops[hi];+ const span = s1.offset - s0.offset;+ const f = span > 1e-6 ? (u - s0.offset) / span : 0;+ out[0] = s0.r + (s1.r - s0.r) * f;+ out[1] = s0.g + (s1.g - s0.g) * f;+ out[2] = s0.b + (s1.b - s0.b) * f;+ out[3] = s0.a + (s1.a - s0.a) * f;+}++/**+ * Snaps end point to 15-degree increments relative to start when Shift is held.+ */+export function constrainGradientEndpoint(start: Point2D, end: Point2D): Point2D {+ const dx = end.x - start.x;+ const dy = end.y - start.y;+ const len = Math.hypot(dx, dy);+ if (len < 1e-4) return end;+ const angle = Math.atan2(dy, dx);+ const snapped = Math.round(angle / (Math.PI / 12)) * (Math.PI / 12);+ return {+ x: start.x + Math.cos(snapped) * len,+ y: start.y + Math.sin(snapped) * len,+ };+}++/**+ * Generates an initial interactive Mesh Gradient grid over `bounds`.+ */+export function createDefaultGradientMesh(+ bounds: { x: number; y: number; width: number; height: number },+ cols: number,+ rows: number,+ primaryColor: string,+ secondaryColor: string,+ stops?: readonly GradientToolStop[]+): GradientMeshState {+ const cCount = Math.max(2, Math.min(6, Math.round(cols)));+ const rCount = Math.max(2, Math.min(6, Math.round(rows)));+ const w = Math.max(1, bounds.width);+ const h = Math.max(1, bounds.height);++ const cornerColors = [+ primaryColor || '#3b82f6',+ secondaryColor || '#f43f5e',+ stops && stops.length > 2 ? stops[Math.floor(stops.length / 2)].color : '#10b981',+ stops && stops.length > 0 ? stops[stops.length - 1].color : '#f59e0b',+ ];+ const parsedCorners = cornerColors.map((c) => parseHexRgb(c));++ const nodes: GradientMeshNode[] = [];+ for (let r = 0; r < rCount; r++) {+ const v = rCount > 1 ? r / (rCount - 1) : 0;+ for (let c = 0; c < cCount; c++) {+ const u = cCount > 1 ? c / (cCount - 1) : 0;+ const topR = parsedCorners[0][0] * (1 - u) + parsedCorners[1][0] * u;+ const topG = parsedCorners[0][1] * (1 - u) + parsedCorners[1][1] * u;+ const topB = parsedCorners[0][2] * (1 - u) + parsedCorners[1][2] * u;+ const botR = parsedCorners[2][0] * (1 - u) + parsedCorners[3][0] * u;+ const botG = parsedCorners[2][1] * (1 - u) + parsedCorners[3][1] * u;+ const botB = parsedCorners[2][2] * (1 - u) + parsedCorners[3][2] * u;+ const rr = Math.round(topR * (1 - v) + botR * v);+ const gg = Math.round(topG * (1 - v) + botG * v);+ const bb = Math.round(topB * (1 - v) + botB * v);+ const hex =+ '#' ++ rr.toString(16).padStart(2, '0') ++ gg.toString(16).padStart(2, '0') ++ bb.toString(16).padStart(2, '0');+ nodes.push({+ x: bounds.x + u * w,+ y: bounds.y + v * h,+ color: hex,+ opacity: 1,+ });+ }+ }++ return {+ cols: cCount,+ rows: rCount,+ nodes,+ selectedNodeIndex: 0,+ };+}++function blendChannel(src: number, dst: number, mode: GradientBlendMode): number {+ const s = src / 255;+ const d = dst / 255;+ let out: number;+ switch (mode) {+ case 'multiply':+ out = s * d;+ break;+ case 'screen':+ out = 1 - (1 - s) * (1 - d);+ break;+ case 'overlay':+ out = d < 0.5 ? 2 * s * d : 1 - 2 * (1 - s) * (1 - d);+ break;+ case 'normal':+ default:+ out = s;+ break;+ }+ return out * 255;+}++function compositePixelInPlace(+ buf: Uint8ClampedArray,+ idx: number,+ sr: number,+ sg: number,+ sb: number,+ saNorm: number,+ blendMode: GradientBlendMode,+ alphaLock: boolean,+ ditherVal: number+): void {+ if (saNorm <= 0) return;+ const dr = buf[idx];+ const dg = buf[idx + 1];+ const db = buf[idx + 2];+ const da = buf[idx + 3] / 255;++ if (alphaLock && da <= 0) return;++ const br = blendMode === 'normal' || da <= 0 ? sr : blendChannel(sr, dr, blendMode);+ const bg = blendMode === 'normal' || da <= 0 ? sg : blendChannel(sg, dg, blendMode);+ const bb = blendMode === 'normal' || da <= 0 ? sb : blendChannel(sb, db, blendMode);++ if (alphaLock) {+ const r = dr * (1 - saNorm) + br * saNorm + ditherVal;+ const g = dg * (1 - saNorm) + bg * saNorm + ditherVal;+ const b = db * (1 - saNorm) + bb * saNorm + ditherVal;+ buf[idx] = r < 0 ? 0 : r > 255 ? 255 : Math.round(r);+ buf[idx + 1] = g < 0 ? 0 : g > 255 ? 255 : Math.round(g);+ buf[idx + 2] = b < 0 ? 0 : b > 255 ? 255 : Math.round(b);+ return;+ }++ const outA = saNorm + da * (1 - saNorm);+ if (outA <= 1e-6) return;++ const invOutA = 1 / outA;+ // Blend source color against backdrop where backdrop exists, otherwise use raw source color+ const mixR = (da > 0 ? br * da + sr * (1 - da) : sr) * saNorm + dr * da * (1 - saNorm);+ const mixG = (da > 0 ? bg * da + sg * (1 - da) : sg) * saNorm + dg * da * (1 - saNorm);+ const mixB = (da > 0 ? bb * da + sb * (1 - da) : sb) * saNorm + db * da * (1 - saNorm);++ const r = mixR * invOutA + ditherVal;+ const g = mixG * invOutA + ditherVal;+ const b = mixB * invOutA + ditherVal;+ const a = outA * 255;++ buf[idx] = r < 0 ? 0 : r > 255 ? 255 : Math.round(r);+ buf[idx + 1] = g < 0 ? 0 : g > 255 ? 255 : Math.round(g);+ buf[idx + 2] = b < 0 ? 0 : b > 255 ? 255 : Math.round(b);+ buf[idx + 3] = a < 0 ? 0 : a > 255 ? 255 : Math.round(a);+}++function catmullRomScalar(p0: number, p1: number, p2: number, p3: number, t: number): number {+ const t2 = t * t;+ const t3 = t2 * t;+ return (+ 0.5 *+ (2 * p1 ++ (-p0 + p2) * t ++ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 ++ (-p0 + 3 * p1 - 3 * p2 + p3) * t3)+ );+}++interface MeshVertex {+ x: number;+ y: number;+ r: number;+ g: number;+ b: number;+ a: number;+}++function sampleMeshBicubic(+ nodes: readonly MeshVertex[],+ cols: number,+ rows: number,+ cellC: number,+ cellR: number,+ u: number,+ v: number+): MeshVertex {+ const clampC = (c: number) => (c < 0 ? 0 : c >= cols ? cols - 1 : c);+ const clampR = (r: number) => (r < 0 ? 0 : r >= rows ? rows - 1 : r);++ const rx = [0, 0, 0, 0];+ const ry = [0, 0, 0, 0];+ const rr = [0, 0, 0, 0];+ const rg = [0, 0, 0, 0];+ const rb = [0, 0, 0, 0];+ const ra = [0, 0, 0, 0];++ for (let j = -1; j <= 2; j++) {+ const rIdx = clampR(cellR + j);+ const n0 = nodes[rIdx * cols + clampC(cellC - 1)];+ const n1 = nodes[rIdx * cols + clampC(cellC)];+ const n2 = nodes[rIdx * cols + clampC(cellC + 1)];+ const n3 = nodes[rIdx * cols + clampC(cellC + 2)];+ const k = j + 1;+ rx[k] = catmullRomScalar(n0.x, n1.x, n2.x, n3.x, u);+ ry[k] = catmullRomScalar(n0.y, n1.y, n2.y, n3.y, u);+ rr[k] = catmullRomScalar(n0.r, n1.r, n2.r, n3.r, u);+ rg[k] = catmullRomScalar(n0.g, n1.g, n2.g, n3.g, u);+ rb[k] = catmullRomScalar(n0.b, n1.b, n2.b, n3.b, u);+ ra[k] = catmullRomScalar(n0.a, n1.a, n2.a, n3.a, u);+ }++ const clamp255 = (val: number) => (val < 0 ? 0 : val > 255 ? 255 : val);+ return {+ x: catmullRomScalar(rx[0], rx[1], rx[2], rx[3], v),+ y: catmullRomScalar(ry[0], ry[1], ry[2], ry[3], v),+ r: clamp255(catmullRomScalar(rr[0], rr[1], rr[2], rr[3], v)),+ g: clamp255(catmullRomScalar(rg[0], rg[1], rg[2], rg[3], v)),+ b: clamp255(catmullRomScalar(rb[0], rb[1], rb[2], rb[3], v)),+ a: clamp255(catmullRomScalar(ra[0], ra[1], ra[2], ra[3], v)),+ };+}++function rasterizeTriangleIntoBuffer(+ outRgba: Uint8ClampedArray,+ bufWidth: number,+ bufHeight: number,+ originX: number,+ originY: number,+ v0: MeshVertex,+ v1: MeshVertex,+ v2: MeshVertex,+ dither: boolean+): void {+ const minX = Math.max(0, Math.floor(Math.min(v0.x, v1.x, v2.x) - originX));+ const maxX = Math.min(bufWidth - 1, Math.ceil(Math.max(v0.x, v1.x, v2.x) - originX));+ const minY = Math.max(0, Math.floor(Math.min(v0.y, v1.y, v2.y) - originY));+ const maxY = Math.min(bufHeight - 1, Math.ceil(Math.max(v0.y, v1.y, v2.y) - originY));+ if (minX > maxX || minY > maxY) return;++ const x0 = v0.x - originX;+ const y0 = v0.y - originY;+ const x1 = v1.x - originX;+ const y1 = v1.y - originY;+ const x2 = v2.x - originX;+ const y2 = v2.y - originY;++ const denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2);+ if (Math.abs(denom) < 1e-6) return;+ const invDenom = 1 / denom;++ for (let py = minY; py <= maxY; py++) {+ const cy = py + 0.5;+ const rowOffset = py * bufWidth;+ for (let px = minX; px <= maxX; px++) {+ const cx = px + 0.5;+ const w0 = ((y1 - y2) * (cx - x2) + (x2 - x1) * (cy - y2)) * invDenom;+ if (w0 < -1e-4) continue;+ const w1 = ((y2 - y0) * (cx - x2) + (x0 - x2) * (cy - y2)) * invDenom;+ if (w1 < -1e-4) continue;+ const w2 = 1 - w0 - w1;+ if (w2 < -1e-4) continue;++ const d = dither ? BAYER_4X4[((py & 3) << 2) | (px & 3)] : 0;+ const idx = (rowOffset + px) * 4;+ const r = v0.r * w0 + v1.r * w1 + v2.r * w2 + d;+ const g = v0.g * w0 + v1.g * w1 + v2.g * w2 + d;+ const b = v0.b * w0 + v1.b * w1 + v2.b * w2 + d;+ const a = v0.a * w0 + v1.a * w1 + v2.a * w2;++ outRgba[idx] = r < 0 ? 0 : r > 255 ? 255 : Math.round(r);+ outRgba[idx + 1] = g < 0 ? 0 : g > 255 ? 255 : Math.round(g);+ outRgba[idx + 2] = b < 0 ? 0 : b > 255 ? 255 : Math.round(b);+ outRgba[idx + 3] = a < 0 ? 0 : a > 255 ? 255 : Math.round(a);+ }+ }+}++/**+ * Renders a Mesh Gradient directly into an RGBA buffer covering `[originX, originY, width, height]`.+ * Used both for fast interactive preview canvases and for committing to SparseTileGrid tiles.+ */+export function rasterizeMeshGradientToRgba(+ mesh: GradientMeshState,+ originX: number,+ originY: number,+ width: number,+ height: number,+ scaleX = 1,+ scaleY = 1,+ dither = true,+ subdivisionsPerCell = 8+): Uint8ClampedArray {+ const out = new Uint8ClampedArray(width * height * 4);+ if (mesh.cols < 2 || mesh.rows < 2 || mesh.nodes.length < mesh.cols * mesh.rows) {+ return out;+ }++ const verts: MeshVertex[] = mesh.nodes.map((n) => {+ const [r, g, b] = parseHexRgb(n.color);+ return {+ x: n.x * scaleX,+ y: n.y * scaleY,+ r,+ g,+ b,+ a: Math.max(0, Math.min(1, n.opacity)) * 255,+ };+ });++ const sub = Math.max(2, Math.min(16, Math.round(subdivisionsPerCell)));+ const scaledOriginX = originX * scaleX;+ const scaledOriginY = originY * scaleY;++ for (let r = 0; r < mesh.rows - 1; r++) {+ for (let c = 0; c < mesh.cols - 1; c++) {+ // Sample (sub+1) x (sub+1) bicubic patch vertices+ const patch: MeshVertex[] = new Array((sub + 1) * (sub + 1));+ for (let iy = 0; iy <= sub; iy++) {+ const v = iy / sub;+ for (let ix = 0; ix <= sub; ix++) {+ const u = ix / sub;+ patch[iy * (sub + 1) + ix] = sampleMeshBicubic(+ verts,+ mesh.cols,+ mesh.rows,+ c,+ r,+ u,+ v+ );+ }+ }+ for (let iy = 0; iy < sub; iy++) {+ for (let ix = 0; ix < sub; ix++) {+ const a = patch[iy * (sub + 1) + ix];+ const b = patch[iy * (sub + 1) + ix + 1];+ const d = patch[(iy + 1) * (sub + 1) + ix];+ const e = patch[(iy + 1) * (sub + 1) + ix + 1];+ rasterizeTriangleIntoBuffer(out, width, height, scaledOriginX, scaledOriginY, a, b, e, dither);+ rasterizeTriangleIntoBuffer(out, width, height, scaledOriginX, scaledOriginY, a, e, d, dither);+ }+ }+ }+ }++ return out;+}++export interface RenderGradientParams {+ grid: SparseTileGrid;+ layerId: string;+ dimensions: CanvasDimensions;+ targetFormat: TileFormat;+ settings: GradientSettings;+ primaryColor: string;+ secondaryColor: string;+ start?: Point2D;+ end?: Point2D;+ mesh?: GradientMeshState | null;+ selection?: CanvasSelection | null;+ alphaLock?: boolean;+}++export interface RenderGradientResult {+ modified: boolean;+ dirtyRect: DirtyRect | null;+ tileDeltas: TileDelta[];+}++/**+ * Tile-native gradient rasterizer for Linear, Radial, and Mesh gradients.+ * Writes directly into SparseTileGrid respecting selection masks, alpha-lock, blend modes, and dithering.+ */+export function renderGradientToTileGrid(params: RenderGradientParams): RenderGradientResult {+ const {+ grid,+ layerId,+ dimensions,+ targetFormat,+ settings,+ primaryColor,+ secondaryColor,+ start,+ end,+ mesh,+ selection = null,+ alphaLock = false,+ } = params;++ const docW = dimensions.width;+ const docH = dimensions.height;+ if (docW <= 0 || docH <= 0) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }++ const opacity = Math.max(0, Math.min(1, settings.opacity ?? 1));+ if (opacity <= 0) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }++ const selMask = selection ? createSelectionMask(selection, docW, docH) : null;++ // Determine active bounding rectangle+ let bx0 = 0;+ let by0 = 0;+ let bx1 = docW;+ let by1 = docH;++ if (selection) {+ bx0 = Math.max(0, Math.floor(selection.bounds.x));+ by0 = Math.max(0, Math.floor(selection.bounds.y));+ bx1 = Math.min(docW, Math.ceil(selection.bounds.x + selection.bounds.width));+ by1 = Math.min(docH, Math.ceil(selection.bounds.y + selection.bounds.height));+ }++ if (settings.type === 'mesh') {+ if (!mesh || mesh.cols < 2 || mesh.rows < 2 || mesh.nodes.length < mesh.cols * mesh.rows) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }+ let mMinX = Infinity;+ let mMinY = Infinity;+ let mMaxX = -Infinity;+ let mMaxY = -Infinity;+ for (const n of mesh.nodes) {+ if (n.x < mMinX) mMinX = n.x;+ if (n.y < mMinY) mMinY = n.y;+ if (n.x > mMaxX) mMaxX = n.x;+ if (n.y > mMaxY) mMaxY = n.y;+ }+ // Pad slightly for Catmull-Rom overshoot+ const pad = Math.ceil(Math.max(mMaxX - mMinX, mMaxY - mMinY) * 0.15) + 4;+ bx0 = Math.max(bx0, Math.floor(mMinX - pad));+ by0 = Math.max(by0, Math.floor(mMinY - pad));+ bx1 = Math.min(bx1, Math.ceil(mMaxX + pad));+ by1 = Math.min(by1, Math.ceil(mMaxY + pad));+ } else {+ if (!start || !end) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }+ }++ if (bx0 >= bx1 || by0 >= by1) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }++ const dirtyRect: DirtyRect = {+ x: bx0,+ y: by0,+ width: bx1 - bx0,+ height: by1 - by0,+ };++ const minTx = Math.floor(bx0 / TILE_SIZE);+ const maxTx = Math.floor((bx1 - 1) / TILE_SIZE);+ const minTy = Math.floor(by0 / TILE_SIZE);+ const maxTy = Math.floor((by1 - 1) / TILE_SIZE);++ const beforeSnapshot = new Map<string, TileSnapshotEntry>();+ const stops = resolveGradientStops(settings, primaryColor, secondaryColor);+ const sampleOut: [number, number, number, number] = [0, 0, 0, 0];++ const dx = start && end ? end.x - start.x : 1;+ const dy = start && end ? end.y - start.y : 0;+ const lenSq = dx * dx + dy * dy;+ const invLenSq = lenSq > 1e-6 ? 1 / lenSq : 0;+ const invRad = lenSq > 1e-6 ? 1 / Math.sqrt(lenSq) : 0;++ const tileRgba = new Uint8ClampedArray(BYTES_32BIT);+ let anyModified = false;++ for (let ty = minTy; ty <= maxTy; ty++) {+ const tileOriginY = ty * TILE_SIZE;+ const localY0 = Math.max(0, by0 - tileOriginY);+ const localY1 = Math.min(TILE_SIZE, by1 - tileOriginY);++ for (let tx = minTx; tx <= maxTx; tx++) {+ const tileOriginX = tx * TILE_SIZE;+ const localX0 = Math.max(0, bx0 - tileOriginX);+ const localX1 = Math.min(TILE_SIZE, bx1 - tileOriginX);++ const existingTile = grid.getTile(layerId, tx, ty, 0);+ if (alphaLock && !existingTile) {+ continue;+ }++ // Snapshot before mutation+ grid.snapshotSingleTileInto(layerId, tx, ty, beforeSnapshot);++ if (existingTile && existingTile.data) {+ if (existingTile.format === 'color-32bit') {+ tileRgba.set(existingTile.data);+ } else if (existingTile.format === 'monochrome-1bit') {+ unpack1BitToRGBA(existingTile.data, tileRgba);+ } else {+ unpack8BitToRGBA(existingTile.data, tileRgba);+ }+ } else {+ tileRgba.fill(0);+ }++ let meshTileBuf: Uint8ClampedArray | null = null;+ if (settings.type === 'mesh' && mesh) {+ meshTileBuf = rasterizeMeshGradientToRgba(+ mesh,+ tileOriginX,+ tileOriginY,+ TILE_SIZE,+ TILE_SIZE,+ 1,+ 1,+ settings.dither,+ 8+ );+ }++ let tileTouched = false;+ for (let ly = localY0; ly < localY1; ly++) {+ const gy = tileOriginY + ly;+ const rowSelBase = gy * docW;+ const tileRowBase = ly * TILE_SIZE;++ for (let lx = localX0; lx < localX1; lx++) {+ const gx = tileOriginX + lx;+ let maskWeight = 1;+ if (selMask) {+ const m = selMask[rowSelBase + gx];+ if (m === 0) continue;+ maskWeight = m / 255;+ }++ const idx = (tileRowBase + lx) * 4;+ const ditherVal = settings.dither ? BAYER_4X4[((ly & 3) << 2) | (lx & 3)] : 0;++ if (settings.type === 'mesh' && meshTileBuf) {+ const ma = meshTileBuf[idx + 3];+ if (ma === 0) continue;+ const effAlpha = (ma / 255) * opacity * maskWeight;+ compositePixelInPlace(+ tileRgba,+ idx,+ meshTileBuf[idx],+ meshTileBuf[idx + 1],+ meshTileBuf[idx + 2],+ effAlpha,+ settings.blendMode,+ alphaLock,+ 0 // already dithered during mesh scanline+ );+ tileTouched = true;+ } else if (start && end) {+ let t = 0;+ if (settings.type === 'linear') {+ t = invLenSq > 0 ? ((gx - start.x) * dx + (gy - start.y) * dy) * invLenSq : 0;+ } else {+ t = invRad > 0 ? Math.hypot(gx - start.x, gy - start.y) * invRad : 0;+ }+ sampleGradientStops(stops, t, settings.repeat, settings.reverse, sampleOut);+ const effAlpha = (sampleOut[3] / 255) * opacity * maskWeight;+ if (effAlpha <= 0) continue;+ compositePixelInPlace(+ tileRgba,+ idx,+ sampleOut[0],+ sampleOut[1],+ sampleOut[2],+ effAlpha,+ settings.blendMode,+ alphaLock,+ ditherVal+ );+ tileTouched = true;+ }+ }+ }++ if (!tileTouched) continue;++ const tile = grid.getOrCreateTile(layerId, tx, ty, targetFormat, 0);+ if (tile.format === 'color-32bit') {+ if (!tile.data) tile.data = new Uint8Array(BYTES_32BIT);+ tile.data.set(tileRgba);+ } else if (tile.format === 'monochrome-1bit') {+ if (!tile.data) tile.data = new Uint8Array((TILE_SIZE * TILE_SIZE) / 8);+ packRGBATo1Bit(tileRgba, tile.data);+ } else {+ if (!tile.data) tile.data = new Uint8Array(TILE_SIZE * TILE_SIZE);+ packRGBATo8Bit(tileRgba, tile.data);+ }+ tile.dirty = true;+ tile.version++;+ grid.markLodAncestorsDirty(layerId, tx, ty);+ anyModified = true;+ }+ }++ if (!anyModified) {+ return { modified: false, dirtyRect: null, tileDeltas: [] };+ }++ grid.bumpLayerVersion(layerId);+ grid.notifyChange(true);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);+ return { modified: true, dirtyRect, tileDeltas };+}diff --git a/src/utils/inkbBrushFormat.ts b/src/utils/inkbBrushFormat.tsindex 3623616..1ea8f4e 100644--- a/src/utils/inkbBrushFormat.ts+++ b/src/utils/inkbBrushFormat.ts@@ -2,7 +2,11 @@ import { zipSync, unzipSync, strToU8, strFromU8 } from 'fflate';import {ALL_BLEND_MODES,BlendMode,+ BristleProfilePreset,+ BristleSettings,+ BrushCategory,BrushDynamics,+ BrushRenderMode,BrushSettings,CspAngleDynamicsMode,CspBlendTipsMode,@@ -13,6 +17,11 @@ import {CspSubTip,CspTaperSettings,CspTipFlipMode,+ GrainMappingMode,+ ImpastoSettings,+ NaturalMixingMode,+ NaturalPaintSettings,+ SurfaceTextureId,} from '../types/editor';import { getEffectiveBrushSettings } from './brushPresetManager';import {@@ -26,7 +35,7 @@ import { parseSutFile } from './sutParser';import { toolStoreActions } from '../stores';export const INKB_FORMAT = 'inkb';-export const INKB_VERSION = 1;+export const INKB_VERSION = 2;export const INKB_EXTENSION = '.inkb';const MAX_INKB_FILE_BYTES = 25 * 1024 * 1024;@@ -46,7 +55,12 @@ const VALID_ANGLE_DYNAMICS = new Set<CspAngleDynamicsMode>([]);const VALID_FLIP_MODES = new Set<CspTipFlipMode>(['none', 'random', 'alternate']);const VALID_BLEND_TIPS = new Set<CspBlendTipsMode>(['normal', 'darken', 'compare']);-const VALID_MIXING_MODES = new Set(['blend', 'running_color', 'smear']);+const VALID_MIXING_MODES = new Set<NaturalMixingMode>([+ 'blend',+ 'running_color',+ 'smear',+ 'impasto_mix',+]);const VALID_TEXTURE_MODES = new Set<CspPaperTextureMode>(['multiply','subtract',@@ -54,6 +68,38 @@ const VALID_TEXTURE_MODES = new Set<CspPaperTextureMode>(['overlay','outline',]);+const VALID_RENDER_MODES = new Set<BrushRenderMode>(['stamp', 'bristle-ribbon', 'bristle-hybrid']);+const VALID_GRAIN_MAPPING_MODES = new Set<GrainMappingMode>([+ 'canvas-locked',+ 'brush-aligned',+ 'stroke-flow',+ 'random-per-stroke',+]);+const VALID_SURFACE_TEXTURES = new Set<SurfaceTextureId>([+ 'linen-canvas',+ 'coarse-burlap',+ 'fine-cotton',+ 'cold-press-watercolor',+ 'rough-pastel',+ 'gesso-board',+ 'stipple-grain',+]);+const VALID_BRISTLE_PROFILES = new Set<BristleProfilePreset>([+ 'round',+ 'flat',+ 'filbert',+ 'fan',+ 'rake',+ 'knife',+ 'custom',+]);+const VALID_CATEGORIES = new Set<BrushCategory | 'custom'>([+ 'pen',+ 'sketch',+ 'brush',+ 'natural-paint',+ 'custom',+]);const VALID_BLEND_MODES = new Set<BlendMode>(ALL_BLEND_MODES);interface InkbArchivePayload {@@ -112,16 +158,77 @@ function sanitizeSensor(val: unknown): CspSensorConfig | undefined {if (typeof s.useTilt === 'boolean') out.useTilt = s.useTilt;const tMin = optNum(s.tiltMin, 0, 1);if (tMin !== undefined) out.tiltMin = tMin;+ if (typeof s.useTiltAzimuth === 'boolean') out.useTiltAzimuth = s.useTiltAzimuth;+ if (typeof s.useBarrelTwist === 'boolean') out.useBarrelTwist = s.useBarrelTwist;+ const twMin = optNum(s.twistMin, 0, 1);+ if (twMin !== undefined) out.twistMin = twMin;if (typeof s.useVelocity === 'boolean') out.useVelocity = s.useVelocity;const vMin = optNum(s.velocityMin, 0, 1);if (vMin !== undefined) out.velocityMin = vMin;if (typeof s.invertVelocity === 'boolean') out.invertVelocity = s.invertVelocity;+ if (typeof s.useDistance === 'boolean') out.useDistance = s.useDistance;+ const dMin = optNum(s.distanceMin, 0, 1);+ if (dMin !== undefined) out.distanceMin = dMin;+ const dMax = optNum(s.distanceMaxPx, 10, 10000);+ if (dMax !== undefined) out.distanceMaxPx = dMax;if (typeof s.useRandom === 'boolean') out.useRandom = s.useRandom;const rMin = optNum(s.randomMin, 0, 1);if (rMin !== undefined) out.randomMin = rMin;return Object.keys(out).length > 0 ? out : undefined;}+function sanitizeBristle(val: unknown): BristleSettings | undefined {+ if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;+ const b = val as Record<string, unknown>;+ const profile =+ typeof b.profile === 'string' && VALID_BRISTLE_PROFILES.has(b.profile as BristleProfilePreset)+ ? (b.profile as BristleProfilePreset)+ : 'filbert';+ return {+ profile,+ count: Math.round(clampNum(b.count, 4, 64, 28)),+ clumping: clampNum(b.clumping, 0, 1, 0.35),+ stiffness: clampNum(b.stiffness, 0, 1, 0.6),+ length: clampNum(b.length, 0.2, 2.0, 1.0),+ splay: clampNum(b.splay, 0, 1, 0.3),+ irregularity: clampNum(b.irregularity, 0, 1, 0.35),+ edgeRidge: optNum(b.edgeRidge, 0, 1),+ };+}++function sanitizeNaturalPaint(val: unknown): NaturalPaintSettings | undefined {+ if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;+ const n = val as Record<string, unknown>;+ return {+ enabled: Boolean(n.enabled),+ spatialMixing: Boolean(n.spatialMixing),+ pigmentMixingStrength: clampNum(n.pigmentMixingStrength, 0, 1, 0.85),+ paintLoad: clampNum(n.paintLoad, 0, 1, 0.85),+ depletionRate: clampNum(n.depletionRate, 0, 1, 0.25),+ wetness: clampNum(n.wetness, 0, 1, 0.5),+ viscosity: clampNum(n.viscosity, 0, 1, 0.5),+ autoClean: typeof n.autoClean === 'boolean' ? n.autoClean : true,+ chargePerPressure: clampNum(n.chargePerPressure, 0, 1, 0.45),+ dryBrush: clampNum(n.dryBrush, 0, 1, 0.3),+ granulation: optNum(n.granulation, 0, 1),+ penetrationCurve: sanitizeCurve(n.penetrationCurve),+ };+}++function sanitizeImpasto(val: unknown): ImpastoSettings | undefined {+ if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;+ const imp = val as Record<string, unknown>;+ return {+ enabled: Boolean(imp.enabled),+ depth: clampNum(imp.depth, 0, 1, 0.55),+ bristleRelief: clampNum(imp.bristleRelief, 0, 1, 0.6),+ gloss: clampNum(imp.gloss, 0, 1, 0.45),+ reliefContrast: clampNum(imp.reliefContrast, 0, 1, 0.55),+ lightAzimuth: clampNum(imp.lightAzimuth, 0, 360, 315),+ lightElevation: clampNum(imp.lightElevation, 5, 85, 42),+ };+}+function sanitizeSpray(val: unknown): CspSpraySettings | undefined {if (!val || typeof val !== 'object' || Array.isArray(val)) return undefined;const s = val as Record<string, unknown>;@@ -151,6 +258,7 @@ function sanitizeTaper(val: unknown): CspTaperSettings | undefined {affectSize: optBool(t.affectSize),affectDensity: optBool(t.affectDensity),affectOpacity: optBool(t.affectOpacity),+ affectLoad: optBool(t.affectLoad),};}@@ -169,6 +277,7 @@ function sanitizeDynamics(val: unknown): BrushDynamics | undefined {hueJitter: clampNum(d.hueJitter, 0, 1, 0),saturationJitter: clampNum(d.saturationJitter, 0, 1, 0),brightnessJitter: clampNum(d.brightnessJitter, 0, 1, 0),+ temperatureJitter: optNum(d.temperatureJitter, 0, 1),foregroundBackgroundJitter: clampNum(d.foregroundBackgroundJitter, 0, 1, 0),};}@@ -233,6 +342,7 @@ export function buildExportableBrush(return {id: existingCustom?.id || `inkb-${presetId}`,name,+ category: existingCustom?.category,badge: 'INKB',desc: existingCustom?.desc,tipDataUrl: merged.customTipDataUrl ?? existingCustom?.tipDataUrl,@@ -274,6 +384,11 @@ export function buildExportableBrush(sizeSensor: merged.sizeSensor,opacitySensor: merged.opacitySensor,densitySensor: merged.densitySensor,+ bristleSplaySensor: merged.bristleSplaySensor,+ paintLoadSensor: merged.paintLoadSensor,+ grainPenetrationSensor: merged.grainPenetrationSensor,+ angleSensor: merged.angleSensor,+ scatterSensor: merged.scatterSensor,colorMixing: merged.colorMixing,perceptualMixing: merged.perceptualMixing,amountOfPaint: merged.amountOfPaint,@@ -285,6 +400,8 @@ export function buildExportableBrush(wetEdgeAlphaPower: merged.wetEdgeAlphaPower,wetEdgeValuePower: merged.wetEdgeValuePower,paperTexture: merged.paperTexture ?? existingCustom?.paperTexture,+ surfaceTextureId: merged.surfaceTextureId ?? existingCustom?.surfaceTextureId,+ grainMappingMode: merged.grainMappingMode ?? existingCustom?.grainMappingMode,textureDensity: merged.textureDensity ?? merged.grain,paperTextureMode: merged.paperTextureMode,paperTextureBrightness: merged.paperTextureBrightness,@@ -297,6 +414,11 @@ export function buildExportableBrush(dualBrushCompositeMode: merged.dualBrushCompositeMode,dualSize: merged.dualSize,dualSpacing: merged.dualSpacing,+ dualScatter: merged.dualScatter,+ dualAngle: merged.dualAngle,+ dualScale: merged.dualScale,+ dualSurfaceTextureId: merged.dualSurfaceTextureId,+ dualGrainDepth: merged.dualGrainDepth,spray: merged.spray,taper: merged.taper,isRibbon: merged.isRibbon,@@ -304,6 +426,10 @@ export function buildExportableBrush(pressureCurveGamma: merged.pressureCurveGamma,velocityDynamics: merged.velocityDynamics,dynamics: merged.dynamics,+ renderMode: merged.renderMode,+ bristle: merged.bristle,+ naturalPaint: merged.naturalPaint,+ impasto: merged.impasto,importedAt: Date.now(),};}@@ -392,6 +518,10 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.inkreturn {id: `inkb-${idSuffix}`,name,+ category:+ typeof b.category === 'string' && VALID_CATEGORIES.has(b.category as BrushCategory | 'custom')+ ? (b.category as BrushCategory | 'custom')+ : undefined,badge: 'INKB',desc: typeof b.desc === 'string' ? b.desc.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 200) : undefined,tipDataUrl: sanitizeDataUrl(b.tipDataUrl),@@ -454,13 +584,18 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.inksizeSensor: sanitizeSensor(b.sizeSensor),opacitySensor: sanitizeSensor(b.opacitySensor),densitySensor: sanitizeSensor(b.densitySensor),+ bristleSplaySensor: sanitizeSensor(b.bristleSplaySensor),+ paintLoadSensor: sanitizeSensor(b.paintLoadSensor),+ grainPenetrationSensor: sanitizeSensor(b.grainPenetrationSensor),+ angleSensor: sanitizeSensor(b.angleSensor),+ scatterSensor: sanitizeSensor(b.scatterSensor),colorMixing: optBool(b.colorMixing),perceptualMixing: optBool(b.perceptualMixing),amountOfPaint: optNum(b.amountOfPaint, 0, 1),densityOfPaint: optNum(b.densityOfPaint, 0, 1),colorStretch: optNum(b.colorStretch, 0, 1),mixingMode:- typeof b.mixingMode === 'string' && VALID_MIXING_MODES.has(b.mixingMode)+ typeof b.mixingMode === 'string' && VALID_MIXING_MODES.has(b.mixingMode as NaturalMixingMode)? (b.mixingMode as CspBrush['mixingMode']): undefined,wetEdge: optNum(b.wetEdge, 0, 1),@@ -468,6 +603,16 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.inkwetEdgeAlphaPower: optNum(b.wetEdgeAlphaPower, 0, 10),wetEdgeValuePower: optNum(b.wetEdgeValuePower, 0, 10),paperTexture: sanitizeDataUrl(b.paperTexture),+ surfaceTextureId:+ typeof b.surfaceTextureId === 'string' &&+ VALID_SURFACE_TEXTURES.has(b.surfaceTextureId as SurfaceTextureId)+ ? (b.surfaceTextureId as SurfaceTextureId)+ : undefined,+ grainMappingMode:+ typeof b.grainMappingMode === 'string' &&+ VALID_GRAIN_MAPPING_MODES.has(b.grainMappingMode as GrainMappingMode)+ ? (b.grainMappingMode as GrainMappingMode)+ : undefined,textureDensity: optNum(b.textureDensity, 0, 1),paperTextureMode:typeof b.paperTextureMode === 'string' &&@@ -485,6 +630,15 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.inktypeof b.dualBrushCompositeMode === 'string' ? b.dualBrushCompositeMode.slice(0, 32) : undefined,dualSize: optNum(b.dualSize, 0.5, 2000),dualSpacing: optNum(b.dualSpacing, 0.01, 5),+ dualScatter: optNum(b.dualScatter, 0, 5),+ dualAngle: optNum(b.dualAngle, -360, 360),+ dualScale: optNum(b.dualScale, 0.05, 10),+ dualSurfaceTextureId:+ typeof b.dualSurfaceTextureId === 'string' &&+ VALID_SURFACE_TEXTURES.has(b.dualSurfaceTextureId as SurfaceTextureId)+ ? (b.dualSurfaceTextureId as SurfaceTextureId)+ : undefined,+ dualGrainDepth: optNum(b.dualGrainDepth, 0, 1),spray: sanitizeSpray(b.spray),taper: sanitizeTaper(b.taper),isRibbon: optBool(b.isRibbon),@@ -492,6 +646,13 @@ export function parseInkbFile(buffer: ArrayBuffer, fileName: string = 'Brush.inkpressureCurveGamma: optNum(b.pressureCurveGamma, 0.1, 5),velocityDynamics: optBool(b.velocityDynamics),dynamics: sanitizeDynamics(b.dynamics),+ renderMode:+ typeof b.renderMode === 'string' && VALID_RENDER_MODES.has(b.renderMode as BrushRenderMode)+ ? (b.renderMode as BrushRenderMode)+ : undefined,+ bristle: sanitizeBristle(b.bristle),+ naturalPaint: sanitizeNaturalPaint(b.naturalPaint),+ impasto: sanitizeImpasto(b.impasto),importedAt: Date.now(),};}diff --git a/src/utils/liquifyEngine.ts b/src/utils/liquifyEngine.tsindex c43eaf6..da9379a 100644--- a/src/utils/liquifyEngine.ts+++ b/src/utils/liquifyEngine.ts@@ -1,4 +1,4 @@-import { CanvasDimensions, CanvasSelection, LayerItem, isFolderLikeLayer } from '../types/editor';+import { CanvasDimensions, CanvasSelection, LayerItem, isFolderLikeLayer } from '../types/editor';import { isNativeRustAvailable, liquifyStepNative } from './nativeBackend';import {BYTES_32BIT,@@ -75,9 +75,32 @@ export const LIQUIFY_FRAGMENT_SHADER = `uniform float u_strength;uniform int u_mode; // 0: push, 1: push-left, 2: push-right, 3: expand, 4: pinch, 5: twirl-cw, 6: twirl-ccw+ vec4 cubicWeights(float f) {+ float f2 = f * f;+ float f3 = f2 * f;+ return vec4(+ -0.5 * f + f2 - 0.5 * f3,+ 1.0 - 2.5 * f2 + 1.5 * f3,+ 0.5 * f + 2.0 * f2 - 1.5 * f3,+ -0.5 * f2 + 0.5 * f3+ );+ }++ vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize, vec2 maxIdx) {+ float y = (clamp(base.y + dy, 0.0, maxIdx.y) + 0.5) * invSize.y;+ float x0 = (clamp(base.x - 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x1 = (clamp(base.x, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x2 = (clamp(base.x + 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x3 = (clamp(base.x + 2.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ return texture2D(u_sourceTex, vec2(x0, y)) * wx.x+ + texture2D(u_sourceTex, vec2(x1, y)) * wx.y+ + texture2D(u_sourceTex, vec2(x2, y)) * wx.z+ + texture2D(u_sourceTex, vec2(x3, y)) * wx.w;+ }+void main() {- // Convert v_uv (with WebGL Y-flip accounted for) to canvas pixel coordinates- vec2 localPos = vec2(v_uv.x * u_roiSize.x, (1.0 - v_uv.y) * u_roiSize.y);+ // Exact integer pixel coordinate matching CPU (rx, ry) with WebGL Y-flip accounted for+ vec2 localPos = vec2(v_uv.x * u_roiSize.x, (1.0 - v_uv.y) * u_roiSize.y) - 0.5;vec2 canvasPos = u_roiOrigin + localPos;vec2 delta = canvasPos - u_center;float distSq = dot(delta, delta);@@ -117,9 +140,21 @@ export const LIQUIFY_FRAGMENT_SHADER = `srcCanvas = u_center + vec2(delta.x * cosT + delta.y * sinT, -delta.x * sinT + delta.y * cosT);}- vec2 sampleLocal = clamp(srcCanvas - u_roiOrigin, vec2(0.0), u_roiSize - vec2(1.0));- vec2 sampleUv = sampleLocal / u_roiSize;- gl_FragColor = texture2D(u_sourceTex, sampleUv);+ vec2 maxIdx = u_roiSize - 1.0;+ vec2 sampleLocal = clamp(srcCanvas - u_roiOrigin, vec2(0.0), maxIdx);+ vec2 base = floor(sampleLocal);+ vec2 f = sampleLocal - base;+ vec4 wx = cubicWeights(f.x);+ vec4 wy = cubicWeights(f.y);+ vec2 invSize = 1.0 / u_roiSize;++ vec4 c = fetchRow(base, -1.0, wx, invSize, maxIdx) * wy.x+ + fetchRow(base, 0.0, wx, invSize, maxIdx) * wy.y+ + fetchRow(base, 1.0, wx, invSize, maxIdx) * wy.z+ + fetchRow(base, 2.0, wx, invSize, maxIdx) * wy.w;++ float a = clamp(c.a, 0.0, 1.0);+ gl_FragColor = vec4(clamp(c.rgb, vec3(0.0), vec3(a)), a);}`;@@ -145,8 +180,8 @@ export class WebGlLiquifyEngine {try {this.canvas = document.createElement('canvas');this.roiStagingCanvas = document.createElement('canvas');- const gl = (this.canvas.getContext('webgl2', { premultipliedAlpha: false, alpha: true }) ||- this.canvas.getContext('webgl', { premultipliedAlpha: false, alpha: true })) as WebGLRenderingContext | null;+ const gl = (this.canvas.getContext('webgl2', { premultipliedAlpha: true, alpha: true }) ||+ this.canvas.getContext('webgl', { premultipliedAlpha: true, alpha: true })) as WebGLRenderingContext | null;if (!gl) return;this.gl = gl;@@ -242,12 +277,12 @@ export class WebGlLiquifyEngine {gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, this.sourceTex);- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.roiStagingCanvas);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);gl.uniform1i(gl.getUniformLocation(this.program, 'u_sourceTex'), 0);gl.uniform2f(gl.getUniformLocation(this.program, 'u_roiOrigin'), minX, minY);@@ -306,6 +341,167 @@ function computeFalloffWeight(dist: number, radius: number, hardnessFactor: numbreturn (1 - hardnessFactor) * (t * t) + hardnessFactor * t;}+/**+ * Premultiplied linear blend toward a target pixel (used by reconstruct mode to prevent dark fringes).+ */+function blendPremulToward(+ dst: Uint8ClampedArray,+ dstIdx: number,+ target: Uint8ClampedArray,+ targetIdx: number,+ alpha: number+): void {+ const inv = 1 - alpha;+ const dA = dst[dstIdx + 3];+ const tA = target[targetIdx + 3];+ const outA = dA * inv + tA * alpha;+ if (outA <= 0.5) {+ dst[dstIdx] = 0;+ dst[dstIdx + 1] = 0;+ dst[dstIdx + 2] = 0;+ dst[dstIdx + 3] = 0;+ return;+ }+ const invOut = 1 / outA;+ const r = (dst[dstIdx] * dA * inv + target[targetIdx] * tA * alpha) * invOut;+ const g = (dst[dstIdx + 1] * dA * inv + target[targetIdx + 1] * tA * alpha) * invOut;+ const b = (dst[dstIdx + 2] * dA * inv + target[targetIdx + 2] * tA * alpha) * invOut;+ dst[dstIdx] = r <= 0 ? 0 : r >= 255 ? 255 : Math.round(r);+ dst[dstIdx + 1] = g <= 0 ? 0 : g >= 255 ? 255 : Math.round(g);+ dst[dstIdx + 2] = b <= 0 ? 0 : b >= 255 ? 255 : Math.round(b);+ dst[dstIdx + 3] = outA >= 255 ? 255 : Math.round(outA);+}++/**+ * Premultiplied 4x4 Catmull-Rom (Keys a=-0.5) bicubic sample from a flat RGBA buffer.+ * Eliminates bilinear softening and straight-alpha black fringing on brushes and smudges.+ */+function samplePremulBicubicBuffer(+ src: Uint8ClampedArray,+ w: number,+ h: number,+ sx: number,+ sy: number,+ dst: Uint8ClampedArray,+ dstIdx: number+): void {+ const maxX = w - 1;+ const maxY = h - 1;+ const cx = sx <= 0 ? 0 : sx >= maxX ? maxX : sx;+ const cy = sy <= 0 ? 0 : sy >= maxY ? maxY : sy;+ const x0 = Math.floor(cx);+ const y0 = Math.floor(cy);+ const fx = cx - x0;+ const fy = cy - y0;++ if (fx < 1e-5 && fy < 1e-5) {+ const off = (y0 * w + x0) << 2;+ dst[dstIdx] = src[off];+ dst[dstIdx + 1] = src[off + 1];+ dst[dstIdx + 2] = src[off + 2];+ dst[dstIdx + 3] = src[off + 3];+ return;+ }++ const fx2 = fx * fx;+ const fx3 = fx2 * fx;+ const wx0 = -0.5 * fx + fx2 - 0.5 * fx3;+ const wx1 = 1.0 - 2.5 * fx2 + 1.5 * fx3;+ const wx2 = 0.5 * fx + 2.0 * fx2 - 1.5 * fx3;+ const wx3 = -0.5 * fx2 + 0.5 * fx3;++ const fy2 = fy * fy;+ const fy3 = fy2 * fy;+ const wy0 = -0.5 * fy + fy2 - 0.5 * fy3;+ const wy1 = 1.0 - 2.5 * fy2 + 1.5 * fy3;+ const wy2 = 0.5 * fy + 2.0 * fy2 - 1.5 * fy3;+ const wy3 = -0.5 * fy2 + 0.5 * fy3;++ const ix0 = x0 > 0 ? x0 - 1 : 0;+ const ix1 = x0;+ const ix2 = x0 < maxX ? x0 + 1 : maxX;+ const ix3 = x0 + 2 <= maxX ? x0 + 2 : maxX;++ let sumPR = 0;+ let sumPG = 0;+ let sumPB = 0;+ let sumA = 0;++ for (let row = 0; row < 4; row++) {+ const wy = row === 0 ? wy0 : row === 1 ? wy1 : row === 2 ? wy2 : wy3;+ const rawY = y0 + row - 1;+ const iy = rawY <= 0 ? 0 : rawY >= maxY ? maxY : rawY;+ const rowBase = iy * w;++ const o0 = (rowBase + ix0) << 2;+ const o1 = (rowBase + ix1) << 2;+ const o2 = (rowBase + ix2) << 2;+ const o3 = (rowBase + ix3) << 2;++ const a0 = src[o0 + 3];+ const a1 = src[o1 + 3];+ const a2 = src[o2 + 3];+ const a3 = src[o3 + 3];+ if ((a0 | a1 | a2 | a3) === 0) continue;++ let rPR = 0;+ let rPG = 0;+ let rPB = 0;+ let rA = 0;++ if (a0 !== 0) {+ const wa = wx0 * a0;+ rPR += wa * src[o0];+ rPG += wa * src[o0 + 1];+ rPB += wa * src[o0 + 2];+ rA += wa;+ }+ if (a1 !== 0) {+ const wa = wx1 * a1;+ rPR += wa * src[o1];+ rPG += wa * src[o1 + 1];+ rPB += wa * src[o1 + 2];+ rA += wa;+ }+ if (a2 !== 0) {+ const wa = wx2 * a2;+ rPR += wa * src[o2];+ rPG += wa * src[o2 + 1];+ rPB += wa * src[o2 + 2];+ rA += wa;+ }+ if (a3 !== 0) {+ const wa = wx3 * a3;+ rPR += wa * src[o3];+ rPG += wa * src[o3 + 1];+ rPB += wa * src[o3 + 2];+ rA += wa;+ }++ sumPR += wy * rPR;+ sumPG += wy * rPG;+ sumPB += wy * rPB;+ sumA += wy * rA;+ }++ if (sumA <= 0.5) {+ dst[dstIdx] = 0;+ dst[dstIdx + 1] = 0;+ dst[dstIdx + 2] = 0;+ dst[dstIdx + 3] = 0;+ return;+ }++ const invA = 1 / sumA;+ const r = sumPR * invA;+ const g = sumPG * invA;+ const b = sumPB * invA;+ dst[dstIdx] = r <= 0 ? 0 : r >= 255 ? 255 : Math.round(r);+ dst[dstIdx + 1] = g <= 0 ? 0 : g >= 255 ? 255 : Math.round(g);+ dst[dstIdx + 2] = b <= 0 ? 0 : b >= 255 ? 255 : Math.round(b);+ dst[dstIdx + 3] = sumA >= 255 ? 255 : Math.round(sumA);+}+/*** Executes a single localized, bilinear-interpolated liquify deformation step on the target canvas.* Uses hardware WebGL shader displacement on large brushes when available, with automatic CPU fallback.@@ -437,10 +633,7 @@ export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {if (!initData) continue;const alpha = Math.min(1, strengthFactor * weight * 0.35);const initIdx = (py * initW + px) * 4;- dst[dstIdx] = Math.round(dst[dstIdx] * (1 - alpha) + initData[initIdx] * alpha);- dst[dstIdx + 1] = Math.round(dst[dstIdx + 1] * (1 - alpha) + initData[initIdx + 1] * alpha);- dst[dstIdx + 2] = Math.round(dst[dstIdx + 2] * (1 - alpha) + initData[initIdx + 2] * alpha);- dst[dstIdx + 3] = Math.round(dst[dstIdx + 3] * (1 - alpha) + initData[initIdx + 3] * alpha);+ blendPremulToward(dst, dstIdx, initData, initIdx, alpha);continue;}@@ -481,32 +674,7 @@ export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {srcCanvasY = cy - dx * sinT + dy * cosT;}- // Convert from global canvas coords to ROI local coords for sampling- const localSx = Math.max(0, Math.min(roiW - 1.0001, srcCanvasX - minX));- const localSy = Math.max(0, Math.min(roiH - 1.0001, srcCanvasY - minY));-- const x0 = Math.floor(localSx);- const y0 = Math.floor(localSy);- const x1 = Math.min(roiW - 1, x0 + 1);- const y1 = Math.min(roiH - 1, y0 + 1);-- const fx = localSx - x0;- const fy = localSy - y0;-- const w00 = (1 - fx) * (1 - fy);- const w10 = fx * (1 - fy);- const w01 = (1 - fx) * fy;- const w11 = fx * fy;-- const i00 = (y0 * roiW + x0) * 4;- const i10 = (y0 * roiW + x1) * 4;- const i01 = (y1 * roiW + x0) * 4;- const i11 = (y1 * roiW + x1) * 4;-- dst[dstIdx] = Math.round(w00 * src[i00] + w10 * src[i10] + w01 * src[i01] + w11 * src[i11]);- dst[dstIdx + 1] = Math.round(w00 * src[i00 + 1] + w10 * src[i10 + 1] + w01 * src[i01 + 1] + w11 * src[i11 + 1]);- dst[dstIdx + 2] = Math.round(w00 * src[i00 + 2] + w10 * src[i10 + 2] + w01 * src[i01 + 2] + w11 * src[i11 + 2]);- dst[dstIdx + 3] = Math.round(w00 * src[i00 + 3] + w10 * src[i10 + 3] + w01 * src[i01 + 3] + w11 * src[i11 + 3]);+ samplePremulBicubicBuffer(src, roiW, roiH, srcCanvasX - minX, srcCanvasY - minY, dst, dstIdx);}}@@ -830,10 +998,7 @@ export function applyLiquifyStepOnTileGrid(params: TileGridLiquifyStepParams): Dif (mode === 'reconstruct') {if (!initRoiData) continue;const alpha = Math.min(1, strengthFactor * weight * 0.35);- dst[dstIdx] = Math.round(dst[dstIdx] * (1 - alpha) + initRoiData[dstIdx] * alpha);- dst[dstIdx + 1] = Math.round(dst[dstIdx + 1] * (1 - alpha) + initRoiData[dstIdx + 1] * alpha);- dst[dstIdx + 2] = Math.round(dst[dstIdx + 2] * (1 - alpha) + initRoiData[dstIdx + 2] * alpha);- dst[dstIdx + 3] = Math.round(dst[dstIdx + 3] * (1 - alpha) + initRoiData[dstIdx + 3] * alpha);+ blendPremulToward(dst, dstIdx, initRoiData, dstIdx, alpha);continue;}@@ -867,29 +1032,7 @@ export function applyLiquifyStepOnTileGrid(params: TileGridLiquifyStepParams): DsrcCanvasY = cy - dx * sinT + dy * cosT;}- const localSx = Math.max(0, Math.min(roiW - 1.0001, srcCanvasX - minX));- const localSy = Math.max(0, Math.min(roiH - 1.0001, srcCanvasY - minY));- const x0 = Math.floor(localSx);- const y0 = Math.floor(localSy);- const x1 = Math.min(roiW - 1, x0 + 1);- const y1 = Math.min(roiH - 1, y0 + 1);- const fx = localSx - x0;- const fy = localSy - y0;-- const w00 = (1 - fx) * (1 - fy);- const w10 = fx * (1 - fy);- const w01 = (1 - fx) * fy;- const w11 = fx * fy;-- const i00 = (y0 * roiW + x0) * 4;- const i10 = (y0 * roiW + x1) * 4;- const i01 = (y1 * roiW + x0) * 4;- const i11 = (y1 * roiW + x1) * 4;-- dst[dstIdx] = Math.round(w00 * src[i00] + w10 * src[i10] + w01 * src[i01] + w11 * src[i11]);- dst[dstIdx + 1] = Math.round(w00 * src[i00 + 1] + w10 * src[i10 + 1] + w01 * src[i01 + 1] + w11 * src[i11 + 1]);- dst[dstIdx + 2] = Math.round(w00 * src[i00 + 2] + w10 * src[i10 + 2] + w01 * src[i01 + 2] + w11 * src[i11 + 2]);- dst[dstIdx + 3] = Math.round(w00 * src[i00 + 3] + w10 * src[i10 + 3] + w01 * src[i01 + 3] + w11 * src[i11 + 3]);+ samplePremulBicubicBuffer(src, roiW, roiH, srcCanvasX - minX, srcCanvasY - minY, dst, dstIdx);}}@@ -1052,3 +1195,627 @@ export async function applyLiquifyStepOnTileGridAsync(grid.writeImageData(layerId, { data: dst, width: roiW, height: roiH }, minX, minY, targetFormat, true);return { x: minX, y: minY, width: roiW, height: roiH };}++// ---------------------------------------------------------------------------+// Zero-Compound-Blur Accumulated Displacement Field Liquify Pipeline+// ---------------------------------------------------------------------------++const WARP_TILE_SIZE = 128;+const WARP_TILE_SHIFT = 7;+const WARP_TILE_MASK = 127;+const WARP_TILE_FLOATS = WARP_TILE_SIZE * WARP_TILE_SIZE * 2;++function numericTileKey(tx: number, ty: number): number {+ return (ty + 32768) * 65536 + (tx + 32768);+}++export interface LiquifySubStep {+ cx: number;+ cy: number;+ prevX: number;+ prevY: number;+ pressure?: number;+}++/**+ * Sparse 128x128 Float32 inverse-displacement field storing relative source offsets (dx, dy)+ * so every pixel in a Liquify stroke is resampled ONCE from pristine pre-stroke pixels+ * instead of suffering compounded N-step blur.+ * Shared across all target layers during multi-layer Liquify.+ */+export class LiquifyWarpField {+ private tiles = new Map<number, Float32Array>();+ private scratchNext = new Float32Array(0);+ private scratchMask = new Uint8Array(0);+ private tmpDisp: [number, number] = [0, 0];++ public getDisplacement(px: number, py: number, out: [number, number]): void {+ const tile = this.tiles.get(numericTileKey(px >> WARP_TILE_SHIFT, py >> WARP_TILE_SHIFT));+ if (!tile) {+ out[0] = 0;+ out[1] = 0;+ return;+ }+ const idx = (((py & WARP_TILE_MASK) << WARP_TILE_SHIFT) | (px & WARP_TILE_MASK)) << 1;+ out[0] = tile[idx];+ out[1] = tile[idx + 1];+ }++ public sampleDisplacement(+ sx: number,+ sy: number,+ width: number,+ height: number,+ out: [number, number]+ ): void {+ const cx = sx <= 0 ? 0 : sx >= width - 1 ? width - 1 : sx;+ const cy = sy <= 0 ? 0 : sy >= height - 1 ? height - 1 : sy;+ const x0 = Math.floor(cx);+ const y0 = Math.floor(cy);+ const x1 = x0 + 1 < width ? x0 + 1 : x0;+ const y1 = y0 + 1 < height ? y0 + 1 : y0;+ const fx = cx - x0;+ const fy = cy - y0;++ const tx0 = x0 >> WARP_TILE_SHIFT;+ const ty0 = y0 >> WARP_TILE_SHIFT;+ const tx1 = x1 >> WARP_TILE_SHIFT;+ const ty1 = y1 >> WARP_TILE_SHIFT;++ if (tx0 === tx1 && ty0 === ty1) {+ const tile = this.tiles.get(numericTileKey(tx0, ty0));+ if (!tile) {+ out[0] = 0;+ out[1] = 0;+ return;+ }+ const lx0 = x0 & WARP_TILE_MASK;+ const ly0 = y0 & WARP_TILE_MASK;+ const lx1 = x1 & WARP_TILE_MASK;+ const ly1 = y1 & WARP_TILE_MASK;+ const i00 = ((ly0 << WARP_TILE_SHIFT) | lx0) << 1;+ const i10 = ((ly0 << WARP_TILE_SHIFT) | lx1) << 1;+ const i01 = ((ly1 << WARP_TILE_SHIFT) | lx0) << 1;+ const i11 = ((ly1 << WARP_TILE_SHIFT) | lx1) << 1;+ const w00 = (1 - fx) * (1 - fy);+ const w10 = fx * (1 - fy);+ const w01 = (1 - fx) * fy;+ const w11 = fx * fy;+ out[0] = w00 * tile[i00] + w10 * tile[i10] + w01 * tile[i01] + w11 * tile[i11];+ out[1] = w00 * tile[i00 + 1] + w10 * tile[i10 + 1] + w01 * tile[i01 + 1] + w11 * tile[i11 + 1];+ return;+ }++ const t00 = this.tiles.get(numericTileKey(tx0, ty0));+ const t10 = this.tiles.get(numericTileKey(tx1, ty0));+ const t01 = this.tiles.get(numericTileKey(tx0, ty1));+ const t11 = this.tiles.get(numericTileKey(tx1, ty1));+ if (!t00 && !t10 && !t01 && !t11) {+ out[0] = 0;+ out[1] = 0;+ return;+ }++ const lx0 = x0 & WARP_TILE_MASK;+ const ly0 = y0 & WARP_TILE_MASK;+ const lx1 = x1 & WARP_TILE_MASK;+ const ly1 = y1 & WARP_TILE_MASK;+ const w00 = (1 - fx) * (1 - fy);+ const w10 = fx * (1 - fy);+ const w01 = (1 - fx) * fy;+ const w11 = fx * fy;++ let dx = 0;+ let dy = 0;+ if (t00) {+ const i = ((ly0 << WARP_TILE_SHIFT) | lx0) << 1;+ dx += w00 * t00[i];+ dy += w00 * t00[i + 1];+ }+ if (t10) {+ const i = ((ly0 << WARP_TILE_SHIFT) | lx1) << 1;+ dx += w10 * t10[i];+ dy += w10 * t10[i + 1];+ }+ if (t01) {+ const i = ((ly1 << WARP_TILE_SHIFT) | lx0) << 1;+ dx += w01 * t01[i];+ dy += w01 * t01[i + 1];+ }+ if (t11) {+ const i = ((ly1 << WARP_TILE_SHIFT) | lx1) << 1;+ dx += w11 * t11[i];+ dy += w11 * t11[i + 1];+ }+ out[0] = dx;+ out[1] = dy;+ }++ public hasAnyWarp(): boolean {+ return this.tiles.size > 0;+ }++ /**+ * Composes 1..N Liquify sub-steps into the float32 displacement field and returns the+ * union pixel rect that changed.+ */+ public applySubSteps(+ steps: LiquifySubStep[],+ dimensions: CanvasDimensions,+ settings: LiquifySettings,+ selectionMask?: Uint8Array | null+ ): DirtyRect | null {+ const width = dimensions.width;+ const height = dimensions.height;+ if (width <= 0 || height <= 0 || steps.length === 0) return null;++ const radius = Math.max(2, Math.round(settings.size / 2));+ const radiusSq = radius * radius;+ const hardnessFactor = Math.max(0, Math.min(1, settings.hardness / 100));+ const mode = settings.mode;+ const isPushMode = mode === 'push' || mode === 'push-left' || mode === 'push-right';+ const tmp = this.tmpDisp;++ let unionMinX = width;+ let unionMinY = height;+ let unionMaxX = 0;+ let unionMaxY = 0;+ let anyModified = false;++ for (let s = 0; s < steps.length; s++) {+ const step = steps[s];+ const cx = step.cx;+ const cy = step.cy;+ const vx = cx - step.prevX;+ const vy = cy - step.prevY;+ const vLen = Math.hypot(vx, vy);+ if (isPushMode && vLen < 0.0001) continue;++ let ux = 0;+ let uy = 0;+ if (vLen > 0.0001) {+ ux = vx / vLen;+ uy = vy / vLen;+ }++ const effectivePressure = settings.usePressure ? Math.max(0.1, step.pressure ?? 1.0) : 1.0;+ const strengthFactor = (settings.strength / 100) * effectivePressure;+ const twirlBaseAngle = (mode === 'twirl-cw' ? 1 : -1) * (strengthFactor * 0.45);++ const minX = Math.max(0, Math.floor(cx - radius));+ const minY = Math.max(0, Math.floor(cy - radius));+ const maxX = Math.min(width, Math.ceil(cx + radius));+ const maxY = Math.min(height, Math.ceil(cy + radius));+ const roiW = maxX - minX;+ const roiH = maxY - minY;+ if (roiW <= 0 || roiH <= 0) continue;++ const pixelCount = roiW * roiH;+ if (this.scratchNext.length < pixelCount * 2) {+ this.scratchNext = new Float32Array(pixelCount * 2);+ }+ if (this.scratchMask.length < pixelCount) {+ this.scratchMask = new Uint8Array(pixelCount);+ }+ const nextBuf = this.scratchNext;+ const maskBuf = this.scratchMask;+ maskBuf.fill(0, 0, pixelCount);++ let stepModified = false;++ // Read-only pass against this.tiles -> write composed displacement into scratchNext+ for (let ry = 0; ry < roiH; ry++) {+ const py = minY + ry;+ const dy = py - cy;+ const dySq = dy * dy;+ if (dySq >= radiusSq) continue;+ const rowPixelBase = ry * roiW;+ const selRowOff = py * width;++ for (let rx = 0; rx < roiW; rx++) {+ const px = minX + rx;+ const dx = px - cx;+ const distSq = dx * dx + dySq;+ if (distSq >= radiusSq) continue;+ if (selectionMask && selectionMask[selRowOff + px] === 0) continue;++ const dist = Math.sqrt(distSq);+ const weight = computeFalloffWeight(dist, radius, hardnessFactor);+ if (weight <= 0) continue;++ const pIdx = rowPixelBase + rx;+ const fIdx = pIdx << 1;++ if (mode === 'reconstruct') {+ this.getDisplacement(px, py, tmp);+ if (tmp[0] === 0 && tmp[1] === 0) continue;+ const alpha = Math.min(1, strengthFactor * weight * 0.35);+ const keep = 1 - alpha;+ const ndx = tmp[0] * keep;+ const ndy = tmp[1] * keep;+ nextBuf[fIdx] = Math.abs(ndx) < 1e-4 ? 0 : ndx;+ nextBuf[fIdx + 1] = Math.abs(ndy) < 1e-4 ? 0 : ndy;+ maskBuf[pIdx] = 1;+ stepModified = true;+ continue;+ }++ let qx = px;+ let qy = py;+ if (mode === 'push') {+ const pushAmount = vLen * strengthFactor * weight;+ qx = px - ux * pushAmount;+ qy = py - uy * pushAmount;+ } else if (mode === 'push-left') {+ const pushAmount = Math.max(1.5, vLen) * strengthFactor * weight;+ qx = px + uy * pushAmount;+ qy = py - ux * pushAmount;+ } else if (mode === 'push-right') {+ const pushAmount = Math.max(1.5, vLen) * strengthFactor * weight;+ qx = px - uy * pushAmount;+ qy = py + ux * pushAmount;+ } else if (mode === 'expand') {+ const factor = strengthFactor * weight * 0.3;+ qx = cx + dx * (1 - factor);+ qy = cy + dy * (1 - factor);+ } else if (mode === 'pinch') {+ const factor = strengthFactor * weight * 0.3;+ qx = cx + dx * (1 + factor);+ qy = cy + dy * (1 + factor);+ } else if (mode === 'twirl-cw' || mode === 'twirl-ccw') {+ const theta = twirlBaseAngle * weight;+ const cosT = Math.cos(theta);+ const sinT = Math.sin(theta);+ qx = cx + dx * cosT + dy * sinT;+ qy = cy - dx * sinT + dy * cosT;+ }++ this.sampleDisplacement(qx, qy, width, height, tmp);+ let srcX = qx + tmp[0];+ let srcY = qy + tmp[1];+ if (srcX < 0) srcX = 0;+ else if (srcX > width - 1) srcX = width - 1;+ if (srcY < 0) srcY = 0;+ else if (srcY > height - 1) srcY = height - 1;++ nextBuf[fIdx] = srcX - px;+ nextBuf[fIdx + 1] = srcY - py;+ maskBuf[pIdx] = 1;+ stepModified = true;+ }+ }++ if (!stepModified) continue;++ // Scatter updated displacements back into sparse float32 warp tiles+ let cachedKey = -1;+ let cachedTile: Float32Array | null = null;+ for (let ry = 0; ry < roiH; ry++) {+ const py = minY + ry;+ const ty = py >> WARP_TILE_SHIFT;+ const lyShift = (py & WARP_TILE_MASK) << WARP_TILE_SHIFT;+ const rowPixelBase = ry * roiW;++ for (let rx = 0; rx < roiW; rx++) {+ const pIdx = rowPixelBase + rx;+ if (maskBuf[pIdx] === 0) continue;+ const px = minX + rx;+ const tx = px >> WARP_TILE_SHIFT;+ const k = numericTileKey(tx, ty);+ if (k !== cachedKey) {+ cachedKey = k;+ let t = this.tiles.get(k);+ if (!t) {+ t = new Float32Array(WARP_TILE_FLOATS);+ this.tiles.set(k, t);+ }+ cachedTile = t;+ }+ const tIdx = (lyShift | (px & WARP_TILE_MASK)) << 1;+ const fIdx = pIdx << 1;+ cachedTile![tIdx] = nextBuf[fIdx];+ cachedTile![tIdx + 1] = nextBuf[fIdx + 1];+ }+ }++ if (minX < unionMinX) unionMinX = minX;+ if (minY < unionMinY) unionMinY = minY;+ if (maxX > unionMaxX) unionMaxX = maxX;+ if (maxY > unionMaxY) unionMaxY = maxY;+ anyModified = true;+ }++ if (!anyModified || unionMaxX <= unionMinX || unionMaxY <= unionMinY) return null;+ return {+ x: unionMinX,+ y: unionMinY,+ width: unionMaxX - unionMinX,+ height: unionMaxY - unionMinY,+ };+ }++ public clear(): void {+ this.tiles.clear();+ this.scratchNext = new Float32Array(0);+ this.scratchMask = new Uint8Array(0);+ }+}++export interface ResampleWarpLayerParams {+ grid: SparseTileGrid;+ layerId: string;+ dimensions: CanvasDimensions;+ targetFormat: TileFormat;+ warpField: LiquifyWarpField;+ dirtyRect: DirtyRect;+ beforeTileSnapshot: Map<string, TileSnapshotEntry>;+ origRgbaCache: Map<number, Uint8ClampedArray | null>;+}++/**+ * Single-pass premultiplied 4x4 Catmull-Rom bicubic resample of a layer's dirtyRect+ * directly from its pristine pre-stroke tiles using the accumulated LiquifyWarpField.+ * Zero compounded blur and zero dark alpha fringes across arbitrarily long strokes.+ */+export function resampleLayerFromWarpField(params: ResampleWarpLayerParams): DirtyRect | null {+ const {+ grid,+ layerId,+ dimensions,+ targetFormat,+ warpField,+ dirtyRect,+ beforeTileSnapshot,+ origRgbaCache,+ } = params;++ const width = dimensions.width;+ const height = dimensions.height;+ const minX = Math.max(0, dirtyRect.x);+ const minY = Math.max(0, dirtyRect.y);+ const maxX = Math.min(width, dirtyRect.x + dirtyRect.width);+ const maxY = Math.min(height, dirtyRect.y + dirtyRect.height);+ const roiW = maxX - minX;+ const roiH = maxY - minY;+ if (roiW <= 0 || roiH <= 0) return null;++ // Snapshot all destination tiles intersecting dirtyRect BEFORE mutating grid,+ // and prime origRgbaCache so every mutated tile preserves its pristine pre-session pixels+ // across multi-stroke Liquify sessions.+ const minTx = pixelToTileCoord(minX, 0);+ const minTy = pixelToTileCoord(minY, 0);+ const maxTx = pixelToTileCoord(maxX - 1, 0);+ const maxTy = pixelToTileCoord(maxY - 1, 0);++ // Lazy O(1) cache of pristine pre-stroke 256x256 RGBA tiles+ let lastTileKey = -1;+ let lastTile: Uint8ClampedArray | null = null;++ const getOrigTile = (tx: number, ty: number): Uint8ClampedArray | null => {+ const k = numericTileKey(tx, ty);+ if (k === lastTileKey) return lastTile;++ let cached = origRgbaCache.get(k);+ if (cached === undefined) {+ const snap = beforeTileSnapshot.get(getTileKey(layerId, tx, ty, 0));+ if (snap !== undefined) {+ if (!snap.data) {+ cached = null;+ } else if (snap.format === 'color-32bit') {+ cached = new Uint8ClampedArray(snap.data.buffer, snap.data.byteOffset, BYTES_32BIT);+ } else if (snap.format === 'monochrome-1bit') {+ cached = new Uint8ClampedArray(BYTES_32BIT);+ unpack1BitToRGBA(snap.data, cached);+ } else {+ cached = new Uint8ClampedArray(BYTES_32BIT);+ unpack8BitToRGBA(snap.data, cached);+ }+ } else {+ const tile = grid.getTile(layerId, tx, ty, 0);+ if (!tile || !tile.data) {+ cached = null;+ } else {+ const rgba = grid.getTileAsRGBA(tile);+ // Copy so subsequent writes to this tile never corrupt pristine source data+ cached = new Uint8ClampedArray(BYTES_32BIT);+ cached.set(rgba);+ }+ }+ origRgbaCache.set(k, cached);+ }++ lastTileKey = k;+ lastTile = cached;+ return cached;+ };++ for (let ty = minTy; ty <= maxTy; ty++) {+ for (let tx = minTx; tx <= maxTx; tx++) {+ grid.snapshotSingleTileInto(layerId, tx, ty, beforeTileSnapshot);+ getOrigTile(tx, ty);+ }+ }++ const dst = new Uint8ClampedArray(roiW * roiH * 4);+ const maxDocX = width - 1;+ const maxDocY = height - 1;+ const disp: [number, number] = [0, 0];++ for (let ry = 0; ry < roiH; ry++) {+ const py = minY + ry;+ const rowDstBase = ry * roiW * 4;++ for (let rx = 0; rx < roiW; rx++) {+ const px = minX + rx;+ const dstIdx = rowDstBase + (rx << 2);++ warpField.getDisplacement(px, py, disp);+ const dx = disp[0];+ const dy = disp[1];++ // Exact identity fast path (zero loss for untouched or reconstructed pixels)+ if (dx === 0 && dy === 0) {+ const tile = getOrigTile(px >> 8, py >> 8);+ if (tile) {+ const off = (((py & 255) << 8) | (px & 255)) << 2;+ dst[dstIdx] = tile[off];+ dst[dstIdx + 1] = tile[off + 1];+ dst[dstIdx + 2] = tile[off + 2];+ dst[dstIdx + 3] = tile[off + 3];+ }+ continue;+ }++ const rawSx = px + dx;+ const rawSy = py + dy;+ const sx = rawSx <= 0 ? 0 : rawSx >= maxDocX ? maxDocX : rawSx;+ const sy = rawSy <= 0 ? 0 : rawSy >= maxDocY ? maxDocY : rawSy;++ const x0 = Math.floor(sx);+ const y0 = Math.floor(sy);+ const fx = sx - x0;+ const fy = sy - y0;++ if (fx < 1e-5 && fy < 1e-5) {+ const tile = getOrigTile(x0 >> 8, y0 >> 8);+ if (tile) {+ const off = (((y0 & 255) << 8) | (x0 & 255)) << 2;+ dst[dstIdx] = tile[off];+ dst[dstIdx + 1] = tile[off + 1];+ dst[dstIdx + 2] = tile[off + 2];+ dst[dstIdx + 3] = tile[off + 3];+ }+ continue;+ }++ const fx2 = fx * fx;+ const fx3 = fx2 * fx;+ const wx0 = -0.5 * fx + fx2 - 0.5 * fx3;+ const wx1 = 1.0 - 2.5 * fx2 + 1.5 * fx3;+ const wx2 = 0.5 * fx + 2.0 * fx2 - 1.5 * fx3;+ const wx3 = -0.5 * fx2 + 0.5 * fx3;++ const fy2 = fy * fy;+ const fy3 = fy2 * fy;+ const wy0 = -0.5 * fy + fy2 - 0.5 * fy3;+ const wy1 = 1.0 - 2.5 * fy2 + 1.5 * fy3;+ const wy2 = 0.5 * fy + 2.0 * fy2 - 1.5 * fy3;+ const wy3 = -0.5 * fy2 + 0.5 * fy3;++ const lx = x0 & 255;+ const ly = y0 & 255;++ let sumPR = 0;+ let sumPG = 0;+ let sumPB = 0;+ let sumA = 0;++ // Single-tile interior fast path (~97.7% of all pixels: 1 tile lookup, zero clamping)+ if (lx >= 1 && lx <= 253 && ly >= 1 && ly <= 253 && x0 + 2 <= maxDocX && y0 + 2 <= maxDocY) {+ const tile = getOrigTile(x0 >> 8, y0 >> 8);+ if (!tile) continue;++ let baseOff = (((ly - 1) << 8) | (lx - 1)) << 2;+ for (let row = 0; row < 4; row++, baseOff += 1024) {+ const a0 = tile[baseOff + 3];+ const a1 = tile[baseOff + 7];+ const a2 = tile[baseOff + 11];+ const a3 = tile[baseOff + 15];+ if ((a0 | a1 | a2 | a3) === 0) continue;++ const wy = row === 0 ? wy0 : row === 1 ? wy1 : row === 2 ? wy2 : wy3;+ let rPR = 0;+ let rPG = 0;+ let rPB = 0;+ let rA = 0;++ if (a0 !== 0) {+ const wa = wx0 * a0;+ rPR += wa * tile[baseOff];+ rPG += wa * tile[baseOff + 1];+ rPB += wa * tile[baseOff + 2];+ rA += wa;+ }+ if (a1 !== 0) {+ const wa = wx1 * a1;+ rPR += wa * tile[baseOff + 4];+ rPG += wa * tile[baseOff + 5];+ rPB += wa * tile[baseOff + 6];+ rA += wa;+ }+ if (a2 !== 0) {+ const wa = wx2 * a2;+ rPR += wa * tile[baseOff + 8];+ rPG += wa * tile[baseOff + 9];+ rPB += wa * tile[baseOff + 10];+ rA += wa;+ }+ if (a3 !== 0) {+ const wa = wx3 * a3;+ rPR += wa * tile[baseOff + 12];+ rPG += wa * tile[baseOff + 13];+ rPB += wa * tile[baseOff + 14];+ rA += wa;+ }++ sumPR += wy * rPR;+ sumPG += wy * rPG;+ sumPB += wy * rPB;+ sumA += wy * rA;+ }+ } else {+ // Tile-boundary / canvas-edge 4x4 fallback+ const ix0 = x0 > 0 ? x0 - 1 : 0;+ const ix1 = x0;+ const ix2 = x0 < maxDocX ? x0 + 1 : maxDocX;+ const ix3 = x0 + 2 <= maxDocX ? x0 + 2 : maxDocX;++ for (let row = 0; row < 4; row++) {+ const rawY = y0 + row - 1;+ const iy = rawY <= 0 ? 0 : rawY >= maxDocY ? maxDocY : rawY;+ const wy = row === 0 ? wy0 : row === 1 ? wy1 : row === 2 ? wy2 : wy3;+ const ty = iy >> 8;+ const lyOff = (iy & 255) << 8;++ let rPR = 0;+ let rPG = 0;+ let rPB = 0;+ let rA = 0;++ for (let col = 0; col < 4; col++) {+ const ix = col === 0 ? ix0 : col === 1 ? ix1 : col === 2 ? ix2 : ix3;+ const tile = getOrigTile(ix >> 8, ty);+ if (!tile) continue;+ const off = (lyOff | (ix & 255)) << 2;+ const a = tile[off + 3];+ if (a === 0) continue;+ const wx = col === 0 ? wx0 : col === 1 ? wx1 : col === 2 ? wx2 : wx3;+ const wa = wx * a;+ rPR += wa * tile[off];+ rPG += wa * tile[off + 1];+ rPB += wa * tile[off + 2];+ rA += wa;+ }++ sumPR += wy * rPR;+ sumPG += wy * rPG;+ sumPB += wy * rPB;+ sumA += wy * rA;+ }+ }++ if (sumA <= 0.5) continue;+ const invA = 1 / sumA;+ const r = sumPR * invA;+ const g = sumPG * invA;+ const b = sumPB * invA;+ dst[dstIdx] = r <= 0 ? 0 : r >= 255 ? 255 : Math.round(r);+ dst[dstIdx + 1] = g <= 0 ? 0 : g >= 255 ? 255 : Math.round(g);+ dst[dstIdx + 2] = b <= 0 ? 0 : b >= 255 ? 255 : Math.round(b);+ dst[dstIdx + 3] = sumA >= 255 ? 255 : Math.round(sumA);+ }+ }++ grid.writeImageData(layerId, { data: dst, width: roiW, height: roiH }, minX, minY, targetFormat, true);+ return { x: minX, y: minY, width: roiW, height: roiH };+}diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.tsindex 940bcd1..542d891 100644--- a/src/utils/presetBrushes.ts+++ b/src/utils/presetBrushes.ts@@ -23,6 +23,8 @@ import {generateCharcoalPaperTexture,generateCanvasWeaveTexture,generateNoiseGrainTexture,+ generateNaturalTipByProfile,+ getSurfaceTextureDataUrl,} from './proceduralBrushTips';export interface BuiltinBrushDefinition {@@ -34,7 +36,7 @@ export interface BuiltinBrushDefinition {badgeText: string;badgeBorder: string;desc: string;- icon: 'pen' | 'pencil' | 'paintbrush';+ icon: 'pen' | 'pencil' | 'paintbrush' | 'palette';settings: Partial<BrushSettings>;tipGenerator?: () => string; // Returns Base64 PNG data URLpaperTextureGenerator?: () => string; // Returns seamless Base64 PNG data URL@@ -49,6 +51,7 @@ export const BUILTIN_BRUSH_SECTIONS: BuiltinBrushSection[] = [{ id: 'pen', label: 'Pen' },{ id: 'sketch', label: 'Sketch' },{ id: 'brush', label: 'Brush' },+ { id: 'natural-paint', label: 'Natural Paint' },];const preloadedTipImages = new Map<string, HTMLImageElement>();@@ -529,8 +532,8 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [colorMixing: true,perceptualMixing: true,mixingMode: 'blend',- amountOfPaint: 0.62,- densityOfPaint: 0.82,+ amountOfPaint: 0.68,+ densityOfPaint: 0.86,colorStretch: 0.68,grain: 0.22,textureDensity: 0.22,@@ -573,9 +576,9 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [colorMixing: true,perceptualMixing: true,mixingMode: 'running_color',- amountOfPaint: 0.78,- densityOfPaint: 0.96,- colorStretch: 0.82,+ amountOfPaint: 0.82,+ densityOfPaint: 0.95,+ colorStretch: 0.78,grain: 0.3,textureDensity: 0.3,paperTextureMode: 'multiply',@@ -618,7 +621,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [colorMixing: true,perceptualMixing: true,mixingMode: 'blend',- amountOfPaint: 0.65,+ amountOfPaint: 0.72,densityOfPaint: 0.86,colorStretch: 0.58,grain: 0.52,@@ -799,6 +802,678 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [useGpu: true,},},++ // =========================================================================+ // NATURAL PAINT SECTION (Realistic Impasto, Bristle Ribbon & Pigment Mixing)+ // =========================================================================+ {+ id: 'impasto-bristle-oil',+ category: 'natural-paint',+ name: 'Impasto Bristle Oil',+ badge: 'Oil',+ badgeBg: 'bg-rose-500/15',+ badgeText: 'text-rose-300',+ badgeBorder: 'border-rose-500/30',+ desc: 'Thick Tactile Oil Paint with Pronounced 3D Bristle Ridges, Specular Sheen & Linen Weave Fringes',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('filbert'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 46,+ minSizeFactor: 0.35,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.15,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'filbert',+ count: 24,+ clumping: 0.56,+ stiffness: 0.64,+ length: 1.0,+ splay: 0.34,+ irregularity: 0.44,+ edgeRidge: 0.32,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'impasto_mix',+ amountOfPaint: 0.88,+ densityOfPaint: 0.96,+ colorStretch: 0.74,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.9,+ paintLoad: 0.88,+ depletionRate: 0.2,+ wetness: 0.54,+ viscosity: 0.68,+ autoClean: true,+ chargePerPressure: 0.52,+ dryBrush: 0.32,+ },+ impasto: {+ enabled: true,+ depth: 0.86,+ bristleRelief: 0.90,+ gloss: 0.50,+ reliefContrast: 0.72,+ lightAzimuth: 225,+ lightElevation: 32,+ },+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'canvas-locked',+ grain: 0.46,+ textureDensity: 0.46,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 24,+ useGpu: true,+ },+ },+ {+ id: 'wet-mixing-filbert',+ category: 'natural-paint',+ name: 'Creamy Oil Filbert',+ badge: 'Oil',+ badgeBg: 'bg-rose-500/15',+ badgeText: 'text-rose-300',+ badgeBorder: 'border-rose-500/30',+ desc: 'Buttery Oil Filbert with Per-Bristle Spatial Color Pickup & Vibrant Multi-Color Curved Streaks',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('filbert'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 54,+ minSizeFactor: 0.38,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 2,+ spacing: 0.045,+ stabilization: 12,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.25,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'filbert',+ count: 32,+ clumping: 0.36,+ stiffness: 0.56,+ length: 1.15,+ splay: 0.38,+ irregularity: 0.3,+ edgeRidge: 0.22,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'running_color',+ amountOfPaint: 0.76,+ densityOfPaint: 0.94,+ colorStretch: 0.85,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.95,+ paintLoad: 0.76,+ depletionRate: 0.14,+ wetness: 0.82,+ viscosity: 0.4,+ autoClean: true,+ chargePerPressure: 0.48,+ dryBrush: 0.24,+ },+ impasto: {+ enabled: true,+ depth: 0.66,+ bristleRelief: 0.72,+ gloss: 0.56,+ reliefContrast: 0.60,+ lightAzimuth: 225,+ lightElevation: 34,+ },+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'canvas-locked',+ grain: 0.36,+ textureDensity: 0.36,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 20,+ useGpu: true,+ },+ },+ {+ id: 'dry-bristle-rake',+ category: 'natural-paint',+ name: 'Dry Bristle Rake',+ badge: 'Dry',+ badgeBg: 'bg-sky-500/15',+ badgeText: 'text-sky-300',+ badgeBorder: 'border-sky-500/30',+ desc: 'Stiff Separated Bristles with Crisp Parallel Tracks, Paint Exhaustion & Linen Weave Breakup',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('rake'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 48,+ minSizeFactor: 0.42,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.94,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 8,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'rake',+ count: 34,+ clumping: 0.58,+ stiffness: 0.84,+ length: 0.95,+ splay: 0.28,+ irregularity: 0.52,+ edgeRidge: 0.14,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.9,+ densityOfPaint: 0.97,+ colorStretch: 0.72,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.86,+ paintLoad: 0.9,+ depletionRate: 0.26,+ wetness: 0.42,+ viscosity: 0.68,+ autoClean: true,+ chargePerPressure: 0.5,+ dryBrush: 0.34,+ },+ impasto: {+ enabled: true,+ depth: 0.58,+ bristleRelief: 0.86,+ gloss: 0.34,+ reliefContrast: 0.64,+ lightAzimuth: 225,+ lightElevation: 36,+ },+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'canvas-locked',+ grain: 0.38,+ textureDensity: 0.38,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 26,+ useGpu: true,+ },+ },+ {+ id: 'heavy-body-acrylic',+ category: 'natural-paint',+ name: 'Heavy Body Acrylic',+ badge: 'Acrylic',+ badgeBg: 'bg-orange-500/15',+ badgeText: 'text-orange-300',+ badgeBorder: 'border-orange-500/30',+ desc: 'Opaque Springy Flat Bristle Acrylic with Crisp Edges, Satin Relief & Controlled Wet Blending',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('flat'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('fine-cotton'),+ settings: {+ size: 42,+ minSizeFactor: 0.32,+ flow: 0.95,+ opacity: 1.0,+ hardness: 0.92,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.1,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'flat',+ count: 30,+ clumping: 0.38,+ stiffness: 0.76,+ length: 0.9,+ splay: 0.25,+ irregularity: 0.3,+ edgeRidge: 0.28,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.9,+ densityOfPaint: 0.96,+ colorStretch: 0.58,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.85,+ paintLoad: 0.9,+ depletionRate: 0.18,+ wetness: 0.45,+ viscosity: 0.62,+ autoClean: true,+ chargePerPressure: 0.45,+ dryBrush: 0.24,+ },+ impasto: {+ enabled: true,+ depth: 0.62,+ bristleRelief: 0.64,+ gloss: 0.34,+ reliefContrast: 0.58,+ lightAzimuth: 225,+ lightElevation: 36,+ },+ surfaceTextureId: 'fine-cotton',+ grainMappingMode: 'canvas-locked',+ grain: 0.32,+ textureDensity: 0.32,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 18,+ useGpu: true,+ },+ },+ {+ id: 'palette-knife-impasto',+ category: 'natural-paint',+ name: 'Palette Knife',+ badge: 'Knife',+ badgeBg: 'bg-fuchsia-500/15',+ badgeText: 'text-fuchsia-300',+ badgeBorder: 'border-fuchsia-500/30',+ desc: 'Sharp-Edged Painting Knife with Heavy Border Paint Ridges & Bold Spatial Scraping',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('knife'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('coarse-burlap'),+ settings: {+ size: 56,+ minSizeFactor: 0.45,+ flow: 0.96,+ opacity: 1.0,+ hardness: 0.98,+ antiAlias: 2,+ spacing: 0.045,+ stabilization: 9,+ sharpCorners: true,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.35,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'knife',+ count: 16,+ clumping: 0.05,+ stiffness: 0.96,+ length: 0.65,+ splay: 0.15,+ irregularity: 0.18,+ edgeRidge: 0.92,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'impasto_mix',+ amountOfPaint: 0.85,+ densityOfPaint: 0.98,+ colorStretch: 0.76,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.9,+ paintLoad: 0.85,+ depletionRate: 0.36,+ wetness: 0.68,+ viscosity: 0.78,+ autoClean: true,+ chargePerPressure: 0.58,+ dryBrush: 0.44,+ },+ impasto: {+ enabled: true,+ depth: 0.92,+ bristleRelief: 0.32,+ gloss: 0.68,+ reliefContrast: 0.82,+ lightAzimuth: 225,+ lightElevation: 30,+ },+ surfaceTextureId: 'coarse-burlap',+ grainMappingMode: 'canvas-locked',+ grain: 0.44,+ textureDensity: 0.44,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ paperTextureContrast: 26,+ useGpu: true,+ },+ },+ {+ id: 'velvet-gouache',+ category: 'natural-paint',+ name: 'Velvet Gouache',+ badge: 'Matte',+ badgeBg: 'bg-violet-500/15',+ badgeText: 'text-violet-300',+ badgeBorder: 'border-violet-500/30',+ desc: 'Smooth Matte Opaque Gouache with Gentle Wet Reactivation & Fine Gesso Tooth',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('filbert'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('gesso-board'),+ settings: {+ size: 38,+ minSizeFactor: 0.28,+ flow: 0.94,+ opacity: 1.0,+ hardness: 0.86,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.0,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'filbert',+ count: 34,+ clumping: 0.18,+ stiffness: 0.48,+ length: 1.05,+ splay: 0.32,+ irregularity: 0.2,+ edgeRidge: 0.08,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.88,+ densityOfPaint: 0.96,+ colorStretch: 0.55,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.88,+ paintLoad: 0.88,+ depletionRate: 0.14,+ wetness: 0.55,+ viscosity: 0.35,+ autoClean: true,+ chargePerPressure: 0.38,+ dryBrush: 0.18,+ },+ impasto: {+ enabled: true,+ depth: 0.16,+ bristleRelief: 0.22,+ gloss: 0.04,+ reliefContrast: 0.25,+ lightAzimuth: 225,+ lightElevation: 42,+ },+ surfaceTextureId: 'gesso-board',+ grainMappingMode: 'canvas-locked',+ grain: 0.28,+ textureDensity: 0.28,+ paperTextureMode: 'multiply',+ paperTextureScale: 0.9,+ paperTextureContrast: 16,+ useGpu: true,+ },+ },+ {+ id: 'granulating-watercolor',+ category: 'natural-paint',+ name: 'Granulating Watercolor',+ badge: 'Water',+ badgeBg: 'bg-cyan-500/15',+ badgeText: 'text-cyan-300',+ badgeBorder: 'border-cyan-500/30',+ desc: 'Translucent Watercolor Glaze with Wet Edge Rim & Pigment Settling into Cold-Press Valleys',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('round'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('cold-press-watercolor'),+ settings: {+ size: 44,+ minSizeFactor: 0.22,+ flow: 0.58,+ opacity: 0.72,+ hardness: 0.65,+ antiAlias: 2,+ spacing: 0.055,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.35,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'round',+ count: 28,+ clumping: 0.14,+ stiffness: 0.32,+ length: 1.35,+ splay: 0.52,+ irregularity: 0.22,+ edgeRidge: 0.05,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.72,+ densityOfPaint: 0.65,+ colorStretch: 0.65,+ wetEdge: 0.58,+ wetEdgeRadius: 3.0,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.92,+ paintLoad: 0.72,+ depletionRate: 0.12,+ wetness: 0.68,+ viscosity: 0.15,+ autoClean: true,+ chargePerPressure: 0.45,+ dryBrush: 0.14,+ granulation: 0.76,+ },+ impasto: {+ enabled: false,+ depth: 0.0,+ bristleRelief: 0.0,+ gloss: 0.0,+ reliefContrast: 0.0,+ lightAzimuth: 225,+ lightElevation: 42,+ },+ surfaceTextureId: 'cold-press-watercolor',+ grainMappingMode: 'canvas-locked',+ grain: 0.56,+ textureDensity: 0.56,+ paperTextureMode: 'multiply',+ paperTextureScale: 0.95,+ paperTextureContrast: 24,+ useGpu: true,+ },+ },+ {+ id: 'oil-bristle-blender',+ category: 'natural-paint',+ name: 'Dry Bristle Blender',+ badge: 'Blend',+ badgeBg: 'bg-teal-500/15',+ badgeText: 'text-teal-300',+ badgeBorder: 'border-teal-500/30',+ desc: 'Zero-Load Physical Fan Bristle Blender — Pulls & Harmonizes Paint with Relief Grooves Intact',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('fan'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('linen-canvas'),+ settings: {+ size: 52,+ minSizeFactor: 0.35,+ flow: 0.9,+ opacity: 1.0,+ hardness: 0.75,+ antiAlias: 2,+ spacing: 0.05,+ stabilization: 10,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.2,+ smoothing: true,+ renderMode: 'bristle-ribbon',+ bristle: {+ profile: 'fan',+ count: 32,+ clumping: 0.34,+ stiffness: 0.62,+ length: 1.15,+ splay: 0.42,+ irregularity: 0.35,+ edgeRidge: 0.14,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'smear',+ amountOfPaint: 0.0,+ densityOfPaint: 0.92,+ colorStretch: 0.85,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.92,+ paintLoad: 0.0,+ depletionRate: 0.0,+ wetness: 0.92,+ viscosity: 0.45,+ autoClean: true,+ chargePerPressure: 0.35,+ dryBrush: 0.22,+ },+ impasto: {+ enabled: true,+ depth: 0.45,+ bristleRelief: 0.68,+ gloss: 0.32,+ reliefContrast: 0.48,+ lightAzimuth: 225,+ lightElevation: 36,+ },+ surfaceTextureId: 'linen-canvas',+ grainMappingMode: 'canvas-locked',+ grain: 0.3,+ textureDensity: 0.3,+ paperTextureMode: 'compare',+ paperTextureScale: 0.85,+ useGpu: true,+ },+ },+ {+ id: 'pastel-stick-canvas',+ category: 'natural-paint',+ name: 'Soft Oil Pastel',+ badge: 'Pastel',+ badgeBg: 'bg-amber-500/15',+ badgeText: 'text-amber-300',+ badgeBorder: 'border-amber-500/30',+ desc: 'Creamy Oil Pastel with Broad Stylus Tilt Shading & Crisp Coverage Across Rough Paper Peaks',+ icon: 'palette',+ tipGenerator: () => generateNaturalTipByProfile('flat'),+ paperTextureGenerator: () => getSurfaceTextureDataUrl('rough-pastel'),+ settings: {+ size: 32,+ minSizeFactor: 0.4,+ flow: 0.92,+ opacity: 1.0,+ hardness: 0.88,+ antiAlias: 2,+ spacing: 0.055,+ stabilization: 6,+ sharpCorners: false,+ usePressure: true,+ useTilt: true,+ tiltScale: 1.85,+ smoothing: true,+ renderMode: 'bristle-hybrid',+ bristle: {+ profile: 'flat',+ count: 26,+ clumping: 0.22,+ stiffness: 0.88,+ length: 0.7,+ splay: 0.55,+ irregularity: 0.48,+ edgeRidge: 0.15,+ },+ colorMixing: true,+ perceptualMixing: true,+ mixingMode: 'blend',+ amountOfPaint: 0.85,+ densityOfPaint: 0.92,+ colorStretch: 0.48,+ naturalPaint: {+ enabled: true,+ spatialMixing: true,+ pigmentMixingStrength: 0.86,+ paintLoad: 0.85,+ depletionRate: 0.26,+ wetness: 0.4,+ viscosity: 0.74,+ autoClean: true,+ chargePerPressure: 0.72,+ dryBrush: 0.66,+ },+ impasto: {+ enabled: true,+ depth: 0.38,+ bristleRelief: 0.32,+ gloss: 0.14,+ reliefContrast: 0.52,+ lightAzimuth: 315,+ lightElevation: 45,+ },+ surfaceTextureId: 'rough-pastel',+ grainMappingMode: 'canvas-locked',+ grain: 0.78,+ textureDensity: 0.78,+ paperTextureMode: 'compare',+ paperTextureScale: 0.95,+ paperTextureContrast: 36,+ useGpu: true,+ },+ },];let _assetsPrewarmed = false;diff --git a/src/utils/proceduralBrushTips.ts b/src/utils/proceduralBrushTips.tsindex 0f4a7ec..6b65192 100644--- a/src/utils/proceduralBrushTips.ts+++ b/src/utils/proceduralBrushTips.ts@@ -7,8 +7,13 @@* Paper textures encode surface elevation in luminance [0..255] with opaque alpha=255.*/+import type { BristleProfilePreset, SurfaceTextureId } from '../types/editor';+const TIP_SIZE = 128;const PAPER_SIZE = 256;+export const SURFACE_TEXTURE_SIZE = 1024;+/** High-DPI texel density multiplier: 2x oversampled texels per document pixel at scale=1.0 */+export const SURFACE_TEXELS_PER_PX = 2.0;const generatedCache = new Map<string, string>();@@ -874,3 +879,496 @@ export function generateNoiseGrainTexture(): string {}});}++// -------------------------------------------------------------+// HIGH-DPI (1024x1024, 2x OVERSAMPLED) SEAMLESS SURFACE LIBRARY+// Used by Natural Paint Engine (Canvas Tooth, Dry-Brush & Impasto)+// -------------------------------------------------------------++export interface SurfaceTextureMeta {+ id: SurfaceTextureId;+ label: string;+ desc: string;+}++export const SURFACE_TEXTURE_CATALOG: SurfaceTextureMeta[] = [+ { id: 'linen-canvas', label: 'Linen Canvas', desc: 'High-DPI woven primed Belgian linen with spun fibers & slubs' },+ { id: 'coarse-burlap', label: 'Coarse Burlap', desc: 'Heavy twisted-yarn rustic canvas weave with deep valleys' },+ { id: 'fine-cotton', label: 'Fine Cotton', desc: 'Smooth tight-weave primed cotton duck with gesso micro-tooth' },+ { id: 'cold-press-watercolor', label: 'Cold-Press Paper', desc: 'Domed cotton fibers with granulating micro-valleys' },+ { id: 'rough-pastel', label: 'Rough Pastel', desc: 'Toothy laid charcoal and pastel paper with crisp ridges' },+ { id: 'gesso-board', label: 'Gesso Board', desc: 'Cross-brushed primed wood panel with fine bristle striations' },+ { id: 'stipple-grain', label: 'Stipple Grain', desc: 'Organic high-DPI mineral & fine film grain' },+];++const surfaceHeightCache = new Map<SurfaceTextureId, Uint8Array>();++function buildSurfaceHeightField(id: SurfaceTextureId): Uint8Array {+ const size = SURFACE_TEXTURE_SIZE;+ const out = new Uint8Array(size * size);+ const invSize = 1 / size;++ if (id === 'linen-canvas') {+ const rand = createPrng(0x7a11f01);+ // 80 Belgian linen threads across 1024 high-DPI texels (12.8 texels/thread -> ~5.5px at scale=0.85)+ // Purely continuous, band-limited cylindrical yarn geometry (ZERO per-texel white noise -> silky 3D normals!)+ const threads = 80;+ const warpSlub = new Float32Array(threads);+ const weftSlub = new Float32Array(threads);+ const warpJitter = new Float32Array(threads);+ const weftJitter = new Float32Array(threads);+ const warpHeight = new Float32Array(threads);+ const weftHeight = new Float32Array(threads);+ for (let i = 0; i < threads; i++) {+ warpSlub[i] = 0.82 + rand() * 0.30;+ weftSlub[i] = 0.82 + rand() * 0.30;+ warpJitter[i] = (rand() - 0.5) * 0.18;+ weftJitter[i] = (rand() - 0.5) * 0.18;+ warpHeight[i] = 0.90 + rand() * 0.15;+ weftHeight[i] = 0.88 + rand() * 0.15;+ }+ const gFiber = makePeriodicGrid(128, rand);+ const gUndul = makePeriodicGrid(32, rand);+ const gDrift = makePeriodicGrid(16, rand);++ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ // Gentle hand-loomed warp/weft drift so the weave feels genuinely woven, never mechanical+ const driftX = (samplePeriodic(gDrift, 16, nx * 16, ny * 16) - 0.5) * 0.24;+ const driftY = (samplePeriodic(gDrift, 16, nx * 16 + 7.3, ny * 16 + 4.9) - 0.5) * 0.24;++ const tx = ((nx * threads + driftX) % threads + threads) % threads;+ const ty = ((ny * threads + driftY) % threads + threads) % threads;+ const colCell = Math.floor(tx);+ const rowCell = Math.floor(ty);+ const fracX = tx - colCell;+ const fracY = ty - rowCell;++ const parity = ((rowCell + colCell) & 1) === 0;+ const dx = (fracX - 0.5 + warpJitter[colCell] * 0.15) * 2.0;+ const dy = (fracY - 0.5 + weftJitter[rowCell] * 0.15) * 2.0;++ // Smooth cylindrical yarn cross-section with crisp dark woven interstices+ const warpWidth = warpSlub[colCell];+ const weftWidth = weftSlub[rowCell];+ const warpCyl = Math.cos(Math.min(1, Math.abs(dx) / Math.max(0.60, warpWidth)) * Math.PI * 0.5);+ const weftCyl = Math.cos(Math.min(1, Math.abs(dy) / Math.max(0.60, weftWidth)) * Math.PI * 0.5);++ // Smooth band-limited spun-yarn twist along each thread (crisp at 1024x1024, zero static noise)+ const warpTwist = 0.93 + 0.07 * Math.sin((fracX * 2.2 + ny * threads * 2.5) * Math.PI);+ const weftTwist = 0.93 + 0.07 * Math.sin((fracY * 2.2 - nx * threads * 2.5) * Math.PI);++ // Over/under yarn arch profile+ const warpArch = warpCyl * (0.64 + 0.36 * Math.cos(dy * Math.PI * 0.5)) * warpTwist * warpHeight[colCell];+ const weftArch = weftCyl * (0.64 + 0.36 * Math.cos(dx * Math.PI * 0.5)) * weftTwist * weftHeight[rowCell];++ const over = parity ? warpArch : weftArch;+ const under = parity ? weftArch * 0.44 : warpArch * 0.44;+ const baseWeave = Math.max(over, under);++ const fiber = samplePeriodic(gFiber, 128, nx * 128, ny * 128);+ const undul = samplePeriodic(gUndul, 32, nx * 32, ny * 32);+ const h = clamp01(baseWeave * 0.82 + fiber * 0.11 + undul * 0.07);+ out[row + x] = Math.round(Math.pow(h, 0.95) * 255);+ }+ }+ return out;+ }++ if (id === 'coarse-burlap') {+ const rand = createPrng(0x7a22b02);+ // 64 heavy twisted jute/burlap threads across 1024 high-DPI texels (16 texels/thread!)+ const threads = 64;+ const warpThick = new Float32Array(threads);+ const weftThick = new Float32Array(threads);+ for (let i = 0; i < threads; i++) {+ warpThick[i] = 0.72 + rand() * 0.42;+ weftThick[i] = 0.72 + rand() * 0.42;+ }+ const gRough = makePeriodicGrid(256, rand);+ const gDrift = makePeriodicGrid(32, rand);++ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const driftX = (samplePeriodic(gDrift, 32, nx * 32, ny * 32) - 0.5) * 0.25;+ const driftY = (samplePeriodic(gDrift, 32, nx * 32 + 13, ny * 32 + 5) - 0.5) * 0.25;+ const tx = ((nx * threads + driftX) % threads + threads) % threads;+ const ty = ((ny * threads + driftY) % threads + threads) % threads;+ const cCell = Math.floor(tx);+ const rCell = Math.floor(ty);+ const fx = (tx - cCell - 0.5) * 2.0;+ const fy = (ty - rCell - 0.5) * 2.0;+ const parity = ((rCell + cCell) & 1) === 0;+ const twistW = 0.84 + 0.16 * Math.sin((ny * threads * 4.0 + fx * 2.2) * Math.PI);+ const twistH = 0.84 + 0.16 * Math.sin((nx * threads * 4.0 - fy * 2.2) * Math.PI);+ const warpC = Math.cos(Math.min(1, Math.abs(fx) / Math.max(0.55, warpThick[cCell])) * Math.PI * 0.5) * twistW;+ const weftC = Math.cos(Math.min(1, Math.abs(fy) / Math.max(0.55, weftThick[rCell])) * Math.PI * 0.5) * twistH;+ const weave = parity ? Math.max(warpC, weftC * 0.40) : Math.max(weftC, warpC * 0.40);+ const rough = samplePeriodic(gRough, 256, nx * 256, ny * 256);+ const h = clamp01(weave * 0.82 + rough * 0.18 - 0.04);+ out[row + x] = Math.round(Math.pow(h, 1.04) * 255);+ }+ }+ return out;+ }++ if (id === 'fine-cotton') {+ const rand = createPrng(0x7a33c03);+ const threads = 160; // Ultra-tight primed cotton duck across 1024 high-DPI texels+ const gGesso = makePeriodicGrid(128, rand);+ const gMicro = makePeriodicGrid(256, rand);+ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ const wy = Math.sin(ny * Math.PI * 2 * threads);+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const wx = Math.sin(nx * Math.PI * 2 * threads);+ const checker = Math.sin((nx + ny) * Math.PI * 2 * (threads * 0.5)) * 0.16;+ const weave = (wx * 0.5 + 0.5) * 0.36 + (wy * 0.5 + 0.5) * 0.36 + 0.14 + checker;+ const gesso = samplePeriodic(gGesso, 128, nx * 128, ny * 128);+ const micro = samplePeriodic(gMicro, 256, nx * 256, ny * 256);+ const h = clamp01(weave * 0.58 + gesso * 0.24 + micro * 0.14 + rand() * 0.04);+ out[row + x] = Math.round(h * 255);+ }+ }+ return out;+ }++ if (id === 'cold-press-watercolor') {+ const rand = createPrng(0x7a44d04);+ const coarseDomes = makeCellularDomeField(256, 48, rand);+ const fineDomes = makeCellularDomeField(256, 96, rand);+ const gFiber = makePeriodicGrid(256, rand);+ const gUndul = makePeriodicGrid(64, rand);+ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ const sy = ny * 256;+ const y0 = Math.floor(sy) & 255;+ const y1 = (y0 + 1) & 255;+ const ty = sy - Math.floor(sy);+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const sx = nx * 256;+ const x0 = Math.floor(sx) & 255;+ const x1 = (x0 + 1) & 255;+ const tx = sx - Math.floor(sx);+ const cTop = coarseDomes[y0 * 256 + x0] * (1 - tx) + coarseDomes[y0 * 256 + x1] * tx;+ const cBot = coarseDomes[y1 * 256 + x0] * (1 - tx) + coarseDomes[y1 * 256 + x1] * tx;+ const d1 = cTop * (1 - ty) + cBot * ty;+ const fTop = fineDomes[y0 * 256 + x0] * (1 - tx) + fineDomes[y0 * 256 + x1] * tx;+ const fBot = fineDomes[y1 * 256 + x0] * (1 - tx) + fineDomes[y1 * 256 + x1] * tx;+ const d2 = fTop * (1 - ty) + fBot * ty;+ const fiber = samplePeriodic(gFiber, 256, nx * 256, ny * 256);+ const undul = samplePeriodic(gUndul, 64, nx * 64, ny * 64);+ const raw = d1 * 0.48 + d2 * 0.26 + fiber * 0.14 + undul * 0.08 + rand() * 0.04;+ const h = clamp01((raw - 0.12) / 0.74);+ out[row + x] = Math.round(Math.pow(h, 1.06) * 255);+ }+ }+ return out;+ }++ if (id === 'rough-pastel') {+ const rand = createPrng(0x7a55e05);+ const domes = makeCellularDomeField(256, 60, rand);+ const gGrit = makePeriodicGrid(256, rand);+ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ const rib = Math.sin(ny * Math.PI * 2 * 96) * 0.15;+ const sy = ny * 256;+ const y0 = Math.floor(sy) & 255;+ const y1 = (y0 + 1) & 255;+ const ty = sy - Math.floor(sy);+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const chain = Math.sin(nx * Math.PI * 2 * 16) * 0.06;+ const sx = nx * 256;+ const x0 = Math.floor(sx) & 255;+ const x1 = (x0 + 1) & 255;+ const tx = sx - Math.floor(sx);+ const top = domes[y0 * 256 + x0] * (1 - tx) + domes[y0 * 256 + x1] * tx;+ const bot = domes[y1 * 256 + x0] * (1 - tx) + domes[y1 * 256 + x1] * tx;+ const d = top * (1 - ty) + bot * ty;+ const grit = samplePeriodic(gGrit, 256, nx * 256, ny * 256);+ const raw = d * 0.48 + grit * 0.30 + rand() * 0.14 + rib + chain;+ const h = clamp01((raw - 0.14) / 0.72);+ out[row + x] = Math.round(Math.pow(h, 1.15) * 255);+ }+ }+ return out;+ }++ if (id === 'gesso-board') {+ const rand = createPrng(0x7a66f06);+ const gBrushH = makePeriodicGrid(128, rand);+ const gBrushV = makePeriodicGrid(128, rand);+ const gMicro = makePeriodicGrid(256, rand);+ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const hStreak = samplePeriodic(gBrushH, 128, nx * 28, ny * 220);+ const vStreak = samplePeriodic(gBrushV, 128, nx * 220, ny * 28);+ const micro = samplePeriodic(gMicro, 256, nx * 256, ny * 256);+ const raw = hStreak * 0.38 + vStreak * 0.30 + micro * 0.24 + rand() * 0.08;+ const h = clamp01((raw - 0.12) / 0.76);+ out[row + x] = Math.round(h * 255);+ }+ }+ return out;+ }++ // 'stipple-grain'+ const rand = createPrng(0x7a77007);+ const gMed = makePeriodicGrid(128, rand);+ const gFine = makePeriodicGrid(256, rand);+ for (let y = 0; y < size; y++) {+ const row = y * size;+ const ny = y * invSize;+ for (let x = 0; x < size; x++) {+ const nx = x * invSize;+ const m = samplePeriodic(gMed, 128, nx * 128, ny * 128);+ const f = samplePeriodic(gFine, 256, nx * 256, ny * 256);+ const raw = m * 0.28 + f * 0.36 + rand() * 0.36;+ const h = clamp01((raw - 0.14) / 0.72);+ out[row + x] = Math.round(h * 255);+ }+ }+ return out;+}++/**+ * Returns the cached 1024x1024 seamless high-DPI surface elevation table [0..255] for a built-in texture ID.+ */+export function getSurfaceTextureHeightField(id: SurfaceTextureId): Uint8Array {+ const hit = surfaceHeightCache.get(id);+ if (hit) return hit;+ const field = buildSurfaceHeightField(id);+ surfaceHeightCache.set(id, field);+ return field;+}++/**+ * Fast bilinear periodic lookup of the high-DPI 1024x1024 surface heightmap in [0..1]+ * using 2x oversampled texel coordinates for razor-sharp grain at 100%-400% zoom.+ */+export function sampleSurfaceTextureHeight(+ id: SurfaceTextureId,+ x: number,+ y: number,+ scale: number = 1.0,+ rotateRad: number = 0+): number {+ const table = getSurfaceTextureHeightField(id);+ const size = SURFACE_TEXTURE_SIZE;+ const mask = size - 1;+ const invScale = SURFACE_TEXELS_PER_PX / Math.max(0.05, scale);+ let px = x * invScale;+ let py = y * invScale;+ if (Math.abs(rotateRad) > 1e-4) {+ const c = Math.cos(rotateRad);+ const s = Math.sin(rotateRad);+ const rx = px * c - py * s;+ const ry = px * s + py * c;+ px = rx;+ py = ry;+ }+ const fx = Math.floor(px);+ const fy = Math.floor(py);+ const tx = px - fx;+ const ty = py - fy;+ const x0 = fx & mask;+ const y0 = fy & mask;+ const x1 = (fx + 1) & mask;+ const y1 = (fy + 1) & mask;+ const v00 = table[y0 * size + x0];+ const v10 = table[y0 * size + x1];+ const v01 = table[y1 * size + x0];+ const v11 = table[y1 * size + x1];+ const top = v00 + (v10 - v00) * tx;+ const bot = v01 + (v11 - v01) * tx;+ return (top + (bot - top) * ty) / 255.0;+}++/**+ * Samples true 2x-DPI analytical surface gradients (dh/dx, dh/dy) directly from the 1024x1024+ * continuous heightfield at sub-texel central differences — eliminates 1px aliasing on linen weave!+ */+export function sampleSurfaceTextureGrad(+ id: SurfaceTextureId,+ x: number,+ y: number,+ scale: number,+ rotateRad: number,+ out: { gx: number; gy: number }+): void {+ const table = getSurfaceTextureHeightField(id);+ const size = SURFACE_TEXTURE_SIZE;+ const mask = size - 1;+ const invScale = SURFACE_TEXELS_PER_PX / Math.max(0.05, scale);+ let px = x * invScale;+ let py = y * invScale;+ let cosR = 1;+ let sinR = 0;+ if (Math.abs(rotateRad) > 1e-4) {+ cosR = Math.cos(rotateRad);+ sinR = Math.sin(rotateRad);+ const rx = px * cosR - py * sinR;+ const ry = px * sinR + py * cosR;+ px = rx;+ py = ry;+ }++ const sampleBilin = (sx: number, sy: number): number => {+ const fx = Math.floor(sx);+ const fy = Math.floor(sy);+ const tx = sx - fx;+ const ty = sy - fy;+ const x0 = fx & mask;+ const y0 = fy & mask;+ const x1 = (fx + 1) & mask;+ const y1 = (fy + 1) & mask;+ const r0 = y0 * size;+ const r1 = y1 * size;+ const v00 = table[r0 + x0];+ const v10 = table[r0 + x1];+ const v01 = table[r1 + x0];+ const v11 = table[r1 + x1];+ return v00 + (v10 - v00) * tx + ((v01 + (v11 - v01) * tx) - (v00 + (v10 - v00) * tx)) * ty;+ };++ // Central difference across +/-0.65 high-DPI texels (band-limited, zero stair-step!)+ const eps = 0.65;+ const dU = (sampleBilin(px + eps, py) - sampleBilin(px - eps, py)) / (255.0 * 2.0 * eps);+ const dV = (sampleBilin(px, py + eps) - sampleBilin(px, py - eps)) / (255.0 * 2.0 * eps);+ out.gx = dU * cosR + dV * sinR;+ out.gy = -dU * sinR + dV * cosR;+}++/**+ * Generates and caches a crisp 512x512 seamless PNG data URL (2x box-filtered from 1024x1024)+ * for UI swatches and legacy paper-texture GPU binding.+ */+export function getSurfaceTextureDataUrl(id: SurfaceTextureId): string {+ const outSize = 512;+ return buildCachedPng(`surface512:${id}`, outSize, (data, size) => {+ const field = getSurfaceTextureHeightField(id);+ const srcSize = SURFACE_TEXTURE_SIZE;+ const step = Math.max(1, srcSize / size);+ for (let y = 0; y < size; y++) {+ const sy = y * step;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const sx = x * step;+ const v =+ step === 2+ ? Math.round(+ (field[sy * srcSize + sx] ++ field[sy * srcSize + sx + 1] ++ field[(sy + 1) * srcSize + sx] ++ field[(sy + 1) * srcSize + sx + 1]) *+ 0.25+ )+ : field[sy * srcSize + sx];+ const idx = row + x * 4;+ data[idx] = v;+ data[idx + 1] = v;+ data[idx + 2] = v;+ data[idx + 3] = 255;+ }+ }+ });+}++// -------------------------------------------------------------+// NATURAL PAINT PHYSICAL BRUSH TIP GENERATORS (128x128)+// -------------------------------------------------------------++export function generateNaturalTipByProfile(profile: BristleProfilePreset): string {+ const key = `natural-tip:${profile}`;+ return buildCachedPng(key, TIP_SIZE, (data, size) => {+ const rand = createPrng(+ profile === 'flat'+ ? 0x9011+ : profile === 'filbert'+ ? 0x9022+ : profile === 'fan'+ ? 0x9033+ : profile === 'rake'+ ? 0x9044+ : profile === 'knife'+ ? 0x9055+ : 0x9066+ );+ const half = size * 0.5;+ const rx = half - 6;+ const ry = profile === 'knife' ? half * 0.24 : profile === 'flat' || profile === 'rake' ? half * 0.42 : profile === 'filbert' ? half * 0.55 : half - 8;++ const strandCount =+ profile === 'rake' ? 18 : profile === 'fan' ? 28 : profile === 'knife' ? 1 : 38;++ if (profile === 'knife') {+ // Sharp palette knife blade: crisp chisel edge with subtle paint buildup along outer ridge+ for (let y = 0; y < size; y++) {+ const ny = (y - half + 0.5) / ry;+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ const nx = (x - half + 0.5) / rx;+ if (Math.abs(nx) > 1.02 || Math.abs(ny) > 1.05) continue;+ const bladeMask =+ (1.0 - smoothstep(0.86, 1.0, Math.abs(nx))) *+ (1.0 - smoothstep(0.65, 1.0, Math.abs(ny)));+ const micro = 0.88 + rand() * 0.12;+ writeAlphaPixel(data, row + x * 4, bladeMask * micro);+ }+ }+ return;+ }++ // Build bristle tuft clusters across the brush cross-section+ const tufts: Array<{ cx: number; cy: number; r: number; strength: number }> = [];+ for (let i = 0; i < strandCount; i++) {+ const u = strandCount > 1 ? (i / (strandCount - 1)) * 2 - 1 : 0;+ const arch = profile === 'filbert' ? Math.sqrt(Math.max(0.15, 1.0 - u * u * 0.85)) : profile === 'fan' ? 1.0 - Math.abs(u) * 0.35 : 1.0;+ const cx = half + u * rx * (profile === 'rake' ? 0.94 : 0.86) + (rand() - 0.5) * (profile === 'rake' ? 1.2 : 3.5);+ const cy = half + (rand() - 0.5) * ry * (profile === 'rake' ? 0.55 : 0.95) * arch;+ const r =+ profile === 'rake'+ ? 2.2 + rand() * 1.4+ : profile === 'fan'+ ? 2.6 + rand() * 2.2+ : (4.2 + rand() * 3.8) * (0.65 + 0.35 * arch);+ tufts.push({ cx, cy, r, strength: 0.72 + rand() * 0.28 });+ }++ for (let y = 0; y < size; y++) {+ const row = y * size * 4;+ for (let x = 0; x < size; x++) {+ let accum = 0;+ for (let i = 0; i < tufts.length; i++) {+ const t = tufts[i];+ const dx = x - t.cx;+ const dy = (y - t.cy) * (profile === 'flat' || profile === 'rake' ? 1.4 : 1.0);+ const d = Math.hypot(dx, dy) / t.r;+ if (d < 1.0) {+ const v = (1.0 - smoothstep(0.35, 1.0, d)) * t.strength;+ if (v > accum) accum = v;+ }+ }+ if (accum > 0.02) {+ writeAlphaPixel(data, row + x * 4, accum);+ }+ }+ }+ });+}diff --git a/src/utils/retouchEngine.ts b/src/utils/retouchEngine.tsnew file mode 100644index 0000000..f664aa5--- /dev/null+++ b/src/utils/retouchEngine.ts@@ -0,0 +1,932 @@+/**+ * Professional Retouch Engine — Smudge, Blur, Dodge, Burn & Clone Stamp+ *+ * Operates directly on SparseTileGrid ROIs with zero full-document canvas allocations.+ * Uses premultiplied alpha math across Smudge/Blur/Clone to prevent dark edge fringes,+ * Rec.709 luminance tonal weighting for Dodge/Burn, and lazy per-tile snapshots for undo.+ */++import type {+ CanvasDimensions,+ DirtyRect,+ LayerItem,+ Point2D,+} from '../types/editor';+import {+ BYTES_32BIT,+ SparseTileGrid,+ TILE_SIZE,+ TileFormat,+ TileSnapshotEntry,+ getTileKey,+ unpack1BitToRGBA,+ unpack8BitToRGBA,+} from './tileEngine';+import { parseHexRgb } from './gradientEngine';++export type RetouchMode = 'smudge' | 'blur' | 'dodge' | 'burn' | 'clone-stamp';+export type RetouchTonalRange = 'shadows' | 'midtones' | 'highlights';+export type CloneSampleMode = 'active' | 'all-visible';++export interface RetouchSettings {+ mode: RetouchMode;+ size: number; // 2..300 px+ strength: number; // 1..100 %+ hardness: number; // 0..100 %+ spacing: number; // 0.05..0.5+ usePressure: boolean;+ tonalRange: RetouchTonalRange; // Dodge / Burn range+ protectTones: boolean; // Dodge / Burn hue preservation+ smudgeFingerPainting: boolean; // Load primary color at stroke start+ cloneAligned: boolean; // Keep relative offset across strokes+ cloneSampleMode: CloneSampleMode; // Active layer vs all visible composited+}++export const DEFAULT_RETOUCH_SETTINGS: RetouchSettings = {+ mode: 'smudge',+ size: 40,+ strength: 50,+ hardness: 45,+ spacing: 0.15,+ usePressure: true,+ tonalRange: 'midtones',+ protectTones: true,+ smudgeFingerPainting: false,+ cloneAligned: true,+ cloneSampleMode: 'active',+};++export interface RetouchStrokeSession {+ mode: RetouchMode;+ layerId: string;+ targetFormat: TileFormat;+ alphaLock: boolean;+ dimensions: CanvasDimensions;+ selectionMask: Uint8Array | null;+ beforeSnapshot: Map<string, TileSnapshotEntry>;+ dirtyRect: DirtyRect | null;+ lastDabPos: Point2D | null;+ remainderDist: number;+ // Smudge state: premultiplied RGBA float buffer of size dabDim * dabDim * 4+ smudgeBuf: Float32Array | null;+ smudgeDim: number;+ // Clone Stamp state+ cloneOffset: Point2D | null; // source - dest+ cloneSourceTileCache: Map<string, Uint8ClampedArray | null>;+ visibleLayers?: LayerItem[];+ isLayerVisible?: (layer: LayerItem) => boolean;+ getEffectiveOpacity?: (layer: LayerItem) => number;+}++function clamp255(v: number): number {+ return v <= 0 ? 0 : v >= 255 ? 255 : v;+}++function clamp01(v: number): number {+ return v <= 0 ? 0 : v >= 1 ? 1 : v;+}++function mergeDirty(a: DirtyRect | null, b: DirtyRect): DirtyRect {+ if (!a) return { ...b };+ const minX = Math.min(a.x, b.x);+ const minY = Math.min(a.y, b.y);+ const maxX = Math.max(a.x + a.width, b.x + b.width);+ const maxY = Math.max(a.y + a.height, b.y + b.height);+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };+}++/**+ * Radial falloff weight in [0, 1] matching hardness in [0, 1].+ */+export function computeBrushFalloff(distNorm: number, hardness: number): number {+ if (distNorm >= 1) return 0;+ if (hardness >= 0.999) return 1;+ if (distNorm <= hardness) return 1;+ const t = (distNorm - hardness) / Math.max(1e-4, 1 - hardness);+ // Smoothstep C1 falloff+ const inv = 1 - t;+ return inv * inv * (3 - 2 * inv);+}++/**+ * Snapshots all tiles intersecting `[x, y, w, h]` lazily before mutation.+ */+function snapshotRoiTiles(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number,+ w: number,+ h: number,+ beforeSnapshot: Map<string, TileSnapshotEntry>+): void {+ if (w <= 0 || h <= 0) return;+ const minTx = Math.floor(x / TILE_SIZE);+ const maxTx = Math.floor((x + w - 1) / TILE_SIZE);+ const minTy = Math.floor(y / TILE_SIZE);+ const maxTy = Math.floor((y + h - 1) / TILE_SIZE);+ for (let ty = minTy; ty <= maxTy; ty++) {+ for (let tx = minTx; tx <= maxTx; tx++) {+ grid.snapshotSingleTileInto(layerId, tx, ty, beforeSnapshot);+ }+ }+}++/**+ * Creates a new retouch stroke session.+ */+export function createRetouchStrokeSession(params: {+ mode: RetouchMode;+ layerId: string;+ targetFormat: TileFormat;+ alphaLock: boolean;+ dimensions: CanvasDimensions;+ selectionMask: Uint8Array | null;+ cloneOffset?: Point2D | null;+ visibleLayers?: LayerItem[];+ isLayerVisible?: (layer: LayerItem) => boolean;+ getEffectiveOpacity?: (layer: LayerItem) => number;+}): RetouchStrokeSession {+ return {+ mode: params.mode,+ layerId: params.layerId,+ targetFormat: params.targetFormat,+ alphaLock: params.alphaLock,+ dimensions: params.dimensions,+ selectionMask: params.selectionMask,+ beforeSnapshot: new Map<string, TileSnapshotEntry>(),+ dirtyRect: null,+ lastDabPos: null,+ remainderDist: 0,+ smudgeBuf: null,+ smudgeDim: 0,+ cloneOffset: params.cloneOffset ? { ...params.cloneOffset } : null,+ cloneSourceTileCache: new Map<string, Uint8ClampedArray | null>(),+ visibleLayers: params.visibleLayers,+ isLayerVisible: params.isLayerVisible,+ getEffectiveOpacity: params.getEffectiveOpacity,+ };+}++function readCachedPreStrokeTile(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ layerId: string,+ tx: number,+ ty: number+): Uint8ClampedArray | null {+ const key = getTileKey(layerId, tx, ty, 0);+ if (session.cloneSourceTileCache.has(key)) {+ return session.cloneSourceTileCache.get(key) ?? null;+ }++ // Prefer pre-stroke snapshot if this tile was already mutated during the current stroke+ const snap = session.beforeSnapshot.get(key);+ if (snap) {+ if (!snap.data) {+ session.cloneSourceTileCache.set(key, null);+ return null;+ }+ const rgba = new Uint8ClampedArray(BYTES_32BIT);+ if (snap.format === 'color-32bit') {+ rgba.set(snap.data);+ } else if (snap.format === 'monochrome-1bit') {+ unpack1BitToRGBA(snap.data, rgba);+ } else {+ unpack8BitToRGBA(snap.data, rgba);+ }+ session.cloneSourceTileCache.set(key, rgba);+ return rgba;+ }++ const tile = grid.getTile(layerId, tx, ty, 0);+ if (!tile || !tile.data) {+ session.cloneSourceTileCache.set(key, null);+ return null;+ }+ const rgba = new Uint8ClampedArray(BYTES_32BIT);+ if (tile.format === 'color-32bit') {+ rgba.set(tile.data);+ } else if (tile.format === 'monochrome-1bit') {+ unpack1BitToRGBA(tile.data, rgba);+ } else {+ unpack8BitToRGBA(tile.data, rgba);+ }+ session.cloneSourceTileCache.set(key, rgba);+ return rgba;+}++function samplePreStrokePixel(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ px: number,+ py: number,+ sampleMode: CloneSampleMode,+ out: [number, number, number, number]+): void {+ const docW = session.dimensions.width;+ const docH = session.dimensions.height;+ if (px < 0 || py < 0 || px >= docW || py >= docH) {+ out[0] = 0;+ out[1] = 0;+ out[2] = 0;+ out[3] = 0;+ return;+ }+ const tx = Math.floor(px / TILE_SIZE);+ const ty = Math.floor(py / TILE_SIZE);+ const lx = px - tx * TILE_SIZE;+ const ly = py - ty * TILE_SIZE;+ const off = (ly * TILE_SIZE + lx) * 4;++ if (sampleMode === 'active' || !session.visibleLayers) {+ const rgba = readCachedPreStrokeTile(grid, session, session.layerId, tx, ty);+ if (!rgba) {+ out[0] = 0;+ out[1] = 0;+ out[2] = 0;+ out[3] = 0;+ return;+ }+ out[0] = rgba[off];+ out[1] = rgba[off + 1];+ out[2] = rgba[off + 2];+ out[3] = rgba[off + 3];+ return;+ }++ // Composite all visible layers bottom-to-top (layers array is top-to-bottom)+ let accR = 0;+ let accG = 0;+ let accB = 0;+ let accA = 0;+ const layers = session.visibleLayers;+ for (let i = layers.length - 1; i >= 0; i--) {+ const l = layers[i];+ if (l.type === 'folder' || l.type === 'frame-folder' || l.type === 'adjustment') continue;+ if (session.isLayerVisible && !session.isLayerVisible(l)) continue;+ const rgba = readCachedPreStrokeTile(grid, session, l.id, tx, ty);+ if (!rgba) continue;+ const saRaw = rgba[off + 3];+ if (saRaw === 0) continue;+ const op = session.getEffectiveOpacity ? session.getEffectiveOpacity(l) : (l.opacity ?? 1);+ const sa = (saRaw / 255) * op;+ const inv = 1 - sa;+ accR = rgba[off] * sa + accR * inv;+ accG = rgba[off + 1] * sa + accG * inv;+ accB = rgba[off + 2] * sa + accB * inv;+ accA = sa + accA * inv;+ }++ if (accA <= 1e-6) {+ out[0] = 0;+ out[1] = 0;+ out[2] = 0;+ out[3] = 0;+ } else {+ out[0] = clamp255(Math.round(accR / accA));+ out[1] = clamp255(Math.round(accG / accA));+ out[2] = clamp255(Math.round(accB / accA));+ out[3] = clamp255(Math.round(accA * 255));+ }+}++function applySmudgeDab(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ cx: number,+ cy: number,+ radius: number,+ strength: number,+ hardness: number,+ primaryColor: string,+ fingerPainting: boolean+): DirtyRect | null {+ const docW = session.dimensions.width;+ const docH = session.dimensions.height;+ const rCeil = Math.max(1, Math.ceil(radius));+ const dim = rCeil * 2 + 1;+ const ix0 = Math.round(cx) - rCeil;+ const iy0 = Math.round(cy) - rCeil;++ const rx0 = Math.max(0, ix0);+ const ry0 = Math.max(0, iy0);+ const rx1 = Math.min(docW, ix0 + dim);+ const ry1 = Math.min(docH, iy0 + dim);+ const rw = rx1 - rx0;+ const rh = ry1 - ry0;+ if (rw <= 0 || rh <= 0) return null;++ const roi = grid.readImageData(session.layerId, rx0, ry0, rw, rh);+ const data = roi.data;++ // Initialize pickup buffer on first dab of stroke+ if (!session.smudgeBuf || session.smudgeDim !== dim) {+ const buf = new Float32Array(dim * dim * 4);+ const [pr, pg, pb] = parseHexRgb(primaryColor);++ for (let dy = 0; dy < dim; dy++) {+ const gy = iy0 + dy;+ const inY = gy >= ry0 && gy < ry1;+ for (let dx = 0; dx < dim; dx++) {+ const gx = ix0 + dx;+ const bIdx = (dy * dim + dx) * 4;+ if (fingerPainting) {+ buf[bIdx] = pr;+ buf[bIdx + 1] = pg;+ buf[bIdx + 2] = pb;+ buf[bIdx + 3] = 255;+ } else if (inY && gx >= rx0 && gx < rx1) {+ const rIdx = ((gy - ry0) * rw + (gx - rx0)) * 4;+ const a = data[rIdx + 3] / 255;+ buf[bIdx] = data[rIdx] * a;+ buf[bIdx + 1] = data[rIdx + 1] * a;+ buf[bIdx + 2] = data[rIdx + 2] * a;+ buf[bIdx + 3] = data[rIdx + 3];+ }+ }+ }+ session.smudgeBuf = buf;+ session.smudgeDim = dim;+ if (!fingerPainting) {+ return null; // Pickup only on initial touch+ }+ }++ snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);++ const buf = session.smudgeBuf;+ const selMask = session.selectionMask;+ const invR = 1 / Math.max(1, radius);+ const alphaLock = session.alphaLock;+ const str = clamp01(strength);+ let touched = false;++ for (let py = ry0; py < ry1; py++) {+ const by = py - iy0;+ const distY = py + 0.5 - cy;+ const selRow = py * docW;+ const roiRow = (py - ry0) * rw;++ for (let px = rx0; px < rx1; px++) {+ const bx = px - ix0;+ const distX = px + 0.5 - cx;+ const dNorm = Math.hypot(distX, distY) * invR;+ if (dNorm >= 1) continue;++ let w = computeBrushFalloff(dNorm, hardness) * str;+ if (selMask) {+ const m = selMask[selRow + px];+ if (m === 0) continue;+ w *= m / 255;+ }+ if (w <= 1e-4) continue;++ const rIdx = (roiRow + (px - rx0)) * 4;+ const bIdx = (by * dim + bx) * 4;++ const dstA = data[rIdx + 3];+ if (alphaLock && dstA === 0) continue;++ const dstANorm = dstA / 255;+ const dstPR = data[rIdx] * dstANorm;+ const dstPG = data[rIdx + 1] * dstANorm;+ const dstPB = data[rIdx + 2] * dstANorm;++ const srcPR = buf[bIdx];+ const srcPG = buf[bIdx + 1];+ const srcPB = buf[bIdx + 2];+ const srcA = buf[bIdx + 3];++ const invW = 1 - w;+ const outPR = dstPR * invW + srcPR * w;+ const outPG = dstPG * invW + srcPG * w;+ const outPB = dstPB * invW + srcPB * w;+ const outA = alphaLock ? dstA : dstA * invW + srcA * w;++ if (outA <= 0.5) {+ data[rIdx] = 0;+ data[rIdx + 1] = 0;+ data[rIdx + 2] = 0;+ data[rIdx + 3] = 0;+ } else {+ const invOutA = 255 / outA;+ data[rIdx] = clamp255(Math.round(outPR * invOutA));+ data[rIdx + 1] = clamp255(Math.round(outPG * invOutA));+ data[rIdx + 2] = clamp255(Math.round(outPB * invOutA));+ data[rIdx + 3] = clamp255(Math.round(outA));+ }++ // Reload pickup buffer from blended canvas pixel (prevents rapid fadeout while picking up new pigment)+ const pickupRate = 1 - str * 0.88;+ const invPickup = 1 - pickupRate;+ buf[bIdx] = srcPR * invPickup + outPR * pickupRate;+ buf[bIdx + 1] = srcPG * invPickup + outPG * pickupRate;+ buf[bIdx + 2] = srcPB * invPickup + outPB * pickupRate;+ buf[bIdx + 3] = srcA * invPickup + outA * pickupRate;+ touched = true;+ }+ }++ if (!touched) return null;+ grid.writeImageData(session.layerId, roi, rx0, ry0, session.targetFormat, true);+ return { x: rx0, y: ry0, width: rw, height: rh };+}++function applyBlurDab(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ cx: number,+ cy: number,+ radius: number,+ strength: number,+ hardness: number+): DirtyRect | null {+ const docW = session.dimensions.width;+ const docH = session.dimensions.height;+ const blurK = Math.max(1, Math.min(6, Math.round(1 + strength * 4)));+ const rCeil = Math.max(1, Math.ceil(radius));++ const rx0 = Math.max(0, Math.floor(cx - rCeil));+ const ry0 = Math.max(0, Math.floor(cy - rCeil));+ const rx1 = Math.min(docW, Math.ceil(cx + rCeil));+ const ry1 = Math.min(docH, Math.ceil(cy + rCeil));+ const rw = rx1 - rx0;+ const rh = ry1 - ry0;+ if (rw <= 0 || rh <= 0) return null;++ // Read padded source ROI for border-artifact-free convolution+ const px0 = Math.max(0, rx0 - blurK);+ const py0 = Math.max(0, ry0 - blurK);+ const px1 = Math.min(docW, rx1 + blurK);+ const py1 = Math.min(docH, ry1 + blurK);+ const pw = px1 - px0;+ const ph = py1 - py0;++ const srcRoi = grid.readImageData(session.layerId, px0, py0, pw, ph);+ const srcData = srcRoi.data;++ // Convert to premultiplied Float32 for fringe-free separable box blur+ const premul = new Float32Array(pw * ph * 4);+ const horiz = new Float32Array(pw * ph * 4);+ for (let i = 0; i < pw * ph; i++) {+ const o = i * 4;+ const a = srcData[o + 3] / 255;+ premul[o] = srcData[o] * a;+ premul[o + 1] = srcData[o + 1] * a;+ premul[o + 2] = srcData[o + 2] * a;+ premul[o + 3] = srcData[o + 3];+ }++ const kSize = blurK * 2 + 1;+ const invK = 1 / kSize;++ // Horizontal pass+ for (let y = 0; y < ph; y++) {+ const rowBase = y * pw;+ let sr = 0;+ let sg = 0;+ let sb = 0;+ let sa = 0;+ for (let k = -blurK; k <= blurK; k++) {+ const sx = k < 0 ? 0 : k >= pw ? pw - 1 : k;+ const o = (rowBase + sx) * 4;+ sr += premul[o];+ sg += premul[o + 1];+ sb += premul[o + 2];+ sa += premul[o + 3];+ }+ for (let x = 0; x < pw; x++) {+ const o = (rowBase + x) * 4;+ horiz[o] = sr * invK;+ horiz[o + 1] = sg * invK;+ horiz[o + 2] = sb * invK;+ horiz[o + 3] = sa * invK;++ const remX = x - blurK < 0 ? 0 : x - blurK;+ const addX = x + blurK + 1 >= pw ? pw - 1 : x + blurK + 1;+ const ro = (rowBase + remX) * 4;+ const ao = (rowBase + addX) * 4;+ sr += premul[ao] - premul[ro];+ sg += premul[ao + 1] - premul[ro + 1];+ sb += premul[ao + 2] - premul[ro + 2];+ sa += premul[ao + 3] - premul[ro + 3];+ }+ }++ // Vertical pass only over inner destination ROI+ const outRoi = grid.readImageData(session.layerId, rx0, ry0, rw, rh);+ const outData = outRoi.data;+ const selMask = session.selectionMask;+ const invR = 1 / Math.max(1, radius);+ const alphaLock = session.alphaLock;+ const blendStr = clamp01(strength);+ let touched = false;++ snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);++ for (let lx = 0; lx < rw; lx++) {+ const sx = rx0 - px0 + lx;+ const gx = rx0 + lx;+ const distX = gx + 0.5 - cx;++ const startY = ry0 - py0;+ let sr = 0;+ let sg = 0;+ let sb = 0;+ let sa = 0;+ for (let k = -blurK; k <= blurK; k++) {+ const sy = Math.max(0, Math.min(ph - 1, startY + k));+ const o = (sy * pw + sx) * 4;+ sr += horiz[o];+ sg += horiz[o + 1];+ sb += horiz[o + 2];+ sa += horiz[o + 3];+ }++ for (let ly = 0; ly < rh; ly++) {+ const gy = ry0 + ly;+ const curY = startY + ly;+ const br = sr * invK;+ const bg = sg * invK;+ const bb = sb * invK;+ const ba = sa * invK;++ const remY = Math.max(0, curY - blurK);+ const addY = Math.min(ph - 1, curY + blurK + 1);+ const ro = (remY * pw + sx) * 4;+ const ao = (addY * pw + sx) * 4;+ sr += horiz[ao] - horiz[ro];+ sg += horiz[ao + 1] - horiz[ro + 1];+ sb += horiz[ao + 2] - horiz[ro + 2];+ sa += horiz[ao + 3] - horiz[ro + 3];++ const distY = gy + 0.5 - cy;+ const dNorm = Math.hypot(distX, distY) * invR;+ if (dNorm >= 1) continue;++ let w = computeBrushFalloff(dNorm, hardness) * blendStr;+ if (selMask) {+ const m = selMask[gy * docW + gx];+ if (m === 0) continue;+ w *= m / 255;+ }+ if (w <= 1e-4) continue;++ const oIdx = (ly * rw + lx) * 4;+ const dstA = outData[oIdx + 3];+ if (alphaLock && dstA === 0) continue;++ const dstANorm = dstA / 255;+ const invW = 1 - w;+ const finalPR = outData[oIdx] * dstANorm * invW + br * w;+ const finalPG = outData[oIdx + 1] * dstANorm * invW + bg * w;+ const finalPB = outData[oIdx + 2] * dstANorm * invW + bb * w;+ const finalA = alphaLock ? dstA : dstA * invW + ba * w;++ if (finalA <= 0.5) {+ outData[oIdx] = 0;+ outData[oIdx + 1] = 0;+ outData[oIdx + 2] = 0;+ outData[oIdx + 3] = 0;+ } else {+ const invA = 255 / finalA;+ outData[oIdx] = clamp255(Math.round(finalPR * invA));+ outData[oIdx + 1] = clamp255(Math.round(finalPG * invA));+ outData[oIdx + 2] = clamp255(Math.round(finalPB * invA));+ outData[oIdx + 3] = clamp255(Math.round(finalA));+ }+ touched = true;+ }+ }++ if (!touched) return null;+ grid.writeImageData(session.layerId, outRoi, rx0, ry0, session.targetFormat, true);+ return { x: rx0, y: ry0, width: rw, height: rh };+}++function tonalRangeWeight(lum: number, range: RetouchTonalRange): number {+ const l = clamp01(lum);+ if (range === 'shadows') {+ const inv = 1 - l;+ return inv * inv;+ }+ if (range === 'highlights') {+ return l * l;+ }+ // Midtones bell curve peaking at 0.5+ return 4 * l * (1 - l);+}++function applyDodgeBurnDab(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ mode: 'dodge' | 'burn',+ cx: number,+ cy: number,+ radius: number,+ strength: number,+ hardness: number,+ tonalRange: RetouchTonalRange,+ protectTones: boolean+): DirtyRect | null {+ const docW = session.dimensions.width;+ const docH = session.dimensions.height;+ const rCeil = Math.max(1, Math.ceil(radius));++ const rx0 = Math.max(0, Math.floor(cx - rCeil));+ const ry0 = Math.max(0, Math.floor(cy - rCeil));+ const rx1 = Math.min(docW, Math.ceil(cx + rCeil));+ const ry1 = Math.min(docH, Math.ceil(cy + rCeil));+ const rw = rx1 - rx0;+ const rh = ry1 - ry0;+ if (rw <= 0 || rh <= 0) return null;++ const roi = grid.readImageData(session.layerId, rx0, ry0, rw, rh);+ const data = roi.data;+ const selMask = session.selectionMask;+ const invR = 1 / Math.max(1, radius);+ const exposure = clamp01(strength) * 0.32;+ let touched = false;++ snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);++ for (let ly = 0; ly < rh; ly++) {+ const gy = ry0 + ly;+ const distY = gy + 0.5 - cy;+ const selRow = gy * docW;+ const roiRow = ly * rw;++ for (let lx = 0; lx < rw; lx++) {+ const gx = rx0 + lx;+ const distX = gx + 0.5 - cx;+ const dNorm = Math.hypot(distX, distY) * invR;+ if (dNorm >= 1) continue;++ const idx = (roiRow + lx) * 4;+ if (data[idx + 3] === 0) continue;++ let w = computeBrushFalloff(dNorm, hardness);+ if (selMask) {+ const m = selMask[selRow + gx];+ if (m === 0) continue;+ w *= m / 255;+ }+ if (w <= 1e-4) continue;++ const r = data[idx] / 255;+ const g = data[idx + 1] / 255;+ const b = data[idx + 2] / 255;+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;+ const tw = tonalRangeWeight(lum, tonalRange);+ const amt = Math.min(0.85, exposure * w * (0.25 + 0.75 * tw));+ if (amt <= 1e-5) continue;++ let nr: number;+ let ng: number;+ let nb: number;++ if (mode === 'dodge') {+ if (protectTones) {+ // Lift luminance smoothly while scaling RGB proportionally to preserve hue+ const targetLum = Math.min(1, lum + (1 - lum) * amt);+ if (lum > 1e-4) {+ const scale = targetLum / lum;+ nr = Math.min(1, r * scale);+ ng = Math.min(1, g * scale);+ nb = Math.min(1, b * scale);+ } else {+ nr = targetLum;+ ng = targetLum;+ nb = targetLum;+ }+ } else {+ const inv = 1 / Math.max(0.15, 1 - amt);+ nr = Math.min(1, r * inv);+ ng = Math.min(1, g * inv);+ nb = Math.min(1, b * inv);+ }+ } else {+ if (protectTones) {+ const scale = Math.max(0, 1 - amt);+ nr = r * scale;+ ng = g * scale;+ nb = b * scale;+ } else {+ const gamma = 1 + amt * 2.2;+ nr = Math.pow(r, gamma);+ ng = Math.pow(g, gamma);+ nb = Math.pow(b, gamma);+ }+ }++ data[idx] = clamp255(Math.round(nr * 255));+ data[idx + 1] = clamp255(Math.round(ng * 255));+ data[idx + 2] = clamp255(Math.round(nb * 255));+ touched = true;+ }+ }++ if (!touched) return null;+ grid.writeImageData(session.layerId, roi, rx0, ry0, session.targetFormat, true);+ return { x: rx0, y: ry0, width: rw, height: rh };+}++function applyCloneStampDab(+ grid: SparseTileGrid,+ session: RetouchStrokeSession,+ cx: number,+ cy: number,+ radius: number,+ strength: number,+ hardness: number,+ sampleMode: CloneSampleMode+): DirtyRect | null {+ if (!session.cloneOffset) return null;++ const docW = session.dimensions.width;+ const docH = session.dimensions.height;+ const rCeil = Math.max(1, Math.ceil(radius));++ const rx0 = Math.max(0, Math.floor(cx - rCeil));+ const ry0 = Math.max(0, Math.floor(cy - rCeil));+ const rx1 = Math.min(docW, Math.ceil(cx + rCeil));+ const ry1 = Math.min(docH, Math.ceil(cy + rCeil));+ const rw = rx1 - rx0;+ const rh = ry1 - ry0;+ if (rw <= 0 || rh <= 0) return null;++ snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);++ const roi = grid.readImageData(session.layerId, rx0, ry0, rw, rh);+ const data = roi.data;+ const selMask = session.selectionMask;+ const invR = 1 / Math.max(1, radius);+ const alphaLock = session.alphaLock;+ const opacity = clamp01(strength);+ const offX = Math.round(session.cloneOffset.x);+ const offY = Math.round(session.cloneOffset.y);+ const sampleOut: [number, number, number, number] = [0, 0, 0, 0];+ let touched = false;++ for (let ly = 0; ly < rh; ly++) {+ const gy = ry0 + ly;+ const distY = gy + 0.5 - cy;+ const selRow = gy * docW;+ const roiRow = ly * rw;++ for (let lx = 0; lx < rw; lx++) {+ const gx = rx0 + lx;+ const distX = gx + 0.5 - cx;+ const dNorm = Math.hypot(distX, distY) * invR;+ if (dNorm >= 1) continue;++ let w = computeBrushFalloff(dNorm, hardness) * opacity;+ if (selMask) {+ const m = selMask[selRow + gx];+ if (m === 0) continue;+ w *= m / 255;+ }+ if (w <= 1e-4) continue;++ samplePreStrokePixel(grid, session, gx + offX, gy + offY, sampleMode, sampleOut);+ const srcA = sampleOut[3];+ if (srcA === 0) continue;++ const idx = (roiRow + lx) * 4;+ const dstA = data[idx + 3];+ if (alphaLock && dstA === 0) continue;++ const effSrcA = (srcA / 255) * w;+ if (alphaLock) {+ const inv = 1 - effSrcA;+ data[idx] = clamp255(Math.round(data[idx] * inv + sampleOut[0] * effSrcA));+ data[idx + 1] = clamp255(Math.round(data[idx + 1] * inv + sampleOut[1] * effSrcA));+ data[idx + 2] = clamp255(Math.round(data[idx + 2] * inv + sampleOut[2] * effSrcA));+ } else {+ const dstANorm = dstA / 255;+ const outA = effSrcA + dstANorm * (1 - effSrcA);+ if (outA <= 1e-6) continue;+ const invOutA = 1 / outA;+ const r = (sampleOut[0] * effSrcA + data[idx] * dstANorm * (1 - effSrcA)) * invOutA;+ const g = (sampleOut[1] * effSrcA + data[idx + 1] * dstANorm * (1 - effSrcA)) * invOutA;+ const b = (sampleOut[2] * effSrcA + data[idx + 2] * dstANorm * (1 - effSrcA)) * invOutA;+ data[idx] = clamp255(Math.round(r));+ data[idx + 1] = clamp255(Math.round(g));+ data[idx + 2] = clamp255(Math.round(b));+ data[idx + 3] = clamp255(Math.round(outA * 255));+ }+ touched = true;+ }+ }++ if (!touched) return null;+ grid.writeImageData(session.layerId, roi, rx0, ry0, session.targetFormat, true);+ return { x: rx0, y: ry0, width: rw, height: rh };+}++/**+ * Stamps spaced retouch dabs along the segment from `session.lastDabPos` to `targetPt`.+ */+export function applyRetouchStrokeSegment(params: {+ grid: SparseTileGrid;+ session: RetouchStrokeSession;+ pt: Point2D;+ pressure: number;+ settings: RetouchSettings;+ primaryColor: string;+}): DirtyRect | null {+ const { grid, session, pt, pressure, settings, primaryColor } = params;+ const effPressure = settings.usePressure ? Math.max(0.1, Math.min(1, pressure || 1)) : 1;+ const radius = Math.max(1, (settings.size * (0.4 + 0.6 * effPressure)) * 0.5);+ const strength = clamp01((settings.strength / 100) * (0.35 + 0.65 * effPressure));+ const hardness = clamp01(settings.hardness / 100);+ const stepPx = Math.max(1, radius * Math.max(0.05, Math.min(0.5, settings.spacing || 0.15)) * 2);++ const runDab = (dx: number, dy: number): DirtyRect | null => {+ switch (session.mode) {+ case 'smudge':+ return applySmudgeDab(+ grid,+ session,+ dx,+ dy,+ radius,+ strength,+ hardness,+ primaryColor,+ settings.smudgeFingerPainting+ );+ case 'blur':+ return applyBlurDab(grid, session, dx, dy, radius, strength, hardness);+ case 'dodge':+ case 'burn':+ return applyDodgeBurnDab(+ grid,+ session,+ session.mode,+ dx,+ dy,+ radius,+ strength,+ hardness,+ settings.tonalRange,+ settings.protectTones+ );+ case 'clone-stamp':+ return applyCloneStampDab(+ grid,+ session,+ dx,+ dy,+ radius,+ strength,+ hardness,+ settings.cloneSampleMode+ );+ }+ };++ let segDirty: DirtyRect | null = null;++ if (!session.lastDabPos) {+ session.lastDabPos = { x: pt.x, y: pt.y };+ session.remainderDist = 0;+ const d = runDab(pt.x, pt.y);+ if (d) {+ segDirty = mergeDirty(segDirty, d);+ session.dirtyRect = mergeDirty(session.dirtyRect, d);+ }+ return segDirty;+ }++ const prev = session.lastDabPos;+ const vx = pt.x - prev.x;+ const vy = pt.y - prev.y;+ const dist = Math.hypot(vx, vy);+ if (dist < 1e-4) return null;++ const ux = vx / dist;+ const uy = vy / dist;+ let traveled = stepPx - session.remainderDist;++ // Guard maximum dabs per pointermove to prevent stalls on sudden jumps+ let dabCount = 0;+ const MAX_DABS_PER_MOVE = 64;+ while (traveled <= dist && dabCount < MAX_DABS_PER_MOVE) {+ const dx = prev.x + ux * traveled;+ const dy = prev.y + uy * traveled;+ const d = runDab(dx, dy);+ if (d) {+ segDirty = mergeDirty(segDirty, d);+ session.dirtyRect = mergeDirty(session.dirtyRect, d);+ }+ traveled += stepPx;+ dabCount++;+ }++ session.remainderDist = Math.max(0, dist - (traveled - stepPx));+ session.lastDabPos = { x: pt.x, y: pt.y };++ return segDirty;+}diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.tsindex 120400b..33370a7 100644--- a/src/utils/selectionUtils.ts+++ b/src/utils/selectionUtils.ts@@ -1,9 +1,15 @@import { CanvasDimensions, CanvasSelection, DirtyRect, LayerItem, TileDelta, WandSettings } from '../types/editor';import {+ BYTES_1BIT,+ BYTES_8BIT,+ BYTES_32BIT,SparseTileGrid,TILE_SIZE,TileFormat,TileSnapshotEntry,+ getTileKey,+ packRGBATo1Bit,+ packRGBATo8Bit,pixelToTileCoord,releaseTemporaryCanvas,} from './tileEngine';@@ -1188,22 +1194,41 @@ export function clearSelectionInTileGrid(params: {}}}- } else if (maskCanvas && mCtx && selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {- if (maskCanvas.width !== cw) maskCanvas.width = cw;- if (maskCanvas.height !== ch) maskCanvas.height = ch;- mCtx.clearRect(0, 0, cw, ch);- mCtx.save();- mCtx.translate(-cx, -cy);- mCtx.fillStyle = isBackground ? '#ffffff' : '#000000';- mCtx.beginPath();- mCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);- for (let i = 1; i < selection.polygon.length; i++) {- mCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {+ if (maskCanvas && mCtx) {+ if (maskCanvas.width !== cw) maskCanvas.width = cw;+ if (maskCanvas.height !== ch) maskCanvas.height = ch;+ mCtx.clearRect(0, 0, cw, ch);+ mCtx.save();+ mCtx.translate(-cx, -cy);+ mCtx.fillStyle = isBackground ? '#ffffff' : '#000000';+ mCtx.beginPath();+ mCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);+ for (let i = 1; i < selection.polygon.length; i++) {+ mCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);+ }+ mCtx.closePath();+ mCtx.fill();+ mCtx.restore();+ chunkAlpha = mCtx.getImageData(0, 0, cw, ch).data;+ } else {+ chunkAlpha = new Uint8ClampedArray(cw * ch * 4);+ const rgb = isBackground ? 255 : 0;+ const poly = selection.polygon;+ for (let ly = 0; ly < ch; ly++) {+ const gy = cy + ly + 0.5;+ const dRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ if (isPointInPolygon(cx + lx + 0.5, gy, poly)) {+ const off = dRow + lx * 4;+ chunkAlpha[off] = rgb;+ chunkAlpha[off + 1] = rgb;+ chunkAlpha[off + 2] = rgb;+ chunkAlpha[off + 3] = 255;+ }+ }+ }}- mCtx.closePath();- mCtx.fill();- mCtx.restore();- chunkAlpha = mCtx.getImageData(0, 0, cw, ch).data;} else {continue;}@@ -1487,3 +1512,570 @@ export function commitFloatingSelectionToTileGrid(params: {grid.notifyChange(true);return { dirtyRect, tileDeltas };}++export interface SelectionTileSnapshot {+ format: TileFormat;+ tiles: Array<{ tileX: number; tileY: number; format: TileFormat; data: Uint8Array }>;+ bounds: DirtyRect;+}++function encodeRgbaToTileData(rgba: Uint8ClampedArray, format: TileFormat): Uint8Array {+ if (format === 'monochrome-1bit') {+ const out = new Uint8Array(BYTES_1BIT);+ packRGBATo1Bit(rgba, out);+ return out;+ }+ if (format === 'grayscale-8bit') {+ const out = new Uint8Array(BYTES_8BIT);+ packRGBATo8Bit(rgba, out);+ return out;+ }+ const out = new Uint8Array(BYTES_32BIT);+ out.set(rgba);+ return out;+}++function buildTileLassoAlpha(+ polygon: Array<{ x: number; y: number }>,+ tileDocX: number,+ tileDocY: number,+ outAlpha: Uint8Array,+ scratchCanvas: HTMLCanvasElement | null,+ scratchCtx: CanvasRenderingContext2D | null+): void {+ outAlpha.fill(0);+ if (scratchCanvas && scratchCtx) {+ scratchCtx.clearRect(0, 0, TILE_SIZE, TILE_SIZE);+ scratchCtx.save();+ scratchCtx.translate(-tileDocX, -tileDocY);+ scratchCtx.fillStyle = '#ffffff';+ scratchCtx.beginPath();+ scratchCtx.moveTo(polygon[0].x, polygon[0].y);+ for (let i = 1; i < polygon.length; i++) {+ scratchCtx.lineTo(polygon[i].x, polygon[i].y);+ }+ scratchCtx.closePath();+ scratchCtx.fill();+ scratchCtx.restore();+ const img = scratchCtx.getImageData(0, 0, TILE_SIZE, TILE_SIZE).data;+ for (let i = 0; i < TILE_SIZE * TILE_SIZE; i++) {+ outAlpha[i] = img[i * 4 + 3];+ }+ return;+ }++ for (let ly = 0; ly < TILE_SIZE; ly++) {+ const gy = tileDocY + ly + 0.5;+ const row = ly * TILE_SIZE;+ for (let lx = 0; lx < TILE_SIZE; lx++) {+ if (isPointInPolygon(tileDocX + lx + 0.5, gy, polygon)) {+ outAlpha[row + lx] = 255;+ }+ }+ }+}++/**+ * Tile-native extraction of selected pixels into a sparse tile snapshot at original document coordinates.+ * Zero full-document HTMLCanvasElement allocation. Returns null if the selected region is empty.+ */+export function extractSelectionTileSnapshot(params: {+ grid: SparseTileGrid;+ layerId: string;+ dimensions: CanvasDimensions;+ selection: CanvasSelection;+ targetFormat?: TileFormat;+}): SelectionTileSnapshot | null {+ const { grid, layerId, dimensions, selection } = params;+ const format = params.targetFormat ?? grid.getLayerFormat(layerId);++ if (selection.floating) {+ const { canvas, x, y } = selection.floating;+ const fCtx = canvas.getContext('2d', { willReadFrequently: true });+ if (!fCtx) return null;++ const dx = Math.round(x);+ const dy = Math.round(y);+ const clipX0 = Math.max(0, dx);+ const clipY0 = Math.max(0, dy);+ const clipX1 = Math.min(dimensions.width, dx + canvas.width);+ const clipY1 = Math.min(dimensions.height, dy + canvas.height);+ if (clipX1 <= clipX0 || clipY1 <= clipY0) return null;++ const minTx = pixelToTileCoord(clipX0, 0);+ const minTy = pixelToTileCoord(clipY0, 0);+ const maxTx = pixelToTileCoord(clipX1 - 1, 0);+ const maxTy = pixelToTileCoord(clipY1 - 1, 0);++ const tiles: SelectionTileSnapshot['tiles'] = [];+ const tileRgba = new Uint8ClampedArray(BYTES_32BIT);++ for (let ty = minTy; ty <= maxTy; ty++) {+ const tileDocY = ty * TILE_SIZE;+ const y0 = Math.max(clipY0, tileDocY);+ const y1 = Math.min(clipY1, tileDocY + TILE_SIZE);+ for (let tx = minTx; tx <= maxTx; tx++) {+ const tileDocX = tx * TILE_SIZE;+ const x0 = Math.max(clipX0, tileDocX);+ const x1 = Math.min(clipX1, tileDocX + TILE_SIZE);+ const cw = x1 - x0;+ const ch = y1 - y0;+ if (cw <= 0 || ch <= 0) continue;++ const img = fCtx.getImageData(x0 - dx, y0 - dy, cw, ch).data;+ tileRgba.fill(0);+ let hasOpaque = false;+ const dstStartX = x0 - tileDocX;+ const dstStartY = y0 - tileDocY;++ for (let row = 0; row < ch; row++) {+ const srcRow = row * cw * 4;+ const dstRow = ((dstStartY + row) * TILE_SIZE + dstStartX) * 4;+ for (let col = 0; col < cw; col++) {+ const sOff = srcRow + col * 4;+ const a = img[sOff + 3];+ if (a > 0) {+ hasOpaque = true;+ const dOff = dstRow + col * 4;+ tileRgba[dOff] = img[sOff];+ tileRgba[dOff + 1] = img[sOff + 1];+ tileRgba[dOff + 2] = img[sOff + 2];+ tileRgba[dOff + 3] = a;+ }+ }+ }++ if (hasOpaque) {+ tiles.push({+ tileX: tx,+ tileY: ty,+ format,+ data: encodeRgbaToTileData(tileRgba, format),+ });+ }+ }+ }++ if (tiles.length === 0) return null;+ return {+ format,+ tiles,+ bounds: { x: clipX0, y: clipY0, width: clipX1 - clipX0, height: clipY1 - clipY0 },+ };+ }++ const raw = selection.bounds;+ if (!raw || raw.width <= 0 || raw.height <= 0) return null;++ const bx = Math.max(0, Math.floor(raw.x));+ const by = Math.max(0, Math.floor(raw.y));+ const bx1 = Math.min(dimensions.width, Math.ceil(raw.x + raw.width));+ const by1 = Math.min(dimensions.height, Math.ceil(raw.y + raw.height));+ if (bx1 <= bx || by1 <= by) return null;++ const intersecting = grid.getTilesInBounds(layerId, bx, by, bx1 - 1, by1 - 1, 0);+ if (intersecting.length === 0) return null;++ const hasMask = Boolean(selection.mask && selection.maskWidth && selection.maskHeight);+ const hasLasso =+ !hasMask && selection.type === 'lasso' && Boolean(selection.polygon && selection.polygon.length >= 3);++ let scratchCanvas: HTMLCanvasElement | null = null;+ let scratchCtx: CanvasRenderingContext2D | null = null;+ const lassoAlpha = hasLasso ? new Uint8Array(TILE_SIZE * TILE_SIZE) : null;+ if (hasLasso && typeof document !== 'undefined') {+ scratchCanvas = document.createElement('canvas');+ scratchCanvas.width = TILE_SIZE;+ scratchCanvas.height = TILE_SIZE;+ scratchCtx = scratchCanvas.getContext('2d', { willReadFrequently: true });+ }++ const tiles: SelectionTileSnapshot['tiles'] = [];+ const outRgba = new Uint8ClampedArray(BYTES_32BIT);++ try {+ for (const tile of intersecting) {+ if (!tile.data) continue;+ const tileDocX = tile.tileX * TILE_SIZE;+ const tileDocY = tile.tileY * TILE_SIZE;+ const x0 = Math.max(bx, tileDocX);+ const y0 = Math.max(by, tileDocY);+ const x1 = Math.min(bx1, tileDocX + TILE_SIZE);+ const y1 = Math.min(by1, tileDocY + TILE_SIZE);+ if (x1 <= x0 || y1 <= y0) continue;++ const srcRgba = grid.getTileAsRGBA(tile);+ outRgba.fill(0);+ let hasOpaque = false;++ if (hasLasso && lassoAlpha && selection.polygon) {+ buildTileLassoAlpha(selection.polygon, tileDocX, tileDocY, lassoAlpha, scratchCanvas, scratchCtx);+ }++ const lx0 = x0 - tileDocX;+ const ly0 = y0 - tileDocY;+ const lx1 = x1 - tileDocX;+ const ly1 = y1 - tileDocY;++ if (hasMask && selection.mask && selection.maskWidth && selection.maskHeight) {+ const mw = selection.maskWidth;+ const mh = selection.maskHeight;+ for (let ly = ly0; ly < ly1; ly++) {+ const gy = tileDocY + ly;+ if (gy < 0 || gy >= mh) continue;+ const mRow = gy * mw;+ const tRow = ly * TILE_SIZE;+ for (let lx = lx0; lx < lx1; lx++) {+ const gx = tileDocX + lx;+ const ma = gx >= 0 && gx < mw ? selection.mask[mRow + gx] : 0;+ if (ma === 0) continue;+ const off = (tRow + lx) * 4;+ const sa = srcRgba[off + 3];+ if (sa === 0) continue;+ const ea = ma === 255 ? sa : Math.round((sa * ma) / 255);+ if (ea === 0) continue;+ hasOpaque = true;+ outRgba[off] = srcRgba[off];+ outRgba[off + 1] = srcRgba[off + 1];+ outRgba[off + 2] = srcRgba[off + 2];+ outRgba[off + 3] = ea;+ }+ }+ } else if (hasLasso && lassoAlpha) {+ for (let ly = ly0; ly < ly1; ly++) {+ const tRow = ly * TILE_SIZE;+ for (let lx = lx0; lx < lx1; lx++) {+ const ma = lassoAlpha[tRow + lx];+ if (ma === 0) continue;+ const off = (tRow + lx) * 4;+ const sa = srcRgba[off + 3];+ if (sa === 0) continue;+ const ea = ma === 255 ? sa : Math.round((sa * ma) / 255);+ if (ea === 0) continue;+ hasOpaque = true;+ outRgba[off] = srcRgba[off];+ outRgba[off + 1] = srcRgba[off + 1];+ outRgba[off + 2] = srcRgba[off + 2];+ outRgba[off + 3] = ea;+ }+ }+ } else {+ for (let ly = ly0; ly < ly1; ly++) {+ const tRow = ly * TILE_SIZE;+ for (let lx = lx0; lx < lx1; lx++) {+ const off = (tRow + lx) * 4;+ const sa = srcRgba[off + 3];+ if (sa === 0) continue;+ hasOpaque = true;+ outRgba[off] = srcRgba[off];+ outRgba[off + 1] = srcRgba[off + 1];+ outRgba[off + 2] = srcRgba[off + 2];+ outRgba[off + 3] = sa;+ }+ }+ }++ if (hasOpaque) {+ tiles.push({+ tileX: tile.tileX,+ tileY: tile.tileY,+ format,+ data: encodeRgbaToTileData(outRgba, format),+ });+ }+ }+ } finally {+ if (scratchCanvas) releaseTemporaryCanvas(scratchCanvas);+ }++ if (tiles.length === 0) return null;+ return {+ format,+ tiles,+ bounds: { x: bx, y: by, width: bx1 - bx, height: by1 - by },+ };+}++/**+ * Tile-native Delete Outside Selection: erases (or fills white on background) every pixel+ * on `layerId` outside `selection`, leaving only the selected pixels intact.+ */+export function clearOutsideSelectionInTileGrid(params: {+ grid: SparseTileGrid;+ layerId: string;+ dimensions: CanvasDimensions;+ selection: CanvasSelection;+ isBackground: boolean;+ targetFormat: TileFormat;+ snapshotOut?: Map<string, TileSnapshotEntry>;+}): { dirtyRect: DirtyRect | null; tileDeltas: TileDelta[] } {+ const { grid, layerId, dimensions, selection, isBackground, targetFormat } = params;+ const fullRect: DirtyRect = { x: 0, y: 0, width: dimensions.width, height: dimensions.height };++ if (selection.floating) {+ const beforeSnapshot = params.snapshotOut ?? new Map<string, TileSnapshotEntry>();+ if (selection.floating.beforeTileSnapshot) {+ for (const [k, v] of selection.floating.beforeTileSnapshot.entries()) {+ if (!beforeSnapshot.has(k)) {+ beforeSnapshot.set(k, v);+ }+ }+ }++ const existingTiles = grid.getLayerTiles(layerId, 0);+ for (const tile of existingTiles) {+ const key = getTileKey(layerId, tile.tileX, tile.tileY, 0);+ if (!beforeSnapshot.has(key)) {+ beforeSnapshot.set(key, {+ format: tile.format,+ data: tile.data ? new Uint8Array(tile.data) : null,+ });+ }+ }++ grid.clearLayer(layerId);+ if (isBackground) {+ grid.fillLayerSolidWhite(layerId, dimensions.width, dimensions.height, targetFormat);+ }++ const { canvas, x, y } = selection.floating;+ const fCtx = canvas.getContext('2d', { willReadFrequently: true });+ const dx = Math.round(x);+ const dy = Math.round(y);+ const clipX0 = Math.max(0, dx);+ const clipY0 = Math.max(0, dy);+ const clipX1 = Math.min(dimensions.width, dx + canvas.width);+ const clipY1 = Math.min(dimensions.height, dy + canvas.height);++ if (fCtx && clipX1 > clipX0 && clipY1 > clipY0) {+ const imgData = fCtx.getImageData(clipX0 - dx, clipY0 - dy, clipX1 - clipX0, clipY1 - clipY0);+ grid.compositeStrokeToTiles({+ layerId,+ strokeData: imgData,+ destX: clipX0,+ destY: clipY0,+ format: targetFormat,+ compositeOp: 'source-over',+ opacity: 1.0,+ snapshotOut: beforeSnapshot,+ suppressNotify: true,+ });+ }++ if (!isBackground) {+ grid.pruneEmptyTiles(layerId);+ }+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId);+ grid.notifyChange(true);+ return { dirtyRect: fullRect, tileDeltas };+ }++ const raw = selection.bounds;+ if (!raw || raw.width <= 0 || raw.height <= 0) return { dirtyRect: null, tileDeltas: [] };++ const bx = Math.max(0, Math.floor(raw.x));+ const by = Math.max(0, Math.floor(raw.y));+ const bx1 = Math.min(dimensions.width, Math.ceil(raw.x + raw.width));+ const by1 = Math.min(dimensions.height, Math.ceil(raw.y + raw.height));+ if (bx1 <= bx || by1 <= by) return { dirtyRect: null, tileDeltas: [] };++ const existingTiles = grid.getLayerTiles(layerId, 0);+ if (existingTiles.length === 0) return { dirtyRect: null, tileDeltas: [] };++ const beforeSnapshot = params.snapshotOut ?? new Map<string, TileSnapshotEntry>();+ const hasMask = Boolean(selection.mask && selection.maskWidth && selection.maskHeight);+ const hasLasso =+ !hasMask && selection.type === 'lasso' && Boolean(selection.polygon && selection.polygon.length >= 3);++ let scratchCanvas: HTMLCanvasElement | null = null;+ let scratchCtx: CanvasRenderingContext2D | null = null;+ const lassoAlpha = hasLasso ? new Uint8Array(TILE_SIZE * TILE_SIZE) : null;+ if (hasLasso && typeof document !== 'undefined') {+ scratchCanvas = document.createElement('canvas');+ scratchCanvas.width = TILE_SIZE;+ scratchCanvas.height = TILE_SIZE;+ scratchCtx = scratchCanvas.getContext('2d', { willReadFrequently: true });+ }++ const outRgba = new Uint8ClampedArray(BYTES_32BIT);+ let dirtyMinX = dimensions.width;+ let dirtyMinY = dimensions.height;+ let dirtyMaxX = -1;+ let dirtyMaxY = -1;++ const markDirtyTile = (tx: number, ty: number) => {+ const tx0 = Math.max(0, tx * TILE_SIZE);+ const ty0 = Math.max(0, ty * TILE_SIZE);+ const tx1 = Math.min(dimensions.width, (tx + 1) * TILE_SIZE);+ const ty1 = Math.min(dimensions.height, (ty + 1) * TILE_SIZE);+ if (tx0 < dirtyMinX) dirtyMinX = tx0;+ if (ty0 < dirtyMinY) dirtyMinY = ty0;+ if (tx1 > dirtyMaxX) dirtyMaxX = tx1;+ if (ty1 > dirtyMaxY) dirtyMaxY = ty1;+ };++ try {+ const tileList = existingTiles.slice();+ for (const tile of tileList) {+ const tx = tile.tileX;+ const ty = tile.tileY;+ const tileDocX = tx * TILE_SIZE;+ const tileDocY = ty * TILE_SIZE;+ const key = getTileKey(layerId, tx, ty, 0);++ const intersectsBounds =+ tileDocX < bx1 && tileDocX + TILE_SIZE > bx && tileDocY < by1 && tileDocY + TILE_SIZE > by;++ if (!intersectsBounds) {+ if (!beforeSnapshot.has(key)) {+ beforeSnapshot.set(key, {+ format: tile.format,+ data: tile.data ? new Uint8Array(tile.data) : null,+ });+ }+ if (isBackground) {+ outRgba.fill(0);+ const maxLy = Math.min(TILE_SIZE, dimensions.height - tileDocY);+ const maxLx = Math.min(TILE_SIZE, dimensions.width - tileDocX);+ for (let ly = 0; ly < maxLy; ly++) {+ const row = ly * TILE_SIZE * 4;+ for (let lx = 0; lx < maxLx; lx++) {+ const off = row + lx * 4;+ outRgba[off] = 255;+ outRgba[off + 1] = 255;+ outRgba[off + 2] = 255;+ outRgba[off + 3] = 255;+ }+ }+ grid.writeImageData(+ layerId,+ { data: outRgba, width: TILE_SIZE, height: TILE_SIZE },+ tileDocX,+ tileDocY,+ targetFormat,+ true+ );+ } else {+ grid.deleteTile(layerId, tx, ty, 0);+ }+ markDirtyTile(tx, ty);+ continue;+ }++ if (+ !hasMask &&+ !hasLasso &&+ tileDocX >= bx &&+ tileDocX + TILE_SIZE <= bx1 &&+ tileDocY >= by &&+ tileDocY + TILE_SIZE <= by1+ ) {+ continue;+ }++ if (!beforeSnapshot.has(key)) {+ beforeSnapshot.set(key, {+ format: tile.format,+ data: tile.data ? new Uint8Array(tile.data) : null,+ });+ }++ const srcRgba = grid.getTileAsRGBA(tile);+ outRgba.fill(0);++ if (hasLasso && lassoAlpha && selection.polygon) {+ buildTileLassoAlpha(selection.polygon, tileDocX, tileDocY, lassoAlpha, scratchCanvas, scratchCtx);+ }++ let hasAnyPixel = false;+ const mw = selection.maskWidth ?? 0;+ const mh = selection.maskHeight ?? 0;++ for (let ly = 0; ly < TILE_SIZE; ly++) {+ const gy = tileDocY + ly;+ const inDocY = gy >= 0 && gy < dimensions.height;+ const tRow = ly * TILE_SIZE;+ for (let lx = 0; lx < TILE_SIZE; lx++) {+ const gx = tileDocX + lx;+ const off = (tRow + lx) * 4;+ const inDoc = inDocY && gx >= 0 && gx < dimensions.width;+ if (!inDoc) continue;++ let keepAlpha = 0;+ if (gx >= bx && gx < bx1 && gy >= by && gy < by1) {+ if (hasMask && selection.mask) {+ keepAlpha = gy < mh && gx < mw ? selection.mask[gy * mw + gx] : 0;+ } else if (hasLasso && lassoAlpha) {+ keepAlpha = lassoAlpha[tRow + lx];+ } else {+ keepAlpha = 255;+ }+ }++ if (isBackground) {+ hasAnyPixel = true;+ if (keepAlpha === 255) {+ outRgba[off] = srcRgba[off];+ outRgba[off + 1] = srcRgba[off + 1];+ outRgba[off + 2] = srcRgba[off + 2];+ outRgba[off + 3] = srcRgba[off + 3];+ } else if (keepAlpha === 0) {+ outRgba[off] = 255;+ outRgba[off + 1] = 255;+ outRgba[off + 2] = 255;+ outRgba[off + 3] = 255;+ } else {+ const k = keepAlpha / 255;+ const inv = 1 - k;+ outRgba[off] = Math.round(srcRgba[off] * k + 255 * inv);+ outRgba[off + 1] = Math.round(srcRgba[off + 1] * k + 255 * inv);+ outRgba[off + 2] = Math.round(srcRgba[off + 2] * k + 255 * inv);+ outRgba[off + 3] = 255;+ }+ } else {+ if (keepAlpha === 0) continue;+ const sa = srcRgba[off + 3];+ if (sa === 0) continue;+ const ea = keepAlpha === 255 ? sa : Math.round((sa * keepAlpha) / 255);+ if (ea === 0) continue;+ hasAnyPixel = true;+ outRgba[off] = srcRgba[off];+ outRgba[off + 1] = srcRgba[off + 1];+ outRgba[off + 2] = srcRgba[off + 2];+ outRgba[off + 3] = ea;+ }+ }+ }++ if (hasAnyPixel) {+ grid.writeImageData(+ layerId,+ { data: outRgba, width: TILE_SIZE, height: TILE_SIZE },+ tileDocX,+ tileDocY,+ targetFormat,+ true+ );+ } else {+ grid.deleteTile(layerId, tx, ty, 0);+ }+ markDirtyTile(tx, ty);+ }+ } finally {+ if (scratchCanvas) releaseTemporaryCanvas(scratchCanvas);+ }++ if (!isBackground) {+ grid.pruneEmptyTiles(layerId);+ }++ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId);+ grid.notifyChange(true);++ const dirtyRect =+ dirtyMaxX > dirtyMinX && dirtyMaxY > dirtyMinY+ ? { x: dirtyMinX, y: dirtyMinY, width: dirtyMaxX - dirtyMinX, height: dirtyMaxY - dirtyMinY }+ : null;++ return { dirtyRect, tileDeltas };+}diff --git a/src/utils/shortcutManager.ts b/src/utils/shortcutManager.tsindex 0acd2be..d6ff277 100644--- a/src/utils/shortcutManager.ts+++ b/src/utils/shortcutManager.ts@@ -130,6 +130,24 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [toolId: 'fill',springLoaded: true,},+ {+ id: 'tool.gradient',+ label: 'Gradient Tool',+ description: 'Draw linear, radial, and interactive mesh gradients',+ category: 'Tools',+ defaultShortcut: 'Shift+G',+ toolId: 'gradient',+ springLoaded: true,+ },+ {+ id: 'tool.retouch',+ label: 'Retouch Tool',+ description: 'Smudge, Blur, Dodge, Burn, and Clone Stamp brush',+ category: 'Tools',+ defaultShortcut: 'S',+ toolId: 'retouch',+ springLoaded: true,+ },{id: 'tool.shape',label: 'Geometric Shapes',@@ -139,6 +157,15 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [toolId: 'shape',springLoaded: true,},+ {+ id: 'tool.pen',+ label: 'Bézier Pen Tool',+ description: 'Plot true cubic Bézier curves with editable anchor handles',+ category: 'Tools',+ defaultShortcut: 'P',+ toolId: 'pen',+ springLoaded: true,+ },{id: 'tool.text',label: 'Text Tool',@@ -394,20 +421,34 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [defaultShortcut: 'Ctrl+Y',altDefaultShortcut: 'Ctrl+Shift+Z',},+ {+ id: 'edit.cut',+ label: 'Cut',+ description: 'Cut active selection or layer to clipboard',+ category: 'Edit',+ defaultShortcut: 'Ctrl+X',+ },{id: 'edit.copy',- label: 'Copy Layer',- description: 'Copy active layer to clipboard',+ label: 'Copy',+ description: 'Copy active selection or layer to clipboard',category: 'Edit',defaultShortcut: 'Ctrl+C',},{id: 'edit.paste',- label: 'Paste Layer',- description: 'Paste layer from clipboard',+ label: 'Paste',+ description: 'Paste clipboard contents into a new layer',category: 'Edit',defaultShortcut: 'Ctrl+V',},+ {+ id: 'edit.moveSelectionToNewLayer',+ label: 'Move Selection to New Layer',+ description: 'Cut selected section and paste into a new layer',+ category: 'Edit',+ defaultShortcut: 'Ctrl+Shift+J',+ },{id: 'edit.delete',label: 'Clear / Delete Layer',diff --git a/src/utils/sphereColorMath.ts b/src/utils/sphereColorMath.tsnew file mode 100644index 0000000..7f71c6e--- /dev/null+++ b/src/utils/sphereColorMath.ts@@ -0,0 +1,991 @@+import { HSV, RGB, hsvToRgb, rgbToHex } from './colorUtils';++export type SphereColorSlot = 'shadow' | 'base' | 'light' | 'rim';++export interface SphereLightingConfig {+ /** Horizontal light angle in degrees (-180..180). Negative = left, positive = right. */+ lightAzimuth: number;+ /** Vertical light elevation in degrees (-80..80). Positive = top. */+ lightElevation: number;+ /** Key light brightness / exposure (0.1 = dim chiaroscuro, 1.0 = neutral, 2.8 = bright key). */+ lightIntensity: number;+ /** Global chroma saturation (0.0 = pure B&W / grayscale, 1.0 = normal, 1.8 = vivid). */+ saturation: number;+ /** Perceptual lighting contrast (0.4 = soft/flat, 1.15 = sculptural default, 2.2 = high contrast). */+ contrast: number;+ /** Surface finish: 0.05 = wet gloss, 0.95 = matte. */+ roughness: number;+ /** Specular highlight intensity (0..1.6). */+ specularStrength: number;+ /** Soft bounce light from below (0..1.2). */+ bounceIntensity: number;+ /** Painterly shadow depth (0..1). */+ shadowDepth: number;+ /** Omnidirectional ambient fill lifting shadows/overall brightness (0..1). */+ ambientIntensity?: number;+ /** How strongly the Light slot color tints the lit body vs neutral white light (0..1). */+ lightTint?: number;+ /** Grazing Fresnel rim / backlight intensity driven by Rim slot color (0..1.5). */+ rimIntensity?: number;+ /** Chromatic subsurface / terminator scatter glow along the shadow boundary (0..1). */+ subsurface?: number;+}++export interface SphereSlotsState {+ shadow: HSV;+ base: HSV;+ light: HSV;+ /** Edge rim / bounce light accent color (optional for backward compatibility). */+ rim?: HSV;+}++export interface SphereMarkerPosition {+ /** Normalized X on sphere projection (-1..1, +right). */+ x: number;+ /** Normalized Y on sphere projection (-1..1, +up). */+ y: number;+}++export interface SphereColorResult {+ hex: string;+ rgb: RGB;+}++export interface SpherePreset {+ id: string;+ label: string;+ swatch?: string;+ lighting: Partial<SphereLightingConfig>;+ slots?: Partial<SphereSlotsState>;+}++export const DEFAULT_SPHERE_LIGHTING: SphereLightingConfig = {+ lightAzimuth: -38,+ lightElevation: 42,+ lightIntensity: 1.0,+ saturation: 1.0,+ contrast: 1.15,+ roughness: 0.44,+ specularStrength: 0.34,+ bounceIntensity: 0.34,+ shadowDepth: 0.84,+ ambientIntensity: 0.08,+ lightTint: 0.28,+ rimIntensity: 0.14,+ subsurface: 0.16,+};++export const DEFAULT_SPHERE_SLOTS: SphereSlotsState = {+ shadow: { h: 215, s: 0.28, v: 0.44 },+ base: { h: 162, s: 0.16, v: 0.62 },+ light: { h: 52, s: 0.14, v: 0.94 },+ rim: { h: 200, s: 0.28, v: 0.82 },+};++export const SPHERE_LIGHTING_PRESETS: SpherePreset[] = [+ {+ id: 'studio',+ label: 'Studio Matte',+ swatch: '#9aa8a0',+ lighting: {+ lightAzimuth: -38,+ lightElevation: 42,+ lightIntensity: 1.05,+ saturation: 1.0,+ contrast: 1.15,+ roughness: 0.44,+ specularStrength: 0.34,+ bounceIntensity: 0.34,+ shadowDepth: 0.84,+ ambientIntensity: 0.14,+ lightTint: 0.28,+ rimIntensity: 0.16,+ subsurface: 0.18,+ },+ },+ {+ id: 'crimson-mood',+ label: 'Crimson Mood',+ swatch: '#c82314',+ lighting: {+ lightAzimuth: -46,+ lightElevation: 34,+ lightIntensity: 1.5,+ saturation: 1.24,+ contrast: 1.48,+ roughness: 0.1,+ specularStrength: 1.1,+ bounceIntensity: 0.22,+ shadowDepth: 0.96,+ ambientIntensity: 0.03,+ lightTint: 0.88,+ rimIntensity: 0.68,+ subsurface: 0.48,+ },+ slots: {+ shadow: { h: 356, s: 0.92, v: 0.12 },+ base: { h: 8, s: 0.8, v: 0.52 },+ light: { h: 7, s: 0.95, v: 1.0 },+ rim: { h: 12, s: 0.96, v: 0.98 },+ },+ },+ {+ id: 'high-key',+ label: 'High-Key Bright',+ swatch: '#f2e8dc',+ lighting: {+ lightAzimuth: -30,+ lightElevation: 46,+ lightIntensity: 1.65,+ saturation: 1.05,+ contrast: 0.96,+ roughness: 0.38,+ specularStrength: 0.45,+ bounceIntensity: 0.62,+ shadowDepth: 0.52,+ ambientIntensity: 0.46,+ lightTint: 0.24,+ rimIntensity: 0.38,+ subsurface: 0.28,+ },+ },+ {+ id: 'warm-cool',+ label: 'Warm / Cool',+ swatch: '#e8b36b',+ lighting: {+ lightAzimuth: -44,+ lightElevation: 48,+ lightIntensity: 1.25,+ saturation: 1.1,+ contrast: 1.25,+ roughness: 0.36,+ specularStrength: 0.48,+ bounceIntensity: 0.4,+ shadowDepth: 0.86,+ ambientIntensity: 0.14,+ lightTint: 0.52,+ rimIntensity: 0.32,+ subsurface: 0.34,+ },+ slots: {+ shadow: { h: 224, s: 0.56, v: 0.38 },+ light: { h: 38, s: 0.46, v: 0.98 },+ rim: { h: 205, s: 0.62, v: 0.9 },+ },+ },+ {+ id: 'neon-dual',+ label: 'Neon Dual-Tone',+ swatch: '#e024a8',+ lighting: {+ lightAzimuth: -48,+ lightElevation: 32,+ lightIntensity: 1.6,+ saturation: 1.35,+ contrast: 1.42,+ roughness: 0.16,+ specularStrength: 0.95,+ bounceIntensity: 0.55,+ shadowDepth: 0.92,+ ambientIntensity: 0.08,+ lightTint: 0.86,+ rimIntensity: 1.1,+ subsurface: 0.45,+ },+ slots: {+ shadow: { h: 256, s: 0.78, v: 0.22 },+ base: { h: 270, s: 0.32, v: 0.52 },+ light: { h: 324, s: 0.92, v: 1.0 },+ rim: { h: 186, s: 0.96, v: 1.0 },+ },+ },+ {+ id: 'sunset-rim',+ label: 'Sunset Rim',+ swatch: '#ff6a2b',+ lighting: {+ lightAzimuth: -58,+ lightElevation: 22,+ lightIntensity: 1.48,+ saturation: 1.22,+ contrast: 1.36,+ roughness: 0.28,+ specularStrength: 0.65,+ bounceIntensity: 0.52,+ shadowDepth: 0.88,+ ambientIntensity: 0.12,+ lightTint: 0.72,+ rimIntensity: 1.05,+ subsurface: 0.64,+ },+ slots: {+ shadow: { h: 274, s: 0.62, v: 0.24 },+ light: { h: 26, s: 0.84, v: 1.0 },+ rim: { h: 16, s: 0.98, v: 1.0 },+ },+ },+ {+ id: 'glossy-wet',+ label: 'Glossy Wet',+ swatch: '#d6dce5',+ lighting: {+ lightAzimuth: -36,+ lightElevation: 44,+ lightIntensity: 1.32,+ saturation: 1.12,+ contrast: 1.34,+ roughness: 0.08,+ specularStrength: 1.25,+ bounceIntensity: 0.36,+ shadowDepth: 0.88,+ ambientIntensity: 0.12,+ lightTint: 0.38,+ rimIntensity: 0.48,+ subsurface: 0.26,+ },+ },+ {+ id: 'chiaroscuro',+ label: 'Dim Chiaroscuro',+ swatch: '#4a3d36',+ lighting: {+ lightAzimuth: -54,+ lightElevation: 36,+ lightIntensity: 0.58,+ saturation: 0.96,+ contrast: 1.55,+ roughness: 0.42,+ specularStrength: 0.4,+ bounceIntensity: 0.22,+ shadowDepth: 0.95,+ ambientIntensity: 0.02,+ lightTint: 0.42,+ rimIntensity: 0.14,+ subsurface: 0.24,+ },+ },+ {+ id: 'bw-value',+ label: 'B&W Value Study',+ swatch: '#8c8c8c',+ lighting: {+ lightAzimuth: -40,+ lightElevation: 44,+ lightIntensity: 1.1,+ saturation: 0,+ contrast: 1.25,+ roughness: 0.48,+ specularStrength: 0.32,+ bounceIntensity: 0.32,+ shadowDepth: 0.88,+ ambientIntensity: 0.12,+ lightTint: 0.2,+ rimIntensity: 0.18,+ subsurface: 0,+ },+ },+];++export const MAX_MARKER_RADIUS = 0.93;++const DEG2RAD = Math.PI / 180;+const LINEAR_LUT_MAX = 4.0;+const LINEAR_LUT_SIZE = 4096;+const LINEAR_LUT_SCALE = (LINEAR_LUT_SIZE - 1) / LINEAR_LUT_MAX;++// Exact IEC 61966-2-1 sRGB -> Linear LUT (256 entries)+const SRGB_TO_LINEAR_LUT = new Float32Array(256);+for (let i = 0; i < 256; i++) {+ const u = i / 255;+ SRGB_TO_LINEAR_LUT[i] = u <= 0.04045 ? u / 12.92 : Math.pow((u + 0.055) / 1.055, 2.4);+}++// Base sRGB [0..1] curve for Linear [0..4.0] with C1 soft-shoulder highlight rolloff+const LINEAR_TO_SRGB_FLOAT = new Float32Array(LINEAR_LUT_SIZE);+for (let i = 0; i < LINEAR_LUT_SIZE; i++) {+ const x = (i / (LINEAR_LUT_SIZE - 1)) * LINEAR_LUT_MAX;+ const mapped = x <= 0.82 ? x : 0.82 + 0.18 * (1 - Math.exp(-(x - 0.82) * 3.8));+ const clamped = mapped < 0 ? 0 : mapped > 1 ? 1 : mapped;+ LINEAR_TO_SRGB_FLOAT[i] =+ clamped <= 0.0031308 ? 12.92 * clamped : 1.055 * Math.pow(clamped, 1 / 2.4) - 0.055;+}++// Single-entry cached 4096-byte tone LUT with C1 S-curve perceptual contrast (rebuilt only on contrast change, <0.05ms)+let cachedContrastKey = -1;+const TONE_SRGB_LUT = new Uint8Array(LINEAR_LUT_SIZE);++function getToneLut(contrastRaw: number): Uint8Array {+ const contrast = Math.max(0.35, Math.min(2.2, contrastRaw));+ const key = Math.round(contrast * 200);+ if (key === cachedContrastKey) return TONE_SRGB_LUT;+ cachedContrastKey = key;++ if (Math.abs(contrast - 1) < 0.004) {+ for (let i = 0; i < LINEAR_LUT_SIZE; i++) {+ TONE_SRGB_LUT[i] = Math.max(0, Math.min(255, Math.round(LINEAR_TO_SRGB_FLOAT[i] * 255)));+ }+ } else {+ for (let i = 0; i < LINEAR_LUT_SIZE; i++) {+ const s = LINEAR_TO_SRGB_FLOAT[i];+ const curved =+ s < 0.5+ ? 0.5 * Math.pow(Math.max(0, 2 * s), contrast)+ : 1 - 0.5 * Math.pow(Math.max(0, 2 * (1 - s)), contrast);+ TONE_SRGB_LUT[i] = Math.max(0, Math.min(255, Math.round(curved * 255)));+ }+ }+ return TONE_SRGB_LUT;+}++function smoothstep(edge0: number, edge1: number, x: number): number {+ const t = Math.max(0, Math.min(1, (x - edge0) / (edge1 - edge0)));+ return t * t * (3 - 2 * t);+}++export function clampMarkerPosition(x: number, y: number, maxRadius = MAX_MARKER_RADIUS): SphereMarkerPosition {+ const len = Math.hypot(x, y);+ if (len <= maxRadius || len === 0) {+ return { x, y };+ }+ const scale = maxRadius / len;+ return { x: x * scale, y: y * scale };+}++export function markerToNormal(pos: SphereMarkerPosition): { nx: number; ny: number; nz: number } {+ const clamped = clampMarkerPosition(pos.x, pos.y, 0.999);+ const nz = Math.sqrt(Math.max(0.0001, 1 - clamped.x * clamped.x - clamped.y * clamped.y));+ return { nx: clamped.x, ny: clamped.y, nz };+}++export function getLightVectors(config: SphereLightingConfig) {+ const az = config.lightAzimuth * DEG2RAD;+ const el = config.lightElevation * DEG2RAD;+ const cosEl = Math.cos(el);+ let lx = cosEl * Math.sin(az);+ let ly = Math.sin(el);+ let lz = cosEl * Math.cos(az);+ const lLen = Math.hypot(lx, ly, lz) || 1;+ lx /= lLen;+ ly /= lLen;+ lz /= lLen;++ // Blinn-Phong half vector for view V = (0, 0, 1)+ let hx = lx;+ let hy = ly;+ let hz = lz + 1;+ const hLen = Math.hypot(hx, hy, hz) || 1;+ hx /= hLen;+ hy /= hLen;+ hz /= hLen;++ // Soft bounce light coming from below and slightly opposite the key light+ let bx = -lx * 0.45;+ let by = -0.84;+ let bz = 0.38;+ const bLen = Math.hypot(bx, by, bz) || 1;+ bx /= bLen;+ by /= bLen;+ bz /= bLen;++ return { lx, ly, lz, hx, hy, hz, bx, by, bz };+}++function linearToSrgbByte(lin: number, toneLut: Uint8Array): number {+ if (lin <= 0) return 0;+ if (lin >= LINEAR_LUT_MAX) return 255;+ return toneLut[(lin * LINEAR_LUT_SCALE + 0.5) | 0];+}++function hsvToLinearRgb(hsv: HSV): [number, number, number] {+ const rgb = hsvToRgb(hsv.h, hsv.s, hsv.v);+ return [+ SRGB_TO_LINEAR_LUT[rgb.r],+ SRGB_TO_LINEAR_LUT[rgb.g],+ SRGB_TO_LINEAR_LUT[rgb.b],+ ];+}++const LIGHT_FACTORS_STRIDE = 7;++interface SphereShaderConstants {+ shadowToneR: number;+ shadowToneG: number;+ shadowToneB: number;+ diffR: number;+ diffG: number;+ diffB: number;+ ambientR: number;+ ambientG: number;+ ambientB: number;+ keyScaleR: number;+ keyScaleG: number;+ keyScaleB: number;+ specTintR: number;+ specTintG: number;+ specTintB: number;+ bounceR: number;+ bounceG: number;+ bounceB: number;+ rimR: number;+ rimG: number;+ rimB: number;+ sssR: number;+ sssG: number;+ sssB: number;+ sat: number;+ toneLut: Uint8Array;+}++function clampFinite(v: number | undefined, fallback: number, min: number, max: number): number {+ const n = typeof v === 'number' && Number.isFinite(v) ? v : fallback;+ return n < min ? min : n > max ? max : n;+}++function computeShaderConstants(+ slots: SphereSlotsState,+ config: SphereLightingConfig+): SphereShaderConstants {+ const [br, bg, bb] = hsvToLinearRgb(slots.base);+ const [sr, sg, sb] = hsvToLinearRgb(slots.shadow);+ const [lr, lg, lb] = hsvToLinearRgb(slots.light);+ const [rr, rg, rb] = slots.rim+ ? hsvToLinearRgb(slots.rim)+ : [sr * 0.55 + lr * 0.35 + br * 0.1, sg * 0.55 + lg * 0.35 + bg * 0.1, sb * 0.55 + lb * 0.35 + bb * 0.1];++ const intensity = clampFinite(config.lightIntensity, 1, 0.08, 2.8);+ const sat = clampFinite(config.saturation, 1, 0, 1.85);+ const shadowDepth = clampFinite(config.shadowDepth, 0.84, 0, 1);+ const ambient = clampFinite(config.ambientIntensity, 0.08, 0, 1);+ const lightTint = clampFinite(config.lightTint, 0.28, 0, 1);+ const toneLut = getToneLut(clampFinite(config.contrast, 1.15, 0.35, 2.2));++ const bodyLightScale = 0.26 + 0.74 * intensity;+ const bounceScale = (0.45 + 0.55 * Math.min(1.5, intensity)) * 0.95;++ // Luminance-compensated colored key tint so saturated gels (e.g. crimson/neon) stay bright instead of dim+ const lightLum = Math.max(0.08, 0.2126 * lr + 0.7152 * lg + 0.0722 * lb);+ const normFactor = Math.min(2.2, 0.74 / lightLum);+ const kTintR = Math.max(0.04, 1 + lightTint * (lr * normFactor - 1));+ const kTintG = Math.max(0.04, 1 + lightTint * (lg * normFactor - 1));+ const kTintB = Math.max(0.04, 1 + lightTint * (lb * normFactor - 1));+ const gelWash = lightTint * 0.3 * intensity;++ const shadowScale = (1 - 0.72 * shadowDepth) * (0.5 + 0.5 * Math.min(1.25, intensity));+ const shadowToneR = (br * (0.24 + 0.76 * sr) * 0.48 + sr * 0.52) * shadowScale;+ const shadowToneG = (bg * (0.24 + 0.76 * sg) * 0.48 + sg * 0.52) * shadowScale;+ const shadowToneB = (bb * (0.24 + 0.76 * sb) * 0.48 + sb * 0.52) * shadowScale;++ const litBaseR = br * bodyLightScale * kTintR + lr * gelWash;+ const litBaseG = bg * bodyLightScale * kTintG + lg * gelWash;+ const litBaseB = bb * bodyLightScale * kTintB + lb * gelWash;++ // Perceptual curve keeps default shadows sculpted while allowing full high-key lift+ const ambScale = ambient * ambient * 0.48 + ambient * 0.05;+ const ambientR = (br * 0.68 + lr * 0.18 + sr * 0.14) * ambScale;+ const ambientG = (bg * 0.68 + lg * 0.18 + sg * 0.14) * ambScale;+ const ambientB = (bb * 0.68 + lb * 0.18 + sb * 0.14) * ambScale;++ const bounceR = (rr * 0.64 + sr * 0.24 + br * 0.12) * bounceScale;+ const bounceG = (rg * 0.64 + sg * 0.24 + bg * 0.12) * bounceScale;+ const bounceB = (rb * 0.64 + sb * 0.24 + bb * 0.12) * bounceScale;++ const rimScale = 0.58 + 0.42 * Math.min(1.6, intensity);+ const rimR = rr * rimScale;+ const rimG = rg * rimScale;+ const rimB = rb * rimScale;++ // Subsurface terminator scatter keeps skin/red/saturated lighting glowing across the shadow turn+ const sssScale = 0.26 * (0.45 + 0.55 * intensity);+ const sssR = (br * lr * 1.15 + lr * 0.28 + rr * 0.14) * sssScale;+ const sssG = (bg * lg * 1.15 + lg * 0.28 + rg * 0.14) * sssScale;+ const sssB = (bb * lb * 1.15 + lb * 0.28 + rb * 0.14) * sssScale;++ const keyScaleR = 0.36 * intensity * (br * lr + 0.22 * lr);+ const keyScaleG = 0.36 * intensity * (bg * lg + 0.22 * lg);+ const keyScaleB = 0.36 * intensity * (bb * lb + 0.22 * lb);++ // Dielectric wet specular retains crisp bright core while picking up key hue+ const specTintR = (lr * 0.72 + 0.28) * intensity;+ const specTintG = (lg * 0.72 + 0.28) * intensity;+ const specTintB = (lb * 0.72 + 0.28) * intensity;++ return {+ shadowToneR,+ shadowToneG,+ shadowToneB,+ diffR: litBaseR - shadowToneR,+ diffG: litBaseG - shadowToneG,+ diffB: litBaseB - shadowToneB,+ ambientR,+ ambientG,+ ambientB,+ keyScaleR,+ keyScaleG,+ keyScaleB,+ specTintR,+ specTintG,+ specTintB,+ bounceR,+ bounceG,+ bounceB,+ rimR,+ rimG,+ rimB,+ sssR,+ sssG,+ sssB,+ sat,+ toneLut,+ };+}++/**+ * Evaluates the exact painterly matte/glossy/cinematic color at any normalized disk coordinate (x, y)+ * on the 3D sphere. Matches the LUT pixel shader identically.+ */+export function evaluateSphereColor(+ pos: SphereMarkerPosition,+ slots: SphereSlotsState,+ config: SphereLightingConfig+): SphereColorResult {+ const { nx, ny, nz } = markerToNormal(pos);+ const { lx, ly, lz, hx, hy, hz, bx, by, bz } = getLightVectors(config);++ const ndotl = nx * lx + ny * ly + nz * lz;+ const ndoth = Math.max(0, nx * hx + ny * hy + nz * hz);+ const ndotb = Math.max(0, nx * bx + ny * by + nz * bz);+ const oneMinusNz = 1 - nz;+ const fresnel = Math.pow(oneMinusNz, 2.5);++ const shadowDepth = clampFinite(config.shadowDepth, 0.84, 0, 1);+ const roughness = clampFinite(config.roughness, 0.44, 0.05, 0.95);+ const specStrength = clampFinite(config.specularStrength, 0.34, 0, 1.6);+ const bounceIntensity = clampFinite(config.bounceIntensity, 0.34, 0, 1.2);+ const rimIntensity = clampFinite(config.rimIntensity, 0.14, 0, 1.5);+ const subsurface = clampFinite(config.subsurface, 0.16, 0, 1);++ const litFactor = smoothstep(-0.18, 0.64, ndotl);+ const coreShadow = smoothstep(0.14, -0.58, ndotl) * shadowDepth;+ const highlightDiffuse = Math.pow(Math.max(0, (ndotl + 0.08) / 1.08), 1.75);++ const gloss = 1 - roughness;+ const satinExp = 5 + gloss * 18;+ const specExp = 18 + gloss * gloss * 180;+ const specMask = smoothstep(-0.1, 0.22, ndotl);+ const satinWeight = 0.14 * roughness * Math.min(1, specStrength * 1.4);+ const specW =+ (Math.pow(ndoth, satinExp) * satinWeight ++ Math.pow(ndoth, specExp) * specStrength * (0.85 + gloss * 0.9)) *+ specMask;++ const bounceW =+ Math.pow(ndotb, 2.0) *+ smoothstep(0.12, -0.42, ndotl) *+ bounceIntensity *+ (0.45 + 0.55 * fresnel);++ const rimOpp = smoothstep(0.55, -0.35, ndotl);+ const rimW = Math.pow(oneMinusNz, 3.4) * (0.24 + 0.76 * rimOpp) * rimIntensity;++ const termDelta = (ndotl - 0.04) / 0.28;+ const sssW = Math.exp(-(termDelta * termDelta)) * subsurface * (0.65 + 0.35 * oneMinusNz);++ const coreDip = 1 - 0.68 * coreShadow * Math.max(0.22, 1 - bounceW * 1.45);++ const c = computeShaderConstants(slots, config);++ let linR =+ (c.shadowToneR + c.diffR * litFactor) * coreDip ++ c.ambientR ++ highlightDiffuse * c.keyScaleR ++ specW * c.specTintR ++ bounceW * c.bounceR ++ rimW * c.rimR ++ sssW * c.sssR;+ let linG =+ (c.shadowToneG + c.diffG * litFactor) * coreDip ++ c.ambientG ++ highlightDiffuse * c.keyScaleG ++ specW * c.specTintG ++ bounceW * c.bounceG ++ rimW * c.rimG ++ sssW * c.sssG;+ let linB =+ (c.shadowToneB + c.diffB * litFactor) * coreDip ++ c.ambientB ++ highlightDiffuse * c.keyScaleB ++ specW * c.specTintB ++ bounceW * c.bounceB ++ rimW * c.rimB ++ sssW * c.sssB;++ if (c.sat !== 1) {+ const lum = 0.2126 * linR + 0.7152 * linG + 0.0722 * linB;+ linR = lum + (linR - lum) * c.sat;+ linG = lum + (linG - lum) * c.sat;+ linB = lum + (linB - lum) * c.sat;+ }++ const rgb: RGB = {+ r: linearToSrgbByte(linR, c.toneLut),+ g: linearToSrgbByte(linG, c.toneLut),+ b: linearToSrgbByte(linB, c.toneLut),+ };++ return {+ rgb,+ hex: rgbToHex(rgb.r, rgb.g, rgb.b),+ };+}++/**+ * Precomputed per-pixel geometry & lighting weights for sub-millisecond 60+ FPS sphere redraws.+ * Geometry LUT is rebuilt only on canvas resize; lighting LUT only when light angle/finish changes.+ * Slot Hue/color changes only run the linear blend pass (< 0.7ms).+ */+export interface SphereRenderLut {+ width: number;+ height: number;+ count: number;+ /** Pixel offsets into Uint32Array RGBA buffer */+ pixelIndices: Uint32Array;+ /** Anti-aliased edge alpha (0..255) */+ alphas: Uint8Array;+ /** Packed normals [nx, ny, nz] * count */+ normals: Float32Array;+ /** Ordered 4x4 Bayer dither offset (-0.0018..+0.0018) per interior pixel to remove 8-bit banding */+ dither: Float32Array;+ /** Precomputed lighting factors per pixel: [litFactor, coreDip, highlightDiffuse, specW, bounceW, rimW, sssW] */+ lightFactors: Float32Array;+ /** Cached ImageData + Uint32 view for zero-allocation redraws */+ imageData: ImageData | null;+ u32: Uint32Array | null;+}++// 4x4 Bayer threshold matrix normalized to [-0.5, +0.5]+const BAYER_4X4 = new Float32Array([+ -0.46875, 0.03125, -0.34375, 0.15625,+ 0.28125, -0.21875, 0.40625, -0.09375,+ -0.28125, 0.21875, -0.40625, 0.09375,+ 0.46875, -0.03125, 0.34375, -0.15625,+]);++export function buildSphereGeometryLut(+ width: number,+ height: number,+ radiusRatio = 0.465+): SphereRenderLut {+ const cx = width * 0.5;+ const cy = height * 0.5;+ const radius = Math.min(width, height) * radiusRatio;+ const aaWidth = 1.25; // smooth analytical anti-aliasing band in device pixels+ const maxDist = radius + aaWidth;+ const maxDistSq = maxDist * maxDist;++ // First pass: count interior + AA edge pixels+ let count = 0;+ for (let py = 0; py < height; py++) {+ const dyPx = cy - (py + 0.5);+ const dySq = dyPx * dyPx;+ if (dySq > maxDistSq) continue;+ for (let px = 0; px < width; px++) {+ const dxPx = px + 0.5 - cx;+ if (dxPx * dxPx + dySq <= maxDistSq) {+ count++;+ }+ }+ }++ const pixelIndices = new Uint32Array(count);+ const alphas = new Uint8Array(count);+ const normals = new Float32Array(count * 3);+ const dither = new Float32Array(count);+ const lightFactors = new Float32Array(count * LIGHT_FACTORS_STRIDE);++ let idx = 0;+ for (let py = 0; py < height; py++) {+ const dyPx = cy - (py + 0.5);+ const dySq = dyPx * dyPx;+ if (dySq > maxDistSq) continue;+ const rowOffset = py * width;+ const bayerRow = (py & 3) << 2;++ for (let px = 0; px < width; px++) {+ const dxPx = px + 0.5 - cx;+ const distSq = dxPx * dxPx + dySq;+ if (distSq > maxDistSq) continue;++ const dist = Math.sqrt(distSq);+ let nx = dxPx / radius;+ let ny = dyPx / radius;+ const rNorm = dist / radius;+ let nz: number;+ if (rNorm >= 1) {+ const inv = 1 / rNorm;+ nx *= inv;+ ny *= inv;+ nz = 0.001;+ } else {+ nz = Math.sqrt(Math.max(0.0001, 1 - nx * nx - ny * ny));+ }++ const alphaFloat = Math.max(0, Math.min(1, (radius + aaWidth * 0.5 - dist) / aaWidth));+ pixelIndices[idx] = rowOffset + px;+ alphas[idx] = Math.round(alphaFloat * 255);+ const nOff = idx * 3;+ normals[nOff] = nx;+ normals[nOff + 1] = ny;+ normals[nOff + 2] = nz;+ dither[idx] = BAYER_4X4[bayerRow | (px & 3)] * 0.0022;+ idx++;+ }+ }++ return {+ width,+ height,+ count,+ pixelIndices,+ alphas,+ normals,+ dither,+ lightFactors,+ imageData: null,+ u32: null,+ };+}++export function updateSphereLightingLut(+ lut: SphereRenderLut,+ config: SphereLightingConfig+): void {+ const { lx, ly, lz, hx, hy, hz, bx, by, bz } = getLightVectors(config);+ const roughness = clampFinite(config.roughness, 0.44, 0.05, 0.95);+ const gloss = 1 - roughness;+ const satinExp = 5 + gloss * 18;+ const specExp = 18 + gloss * gloss * 180;+ const specStrength = clampFinite(config.specularStrength, 0.34, 0, 1.6);+ const satinWeight = 0.14 * roughness * Math.min(1, specStrength * 1.4);+ const specGain = specStrength * (0.85 + gloss * 0.9);+ const bounceIntensity = clampFinite(config.bounceIntensity, 0.34, 0, 1.2);+ const shadowDepth = clampFinite(config.shadowDepth, 0.84, 0, 1);+ const rimIntensity = clampFinite(config.rimIntensity, 0.14, 0, 1.5);+ const subsurface = clampFinite(config.subsurface, 0.16, 0, 1);++ const normals = lut.normals;+ const out = lut.lightFactors;+ const count = lut.count;++ for (let i = 0; i < count; i++) {+ const nOff = i * 3;+ const nx = normals[nOff];+ const ny = normals[nOff + 1];+ const nz = normals[nOff + 2];++ const ndotl = nx * lx + ny * ly + nz * lz;+ const ndoth = Math.max(0, nx * hx + ny * hy + nz * hz);+ const ndotb = Math.max(0, nx * bx + ny * by + nz * bz);+ const oneMinusNz = 1 - nz;+ const fresnel = Math.pow(oneMinusNz, 2.5);++ const litFactor = smoothstep(-0.18, 0.64, ndotl);+ const coreShadow = smoothstep(0.14, -0.58, ndotl) * shadowDepth;+ const highlightDiffuse = Math.pow(Math.max(0, (ndotl + 0.08) / 1.08), 1.75);+ const specMask = smoothstep(-0.1, 0.22, ndotl);+ const specW =+ (Math.pow(ndoth, satinExp) * satinWeight + Math.pow(ndoth, specExp) * specGain) * specMask;+ const bounceW =+ Math.pow(ndotb, 2.0) *+ smoothstep(0.12, -0.42, ndotl) *+ bounceIntensity *+ (0.45 + 0.55 * fresnel);+ const rimOpp = smoothstep(0.55, -0.35, ndotl);+ const rimW = Math.pow(oneMinusNz, 3.4) * (0.24 + 0.76 * rimOpp) * rimIntensity;+ const termDelta = (ndotl - 0.04) / 0.28;+ const sssW = Math.exp(-(termDelta * termDelta)) * subsurface * (0.65 + 0.35 * oneMinusNz);+ const coreDip = 1 - 0.68 * coreShadow * Math.max(0.22, 1 - bounceW * 1.45);++ const fOff = i * LIGHT_FACTORS_STRIDE;+ out[fOff] = litFactor;+ out[fOff + 1] = coreDip;+ out[fOff + 2] = highlightDiffuse;+ out[fOff + 3] = specW;+ out[fOff + 4] = bounceW;+ out[fOff + 5] = rimW;+ out[fOff + 6] = sssW;+ }+}++export function renderSphereFromLut(+ ctx: CanvasRenderingContext2D,+ lut: SphereRenderLut,+ slots: SphereSlotsState,+ config: SphereLightingConfig+): void {+ if (!lut.imageData || lut.imageData.width !== lut.width || lut.imageData.height !== lut.height) {+ lut.imageData = ctx.createImageData(lut.width, lut.height);+ lut.u32 = new Uint32Array(lut.imageData.data.buffer);+ }++ const u32 = lut.u32!;+ const {+ shadowToneR,+ shadowToneG,+ shadowToneB,+ diffR,+ diffG,+ diffB,+ ambientR,+ ambientG,+ ambientB,+ keyScaleR,+ keyScaleG,+ keyScaleB,+ specTintR,+ specTintG,+ specTintB,+ bounceR,+ bounceG,+ bounceB,+ rimR,+ rimG,+ rimB,+ sssR,+ sssG,+ sssB,+ sat,+ toneLut,+ } = computeShaderConstants(slots, config);++ const indices = lut.pixelIndices;+ const alphas = lut.alphas;+ const factors = lut.lightFactors;+ const dither = lut.dither;+ const count = lut.count;+ const applySat = sat !== 1;++ for (let i = 0; i < count; i++) {+ const fOff = i * LIGHT_FACTORS_STRIDE;+ const lit = factors[fOff];+ const dip = factors[fOff + 1];+ const hiDiff = factors[fOff + 2];+ const specW = factors[fOff + 3];+ const bounceW = factors[fOff + 4];+ const rimW = factors[fOff + 5];+ const sssW = factors[fOff + 6];+ const d = dither[i];++ let linR =+ (shadowToneR + diffR * lit) * dip ++ ambientR ++ hiDiff * keyScaleR ++ specW * specTintR ++ bounceW * bounceR ++ rimW * rimR ++ sssW * sssR;+ let linG =+ (shadowToneG + diffG * lit) * dip ++ ambientG ++ hiDiff * keyScaleG ++ specW * specTintG ++ bounceW * bounceG ++ rimW * rimG ++ sssW * sssG;+ let linB =+ (shadowToneB + diffB * lit) * dip ++ ambientB ++ hiDiff * keyScaleB ++ specW * specTintB ++ bounceW * bounceB ++ rimW * rimB ++ sssW * sssB;++ if (applySat) {+ const lum = 0.2126 * linR + 0.7152 * linG + 0.0722 * linB;+ linR = lum + (linR - lum) * sat;+ linG = lum + (linG - lum) * sat;+ linB = lum + (linB - lum) * sat;+ }++ linR += d;+ linG += d;+ linB += d;++ const r = linR <= 0 ? 0 : linR >= LINEAR_LUT_MAX ? 255 : toneLut[(linR * LINEAR_LUT_SCALE + 0.5) | 0];+ const g = linG <= 0 ? 0 : linG >= LINEAR_LUT_MAX ? 255 : toneLut[(linG * LINEAR_LUT_SCALE + 0.5) | 0];+ const b = linB <= 0 ? 0 : linB >= LINEAR_LUT_MAX ? 255 : toneLut[(linB * LINEAR_LUT_SCALE + 0.5) | 0];++ // Little-endian ABGR packing for ImageData Uint32Array+ u32[indices[i]] = (alphas[i] << 24) | (b << 16) | (g << 8) | r;+ }++ ctx.putImageData(lut.imageData, 0, 0);+}++/**+ * Computes exact 3D orthographic projection parameters for the tangent disc/puck marker.+ */+export interface ProjectedMarkerGeometry {+ baseX: number;+ baseY: number;+ rx: number;+ ry: number;+ /** Extrusion shift along local +Y (radial outward direction) */+ extrudeShift: number;+ /** SVG rotation in degrees so local +Y aligns with radial outward vector */+ rotateDeg: number;+ /** Shadow offset in local puck space */+ shadowLocalX: number;+ shadowLocalY: number;+ nz: number;+}++export function projectSphereMarker(+ pos: SphereMarkerPosition,+ sphereSize: number,+ radiusRatio: number,+ config: SphereLightingConfig+): ProjectedMarkerGeometry {+ const { nx, ny, nz } = markerToNormal(pos);+ const cx = sphereSize * 0.5;+ const cy = sphereSize * 0.5;+ const R = sphereSize * radiusRatio;++ const baseX = cx + nx * R;+ const baseY = cy - ny * R;++ const discRadius = R * 0.165;+ const puckHeight = R * 0.044;+ const radialLen = Math.hypot(nx, ny);++ // Tangent axis stays full width; radial axis foreshortens by cos(theta) = nz+ const rx = discRadius;+ const ry = Math.max(discRadius * 0.22, discRadius * nz);+ const extrudeShift = puckHeight * radialLen;++ // Screen-space radial angle: dx = nx, dy = -ny+ const radAngleRad = radialLen > 1e-4 ? Math.atan2(-ny, nx) : 0;+ const rotateDeg = (radAngleRad * 180) / Math.PI - 90;++ // Subtle cast shadow offset opposite to key light, projected into local rotated frame+ const { lx, ly } = getLightVectors(config);+ const shadowWorldX = -lx * puckHeight * 1.15;+ const shadowWorldY = ly * puckHeight * 1.15; // screen Y inverted+ const cosR = Math.cos(-(rotateDeg * DEG2RAD));+ const sinR = Math.sin(-(rotateDeg * DEG2RAD));+ const shadowLocalX = shadowWorldX * cosR - shadowWorldY * sinR;+ const shadowLocalY = shadowWorldX * sinR + shadowWorldY * cosR;++ return {+ baseX,+ baseY,+ rx,+ ry,+ extrudeShift,+ rotateDeg,+ shadowLocalX,+ shadowLocalY,+ nz,+ };+}diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.tsindex 40a5a84..1d585a9 100644--- a/src/utils/transformEngine.ts+++ b/src/utils/transformEngine.ts@@ -103,11 +103,35 @@ export function evaluateMeshSurface(const rowIdx = Math.min(Math.floor(scaledV), rows - 2);const s = scaledV - rowIdx;- // Helper to safely get point with border clamping+ // Helper to get control point with linear phantom extrapolation beyond borders.+ // Clamping borders to edge points halves the boundary Catmull-Rom tangent and warps+ // even an unmodified mesh by ~1.5% across outer cells.const getP = (r: number, c: number): Point2D => {- const cr = Math.max(0, Math.min(rows - 1, r));- const cc = Math.max(0, Math.min(cols - 1, c));- return meshPoints[cr][cc];+ const getRowP = (rr: number, cc: number): Point2D => {+ if (cc < 0) {+ const a = meshPoints[rr][0];+ const b = meshPoints[rr][1];+ return { x: 2 * a.x - b.x, y: 2 * a.y - b.y };+ }+ if (cc >= cols) {+ const a = meshPoints[rr][cols - 1];+ const b = meshPoints[rr][cols - 2];+ return { x: 2 * a.x - b.x, y: 2 * a.y - b.y };+ }+ return meshPoints[rr][cc];+ };++ if (r < 0) {+ const a = getRowP(0, c);+ const b = getRowP(1, c);+ return { x: 2 * a.x - b.x, y: 2 * a.y - b.y };+ }+ if (r >= rows) {+ const a = getRowP(rows - 1, c);+ const b = getRowP(rows - 2, c);+ return { x: 2 * a.x - b.x, y: 2 * a.y - b.y };+ }+ return getRowP(r, c);};// Interpolate 4 row spans across u@@ -221,6 +245,10 @@ export function drawAffineTriangle(const f = dy0 - b * sx0 - d * sy0;ctx.save();+ ctx.imageSmoothingEnabled = true;+ if ('imageSmoothingQuality' in ctx) {+ ctx.imageSmoothingQuality = 'high';+ }ctx.beginPath();ctx.moveTo(expanded[0], expanded[1]);ctx.lineTo(expanded[2], expanded[3]);@@ -233,7 +261,7 @@ export function drawAffineTriangle(ctx.restore();}-const MESH_VERTEX_SHADER = `+const MESH_VERTEX_SHADER_ES1 = `attribute vec2 a_pos;attribute vec2 a_uv;uniform vec2 u_origin;@@ -246,12 +274,133 @@ const MESH_VERTEX_SHADER = `}`;-const MESH_FRAGMENT_SHADER = `+const MESH_FRAGMENT_SHADER_ES1 = `precision highp float;uniform sampler2D u_tex;+ uniform vec2 u_texSize;varying vec2 v_uv;++ vec4 cubicWeights(float f) {+ float f2 = f * f;+ float f3 = f2 * f;+ return vec4(+ -0.5 * f + f2 - 0.5 * f3,+ 1.0 - 2.5 * f2 + 1.5 * f3,+ 0.5 * f + 2.0 * f2 - 1.5 * f3,+ -0.5 * f2 + 0.5 * f3+ );+ }++ vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize, vec2 maxIdx) {+ float y = (clamp(base.y + dy, 0.0, maxIdx.y) + 0.5) * invSize.y;+ float x0 = (clamp(base.x - 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x1 = (clamp(base.x, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x2 = (clamp(base.x + 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x3 = (clamp(base.x + 2.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ return texture2D(u_tex, vec2(x0, y)) * wx.x+ + texture2D(u_tex, vec2(x1, y)) * wx.y+ + texture2D(u_tex, vec2(x2, y)) * wx.z+ + texture2D(u_tex, vec2(x3, y)) * wx.w;+ }+void main() {- gl_FragColor = texture2D(u_tex, v_uv);+ vec2 texPos = v_uv * u_texSize - 0.5;+ vec2 base = floor(texPos);+ vec2 f = texPos - base;+ vec4 wx = cubicWeights(f.x);+ vec4 wy = cubicWeights(f.y);+ vec2 invSize = 1.0 / u_texSize;+ vec2 maxIdx = u_texSize - 1.0;++ vec4 c = fetchRow(base, -1.0, wx, invSize, maxIdx) * wy.x+ + fetchRow(base, 0.0, wx, invSize, maxIdx) * wy.y+ + fetchRow(base, 1.0, wx, invSize, maxIdx) * wy.z+ + fetchRow(base, 2.0, wx, invSize, maxIdx) * wy.w;++ float a = clamp(c.a, 0.0, 1.0);+ vec3 rgb = clamp(c.rgb, vec3(0.0), vec3(a));+ gl_FragColor = vec4(rgb, a);+ }+`;++const MESH_VERTEX_SHADER_ES3 = `#version 300 es+ in vec2 a_pos;+ in vec2 a_uv;+ uniform vec2 u_origin;+ uniform vec2 u_size;+ out vec2 v_uv;+ void main() {+ vec2 norm = (a_pos - u_origin) / u_size;+ gl_Position = vec4(norm.x * 2.0 - 1.0, 1.0 - norm.y * 2.0, 0.0, 1.0);+ v_uv = a_uv;+ }+`;++const MESH_FRAGMENT_SHADER_ES3 = `#version 300 es+ precision highp float;+ uniform sampler2D u_tex;+ uniform vec2 u_texSize;+ in vec2 v_uv;+ out vec4 outColor;++ vec4 cubicWeights(float f) {+ float f2 = f * f;+ float f3 = f2 * f;+ return vec4(+ -0.5 * f + f2 - 0.5 * f3,+ 1.0 - 2.5 * f2 + 1.5 * f3,+ 0.5 * f + 2.0 * f2 - 1.5 * f3,+ -0.5 * f2 + 0.5 * f3+ );+ }++ vec4 fetchRow(vec2 base, float dy, vec4 wx, vec2 invSize, vec2 maxIdx) {+ float y = (clamp(base.y + dy, 0.0, maxIdx.y) + 0.5) * invSize.y;+ float x0 = (clamp(base.x - 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x1 = (clamp(base.x, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x2 = (clamp(base.x + 1.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ float x3 = (clamp(base.x + 2.0, 0.0, maxIdx.x) + 0.5) * invSize.x;+ return texture(u_tex, vec2(x0, y)) * wx.x+ + texture(u_tex, vec2(x1, y)) * wx.y+ + texture(u_tex, vec2(x2, y)) * wx.z+ + texture(u_tex, vec2(x3, y)) * wx.w;+ }++ vec4 sampleBicubic(vec2 uv, vec2 invSize, vec2 maxIdx) {+ vec2 texPos = uv * u_texSize - 0.5;+ vec2 base = floor(texPos);+ vec2 f = texPos - base;+ vec4 wx = cubicWeights(f.x);+ vec4 wy = cubicWeights(f.y);++ vec4 c = fetchRow(base, -1.0, wx, invSize, maxIdx) * wy.x+ + fetchRow(base, 0.0, wx, invSize, maxIdx) * wy.y+ + fetchRow(base, 1.0, wx, invSize, maxIdx) * wy.z+ + fetchRow(base, 2.0, wx, invSize, maxIdx) * wy.w;++ float a = clamp(c.a, 0.0, 1.0);+ return vec4(clamp(c.rgb, vec3(0.0), vec3(a)), a);+ }++ void main() {+ vec2 invSize = 1.0 / u_texSize;+ vec2 maxIdx = u_texSize - 1.0;+ vec2 du = dFdx(v_uv);+ vec2 dv = dFdy(v_uv);+ float footprint = max(length(du * u_texSize), length(dv * u_texSize));++ if (footprint <= 1.35) {+ outColor = sampleBicubic(v_uv, invSize, maxIdx);+ } else {+ vec4 acc =+ sampleBicubic(v_uv + du * -0.375 + dv * -0.125, invSize, maxIdx) ++ sampleBicubic(v_uv + du * 0.125 + dv * -0.375, invSize, maxIdx) ++ sampleBicubic(v_uv + du * 0.375 + dv * 0.125, invSize, maxIdx) ++ sampleBicubic(v_uv + du * -0.125 + dv * 0.375, invSize, maxIdx);+ vec4 res = acc * 0.25;+ float a = clamp(res.a, 0.0, 1.0);+ outColor = vec4(clamp(res.rgb, vec3(0.0), vec3(a)), a);+ }}`;@@ -266,6 +415,7 @@ class WebGlMeshWarpRenderer {private uvLoc = -1;private originLoc: WebGLUniformLocation | null = null;private sizeLoc: WebGLUniformLocation | null = null;+ private texSizeLoc: WebGLUniformLocation | null = null;private texLoc: WebGLUniformLocation | null = null;private maxDim = 0;private vertexData = new Float32Array(0);@@ -282,6 +432,46 @@ class WebGlMeshWarpRenderer {this.init();}+ private compileProgram(+ gl: WebGLRenderingContext,+ vsSrc: string,+ fsSrc: string+ ): WebGLProgram | null {+ const vs = gl.createShader(gl.VERTEX_SHADER);+ const fs = gl.createShader(gl.FRAGMENT_SHADER);+ if (!vs || !fs) return null;++ gl.shaderSource(vs, vsSrc);+ gl.compileShader(vs);+ gl.shaderSource(fs, fsSrc);+ gl.compileShader(fs);+ if (+ !gl.getShaderParameter(vs, gl.COMPILE_STATUS) ||+ !gl.getShaderParameter(fs, gl.COMPILE_STATUS)+ ) {+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ return null;+ }++ const program = gl.createProgram();+ if (!program) {+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ return null;+ }+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ gl.deleteProgram(program);+ return null;+ }+ return program;+ }+private init(): void {this.ready = false;if (typeof document === 'undefined') return;@@ -295,42 +485,14 @@ class WebGlMeshWarpRenderer {stencil: false,preserveDrawingBuffer: false,};- const gl = (canvas.getContext('webgl2', attrs) ||- canvas.getContext('webgl', attrs)) as WebGLRenderingContext | null;+ const gl2 = canvas.getContext('webgl2', attrs) as WebGL2RenderingContext | null;+ const gl = (gl2 || canvas.getContext('webgl', attrs)) as WebGLRenderingContext | null;if (!gl) return;- const vs = gl.createShader(gl.VERTEX_SHADER);- const fs = gl.createShader(gl.FRAGMENT_SHADER);- if (!vs || !fs) return;-- gl.shaderSource(vs, MESH_VERTEX_SHADER);- gl.compileShader(vs);- gl.shaderSource(fs, MESH_FRAGMENT_SHADER);- gl.compileShader(fs);- if (- !gl.getShaderParameter(vs, gl.COMPILE_STATUS) ||- !gl.getShaderParameter(fs, gl.COMPILE_STATUS)- ) {- gl.deleteShader(vs);- gl.deleteShader(fs);- return;- }-- const program = gl.createProgram();- if (!program) {- gl.deleteShader(vs);- gl.deleteShader(fs);- return;- }- gl.attachShader(program, vs);- gl.attachShader(program, fs);- gl.linkProgram(program);- gl.deleteShader(vs);- gl.deleteShader(fs);- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {- gl.deleteProgram(program);- return;- }+ const program =+ (gl2 ? this.compileProgram(gl, MESH_VERTEX_SHADER_ES3, MESH_FRAGMENT_SHADER_ES3) : null) ||+ this.compileProgram(gl, MESH_VERTEX_SHADER_ES1, MESH_FRAGMENT_SHADER_ES1);+ if (!program) return;const vertexBuffer = gl.createBuffer();const texture = gl.createTexture();@@ -356,6 +518,7 @@ class WebGlMeshWarpRenderer {this.uvLoc = uvLoc;this.originLoc = gl.getUniformLocation(program, 'u_origin');this.sizeLoc = gl.getUniformLocation(program, 'u_size');+ this.texSizeLoc = gl.getUniformLocation(program, 'u_texSize');this.texLoc = gl.getUniformLocation(program, 'u_tex');this.maxDim = Math.min(maxTex || 4096, maxVpDim || 4096);this.ready = true;@@ -382,7 +545,7 @@ class WebGlMeshWarpRenderer {const sw = sourceCanvas.width;const sh = sourceCanvas.height;- if (sw > this.maxDim || sh > this.maxDim) return false;+ if (sw <= 0 || sh <= 0 || sw > this.maxDim || sh > this.maxDim) return false;let minX = Infinity;let minY = Infinity;@@ -412,11 +575,11 @@ class WebGlMeshWarpRenderer {typeof ctx.getTransform === 'function') {const m = ctx.getTransform();- if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && m.e === 0 && m.f === 0) {- originX = Math.max(0, originX);- originY = Math.max(0, originY);- endX = Math.min(ctx.canvas.width, endX);- endY = Math.min(ctx.canvas.height, endY);+ if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1) {+ originX = Math.max(Math.floor(-m.e), originX);+ originY = Math.max(Math.floor(-m.f), originY);+ endX = Math.min(Math.ceil(ctx.canvas.width - m.e), endX);+ endY = Math.min(Math.ceil(ctx.canvas.height - m.f), endY);}}@@ -471,12 +634,13 @@ class WebGlMeshWarpRenderer {gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sourceCanvas);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);gl.uniform1i(this.texLoc, 0);gl.uniform2f(this.originLoc, originX, originY);gl.uniform2f(this.sizeLoc, outW, outH);+ gl.uniform2f(this.texSizeLoc, sw, sh);gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);gl.bufferData(gl.ARRAY_BUFFER, buf.subarray(0, neededFloats), gl.STREAM_DRAW);@@ -630,8 +794,8 @@ export function createDefaultPerspectiveQuad(const rx = px - cx;const ry = py - cy;return {- x: Math.round(cx + rx * cos - ry * sin),- y: Math.round(cy + rx * sin + ry * cos),+ x: cx + rx * cos - ry * sin,+ y: cy + rx * sin + ry * cos,};};@@ -645,6 +809,7 @@ export function createDefaultPerspectiveQuad(/*** Creates a default grid of (rows x cols) control points interpolated from 4 corners.+ * Preserves exact floating-point coordinates so an unmodified mesh is a lossless identity warp.*/export function createDefaultMeshPoints(quad: [Point2D, Point2D, Point2D, Point2D],@@ -662,7 +827,7 @@ export function createDefaultMeshPoints(// Bilinear interpolation across cornersconst x = (1 - u) * (1 - v) * q0.x + u * (1 - v) * q1.x + u * v * q2.x + (1 - u) * v * q3.x;const y = (1 - u) * (1 - v) * q0.y + u * (1 - v) * q1.y + u * v * q2.y + (1 - u) * v * q3.y;- row.push({ x: Math.round(x), y: Math.round(y) });+ row.push({ x, y });}points.push(row);}@@ -670,6 +835,26 @@ export function createDefaultMeshPoints(return points;}+/**+ * Computes adaptive per-cell mesh subdivision count to prevent polygonal faceting+ * and UV shearing on large or sharply curved warps.+ */+export function computeMeshSubdivisions(+ sourceWidth: number,+ sourceHeight: number,+ meshPoints: Point2D[][],+ highQuality: boolean+): number {+ const rows = Math.max(2, meshPoints.length);+ const cols = Math.max(2, meshPoints[0]?.length || 2);+ const maxSpan = Math.max(sourceWidth, sourceHeight);+ const cells = Math.max(1, Math.min(rows - 1, cols - 1));+ const targetPxPerSub = highQuality ? 20 : 32;+ const minSub = highQuality ? 10 : 6;+ const maxSub = highQuality ? 20 : 12;+ return Math.max(minSub, Math.min(maxSub, Math.ceil(maxSpan / (cells * targetPxPerSub))));+}+/*** Calculates tight bounding box of a perspective quad or mesh point set.*/@@ -697,12 +882,72 @@ export function getPointsBounds(points: Point2D[]): {if (p.y > maxY) maxY = p.y;}+ const minXF = Math.floor(minX);+ const minYF = Math.floor(minY);+ const maxXC = Math.ceil(maxX);+ const maxYC = Math.ceil(maxY);++ return {+ minX: minXF,+ minY: minYF,+ maxX: maxXC,+ maxY: maxYC,+ width: Math.max(1, maxXC - minXF),+ height: Math.max(1, maxYC - minYF),+ };+}++/**+ * Calculates tight bounding box of an evaluated Catmull-Rom mesh surface,+ * preventing spline overshoot clipping in preview and final commit.+ */+export function getMeshSurfaceBounds(+ meshPoints: Point2D[][],+ subPerCell = 6+): {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+ width: number;+ height: number;+} {+ const rows = meshPoints.length;+ const cols = meshPoints[0]?.length || 0;+ if (rows < 2 || cols < 2) {+ return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };+ }++ const totalRows = (rows - 1) * subPerCell;+ const totalCols = (cols - 1) * subPerCell;+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (let j = 0; j <= totalRows; j++) {+ const v = j / totalRows;+ for (let i = 0; i <= totalCols; i++) {+ const u = i / totalCols;+ const p = evaluateMeshSurface(meshPoints, u, v);+ if (p.x < minX) minX = p.x;+ if (p.x > maxX) maxX = p.x;+ if (p.y < minY) minY = p.y;+ if (p.y > maxY) maxY = p.y;+ }+ }++ const minXF = Math.floor(minX);+ const minYF = Math.floor(minY);+ const maxXC = Math.ceil(maxX);+ const maxYC = Math.ceil(maxY);+return {- minX: Math.floor(minX),- minY: Math.floor(minY),- maxX: Math.ceil(maxX),- maxY: Math.ceil(maxY),- width: Math.max(1, Math.ceil(maxX - minX)),- height: Math.max(1, Math.ceil(maxY - minY)),+ minX: minXF,+ minY: minYF,+ maxX: maxXC,+ maxY: maxYC,+ width: Math.max(1, maxXC - minXF),+ height: Math.max(1, maxYC - minYF),};}diff --git a/src/utils/vectorEngine.ts b/src/utils/vectorEngine.tsindex 22386a7..1133b02 100644--- a/src/utils/vectorEngine.ts+++ b/src/utils/vectorEngine.ts@@ -7,6 +7,12 @@*/import { VectorKnot, VectorStroke } from '../types/editor';+import {+ computeBezierPathBounds,+ isUniformWidthBezier,+ tessellateBezierStroke,+ traceBezierPathOnContext,+} from './bezierEngine';export interface Point2D {x: number;@@ -114,8 +120,12 @@ export function evaluateCatmullRom(/*** Discretize a spline stroke into fine polyline segments for accurate rendering and intersection checks.+ * Supports both Catmull-Rom freehand strokes and true cubic Bézier paths with explicit handles.*/export function tessellateStroke(stroke: VectorStroke, stepsPerSegment = 6): VectorKnot[] {+ if (stroke.curveType === 'bezier') {+ return tessellateBezierStroke(stroke, stepsPerSegment);+ }const knots = stroke.knots;if (knots.length === 0) return [];if (knots.length === 1) return [knots[0]];@@ -142,9 +152,13 @@ export function tessellateStroke(stroke: VectorStroke, stepsPerSegment = 6): Vec}/**- * Compute axis-aligned bounding box of a list of knots.+ * Compute axis-aligned bounding box of a list of knots (uses analytical cubic extrema for Bézier paths).*/-export function computeStrokeBounds(knots: VectorKnot[]): {+export function computeStrokeBounds(+ knots: VectorKnot[],+ closed = false,+ curveType?: 'catmull-rom' | 'bezier'+): {minX: number;minY: number;maxX: number;@@ -153,6 +167,13 @@ export function computeStrokeBounds(knots: VectorKnot[]): {if (knots.length === 0) {return { minX: 0, minY: 0, maxX: 0, maxY: 0 };}+ const hasBezierHandles =+ curveType === 'bezier' ||+ knots.some((k) => Boolean(k.handleIn) || Boolean(k.handleOut));+ if (hasBezierHandles) {+ return computeBezierPathBounds(knots, closed);+ }+let minX = Infinity;let minY = Infinity;let maxX = -Infinity;@@ -594,8 +615,9 @@ export function applyVectorEraser(}/**- * Render a single vector stroke to a Canvas 2D context using Catmull-Rom tessellation- * with pressure-sensitive stroke width and smooth round caps.+ * Render a single vector stroke to a Canvas 2D context.+ * True cubic Bézier paths (`curveType === 'bezier'`) use native `ctx.bezierCurveTo()`+ * for filled paths and uniform-width strokes, and adaptive cubic tessellation for variable widths.*/export function renderVectorStroke(ctx: CanvasRenderingContext2D,@@ -603,15 +625,52 @@ export function renderVectorStroke(): void {if (stroke.deleted || stroke.knots.length < 2) return;- const tessellated = tessellateStroke(stroke);- if (tessellated.length < 2) return;-ctx.save();ctx.lineCap = 'round';ctx.lineJoin = 'round';+ ctx.globalAlpha = stroke.opacity ?? 1.0;++ if (stroke.curveType === 'bezier') {+ const closed = Boolean(stroke.closed);+ if (closed && stroke.fillColor) {+ traceBezierPathOnContext(ctx, stroke.knots, true);+ ctx.fillStyle = stroke.fillColor;+ ctx.fill();+ }++ if (stroke.baseWidth > 0 && stroke.color && stroke.color !== 'none') {+ ctx.strokeStyle = stroke.color;+ if (isUniformWidthBezier(stroke.knots)) {+ traceBezierPathOnContext(ctx, stroke.knots, closed);+ ctx.lineWidth = Math.max(0.5, stroke.knots[0]?.width ?? stroke.baseWidth);+ ctx.stroke();+ ctx.restore();+ return;+ }+ const tessellated = tessellateBezierStroke(stroke, 8);+ for (let i = 0; i < tessellated.length - 1; i++) {+ const k1 = tessellated[i];+ const k2 = tessellated[i + 1];+ ctx.lineWidth = Math.max(0.5, (k1.width + k2.width) * 0.5);+ ctx.beginPath();+ ctx.moveTo(k1.x, k1.y);+ ctx.lineTo(k2.x, k2.y);+ ctx.stroke();+ }+ }++ ctx.restore();+ return;+ }++ const tessellated = tessellateStroke(stroke);+ if (tessellated.length < 2) {+ ctx.restore();+ return;+ }+ctx.strokeStyle = stroke.color;ctx.fillStyle = stroke.color;- ctx.globalAlpha = stroke.opacity ?? 1.0;for (let i = 0; i < tessellated.length - 1; i++) {const k1 = tessellated[i];@@ -764,10 +823,14 @@ export function reshapeVectorLine(const dist = Math.hypot(k.x - cursorPos.x, k.y - cursorPos.y);if (dist >= radius) return k;const factor = Math.cos((dist / radius) * (Math.PI / 2)); // Smooth cosine falloff+ const dx = delta.x * factor;+ const dy = delta.y * factor;return {...k,- x: k.x + delta.x * factor,- y: k.y + delta.y * factor,+ x: k.x + dx,+ y: k.y + dy,+ handleIn: k.handleIn ? { x: k.handleIn.x + dx, y: k.handleIn.y + dy } : k.handleIn,+ handleOut: k.handleOut ? { x: k.handleOut.x + dx, y: k.handleOut.y + dy } : k.handleOut,};});}@@ -776,7 +839,7 @@ export function reshapeVectorLine(...stroke,baseWidth,knots,- bounds: computeStrokeBounds(knots),+ bounds: computeStrokeBounds(knots, Boolean(stroke.closed), stroke.curveType),};}@@ -816,17 +879,21 @@ export function pinchVectorStroke(const dist = Math.hypot(k.x - point.x, k.y - point.y);if (dist >= radius) return k;const factor = 0.5 * (1 + Math.cos(Math.PI * dist * invRadius));+ const dx = delta.x * factor;+ const dy = delta.y * factor;return {...k,- x: k.x + delta.x * factor,- y: k.y + delta.y * factor,+ x: k.x + dx,+ y: k.y + dy,+ handleIn: k.handleIn ? { x: k.handleIn.x + dx, y: k.handleIn.y + dy } : k.handleIn,+ handleOut: k.handleOut ? { x: k.handleOut.x + dx, y: k.handleOut.y + dy } : k.handleOut,};});return {...stroke,knots: updatedKnots,- bounds: computeStrokeBounds(updatedKnots),+ bounds: computeStrokeBounds(updatedKnots, Boolean(stroke.closed), stroke.curveType),};}