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
pre103
sora6f2861b4a4a0
diff --git a/src/App.tsx b/src/App.tsxindex 5a3b669..cf9b5ef 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -24,7 +24,7 @@ import {useVectorDrawing,} from './hooks/drawing';import { useCanvasNavigation } from './hooks/useCanvasNavigation';-import { useLayerManager } from './hooks/useLayerManager';+import { createLayerTreeSnapshotDelta, useLayerManager } from './hooks/useLayerManager';import { useCollabSync } from './hooks/useCollabSync';import { useTonalAndFilterActions } from './hooks/useTonalAndFilterActions';import { useAppMenuSections } from './hooks/useAppMenuSections';@@ -32,8 +32,10 @@ import { useExternalFileDrop } from './hooks/useExternalFileDrop';import {autoActionStoreActions,documentStoreActions,+ scene3DBridge,selectHasOpenDocument,uiStoreActions,+ use3DStore,useDocumentStore,useToolStore,useUiStore,@@ -58,6 +60,9 @@ export function App() {const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);const animationTimeline = useDocumentStore((s) => s.animationTimeline);const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);+ const is3DLayerOpen = useUiStore((s) => s.is3DLayerOpen);+ const canUndo3D = use3DStore((s) => s.canUndo3D);+ const canRedo3D = use3DStore((s) => s.canRedo3D);const appView = useUiStore((s) => s.appView);// Delayed silent startup check for desktop Tauri updates (never blocks startup or crash recovery)@@ -86,6 +91,7 @@ export function App() {dimensions,activeSessionId: activeDocumentId,tileGrid: activeTileGrid,+ pushHistoryStepRef,});const activeDoc = documents.find((d) => d.id === activeDocumentId);@@ -108,6 +114,8 @@ export function App() {const handleAddAnimationCel = useCallback((frameIndex: number) => {+ const beforeLayers = layerMgr.layers;+ const beforeActiveLayerId = layerMgr.activeLayerId;const newLayerId = `layer-cel-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;const newCelLayer: LayerItem = {id: newLayerId,@@ -123,8 +131,23 @@ export function App() {activeTileGrid.setLayerFormat(newLayerId, 'color-32bit');activeTileGrid.markLayerIngested(newLayerId);- layerMgr.setLayers((prev) => [newCelLayer, ...prev]);+ const nextLayers = [newCelLayer, ...beforeLayers];+ layerMgr.setLayers(nextLayers);layerMgr.setActiveLayerId(newLayerId);+ pushHistoryStepRef.current?.(+ 'layer',+ `Add Cel Frame ${frameIndex + 1}`,+ null,+ null,+ newLayerId,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ false,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, newLayerId)+ );const currentTl = activeAnimationTimeline || createDefaultAnimationTimeline(layerMgr.layers);handleUpdateAnimationTimeline(setFrameCel(currentTl, frameIndex, newLayerId));@@ -316,6 +339,15 @@ export function App() {flushPendingHistoryTasksRef.current = drawing.flushPendingHistoryTasks;const handleUndo = useCallback(() => {+ if (+ useUiStore.getState().is3DLayerOpen &&+ useToolStore.getState().tool === '3d' &&+ scene3DBridge.canUndo?.()+ ) {+ if (scene3DBridge.undo?.()) {+ return;+ }+ }if (selectionTools.transformSession?.active) {selectionTools.handleCancelTransform();return;@@ -336,6 +368,19 @@ export function App() {}}, [collab.isConnected, collab.myPeer.id, drawing, selectionTools]);+ const handleRedo = useCallback(() => {+ if (+ useUiStore.getState().is3DLayerOpen &&+ useToolStore.getState().tool === '3d' &&+ scene3DBridge.canRedo?.()+ ) {+ if (scene3DBridge.redo?.()) {+ return;+ }+ }+ drawing.redo();+ }, [drawing]);+const getCanvasCoords = useCallback((e: React.PointerEvent<HTMLElement> | PointerEvent) => {if (!nav.viewportRef.current) return { x: 0, y: 0 };@@ -364,6 +409,7 @@ export function App() {activeLayerId: layerMgr.activeLayerId,selectedLayerIds: layerMgr.selectedLayerIds,selection: selectionTools.selection,+ onCommitFloatingSelection: selectionTools.handleCommitFloatingSelection,flushPendingHistoryTasks: drawing.flushPendingHistoryTasks,isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,getEffectiveOpacity: layerMgr.getEffectiveOpacity,@@ -492,12 +538,38 @@ export function App() {const handleToggleReferenceLayer = useCallback((layerId: string) => {- layerMgr.setLayers((prev) =>- prev.map((l) => (l.id === layerId ? { ...l, isReference: !l.isReference } : l))+ const beforeLayers = layerMgr.layers;+ const nextLayers = beforeLayers.map((l) =>+ l.id === layerId ? { ...l, isReference: !l.isReference } : l+ );+ layerMgr.setLayers(nextLayers);+ pushHistoryStepRef.current?.(+ 'layer',+ 'Toggle Reference Layer',+ null,+ null,+ layerId,+ undefined,+ undefined,+ undefined,+ undefined,+ undefined,+ false,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, layerMgr.activeLayerId, layerMgr.activeLayerId));documentStoreActions.markDocumentDirty(activeDocumentId, true);},- [activeDocumentId, layerMgr.setLayers]+ [activeDocumentId, layerMgr]+ );++ const handleToggleTone = useCallback(+ (layerId: string) => {+ if (selectionTools.selection?.floating) {+ selectionTools.handleCommitFloatingSelection();+ }+ layerMgr.toggleTone(layerId, selectionTools.selection);+ },+ [layerMgr.toggleTone, selectionTools]);const handleMergeDown = useCallback(() => {@@ -511,6 +583,26 @@ export function App() {}}, [layerMgr.mergeDown, activeDocumentId, showToast]);+ const handleMergeFolder = useCallback(+ (folderId?: string) => {+ if (selectionTools.selection?.floating) {+ selectionTools.handleCommitFloatingSelection();+ }+ if (selectionTools.transformSession?.active) {+ selectionTools.handleApplyTransform();+ }+ const res = layerMgr.mergeFolder(folderId);+ if (res) {+ documentStoreActions.markDocumentDirty(activeDocumentId, true);+ autoActionStoreActions.recordStep('merge-folder', 'Merge Folder');+ showToast('Merged folder into layer');+ } else {+ showToast('Cannot merge folder: select an unlocked folder');+ }+ },+ [layerMgr.mergeFolder, activeDocumentId, selectionTools, showToast]+ );+const handleAddDefaultFrameFolder = useCallback(() => {drawing.flushPendingHistoryTasks();const dpi = dimensions.dpi ?? 600;@@ -538,14 +630,13 @@ export function App() {(layerId: string) => {const ok = layerMgr.rasterizeLayer(layerId);if (ok) {- drawing.pushHistoryStep('layer-convert', 'Rasterize Layer', null, null, layerId);autoActionStoreActions.recordStep('rasterize-layer', 'Rasterize Layer');showToast('Layer rasterized');} else {showToast('Only Text, Speech Balloon, or Vector layers can be rasterized');}},- [layerMgr.rasterizeLayer, drawing.pushHistoryStep, showToast]+ [layerMgr.rasterizeLayer, showToast]);// Auto-Action Recording Wrappers for common layer/filter commands@@ -617,6 +708,8 @@ export function App() {async (action: AutoAction) => {if (!hasOpenDocument) return;autoActionStoreActions.setIsPlaying(true);+ const beforeAutoLayers = layerMgr.layers;+ const beforeAutoActiveId = layerMgr.activeLayerId;let currentLayerId = layerMgr.activeLayerId;let groupStartSnapshot: Map<string, TileSnapshotEntry> | null = null;let groupTargetLayerId = currentLayerId;@@ -625,12 +718,16 @@ export function App() {const ctx: AutoActionExecutionContext = {getActiveLayerId: () => currentLayerId,createLayer: (name, type = 'raster') => {- const created = layerMgr.addLayer(type, undefined, name, undefined, true);+ const created = layerMgr.runWithoutLayerHistory(() =>+ layerMgr.addLayer(type, undefined, name, undefined, true)+ );currentLayerId = created.id;return created.id;},createFolder: (name) => {- const created = layerMgr.addLayer('folder', undefined, name, undefined, true);+ const created = layerMgr.runWithoutLayerHistory(() =>+ layerMgr.addLayer('folder', undefined, name, undefined, true)+ );currentLayerId = created.id;return created.id;},@@ -656,35 +753,45 @@ export function App() {currentLayerId = folder.id;return folder.id;},- duplicateLayer: (id) => layerMgr.duplicateLayer(id),- deleteLayer: (id) => collab.handleDeleteLayer(id),- renameLayer: (id, name) => layerMgr.renameLayer(id, name),- setBlendMode: (id, blendMode) => layerMgr.setBlendMode(id, blendMode),- setOpacity: (id, opacity) => layerMgr.setOpacity(id, opacity),- setVisibility: (id) => layerMgr.toggleVisibility(id),+ duplicateLayer: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.duplicateLayer(id)),+ deleteLayer: (id) => layerMgr.runWithoutLayerHistory(() => collab.handleDeleteLayer(id)),+ renameLayer: (id, name) => layerMgr.runWithoutLayerHistory(() => layerMgr.renameLayer(id, name)),+ setBlendMode: (id, blendMode) =>+ layerMgr.runWithoutLayerHistory(() => layerMgr.setBlendMode(id, blendMode)),+ setOpacity: (id, opacity) =>+ layerMgr.runWithoutLayerHistory(() => layerMgr.setOpacity(id, opacity)),+ setVisibility: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.toggleVisibility(id)),setClipping: (id, clipped) => {const existing = layerMgr.layers.find((l) => l.id === id);if (clipped === undefined || Boolean(existing?.clipped) !== clipped) {- layerMgr.toggleClipping(id);+ layerMgr.runWithoutLayerHistory(() => layerMgr.toggleClipping(id));}},- setAlphaLock: (id) => layerMgr.toggleAlphaLock(id),- setExpressionColor: (id, mode) => layerMgr.setLayerExpressionColor(id, mode),+ setAlphaLock: (id) => layerMgr.runWithoutLayerHistory(() => layerMgr.toggleAlphaLock(id)),+ setExpressionColor: (id, mode) =>+ layerMgr.runWithoutLayerHistory(() => layerMgr.setLayerExpressionColor(id, mode)),setLayerColor: (id, enabled, color) => {- if (color) layerMgr.setLayerColor(id, color);- const existing = layerMgr.layers.find((l) => l.id === id);- if (Boolean(existing?.layerColorEnabled) !== enabled) {- layerMgr.toggleLayerColor(id);- }+ layerMgr.runWithoutLayerHistory(() => {+ if (color) layerMgr.setLayerColor(id, color);+ const existing = layerMgr.layers.find((l) => l.id === id);+ if (Boolean(existing?.layerColorEnabled) !== enabled) {+ layerMgr.toggleLayerColor(id);+ }+ });},setTone: (id, enabled, opts) => {- const existing = layerMgr.layers.find((l) => l.id === id);- if (Boolean(existing?.toneEnabled) !== enabled) {- layerMgr.toggleTone(id);- }- if (opts?.frequency !== undefined) layerMgr.setToneFrequency(id, opts.frequency);- if (opts?.density !== undefined) layerMgr.setToneDensity(id, opts.density);- if (opts?.angle !== undefined) layerMgr.setToneAngle(id, opts.angle);+ layerMgr.runWithoutLayerHistory(() => {+ const existing = layerMgr.layers.find((l) => l.id === id);+ if (Boolean(existing?.toneEnabled) !== enabled) {+ layerMgr.toggleTone(id);+ }+ if (opts?.frequency !== undefined) layerMgr.setToneFrequency(id, opts.frequency);+ if (opts?.density !== undefined) {+ layerMgr.setToneDensityType(id, 'specified');+ layerMgr.setToneDensity(id, opts.density);+ }+ if (opts?.angle !== undefined) layerMgr.setToneAngle(id, opts.angle);+ });},fillLayer: (id, color) => {if (!groupStartSnapshot) {@@ -705,10 +812,13 @@ export function App() {layerMgr.updateLayerThumbnail(id, true);},mergeDown: () => {- layerMgr.mergeDown();+ layerMgr.runWithoutLayerHistory(() => layerMgr.mergeDown());+ },+ mergeFolder: (folderId) => {+ layerMgr.runWithoutLayerHistory(() => layerMgr.mergeFolder(folderId));},rasterizeLayer: (id) => {- layerMgr.rasterizeLayer(id);+ layerMgr.runWithoutLayerHistory(() => layerMgr.rasterizeLayer(id));},applyFilter: (type, params) => {tonalActions.handleApplyFilter(@@ -722,8 +832,21 @@ export function App() {endHistoryGroup: (label) => {const targetId = groupTargetLayerId || currentLayerId;const tileDeltas = groupStartSnapshot- ? activeTileGrid.computeDeltasFromSnapshot(groupStartSnapshot, targetId)+ ? activeTileGrid.computeDeltasFromSnapshot(groupStartSnapshot, targetId, {+ x: 0,+ y: 0,+ width: dimensions.width,+ height: dimensions.height,+ }): undefined;+ const finalTreeDelta =+ groupLayerTreeDelta ??+ createLayerTreeSnapshotDelta(+ beforeAutoLayers,+ layerMgr.layers,+ beforeAutoActiveId,+ currentLayerId+ );drawing.pushHistoryStep('auto-action',label,@@ -736,7 +859,7 @@ export function App() {undefined,undefined,undefined,- groupLayerTreeDelta+ finalTreeDelta);},};@@ -959,7 +1082,7 @@ export function App() {penTools.handlePenPointerUp(e);return;}- if (selectionTools.handleSelectionPointerUp(pt)) return;+ if (selectionTools.handleSelectionPointerUp(pt, e)) return;shapeFillTools.handleShapeFillPointerUp(e, pt);},[drawing, vectorTools, gradientTools, retouchTools, penTools, getCanvasCoords, selectionTools, shapeFillTools]@@ -973,8 +1096,8 @@ export function App() {activeLayer: layerMgr.activeLayer,activeLayerId: layerMgr.activeLayerId,selection: selectionTools.selection,- canUndo: drawing.canUndo,- canRedo: drawing.canRedo,+ canUndo: drawing.canUndo || (is3DLayerOpen && canUndo3D),+ canRedo: drawing.canRedo || (is3DLayerOpen && canRedo3D),flipX: nav.flipX,flipY: nav.flipY,isWebtoonMode,@@ -984,7 +1107,7 @@ export function App() {activeAnimationTimeline,clearCanvas: drawing.clearCanvas,handleUndo,- redo: drawing.redo,+ redo: handleRedo,handleTriggerOpenFile: docLifecycle.handleTriggerOpenFile,handleTriggerImport3DFile: docLifecycle.handleTriggerImport3DFile,handleSave: docLifecycle.handleSave,@@ -1011,6 +1134,8 @@ export function App() {handleContractSelection: selectionTools.handleContractSelection,handleFeatherSelection: selectionTools.handleFeatherSelection,handleAddLayer: handleRecordedAddLayer,+ handleFillScreentone: tonalActions.handleFillScreentone,+ toggleTone: handleToggleTone,handleOpenAdjustmentModal: tonalActions.handleOpenAdjustmentModal,addLayerMask: layerMgr.addLayerMask,removeLayerMask: layerMgr.removeLayerMask,@@ -1018,6 +1143,7 @@ export function App() {toggleMaskLinked: layerMgr.toggleMaskLinked,duplicateLayer: handleRecordedDuplicateLayer,handleMergeDown,+ handleMergeFolder,handleOpenLayerStylesModal: tonalActions.handleOpenLayerStylesModal,toggleLayerColor: layerMgr.toggleLayerColor,handleConvertLayer: tonalActions.handleConvertLayer,@@ -1065,7 +1191,7 @@ export function App() {startZoomDrag: nav.startZoomDrag,onSampleColor: shapeFillTools.handleSampleColor,onUndo: handleUndo,- onRedo: drawing.redo,+ onRedo: handleRedo,onFlipHorizontal: nav.toggleFlipHorizontal,isHovering: drawing.isHovering,cursorPos: drawing.cursorPos,@@ -1175,7 +1301,7 @@ export function App() {penTools.handleCancelPenPath,penTools.handleClosePenPath,handleUndo,- drawing.redo,+ handleRedo,activeAnimationTimeline,handleUpdateAnimationTimeline,handleAddAnimationCel,@@ -1202,10 +1328,10 @@ export function App() {handleFileInputChange={docLifecycle.handleFileInputChange}handlePasteFileInputChange={docLifecycle.handlePasteFileInputChange}handleImport3DFileInputChange={docLifecycle.handleImport3DFileInputChange}- canUndo={drawing.canUndo}- canRedo={drawing.canRedo}+ canUndo={drawing.canUndo || (is3DLayerOpen && canUndo3D)}+ canRedo={drawing.canRedo || (is3DLayerOpen && canRedo3D)}handleUndo={handleUndo}- redo={drawing.redo}+ redo={handleRedo}zoom={nav.zoom}zoomIn={nav.zoomIn}zoomOut={nav.zoomOut}@@ -1259,7 +1385,7 @@ export function App() {moveLayerToFolder={layerMgr.moveLayerToFolder}reorderLayers={layerMgr.reorderLayers}handleToggleReferenceLayer={handleToggleReferenceLayer}- toggleTone={layerMgr.toggleTone}+ toggleTone={handleToggleTone}setToneFrequency={layerMgr.setToneFrequency}setToneAngle={layerMgr.setToneAngle}setToneDotShape={layerMgr.setToneDotShape}@@ -1281,6 +1407,7 @@ export function App() {handleOpenLayerStylesModal={tonalActions.handleOpenLayerStylesModal}onEditVectorLayer={shapeFillTools.openLayerForEditing}onRasterizeLayer={handleRasterizeLayer}+ onMergeFolder={handleMergeFolder}onPlayAutoAction={handlePlayAutoAction}externalFileDropTarget={externalFileDrop.activeDropTarget}>@@ -1311,7 +1438,7 @@ export function App() {isSelectionPenDrawingRef={selectionTools.isSelectionPenDrawingRef}isPipetteSamplingRef={shapeFillTools.isPipetteSamplingRef}handleUndo={handleUndo}- redo={drawing.redo}+ redo={handleRedo}handleAddLayer={collab.handleAddLayer}handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}handleSave={docLifecycle.handleSave}diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsxindex 14ba56c..4add6ca 100644--- a/src/components/AppShell.tsx+++ b/src/components/AppShell.tsx@@ -28,11 +28,14 @@ import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';import { TextPlacementSession, FrameDragPreview } from '../hooks/drawing/useShapeAndFillTools';import { AutoAction } from '../utils/autoActionEngine';import { ExternalFileDropTarget } from '../utils/fileDropImport';+import { HalftoneDotShape } from '../utils/screentoneEngine';import {documentStoreActions,selectHasOpenDocument,+ store3DActions,toolStoreActions,uiStoreActions,+ use3DStore,useDocumentStore,useToolStore,useUiStore,@@ -169,6 +172,11 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((propconst handleClose3DLayer = useCallback(() => {uiStoreActions.set3DLayerOpen(false, null);+ const prevTool = use3DStore.getState().previousToolBefore3D;+ store3DActions.resetSceneMeta();+ if (useToolStore.getState().tool === '3d') {+ toolStoreActions.selectTool((prevTool as import('../types/editor').ToolType) || 'brush');+ }}, []);const handleToggleWebtoon = useCallback(() => {@@ -441,7 +449,7 @@ export interface AppShellProps {toggleTone: (id: string) => void;setToneFrequency: (id: string, frequency: number) => void;setToneAngle: (id: string, angle: number) => void;- setToneDotShape: (id: string, dotShape: 'circle' | 'euclidean') => void;+ setToneDotShape: (id: string, dotShape: HalftoneDotShape) => void;setToneDensity: (id: string, density: number) => void;setToneDensityType: (id: string, densityType: 'specified' | 'image') => void;toggleLayerColor: (id: string) => void;@@ -463,6 +471,7 @@ export interface AppShellProps {handleOpenLayerStylesModal: (layerId?: string) => void;onEditVectorLayer?: (layer: LayerItem) => void;onRasterizeLayer?: (layerId: string) => void;+ onMergeFolder?: (folderId: string) => void;onPlayAutoAction?: (action: AutoAction) => void;externalFileDropTarget?: ExternalFileDropTarget | null;children?: React.ReactNode;@@ -555,6 +564,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(handleOpenLayerStylesModal,onEditVectorLayer,onRasterizeLayer,+ onMergeFolder,onPlayAutoAction,externalFileDropTarget = null,children,@@ -632,6 +642,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(}, []);const handleOpen3DLayer = useCallback(() => {+ toolStoreActions.selectTool('3d');uiStoreActions.set3DLayerOpen(true);}, []);@@ -813,6 +824,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(onSetToneDotShape: setToneDotShape,onSetToneDensity: setToneDensity,onSetToneDensityType: setToneDensityType,+ onCreateToneLayer: canvasProps.onFillScreentone,onToggleLayerColor: toggleLayerColor,onSetLayerColor: setLayerColor,onSetLayerSubColor: setLayerSubColor,@@ -831,6 +843,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(onOpenLayerStylesModal: handleOpenLayerStylesModal,onEditVectorLayer,onRasterizeLayer,+ onMergeFolder,+ onTransformLayer: canvasProps.onTransformSelection,externalFileDropIndicator:externalFileDropTarget?.zone === 'layers'? {@@ -884,6 +898,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(setToneDotShape,setToneDensity,setToneDensityType,+ canvasProps.onFillScreentone,toggleLayerColor,setLayerColor,setLayerSubColor,@@ -901,6 +916,8 @@ export const AppShell: React.FC<AppShellProps> = React.memo(handleOpenLayerStylesModal,onEditVectorLayer,onRasterizeLayer,+ onMergeFolder,+ canvasProps.onTransformSelection,externalFileDropTarget,]);diff --git a/src/components/Csp3DToolbar.tsx b/src/components/Csp3DToolbar.tsxindex f61016d..e7861f5 100644--- a/src/components/Csp3DToolbar.tsx+++ b/src/components/Csp3DToolbar.tsx@@ -1,63 +1,119 @@-import React, { useRef, useCallback, useState, useEffect } from 'react';-import { X } from 'lucide-react';-import { LTConversionSettings } from '../types/editor';--export type Csp3DToolMode =- | 'camera-orbit'- | 'camera-pan'- | 'camera-zoom'- | 'model-move'- | 'model-rotate-free'- | 'model-rotate-yaw'- | 'model-rotate-roll'- | 'model-plane-move';+import React, { useRef, useCallback, useState } from 'react';+import {+ X,+ Box,+ Sun,+ Magnet,+ HelpCircle,+ Eye,+ EyeOff,+ RotateCw,+ Move,+ Maximize2,+ Ban,+ Upload,+ Layers,+ Undo2,+ Redo2,+} from 'lucide-react';+import {+ Gizmo3DMode,+ TOOL_3D_BEHAVIOR_RULES,+ Tool3DMode,+} from '../utils/tool3DRules';+import { LightSourceWidget } from './LightSourceWidget';+import { store3DActions, use3DStore } from '../stores';++export type Csp3DToolMode = Tool3DMode;interface Csp3DToolbarProps {- activeMode: Csp3DToolMode;- onSelectMode: (mode: Csp3DToolMode) => void;- onDirectDrag: (mode: Csp3DToolMode, deltaX: number, deltaY: number, e: PointerEvent) => void;- onExtractLineAndTone?: (settings: LTConversionSettings) => void;- isExtracting?: boolean;- hasModel?: boolean;- modelName?: string;+ is3DToolActive: boolean;+ onActivate3DTool: () => void;+ onDirectDrag: (mode: Tool3DMode, deltaX: number, deltaY: number, snap: boolean) => void;+ onDirectDragEnd: () => void;+ onTriggerImport: () => void;+ onSnapToGround: () => void;+ onUndo: () => void;+ onRedo: () => void;+ onOpenLTModal: () => void;+ isLTModalOpen?: boolean;+ onBakeTo2D: (closeAfter: boolean) => void;+ onClose: () => void;}-const CAMERA_MODES: Array<{ mode: Csp3DToolMode; label: string; title: string }> = [+const OBJECT_MODES: Array<{ mode: Tool3DMode; label: string; title: string }> = [+ {+ mode: 'smart',+ label: 'Smart',+ title: 'Smart CSP mode: drag model to transform, drag background to orbit',+ },+ {+ mode: 'model-rotate',+ label: 'Rotate',+ title: 'Rotate model freely (click to select or drag button directly)',+ },+ {+ mode: 'model-move',+ label: 'Move',+ title: 'Move model in view plane (click to select or drag button directly)',+ },+ {+ mode: 'model-scale',+ label: 'Scale',+ title: 'Scale model uniformly (click to select or drag button directly)',+ },+ {+ mode: 'model-plane-move',+ label: 'Floor',+ title: 'Slide model along ground floor plane (click or drag)',+ },+];++const CAMERA_MODES: Array<{ mode: Tool3DMode; label: string; title: string }> = [{ mode: 'camera-orbit', label: 'Orbit', title: 'Orbit camera around model (click or drag)' },{ mode: 'camera-pan', label: 'Pan', title: 'Pan camera in screen plane (click or drag)' },{ mode: 'camera-zoom', label: 'Zoom', title: 'Zoom camera distance (click or drag)' },];-const MODEL_MODES: Array<{ mode: Csp3DToolMode; label: string; title: string }> = [- { mode: 'model-move', label: 'Move', title: 'Move model in view plane (click or drag)' },- { mode: 'model-rotate-free', label: 'Rotate', title: 'Rotate model freely (click or drag)' },- { mode: 'model-plane-move', label: 'Floor', title: 'Slide model along floor plane (click or drag)' },+const GIZMO_BUTTONS: Array<{+ mode: Gizmo3DMode;+ label: string;+ icon: React.ReactNode;+}> = [+ { mode: 'rotate', label: 'Rotate Gizmo', icon: <RotateCw className="w-3 h-3" /> },+ { mode: 'translate', label: 'Move Gizmo', icon: <Move className="w-3 h-3" /> },+ { mode: 'scale', label: 'Scale Gizmo', icon: <Maximize2 className="w-3 h-3" /> },+ { mode: 'none', label: 'Hide Gizmo', icon: <Ban className="w-3 h-3" /> },];export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({- activeMode,- onSelectMode,+ is3DToolActive,+ onActivate3DTool,onDirectDrag,- onExtractLineAndTone,- isExtracting = false,- hasModel = false,- modelName = 'Model',+ onDirectDragEnd,+ onTriggerImport,+ onSnapToGround,+ onUndo,+ onRedo,+ onOpenLTModal,+ isLTModalOpen = false,+ onBakeTo2D,+ onClose,}) => {- const [showLTDialog, setShowLTDialog] = useState(false);- const [lineWidth, setLineWidth] = useState(1);- const [lineThreshold, setLineThreshold] = useState(0.28);- const [toneCount, setToneCount] = useState<number>(2);- const [folderName, setFolderName] = useState('');+ const activeMode = use3DStore((s) => s.activeMode);+ const gizmoMode = use3DStore((s) => s.gizmoMode);+ const loadedModelName = use3DStore((s) => s.loadedModelName);+ const isBaking = use3DStore((s) => s.isBaking);+ const canUndo3D = use3DStore((s) => s.canUndo3D);+ const canRedo3D = use3DStore((s) => s.canRedo3D);+ const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);+ const lighting = use3DStore((s) => s.lighting);- const cleanModelName = (modelName || 'Model').replace(/\.[^/.]+$/, '').trim();- const defaultFolderName = `3D Extraction [${cleanModelName}]`;-- useEffect(() => {- setFolderName(defaultFolderName);- }, [defaultFolderName]);+ const [openPopover, setOpenPopover] = useState<'light' | 'help' | null>(null);+ const hasModel = Boolean(loadedModelName);const dragRef = useRef<{- mode: Csp3DToolMode;+ mode: Tool3DMode;startX: number;startY: number;lastX: number;@@ -65,11 +121,16 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({hasDragged: boolean;} | null>(null);- const handlePointerDown = useCallback(- (mode: Csp3DToolMode, e: React.PointerEvent<HTMLButtonElement>) => {+ const handleModeButtonPointerDown = useCallback(+ (mode: Tool3DMode, e: React.PointerEvent<HTMLButtonElement>) => {e.preventDefault();e.stopPropagation();+ if (mode === 'smart') {+ store3DActions.setActiveMode('smart');+ return;+ }+const target = e.currentTarget;try {target.setPointerCapture(e.pointerId);@@ -101,7 +162,7 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({dragRef.current.lastY = ev.clientY;if (dx !== 0 || dy !== 0) {- onDirectDrag(mode, dx, dy, ev);+ onDirectDrag(mode, dx, dy, ev.shiftKey);}};@@ -115,8 +176,19 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({window.removeEventListener('pointerup', handlePointerUp);window.removeEventListener('pointercancel', handlePointerUp);- if (dragRef.current && !dragRef.current.hasDragged) {- onSelectMode(mode);+ if (dragRef.current) {+ if (dragRef.current.hasDragged) {+ onDirectDragEnd();+ } else {+ store3DActions.setActiveMode(mode);+ if (mode === 'model-rotate' || mode === 'model-rotate-yaw' || mode === 'model-rotate-roll') {+ store3DActions.setGizmoMode('rotate');+ } else if (mode === 'model-move' || mode === 'model-plane-move') {+ store3DActions.setGizmoMode('translate');+ } else if (mode === 'model-scale') {+ store3DActions.setGizmoMode('scale');+ }+ }}dragRef.current = null;};@@ -125,22 +197,77 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({window.addEventListener('pointerup', handlePointerUp);window.addEventListener('pointercancel', handlePointerUp);},- [onDirectDrag, onSelectMode]+ [onDirectDrag, onDirectDragEnd]);+ // Minimized non-intrusive pill while user is painting with a 2D tool over the live 3D reference+ if (!is3DToolActive) {+ return (+ <div+ className="fixed top-12 left-1/2 -translate-x-1/2 z-40 bg-[#202020]/90 backdrop-blur-md border border-white/[0.1] rounded-full px-2.5 py-1 shadow-xl flex items-center gap-2 text-[11px] text-[#e5e5e5] select-none"+ onPointerDown={(e) => e.stopPropagation()}+ >+ <span className="flex items-center gap-1.5 text-[#a3a3a3]">+ <Box className="w-3.5 h-3.5 text-[var(--accent)]" />+ <span className="max-w-[120px] truncate">{loadedModelName || '3D Reference'}</span>+ </span>+ <button+ type="button"+ onClick={onActivate3DTool}+ title="Switch to 3D Tool (K) to rotate, move, scale, or adjust lighting"+ className="px-2 py-0.5 rounded-full bg-[var(--accent)] text-[var(--accent-contrast)] font-medium hover:opacity-90 transition-opacity cursor-pointer"+ >+ Edit 3D (K)+ </button>+ <button+ type="button"+ onClick={() => store3DActions.toggleReferenceVisible()}+ title={isReferenceVisible ? 'Hide 3D Reference' : 'Show 3D Reference'}+ className="p-1 rounded-full text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"+ >+ {isReferenceVisible ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}+ </button>+ <button+ type="button"+ onClick={onClose}+ title="Close 3D Stage"+ className="p-1 rounded-full text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button>+ </div>+ );+ }+return (<div- className="flex items-center gap-1.5 select-none"+ className="fixed top-12 left-1/2 -translate-x-1/2 z-50 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-lg px-2 py-1 shadow-2xl flex items-center gap-1.5 text-xs text-[#e5e5e5] select-none max-w-[calc(100vw-24px)]"onPointerDown={(e) => e.stopPropagation()}>- {/* Camera Mode Group */}+ {/* 1. Import 3D Model */}+ <button+ type="button"+ onClick={onTriggerImport}+ title="Import 3D Model (.glb, .gltf, .obj)"+ className={`flex items-center gap-1 px-2 py-1 rounded text-[11px] border border-white/[0.06] transition-colors cursor-pointer max-w-[110px] truncate ${+ loadedModelName+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'bg-[#161616] text-[#cccccc] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <Upload className="w-3 h-3 shrink-0 text-[var(--accent)]" />+ <span className="truncate">{loadedModelName || 'Import 3D'}</span>+ </button>++ <div className="w-px h-4 bg-white/[0.08]" />++ {/* 2. Object Transform Modes (Click or Scrub-Drag) */}<div className="flex items-center bg-[#161616] rounded p-0.5 border border-white/[0.06]">- <span className="px-1.5 text-[10px] text-[#666666] font-medium">Cam</span>- {CAMERA_MODES.map((item) => (+ {OBJECT_MODES.map((item) => (<buttonkey={item.mode}type="button"- onPointerDown={(e) => handlePointerDown(item.mode, e)}+ onPointerDown={(e) => handleModeButtonPointerDown(item.mode, e)}title={item.title}className={`px-2 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${activeMode === item.mode@@ -153,16 +280,16 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({))}</div>- {/* Model Mode Group */}+ {/* 3. Camera Modes (Click or Scrub-Drag) */}<div className="flex items-center bg-[#161616] rounded p-0.5 border border-white/[0.06]">- <span className="px-1.5 text-[10px] text-[#666666] font-medium">Obj</span>- {MODEL_MODES.map((item) => (+ <span className="px-1 text-[10px] text-[#666666] font-medium">Cam</span>+ {CAMERA_MODES.map((item) => (<buttonkey={item.mode}type="button"- onPointerDown={(e) => handlePointerDown(item.mode, e)}+ onPointerDown={(e) => handleModeButtonPointerDown(item.mode, e)}title={item.title}- className={`px-2 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${+ className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${activeMode === item.mode? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium': 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'@@ -173,142 +300,195 @@ export const Csp3DToolbar: React.FC<Csp3DToolbarProps> = ({))}</div>- {/* Unified Line & Tone (LT Conversion) Popover */}+ <div className="w-px h-4 bg-white/[0.08]" />++ {/* 4. On-Canvas Gizmo Mode + Snap Floor + Undo/Redo */}+ <div className="flex items-center bg-[#161616] rounded p-0.5 border border-white/[0.06]">+ {GIZMO_BUTTONS.map((g) => (+ <button+ key={g.mode}+ type="button"+ onClick={() => store3DActions.setGizmoMode(g.mode)}+ title={g.label}+ className={`p-1 rounded transition-colors cursor-pointer ${+ gizmoMode === g.mode+ ? 'bg-[#2c2c2c] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {g.icon}+ </button>+ ))}+ </div>++ <button+ type="button"+ onClick={onSnapToGround}+ disabled={!hasModel}+ title="Snap Model to Ground Floor (Y = 0)"+ className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] disabled:opacity-40 cursor-pointer"+ >+ <Magnet className="w-3.5 h-3.5" />+ </button>++ <div className="flex items-center">+ <button+ type="button"+ onClick={onUndo}+ disabled={!canUndo3D}+ title="Undo 3D Action (Ctrl+Z)"+ className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"+ >+ <Undo2 className="w-3.5 h-3.5" />+ </button>+ <button+ type="button"+ onClick={onRedo}+ disabled={!canRedo3D}+ title="Redo 3D Action (Ctrl+Y)"+ className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] disabled:opacity-30 disabled:cursor-not-allowed cursor-pointer"+ >+ <Redo2 className="w-3.5 h-3.5" />+ </button>+ </div>++ {/* 5. Quick Lighting Popover */}<div className="relative"><buttontype="button"- onClick={() => setShowLTDialog((prev) => !prev)}- disabled={isExtracting || !hasModel}- title="Extract Lineart and Screentones from 3D Model"- className={`px-2.5 py-1 rounded text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed ${- showLTDialog- ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent-border)]'- : 'bg-[#2c2c2c] text-[#e5e5e5] hover:bg-[#383838]'+ onClick={() => setOpenPopover((p) => (p === 'light' ? null : 'light'))}+ title="Quick Lighting & 3D Light Sphere"+ className={`p-1 rounded transition-colors cursor-pointer ${+ openPopover === 'light'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'}`}>- Line & Tone+ <Sun className="w-3.5 h-3.5" /></button>- {showLTDialog && (- <div- className="absolute top-full mt-2 right-0 w-72 bg-[#202020] border border-white/[0.1] rounded-lg p-3.5 shadow-2xl z-50 text-[#e5e5e5] select-none"- onPointerDown={(e) => e.stopPropagation()}- >- <div className="flex items-center justify-between pb-2 border-b border-white/[0.06]">- <span className="text-xs font-medium text-[#e5e5e5]">Line & Tone Extraction</span>+ {openPopover === 'light' && (+ <div className="absolute top-full mt-2 right-0 w-64 bg-[#202020] border border-white/[0.1] rounded-lg p-2.5 shadow-2xl z-50">+ <LightSourceWidget+ embedded+ compact+ settings={{+ azimuth: lighting.keyLight.azimuth,+ elevation: lighting.keyLight.elevation,+ intensity: lighting.keyLight.intensity,+ ambientIntensity: lighting.ambientIntensity,+ color: lighting.keyLight.color,+ isBacklit: lighting.keyLight.isBacklit,+ }}+ onChange={(next) => {+ store3DActions.updateKeyLight({+ azimuth: next.azimuth,+ elevation: next.elevation,+ intensity: next.intensity,+ color: next.color,+ isBacklit: next.isBacklit,+ });+ store3DActions.updateLighting({ ambientIntensity: next.ambientIntensity });+ }}+ onReset={() => store3DActions.resetLighting()}+ />+ </div>+ )}+ </div>++ {/* 6. Behavior Rules Help Popover */}+ <div className="relative">+ <button+ type="button"+ onClick={() => setOpenPopover((p) => (p === 'help' ? null : 'help'))}+ title="3D Tool Controls & Behavior Rules"+ className={`p-1 rounded transition-colors cursor-pointer ${+ openPopover === 'help'+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ <HelpCircle className="w-3.5 h-3.5" />+ </button>++ {openPopover === 'help' && (+ <div className="absolute top-full mt-2 right-0 w-72 bg-[#202020] border border-white/[0.1] rounded-lg p-3 shadow-2xl z-50 space-y-2">+ <div className="flex items-center justify-between pb-1.5 border-b border-white/[0.06]">+ <span className="text-[11px] font-medium text-[#e5e5e5]">3D Tool Behavior Rules</span><buttontype="button"- onClick={() => setShowLTDialog(false)}- className="text-[#8a8a8a] hover:text-[#e5e5e5] p-0.5 rounded hover:bg-[#2c2c2c] cursor-pointer"+ onClick={() => setOpenPopover(null)}+ className="text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"><X className="w-3.5 h-3.5" /></button></div>-- <div className="mt-3 space-y-2.5">- <div className="space-y-1">- <div className="flex justify-between text-[11px]">- <span className="text-[#8a8a8a]">Line Width</span>- <span className="font-mono text-[#e5e5e5]">{lineWidth} px</span>- </div>- <input- type="range"- min="1"- max="5"- step="1"- value={lineWidth}- onChange={(e) => setLineWidth(parseInt(e.target.value, 10))}- className="w-full"- />- </div>-- <div className="space-y-1">- <div className="flex justify-between text-[11px]">- <span className="text-[#8a8a8a]">Edge Sensitivity</span>- <span className="font-mono text-[#e5e5e5]">- {Math.round((1 - lineThreshold) * 100)}%- </span>+ <div className="space-y-1.5">+ {TOOL_3D_BEHAVIOR_RULES.map((rule) => (+ <div key={rule.gesture} className="flex items-start justify-between gap-2 text-[10px]">+ <span className="font-mono text-[#e5e5e5] shrink-0">{rule.gesture}</span>+ <span className="text-[#8a8a8a] text-right">{rule.action}</span></div>- <input- type="range"- min="0.05"- max="0.8"- step="0.01"- value={lineThreshold}- onChange={(e) => setLineThreshold(parseFloat(e.target.value))}- className="w-full"- />- </div>- </div>-- <div className="mt-3 space-y-1.5">- <div className="flex justify-between text-[11px]">- <span className="text-[#8a8a8a]">Screentone Bands</span>- <span className="text-[10px] text-[#666666] font-mono">60 LPI</span>- </div>- <div className="grid grid-cols-4 gap-1">- {([1, 2, 3, 4] as const).map((count) => (- <button- key={count}- type="button"- onClick={() => setToneCount(count)}- className={`py-1 rounded text-[11px] transition-colors cursor-pointer ${- toneCount === count- ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'- : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- {count}- </button>- ))}- </div>- <p className="text-[10px] text-[#8a8a8a] font-mono">- {toneCount === 1 && 'Deep Shadow (45%)'}- {toneCount === 2 && 'Light (20%) + Deep (45%)'}- {toneCount === 3 && 'Light (15%) + Mid (30%) + Deep (50%)'}- {toneCount === 4 && '4-step gradation (10% - 55%)'}- </p>- </div>-- <div className="mt-3 space-y-1">- <label className="text-[11px] text-[#8a8a8a] block">Output Folder</label>- <input- type="text"- value={folderName}- onChange={(e) => setFolderName(e.target.value)}- placeholder={defaultFolderName}- className="w-full px-2 py-1 text-xs bg-[#161616] border border-white/[0.08] rounded text-[#e5e5e5] font-mono"- />- </div>-- <div className="mt-3.5 flex items-center space-x-2">- <button- type="button"- onClick={() => setShowLTDialog(false)}- className="flex-1 py-1.5 rounded text-xs text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"- >- Cancel- </button>- <button- type="button"- disabled={isExtracting}- onClick={() => {- onExtractLineAndTone?.({- lineWidth,- lineThreshold,- toneCount,- folderName: folderName.trim() || defaultFolderName,- });- setShowLTDialog(false);- }}- className="flex-1 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium rounded text-xs transition-opacity disabled:opacity-50 cursor-pointer"- >- {isExtracting ? 'Extracting...' : 'Extract'}- </button>+ ))}</div></div>)}</div>++ <div className="w-px h-4 bg-white/[0.08]" />++ {/* 7. Open Separate Line & Tone Extraction Modal with Live Preview */}+ <button+ type="button"+ onClick={() => {+ setOpenPopover(null);+ onOpenLTModal();+ }}+ disabled={isBaking || !hasModel}+ title="Open Line & Tone Extraction Preview Dialog"+ className={`px-2 py-1 rounded text-[11px] font-medium transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed ${+ isLTModalOpen+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-[var(--accent-border)]'+ : 'bg-[#2c2c2c] text-[#e5e5e5] hover:bg-[#383838]'+ }`}+ >+ LT+ </button>++ {/* 8. Primary Bake Action (Shift+Click stamps a copy without closing!) */}+ <button+ type="button"+ onClick={(e) => onBakeTo2D(!e.shiftKey)}+ disabled={isBaking || !hasModel}+ title={+ !hasModel+ ? 'Load a 3D model first'+ : 'Rasterize 3D view into a 2D Layer (Shift+Click to keep 3D stage open)'+ }+ className="flex items-center gap-1 px-2.5 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium rounded text-[11px] transition-opacity disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"+ >+ <Layers className="w-3 h-3" />+ <span>{isBaking ? 'Baking...' : 'Bake'}</span>+ </button>++ {/* 9. Reference Visibility & Close */}+ <button+ type="button"+ onClick={() => store3DActions.toggleReferenceVisible()}+ title={isReferenceVisible ? 'Hide 3D Reference' : 'Show 3D Reference'}+ className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ >+ {isReferenceVisible ? <Eye className="w-3.5 h-3.5" /> : <EyeOff className="w-3.5 h-3.5" />}+ </button>++ <button+ type="button"+ onClick={onClose}+ title="Close 3D Stage"+ className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"+ >+ <X className="w-3.5 h-3.5" />+ </button></div>);};diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsxindex abeb405..f174eb9 100644--- a/src/components/DocumentLifecycleManager.tsx+++ b/src/components/DocumentLifecycleManager.tsx@@ -69,10 +69,13 @@ function hasMeaningfulLayerEdit(prev: LayerItem[], next: LayerItem[]): boolean {a.clipped !== b.clipped ||a.parentId !== b.parentId ||a.isReference !== b.isReference ||+ a.isToneLayer !== b.isToneLayer ||a.toneEnabled !== b.toneEnabled ||a.toneFrequency !== b.toneFrequency ||a.toneAngle !== b.toneAngle ||+ a.toneDotShape !== b.toneDotShape ||a.toneDensity !== b.toneDensity ||+ a.toneDensityType !== b.toneDensityType ||a.layerColorEnabled !== b.layerColorEnabled ||a.layerColor !== b.layerColor ||a.expressionColor !== b.expressionColor ||@@ -211,6 +214,7 @@ export interface UseDocumentLifecycleParams {layerId?: string;layerName?: string;tileDeltas?: import('../types/editor').TileDelta[];+ layerTreeDelta?: import('../types/editor').LayerTreeDelta;}>;onDeselectAfterPaste?: () => void;deleteLayer: (id: string) => void;@@ -348,7 +352,7 @@ export function useDocumentLifecycle({const handlePasteSelectedLayer = useCallback(async () => {const res = await pasteLayer();if (res.success && res.layerName) {- if (res.layerId && res.tileDeltas && res.tileDeltas.length > 0) {+ if (res.layerId && ((res.tileDeltas && res.tileDeltas.length > 0) || res.layerTreeDelta)) {pushHistoryStep('selection-move',`Paste "${res.layerName}"`,@@ -356,7 +360,12 @@ export function useDocumentLifecycle({null,res.layerId,undefined,- res.tileDeltas+ res.tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ res.layerTreeDelta);}onDeselectAfterPaste?.();@@ -411,8 +420,9 @@ export function useDocumentLifecycle({(e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];if (file) {+ toolStoreActions.selectTool('3d');uiStoreActions.set3DLayerOpen(true, file);- showToast(`Importing 3D model "${file.name}" into local ghost layer...`);+ showToast(`Importing 3D model "${file.name}" into 3D stage...`);if (import3DFileInputRef.current) {import3DFileInputRef.current.value = '';}@@ -489,6 +499,16 @@ export function useDocumentLifecycle({const handleProcessFile = useCallback(async (file: File, options?: ProcessFileOptions) => {+ const lowerName = file.name.toLowerCase();+ if (+ (lowerName.endsWith('.glb') || lowerName.endsWith('.gltf') || lowerName.endsWith('.obj')) &&+ useDocumentStore.getState().documents.length > 0+ ) {+ toolStoreActions.selectTool('3d');+ uiStoreActions.set3DLayerOpen(true, file);+ showToast(`Importing 3D model "${file.name}" into 3D stage...`);+ return;+ }if (isSupportedBrushFileName(file.name)) {try {uiStoreActions.setLoading(true, `Importing Brush: ${file.name}...`);diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsxindex 338e0ab..e92c3db 100644--- a/src/components/GlobalShortcutListener.tsx+++ b/src/components/GlobalShortcutListener.tsx@@ -117,11 +117,16 @@ const NON_TEXT_INPUT_TYPES = new Set(['image',]);-function isEditableTarget(target: EventTarget | null): boolean {+export function isEditableTarget(target: EventTarget | null, e?: KeyboardEvent): boolean {if (!(target instanceof HTMLElement)) return false;if (target.isContentEditable) return true;const tag = target.tagName;- if (tag === 'TEXTAREA' || tag === 'SELECT') return true;+ if (tag === 'TEXTAREA') return true;+ if (tag === 'SELECT') {+ // Allow Ctrl/Cmd shortcuts (such as Ctrl+Z Undo / Ctrl+Y Redo / Ctrl+S Save) even when a <select> dropdown retains focus+ if (e && (e.ctrlKey || e.metaKey)) return false;+ return true;+ }if (tag === 'INPUT') {const inputType = ((target as HTMLInputElement).type || 'text').toLowerCase();return !NON_TEXT_INPUT_TYPES.has(inputType);@@ -383,6 +388,11 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea},// Tools & Colors+ 'tool.3d': () => {+ if (propsRef.current.hasOpenDocument) {+ toolStoreActions.selectTool('3d');+ }+ },'tool.brushSizeDown': () => stepBrush(-1),'tool.brushSizeUp': () => stepBrush(1),'color.swap': () => toolStoreActions.swapColors(),@@ -417,7 +427,7 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Reaconst p = propsRef.current;const uiState = useUiStore.getState();const isModalOpen = selectIsAnyModalOpen(uiState, p.isHostModalOpen) || uiState.isLoadingFile;- if (isModalOpen || isEditableTarget(e.target)) {+ if (isModalOpen || isEditableTarget(e.target, e)) {return;}@@ -453,7 +463,8 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = ReamodKey === 'Alt' &&tempTool === 'pipette' &&((curState.tool === 'retouch' && curState.retouchSettings.mode === 'clone-stamp') ||- curState.tool === 'pen');+ curState.tool === 'pen' ||+ curState.tool === '3d');if (reserveAltForActiveTool) {return;}diff --git a/src/components/LTExtractionModal.tsx b/src/components/LTExtractionModal.tsxnew file mode 100644index 0000000..7fce10a--- /dev/null+++ b/src/components/LTExtractionModal.tsx@@ -0,0 +1,453 @@+import React, { useEffect, useRef, useState, useCallback } from 'react';+import { X, Loader2, Layers, Eye } from 'lucide-react';+import { LTConversionSettings } from '../types/editor';++export interface LTPreviewBuffers {+ lineCanvas: HTMLCanvasElement;+ toneCanvases: HTMLCanvasElement[];+}++export interface LTExtractionModalProps {+ isOpen: boolean;+ modelName: string;+ dimensions: { width: number; height: number };+ isExtracting: boolean;+ onRenderPreview: (settings: LTConversionSettings) => Promise<LTPreviewBuffers | null>;+ onExtract: (settings: LTConversionSettings) => void;+ onClose: () => void;+}++type PreviewLayerMode = 'combined' | 'line' | 'tone';+type PreviewBgMode = 'white' | 'checker';++export const LTExtractionModal: React.FC<LTExtractionModalProps> = ({+ isOpen,+ modelName,+ dimensions,+ isExtracting,+ onRenderPreview,+ onExtract,+ onClose,+}) => {+ const cleanModelName = (modelName || '3D Model').replace(/\.[^/.]+$/, '').trim();+ const defaultFolderName = `3D Extraction [${cleanModelName}]`;++ const [lineWidth, setLineWidth] = useState(1);+ const [lineThreshold, setLineThreshold] = useState(0.28);+ const [antiAliasing, setAntiAliasing] = useState(false);+ const [includeTones, setIncludeTones] = useState(true);+ const [toneCount, setToneCount] = useState<number>(2);+ const [toneFrequency, setToneFrequency] = useState<number>(60);+ const [folderName, setFolderName] = useState(defaultFolderName);++ const [previewLayerMode, setPreviewLayerMode] = useState<PreviewLayerMode>('combined');+ const [previewBgMode, setPreviewBgMode] = useState<PreviewBgMode>('white');+ const [isUpdatingPreview, setIsUpdatingPreview] = useState(false);++ const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);+ const buffersRef = useRef<LTPreviewBuffers | null>(null);+ const renderReqIdRef = useRef<number>(0);++ useEffect(() => {+ if (isOpen) {+ setFolderName(defaultFolderName);+ }+ }, [isOpen, defaultFolderName]);++ // Escape key closes modal+ useEffect(() => {+ if (!isOpen) return;+ const handleKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape' && !isExtracting) {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ }+ };+ window.addEventListener('keydown', handleKey, true);+ return () => window.removeEventListener('keydown', handleKey, true);+ }, [isOpen, isExtracting, onClose]);++ const buildSettings = useCallback((): LTConversionSettings => {+ const effectiveToneCount = includeTones ? toneCount : 0;+ return {+ lineWidth,+ lineThreshold,+ toneCount: effectiveToneCount,+ toneFrequencies: Array.from({ length: effectiveToneCount }, () => toneFrequency),+ antiAliasing,+ folderName: folderName.trim() || defaultFolderName,+ };+ }, [+ includeTones,+ toneCount,+ lineWidth,+ lineThreshold,+ toneFrequency,+ antiAliasing,+ folderName,+ defaultFolderName,+ ]);++ // Composite cached line + tone preview buffers onto visible canvas+ const compositePreviewCanvas = useCallback(+ (buffers: LTPreviewBuffers | null, layerMode: PreviewLayerMode, bgMode: PreviewBgMode) => {+ const canvas = previewCanvasRef.current;+ if (!canvas || !buffers) return;+ const w = buffers.lineCanvas.width;+ const h = buffers.lineCanvas.height;+ if (w <= 0 || h <= 0) return;++ if (canvas.width !== w || canvas.height !== h) {+ canvas.width = w;+ canvas.height = h;+ }++ const ctx = canvas.getContext('2d');+ if (!ctx) return;++ ctx.imageSmoothingEnabled = false;+ ctx.clearRect(0, 0, w, h);++ if (bgMode === 'white') {+ ctx.fillStyle = '#ffffff';+ ctx.fillRect(0, 0, w, h);+ }++ // Draw screentone bands (light -> deep) with multiply blend+ if (layerMode === 'combined' || layerMode === 'tone') {+ ctx.save();+ ctx.globalCompositeOperation = bgMode === 'white' ? 'multiply' : 'source-over';+ for (const toneCanvas of buffers.toneCanvases) {+ ctx.drawImage(toneCanvas, 0, 0, w, h);+ }+ ctx.restore();+ }++ // Draw 3D outline on top+ if (layerMode === 'combined' || layerMode === 'line') {+ ctx.drawImage(buffers.lineCanvas, 0, 0, w, h);+ }+ },+ []+ );++ // Instant re-composite when user switches preview layer/background toggles+ useEffect(() => {+ if (!isOpen) return;+ compositePreviewCanvas(buffersRef.current, previewLayerMode, previewBgMode);+ }, [isOpen, previewLayerMode, previewBgMode, compositePreviewCanvas]);++ // Debounced live WebGL Line & Tone preview generation when settings change+ useEffect(() => {+ if (!isOpen) return;+ const reqId = ++renderReqIdRef.current;+ setIsUpdatingPreview(true);++ const timer = setTimeout(async () => {+ try {+ const settings = buildSettings();+ const buffers = await onRenderPreview(settings);+ if (renderReqIdRef.current !== reqId) return;+ buffersRef.current = buffers;+ compositePreviewCanvas(buffers, previewLayerMode, previewBgMode);+ } catch (err) {+ console.warn('[LT Preview] Failed to render preview:', err);+ } finally {+ if (renderReqIdRef.current === reqId) {+ setIsUpdatingPreview(false);+ }+ }+ }, 110);++ return () => clearTimeout(timer);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ isOpen,+ lineWidth,+ lineThreshold,+ antiAliasing,+ includeTones,+ toneCount,+ toneFrequency,+ onRenderPreview,+ ]);++ if (!isOpen) return null;++ const docAspect = `${Math.max(1, dimensions.width)} × ${Math.max(1, dimensions.height)} px`;++ return (+ <div+ data-testid="lt-extraction-modal"+ className="fixed inset-0 z-[70] bg-black/65 backdrop-blur-xs flex items-center justify-center p-4 select-none"+ onPointerDown={(e) => {+ e.stopPropagation();+ if (e.target === e.currentTarget && !isExtracting) {+ onClose();+ }+ }}+ >+ <div+ className="w-full max-w-3xl bg-[#202020] border border-white/[0.12] rounded-xl shadow-2xl overflow-hidden flex flex-col max-h-[88vh] text-[#e5e5e5]"+ onPointerDown={(e) => e.stopPropagation()}+ >+ {/* Modal Header */}+ <div className="px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.08] flex items-center justify-between shrink-0">+ <div className="flex items-center gap-2 min-w-0">+ <Layers className="w-4 h-4 text-[var(--accent)] shrink-0" />+ <span className="text-xs font-semibold tracking-wide truncate">+ Line & Tone Extraction (LT Conversion)+ </span>+ <span className="text-[10px] font-mono text-[#8a8a8a] hidden sm:inline">+ · {cleanModelName}+ </span>+ </div>+ <button+ type="button"+ disabled={isExtracting}+ onClick={onClose}+ className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] disabled:opacity-40 cursor-pointer"+ >+ <X className="w-4 h-4" />+ </button>+ </div>++ {/* Main Content: Live Preview (Left) + Controls (Right) */}+ <div className="flex flex-col md:flex-row flex-1 min-h-0 overflow-hidden">+ {/* Left Pane: Live Extraction Preview */}+ <div className="flex-1 bg-[#141414] flex flex-col min-h-[280px] border-b md:border-b-0 md:border-r border-white/[0.08]">+ {/* Preview Toolbar */}+ <div className="px-3 py-1.5 bg-[#181818] border-b border-white/[0.06] flex items-center justify-between gap-2 shrink-0">+ <div className="flex items-center gap-1 bg-[#121212] p-0.5 rounded border border-white/[0.06]">+ {(+ [+ ['combined', 'Line + Tone'],+ ['line', 'Outline'],+ ['tone', 'Tones'],+ ] as Array<[PreviewLayerMode, string]>+ ).map(([mode, label]) => (+ <button+ key={mode}+ type="button"+ onClick={() => setPreviewLayerMode(mode)}+ className={`px-2 py-0.5 rounded text-[10px] transition-colors cursor-pointer ${+ previewLayerMode === mode+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {label}+ </button>+ ))}+ </div>++ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={() =>+ setPreviewBgMode((prev) => (prev === 'white' ? 'checker' : 'white'))+ }+ title="Toggle Paper / Transparent Preview Background"+ className="flex items-center gap-1 px-2 py-0.5 rounded bg-[#222] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] cursor-pointer"+ >+ <Eye className="w-3 h-3 text-[var(--accent)]" />+ <span>{previewBgMode === 'white' ? 'Paper' : 'Alpha'}</span>+ </button>+ <span className="text-[10px] font-mono text-[#6e6e6e] hidden sm:inline">+ {docAspect}+ </span>+ </div>+ </div>++ {/* Preview Viewport */}+ <div className="relative flex-1 flex items-center justify-center p-4 overflow-hidden">+ <div+ className="relative max-w-full max-h-full flex items-center justify-center rounded shadow-2xl border border-white/[0.1] overflow-hidden"+ style={+ previewBgMode === 'checker'+ ? {+ backgroundImage:+ 'repeating-conic-gradient(#333 0% 25%, #444 0% 50%)',+ backgroundSize: '14px 14px',+ }+ : { backgroundColor: '#ffffff' }+ }+ >+ <canvas+ ref={previewCanvasRef}+ className="block max-w-full max-h-[52vh] w-auto h-auto object-contain"+ />+ </div>++ {isUpdatingPreview && (+ <div className="absolute bottom-3 right-3 px-2.5 py-1 rounded-full bg-[#202020]/90 border border-white/[0.1] flex items-center gap-1.5 text-[10px] text-[#cccccc] shadow-lg">+ <Loader2 className="w-3 h-3 animate-spin text-[var(--accent)]" />+ <span>Updating preview...</span>+ </div>+ )}+ </div>+ </div>++ {/* Right Pane: LT Parameters */}+ <div className="w-full md:w-72 p-4 space-y-4 overflow-y-auto shrink-0 bg-[#202020]">+ {/* Line Extraction Section */}+ <div className="space-y-2.5">+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium">+ Line Extraction+ </div>++ <div className="space-y-1">+ <div className="flex justify-between text-[11px]">+ <span className="text-[#a3a3a3]">Line Width</span>+ <span className="font-mono text-[#e5e5e5]">{lineWidth} px</span>+ </div>+ <input+ type="range"+ min="1"+ max="5"+ step="1"+ value={lineWidth}+ onChange={(e) => setLineWidth(parseInt(e.target.value, 10))}+ className="w-full"+ />+ </div>++ <div className="space-y-1">+ <div className="flex justify-between text-[11px]">+ <span className="text-[#a3a3a3]">Edge Sensitivity</span>+ <span className="font-mono text-[#e5e5e5]">+ {Math.round((1 - lineThreshold) * 100)}%+ </span>+ </div>+ <input+ type="range"+ min="0.05"+ max="0.8"+ step="0.01"+ value={lineThreshold}+ onChange={(e) => setLineThreshold(parseFloat(e.target.value))}+ className="w-full"+ />+ </div>++ <label className="flex items-center justify-between text-[11px] text-[#cccccc] pt-0.5 cursor-pointer">+ <span>Anti-Aliasing</span>+ <input+ type="checkbox"+ checked={antiAliasing}+ onChange={(e) => setAntiAliasing(e.target.checked)}+ />+ </label>+ </div>++ {/* Screentone Section */}+ <div className="space-y-2.5 pt-3 border-t border-white/[0.08]">+ <label className="flex items-center justify-between cursor-pointer">+ <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium">+ Screentones+ </span>+ <input+ type="checkbox"+ checked={includeTones}+ onChange={(e) => setIncludeTones(e.target.checked)}+ />+ </label>++ {includeTones && (+ <>+ <div className="space-y-1.5">+ <div className="flex justify-between text-[11px]">+ <span className="text-[#a3a3a3]">Shadow Bands</span>+ <span className="text-[10px] text-[#8a8a8a] font-mono">+ {toneFrequency} LPI+ </span>+ </div>+ <div className="grid grid-cols-4 gap-1">+ {([1, 2, 3, 4] as const).map((count) => (+ <button+ key={count}+ type="button"+ onClick={() => setToneCount(count)}+ className={`py-1 rounded text-[11px] transition-colors cursor-pointer ${+ toneCount === count+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {count}+ </button>+ ))}+ </div>+ <p className="text-[10px] text-[#8a8a8a] font-mono">+ {toneCount === 1 && 'Deep Shadow (45%)'}+ {toneCount === 2 && 'Light (20%) + Deep (45%)'}+ {toneCount === 3 && 'Light (15%) + Mid (30%) + Deep (50%)'}+ {toneCount === 4 && '4-step gradation (10% - 55%)'}+ </p>+ </div>++ <div className="space-y-1">+ <div className="flex justify-between text-[11px]">+ <span className="text-[#a3a3a3]">Frequency</span>+ <span className="font-mono text-[#e5e5e5]">{toneFrequency} LPI</span>+ </div>+ <div className="grid grid-cols-3 gap-1">+ {([40, 60, 85] as const).map((lpi) => (+ <button+ key={lpi}+ type="button"+ onClick={() => setToneFrequency(lpi)}+ className={`py-1 rounded text-[10px] font-mono transition-colors cursor-pointer ${+ toneFrequency === lpi+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium border border-white/[0.12]'+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {lpi} LPI+ </button>+ ))}+ </div>+ </div>+ </>+ )}+ </div>++ {/* Output Folder Section */}+ <div className="space-y-1.5 pt-3 border-t border-white/[0.08]">+ <label className="text-[11px] text-[#a3a3a3] block">Output Folder</label>+ <input+ type="text"+ value={folderName}+ onChange={(e) => setFolderName(e.target.value)}+ placeholder={defaultFolderName}+ className="w-full px-2.5 py-1.5 text-xs bg-[#161616] border border-white/[0.08] rounded text-[#e5e5e5] font-mono outline-none focus:border-[var(--accent)]"+ />+ </div>++ {/* Action Buttons */}+ <div className="pt-2 flex items-center gap-2">+ <button+ type="button"+ disabled={isExtracting}+ onClick={onClose}+ className="flex-1 py-2 rounded text-xs text-[#a3a3a3] hover:text-[#e5e5e5] bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] transition-colors cursor-pointer disabled:opacity-40"+ >+ Cancel+ </button>+ <button+ type="button"+ disabled={isExtracting}+ onClick={() => onExtract(buildSettings())}+ className="flex-1 py-2 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium rounded text-xs transition-opacity disabled:opacity-50 cursor-pointer flex items-center justify-center gap-1.5"+ >+ {isExtracting && <Loader2 className="w-3.5 h-3.5 animate-spin" />}+ <span>{isExtracting ? 'Extracting...' : 'Extract'}</span>+ </button>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/src/components/LightSourceWidget.tsx b/src/components/LightSourceWidget.tsxindex 527b109..93d749a 100644--- a/src/components/LightSourceWidget.tsx+++ b/src/components/LightSourceWidget.tsx@@ -1,11 +1,12 @@import React, { useRef, useEffect, useCallback, useState } from 'react';import { RotateCcw } from 'lucide-react';+import { sphericalLightToVector } from '../utils/tool3DRules';export interface LightSettings {azimuth: number; // 0 to 360 degrees (horizontal)elevation: number; // -85 to 85 degrees (vertical)- intensity: number; // 0.2 to 3.0- ambientIntensity: number; // 0.1 to 1.5 (fill light / shadow contrast)+ intensity: number; // 0.0 to 3.0+ ambientIntensity: number; // 0.0 to 1.5 (fill light / shadow contrast)color: string; // hexisBacklit: boolean;}@@ -15,6 +16,7 @@ interface LightSourceWidgetProps {onChange: (settings: LightSettings) => void;onReset: () => void;embedded?: boolean;+ compact?: boolean;}export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({@@ -22,26 +24,16 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({onChange,onReset,embedded = false,+ compact = false,}) => {const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const sphereBufferRef = useRef<HTMLCanvasElement | null>(null);const isDraggingRef = useRef<boolean>(false);+ const settingsRef = useRef(settings);+ settingsRef.current = settings;const [activeTab, setActiveTab] = useState<'sphere' | 'sliders'>('sphere');- // Convert spherical angles to normalized 3D unit vector [x, y, z]- const getLightVector = useCallback(- (azimuthDeg: number, elevationDeg: number, isBacklit: boolean) => {- const az = (azimuthDeg * Math.PI) / 180;- const el = (elevationDeg * Math.PI) / 180;- // In Three.js coordinates: Y is up, X is right, Z is front- const y = Math.sin(el);- const hyp = Math.cos(el);- const x = hyp * Math.sin(az);- let z = hyp * Math.cos(az);- if (isBacklit) z = -Math.abs(z);- return { x, y, z };- },- []- );+ const sphereSize = compact ? 112 : 128;// Render the interactive 3D shaded sphere with real-time lighting & directional gizmoconst renderSphere = useCallback(() => {@@ -54,107 +46,120 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({const height = canvas.height;const cx = width / 2;const cy = height / 2;- const radius = width * 0.42;+ const radius = width * 0.41;ctx.clearRect(0, 0, width, height);- // Calculate normalized light vector- const light = getLightVector(settings.azimuth, settings.elevation, settings.isBacklit);- const lightLen = Math.hypot(light.x, light.y, light.z) || 1;- const lx = light.x / lightLen;- const ly = light.y / lightLen;- const lz = light.z / lightLen;+ // Unified light direction matching Local3DContainer exactly+ const light = sphericalLightToVector(settings.azimuth, settings.elevation, settings.isBacklit, 1);+ const lx = light.x;+ const ly = light.y;+ const lz = light.z;- // 1. Drop shadow beneath the 3D sphere+ // 1. Subtle studio drop shadow beneath the sphere (composited cleanly, never erased by putImageData)ctx.beginPath();- ctx.ellipse(cx, cy + radius * 0.88, radius * 0.85, radius * 0.25, 0, 0, Math.PI * 2);- ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';+ ctx.ellipse(cx, cy + radius * 0.94, radius * 0.78, radius * 0.18, 0, 0, Math.PI * 2);+ ctx.fillStyle = 'rgba(0, 0, 0, 0.42)';ctx.fill();- // 2. Base Sphere render with Phong/Lambertian shading- const imgData = ctx.createImageData(width, height);+ // 2. Render shaded sphere pixels into offscreen buffer so alpha composites over shadow+ if (!sphereBufferRef.current) {+ sphereBufferRef.current = document.createElement('canvas');+ }+ const buf = sphereBufferRef.current;+ if (buf.width !== width || buf.height !== height) {+ buf.width = width;+ buf.height = height;+ }+ const bufCtx = buf.getContext('2d');+ if (!bufCtx) return;++ const imgData = bufCtx.createImageData(width, height);const data = imgData.data;- // Parse light color hex- const cr = parseInt(settings.color.slice(1, 3), 16) || 255;- const cg = parseInt(settings.color.slice(3, 5), 16) || 255;- const cb = parseInt(settings.color.slice(5, 7), 16) || 255;+ const hex = settings.color.startsWith('#') && settings.color.length >= 7 ? settings.color : '#ffffff';+ const cr = parseInt(hex.slice(1, 3), 16) || 255;+ const cg = parseInt(hex.slice(3, 5), 16) || 255;+ const cb = parseInt(hex.slice(5, 7), 16) || 255;- const ambient = Math.min(1.0, Math.max(0.1, settings.ambientIntensity * 0.4));- const intensity = Math.min(2.5, settings.intensity);+ const ambient = Math.min(0.95, Math.max(0.06, settings.ambientIntensity * 0.42));+ const intensity = Math.min(2.6, Math.max(0, settings.intensity));for (let py = 0; py < height; py++) {for (let px = 0; px < width; px++) {const dx = (px - cx) / radius;- const dy = (cy - py) / radius; // Invert Y so up is positive+ const dy = (cy - py) / radius;const d2 = dx * dx + dy * dy;if (d2 <= 1.0) {const dz = Math.sqrt(Math.max(0, 1.0 - d2));- // Normal vector on sphere surface (dx, dy, dz)const dot = dx * lx + dy * ly + dz * lz;const diffuse = Math.max(0, dot);- // Blinn-Phong specular highlight- // View vector is (0, 0, 1)+ // Blinn-Phong specular highlight (view vector = 0,0,1)const hx = lx;const hy = ly;const hz = lz + 1.0;const hLen = Math.hypot(hx, hy, hz) || 1;const specDot = Math.max(0, (dx * hx + dy * hy + dz * hz) / hLen);- const specular = Math.pow(specDot, 24) * 0.7 * intensity;+ const specular = Math.pow(specDot, 26) * 0.65 * intensity;++ // Subtle rim glow when backlit so user sees backlight silhouette clearly+ const rim = settings.isBacklit ? Math.pow(1 - dz, 2.5) * 0.55 * intensity : 0;- const totalLight = ambient + diffuse * 0.75 * intensity + specular;+ const totalLight = ambient + diffuse * 0.78 * intensity + specular + rim;const idx = (py * width + px) * 4;- data[idx] = Math.min(255, Math.round(cr * totalLight * 0.8));- data[idx + 1] = Math.min(255, Math.round(cg * totalLight * 0.8));- data[idx + 2] = Math.min(255, Math.round(cb * totalLight * 0.8));- data[idx + 3] = 255;+ data[idx] = Math.min(255, Math.round(cr * totalLight * 0.82));+ data[idx + 1] = Math.min(255, Math.round(cg * totalLight * 0.82));+ data[idx + 2] = Math.min(255, Math.round(cb * totalLight * 0.82));+ // Anti-alias outer edge smoothly+ const edgeAlpha = d2 > 0.94 ? Math.max(0, (1 - d2) / 0.06) : 1;+ data[idx + 3] = Math.round(edgeAlpha * 255);}}}- ctx.putImageData(imgData, 0, 0);+ bufCtx.putImageData(imgData, 0, 0);+ ctx.drawImage(buf, 0, 0);// 3. Rim contour ringctx.beginPath();ctx.arc(cx, cy, radius, 0, Math.PI * 2);- ctx.strokeStyle = settings.isBacklit ? 'rgba(239, 68, 68, 0.6)' : 'rgba(59, 130, 246, 0.4)';- ctx.lineWidth = 2;+ ctx.strokeStyle = settings.isBacklit ? 'rgba(248, 113, 113, 0.7)' : 'rgba(56, 189, 248, 0.45)';+ ctx.lineWidth = 1.5;ctx.stroke();- // 4. Directional Arrow and Target Handle+ // 4. Directional vector guide and draggable sun handleconst handleX = cx + lx * radius * 0.85;- const handleY = cy - ly * radius * 0.85; // invert Y for screen coords+ const handleY = cy - ly * radius * 0.85;ctx.beginPath();ctx.moveTo(cx, cy);ctx.lineTo(handleX, handleY);- ctx.strokeStyle = settings.isBacklit ? '#ef4444' : '#38bdf8';- ctx.lineWidth = 2;+ ctx.strokeStyle = settings.isBacklit ? '#f87171' : '#38bdf8';+ ctx.lineWidth = 1.75;ctx.setLineDash([3, 2]);ctx.stroke();ctx.setLineDash([]);- // Glowing dot at light vector pointctx.beginPath();- ctx.arc(handleX, handleY, 6, 0, Math.PI * 2);+ ctx.arc(handleX, handleY, 5.5, 0, Math.PI * 2);ctx.fillStyle = settings.isBacklit ? '#f87171' : '#fde047';ctx.shadowColor = settings.isBacklit ? '#ef4444' : '#fbbf24';- ctx.shadowBlur = 8;+ ctx.shadowBlur = 7;ctx.fill();ctx.strokeStyle = '#ffffff';ctx.lineWidth = 1.5;ctx.stroke();ctx.shadowBlur = 0;- }, [settings, getLightVector]);+ }, [settings]);useEffect(() => {renderSphere();}, [renderSphere]);- // Handle direct click & drag on the 3D Light Sphere (Clip Studio Paint style)+ // Direct click & drag on the 3D Light Sphere (Clip Studio Paint style)const handlePointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {e.preventDefault();e.stopPropagation();@@ -162,7 +167,11 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({const canvas = canvasRef.current;if (!canvas) return;- canvas.setPointerCapture(e.pointerId);+ try {+ canvas.setPointerCapture(e.pointerId);+ } catch {+ // ignore+ }isDraggingRef.current = true;const updateFromPointer = (clientX: number, clientY: number) => {@@ -172,7 +181,7 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({const radius = (rect.width / 2) * 0.85;let dx = (clientX - cx) / radius;- let dy = -(clientY - cy) / radius; // Invert Y+ let dy = -(clientY - cy) / radius;const dist = Math.hypot(dx, dy);if (dist > 1.0) {@@ -180,15 +189,13 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({dy /= dist;}- // Compute spherical angles- // Elevation from Y (-85° to +85°)const elevation = Math.round(Math.asin(Math.max(-0.99, Math.min(0.99, dy))) * (180 / Math.PI));- // Azimuth from X and remaining forward axis- let azimuth = Math.round(Math.atan2(dx, Math.sqrt(Math.max(0, 1 - dx * dx - dy * dy))) * (180 / Math.PI));+ const forward = Math.sqrt(Math.max(0, 1 - dx * dx - dy * dy));+ let azimuth = Math.round(Math.atan2(dx, forward) * (180 / Math.PI));if (azimuth < 0) azimuth += 360;onChange({- ...settings,+ ...settingsRef.current,azimuth,elevation,});@@ -210,10 +217,12 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({}window.removeEventListener('pointermove', onPointerMove);window.removeEventListener('pointerup', onPointerUp);+ window.removeEventListener('pointercancel', onPointerUp);};window.addEventListener('pointermove', onPointerMove);window.addEventListener('pointerup', onPointerUp);+ window.addEventListener('pointercancel', onPointerUp);};const colorPresets = [@@ -221,19 +230,20 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({{ label: 'Warm Sun', color: '#fff3db' },{ label: 'Golden Hour', color: '#ffb56b' },{ label: 'Cool Sky', color: '#dbeafe' },+ { label: 'Cyber Cyan', color: '#67e8f9' },];return (<divclassName={embedded- ? 'bg-[#161616] border border-white/[0.06] rounded-md p-2.5 w-full text-xs text-[#e5e5e5] select-none'+ ? 'bg-[#161616] border border-white/[0.06] rounded-md p-2 w-full text-xs text-[#e5e5e5] select-none': 'bg-[#202020]/95 border border-white/[0.1] rounded-lg p-2.5 shadow-2xl backdrop-blur-md w-60 text-xs text-[#e5e5e5] select-none'}onPointerDown={(e) => e.stopPropagation()}><div className="flex items-center justify-between border-b border-white/[0.06] pb-1.5 mb-2">- <span className="text-[11px] font-medium text-[#e5e5e5]">Light Source</span>+ <span className="text-[11px] font-medium text-[#e5e5e5]">Key Light</span><div className="flex items-center space-x-1"><buttontype="button"@@ -245,7 +255,7 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({<buttontype="button"onClick={onReset}- title="Reset Light to Default (Top-Right Front)"+ title="Reset Lighting to Studio Default"className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"><RotateCcw className="w-3 h-3" />@@ -255,24 +265,22 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({{activeTab === 'sphere' ? (<div className="flex flex-col items-center">- {/* Interactive Shaded 3D Sphere */}<div className="relative group cursor-crosshair"><canvasref={canvasRef}- width={132}- height={132}+ width={sphereSize}+ height={sphereSize}onPointerDown={handlePointerDown}- className="rounded-full border border-white/[0.1]"+ className="rounded-full border border-white/[0.1] bg-[#111111]"style={{ touchAction: 'none' }}/><div className="absolute inset-0 pointer-events-none flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">- <span className="text-[9px] bg-black/70 px-1.5 py-0.5 rounded text-[#e5e5e5]">- Drag to angle+ <span className="text-[9px] bg-black/75 px-1.5 py-0.5 rounded text-[#e5e5e5]">+ Drag light angle</span></div></div>- {/* Front / Back Light Toggle */}<div className="flex items-center justify-between w-full mt-2 px-0.5"><buttontype="button"@@ -292,22 +300,20 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({</div>) : (<div className="space-y-2 py-1">- {/* Azimuth (Horizontal) */}<div className="flex items-center justify-between gap-2"><span className="text-[10px] text-[#8a8a8a] w-14">Azimuth</span><inputtype="range"min="0"max="360"- step="2"+ step="1"value={settings.azimuth}onChange={(e) => onChange({ ...settings, azimuth: parseInt(e.target.value, 10) })}className="flex-1"/>- <span className="text-[10px] font-mono w-7 text-right text-[#e5e5e5]">{settings.azimuth}°</span>+ <span className="text-[10px] font-mono w-8 text-right text-[#e5e5e5]">{settings.azimuth}°</span></div>- {/* Elevation (Vertical) */}<div className="flex items-center justify-between gap-2"><span className="text-[10px] text-[#8a8a8a] w-14">Elevation</span><input@@ -319,33 +325,35 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({onChange={(e) => onChange({ ...settings, elevation: parseInt(e.target.value, 10) })}className="flex-1"/>- <span className="text-[10px] font-mono w-7 text-right text-[#e5e5e5]">{settings.elevation}°</span>+ <span className="text-[10px] font-mono w-8 text-right text-[#e5e5e5]">{settings.elevation}°</span></div></div>)}- {/* Common Controls: Intensity & Ambient Fill */}- <div className="mt-2.5 pt-2 border-t border-white/[0.06] space-y-1.5">+ {/* Intensity, Fill & Color Controls */}+ <div className="mt-2 pt-2 border-t border-white/[0.06] space-y-1.5"><div className="flex items-center justify-between gap-2">- <span className="text-[10px] text-[#8a8a8a] w-14">Intensity</span>+ <span className="text-[10px] text-[#8a8a8a] w-12">Power</span><inputtype="range"- min="0.2"- max="2.5"+ min="0"+ max="3"step="0.05"value={settings.intensity}onChange={(e) => onChange({ ...settings, intensity: parseFloat(e.target.value) })}className="flex-1"/>- <span className="text-[10px] font-mono w-8 text-right text-[#e5e5e5]">{Math.round(settings.intensity * 100)}%</span>+ <span className="text-[10px] font-mono w-8 text-right text-[#e5e5e5]">+ {Math.round(settings.intensity * 100)}%+ </span></div><div className="flex items-center justify-between gap-2">- <span className="text-[10px] text-[#8a8a8a] w-14">Fill</span>+ <span className="text-[10px] text-[#8a8a8a] w-12">Ambient</span><inputtype="range"- min="0.1"- max="1.2"+ min="0"+ max="1.5"step="0.05"value={settings.ambientIntensity}onChange={(e) => onChange({ ...settings, ambientIntensity: parseFloat(e.target.value) })}@@ -356,17 +364,17 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({</span></div>- {/* Color Presets */}- <div className="flex items-center justify-between pt-1">- <span className="text-[10px] text-[#8a8a8a]">Tint</span>- <div className="flex items-center space-x-1.5">+ {/* Color Presets + Custom Picker */}+ <div className="flex items-center justify-between pt-1 gap-1">+ <span className="text-[10px] text-[#8a8a8a]">Color</span>+ <div className="flex items-center space-x-1">{colorPresets.map((preset) => (<buttonkey={preset.label}type="button"onClick={() => onChange({ ...settings, color: preset.color })}title={preset.label}- className={`w-4 h-4 rounded-full border transition-transform cursor-pointer ${+ className={`w-3.5 h-3.5 rounded-full border transition-transform cursor-pointer ${settings.color.toLowerCase() === preset.color.toLowerCase()? 'scale-110 border-[var(--accent)] ring-1 ring-[var(--accent)]': 'border-white/30 hover:scale-105'@@ -374,6 +382,13 @@ export const LightSourceWidget: React.FC<LightSourceWidgetProps> = ({style={{ backgroundColor: preset.color }}/>))}+ <input+ type="color"+ value={settings.color}+ onChange={(e) => onChange({ ...settings, color: e.target.value })}+ title="Custom Light Color"+ className="w-4 h-4 rounded bg-transparent border-0 cursor-pointer p-0"+ /></div></div></div>diff --git a/src/components/Local3DContainer.tsx b/src/components/Local3DContainer.tsxindex 34d022f..fea92cc 100644--- a/src/components/Local3DContainer.tsx+++ b/src/components/Local3DContainer.tsx@@ -1,13 +1,14 @@import React, { useEffect, useRef, useState, useCallback } from 'react';import { createPortal } from 'react-dom';import * as THREE from 'three';-import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';import * as BufferGeometryUtils from 'three/examples/jsm/utils/BufferGeometryUtils.js';-import { LayerItem, LTConversionSettings } from '../types/editor';+import { LayerItem, LTConversionSettings, ToolType } from '../types/editor';import { PerspectiveRuler } from '../types/perspective';+import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';+import { screenToCanvas } from '../utils/canvasUtils';import { calculatePerspectiveFromCamera } from '../utils/perspectiveMath';import {bake3DToRasterLayer,@@ -17,26 +18,55 @@ import {} from '../services/bake3DService';import { performanceManager } from '../utils/performanceManager';import {- createProceduralMannequin,findHumanoidBones,solveTwoBoneIK,createIKHandles,+ syncIKHandlesToBones,applyPosePreset,HumanoidBones,PosePresetName,} from '../utils/mannequin3D';-import { Csp3DToolbar, Csp3DToolMode } from './Csp3DToolbar';-import { LightSourceWidget, LightSettings } from './LightSourceWidget';-import { X, SlidersHorizontal, Upload } from 'lucide-react';--export type ShadingMode = 'shaded' | 'smooth' | 'silhouette';-export type GizmoMode = 'none' | 'rotate' | 'translate';+import {+ BonePoseSnapshot,+ Camera3DPreset,+ mapScreenDeltaToCanvasDelta,+ resolve3DPointerAction,+ resolve3DWheelAction,+ Resolved3DPointerAction,+ Scene3DHistoryStack,+ Scene3DSnapshot,+ Shading3DMode,+ snapAngleDeg,+ snapPositionCoord,+ snapScaleFactor,+ sphericalLightToVector,+ Tool3DMode,+} from '../utils/tool3DRules';+import {+ Model3DTransformState,+ scene3DBridge,+ store3DActions,+ toolStoreActions,+ use3DStore,+} from '../stores';+import { Csp3DToolbar } from './Csp3DToolbar';+import { LTExtractionModal, LTPreviewBuffers } from './LTExtractionModal';+import { Upload, Box } from 'lucide-react';++export type ShadingMode = Shading3DMode;+export type GizmoMode = 'none' | 'rotate' | 'translate' | 'scale';export interface Local3DContainerProps {- dimensions: { width: number; height: number };+ dimensions: { width: number; height: number; dpi?: number };+ viewportRef?: React.RefObject<HTMLDivElement | null>;+ navigation?: CanvasNavigationHandle;zoom?: number;pan?: { x: number; y: number };rotation?: number;+ flipX?: boolean;+ flipY?: boolean;+ activeTool?: ToolType;+ isSpaceDown?: boolean;isOpen: boolean;initialFile?: File | null;onClose: () => void;@@ -46,11 +76,43 @@ export interface Local3DContainerProps {onUpdatePerspectiveRuler?: (ruler: PerspectiveRuler | null) => void;}+const DEFAULT_CAMERA_POS = new THREE.Vector3(0, 1.35, 3.8);+const DEFAULT_CAMERA_TARGET = new THREE.Vector3(0, 0.85, 0);++function createToonGradientTexture(): THREE.DataTexture {+ // 3-step crisp manga cel shading ramp+ const colors = new Uint8Array([+ 85, 85, 95, 255,+ 175, 175, 182, 255,+ 248, 248, 250, 255,+ ]);+ const tex = new THREE.DataTexture(colors, 3, 1, THREE.RGBAFormat);+ tex.minFilter = THREE.NearestFilter;+ tex.magFilter = THREE.NearestFilter;+ tex.generateMipmaps = false;+ tex.needsUpdate = true;+ return tex;+}++function round2(n: number): number {+ return Math.round(n * 100) / 100;+}++function round1(n: number): number {+ return Math.round(n * 10) / 10;+}+export const Local3DContainer: React.FC<Local3DContainerProps> = ({dimensions,- zoom: _zoom,- pan: _pan,- rotation: _rotation = 0,+ viewportRef,+ navigation,+ zoom = 1,+ pan = { x: 0, y: 0 },+ rotation = 0,+ flipX = false,+ flipY = false,+ activeTool = '3d',+ isSpaceDown = false,isOpen,initialFile,onClose,@@ -66,202 +128,616 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({const loadedFileKeyRef = useRef<string | null>(null);const [webglError, setWebglError] = useState<string | null>(null);const [sceneReadyVersion, setSceneReadyVersion] = useState<number>(0);+ const [isLTModalOpen, setIsLTModalOpen] = useState<boolean>(false);++ // Store-backed reactive 3D state+ const activeMode = use3DStore((s) => s.activeMode);+ const gizmoMode = use3DStore((s) => s.gizmoMode);+ const gizmoSpace = use3DStore((s) => s.gizmoSpace);+ const snapEnabled = use3DStore((s) => s.snapEnabled);+ const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);+ const loadedModelName = use3DStore((s) => s.loadedModelName);+ const isBaking = use3DStore((s) => s.isBaking);+ const showIKHandles = use3DStore((s) => s.showIKHandles);+ const lighting = use3DStore((s) => s.lighting);+ const shadingMode = use3DStore((s) => s.shadingMode);+ const materialRoughness = use3DStore((s) => s.materialRoughness);+ const toonOutline = use3DStore((s) => s.toonOutline);+ const opacity = use3DStore((s) => s.opacity);+ const showGrid = use3DStore((s) => s.showGrid);+ const syncCameraPerspective = use3DStore((s) => s.syncCameraPerspective);++ // Live refs for zero-stale closures inside native listeners and rAF loops+ const activeToolRef = useRef<ToolType>(activeTool);+ activeToolRef.current = activeTool;+ const isSpaceDownRef = useRef<boolean>(isSpaceDown);+ isSpaceDownRef.current = isSpaceDown;+ const viewportMetaRef = useRef({ zoom, pan, rotation, flipX, flipY, dimensions });+ viewportMetaRef.current = { zoom, pan, rotation, flipX, flipY, dimensions };+ const onUpdatePerspectiveRulerRef = useRef(onUpdatePerspectiveRuler);+ onUpdatePerspectiveRulerRef.current = onUpdatePerspectiveRuler;+ const perspectiveRulerRef = useRef(perspectiveRuler);+ perspectiveRulerRef.current = perspectiveRuler;- // Local Three.js state references+ // Three.js scene referencesconst sceneRef = useRef<THREE.Scene | null>(null);const cameraRef = useRef<THREE.PerspectiveCamera | null>(null);+ const cameraTargetRef = useRef<THREE.Vector3>(DEFAULT_CAMERA_TARGET.clone());const rendererRef = useRef<THREE.WebGLRenderer | null>(null);- const controlsRef = useRef<OrbitControls | null>(null);const transformControlsRef = useRef<TransformControls | null>(null);const transformHelperRef = useRef<THREE.Object3D | null>(null);const animFrameRef = useRef<number | null>(null);const modelRootRef = useRef<THREE.Group | null>(null);const keyLightRef = useRef<THREE.DirectionalLight | null>(null);+ const rimLightRef = useRef<THREE.DirectionalLight | null>(null);const ambientLightRef = useRef<THREE.AmbientLight | null>(null);const hemiLightRef = useRef<THREE.HemisphereLight | null>(null);const gridHelperRef = useRef<THREE.GridHelper | null>(null);+ const shadowPlaneRef = useRef<THREE.Mesh | null>(null);+ const toonGradientTexRef = useRef<THREE.DataTexture | null>(null);const mannequinBonesRef = useRef<HumanoidBones | null>(null);const ikHandlesRef = useRef<Record<string, THREE.Mesh> | null>(null);const ikHandlesContainerRef = useRef<THREE.Group | null>(null);-- // Interaction State- const [activeToolMode, setActiveToolMode] = useState<Csp3DToolMode>('camera-orbit');- const [gizmoMode, setGizmoMode] = useState<GizmoMode>('none');- const [showGrid, setShowGrid] = useState<boolean>(true);- const [showInspector, setShowInspector] = useState<boolean>(true);- const [inspectorTab, setInspectorTab] = useState<'transform' | 'scene' | 'pose'>('transform');- const [showLightPanel, setShowLightPanel] = useState<boolean>(false);- const [isMannequinActive, setIsMannequinActive] = useState<boolean>(false);- const [syncCameraPerspective, setSyncCameraPerspective] = useState<boolean>(true);- const syncCameraPerspectiveRef = useRef<boolean>(syncCameraPerspective);- syncCameraPerspectiveRef.current = syncCameraPerspective;- const onUpdatePerspectiveRulerRef = useRef(onUpdatePerspectiveRuler);- onUpdatePerspectiveRulerRef.current = onUpdatePerspectiveRuler;- const perspectiveRulerRef = useRef(perspectiveRuler);- perspectiveRulerRef.current = perspectiveRuler;- const [activeIKHandle, setActiveIKHandle] = useState<string | null>(null);-- // Viewport Settings- const [opacity, setOpacity] = useState<number>(0.85);- const [shadingMode, setShadingMode] = useState<ShadingMode>('shaded');- const [perspective, setPerspective] = useState<number>(1.0); // 0.2 to 2.5 (Dolly Zoom)- const [isBaking, setIsBaking] = useState<boolean>(false);- const [loadedFileName, setLoadedFileName] = useState<string | null>(null);-- // Light Source Settings- const [lightSettings, setLightSettings] = useState<LightSettings>({- azimuth: 45,- elevation: 45,- intensity: 1.5,- ambientIntensity: 0.65,- color: '#ffffff',- isBacklit: false,- });-- // Drag interaction state on canvas+ const raycasterRef = useRef<THREE.Raycaster>(new THREE.Raycaster());+ const transformSyncRafRef = useRef<number | null>(null);+ const perspectiveSyncRafRef = useRef<number | null>(null);+ const gizmoSuppressedRef = useRef<boolean>(false);+ const historyStackRef = useRef<Scene3DHistoryStack>(new Scene3DHistoryStack(60));+ const historyDebounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const isRestoringHistoryRef = useRef<boolean>(false);++ // Active canvas drag stateconst canvasDragRef = useRef<{+ action: Resolved3DPointerAction;startX: number;startY: number;lastX: number;lastY: number;- button: number;+ moved: boolean;+ accumYawDeg: number;+ accumPitchDeg: number;+ accumRollDeg: number;+ startQuat: THREE.Quaternion | null;+ startScale: THREE.Vector3 | null;+ startPos: THREE.Vector3 | null;+ totalDx: number;+ totalDy: number;} | null>(null);- // Traverse and dispose cached procedural 3D materials and smoothed geometries+ const is3DToolActive = activeTool === '3d';+ const isInteractive = is3DToolActive && isReferenceVisible && !isSpaceDown;++ // Accurate clientX/clientY -> Three.js NDC [-1, 1] accounting for 2D canvas zoom, pan, rotation, flipX, flipY+ const clientToNDC = useCallback(+ (clientX: number, clientY: number): { x: number; y: number } => {+ const vp = viewportRef?.current;+ const meta = viewportMetaRef.current;+ if (vp) {+ const vpRect = vp.getBoundingClientRect();+ const cam = navigation+ ? navigation.getCameraState()+ : {+ pan: meta.pan,+ zoom: meta.zoom,+ rotation: meta.rotation,+ flipX: meta.flipX,+ flipY: meta.flipY,+ };+ const pt = screenToCanvas(+ clientX,+ clientY,+ vpRect,+ cam.pan,+ cam.zoom,+ cam.rotation,+ meta.dimensions,+ cam.flipX,+ cam.flipY+ );+ return {+ x: (pt.x / Math.max(1, meta.dimensions.width)) * 2 - 1,+ y: -(pt.y / Math.max(1, meta.dimensions.height)) * 2 + 1,+ };+ }+ const canvas = canvasRef.current;+ if (canvas) {+ const rect = canvas.getBoundingClientRect();+ return {+ x: ((clientX - rect.left) / Math.max(1, rect.width)) * 2 - 1,+ y: -((clientY - rect.top) / Math.max(1, rect.height)) * 2 + 1,+ };+ }+ return { x: 0, y: 0 };+ },+ [navigation, viewportRef]+ );++ // Sync live modelRoot transform back into use3DStore (rAF throttled)+ const scheduleTransformSyncToStore = useCallback(() => {+ if (transformSyncRafRef.current !== null) return;+ transformSyncRafRef.current = requestAnimationFrame(() => {+ transformSyncRafRef.current = null;+ const model = modelRootRef.current;+ if (!model) return;+ const euler = new THREE.Euler().setFromQuaternion(model.quaternion, 'YXZ');+ store3DActions.setModelTransform({+ position: [round2(model.position.x), round2(model.position.y), round2(model.position.z)],+ rotation: [+ round1(THREE.MathUtils.radToDeg(euler.x)),+ round1(THREE.MathUtils.radToDeg(euler.y)),+ round1(THREE.MathUtils.radToDeg(euler.z)),+ ],+ scale: [round2(model.scale.x), round2(model.scale.y), round2(model.scale.z)],+ });+ });+ }, []);++ // Optional throttled perspective ruler sync when explicitly enabled+ const schedulePerspectiveRulerSync = useCallback((force = false) => {+ const shouldSync = force || use3DStore.getState().syncCameraPerspective;+ if (!shouldSync || !onUpdatePerspectiveRulerRef.current || !cameraRef.current) return;+ if (perspectiveSyncRafRef.current !== null) return;+ perspectiveSyncRafRef.current = requestAnimationFrame(() => {+ perspectiveSyncRafRef.current = null;+ if (!cameraRef.current || !onUpdatePerspectiveRulerRef.current) return;+ cameraRef.current.updateMatrixWorld(true);+ const dims = viewportMetaRef.current.dimensions;+ const ruler = calculatePerspectiveFromCamera(+ cameraRef.current,+ dims.width,+ dims.height,+ perspectiveRulerRef.current+ );+ onUpdatePerspectiveRulerRef.current(ruler);+ });+ }, []);++ // --- 3D Undo / Redo Snapshot Helpers (Ctrl+Z / Ctrl+Y) ---+ const syncHistoryFlagsToStore = useCallback(() => {+ const stack = historyStackRef.current;+ store3DActions.setHistoryFlags(stack.canUndo(), stack.canRedo());+ }, []);++ const captureSceneSnapshot = useCallback((): Scene3DSnapshot | null => {+ const camera = cameraRef.current;+ if (!camera) return null;+ const model = modelRootRef.current;+ const target = cameraTargetRef.current;+ const s = use3DStore.getState();++ let bonesSnap: Record<string, BonePoseSnapshot> | undefined;+ if (mannequinBonesRef.current) {+ bonesSnap = {};+ for (const [key, bone] of Object.entries(mannequinBonesRef.current)) {+ if (!bone) continue;+ bonesSnap[key] = {+ q: [bone.quaternion.x, bone.quaternion.y, bone.quaternion.z, bone.quaternion.w],+ ...(key === 'hips'+ ? { p: [bone.position.x, bone.position.y, bone.position.z] as [number, number, number] }+ : {}),+ };+ }+ }++ return {+ modelPosition: model ? [model.position.x, model.position.y, model.position.z] : [0, 0, 0],+ modelQuaternion: model+ ? [model.quaternion.x, model.quaternion.y, model.quaternion.z, model.quaternion.w]+ : [0, 0, 0, 1],+ modelScale: model ? [model.scale.x, model.scale.y, model.scale.z] : [1, 1, 1],+ cameraPosition: [camera.position.x, camera.position.y, camera.position.z],+ cameraTarget: [target.x, target.y, target.z],+ cameraFov: camera.fov,+ perspective: s.perspective,+ lighting: {+ keyLight: { ...s.lighting.keyLight },+ rimLight: { ...s.lighting.rimLight },+ ambientIntensity: s.lighting.ambientIntensity,+ ambientColor: s.lighting.ambientColor,+ castGroundShadow: s.lighting.castGroundShadow,+ shadowOpacity: s.lighting.shadowOpacity,+ },+ shadingMode: s.shadingMode,+ materialRoughness: s.materialRoughness,+ toonOutline: s.toonOutline,+ opacity: s.opacity,+ showGrid: s.showGrid,+ ...(bonesSnap ? { bones: bonesSnap } : {}),+ };+ }, []);++ const commitHistoryNow = useCallback(() => {+ if (isRestoringHistoryRef.current) return;+ if (historyDebounceTimerRef.current) {+ clearTimeout(historyDebounceTimerRef.current);+ historyDebounceTimerRef.current = null;+ }+ const snap = captureSceneSnapshot();+ if (!snap) return;+ if (historyStackRef.current.length === 0) {+ historyStackRef.current.reset(snap);+ } else {+ historyStackRef.current.push(snap);+ }+ syncHistoryFlagsToStore();+ }, [captureSceneSnapshot, syncHistoryFlagsToStore]);++ const scheduleDebouncedHistoryCommit = useCallback(() => {+ if (isRestoringHistoryRef.current || historyStackRef.current.length === 0) return;+ if (historyDebounceTimerRef.current) {+ clearTimeout(historyDebounceTimerRef.current);+ }+ historyDebounceTimerRef.current = setTimeout(() => {+ historyDebounceTimerRef.current = null;+ commitHistoryNow();+ }, 260);+ }, [commitHistoryNow]);++ const restoreSceneSnapshot = useCallback(+ (snap: Scene3DSnapshot) => {+ isRestoringHistoryRef.current = true;+ try {+ if (modelRootRef.current) {+ modelRootRef.current.position.set(...snap.modelPosition);+ modelRootRef.current.quaternion.set(...snap.modelQuaternion).normalize();+ modelRootRef.current.scale.set(...snap.modelScale);+ modelRootRef.current.updateMatrixWorld(true);+ const euler = new THREE.Euler().setFromQuaternion(modelRootRef.current.quaternion, 'YXZ');+ store3DActions.setModelTransform({+ position: [+ round2(snap.modelPosition[0]),+ round2(snap.modelPosition[1]),+ round2(snap.modelPosition[2]),+ ],+ rotation: [+ round1(THREE.MathUtils.radToDeg(euler.x)),+ round1(THREE.MathUtils.radToDeg(euler.y)),+ round1(THREE.MathUtils.radToDeg(euler.z)),+ ],+ scale: [+ round2(snap.modelScale[0]),+ round2(snap.modelScale[1]),+ round2(snap.modelScale[2]),+ ],+ });+ }++ if (cameraRef.current) {+ cameraTargetRef.current.set(...snap.cameraTarget);+ cameraRef.current.position.set(...snap.cameraPosition);+ cameraRef.current.fov = snap.cameraFov;+ cameraRef.current.updateProjectionMatrix();+ cameraRef.current.lookAt(cameraTargetRef.current);+ schedulePerspectiveRulerSync();+ }++ if (snap.bones && mannequinBonesRef.current) {+ for (const [key, pose] of Object.entries(snap.bones)) {+ const bone = mannequinBonesRef.current[key];+ if (!bone) continue;+ bone.quaternion.set(...pose.q).normalize();+ if (pose.p) {+ bone.position.set(...pose.p);+ }+ bone.updateMatrixWorld(true);+ }+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ } else if (mannequinBonesRef.current) {+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ }++ store3DActions.setPerspective(snap.perspective, Math.round(snap.cameraFov));+ store3DActions.updateLighting({+ keyLight: { ...snap.lighting.keyLight },+ rimLight: { ...snap.lighting.rimLight },+ ambientIntensity: snap.lighting.ambientIntensity,+ ambientColor: snap.lighting.ambientColor,+ castGroundShadow: snap.lighting.castGroundShadow,+ shadowOpacity: snap.lighting.shadowOpacity,+ });+ store3DActions.setShadingMode(snap.shadingMode);+ store3DActions.setMaterialRoughness(snap.materialRoughness);+ store3DActions.setToonOutline(snap.toonOutline);+ store3DActions.setOpacity(snap.opacity);+ store3DActions.setShowGrid(snap.showGrid);+ } finally {+ // Release restoration guard after React effects for the restored store values flush+ queueMicrotask(() => {+ isRestoringHistoryRef.current = false;+ });+ }+ syncHistoryFlagsToStore();+ },+ [schedulePerspectiveRulerSync, syncHistoryFlagsToStore]+ );++ const handleUndo3D = useCallback((): boolean => {+ // Flush any pending debounced slider/wheel edit before stepping back+ if (historyDebounceTimerRef.current) {+ commitHistoryNow();+ }+ const prev = historyStackRef.current.undo();+ if (!prev) {+ syncHistoryFlagsToStore();+ return false;+ }+ restoreSceneSnapshot(prev);+ return true;+ }, [commitHistoryNow, restoreSceneSnapshot, syncHistoryFlagsToStore]);++ const handleRedo3D = useCallback((): boolean => {+ if (historyDebounceTimerRef.current) {+ clearTimeout(historyDebounceTimerRef.current);+ historyDebounceTimerRef.current = null;+ }+ const next = historyStackRef.current.redo();+ if (!next) {+ syncHistoryFlagsToStore();+ return false;+ }+ restoreSceneSnapshot(next);+ return true;+ }, [restoreSceneSnapshot, syncHistoryFlagsToStore]);++ // Dispose cached procedural materials, smoothed geometries, and outline meshesconst disposeMeshUserData = useCallback((obj: THREE.Object3D) => {+ const outlinesToRemove: THREE.Object3D[] = [];obj.traverse((child) => {+ if (child.userData?.is3DOutline) {+ outlinesToRemove.push(child);+ }const m = child as THREE.Mesh;if (m.isMesh) {if (m.userData.smoothGeometry) {m.userData.smoothGeometry.dispose();m.userData.smoothGeometry = null;}- if (m.userData.silhouetteMaterial) {- m.userData.silhouetteMaterial.dispose();- m.userData.silhouetteMaterial = null;- }- if (m.userData.shadedMaterial) {- m.userData.shadedMaterial.dispose();- m.userData.shadedMaterial = null;- }- if (m.userData.smoothMaterial) {- if (Array.isArray(m.userData.smoothMaterial)) {- m.userData.smoothMaterial.forEach((mat: THREE.Material) => mat.dispose());- } else {- m.userData.smoothMaterial.dispose();+ for (const key of [+ 'silhouetteMaterial',+ 'shadedMaterial',+ 'smoothMaterial',+ 'toonMaterial',+ 'wireframeMaterial',+ ]) {+ const mat = m.userData[key];+ if (mat) {+ if (Array.isArray(mat)) {+ mat.forEach((item: THREE.Material) => item.dispose());+ } else {+ mat.dispose();+ }+ m.userData[key] = null;}- m.userData.smoothMaterial = null;}}});+ for (const outline of outlinesToRemove) {+ const m = outline as THREE.Mesh;+ if (m.material && !Array.isArray(m.material)) m.material.dispose();+ outline.parent?.remove(outline);+ }}, []);- // Apply visual shading mode: Shaded, Advanced Smooth Shading, or Silhouette- const applyShading = useCallback((mode: ShadingMode) => {- if (!modelRootRef.current) return;-- modelRootRef.current.traverse((child) => {- const mesh = child as THREE.Mesh;- if (!mesh.isMesh) return;-- if (!mesh.userData.origGeometry) {- mesh.userData.origGeometry = mesh.geometry;- }- if (!mesh.userData.origMaterial) {- mesh.userData.origMaterial = mesh.material;+ // Apply shading mode, material roughness, and optional inverted-hull manga outline+ const applyShadingAndStyle = useCallback(+ (mode: Shading3DMode, roughness: number, enableOutline: boolean) => {+ if (!modelRootRef.current) return;+ const gradTex = toonGradientTexRef.current;++ // Remove existing outline children before rebuilding if needed+ const existingOutlines: THREE.Object3D[] = [];+ modelRootRef.current.traverse((child) => {+ if (child.userData?.is3DOutline) {+ existingOutlines.push(child);+ }+ });+ for (const o of existingOutlines) {+ const m = o as THREE.Mesh;+ if (m.material && !Array.isArray(m.material)) m.material.dispose();+ o.parent?.remove(o);}- if (mode === 'silhouette') {- if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {- mesh.geometry = mesh.userData.origGeometry;- }- if (!mesh.userData.silhouetteMaterial) {- mesh.userData.silhouetteMaterial = new THREE.MeshBasicMaterial({- color: 0x111827,- });- }- mesh.material = mesh.userData.silhouetteMaterial;- } else if (mode === 'smooth') {- // 1. Advanced Geometry Normal Smoothing (vertex welding + creased normals)- if (!mesh.userData.smoothGeometry && mesh.userData.origGeometry) {- try {- const merged = BufferGeometryUtils.mergeVertices(mesh.userData.origGeometry.clone(), 1e-4);- mesh.userData.smoothGeometry = BufferGeometryUtils.toCreasedNormals(merged, (55 * Math.PI) / 180);- } catch (err) {- console.warn('[3D] Smooth geometry calculation fallback:', err);- const fallback = mesh.userData.origGeometry.clone();- fallback.computeVertexNormals();- mesh.userData.smoothGeometry = fallback;- }+ const meshesToProcess: THREE.Mesh[] = [];+ modelRootRef.current.traverse((child) => {+ const mesh = child as THREE.Mesh;+ if (mesh.isMesh && !mesh.userData?.is3DHelper && !mesh.userData?.is3DOutline) {+ meshesToProcess.push(mesh);}+ });- if (mesh.userData.smoothGeometry) {- mesh.geometry = mesh.userData.smoothGeometry;+ for (const mesh of meshesToProcess) {+ const isSkinned = Boolean((mesh as THREE.SkinnedMesh).isSkinnedMesh);+ if (!mesh.userData.origGeometry) {+ mesh.userData.origGeometry = mesh.geometry;+ }+ if (!mesh.userData.origMaterial) {+ mesh.userData.origMaterial = mesh.material;}- // 2. Material Smoothing with studio PBR highlights- const makeSmoothMat = (mat: THREE.Material): THREE.Material => {- const smooth = mat.clone();- if ('flatShading' in smooth) {- (smooth as any).flatShading = false;+ const extractBaseColor = (mat: THREE.Material | THREE.Material[]): number => {+ const single = Array.isArray(mat) ? mat[0] : mat;+ if (single && 'color' in single && (single as any).color?.isColor) {+ return (single as any).color.getHex();}- if ('roughness' in smooth && typeof (smooth as any).roughness === 'number') {- (smooth as any).roughness = Math.max(0.2, (smooth as any).roughness * 0.9);+ return 0xe2e8f0;+ };++ const extractMap = (mat: THREE.Material | THREE.Material[]): THREE.Texture | null => {+ const single = Array.isArray(mat) ? mat[0] : mat;+ if (single && 'map' in single && (single as any).map) {+ return (single as any).map as THREE.Texture;}- smooth.needsUpdate = true;- return smooth;+ return null;};- if (!mesh.userData.smoothMaterial) {- if (mesh.userData.hasCustomMaterial && mesh.userData.origMaterial) {- if (Array.isArray(mesh.userData.origMaterial)) {- mesh.userData.smoothMaterial = mesh.userData.origMaterial.map(makeSmoothMat);+ if (mode === 'silhouette') {+ if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {+ mesh.geometry = mesh.userData.origGeometry;+ }+ if (!mesh.userData.silhouetteMaterial) {+ mesh.userData.silhouetteMaterial = new THREE.MeshBasicMaterial({+ color: 0x111827,+ side: THREE.DoubleSide,+ });+ }+ mesh.material = mesh.userData.silhouetteMaterial;+ } else if (mode === 'wireframe') {+ if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {+ mesh.geometry = mesh.userData.origGeometry;+ }+ if (!mesh.userData.wireframeMaterial) {+ mesh.userData.wireframeMaterial = new THREE.MeshStandardMaterial({+ color: 0x38bdf8,+ roughness: 0.5,+ metalness: 0.1,+ wireframe: true,+ });+ }+ mesh.material = mesh.userData.wireframeMaterial;+ } else if (mode === 'toon') {+ if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {+ mesh.geometry = mesh.userData.origGeometry;+ }+ if (!mesh.userData.toonMaterial) {+ const baseHex = mesh.userData.hasCustomMaterial+ ? extractBaseColor(mesh.userData.origMaterial)+ : 0xe8edf2;+ const baseMap = mesh.userData.hasCustomMaterial+ ? extractMap(mesh.userData.origMaterial)+ : null;+ mesh.userData.toonMaterial = new THREE.MeshToonMaterial({+ color: baseHex,+ map: baseMap,+ gradientMap: gradTex,+ side: THREE.DoubleSide,+ });+ }+ mesh.material = mesh.userData.toonMaterial;+ } else if (mode === 'smooth') {+ // Never run mergeVertices on SkinnedMesh (would corrupt skinIndex/skinWeight binding!)+ if (!isSkinned && !mesh.userData.smoothGeometry && mesh.userData.origGeometry) {+ try {+ const cloned = mesh.userData.origGeometry.clone();+ const merged = BufferGeometryUtils.mergeVertices(cloned, 1e-4);+ mesh.userData.smoothGeometry = BufferGeometryUtils.toCreasedNormals(+ merged,+ (55 * Math.PI) / 180+ );+ } catch {+ const fallback = mesh.userData.origGeometry.clone();+ fallback.computeVertexNormals();+ mesh.userData.smoothGeometry = fallback;+ }+ }+ if (!isSkinned && mesh.userData.smoothGeometry) {+ mesh.geometry = mesh.userData.smoothGeometry;+ }++ const makeSmoothMat = (mat: THREE.Material): THREE.Material => {+ const smooth = mat.clone();+ if ('flatShading' in smooth) (smooth as any).flatShading = false;+ if ('roughness' in smooth && typeof (smooth as any).roughness === 'number') {+ (smooth as any).roughness = Math.max(0.12, roughness * 0.85);+ }+ smooth.needsUpdate = true;+ return smooth;+ };++ if (!mesh.userData.smoothMaterial) {+ if (mesh.userData.hasCustomMaterial && mesh.userData.origMaterial) {+ mesh.userData.smoothMaterial = Array.isArray(mesh.userData.origMaterial)+ ? mesh.userData.origMaterial.map(makeSmoothMat)+ : makeSmoothMat(mesh.userData.origMaterial);} else {- mesh.userData.smoothMaterial = makeSmoothMat(mesh.userData.origMaterial);+ mesh.userData.smoothMaterial = new THREE.MeshStandardMaterial({+ color: 0xdee4eb,+ roughness: Math.max(0.12, roughness * 0.85),+ metalness: 0.05,+ flatShading: false,+ side: THREE.DoubleSide,+ });}} else {- mesh.userData.smoothMaterial = new THREE.MeshStandardMaterial({- color: 0xdee2e6,- roughness: 0.32,- metalness: 0.05,- flatShading: false,- });+ const sm = mesh.userData.smoothMaterial;+ if (Array.isArray(sm)) {+ sm.forEach((m: any) => {+ if (typeof m.roughness === 'number') m.roughness = Math.max(0.12, roughness * 0.85);+ });+ } else if (typeof sm.roughness === 'number') {+ sm.roughness = Math.max(0.12, roughness * 0.85);+ }}- }- mesh.material = mesh.userData.smoothMaterial;- } else {- // 'shaded' mode: Restore original geometry and material- if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {- mesh.geometry = mesh.userData.origGeometry;- }-- if (mesh.userData.origMaterial && mesh.userData.hasCustomMaterial) {- mesh.material = mesh.userData.origMaterial;+ mesh.material = mesh.userData.smoothMaterial;} else {- if (!mesh.userData.shadedMaterial) {- mesh.userData.shadedMaterial = new THREE.MeshStandardMaterial({- color: 0xe2e8f0,- roughness: 0.35,- metalness: 0.1,- });+ // 'shaded' studio PBR+ if (mesh.userData.origGeometry && mesh.geometry !== mesh.userData.origGeometry) {+ mesh.geometry = mesh.userData.origGeometry;+ }+ if (mesh.userData.origMaterial && mesh.userData.hasCustomMaterial) {+ mesh.material = mesh.userData.origMaterial;+ } else {+ if (!mesh.userData.shadedMaterial) {+ mesh.userData.shadedMaterial = new THREE.MeshStandardMaterial({+ color: 0xe2e8f0,+ roughness,+ metalness: 0.08,+ side: THREE.DoubleSide,+ });+ } else {+ mesh.userData.shadedMaterial.roughness = roughness;+ }+ mesh.material = mesh.userData.shadedMaterial;}- mesh.material = mesh.userData.shadedMaterial;+ }++ // Optional inverted-hull manga outline preview (for non-skinned meshes)+ if (enableOutline && !isSkinned && mode !== 'wireframe') {+ const outlineMat = new THREE.MeshBasicMaterial({+ color: 0x0f172a,+ side: THREE.BackSide,+ });+ const outlineMesh = new THREE.Mesh(mesh.geometry, outlineMat);+ outlineMesh.scale.setScalar(1.022);+ outlineMesh.userData.is3DOutline = true;+ outlineMesh.castShadow = false;+ outlineMesh.receiveShadow = false;+ mesh.add(outlineMesh);}}- });- }, []);+ },+ []+ );- // Update TransformControls attachment when model changes- const updateGizmoTarget = useCallback(() => {- if (!transformControlsRef.current) return;- if (modelRootRef.current && gizmoMode !== 'none') {- transformControlsRef.current.attach(modelRootRef.current);- if (transformHelperRef.current) transformHelperRef.current.visible = true;+ // Sync gizmo attachment to model root (unless an IK handle is currently selected)+ const syncGizmoAttachment = useCallback(() => {+ const tc = transformControlsRef.current;+ const helper = transformHelperRef.current;+ if (!tc || !helper) return;++ const state = use3DStore.getState();+ const canShow = activeToolRef.current === '3d' && state.isReferenceVisible && !isSpaceDownRef.current;++ if (state.activeIKHandle && ikHandlesRef.current?.[state.activeIKHandle]) {+ tc.setMode('translate');+ tc.setSpace('world');+ tc.attach(ikHandlesRef.current[state.activeIKHandle]);+ helper.visible = canShow;+ tc.enabled = canShow;+ return;+ }++ if (state.gizmoMode === 'none' || !modelRootRef.current) {+ tc.detach();+ helper.visible = false;+ tc.enabled = false;} else {- transformControlsRef.current.detach();- if (transformHelperRef.current) transformHelperRef.current.visible = false;+ tc.setMode(state.gizmoMode);+ tc.setSpace(state.gizmoSpace);+ tc.attach(modelRootRef.current);+ helper.visible = canShow;+ tc.enabled = canShow;}- }, [gizmoMode]);+ }, []);// Initialize Three.js scene strictly locally on a fresh canvas per lifecycleuseEffect(() => {@@ -272,7 +748,6 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({setWebglError(null);const docAspect = dimensions.width / Math.max(1, dimensions.height);-const perf = performanceManager.getConfig();const MAX_PREVIEW = perf.preview3DMaxResolution || 1920;let previewW = dimensions.width;@@ -287,7 +762,6 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({}}- // Create a fresh WebGL renderer & canvas so StrictMode/re-mounts never touch a force-lost contextlet renderer: THREE.WebGLRenderer;try {renderer = createSafeWebGLRenderer({@@ -316,103 +790,179 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({sceneRef.current = scene;// 2. Perspective Camera- const camera = new THREE.PerspectiveCamera(45, docAspect, 0.05, 500);- camera.position.set(0, 0.5, 3.8);+ const camera = new THREE.PerspectiveCamera(use3DStore.getState().fov || 45, docAspect, 0.05, 500);+ camera.position.copy(DEFAULT_CAMERA_POS);+ cameraTargetRef.current.copy(DEFAULT_CAMERA_TARGET);+ camera.lookAt(cameraTargetRef.current);cameraRef.current = camera;- // 3. Configure WebGL Renderer+ // 3. Configure WebGL Renderer (Shadows + Filmic Tone Mapping)renderer.setSize(previewW, previewH, false);renderer.setPixelRatio(1);renderer.setClearColor(0x000000, 0);+ if ('toneMapping' in renderer) {+ renderer.toneMapping = THREE.ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ }+ if (renderer.shadowMap) {+ renderer.shadowMap.enabled = true;+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;+ }rendererRef.current = renderer;- // 4. Ground Grid Helper (Clip Studio Paint style floor grid)- const gridHelper = new THREE.GridHelper(8, 16, 0x3b82f6, 0x334155);+ // Toon gradient texture+ toonGradientTexRef.current = createToonGradientTexture();++ // 4. Floor Grid Helper (CSP-style studio grid)+ const gridHelper = new THREE.GridHelper(10, 20, 0x3b82f6, 0x334155);gridHelper.position.y = 0;+ gridHelper.userData.is3DHelper = true;scene.add(gridHelper);gridHelperRef.current = gridHelper;- // 5. Lighting Setup- const hemiLight = new THREE.HemisphereLight(0xffffff, 0x475569, 0.7);+ // 5. Shadow-Catching Ground Plane (Y = 0)+ const shadowGeo = new THREE.PlaneGeometry(14, 14);+ const shadowMat = new THREE.ShadowMaterial({ opacity: 0.32 });+ const shadowPlane = new THREE.Mesh(shadowGeo, shadowMat);+ shadowPlane.rotation.x = -Math.PI / 2;+ shadowPlane.position.y = 0.001;+ shadowPlane.receiveShadow = true;+ shadowPlane.userData.is3DHelper = true;+ scene.add(shadowPlane);+ shadowPlaneRef.current = shadowPlane;++ // 6. Clip Studio Advanced Dual Lighting Setup+ const hemiLight = new THREE.HemisphereLight(0xffffff, 0x475569, 0.45);scene.add(hemiLight);hemiLightRef.current = hemiLight;- const ambientLight = new THREE.AmbientLight(0xffffff, 0.65);+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.55);scene.add(ambientLight);ambientLightRef.current = ambientLight;- const keyLight = new THREE.DirectionalLight(0xffffff, 1.5);- keyLight.position.set(2.5, 4, 3);+ const keyLight = new THREE.DirectionalLight(0xffffff, 1.4);+ keyLight.position.set(3, 4.5, 3.5);+ keyLight.castShadow = true;+ keyLight.shadow.mapSize.width = 1024;+ keyLight.shadow.mapSize.height = 1024;+ keyLight.shadow.camera.near = 0.5;+ keyLight.shadow.camera.far = 22;+ keyLight.shadow.camera.left = -4;+ keyLight.shadow.camera.right = 4;+ keyLight.shadow.camera.top = 4;+ keyLight.shadow.camera.bottom = -4;+ keyLight.shadow.bias = -0.0005;scene.add(keyLight);keyLightRef.current = keyLight;- const rimLight = new THREE.DirectionalLight(0x60a5fa, 0.6);- rimLight.position.set(-3, 2, -3);+ const rimLight = new THREE.DirectionalLight(0x93c5fd, 0.55);+ rimLight.position.set(-3.5, 2.5, -3.5);scene.add(rimLight);+ rimLightRef.current = rimLight;- // 6. OrbitControls for navigation- const controls = new OrbitControls(camera, canvas);- controls.enableDamping = true;- controls.dampingFactor = 0.08;- controls.target.set(0, 0.3, 0);- controls.addEventListener('change', () => {- if (syncCameraPerspectiveRef.current && onUpdatePerspectiveRulerRef.current && cameraRef.current) {- const ruler = calculatePerspectiveFromCamera(- cameraRef.current,- dimensions.width,- dimensions.height,- perspectiveRulerRef.current- );- onUpdatePerspectiveRulerRef.current(ruler);- }- });- controlsRef.current = controls;-- // 7. TransformControls for 3D In-Scene Gizmo Rings+ // 7. TransformControls for On-Canvas 3D Manipulator (Rotate / Translate / Scale)const transformControls = new TransformControls(camera, canvas);transformControls.size = 0.85;- transformControls.setSpace('local');+ transformControls.setSpace(use3DStore.getState().gizmoSpace);++ // CRITICAL FIX: Override TransformControls pointer projection so gizmos work pixel-perfectly+ // under ANY 2D canvas pan, zoom, rotation, or horizontal/vertical flip!+ (transformControls as any)._getPointer = (event: PointerEvent) => {+ const ndc = clientToNDC(event.clientX, event.clientY);+ return { x: ndc.x, y: ndc.y, button: event.button };+ };+const transformHelper = transformControls.getHelper();+ transformHelper.userData.is3DHelper = true;+ transformHelper.traverse((child) => {+ child.userData.is3DHelper = true;+ });transformHelper.visible = false;scene.add(transformHelper);transformControls.addEventListener('dragging-changed', (event: any) => {- if (controlsRef.current) {- controlsRef.current.enabled = !event.value;+ if (!event.value) {+ commitHistoryNow();}});transformControls.addEventListener('objectChange', () => {const targetObj = transformControls.object;- if (targetObj && targetObj.name.startsWith('IKHandle_') && mannequinBonesRef.current) {+ if (!targetObj) return;++ if (targetObj.name.startsWith('IKHandle_') && mannequinBonesRef.current) {const handleName = targetObj.name.replace('IKHandle_', '');const bones = mannequinBonesRef.current;- const targetPos = targetObj.position;+ const targetPos = targetObj.position.clone();+ const toWorldPole = (localPole: THREE.Vector3) =>+ modelRootRef.current ? modelRootRef.current.localToWorld(localPole.clone()) : localPole;+if (handleName === 'leftHand' && bones.leftUpperArm && bones.leftLowerArm && bones.leftHand) {- solveTwoBoneIK(bones.leftUpperArm, bones.leftLowerArm, bones.leftHand, targetPos, new THREE.Vector3(0.6, 1.2, -0.4));+ solveTwoBoneIK(+ bones.leftUpperArm,+ bones.leftLowerArm,+ bones.leftHand,+ targetPos,+ toWorldPole(new THREE.Vector3(0.6, 1.2, -0.5))+ );} else if (handleName === 'rightHand' && bones.rightUpperArm && bones.rightLowerArm && bones.rightHand) {- solveTwoBoneIK(bones.rightUpperArm, bones.rightLowerArm, bones.rightHand, targetPos, new THREE.Vector3(-0.6, 1.2, -0.4));+ solveTwoBoneIK(+ bones.rightUpperArm,+ bones.rightLowerArm,+ bones.rightHand,+ targetPos,+ toWorldPole(new THREE.Vector3(-0.6, 1.2, -0.5))+ );} else if (handleName === 'leftFoot' && bones.leftUpperLeg && bones.leftLowerLeg && bones.leftFoot) {- solveTwoBoneIK(bones.leftUpperLeg, bones.leftLowerLeg, bones.leftFoot, targetPos, new THREE.Vector3(0.12, 0.48, 0.5));+ solveTwoBoneIK(+ bones.leftUpperLeg,+ bones.leftLowerLeg,+ bones.leftFoot,+ targetPos,+ toWorldPole(new THREE.Vector3(0.15, 0.5, 0.8))+ );} else if (handleName === 'rightFoot' && bones.rightUpperLeg && bones.rightLowerLeg && bones.rightFoot) {- solveTwoBoneIK(bones.rightUpperLeg, bones.rightLowerLeg, bones.rightFoot, targetPos, new THREE.Vector3(-0.12, 0.48, 0.5));- } else if (handleName === 'head' && bones.neck && bones.head) {+ solveTwoBoneIK(+ bones.rightUpperLeg,+ bones.rightLowerLeg,+ bones.rightFoot,+ targetPos,+ toWorldPole(new THREE.Vector3(-0.15, 0.5, 0.8))+ );+ } else if (handleName === 'head' && bones.head) {bones.head.lookAt(targetPos);bones.head.updateMatrixWorld(true);}+ } else if (targetObj === modelRootRef.current) {+ // Enforce uniform scaling if locked in TransformControls scale mode+ if (+ transformControls.mode === 'scale' &&+ use3DStore.getState().modelTransform.uniformScale+ ) {+ const avg = Math.max(0.05, Math.min(10, (targetObj.scale.x + targetObj.scale.y + targetObj.scale.z) / 3));+ targetObj.scale.setScalar(avg);+ } else if (transformControls.mode === 'scale') {+ targetObj.scale.set(+ Math.max(0.05, Math.min(10, targetObj.scale.x)),+ Math.max(0.05, Math.min(10, targetObj.scale.y)),+ Math.max(0.05, Math.min(10, targetObj.scale.z))+ );+ }+ targetObj.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();}});transformControlsRef.current = transformControls;transformHelperRef.current = transformHelper;- // 8. Render Loop (skips GPU work while document/tab is hidden to save battery & VRAM bandwidth)+ // 8. Render Loop (skips GPU work when hidden or reference toggled off)let running = true;const animate = () => {if (!running) return;- if (typeof document === 'undefined' || !document.hidden) {+ if ((typeof document === 'undefined' || !document.hidden) && use3DStore.getState().isReferenceVisible) {try {- controls.update();renderer.render(scene, camera);} catch (err) {console.warn('[3D Render Loop Error]:', err);@@ -428,125 +978,213 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({running = false;};canvas.addEventListener('webglcontextlost', handleContextLost, false);+ const initSnap = captureSceneSnapshot();+ if (initSnap) {+ historyStackRef.current.reset(initSnap);+ syncHistoryFlagsToStore();+ }setSceneReadyVersion((v) => v + 1);return () => {running = false;canvas.removeEventListener('webglcontextlost', handleContextLost);+ if (historyDebounceTimerRef.current) {+ clearTimeout(historyDebounceTimerRef.current);+ historyDebounceTimerRef.current = null;+ }+ historyStackRef.current.clear();if (animFrameRef.current) {cancelAnimationFrame(animFrameRef.current);animFrameRef.current = null;}+ if (transformSyncRafRef.current) {+ cancelAnimationFrame(transformSyncRafRef.current);+ transformSyncRafRef.current = null;+ }+ if (perspectiveSyncRafRef.current) {+ cancelAnimationFrame(perspectiveSyncRafRef.current);+ perspectiveSyncRafRef.current = null;+ }if (modelRootRef.current) {disposeMeshUserData(modelRootRef.current);}+ if (toonGradientTexRef.current) {+ toonGradientTexRef.current.dispose();+ toonGradientTexRef.current = null;+ }transformControls.dispose();- controls.dispose();disposeThreeResources(scene, renderer);canvas.remove();canvasRef.current = null;sceneRef.current = null;cameraRef.current = null;rendererRef.current = null;- controlsRef.current = null;transformControlsRef.current = null;transformHelperRef.current = null;modelRootRef.current = null;+ mannequinBonesRef.current = null;+ ikHandlesRef.current = null;+ ikHandlesContainerRef.current = null;loadedFileKeyRef.current = null;};- }, [isOpen, dimensions.width, dimensions.height, disposeMeshUserData]);-- // Synchronize Gizmo Mode (Rotate, Translate, None)+ }, [+ isOpen,+ dimensions.width,+ dimensions.height,+ clientToNDC,+ disposeMeshUserData,+ scheduleTransformSyncToStore,+ commitHistoryNow,+ captureSceneSnapshot,+ syncHistoryFlagsToStore,+ ]);++ // Sync Gizmo Mode, Space, Snap, and Tool InteractivityuseEffect(() => {- if (!transformControlsRef.current || !transformHelperRef.current) return;- if (gizmoMode === 'none') {- transformControlsRef.current.detach();- transformHelperRef.current.visible = false;- } else {- transformControlsRef.current.setMode(gizmoMode);- if (modelRootRef.current) {- transformControlsRef.current.attach(modelRootRef.current);- transformHelperRef.current.visible = true;- }- }- }, [gizmoMode]);+ syncGizmoAttachment();+ }, [gizmoMode, gizmoSpace, activeTool, isReferenceVisible, isSpaceDown, sceneReadyVersion, syncGizmoAttachment]);- // Synchronize Floor Grid Visibility+ useEffect(() => {+ const tc = transformControlsRef.current;+ if (!tc) return;+ tc.setRotationSnap(snapEnabled ? THREE.MathUtils.degToRad(15) : null);+ tc.setTranslationSnap(snapEnabled ? 0.1 : null);+ tc.setScaleSnap(snapEnabled ? 0.1 : null);+ }, [snapEnabled, sceneReadyVersion]);++ // Sync Floor Grid & IK Handle visibility (hide helpers when painting with 2D tools for clean reference view!)useEffect(() => {if (gridHelperRef.current) {- gridHelperRef.current.visible = showGrid;+ gridHelperRef.current.visible = showGrid && is3DToolActive;}- }, [showGrid]);+ if (ikHandlesContainerRef.current) {+ ikHandlesContainerRef.current.visible = showIKHandles && is3DToolActive;+ }+ }, [showGrid, showIKHandles, is3DToolActive, sceneReadyVersion]);- // Synchronize Key Light & Ambient Light from lightSettings+ // Sync Dual Lighting & Ground ShadowuseEffect(() => {if (keyLightRef.current) {- const az = (lightSettings.azimuth * Math.PI) / 180;- const el = (lightSettings.elevation * Math.PI) / 180;- const dist = 5;- const y = Math.sin(el) * dist;- const hyp = Math.cos(el) * dist;- const x = Math.sin(az) * hyp;- const z = (lightSettings.isBacklit ? -1 : 1) * Math.cos(az) * hyp;-- keyLightRef.current.position.set(x, y, z);- keyLightRef.current.intensity = lightSettings.intensity * 1.5;- keyLightRef.current.color.set(lightSettings.color);+ const pos = sphericalLightToVector(+ lighting.keyLight.azimuth,+ lighting.keyLight.elevation,+ lighting.keyLight.isBacklit,+ 6+ );+ keyLightRef.current.position.set(pos.x, pos.y, pos.z);+ keyLightRef.current.intensity = lighting.keyLight.enabled ? lighting.keyLight.intensity * 1.4 : 0;+ keyLightRef.current.color.set(lighting.keyLight.color);+ keyLightRef.current.castShadow = lighting.keyLight.enabled && lighting.castGroundShadow;+ }+ if (rimLightRef.current) {+ const pos = sphericalLightToVector(+ lighting.rimLight.azimuth,+ lighting.rimLight.elevation,+ false,+ 6+ );+ rimLightRef.current.position.set(pos.x, pos.y, pos.z);+ rimLightRef.current.intensity = lighting.rimLight.enabled ? lighting.rimLight.intensity * 1.2 : 0;+ rimLightRef.current.color.set(lighting.rimLight.color);}if (ambientLightRef.current) {- ambientLightRef.current.intensity = lightSettings.ambientIntensity * 0.65;+ ambientLightRef.current.intensity = lighting.ambientIntensity * 0.7;+ ambientLightRef.current.color.set(lighting.ambientColor);}if (hemiLightRef.current) {- hemiLightRef.current.intensity = lightSettings.ambientIntensity * 0.5;+ hemiLightRef.current.intensity = lighting.ambientIntensity * 0.55;+ hemiLightRef.current.color.set(lighting.ambientColor);+ }+ if (shadowPlaneRef.current) {+ shadowPlaneRef.current.visible = lighting.castGroundShadow && lighting.keyLight.enabled;+ const mat = shadowPlaneRef.current.material as THREE.ShadowMaterial;+ mat.opacity = lighting.shadowOpacity;+ }+ }, [lighting, sceneReadyVersion]);++ // Sync Shading Mode, Roughness & Toon Outline+ useEffect(() => {+ applyShadingAndStyle(shadingMode, materialRoughness, toonOutline);+ }, [shadingMode, materialRoughness, toonOutline, applyShadingAndStyle, sceneReadyVersion]);++ // Record history for store-driven lighting, shading, opacity, and grid changes+ useEffect(() => {+ scheduleDebouncedHistoryCommit();+ }, [+ lighting,+ shadingMode,+ materialRoughness,+ toonOutline,+ opacity,+ showGrid,+ scheduleDebouncedHistoryCommit,+ ]);++ // Sync Perspective Ruler when toggle is turned ON+ useEffect(() => {+ if (syncCameraPerspective) {+ schedulePerspectiveRulerSync(true);}- }, [lightSettings]);+ }, [syncCameraPerspective, schedulePerspectiveRulerSync]);- // Execute unified 3D Transformation (used by both direct toolbar drag & canvas drag)+ // Unified Camera & Object Transform Delta Execution (used by BOTH canvas drag & toolbar scrub-drag)const applyTransformDelta = useCallback(- (mode: Csp3DToolMode, deltaX: number, deltaY: number) => {+ (mode: Tool3DMode | Resolved3DPointerAction, rawDx: number, rawDy: number, snap = false) => {const camera = cameraRef.current;const model = modelRootRef.current;- const controls = controlsRef.current;- if (!camera || !controls) return;+ const target = cameraTargetRef.current;+ if (!camera) return;++ const meta = viewportMetaRef.current;+ const camState = navigation+ ? navigation.getCameraState()+ : { rotation: meta.rotation, flipX: meta.flipX, flipY: meta.flipY };+ const { dx, dy } = mapScreenDeltaToCanvasDelta(+ rawDx,+ rawDy,+ camState.rotation,+ camState.flipX,+ camState.flipY+ );switch (mode) {case 'camera-orbit': {- const offset = new THREE.Vector3().subVectors(camera.position, controls.target);+ const offset = new THREE.Vector3().subVectors(camera.position, target);const spherical = new THREE.Spherical().setFromVector3(offset);- const orbitSpeed = 0.007;- spherical.theta -= deltaX * orbitSpeed;- spherical.phi = Math.max(0.01, Math.min(Math.PI - 0.01, spherical.phi - deltaY * orbitSpeed));+ const orbitSpeed = 0.0075;+ spherical.theta -= dx * orbitSpeed;+ spherical.phi = Math.max(0.02, Math.min(Math.PI - 0.02, spherical.phi - dy * orbitSpeed));offset.setFromSpherical(spherical);- camera.position.copy(controls.target).add(offset);- camera.lookAt(controls.target);- controls.update();+ camera.position.copy(target).add(offset);+ camera.lookAt(target);+ schedulePerspectiveRulerSync();break;}case 'camera-pan': {const camUp = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion).normalize();const camRight = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion).normalize();- const dist = camera.position.distanceTo(controls.target);- const panSpeed = 0.0014 * dist;-+ const dist = camera.position.distanceTo(target);+ const panSpeed = 0.0015 * dist;const panOffset = new THREE.Vector3()- .addScaledVector(camRight, -deltaX * panSpeed)- .addScaledVector(camUp, deltaY * panSpeed);-+ .addScaledVector(camRight, -dx * panSpeed)+ .addScaledVector(camUp, dy * panSpeed);camera.position.add(panOffset);- controls.target.add(panOffset);- controls.update();+ target.add(panOffset);+ camera.lookAt(target);+ schedulePerspectiveRulerSync();break;}case 'camera-zoom': {- const zoomSpeed = 0.012;- const toTarget = new THREE.Vector3().subVectors(camera.position, controls.target);- const currentDist = toTarget.length();- const newDist = Math.max(0.4, Math.min(50, currentDist * (1 + deltaY * zoomSpeed)));- toTarget.setLength(newDist);- camera.position.copy(controls.target).add(toTarget);- controls.update();+ const zoomSpeed = 0.009;+ const toCam = new THREE.Vector3().subVectors(camera.position, target);+ const currentDist = toCam.length();+ const newDist = Math.max(0.45, Math.min(45, currentDist * (1 + dy * zoomSpeed)));+ toCam.setLength(newDist);+ camera.position.copy(target).add(toCam);+ camera.lookAt(target);+ schedulePerspectiveRulerSync();break;}@@ -555,32 +1193,66 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({const camUp = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion).normalize();const camRight = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion).normalize();const dist = camera.position.distanceTo(model.position);- const moveSpeed = 0.0016 * dist;+ const moveSpeed = 0.0018 * Math.max(1, dist);+ model.position.addScaledVector(camRight, dx * moveSpeed);+ model.position.addScaledVector(camUp, -dy * moveSpeed);+ if (snap) {+ model.position.set(+ snapPositionCoord(model.position.x, 0.1),+ snapPositionCoord(model.position.y, 0.1),+ snapPositionCoord(model.position.z, 0.1)+ );+ }+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();+ break;+ }- model.position.addScaledVector(camRight, deltaX * moveSpeed);- model.position.addScaledVector(camUp, -deltaY * moveSpeed);+ case 'model-plane-move': {+ if (!model) return;+ const forward = new THREE.Vector3();+ camera.getWorldDirection(forward);+ forward.y = 0;+ if (forward.lengthSq() > 0.0001) forward.normalize();+ else forward.set(0, 0, -1);+ const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();+ const dist = camera.position.distanceTo(model.position);+ const planeSpeed = 0.002 * Math.max(1, dist);+ model.position.addScaledVector(right, dx * planeSpeed);+ model.position.addScaledVector(forward, -dy * planeSpeed);+ if (snap) {+ model.position.x = snapPositionCoord(model.position.x, 0.1);+ model.position.z = snapPositionCoord(model.position.z, 0.1);+ }+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();break;}- case 'model-rotate-free': {+ case 'model-rotate': {if (!model) return;const camUp = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion).normalize();const camRight = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion).normalize();- const rotSpeed = 0.008;-- const qYaw = new THREE.Quaternion().setFromAxisAngle(camUp, deltaX * rotSpeed);- const qPitch = new THREE.Quaternion().setFromAxisAngle(camRight, deltaY * rotSpeed);-- model.quaternion.premultiply(qYaw).premultiply(qPitch);+ const rotSpeed = 0.0085;+ const qYaw = new THREE.Quaternion().setFromAxisAngle(camUp, dx * rotSpeed);+ const qPitch = new THREE.Quaternion().setFromAxisAngle(camRight, dy * rotSpeed);+ model.quaternion.premultiply(qYaw).premultiply(qPitch).normalize();+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();break;}case 'model-rotate-yaw': {if (!model) return;const worldUp = new THREE.Vector3(0, 1, 0);- const rotSpeed = 0.01;- const q = new THREE.Quaternion().setFromAxisAngle(worldUp, deltaX * rotSpeed);- model.quaternion.premultiply(q);+ const q = new THREE.Quaternion().setFromAxisAngle(worldUp, dx * 0.01);+ model.quaternion.premultiply(q).normalize();+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();break;}@@ -588,218 +1260,318 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({if (!model) return;const camDir = new THREE.Vector3();camera.getWorldDirection(camDir);- const rotSpeed = 0.01;- const q = new THREE.Quaternion().setFromAxisAngle(camDir, deltaX * rotSpeed);- model.quaternion.premultiply(q);+ const q = new THREE.Quaternion().setFromAxisAngle(camDir, dx * 0.01);+ model.quaternion.premultiply(q).normalize();+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();break;}- case 'model-plane-move': {+ case 'model-scale': {if (!model) return;- const forward = new THREE.Vector3();- camera.getWorldDirection(forward);- forward.y = 0;- if (forward.lengthSq() > 0.0001) forward.normalize();- else forward.set(0, 0, -1);-- const right = new THREE.Vector3().crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();- const dist = camera.position.distanceTo(model.position);- const planeSpeed = 0.002 * dist;-- model.position.addScaledVector(right, deltaX * planeSpeed);- model.position.addScaledVector(forward, -deltaY * planeSpeed);+ const delta = (dx - dy) * 0.005;+ const factor = Math.exp(delta);+ const nextX = Math.max(0.05, Math.min(10, model.scale.x * factor));+ const nextY = Math.max(0.05, Math.min(10, model.scale.y * factor));+ const nextZ = Math.max(0.05, Math.min(10, model.scale.z * factor));+ if (snap) {+ model.scale.set(+ snapScaleFactor(nextX),+ snapScaleFactor(nextY),+ snapScaleFactor(nextZ)+ );+ } else {+ model.scale.set(nextX, nextY, nextZ);+ }+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();break;}}},- []+ [navigation, schedulePerspectiveRulerSync, scheduleTransformSyncToStore]);- // Magnet Action: Drop model flush to floor plane Y=0 (Clip Studio Paint style)+ // Apply numeric transform directly from Tool Property Inspector+ const applyNumericTransform = useCallback(+ (next: Model3DTransformState) => {+ store3DActions.setModelTransform(next);+ const model = modelRootRef.current;+ if (!model) return;+ model.position.set(next.position[0], next.position[1], next.position[2]);+ const euler = new THREE.Euler(+ THREE.MathUtils.degToRad(next.rotation[0]),+ THREE.MathUtils.degToRad(next.rotation[1]),+ THREE.MathUtils.degToRad(next.rotation[2]),+ 'YXZ'+ );+ model.quaternion.setFromEuler(euler);+ model.scale.set(+ Math.max(0.05, Math.min(10, next.scale[0])),+ Math.max(0.05, Math.min(10, next.scale[1])),+ Math.max(0.05, Math.min(10, next.scale[2]))+ );+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleDebouncedHistoryCommit();+ },+ [scheduleDebouncedHistoryCommit]+ );++ // Magnet Action: Drop model flush to floor plane Y = 0const handleSnapToGround = useCallback(() => {- if (!modelRootRef.current) return;- modelRootRef.current.updateMatrixWorld(true);- const box = new THREE.Box3().setFromObject(modelRootRef.current);+ const model = modelRootRef.current;+ if (!model) return;+ model.updateMatrixWorld(true);+ const box = new THREE.Box3().setFromObject(model);if (Number.isFinite(box.min.y)) {- modelRootRef.current.position.y -= box.min.y;- modelRootRef.current.updateMatrixWorld(true);+ model.position.y -= box.min.y;+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();+ commitHistoryNow();}- }, []);+ }, [commitHistoryNow, scheduleTransformSyncToStore]);- // Reset Model Transform: Position (0, 0.3, 0), zero rotation+ // Reset Model Transform (preserves normalized inner scale!)const handleResetModelTransform = useCallback(() => {- if (!modelRootRef.current) return;- modelRootRef.current.position.set(0, 0.3, 0);- modelRootRef.current.quaternion.identity();- modelRootRef.current.scale.set(1, 1, 1);- modelRootRef.current.updateMatrixWorld(true);- }, []);-- // Perspective (Dolly Zoom) Adjustment (Clip Studio Paint style perspective distortion)- const applyPerspectiveDollyZoom = useCallback((factor: number) => {- if (!cameraRef.current || !controlsRef.current) return;- const camera = cameraRef.current;- const controls = controlsRef.current;-- const baseFovRad = (45 * Math.PI) / 180;- const newTan = factor * Math.tan(baseFovRad / 2);- const newFovDeg = Math.min(105, Math.max(15, (2 * Math.atan(newTan) * 180) / Math.PI));+ const model = modelRootRef.current;+ if (!model) return;+ model.position.set(0, 0, 0);+ model.quaternion.identity();+ model.scale.set(1, 1, 1);+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ store3DActions.setModelTransform({+ position: [0, 0, 0],+ rotation: [0, 0, 0],+ scale: [1, 1, 1],+ });+ commitHistoryNow();+ }, [commitHistoryNow]);- const toTarget = new THREE.Vector3().subVectors(camera.position, controls.target);- const currentDist = toTarget.length();- const oldFovRad = (camera.fov * Math.PI) / 360;- const newFovRad = (newFovDeg * Math.PI) / 360;+ // Quick Model Yaw Rotations+ const rotateModelYaw = useCallback(+ (degrees: number) => {+ const model = modelRootRef.current;+ if (!model) return;+ const q = new THREE.Quaternion().setFromAxisAngle(+ new THREE.Vector3(0, 1, 0),+ THREE.MathUtils.degToRad(degrees)+ );+ model.quaternion.premultiply(q).normalize();+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();+ commitHistoryNow();+ },+ [commitHistoryNow, scheduleTransformSyncToStore]+ );- const targetDist = Math.max(0.5, (currentDist * Math.tan(oldFovRad)) / Math.tan(newFovRad));- toTarget.setLength(targetDist);+ // Perspective (Dolly Zoom) Adjustment+ const applyPerspectiveDollyZoom = useCallback(+ (factor: number) => {+ const camera = cameraRef.current;+ if (!camera) return;+ const target = cameraTargetRef.current;+ const clampedFactor = Math.max(0.3, Math.min(2.5, factor));++ const baseFovRad = THREE.MathUtils.degToRad(45);+ const newTan = clampedFactor * Math.tan(baseFovRad / 2);+ const newFovDeg = Math.min(100, Math.max(16, THREE.MathUtils.radToDeg(2 * Math.atan(newTan))));++ const toCam = new THREE.Vector3().subVectors(camera.position, target);+ const currentDist = toCam.length();+ const oldFovRad = THREE.MathUtils.degToRad(camera.fov) / 2;+ const newFovRad = THREE.MathUtils.degToRad(newFovDeg) / 2;+ const targetDist = Math.max(0.55, Math.min(45, (currentDist * Math.tan(oldFovRad)) / Math.tan(newFovRad)));++ toCam.setLength(targetDist);+ camera.position.copy(target).add(toCam);+ camera.fov = newFovDeg;+ camera.updateProjectionMatrix();+ camera.lookAt(target);+ store3DActions.setPerspective(clampedFactor, Math.round(newFovDeg));+ schedulePerspectiveRulerSync();+ scheduleDebouncedHistoryCommit();+ },+ [scheduleDebouncedHistoryCommit, schedulePerspectiveRulerSync]+ );- camera.position.copy(controls.target).add(toTarget);- camera.fov = newFovDeg;+ const handleResetCamera = useCallback(() => {+ const camera = cameraRef.current;+ if (!camera) return;+ const isMannequin = use3DStore.getState().isMannequinActive;+ cameraTargetRef.current.set(0, isMannequin ? 0.92 : 0.8, 0);+ camera.position.set(0, isMannequin ? 1.25 : 1.35, isMannequin ? 3.4 : 3.8);+ camera.fov = 45;camera.updateProjectionMatrix();- controls.update();-- setPerspective(factor);- }, []);+ camera.lookAt(cameraTargetRef.current);+ store3DActions.setPerspective(1.0, 45);+ schedulePerspectiveRulerSync();+ commitHistoryNow();+ }, [commitHistoryNow, schedulePerspectiveRulerSync]);- // Camera Angle Presetsconst setCameraPreset = useCallback(- (presetName: 'front' | 'side' | 'top' | 'threeQuarter' | 'lowAngle' | 'back') => {- if (!cameraRef.current || !controlsRef.current) return;+ (presetName: Camera3DPreset) => {const camera = cameraRef.current;- const controls = controlsRef.current;- const target = controls.target.clone();- const dist = 3.8;+ if (!camera) return;+ const target = cameraTargetRef.current;+ const dist = Math.max(2.0, camera.position.distanceTo(target));switch (presetName) {case 'front':- camera.position.set(target.x, target.y + 0.2, target.z + dist);+ camera.position.set(target.x, target.y + 0.12, target.z + dist);break;case 'side':- camera.position.set(target.x - dist, target.y + 0.2, target.z);+ camera.position.set(target.x - dist, target.y + 0.12, target.z);break;case 'top':camera.position.set(target.x, target.y + dist, target.z + 0.05);break;case 'threeQuarter':- camera.position.set(target.x + dist * 0.7, target.y + dist * 0.45, target.z + dist * 0.7);+ camera.position.set(target.x + dist * 0.68, target.y + dist * 0.42, target.z + dist * 0.68);break;case 'lowAngle':- camera.position.set(target.x + dist * 0.5, target.y - dist * 0.35, target.z + dist * 0.8);+ camera.position.set(target.x + dist * 0.48, Math.max(0.15, target.y - dist * 0.35), target.z + dist * 0.8);break;case 'back':- camera.position.set(target.x, target.y + 0.2, target.z - dist);+ camera.position.set(target.x, target.y + 0.12, target.z - dist);break;}camera.lookAt(target);- controls.update();+ schedulePerspectiveRulerSync();+ commitHistoryNow();},- []+ [commitHistoryNow, schedulePerspectiveRulerSync]);- // Quick Model Yaw Rotations- const rotateModelYaw = useCallback((degrees: number) => {- if (!modelRootRef.current) return;- const rad = (degrees * Math.PI) / 180;- const q = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), rad);- modelRootRef.current.quaternion.premultiply(q);- }, []);-- // Canvas Pointer Events: Route dragging based on CSP active tool- const handleCanvasPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {- const isModelMode =- activeToolMode === 'model-move' ||- activeToolMode === 'model-rotate-free' ||- activeToolMode === 'model-rotate-yaw' ||- activeToolMode === 'model-rotate-roll' ||- activeToolMode === 'model-plane-move';-- // If active tool is a model transform or if not left-clicking, handle accordingly- if (isModelMode && e.button === 0) {- if (controlsRef.current) controlsRef.current.enabled = false;- try {- e.currentTarget.setPointerCapture(e.pointerId);- } catch {- // ignore- }-- canvasDragRef.current = {- startX: e.clientX,- startY: e.clientY,- lastX: e.clientX,- lastY: e.clientY,- button: e.button,- };- } else {- // Camera mode: let OrbitControls manage it, but ensure enabled- if (controlsRef.current) controlsRef.current.enabled = true;+ // Clean helper to clear previous model & IK handles before attaching a new object+ const clearCurrentModel = useCallback(() => {+ const scene = sceneRef.current;+ if (!scene) return;+ if (transformControlsRef.current) {+ transformControlsRef.current.detach();}- };+ if (modelRootRef.current) {+ disposeMeshUserData(modelRootRef.current);+ disposeThreeResources(modelRootRef.current, null);+ scene.remove(modelRootRef.current);+ modelRootRef.current = null;+ }+ if (ikHandlesContainerRef.current) {+ disposeThreeResources(ikHandlesContainerRef.current, null);+ scene.remove(ikHandlesContainerRef.current);+ ikHandlesContainerRef.current = null;+ ikHandlesRef.current = null;+ }+ mannequinBonesRef.current = null;+ }, [disposeMeshUserData]);++ // Attach any normalized model into a clean user-transform root group (scale 1 = 100%)+ const attachNormalizedObject = useCallback(+ (+ innerContent: THREE.Object3D,+ displayName: string,+ kind: 'imported',+ detectedBones: HumanoidBones | null+ ) => {+ const scene = sceneRef.current;+ if (!scene) return;++ const userRoot = new THREE.Group();+ userRoot.name = 'UserModelRoot';+ userRoot.position.set(0, 0, 0);+ userRoot.quaternion.identity();+ userRoot.scale.set(1, 1, 1);+ userRoot.add(innerContent);++ modelRootRef.current = userRoot;+ scene.add(userRoot);+ userRoot.updateMatrixWorld(true);++ const hasBones = Boolean(+ detectedBones &&+ (detectedBones.hips || detectedBones.leftHand || detectedBones.rightHand || detectedBones.head)+ );++ if (hasBones && detectedBones) {+ mannequinBonesRef.current = detectedBones;+ const { container, handles } = createIKHandles();+ ikHandlesRef.current = handles;+ ikHandlesContainerRef.current = container;+ syncIKHandlesToBones(detectedBones, handles);+ container.visible = use3DStore.getState().showIKHandles && activeToolRef.current === '3d';+ scene.add(container);+ } else {+ mannequinBonesRef.current = null;+ }- const handleCanvasPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {- if (!canvasDragRef.current) return;- const dx = e.clientX - canvasDragRef.current.lastX;- const dy = e.clientY - canvasDragRef.current.lastY;- canvasDragRef.current.lastX = e.clientX;- canvasDragRef.current.lastY = e.clientY;+ store3DActions.setLoadedModel(displayName, kind, hasBones);+ store3DActions.setModelTransform({+ position: [0, 0, 0],+ rotation: [0, 0, 0],+ scale: [1, 1, 1],+ });- if (dx !== 0 || dy !== 0) {- applyTransformDelta(activeToolMode, dx, dy);- }- };+ const s = use3DStore.getState();+ applyShadingAndStyle(s.shadingMode, s.materialRoughness, s.toonOutline);+ syncGizmoAttachment();++ // Frame camera cleanly around the loaded object+ if (cameraRef.current) {+ const box = new THREE.Box3().setFromObject(userRoot);+ const center = new THREE.Vector3(0, 0.85, 0);+ if (!box.isEmpty()) box.getCenter(center);+ cameraTargetRef.current.copy(center);+ cameraRef.current.position.set(center.x, center.y + 0.35, center.z + 3.5);+ cameraRef.current.lookAt(cameraTargetRef.current);+ }- const handleCanvasPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {- if (canvasDragRef.current) {- try {- e.currentTarget.releasePointerCapture(e.pointerId);- } catch {- // ignore+ // Reset 3D undo history baseline to this newly loaded model state+ const baseSnap = captureSceneSnapshot();+ if (baseSnap) {+ historyStackRef.current.reset(baseSnap);+ syncHistoryFlagsToStore();}- canvasDragRef.current = null;- if (controlsRef.current) controlsRef.current.enabled = true;- }- };+ },+ [applyShadingAndStyle, captureSceneSnapshot, syncGizmoAttachment, syncHistoryFlagsToStore]+ );- // Handle Loading 3D Model from File (.glb, .gltf, .obj)+ // Load 3D model from file (.glb, .gltf, .obj)const loadFromFile = useCallback((file: File) => {if (!sceneRef.current) return;-const fileName = file.name.toLowerCase();const fitAndAttach = (model: THREE.Group | THREE.Object3D) => {- if (modelRootRef.current && sceneRef.current) {- if (transformControlsRef.current) transformControlsRef.current.detach();- disposeMeshUserData(modelRootRef.current);- disposeThreeResources(modelRootRef.current, null);- sceneRef.current.remove(modelRootRef.current);- modelRootRef.current = null;- }+ clearCurrentModel();const toRemove: THREE.Object3D[] = [];model.traverse((child) => {if ((child as any).isCamera || (child as any).isLight) {toRemove.push(child);+ return;}const mesh = child as THREE.Mesh;- if (mesh.isMesh && mesh.material) {- mesh.userData.origGeometry = mesh.geometry;- mesh.userData.origMaterial = mesh.material;- mesh.userData.hasCustomMaterial = true;-- if (Array.isArray(mesh.material)) {- mesh.material.forEach((m) => {+ if (mesh.isMesh) {+ mesh.castShadow = true;+ mesh.receiveShadow = true;+ if (mesh.material) {+ mesh.userData.origGeometry = mesh.geometry;+ mesh.userData.origMaterial = mesh.material;+ mesh.userData.hasCustomMaterial = true;+ const fixMat = (m: THREE.Material) => {m.side = THREE.DoubleSide;if ((m as any).transmission !== undefined && (m as any).transmission > 0) {m.transparent = true;if (m.opacity < 0.25) m.opacity = 0.85;}- });- } else {- mesh.material.side = THREE.DoubleSide;- if ((mesh.material as any).transmission !== undefined && (mesh.material as any).transmission > 0) {- mesh.material.transparent = true;- if (mesh.material.opacity < 0.25) mesh.material.opacity = 0.85;- }+ };+ if (Array.isArray(mesh.material)) mesh.material.forEach(fixMat);+ else fixMat(mesh.material);}}});@@ -817,52 +1589,21 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({box.getSize(size);const maxDim = Math.max(size.x, size.y, size.z);- const targetDim = 2.4;- const scale = Number.isFinite(maxDim) && maxDim > 0.0001 ? targetDim / maxDim : 1;-- const wrapper = new THREE.Group();- model.position.set(-center.x, -center.y, -center.z);- wrapper.scale.setScalar(scale);- wrapper.position.set(0, 0.3, 0);- wrapper.add(model);-- modelRootRef.current = wrapper;- if (sceneRef.current) {- sceneRef.current.add(wrapper);- }- setLoadedFileName(file.name);- applyShading(shadingMode);- updateGizmoTarget();-- // Detect humanoid skinned mesh hierarchy- if (ikHandlesContainerRef.current && sceneRef.current) {- disposeThreeResources(ikHandlesContainerRef.current, null);- sceneRef.current.remove(ikHandlesContainerRef.current);- ikHandlesContainerRef.current = null;- ikHandlesRef.current = null;- }- const detectedBones = findHumanoidBones(model);- if (detectedBones.hips || detectedBones.leftHand || detectedBones.rightHand || detectedBones.head) {- mannequinBonesRef.current = detectedBones;- setIsMannequinActive(true);- const { container: handlesContainer, handles } = createIKHandles();- ikHandlesRef.current = handles;- ikHandlesContainerRef.current = handlesContainer;- sceneRef.current?.add(handlesContainer);- } else {- mannequinBonesRef.current = null;- setIsMannequinActive(false);- }+ const targetDim = 2.0;+ const normScale = Number.isFinite(maxDim) && maxDim > 0.0001 ? targetDim / maxDim : 1;- if (cameraRef.current && controlsRef.current) {- cameraRef.current.position.set(0, 0.5, 3.8);- controlsRef.current.target.set(0, 0.3, 0);- controlsRef.current.update();- }+ // Inner normalization wrapper: centers X/Z and places bottom flush at Y = 0+ const normalizedWrapper = new THREE.Group();+ normalizedWrapper.name = 'NormalizedModelWrapper';+ model.position.set(-center.x, -box.min.y, -center.z);+ normalizedWrapper.scale.setScalar(normScale);+ normalizedWrapper.add(model);++ const detectedBones = findHumanoidBones(model);+ attachNormalizedObject(normalizedWrapper, file.name, 'imported', detectedBones);};const blobUrl = URL.createObjectURL(file);-if (fileName.endsWith('.glb') || fileName.endsWith('.gltf')) {const loader = new GLTFLoader();loader.load(@@ -893,9 +1634,30 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({);}},- [applyShading, disposeMeshUserData, shadingMode, updateGizmoTarget]+ [attachNormalizedObject, clearCurrentModel]+ );++ // Select IK target limb (either from clicking sphere on canvas or clicking button in inspector)+ const selectIKTarget = useCallback(+ (targetName: string | null) => {+ store3DActions.setActiveIKHandle(targetName);+ syncGizmoAttachment();+ },+ [syncGizmoAttachment]+ );++ // Apply Pose Preset & keep IK handles glued to updated bone positions+ const handleApplyPreset = useCallback(+ (preset: PosePresetName) => {+ if (!mannequinBonesRef.current) return;+ applyPosePreset(mannequinBonesRef.current, preset);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ commitHistoryNow();+ },+ [commitHistoryNow]);+ // Load initialFile if supplied when opening 3D stageuseEffect(() => {if (initialFile && isOpen && sceneRef.current) {const fileKey = `${initialFile.name}-${initialFile.size}-${initialFile.lastModified}`;@@ -918,194 +1680,565 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({}};- const handleResetCamera = () => {- if (!cameraRef.current || !controlsRef.current) return;- cameraRef.current.position.set(0, 0.5, 3.8);- cameraRef.current.fov = 45;- cameraRef.current.updateProjectionMatrix();- controlsRef.current.target.set(0, 0.3, 0);- controlsRef.current.update();- setPerspective(1.0);- };-- // Load procedural humanoid drawing mannequin- const loadProceduralMannequin = useCallback(() => {- if (!sceneRef.current) return;- if (modelRootRef.current) {- if (transformControlsRef.current) transformControlsRef.current.detach();- disposeMeshUserData(modelRootRef.current);- disposeThreeResources(modelRootRef.current, null);- sceneRef.current.remove(modelRootRef.current);- modelRootRef.current = null;+ // Helper to toggle scene helper objects around baking+ const setHelpersVisible = useCallback((visible: boolean) => {+ const s = use3DStore.getState();+ if (transformHelperRef.current) {+ transformHelperRef.current.visible =+ visible && activeToolRef.current === '3d' && (s.gizmoMode !== 'none' || Boolean(s.activeIKHandle));+ }+ if (gridHelperRef.current) {+ gridHelperRef.current.visible = visible && s.showGrid && activeToolRef.current === '3d';}if (ikHandlesContainerRef.current) {- disposeThreeResources(ikHandlesContainerRef.current, null);- sceneRef.current.remove(ikHandlesContainerRef.current);- ikHandlesContainerRef.current = null;- ikHandlesRef.current = null;+ ikHandlesContainerRef.current.visible = visible && s.showIKHandles && activeToolRef.current === '3d';}+ }, []);++ // Live preview render for the standalone LT Extraction Modal (fast capped resolution, non-destructive)+ const handleRenderLTPreview = useCallback(+ async (settings: LTConversionSettings): Promise<LTPreviewBuffers | null> => {+ if (!sceneRef.current || !cameraRef.current || !modelRootRef.current) return null;++ const MAX_PREVIEW_DIM = 680;+ const aspect = dimensions.width / Math.max(1, dimensions.height);+ let previewW = dimensions.width;+ let previewH = dimensions.height;+ if (previewW > MAX_PREVIEW_DIM || previewH > MAX_PREVIEW_DIM) {+ if (previewW >= previewH) {+ previewW = MAX_PREVIEW_DIM;+ previewH = Math.max(1, Math.round(MAX_PREVIEW_DIM / aspect));+ } else {+ previewH = MAX_PREVIEW_DIM;+ previewW = Math.max(1, Math.round(MAX_PREVIEW_DIM * aspect));+ }+ }++ const prevShadowVis = shadowPlaneRef.current?.visible ?? false;+ try {+ setHelpersVisible(false);+ if (shadowPlaneRef.current) shadowPlaneRef.current.visible = false;++ const docDpi = dimensions.dpi ?? 600;+ const previewScale = previewW / Math.max(1, dimensions.width);+ const previewDpi = Math.max(72, Math.round(docDpi * previewScale));++ const result = await bake3DToLineAndTone({+ scene: sceneRef.current,+ camera: cameraRef.current,+ dimensions: { width: previewW, height: previewH, dpi: previewDpi },+ dpi: previewDpi,+ activeRenderer: rendererRef.current,+ lineWidth: settings.lineWidth,+ lineThreshold: settings.lineThreshold,+ toneCount: settings.toneCount,+ toneFrequencies: settings.toneFrequencies,+ antiAliasing: settings.antiAliasing ?? false,+ disposeOnComplete: false,+ previewOnly: true,+ });- const { group, bones } = createProceduralMannequin();- const { container: handlesContainer, handles } = createIKHandles();+ return {+ lineCanvas: result.lineCanvas,+ toneCanvases: result.toneCanvases,+ };+ } finally {+ setHelpersVisible(true);+ if (shadowPlaneRef.current) {+ shadowPlaneRef.current.visible = prevShadowVis;+ }+ }+ },+ [dimensions.height, dimensions.width, setHelpersVisible]+ );- mannequinBonesRef.current = bones;- ikHandlesRef.current = handles;- ikHandlesContainerRef.current = handlesContainer;+ // 3D LT Lineart & Screentone Extraction+ const handleExtractLineAndTone = useCallback(+ async (settings?: LTConversionSettings) => {+ const s = use3DStore.getState();+ if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || s.isBaking) return;+ store3DActions.setIsBaking(true);- group.position.set(0, 0, 0);- modelRootRef.current = group;- sceneRef.current.add(group);- sceneRef.current.add(handlesContainer);+ try {+ setHelpersVisible(false);+ if (shadowPlaneRef.current) shadowPlaneRef.current.visible = false;++ const effectiveLineWidth = settings?.lineWidth ?? 1;+ const effectiveThreshold = settings?.lineThreshold ?? 0.28;+ const effectiveToneCount = settings?.toneCount ?? 2;+ const modelDisplayName = s.loadedModelName+ ? s.loadedModelName.replace(/\.[^/.]+$/, '')+ : '3D Model';+ const targetFolderName = settings?.folderName?.trim() || `3D Extraction [${modelDisplayName}]`;++ await bake3DToLineAndTone({+ scene: sceneRef.current,+ camera: cameraRef.current,+ dimensions,+ dpi: dimensions.dpi ?? 600,+ activeRenderer: rendererRef.current,+ modelName: modelDisplayName,+ targetFolderName,+ lineWidth: effectiveLineWidth,+ lineThreshold: effectiveThreshold,+ toneCount: effectiveToneCount,+ toneFrequencies: settings?.toneFrequencies,+ antiAliasing: settings?.antiAliasing ?? false,+ disposeOnComplete: false,+ onInsertLayers: (layers, canvases) => {+ for (let i = layers.length - 1; i >= 0; i--) {+ onInsertRasterLayer(layers[i], canvases[i]);+ }+ },+ });- setLoadedFileName('Mannequin (Rigged)');- setIsMannequinActive(true);- applyShading(shadingMode);+ store3DActions.setIsBaking(false);+ setIsLTModalOpen(false);+ onClose();+ } catch (err) {+ console.error('[3D] Failed to extract line & tone:', err);+ store3DActions.setIsBaking(false);+ setHelpersVisible(true);+ if (shadowPlaneRef.current) {+ shadowPlaneRef.current.visible =+ use3DStore.getState().lighting.castGroundShadow &&+ use3DStore.getState().lighting.keyLight.enabled;+ }+ }+ },+ [dimensions, onClose, onInsertRasterLayer, setHelpersVisible]+ );- if (cameraRef.current && controlsRef.current) {- cameraRef.current.position.set(0, 1.1, 3.2);- controlsRef.current.target.set(0, 0.9, 0);- controlsRef.current.update();- }- }, [applyShading, disposeMeshUserData, shadingMode]);-- // Select an IK Target limb to manipulate- const selectIKTarget = useCallback((targetName: string | null) => {- setActiveIKHandle(targetName);- if (!transformControlsRef.current || !ikHandlesRef.current) return;- if (targetName && ikHandlesRef.current[targetName]) {- const handleMesh = ikHandlesRef.current[targetName];- transformControlsRef.current.setMode('translate');- transformControlsRef.current.attach(handleMesh);- if (transformHelperRef.current) transformHelperRef.current.visible = true;- } else {- transformControlsRef.current.detach();- if (transformHelperRef.current) transformHelperRef.current.visible = false;+ // Bake 3D view into a standard 2D Raster Layer+ const handleBakeTo2D = useCallback(+ async (closeAfter = true) => {+ const s = use3DStore.getState();+ if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || s.isBaking) return;+ store3DActions.setIsBaking(true);++ try {+ setHelpersVisible(false);+ const result = await bake3DToRasterLayer({+ scene: sceneRef.current,+ camera: cameraRef.current,+ dimensions,+ activeRenderer: rendererRef.current,+ layerName: s.loadedModelName ? `3D (${s.loadedModelName})` : '3D Model',+ opacity: s.opacity,+ blendMode: 'normal',+ disposeOnComplete: false,+ onInsertLayer: (layer, rasterCanvas) => {+ onInsertRasterLayer(layer, rasterCanvas);+ },+ });++ onBakeSuccess?.(result.layer);+ store3DActions.setIsBaking(false);+ if (closeAfter) {+ onClose();+ } else {+ setHelpersVisible(true);+ }+ } catch (err) {+ console.error('[3D] Failed to rasterize 3D layer:', err);+ store3DActions.setIsBaking(false);+ setHelpersVisible(true);+ }+ },+ [dimensions, onBakeSuccess, onClose, onInsertRasterLayer, setHelpersVisible]+ );++ // Register imperative bridge for ToolPropertyInspector & Global Ctrl+Z / Ctrl+Y+ useEffect(() => {+ if (!isOpen) return;+ scene3DBridge.triggerFilePicker = () => fileInputRef.current?.click();+ scene3DBridge.loadFile = loadFromFile;+ scene3DBridge.applyNumericTransform = applyNumericTransform;+ scene3DBridge.applyTransformDelta = applyTransformDelta;+ scene3DBridge.rotateModelYaw = rotateModelYaw;+ scene3DBridge.snapToGround = handleSnapToGround;+ scene3DBridge.resetModelTransform = handleResetModelTransform;+ scene3DBridge.resetCamera = handleResetCamera;+ scene3DBridge.setCameraPreset = setCameraPreset;+ scene3DBridge.applyPerspectiveDollyZoom = applyPerspectiveDollyZoom;+ scene3DBridge.applyPosePreset = handleApplyPreset;+ scene3DBridge.selectIKTarget = selectIKTarget;+ scene3DBridge.syncPerspectiveRulerNow = () => schedulePerspectiveRulerSync(true);+ scene3DBridge.bakeTo2D = handleBakeTo2D;+ scene3DBridge.extractLineAndTone = handleExtractLineAndTone;+ scene3DBridge.commitHistoryNow = commitHistoryNow;+ scene3DBridge.undo = handleUndo3D;+ scene3DBridge.redo = handleRedo3D;+ scene3DBridge.canUndo = () =>+ historyStackRef.current.canUndo() || historyDebounceTimerRef.current !== null;+ scene3DBridge.canRedo = () => historyStackRef.current.canRedo();++ return () => {+ scene3DBridge.triggerFilePicker = undefined;+ scene3DBridge.loadFile = undefined;+ scene3DBridge.applyNumericTransform = undefined;+ scene3DBridge.applyTransformDelta = undefined;+ scene3DBridge.rotateModelYaw = undefined;+ scene3DBridge.snapToGround = undefined;+ scene3DBridge.resetModelTransform = undefined;+ scene3DBridge.resetCamera = undefined;+ scene3DBridge.setCameraPreset = undefined;+ scene3DBridge.applyPerspectiveDollyZoom = undefined;+ scene3DBridge.applyPosePreset = undefined;+ scene3DBridge.selectIKTarget = undefined;+ scene3DBridge.syncPerspectiveRulerNow = undefined;+ scene3DBridge.bakeTo2D = undefined;+ scene3DBridge.extractLineAndTone = undefined;+ scene3DBridge.commitHistoryNow = undefined;+ scene3DBridge.undo = undefined;+ scene3DBridge.redo = undefined;+ scene3DBridge.canUndo = undefined;+ scene3DBridge.canRedo = undefined;+ };+ }, [+ isOpen,+ loadFromFile,+ applyNumericTransform,+ applyTransformDelta,+ rotateModelYaw,+ handleSnapToGround,+ handleResetModelTransform,+ handleResetCamera,+ setCameraPreset,+ applyPerspectiveDollyZoom,+ handleApplyPreset,+ selectIKTarget,+ schedulePerspectiveRulerSync,+ handleBakeTo2D,+ handleExtractLineAndTone,+ commitHistoryNow,+ handleUndo3D,+ handleRedo3D,+ ]);++ // Non-passive Wheel listener: Unmodified wheel dollies 3D camera; Ctrl/Meta+Wheel zooms 2D canvas+ useEffect(() => {+ const mount = mountRef.current;+ if (!mount || !isOpen) return;++ const handleWheel = (e: WheelEvent) => {+ const wheelAction = resolve3DWheelAction({+ activeTool: activeToolRef.current,+ isSpaceDown: isSpaceDownRef.current,+ isReferenceVisible: use3DStore.getState().isReferenceVisible,+ ctrlKey: e.ctrlKey,+ metaKey: e.metaKey,+ });+ if (wheelAction === 'camera-zoom') {+ e.preventDefault();+ e.stopPropagation();+ const delta = Math.sign(e.deltaY) * Math.min(80, Math.abs(e.deltaY));+ applyTransformDelta('camera-zoom', 0, delta * 0.45, false);+ scheduleDebouncedHistoryCommit();+ }+ };++ mount.addEventListener('wheel', handleWheel, { passive: false });+ return () => mount.removeEventListener('wheel', handleWheel);+ }, [isOpen, applyTransformDelta, scheduleDebouncedHistoryCommit]);++ // Arrow-key fine nudge when 3D tool is active (Arrows = move, Shift+Arrows = 15° rotate)+ useEffect(() => {+ if (!isOpen) return;+ const handleKeyDown = (e: KeyboardEvent) => {+ if (activeToolRef.current !== '3d' || !modelRootRef.current) return;+ const target = e.target as HTMLElement | null;+ if (+ target &&+ (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT')+ ) {+ return;+ }++ if (e.key === 'Escape') {+ if (use3DStore.getState().activeIKHandle) {+ e.preventDefault();+ selectIKTarget(null);+ }+ return;+ }++ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight' || e.key === 'ArrowUp' || e.key === 'ArrowDown') {+ e.preventDefault();+ const model = modelRootRef.current;+ if (e.shiftKey) {+ const stepRad = THREE.MathUtils.degToRad(15);+ if (e.key === 'ArrowLeft') {+ model.quaternion.premultiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -stepRad));+ } else if (e.key === 'ArrowRight') {+ model.quaternion.premultiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), stepRad));+ } else if (e.key === 'ArrowUp') {+ model.quaternion.premultiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), -stepRad));+ } else if (e.key === 'ArrowDown') {+ model.quaternion.premultiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), stepRad));+ }+ model.quaternion.normalize();+ } else {+ const step = 0.08;+ if (e.key === 'ArrowLeft') model.position.x -= step;+ if (e.key === 'ArrowRight') model.position.x += step;+ if (e.key === 'ArrowUp') model.position.y += step;+ if (e.key === 'ArrowDown') model.position.y -= step;+ }+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();+ scheduleDebouncedHistoryCommit();+ }+ };++ window.addEventListener('keydown', handleKeyDown);+ return () => window.removeEventListener('keydown', handleKeyDown);+ }, [isOpen, selectIKTarget, scheduleTransformSyncToStore, scheduleDebouncedHistoryCommit]);++ // Capture-phase guard: Alt+Left, Middle-click, or Right-click ALWAYS suppress TransformControls so camera control never gets blocked by gizmo rings+ const handleHostPointerDownCapture = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!isInteractive) return;+ const tc = transformControlsRef.current;+ if (tc && (e.altKey || e.button !== 0)) {+ tc.enabled = false;+ gizmoSuppressedRef.current = true;}- }, []);+ };- // Apply Pose Presets (Standing, Action, Sitting, Fists, Relaxed Palm)- const handleApplyPreset = useCallback((preset: PosePresetName) => {- if (!mannequinBonesRef.current) return;- applyPosePreset(mannequinBonesRef.current, preset);- if (ikHandlesRef.current) {- const updateHandle = (name: string, bone?: THREE.Bone) => {- if (bone && ikHandlesRef.current![name]) {- const wp = new THREE.Vector3();- bone.getWorldPosition(wp);- ikHandlesRef.current![name].position.copy(wp);+ // Unified deterministic Pointer Down handler (obeys resolve3DPointerAction rules)+ const handleCanvasPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {+ if (!isInteractive) return;++ const tc = transformControlsRef.current;+ const isGizmoHit = Boolean(tc && tc.enabled && (tc.dragging || tc.axis !== null));+ const state = use3DStore.getState();++ // Raycast IK handles & model meshes in exact canvas NDC space+ let hitIKName: string | null = null;+ let isModelHit = false;+ if (cameraRef.current && !isGizmoHit && e.button === 0 && !e.altKey) {+ const ndc = clientToNDC(e.clientX, e.clientY);+ raycasterRef.current.setFromCamera(new THREE.Vector2(ndc.x, ndc.y), cameraRef.current);++ if (ikHandlesContainerRef.current && ikHandlesContainerRef.current.visible) {+ const ikHits = raycasterRef.current.intersectObjects(ikHandlesContainerRef.current.children, true);+ if (ikHits.length > 0) {+ const found = ikHits[0].object;+ hitIKName =+ found.userData?.ikHandleName || found.parent?.userData?.ikHandleName || null;}- };- updateHandle('head', mannequinBonesRef.current.head);- updateHandle('leftHand', mannequinBonesRef.current.leftHand);- updateHandle('rightHand', mannequinBonesRef.current.rightHand);- updateHandle('leftFoot', mannequinBonesRef.current.leftFoot);- updateHandle('rightFoot', mannequinBonesRef.current.rightFoot);+ }++ if (!hitIKName && modelRootRef.current) {+ const modelHits = raycasterRef.current.intersectObject(modelRootRef.current, true);+ isModelHit = modelHits.some((h) => !h.object.userData?.is3DHelper);+ }+ }++ const action = resolve3DPointerAction({+ activeTool: activeToolRef.current,+ isSpaceDown: isSpaceDownRef.current,+ isReferenceVisible: state.isReferenceVisible,+ button: e.button,+ altKey: e.altKey,+ shiftKey: e.shiftKey,+ ctrlKey: e.ctrlKey,+ metaKey: e.metaKey,+ activeMode: state.activeMode,+ gizmoMode: state.gizmoMode,+ isGizmoHit,+ isIKHandleHit: Boolean(hitIKName),+ isModelHit,+ hasModel: Boolean(modelRootRef.current),+ });++ if (action === 'pass-through-2d') {+ return;}- }, []);- // 3D LT Lineart & Screentone Extraction (3D-to-2D Line Extraction)- const handleExtractLineAndTone = async (settings?: LTConversionSettings) => {- if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || isBaking) return;- setIsBaking(true);+ e.stopPropagation();++ if (action === 'gizmo-drag') {+ // TransformControls owns this drag cleanly+ return;+ }+ if (action === 'ik-select' && hitIKName) {+ e.preventDefault();+ selectIKTarget(hitIKName);+ return;+ }++ // Begin our unified camera/model drag+ e.preventDefault();try {- if (transformHelperRef.current) transformHelperRef.current.visible = false;- if (gridHelperRef.current) gridHelperRef.current.visible = false;- if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = false;-- const effectiveLineWidth = settings?.lineWidth ?? 1;- const effectiveThreshold = settings?.lineThreshold ?? 0.28;- const effectiveToneCount = settings?.toneCount ?? 2;- const modelDisplayName = loadedFileName- ? loadedFileName.replace(/\.[^/.]+$/, '')- : isMannequinActive- ? 'Mannequin'- : '3D Model';- const targetFolderName = settings?.folderName?.trim() || `3D Extraction [${modelDisplayName}]`;-- await bake3DToLineAndTone({- scene: sceneRef.current,- camera: cameraRef.current,- dimensions,- activeRenderer: rendererRef.current,- modelName: modelDisplayName,- targetFolderName,- lineWidth: effectiveLineWidth,- lineThreshold: effectiveThreshold,- toneCount: effectiveToneCount,- antiAliasing: true,- disposeOnComplete: true,- onInsertLayers: (layers, canvases) => {- // Insert in reverse order so folder layer ends up at top in layer list- for (let i = layers.length - 1; i >= 0; i--) {- onInsertRasterLayer(layers[i], canvases[i]);- }- },- });+ e.currentTarget.setPointerCapture(e.pointerId);+ } catch {+ // ignore+ }- onClose();- } catch (err) {- console.error('[3D] Failed to extract line & tone:', err);- setIsBaking(false);- if (gridHelperRef.current) gridHelperRef.current.visible = showGrid;- if (transformHelperRef.current && gizmoMode !== 'none') transformHelperRef.current.visible = true;- if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = true;+ const model = modelRootRef.current;+ canvasDragRef.current = {+ action,+ startX: e.clientX,+ startY: e.clientY,+ lastX: e.clientX,+ lastY: e.clientY,+ moved: false,+ accumYawDeg: 0,+ accumPitchDeg: 0,+ accumRollDeg: 0,+ startQuat: model ? model.quaternion.clone() : null,+ startScale: model ? model.scale.clone() : null,+ startPos: model ? model.position.clone() : null,+ totalDx: 0,+ totalDy: 0,+ };+ };++ const handleCanvasPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {+ const drag = canvasDragRef.current;+ if (!drag) return;++ const dx = e.clientX - drag.lastX;+ const dy = e.clientY - drag.lastY;+ drag.lastX = e.clientX;+ drag.lastY = e.clientY;+ drag.totalDx += dx;+ drag.totalDy += dy;++ if (!drag.moved && Math.hypot(e.clientX - drag.startX, e.clientY - drag.startY) > 3) {+ drag.moved = true;+ }++ const snap = e.shiftKey || use3DStore.getState().snapEnabled;+ const model = modelRootRef.current;+ const camera = cameraRef.current;++ // Clean 15° rotation snapping relative to drag start quaternion when Shift/Snap is active+ if (+ snap &&+ model &&+ camera &&+ drag.startQuat &&+ (drag.action === 'model-rotate' ||+ drag.action === 'model-rotate-yaw' ||+ drag.action === 'model-rotate-roll')+ ) {+ const meta = viewportMetaRef.current;+ const camState = navigation+ ? navigation.getCameraState()+ : { rotation: meta.rotation, flipX: meta.flipX, flipY: meta.flipY };+ const mapped = mapScreenDeltaToCanvasDelta(+ drag.totalDx,+ drag.totalDy,+ camState.rotation,+ camState.flipX,+ camState.flipY+ );+ const degPerPx = 0.55;+ model.quaternion.copy(drag.startQuat);++ if (drag.action === 'model-rotate') {+ const yawDeg = snapAngleDeg(mapped.dx * degPerPx, 15);+ const pitchDeg = snapAngleDeg(mapped.dy * degPerPx, 15);+ const camUp = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion).normalize();+ const camRight = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion).normalize();+ model.quaternion+ .premultiply(new THREE.Quaternion().setFromAxisAngle(camUp, THREE.MathUtils.degToRad(yawDeg)))+ .premultiply(new THREE.Quaternion().setFromAxisAngle(camRight, THREE.MathUtils.degToRad(pitchDeg)))+ .normalize();+ } else if (drag.action === 'model-rotate-yaw') {+ const yawDeg = snapAngleDeg(mapped.dx * degPerPx, 15);+ model.quaternion+ .premultiply(+ new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), THREE.MathUtils.degToRad(yawDeg))+ )+ .normalize();+ } else if (drag.action === 'model-rotate-roll') {+ const rollDeg = snapAngleDeg(mapped.dx * degPerPx, 15);+ const camDir = new THREE.Vector3();+ camera.getWorldDirection(camDir);+ model.quaternion+ .premultiply(new THREE.Quaternion().setFromAxisAngle(camDir, THREE.MathUtils.degToRad(rollDeg)))+ .normalize();+ }+ model.updateMatrixWorld(true);+ syncIKHandlesToBones(mannequinBonesRef.current, ikHandlesRef.current);+ scheduleTransformSyncToStore();+ return;+ }++ if (dx !== 0 || dy !== 0) {+ applyTransformDelta(drag.action, dx, dy, snap);}};- // Bake 3D to 2D Layer (Ensuring Gizmos & Grids are NOT baked into layer)- const handleBakeTo2D = async () => {- if (!sceneRef.current || !cameraRef.current || !modelRootRef.current || isBaking) return;- setIsBaking(true);+ const handleCanvasPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {+ if (gizmoSuppressedRef.current) {+ gizmoSuppressedRef.current = false;+ syncGizmoAttachment();+ }++ const drag = canvasDragRef.current;+ if (!drag) return;try {- // Temporarily hide helper gizmo, ground grid, and IK handles- if (transformHelperRef.current) transformHelperRef.current.visible = false;- if (gridHelperRef.current) gridHelperRef.current.visible = false;- if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = false;-- const result = await bake3DToRasterLayer({- scene: sceneRef.current,- camera: cameraRef.current,- dimensions,- activeRenderer: rendererRef.current,- layerName: loadedFileName ? `3D (${loadedFileName})` : '3D Model',- opacity,- blendMode: 'normal',- onInsertLayer: (layer, rasterCanvas) => {- onInsertRasterLayer(layer, rasterCanvas);- },- });+ e.currentTarget.releasePointerCapture(e.pointerId);+ } catch {+ // ignore+ }- onBakeSuccess?.(result.layer);- onClose();- } catch (err) {- console.error('[3D] Failed to rasterize 3D layer:', err);- setIsBaking(false);- if (gridHelperRef.current) gridHelperRef.current.visible = showGrid;- if (transformHelperRef.current && gizmoMode !== 'none') transformHelperRef.current.visible = true;- if (ikHandlesContainerRef.current) ikHandlesContainerRef.current.visible = true;+ // Clicking empty space (without dragging) deselects an active IK handle so model gizmo returns+ if (!drag.moved && drag.action === 'camera-orbit' && use3DStore.getState().activeIKHandle) {+ selectIKTarget(null);+ } else if (drag.moved) {+ commitHistoryNow();}++ canvasDragRef.current = null;};if (!isOpen) return null;+ const cursorClass = !isInteractive+ ? ''+ : activeMode.startsWith('camera') || activeMode === 'smart'+ ? 'cursor-grab active:cursor-grabbing'+ : activeMode === 'model-scale'+ ? 'cursor-nesw-resize'+ : activeMode.startsWith('model-rotate')+ ? 'cursor-crosshair'+ : 'cursor-move';+return (<>- {/* 3D WebGL Canvas Layer */}+ {/* 3D WebGL Canvas Stage (pointer-events-none when drawing with 2D tools or holding Space!) */}<divref={mountRef}- className="absolute inset-0 pointer-events-auto z-30 select-none overflow-visible"+ data-testid="local-3d-stage"+ className={`absolute inset-0 z-30 select-none overflow-visible ${+ isInteractive ? 'pointer-events-auto' : 'pointer-events-none'+ }`}style={{width: `${dimensions.width}px`,height: `${dimensions.height}px`,+ visibility: isReferenceVisible ? 'visible' : 'hidden',+ }}+ onContextMenu={(e) => {+ if (isInteractive) {+ e.preventDefault();+ e.stopPropagation();+ }}}- onPointerDown={(e) => e.stopPropagation()}onDragOver={(e) => {+ if (!isInteractive) return;e.preventDefault();e.stopPropagation();}}onDrop={(e) => {+ if (!isInteractive) return;e.preventDefault();e.stopPropagation();const file = e.dataTransfer.files?.[0];@@ -1121,19 +2254,13 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({><divref={canvasHostRef}+ onPointerDownCapture={handleHostPointerDownCapture}onPointerDown={handleCanvasPointerDown}onPointerMove={handleCanvasPointerMove}onPointerUp={handleCanvasPointerUp}- className={`w-full h-full block ${- activeToolMode.startsWith('camera')- ? 'cursor-grab active:cursor-grabbing'- : activeToolMode === 'model-rotate-free'- ? 'cursor-crosshair'- : 'cursor-move'- }`}- style={{- opacity,- }}+ onPointerCancel={handleCanvasPointerUp}+ className={`w-full h-full block ${cursorClass}`}+ style={{ opacity }}/>{webglError && (@@ -1152,44 +2279,36 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({</div>)}- {/* Empty state prompt if no model is loaded */}- {!webglError && !loadedFileName && (+ {/* Quick-Start Empty State (only interactive when 3D tool is active) */}+ {!webglError && !loadedModelName && is3DToolActive && isReferenceVisible && (<div className="absolute inset-0 flex items-center justify-center pointer-events-none">- <div className="bg-[#202020]/95 border border-white/[0.1] backdrop-blur-md rounded-lg px-6 py-5 flex flex-col items-center space-y-3 pointer-events-auto shadow-2xl text-center max-w-xs">- <div className="w-10 h-10 rounded-md bg-[#161616] border border-white/[0.08] flex items-center justify-center text-[#8a8a8a]">- <Upload className="w-5 h-5" />+ <div+ className="bg-[#202020]/95 border border-white/[0.1] backdrop-blur-md rounded-lg px-5 py-4 flex flex-col items-center space-y-3 pointer-events-auto shadow-2xl text-center w-64"+ onPointerDown={(e) => e.stopPropagation()}+ >+ <div className="w-9 h-9 rounded-md bg-[#161616] border border-white/[0.08] flex items-center justify-center text-[var(--accent)]">+ <Box className="w-5 h-5" /></div><div><p className="text-xs font-medium text-[#e5e5e5]">3D Reference Stage</p><p className="text-[11px] text-[#8a8a8a] mt-1">- Drop a .glb, .gltf, or .obj file, or start with a rigged mannequin+ Drop a .glb, .gltf, or .obj 3D model here to begin.</p></div>- <div className="flex items-center space-x-2 pt-1">- <button- type="button"- onClick={() => fileInputRef.current?.click()}- className="px-3 py-1.5 bg-[#2c2c2c] hover:bg-[#383838] text-[#e5e5e5] rounded text-xs font-medium transition-colors cursor-pointer"- >- Import Model- </button>- <button- type="button"- onClick={() => {- loadProceduralMannequin();- setInspectorTab('pose');- }}- className="px-3 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer"- >- Insert Mannequin- </button>- </div>+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ className="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 rounded text-xs font-medium transition-opacity cursor-pointer"+ >+ <Upload className="w-3.5 h-3.5" />+ <span>Import 3D Model</span>+ </button></div></div>)}</div>- {/* Modern Unified 3D Workspace HUD (Rendered via Portal) */}+ {/* Compact On-Canvas Floating 3D Bar & Separate LT Preview Modal (Rendered via Portal) */}{createPortal(<><input@@ -1199,474 +2318,37 @@ export const Local3DContainer: React.FC<Local3DContainerProps> = ({className="hidden"onChange={handleFileUpload}/>-- {/* Compact Single-Row Top Action Bar */}- <div- className="fixed top-12 left-1/2 -translate-x-1/2 z-50 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-lg px-2 py-1 shadow-2xl flex items-center gap-1.5 text-xs text-[#e5e5e5] select-none"- onPointerDown={(e) => e.stopPropagation()}- >- {/* Model Source */}- <div className="flex items-center bg-[#161616] rounded p-0.5 border border-white/[0.06]">- <button- type="button"- onClick={() => fileInputRef.current?.click()}- title="Import 3D Model (.glb, .gltf, .obj)"- className={`px-2 py-0.5 rounded text-[11px] transition-colors cursor-pointer max-w-[96px] truncate ${- loadedFileName && !isMannequinActive- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- {loadedFileName && !isMannequinActive ? loadedFileName : 'Import 3D'}- </button>- <button- type="button"- onClick={() => {- loadProceduralMannequin();- setInspectorTab('pose');- }}- title="Load Rigged Humanoid Mannequin"- className={`px-2 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${- isMannequinActive- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- Mannequin- </button>- </div>-- <div className="w-px h-4 bg-white/[0.08]" />-- {/* Camera / Object Mode & Unified Line & Tone */}- <Csp3DToolbar- activeMode={activeToolMode}- onSelectMode={(mode) => setActiveToolMode(mode)}- onDirectDrag={(mode, dx, dy) => applyTransformDelta(mode, dx, dy)}- onExtractLineAndTone={handleExtractLineAndTone}- isExtracting={isBaking}- hasModel={Boolean(loadedFileName)}- modelName={loadedFileName || (isMannequinActive ? 'Mannequin' : '3D Model')}- />-- <div className="w-px h-4 bg-white/[0.08]" />-- {/* Inspector Toggle */}- <button- type="button"- onClick={() => setShowInspector((v) => !v)}- title={showInspector ? 'Hide 3D Inspector' : 'Show 3D Inspector'}- className={`p-1 rounded transition-colors cursor-pointer ${- showInspector- ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- <SlidersHorizontal className="w-3.5 h-3.5" />- </button>-- {/* Primary Bake Action */}- <button- type="button"- onClick={handleBakeTo2D}- disabled={isBaking || !loadedFileName}- title={!loadedFileName ? 'Load a model first' : 'Rasterize 3D view into a 2D Layer'}- className="px-2.5 py-1 bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium rounded text-[11px] transition-opacity disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer"- >- {isBaking ? 'Baking...' : 'Bake Layer'}- </button>-- {/* Close */}- <button- type="button"- onClick={onClose}- title="Close 3D Stage"- className="p-1 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] rounded transition-colors cursor-pointer"- >- <X className="w-3.5 h-3.5" />- </button>- </div>-- {/* Collapsible Floating 3D Inspector (Docked Bottom-Left, Zero Overlap) */}- {showInspector && (- <div- className="fixed bottom-10 left-16 z-50 w-64 bg-[#202020]/95 backdrop-blur-md border border-white/[0.1] rounded-lg shadow-2xl overflow-hidden text-xs text-[#e5e5e5] select-none flex flex-col max-h-[calc(100vh-140px)]"- onPointerDown={(e) => e.stopPropagation()}- >- {/* Tabs */}- <div className="flex items-center bg-[#1a1a1a] border-b border-white/[0.06] p-1 gap-0.5">- {(- [- ['transform', 'Transform'],- ['scene', 'Scene'],- ...(isMannequinActive ? ([['pose', 'Pose']] as const) : []),- ] as Array<['transform' | 'scene' | 'pose', string]>- ).map(([tabId, label]) => (- <button- key={tabId}- type="button"- onClick={() => setInspectorTab(tabId)}- className={`flex-1 py-1 rounded text-[11px] transition-colors cursor-pointer ${- inspectorTab === tabId- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'- }`}- >- {label}- </button>- ))}- </div>-- <div className="p-3 space-y-3 overflow-y-auto">- {inspectorTab === 'transform' && (- <>- {/* Fine Model Rotation Modes */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- Model Controls- </span>- <div className="grid grid-cols-3 gap-1 bg-[#161616] p-0.5 rounded border border-white/[0.06]">- {(- [- ['model-rotate-free', 'Free'],- ['model-rotate-yaw', 'Turn Y'],- ['model-rotate-roll', 'Roll'],- ] as Array<[Csp3DToolMode, string]>- ).map(([mode, lbl]) => (- <button- key={mode}- type="button"- onClick={() => setActiveToolMode(mode)}- className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${- activeToolMode === mode- ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'- }`}- >- {lbl}- </button>- ))}- </div>- </div>-- {/* Quick Turn */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- Quick Turn- </span>- <div className="grid grid-cols-3 gap-1">- <button- type="button"- onClick={() => rotateModelYaw(-90)}- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] font-mono text-[#e5e5e5] cursor-pointer"- >- -90°- </button>- <button- type="button"- onClick={() => rotateModelYaw(90)}- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] font-mono text-[#e5e5e5] cursor-pointer"- >- +90°- </button>- <button- type="button"- onClick={() => rotateModelYaw(180)}- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] font-mono text-[#e5e5e5] cursor-pointer"- >- 180°- </button>- </div>- </div>-- {/* 3D Gizmo */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- 3D Gizmo- </span>- <div className="grid grid-cols-3 gap-1 bg-[#161616] p-0.5 rounded border border-white/[0.06]">- {(- [- ['none', 'Off'],- ['rotate', 'Rotate'],- ['translate', 'Move'],- ] as Array<[GizmoMode, string]>- ).map(([gMode, lbl]) => (- <button- key={gMode}- type="button"- onClick={() => setGizmoMode(gMode)}- className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${- gizmoMode === gMode- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'- }`}- >- {lbl}- </button>- ))}- </div>- </div>-- {/* Utility Actions */}- <div className="grid grid-cols-2 gap-1.5 pt-1 border-t border-white/[0.06]">- <button- type="button"- onClick={handleSnapToGround}- className="py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] text-[#e5e5e5] cursor-pointer"- >- Snap Floor- </button>- <button- type="button"- onClick={handleResetModelTransform}- className="py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"- >- Reset Model- </button>- <button- type="button"- onClick={handleResetCamera}- className="col-span-2 py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"- >- Reset Camera- </button>- </div>- </>- )}-- {inspectorTab === 'scene' && (- <>- {/* Camera Presets */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- Camera Angle- </span>- <div className="grid grid-cols-3 gap-1">- {(- [- ['front', 'Front'],- ['threeQuarter', '3/4'],- ['side', 'Side'],- ['back', 'Back'],- ['top', 'Top'],- ['lowAngle', 'Low'],- ] as const- ).map(([preset, lbl]) => (- <button- key={preset}- type="button"- onClick={() => setCameraPreset(preset)}- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] cursor-pointer"- >- {lbl}- </button>- ))}- </div>- </div>-- {/* Shading */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- Shading- </span>- <div className="grid grid-cols-3 gap-1 bg-[#161616] p-0.5 rounded border border-white/[0.06]">- {(['shaded', 'smooth', 'silhouette'] as ShadingMode[]).map((mode) => (- <button- key={mode}- type="button"- onClick={() => {- setShadingMode(mode);- applyShading(mode);- }}- className={`py-1 rounded text-[10px] capitalize transition-colors cursor-pointer ${- shadingMode === mode- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'- }`}- >- {mode}- </button>- ))}- </div>- </div>-- {/* Sliders */}- <div className="space-y-2">- <div>- <div className="flex justify-between text-[11px] mb-0.5">- <span className="text-[#8a8a8a]">Perspective</span>- <span className="font-mono text-[#e5e5e5]">{perspective.toFixed(1)}x</span>- </div>- <input- type="range"- min="0.3"- max="2.5"- step="0.05"- value={perspective}- onChange={(e) => applyPerspectiveDollyZoom(parseFloat(e.target.value))}- className="w-full"- />- </div>-- <div>- <div className="flex justify-between text-[11px] mb-0.5">- <span className="text-[#8a8a8a]">Opacity</span>- <span className="font-mono text-[#e5e5e5]">{Math.round(opacity * 100)}%</span>- </div>- <input- type="range"- min="0.1"- max="1"- step="0.05"- value={opacity}- onChange={(e) => setOpacity(parseFloat(e.target.value))}- className="w-full"- />- </div>- </div>-- {/* Toggles */}- <div className="space-y-1.5 pt-1 border-t border-white/[0.06]">- <label className="flex items-center justify-between text-[11px] text-[#cccccc] cursor-pointer">- <span>Floor Grid</span>- <input- type="checkbox"- checked={showGrid}- onChange={(e) => setShowGrid(e.target.checked)}- />- </label>- <label className="flex items-center justify-between text-[11px] text-[#cccccc] cursor-pointer">- <span>Sync Perspective Ruler</span>- <input- type="checkbox"- checked={syncCameraPerspective}- onChange={(e) => {- const nextSync = e.target.checked;- setSyncCameraPerspective(nextSync);- if (nextSync && cameraRef.current && onUpdatePerspectiveRuler) {- const ruler = calculatePerspectiveFromCamera(- cameraRef.current,- dimensions.width,- dimensions.height,- perspectiveRuler- );- onUpdatePerspectiveRuler(ruler);- }- }}- />- </label>- </div>-- {/* Collapsible Light Source */}- <div className="pt-1 border-t border-white/[0.06] space-y-2">- <button- type="button"- onClick={() => setShowLightPanel((v) => !v)}- className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] text-[#e5e5e5] flex items-center justify-between cursor-pointer"- >- <span>Lighting</span>- <span className="text-[10px] text-[#8a8a8a]">- {showLightPanel ? 'Hide' : 'Adjust'}- </span>- </button>-- {showLightPanel && (- <LightSourceWidget- embedded- settings={lightSettings}- onChange={(s) => setLightSettings(s)}- onReset={() =>- setLightSettings({- azimuth: 45,- elevation: 45,- intensity: 1.5,- ambientIntensity: 0.65,- color: '#ffffff',- isBacklit: false,- })- }- />- )}- </div>- </>- )}-- {inspectorTab === 'pose' && isMannequinActive && (- <>- {/* Pose Presets */}- <div className="space-y-1">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- Pose Presets- </span>- <div className="grid grid-cols-2 gap-1">- {(- [- ['standing', 'Standing'],- ['action', 'Action'],- ['sitting', 'Seated'],- ['fists', 'Fists'],- ['relaxed_palm', 'Relaxed'],- ] as Array<[PosePresetName, string]>- ).map(([preset, lbl]) => (- <button- key={preset}- type="button"- onClick={() => handleApplyPreset(preset)}- className="py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[11px] text-[#e5e5e5] text-left cursor-pointer"- >- {lbl}- </button>- ))}- </div>- </div>-- {/* IK Limb Handles */}- <div className="space-y-1 pt-1 border-t border-white/[0.06]">- <div className="flex items-center justify-between">- <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a]">- IK Limbs- </span>- {activeIKHandle && (- <button- type="button"- onClick={() => selectIKTarget(null)}- className="text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"- >- Deselect- </button>- )}- </div>- <div className="grid grid-cols-3 gap-1">- {(- [- ['head', 'Head'],- ['leftHand', 'L-Hand'],- ['rightHand', 'R-Hand'],- ['leftFoot', 'L-Foot'],- ['rightFoot', 'R-Foot'],- ] as const- ).map(([limb, lbl]) => (- <button- key={limb}- type="button"- onClick={() => selectIKTarget(activeIKHandle === limb ? null : limb)}- className={`py-1 px-1.5 rounded text-[10px] transition-colors cursor-pointer ${- activeIKHandle === limb- ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'- : 'bg-[#161616] border border-white/[0.06] text-[#cccccc] hover:bg-[#2c2c2c]'- }`}- >- {lbl}- </button>- ))}- </div>- </div>- </>- )}- </div>- </div>- )}+ <Csp3DToolbar+ is3DToolActive={is3DToolActive}+ onActivate3DTool={() => toolStoreActions.selectTool('3d')}+ onDirectDrag={(mode, dx, dy, snap) => applyTransformDelta(mode, dx, dy, snap)}+ onDirectDragEnd={commitHistoryNow}+ onTriggerImport={() => fileInputRef.current?.click()}+ onSnapToGround={handleSnapToGround}+ onUndo={() => {+ handleUndo3D();+ }}+ onRedo={() => {+ handleRedo3D();+ }}+ onOpenLTModal={() => setIsLTModalOpen(true)}+ isLTModalOpen={isLTModalOpen}+ onBakeTo2D={(closeAfter) => {+ void handleBakeTo2D(closeAfter);+ }}+ onClose={onClose}+ />+ <LTExtractionModal+ isOpen={isLTModalOpen}+ modelName={loadedModelName || '3D Model'}+ dimensions={dimensions}+ isExtracting={isBaking}+ onRenderPreview={handleRenderLTPreview}+ onExtract={(settings) => {+ void handleExtractLineAndTone(settings);+ }}+ onClose={() => setIsLTModalOpen(false)}+ /></>,document.body)}diff --git a/src/components/PigmentBlendControl.tsx b/src/components/PigmentBlendControl.tsxnew file mode 100644index 0000000..7583e74--- /dev/null+++ b/src/components/PigmentBlendControl.tsx@@ -0,0 +1,252 @@+import React, { useMemo, useState } from 'react';+import {+ mixPigmentsWithStrength,+ parseColorToRgb,+ rgbToHex,+} from '../utils/colorMixingEngine';++export interface PigmentBlendControlProps {+ /** Whether physical spectral pigment blending is active (false = Regular RGB). */+ enabled: boolean;+ onEnabledChange: (enabled: boolean) => void;+ /** Pigment blending strength in [0, 1] (optional — omit to hide strength slider). */+ strength?: number;+ onStrengthChange?: (strength: number) => void;+ /** Optional active foreground / background colors for the live FG -> BG swatch option. */+ primaryColor?: string;+ secondaryColor?: string;+ /** Section heading label (defaults to "Color Blending"). */+ label?: string;+ /** Slider label when Pigment mode is active (defaults to "Pigment Strength"). */+ strengthLabel?: string;+ /** Layout density matching either ToolPropertyInspector ('compact') or BrushStudioModal ('studio'). */+ variant?: 'compact' | 'studio';+ /** Whether to show the live Regular vs Pigment gradient preview bar (defaults to true). */+ showPreview?: boolean;+}++interface SwatchPair {+ id: string;+ label: string;+ c1: string;+ c2: string;+}++const DEFAULT_PAIRS: readonly SwatchPair[] = [+ { id: 'blue-yellow', label: 'Blue + Yellow', c1: '#0084ff', c2: '#fff000' },+ { id: 'green-magenta', label: 'Green + Magenta', c1: '#28ff00', c2: '#ff00a6' },+ { id: 'sky-cream', label: 'Sky + Cream', c1: '#4fa8ff', c2: '#fffef0' },+];++const PREVIEW_STEPS = 14;++/**+ * Computes a CSS linear-gradient string directly from Ink Studio's 7-band Kubelka-Munk+ * spectral pigment engine so the UI swatch matches canvas blending 1:1.+ */+export function buildPigmentPreviewGradient(+ colorA: string,+ colorB: string,+ enabled: boolean,+ strength: number = 1.0+): string {+ const rgbA = parseColorToRgb(colorA);+ const rgbB = parseColorToRgb(colorB);+ const effStrength = enabled ? Math.max(0, Math.min(1, strength)) : 0;+ const stops: string[] = [];++ for (let i = 0; i <= PREVIEW_STEPS; i++) {+ const t = i / PREVIEW_STEPS;+ const mixed = mixPigmentsWithStrength(rgbA, rgbB, t, effStrength);+ const hex = rgbToHex(mixed.r, mixed.g, mixed.b);+ stops.push(`${hex} ${Math.round(t * 100)}%`);+ }++ return `linear-gradient(90deg, ${stops.join(', ')})`;+}++export const PigmentBlendControl: React.FC<PigmentBlendControlProps> = React.memo(+ ({+ enabled,+ onEnabledChange,+ strength = 1.0,+ onStrengthChange,+ primaryColor,+ secondaryColor,+ label = 'Color Blending',+ strengthLabel = 'Pigment Strength',+ variant = 'compact',+ showPreview = true,+ }) => {+ const [pairIndex, setPairIndex] = useState<number>(0);++ const pairs = useMemo<SwatchPair[]>(() => {+ const list: SwatchPair[] = [...DEFAULT_PAIRS];+ if (+ primaryColor &&+ secondaryColor &&+ primaryColor.toLowerCase() !== secondaryColor.toLowerCase()+ ) {+ list.push({+ id: 'fg-bg',+ label: 'FG + BG',+ c1: primaryColor,+ c2: secondaryColor,+ });+ }+ return list;+ }, [primaryColor, secondaryColor]);++ const activePair = pairs[pairIndex % pairs.length] ?? DEFAULT_PAIRS[0];+ const clampedStrength = Math.max(0, Math.min(1, strength));+ const strengthPct = Math.round(clampedStrength * 100);++ const previewGradient = useMemo(+ () =>+ showPreview+ ? buildPigmentPreviewGradient(activePair.c1, activePair.c2, enabled, clampedStrength)+ : '',+ [activePair.c1, activePair.c2, enabled, clampedStrength, showPreview]+ );++ const isStudio = variant === 'studio';++ return (+ <div className={isStudio ? 'space-y-2.5' : 'space-y-1.5'}>+ {/* Header row */}+ <div className="flex items-center justify-between gap-1.5">+ <span+ className={+ isStudio+ ? 'text-[11px] font-medium text-[#d4d4d4]'+ : 'text-[11px] text-[#8a8a8a] truncate'+ }+ >+ {label}+ </span>+ <span+ className={`px-1.5 py-[1px] rounded-full text-[9px] font-medium tracking-wide border transition-colors ${+ enabled+ ? 'bg-emerald-500/12 text-emerald-300 border-emerald-400/25'+ : 'bg-white/[0.04] text-[#7a7a7a] border-white/[0.07]'+ }`}+ >+ {enabled ? 'Spectral' : 'RGB'}+ </span>+ </div>++ {/* Regular vs Pigment segmented switch */}+ <div+ role="radiogroup"+ aria-label={label}+ className={`grid grid-cols-2 gap-0.5 rounded p-0.5 border ${+ isStudio+ ? 'bg-[#141414] border-white/[0.06]'+ : 'bg-[#161616] border-white/[0.05]'+ }`}+ >+ <button+ type="button"+ role="radio"+ aria-checked={!enabled}+ onClick={() => onEnabledChange(false)}+ className={`flex items-center justify-center gap-1.5 rounded transition-all cursor-pointer ${+ isStudio ? 'py-1.5 text-[11px]' : 'py-1 text-[10px]'+ } ${+ !enabled+ ? 'bg-[#2c2c2c] text-[#f2f2f2] font-medium shadow-[inset_0_1px_0_rgba(255,255,255,0.08)]'+ : 'text-[#8a8a8a] hover:text-[#e0e0e0] hover:bg-white/[0.03]'+ }`}+ >+ <span+ className="w-2 h-2 rounded-full shrink-0 border border-white/15"+ style={{+ background: 'linear-gradient(135deg, #3b82f6 0%, #9ca3af 50%, #facc15 100%)',+ opacity: !enabled ? 0.9 : 0.45,+ }}+ />+ <span>Regular</span>+ </button>++ <button+ type="button"+ role="radio"+ aria-checked={enabled}+ onClick={() => onEnabledChange(true)}+ className={`flex items-center justify-center gap-1.5 rounded transition-all cursor-pointer ${+ isStudio ? 'py-1.5 text-[11px]' : 'py-1 text-[10px]'+ } ${+ enabled+ ? 'bg-[#2c2c2c] text-[#f5f5f5] font-medium shadow-[inset_0_1px_0_rgba(255,255,255,0.10)] ring-1 ring-emerald-400/25'+ : 'text-[#8a8a8a] hover:text-[#e0e0e0] hover:bg-white/[0.03]'+ }`}+ >+ <span+ className="w-2 h-2 rounded-full shrink-0 border border-white/20"+ style={{+ background: 'linear-gradient(135deg, #0084ff 0%, #34c759 50%, #fff000 100%)',+ boxShadow: enabled ? '0 0 6px rgba(52, 199, 89, 0.55)' : 'none',+ opacity: enabled ? 1 : 0.55,+ }}+ />+ <span>Pigment</span>+ </button>+ </div>++ {/* Live engine-rendered Regular vs Pigment swatch preview */}+ {showPreview && (+ <button+ type="button"+ onClick={() => setPairIndex((i) => (i + 1) % pairs.length)}+ title={`${activePair.label} (${enabled ? `Pigment ${strengthPct}%` : 'Regular RGB'}) — Click to cycle preview colors`}+ className="group relative w-full rounded overflow-hidden border border-white/[0.10] hover:border-white/[0.22] transition-all cursor-pointer block focus:outline-none focus:ring-1 focus:ring-[var(--accent)]"+ style={{ height: isStudio ? 22 : 17 }}+ >+ <div+ className="w-full h-full transition-[background] duration-200"+ style={{ background: previewGradient }}+ />+ <div+ className="pointer-events-none absolute inset-0"+ style={{+ background:+ 'linear-gradient(180deg, rgba(255,255,255,0.14) 0%, rgba(255,255,255,0) 45%, rgba(0,0,0,0.18) 100%)',+ }}+ />+ <div className="pointer-events-none absolute inset-x-1.5 inset-y-0 flex items-center justify-between">+ <span className="text-[9px] font-medium text-white drop-shadow-[0_1px_2px_rgba(0,0,0,0.85)] opacity-80 group-hover:opacity-100 transition-opacity">+ {activePair.label}+ </span>+ <span className="text-[8.5px] font-mono uppercase tracking-wider text-white/90 bg-black/35 px-1 rounded backdrop-blur-[2px] opacity-85 group-hover:opacity-100 transition-opacity">+ {enabled ? 'Pigment' : 'Regular'}+ </span>+ </div>+ </button>+ )}++ {/* Pigment Strength slider (only shown when Pigment mode is active & callback provided) */}+ {enabled && onStrengthChange && (+ <div className="space-y-1 pt-0.5">+ <div className="flex items-center justify-between text-[11px]">+ <span className={isStudio ? 'text-[#a3a3a3]' : 'text-[#8a8a8a] truncate'}>+ {strengthLabel}+ </span>+ <span className="font-mono text-[10px] text-[#e5e5e5] ml-1 shrink-0">+ {strengthPct}%+ </span>+ </div>+ <input+ type="range"+ min={0}+ max={100}+ step={1}+ value={strengthPct}+ onChange={(e) => onStrengthChange(Number(e.target.value) / 100)}+ className={`w-full ${isStudio ? 'accent-[var(--accent)]' : ''}`}+ />+ </div>+ )}+ </div>+ );+ }+);diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsxindex 9dd71d9..550d10e 100644--- a/src/components/RightSidebar.tsx+++ b/src/components/RightSidebar.tsx@@ -22,6 +22,8 @@ import {Type,MessageSquare,Shield,+ Layers,+ Scaling,} from 'lucide-react';import {HistoryItemMeta,@@ -31,7 +33,9 @@ import {CanvasColorMode,ExpressionColor,isFolderLikeLayer,+ isDedicatedToneLayer,} from '../types/editor';+import { HalftoneDotShape } from '../utils/screentoneEngine';import { BLEND_MODES } from '../utils/canvasUtils';import { ColorPanel } from './ColorPanel';import { useToolStore, toolStoreActions } from '../stores';@@ -151,14 +155,17 @@ export interface RightSidebarProps {onOpenLayerStylesModal?: (layerId: string) => void;onEditVectorLayer?: (layer: LayerItem) => void;onRasterizeLayer?: (layerId: string) => void;+ onMergeFolder?: (folderId: string) => void;+ onTransformLayer?: () => void;onReorderLayers?: (draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => void;onToggleReferenceLayer?: (id: string) => void;onToggleTone?: (id: string) => void;onSetToneFrequency?: (id: string, frequency: number) => void;onSetToneAngle?: (id: string, angle: number) => void;- onSetToneDotShape?: (id: string, dotShape: 'circle' | 'euclidean') => void;+ onSetToneDotShape?: (id: string, dotShape: HalftoneDotShape) => void;onSetToneDensity?: (id: string, density: number) => void;onSetToneDensityType?: (id: string, densityType: 'specified' | 'image') => void;+ onCreateToneLayer?: () => void;onToggleLayerColor?: (id: string) => void;onSetLayerColor?: (id: string, color: string) => void;onSetLayerSubColor?: (id: string, color: string) => void;@@ -249,13 +256,15 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({onOpenLayerStylesModal,onEditVectorLayer,onRasterizeLayer,+ onMergeFolder,+ onTransformLayer,onToggleReferenceLayer,onToggleTone,onSetToneFrequency,onSetToneAngle,onSetToneDotShape,onSetToneDensity,- onSetToneDensityType,+ onCreateToneLayer,onToggleLayerColor,onSetLayerColor,onSetLayerSubColor,@@ -826,6 +835,44 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({fx</button>)}+ {isFolderLikeLayer(activeLayer) && onMergeFolder && (+ <button+ type="button"+ disabled={activeLayer.locked}+ onClick={() => onMergeFolder(activeLayer.id)}+ title={+ activeLayer.locked+ ? 'Unlock folder to merge'+ : 'Merge Folder into Single Layer'+ }+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors ${+ activeLayer.locked+ ? 'text-[#8a8a8a]/30 cursor-not-allowed'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'+ }`}+ >+ <Layers className="w-3 h-3" />+ </button>+ )}+ {isFolderLikeLayer(activeLayer) && onTransformLayer && (+ <button+ type="button"+ disabled={activeLayer.locked}+ onClick={() => onTransformLayer()}+ title={+ activeLayer.locked+ ? 'Unlock folder to transform'+ : 'Transform Folder (Ctrl+T)'+ }+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors ${+ activeLayer.locked+ ? 'text-[#8a8a8a]/30 cursor-not-allowed'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'+ }`}+ >+ <Scaling className="w-3 h-3" />+ </button>+ )}</div></div></div>@@ -1319,97 +1366,102 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({onChange={() => onToggleTone?.(activeLayer.id)}/></label>+ {onCreateToneLayer && (+ <button+ type="button"+ onClick={onCreateToneLayer}+ className="w-full h-6 px-2 rounded bg-[#2a2a2a] hover:bg-[#333333] text-[10px] text-[#d4d4d4] border border-white/[0.06] transition-colors cursor-pointer"+ >+ New Screentone Layer...+ </button>+ )}- {activeLayer.toneEnabled && (- <div className="space-y-2">- <select- value={activeLayer.toneDensityType ?? 'specified'}- onChange={(e) =>- onSetToneDensityType?.(- activeLayer.id,- e.target.value as 'specified' | 'image'- )- }- className="w-full h-6 px-1.5 text-[10px]"- >- <option value="specified">Specified Density</option>- <option value="image">Image Brightness</option>- </select>+ {activeLayer.toneEnabled && (() => {+ const isToneLayer = isDedicatedToneLayer(activeLayer);+ return (+ <div className="space-y-2">+ {isToneLayer ? (+ <div className="space-y-1">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Density</span>+ <span className="font-mono text-[#e5e5e5]">+ {activeLayer.toneDensity ?? 40}%+ </span>+ </div>+ <input+ type="range"+ min="1"+ max="100"+ value={activeLayer.toneDensity ?? 40}+ onChange={(e) =>+ onSetToneDensity?.(activeLayer.id, parseInt(e.target.value, 10))+ }+ className="w-full"+ />+ </div>+ ) : (+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">+ <span>Density</span>+ <span className="font-mono text-[#a3a3a3]">Layer tones</span>+ </div>+ )}- {(activeLayer.toneDensityType ?? 'specified') === 'specified' && (<div className="space-y-1"><div className="flex justify-between text-[10px]">- <span className="text-[#8a8a8a]">Density</span>+ <span className="text-[#8a8a8a]">Frequency</span><span className="font-mono text-[#e5e5e5]">- {activeLayer.toneDensity ?? 40}%+ {activeLayer.toneFrequency ?? 60} LPI</span></div><inputtype="range"- min="1"- max="100"- value={activeLayer.toneDensity ?? 40}+ min="20"+ max="85"+ value={activeLayer.toneFrequency ?? 60}onChange={(e) =>- onSetToneDensity?.(activeLayer.id, parseInt(e.target.value, 10))+ onSetToneFrequency?.(activeLayer.id, parseInt(e.target.value, 10))}className="w-full"/></div>- )}- <div className="space-y-1">- <div className="flex justify-between text-[10px]">- <span className="text-[#8a8a8a]">Frequency</span>- <span className="font-mono text-[#e5e5e5]">- {activeLayer.toneFrequency ?? 60} LPI- </span>+ <div className="space-y-1">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Angle</span>+ <span className="font-mono text-[#e5e5e5]">+ {activeLayer.toneAngle ?? 45}°+ </span>+ </div>+ <input+ type="range"+ min="0"+ max="90"+ value={activeLayer.toneAngle ?? 45}+ onChange={(e) =>+ onSetToneAngle?.(activeLayer.id, parseInt(e.target.value, 10))+ }+ className="w-full"+ /></div>- <input- type="range"- min="20"- max="85"- value={activeLayer.toneFrequency ?? 60}- onChange={(e) =>- onSetToneFrequency?.(activeLayer.id, parseInt(e.target.value, 10))- }- className="w-full"- />- </div>- <div className="space-y-1">- <div className="flex justify-between text-[10px]">- <span className="text-[#8a8a8a]">Angle</span>- <span className="font-mono text-[#e5e5e5]">- {activeLayer.toneAngle ?? 45}°- </span>- </div>- <input- type="range"- min="0"- max="90"- value={activeLayer.toneAngle ?? 45}+ <select+ value={activeLayer.toneDotShape ?? 'circle'}onChange={(e) =>- onSetToneAngle?.(activeLayer.id, parseInt(e.target.value, 10))+ onSetToneDotShape?.(+ activeLayer.id,+ e.target.value as HalftoneDotShape+ )}- className="w-full"- />+ className="w-full h-6 px-1.5 text-[10px]"+ >+ <option value="circle">Circle Dot</option>+ <option value="euclidean">Euclidean Dot</option>+ <option value="line">Line (Hatching)</option>+ <option value="diamond">Diamond</option>+ </select></div>-- <select- value={activeLayer.toneDotShape ?? 'circle'}- onChange={(e) =>- onSetToneDotShape?.(- activeLayer.id,- e.target.value as 'circle' | 'euclidean'- )- }- className="w-full h-6 px-1.5 text-[10px]"- >- <option value="circle">Circle Dot</option>- <option value="euclidean">Euclidean Dot</option>- </select>- </div>- )}+ );+ })()}<label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer"><span>Layer Tint</span>@@ -1595,6 +1647,22 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({</button>)}+ {onCreateToneLayer && (+ <>+ <button+ type="button"+ onClick={() => {+ onCreateToneLayer();+ setContextMenu(null);+ }}+ className="w-full text-left px-2.5 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer"+ >+ New Screentone Layer...+ </button>+ <div className="my-0.5 h-px bg-[#2c2c2c]" />+ </>+ )}+{onOpenAdjustmentModal && (<>{(['curves', 'levels', 'gradient-map', 'color-balance'] as const).map((adjType) => (@@ -1658,6 +1726,46 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({</button>)}+ {isFolderLikeLayer(targetLayer) && (onMergeFolder || onTransformLayer) && (+ <>+ {onMergeFolder && (+ <button+ type="button"+ disabled={targetLayer.locked}+ onClick={() => {+ onMergeFolder(targetLayer.id);+ setContextMenu(null);+ }}+ className={`w-full text-left px-2.5 py-1 rounded ${+ targetLayer.locked+ ? 'text-[#8a8a8a]/40 cursor-not-allowed'+ : 'hover:bg-[#2c2c2c] cursor-pointer'+ }`}+ >+ Merge Folder+ </button>+ )}+ {onTransformLayer && (+ <button+ type="button"+ disabled={targetLayer.locked}+ onClick={() => {+ onTransformLayer();+ setContextMenu(null);+ }}+ className={`w-full text-left px-2.5 py-1 rounded ${+ targetLayer.locked+ ? 'text-[#8a8a8a]/40 cursor-not-allowed'+ : 'hover:bg-[#2c2c2c] cursor-pointer'+ }`}+ >+ Transform Folder (Ctrl+T)+ </button>+ )}+ <div className="my-0.5 h-px bg-[#2c2c2c]" />+ </>+ )}+{onGroupSelectedLayers && (<buttontype="button"diff --git a/src/components/SimpleToneModal.tsx b/src/components/SimpleToneModal.tsxindex 0b5c76a..fbad9cf 100644--- a/src/components/SimpleToneModal.tsx+++ b/src/components/SimpleToneModal.tsx@@ -34,14 +34,12 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({initialDensity = 40,initialAngle = 45,initialDotShape = 'circle',- initialDensityType = 'specified',dpi = 600,}) => {const [frequency, setFrequency] = useState(initialFrequency);const [density, setDensity] = useState(initialDensity);const [angle, setAngle] = useState(initialAngle);const [dotShape, setDotShape] = useState<HalftoneDotShape>(initialDotShape);- const [densityType, setDensityType] = useState<'specified' | 'image'>(initialDensityType);const previewCanvasRef = useRef<HTMLCanvasElement>(null);@@ -52,9 +50,8 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({setDensity(initialDensity);setAngle(initialAngle);setDotShape(initialDotShape);- setDensityType(initialDensityType);}- }, [isOpen, initialFrequency, initialDensity, initialAngle, initialDotShape, initialDensityType]);+ }, [isOpen, initialFrequency, initialDensity, initialAngle, initialDotShape]);// Live Swatch Preview rendereruseEffect(() => {@@ -74,25 +71,19 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({const sCtx = src.getContext('2d');if (!sCtx) return;- if (densityType === 'specified') {- sCtx.fillStyle = '#000000';- sCtx.fillRect(0, 0, w, h);- } else {- const g = Math.round(255 * (1 - density / 100));- sCtx.fillStyle = `rgb(${g},${g},${g})`;- sCtx.fillRect(0, 0, w, h);- }+ sCtx.fillStyle = '#000000';+ sCtx.fillRect(0, 0, w, h);applyScreentoneCPU(src, canvas, {frequency,angle,dotShape,dpi,- densityType,+ densityType: 'specified',specifiedDensity: density / 100,- antiAliasing: true,+ antiAliasing: false,});- }, [isOpen, frequency, density, angle, dotShape, densityType, dpi]);+ }, [isOpen, frequency, density, angle, dotShape, dpi]);// Keyboard navigation (Enter = Confirm, Escape = Close)useEffect(() => {@@ -108,13 +99,13 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({density,angle,dotShape,- densityType,+ densityType: 'specified',});}};window.addEventListener('keydown', handleKeyDown);return () => window.removeEventListener('keydown', handleKeyDown);- }, [isOpen, onClose, onConfirm, frequency, density, angle, dotShape, densityType]);+ }, [isOpen, onClose, onConfirm, frequency, density, angle, dotShape]);if (!isOpen) return null;@@ -144,10 +135,10 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({<div className="flex flex-col items-center"><span className="text-[10px] text-[#8a8a8a] mb-1">Preview</span><div className="w-[120px] h-[120px] rounded border border-white/[0.08] bg-white overflow-hidden flex items-center justify-center">- <canvas ref={previewCanvasRef} className="w-full h-full" />+ <canvas ref={previewCanvasRef} className="w-full h-full" style={{ imageRendering: 'pixelated' }} /></div><span className="text-[9px] text-[#8a8a8a] font-mono mt-1">- {frequency}L · {densityType === 'specified' ? `${density}%` : 'Lum'}+ {frequency}L · {density}%</span></div>@@ -164,19 +155,7 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({<option value="circle">Circle (Standard)</option><option value="euclidean">Euclidean (Halftone)</option><option value="line">Line (Hatching)</option>- </select>- </div>-- {/* Density Mode */}- <div>- <label className="text-[10px] text-[#8a8a8a] block mb-1">Density Mode</label>- <select- value={densityType}- onChange={(e) => setDensityType(e.target.value as 'specified' | 'image')}- className="w-full bg-[#161616] border border-white/[0.08] text-[#e5e5e5] text-xs rounded px-2 py-1 cursor-pointer"- >- <option value="specified">Use specified density</option>- <option value="image">Use image brightness</option>+ <option value="diamond">Diamond</option></select></div>@@ -213,51 +192,49 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({</div></div>- {/* Density Slider & Presets (when specified) */}- {densityType === 'specified' && (- <div className="p-2.5 bg-[#161616] rounded border border-white/[0.06]">- <div className="flex items-center justify-between text-xs mb-1.5">- <span className="text-[#cccccc]">Density</span>- <div className="flex items-center space-x-1">- <input- type="number"- min="1"- max="100"- value={density}- onChange={(e) => {- const v = parseInt(e.target.value, 10);- if (!isNaN(v)) setDensity(Math.max(1, Math.min(100, v)));- }}- className="w-12 bg-[#202020] border border-white/[0.08] text-[#e5e5e5] font-mono text-xs rounded px-1.5 py-0.5 text-right"- />- <span className="text-xs text-[#8a8a8a] font-mono">%</span>- </div>- </div>- <input- type="range"- min="1"- max="100"- step="1"- value={density}- onChange={(e) => setDensity(parseInt(e.target.value, 10))}- className="w-full mb-1.5"- />- <div className="flex items-center justify-between text-[9px] text-[#8a8a8a] font-mono">- {DENSITY_PRESETS.map((p) => (- <button- key={p}- type="button"- onClick={() => setDensity(p)}- className={`hover:text-[#e5e5e5] px-1 py-0.5 rounded transition-colors cursor-pointer ${- density === p ? 'bg-[var(--accent-subtle)] text-[var(--accent)] font-semibold' : ''- }`}- >- {p}%- </button>- ))}+ {/* Density Slider & Presets */}+ <div className="p-2.5 bg-[#161616] rounded border border-white/[0.06]">+ <div className="flex items-center justify-between text-xs mb-1.5">+ <span className="text-[#cccccc]">Density</span>+ <div className="flex items-center space-x-1">+ <input+ type="number"+ min="1"+ max="100"+ value={density}+ onChange={(e) => {+ const v = parseInt(e.target.value, 10);+ if (!isNaN(v)) setDensity(Math.max(1, Math.min(100, v)));+ }}+ className="w-12 bg-[#202020] border border-white/[0.08] text-[#e5e5e5] font-mono text-xs rounded px-1.5 py-0.5 text-right"+ />+ <span className="text-xs text-[#8a8a8a] font-mono">%</span></div></div>- )}+ <input+ type="range"+ min="1"+ max="100"+ step="1"+ value={density}+ onChange={(e) => setDensity(parseInt(e.target.value, 10))}+ className="w-full mb-1.5"+ />+ <div className="flex items-center justify-between text-[9px] text-[#8a8a8a] font-mono">+ {DENSITY_PRESETS.map((p) => (+ <button+ key={p}+ type="button"+ onClick={() => setDensity(p)}+ className={`hover:text-[#e5e5e5] px-1 py-0.5 rounded transition-colors cursor-pointer ${+ density === p ? 'bg-[var(--accent-subtle)] text-[var(--accent)] font-semibold' : ''+ }`}+ >+ {p}%+ </button>+ ))}+ </div>+ </div>{/* Frequency (Lines / LPI) */}<div className="p-2.5 bg-[#161616] rounded border border-white/[0.06]">@@ -322,7 +299,7 @@ export const SimpleToneModal: React.FC<SimpleToneModalProps> = ({density,angle,dotShape,- densityType,+ densityType: 'specified',})}className="px-4 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 font-medium transition-opacity cursor-pointer text-xs"diff --git a/src/components/Tool3DPropertyInspector.tsx b/src/components/Tool3DPropertyInspector.tsxnew file mode 100644index 0000000..f9d41c9--- /dev/null+++ b/src/components/Tool3DPropertyInspector.tsx@@ -0,0 +1,898 @@+import React, { useState, useEffect } from 'react';+import {+ Box,+ Upload,+ Magnet,+ RotateCcw,+ Lock,+ Unlock,+ Layers,+ CopyPlus,+ Eye,+ EyeOff,+ Compass,+} from 'lucide-react';+import {+ Camera3DPreset,+ Gizmo3DMode,+ Shading3DMode,+ TOOL_3D_BEHAVIOR_RULES,+ Tool3DMode,+} from '../utils/tool3DRules';+import { PosePresetName } from '../utils/mannequin3D';+import { LightSourceWidget } from './LightSourceWidget';+import {+ scene3DBridge,+ selectHasOpenDocument,+ store3DActions,+ uiStoreActions,+ use3DStore,+ useDocumentStore,+ useUiStore,+} from '../stores';++type Inspector3DTab = 'transform' | 'light' | 'scene' | 'pose';++interface NumericAxisRowProps {+ label: string;+ values: [number, number, number];+ step: number;+ suffix?: string;+ onChangeAxis: (axisIdx: 0 | 1 | 2, value: number) => void;+}++const AXIS_LABELS = ['X', 'Y', 'Z'] as const;+const AXIS_COLORS = ['text-red-400', 'text-emerald-400', 'text-sky-400'] as const;++const NumericAxisRow: React.FC<NumericAxisRowProps> = ({+ label,+ values,+ step,+ suffix = '',+ onChangeAxis,+}) => (+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">+ <span>{label}</span>+ {suffix && <span className="font-mono text-[9px] text-[#666]">{suffix}</span>}+ </div>+ <div className="grid grid-cols-3 gap-1">+ {([0, 1, 2] as const).map((idx) => (+ <label+ key={AXIS_LABELS[idx]}+ className="flex items-center bg-[#161616] border border-white/[0.06] rounded px-1 py-0.5 gap-0.5 focus-within:border-[var(--accent)]"+ >+ <span className={`text-[9px] font-mono font-semibold ${AXIS_COLORS[idx]}`}>+ {AXIS_LABELS[idx]}+ </span>+ <input+ type="number"+ step={step}+ value={Number.isFinite(values[idx]) ? values[idx] : 0}+ onChange={(e) => {+ const parsed = parseFloat(e.target.value);+ if (Number.isFinite(parsed)) {+ onChangeAxis(idx, parsed);+ }+ }}+ className="w-full min-w-0 bg-transparent text-[10px] font-mono text-[#e5e5e5] outline-none text-right"+ />+ </label>+ ))}+ </div>+ </div>+);++export const Tool3DPropertyInspector: React.FC = () => {+ const hasOpenDocument = useDocumentStore(selectHasOpenDocument);+ const is3DLayerOpen = useUiStore((s) => s.is3DLayerOpen);++ const activeMode = use3DStore((s) => s.activeMode);+ const gizmoMode = use3DStore((s) => s.gizmoMode);+ const gizmoSpace = use3DStore((s) => s.gizmoSpace);+ const snapEnabled = use3DStore((s) => s.snapEnabled);+ const isReferenceVisible = use3DStore((s) => s.isReferenceVisible);+ const loadedModelName = use3DStore((s) => s.loadedModelName);+ const isMannequinActive = use3DStore((s) => s.isMannequinActive);+ const activeIKHandle = use3DStore((s) => s.activeIKHandle);+ const showIKHandles = use3DStore((s) => s.showIKHandles);+ const isBaking = use3DStore((s) => s.isBaking);+ const modelTransform = use3DStore((s) => s.modelTransform);+ const lighting = use3DStore((s) => s.lighting);+ const shadingMode = use3DStore((s) => s.shadingMode);+ const materialRoughness = use3DStore((s) => s.materialRoughness);+ const toonOutline = use3DStore((s) => s.toonOutline);+ const opacity = use3DStore((s) => s.opacity);+ const showGrid = use3DStore((s) => s.showGrid);+ const perspective = use3DStore((s) => s.perspective);+ const fov = use3DStore((s) => s.fov);+ const syncCameraPerspective = use3DStore((s) => s.syncCameraPerspective);++ const [activeTab, setActiveTab] = useState<Inspector3DTab>('transform');+ const [showRules, setShowRules] = useState(false);++ // If mannequin becomes inactive while on Pose tab, return cleanly to Edit tab+ useEffect(() => {+ if (!isMannequinActive && activeTab === 'pose') {+ setActiveTab('transform');+ }+ }, [isMannequinActive, activeTab]);++ const hasModel = Boolean(loadedModelName);++ if (!hasOpenDocument) {+ return (+ <div className="p-2.5 space-y-2 overflow-y-auto flex-1">+ <div className="text-[11px] font-medium text-[#e5e5e5]">3D Studio Tool</div>+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed">+ Open or create a canvas document to use the 3D reference stage.+ </p>+ </div>+ );+ }++ if (!is3DLayerOpen) {+ return (+ <div className="p-2.5 space-y-2.5 overflow-y-auto flex-1">+ <div className="text-[11px] font-medium text-[#e5e5e5]">3D Studio Tool</div>+ <p className="text-[10px] text-[#8a8a8a] leading-relaxed">+ Open the 3D reference stage to position, light, and extract lineart from imported .glb / .gltf / .obj models directly on the canvas.+ </p>+ <button+ type="button"+ onClick={() => uiStoreActions.set3DLayerOpen(true)}+ className="w-full py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] text-[11px] font-medium hover:opacity-90 cursor-pointer"+ >+ Open 3D Stage+ </button>+ </div>+ );+ }++ const updatePosAxis = (idx: 0 | 1 | 2, val: number) => {+ const nextPos: [number, number, number] = [...modelTransform.position];+ nextPos[idx] = val;+ scene3DBridge.applyNumericTransform?.({ ...modelTransform, position: nextPos });+ };++ const updateRotAxis = (idx: 0 | 1 | 2, val: number) => {+ const nextRot: [number, number, number] = [...modelTransform.rotation];+ nextRot[idx] = val;+ scene3DBridge.applyNumericTransform?.({ ...modelTransform, rotation: nextRot });+ };++ const updateScaleAxis = (idx: 0 | 1 | 2, pctVal: number) => {+ const mult = Math.max(0.05, Math.min(10, pctVal / 100));+ const nextScale: [number, number, number] = modelTransform.uniformScale+ ? [mult, mult, mult]+ : ([+ idx === 0 ? mult : modelTransform.scale[0],+ idx === 1 ? mult : modelTransform.scale[1],+ idx === 2 ? mult : modelTransform.scale[2],+ ] as [number, number, number]);+ scene3DBridge.applyNumericTransform?.({ ...modelTransform, scale: nextScale });+ };++ const uniformScalePct = Math.round(modelTransform.scale[0] * 100);+ const tabs: Array<[Inspector3DTab, string]> = [+ ['transform', 'Edit'],+ ['light', 'Light'],+ ['scene', 'View'],+ ...(isMannequinActive ? ([['pose', 'Pose']] as Array<[Inspector3DTab, string]>) : []),+ ];++ return (+ <div className="flex flex-col flex-1 min-h-0 overflow-hidden text-[#e5e5e5]">+ {/* Header + Quick Model Source Actions */}+ <div className="px-2 pt-2 pb-1.5 border-b border-white/[0.06] space-y-1.5 shrink-0">+ <div className="flex items-center justify-between gap-1">+ <div className="flex items-center gap-1 min-w-0">+ <Box className="w-3.5 h-3.5 text-[var(--accent)] shrink-0" />+ <span className="text-[11px] font-medium truncate">+ {loadedModelName || '3D Studio'}+ </span>+ </div>+ <button+ type="button"+ onClick={() => store3DActions.toggleReferenceVisible()}+ title={isReferenceVisible ? 'Hide 3D Reference' : 'Show 3D Reference'}+ className="p-1 rounded text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer shrink-0"+ >+ {isReferenceVisible ? <Eye className="w-3 h-3" /> : <EyeOff className="w-3 h-3" />}+ </button>+ </div>++ <button+ type="button"+ onClick={() => scene3DBridge.triggerFilePicker?.()}+ className="w-full flex items-center justify-center gap-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] cursor-pointer"+ >+ <Upload className="w-3 h-3 text-[var(--accent)]" />+ <span>Import 3D Model (.glb / .obj)</span>+ </button>++ {/* Inspector Section Tabs */}+ <div+ className={`grid gap-0.5 bg-[#161616] p-0.5 rounded ${+ tabs.length === 4 ? 'grid-cols-4' : 'grid-cols-3'+ }`}+ >+ {tabs.map(([tabId, label]) => (+ <button+ key={tabId}+ type="button"+ onClick={() => setActiveTab(tabId)}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ activeTab === tabId+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ </div>++ {/* Scrollable Inspector Body */}+ <div className="flex-1 overflow-y-auto p-2 space-y-3">+ {activeTab === 'transform' && (+ <>+ {/* Canvas Drag Sub-Mode */}+ <div className="space-y-1">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ Canvas Tool Mode+ </span>+ <div className="grid grid-cols-2 gap-1">+ {(+ [+ ['smart', 'Smart (Auto)'],+ ['model-rotate', 'Free Rotate'],+ ['model-rotate-yaw', 'Turn Y-Axis'],+ ['model-rotate-roll', 'Screen Roll'],+ ['model-move', 'Move Plane'],+ ['model-plane-move', 'Slide Floor'],+ ['model-scale', 'Scale Drag'],+ ['camera-orbit', 'Cam Orbit'],+ ] as Array<[Tool3DMode, string]>+ ).map(([mode, label]) => (+ <button+ key={mode}+ type="button"+ onClick={() => store3DActions.setActiveMode(mode)}+ className={`py-1 px-1.5 rounded text-[10px] text-left truncate transition-colors cursor-pointer ${+ activeMode === mode+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {label}+ </button>+ ))}+ </div>+ </div>++ {/* On-Canvas 3D Manipulator Gizmo */}+ <div className="space-y-1.5 pt-1 border-t border-white/[0.06]">+ <div className="flex items-center justify-between">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ On-Canvas Gizmo+ </span>+ <button+ type="button"+ onClick={() =>+ store3DActions.setGizmoSpace(gizmoSpace === 'local' ? 'world' : 'local')+ }+ title="Toggle Local vs World Gizmo Axes"+ className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc] cursor-pointer"+ >+ {gizmoSpace === 'local' ? 'Local' : 'World'}+ </button>+ </div>+ <div className="grid grid-cols-4 gap-0.5 bg-[#161616] p-0.5 rounded">+ {(+ [+ ['rotate', 'Rot'],+ ['translate', 'Pos'],+ ['scale', 'Scl'],+ ['none', 'Off'],+ ] as Array<[Gizmo3DMode, string]>+ ).map(([gm, lbl]) => (+ <button+ key={gm}+ type="button"+ onClick={() => store3DActions.setGizmoMode(gm)}+ className={`py-1 rounded text-[10px] cursor-pointer ${+ gizmoMode === gm+ ? 'bg-[#2c2c2c] text-[var(--accent)] font-medium'+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ <label className="flex items-center justify-between text-[10px] text-[#8a8a8a] cursor-pointer">+ <span>Snap (15° / 10% · Shift)</span>+ <input+ type="checkbox"+ checked={snapEnabled}+ onChange={(e) => store3DActions.setSnapEnabled(e.target.checked)}+ />+ </label>+ </div>++ {/* Live Numeric Position / Rotation / Scale */}+ <div className="space-y-2.5 pt-1 border-t border-white/[0.06]">+ <NumericAxisRow+ label="Position"+ values={modelTransform.position}+ step={0.1}+ suffix="units"+ onChangeAxis={updatePosAxis}+ />++ <NumericAxisRow+ label="Rotation"+ values={modelTransform.rotation}+ step={5}+ suffix="deg"+ onChangeAxis={updateRotAxis}+ />++ {/* Scale with Uniform Lock */}+ <div className="space-y-1">+ <div className="flex items-center justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Scale</span>+ <div className="flex items-center gap-1">+ <span className="font-mono text-[#e5e5e5]">{uniformScalePct}%</span>+ <button+ type="button"+ onClick={() =>+ store3DActions.setModelTransform({+ uniformScale: !modelTransform.uniformScale,+ })+ }+ title={+ modelTransform.uniformScale+ ? 'Uniform scale locked (click to unlock X/Y/Z)'+ : 'Non-uniform X/Y/Z scale (click to lock)'+ }+ className="p-0.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc] cursor-pointer"+ >+ {modelTransform.uniformScale ? (+ <Lock className="w-2.5 h-2.5 text-[var(--accent)]" />+ ) : (+ <Unlock className="w-2.5 h-2.5 text-[#8a8a8a]" />+ )}+ </button>+ </div>+ </div>+ {modelTransform.uniformScale ? (+ <input+ type="range"+ min={15}+ max={300}+ step={5}+ value={Math.max(15, Math.min(300, uniformScalePct))}+ onChange={(e) => updateScaleAxis(0, parseFloat(e.target.value))}+ className="w-full"+ />+ ) : (+ <NumericAxisRow+ label=""+ values={[+ Math.round(modelTransform.scale[0] * 100),+ Math.round(modelTransform.scale[1] * 100),+ Math.round(modelTransform.scale[2] * 100),+ ]}+ step={5}+ suffix="%"+ onChangeAxis={updateScaleAxis}+ />+ )}+ </div>+ </div>++ {/* Quick Turn & Utility Buttons */}+ <div className="space-y-1.5 pt-1 border-t border-white/[0.06]">+ <div className="grid grid-cols-3 gap-1">+ {([-90, 90, 180] as const).map((deg) => (+ <button+ key={deg}+ type="button"+ disabled={!hasModel}+ onClick={() => scene3DBridge.rotateModelYaw?.(deg)}+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] font-mono text-[#e5e5e5] disabled:opacity-40 cursor-pointer"+ >+ {deg > 0 ? `+${deg}°` : `${deg}°`}+ </button>+ ))}+ </div>+ <div className="grid grid-cols-2 gap-1">+ <button+ type="button"+ disabled={!hasModel}+ onClick={() => scene3DBridge.snapToGround?.()}+ className="flex items-center justify-center gap-1 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#e5e5e5] disabled:opacity-40 cursor-pointer"+ >+ <Magnet className="w-3 h-3 text-[var(--accent)]" />+ <span>Snap Floor</span>+ </button>+ <button+ type="button"+ disabled={!hasModel}+ onClick={() => scene3DBridge.resetModelTransform?.()}+ className="flex items-center justify-center gap-1 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] disabled:opacity-40 cursor-pointer"+ >+ <RotateCcw className="w-3 h-3" />+ <span>Reset</span>+ </button>+ </div>+ </div>+ </>+ )}++ {activeTab === 'light' && (+ <>+ {/* Key Light Toggle + Interactive 3D Sphere */}+ <div className="space-y-1.5">+ <label className="flex items-center justify-between text-[11px] text-[#cccccc] cursor-pointer">+ <span>Key Light Enabled</span>+ <input+ type="checkbox"+ checked={lighting.keyLight.enabled}+ onChange={(e) => store3DActions.updateKeyLight({ enabled: e.target.checked })}+ />+ </label>+ <LightSourceWidget+ embedded+ compact+ settings={{+ azimuth: lighting.keyLight.azimuth,+ elevation: lighting.keyLight.elevation,+ intensity: lighting.keyLight.intensity,+ ambientIntensity: lighting.ambientIntensity,+ color: lighting.keyLight.color,+ isBacklit: lighting.keyLight.isBacklit,+ }}+ onChange={(next) => {+ store3DActions.updateKeyLight({+ azimuth: next.azimuth,+ elevation: next.elevation,+ intensity: next.intensity,+ color: next.color,+ isBacklit: next.isBacklit,+ });+ store3DActions.updateLighting({ ambientIntensity: next.ambientIntensity });+ }}+ onReset={() => store3DActions.resetLighting()}+ />+ </div>++ {/* Secondary Light Source (Rim / Fill Light) */}+ <div className="space-y-1.5 pt-2 border-t border-white/[0.06]">+ <div className="flex items-center justify-between">+ <label className="flex items-center gap-1.5 text-[11px] text-[#cccccc] cursor-pointer">+ <input+ type="checkbox"+ checked={lighting.rimLight.enabled}+ onChange={(e) => store3DActions.updateRimLight({ enabled: e.target.checked })}+ />+ <span>Light 2 (Rim / Fill)</span>+ </label>+ <input+ type="color"+ value={lighting.rimLight.color}+ onChange={(e) => store3DActions.updateRimLight({ color: e.target.value })}+ title="Rim Light Color"+ className="w-5 h-4 bg-transparent border-0 cursor-pointer p-0"+ />+ </div>++ {lighting.rimLight.enabled && (+ <div className="space-y-1.5 bg-[#161616] p-2 rounded border border-white/[0.06]">+ <div className="space-y-0.5">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Angle</span>+ <span className="font-mono text-[#e5e5e5]">{lighting.rimLight.azimuth}°</span>+ </div>+ <input+ type="range"+ min={0}+ max={360}+ step={5}+ value={lighting.rimLight.azimuth}+ onChange={(e) =>+ store3DActions.updateRimLight({ azimuth: parseInt(e.target.value, 10) })+ }+ className="w-full"+ />+ </div>+ <div className="space-y-0.5">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Height</span>+ <span className="font-mono text-[#e5e5e5]">{lighting.rimLight.elevation}°</span>+ </div>+ <input+ type="range"+ min={-60}+ max={85}+ step={5}+ value={lighting.rimLight.elevation}+ onChange={(e) =>+ store3DActions.updateRimLight({ elevation: parseInt(e.target.value, 10) })+ }+ className="w-full"+ />+ </div>+ <div className="space-y-0.5">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Intensity</span>+ <span className="font-mono text-[#e5e5e5]">+ {Math.round(lighting.rimLight.intensity * 100)}%+ </span>+ </div>+ <input+ type="range"+ min={0}+ max={2.5}+ step={0.05}+ value={lighting.rimLight.intensity}+ onChange={(e) =>+ store3DActions.updateRimLight({ intensity: parseFloat(e.target.value) })+ }+ className="w-full"+ />+ </div>+ </div>+ )}+ </div>++ {/* Ambient Tint & Ground Shadow */}+ <div className="space-y-1.5 pt-2 border-t border-white/[0.06]">+ <div className="flex items-center justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Ambient Color</span>+ <input+ type="color"+ value={lighting.ambientColor}+ onChange={(e) => store3DActions.updateLighting({ ambientColor: e.target.value })}+ className="w-5 h-4 bg-transparent border-0 cursor-pointer p-0"+ />+ </div>+ <label className="flex items-center justify-between text-[10px] text-[#cccccc] cursor-pointer">+ <span>Cast Ground Shadow</span>+ <input+ type="checkbox"+ checked={lighting.castGroundShadow}+ onChange={(e) =>+ store3DActions.updateLighting({ castGroundShadow: e.target.checked })+ }+ />+ </label>+ {lighting.castGroundShadow && (+ <div className="space-y-0.5">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Shadow Strength</span>+ <span className="font-mono text-[#e5e5e5]">+ {Math.round(lighting.shadowOpacity * 100)}%+ </span>+ </div>+ <input+ type="range"+ min={0.05}+ max={0.85}+ step={0.05}+ value={lighting.shadowOpacity}+ onChange={(e) =>+ store3DActions.updateLighting({ shadowOpacity: parseFloat(e.target.value) })+ }+ className="w-full"+ />+ </div>+ )}+ </div>+ </>+ )}++ {activeTab === 'scene' && (+ <>+ {/* Camera Angle Presets */}+ <div className="space-y-1">+ <div className="flex items-center justify-between">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ Camera Angle+ </span>+ <button+ type="button"+ onClick={() => scene3DBridge.resetCamera?.()}+ className="text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"+ >+ Reset+ </button>+ </div>+ <div className="grid grid-cols-3 gap-1">+ {(+ [+ ['front', 'Front'],+ ['threeQuarter', '3/4'],+ ['side', 'Side'],+ ['back', 'Back'],+ ['top', 'Top'],+ ['lowAngle', 'Low'],+ ] as Array<[Camera3DPreset, string]>+ ).map(([preset, lbl]) => (+ <button+ key={preset}+ type="button"+ onClick={() => scene3DBridge.setCameraPreset?.(preset)}+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] cursor-pointer"+ >+ {lbl}+ </button>+ ))}+ </div>+ </div>++ {/* Shading Style */}+ <div className="space-y-1 pt-1 border-t border-white/[0.06]">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">Shading</span>+ <div className="grid grid-cols-3 gap-1">+ {(+ [+ ['shaded', 'Shaded'],+ ['smooth', 'Smooth'],+ ['toon', 'Cel / Toon'],+ ['wireframe', 'Wire'],+ ['silhouette', 'Silh'],+ ] as Array<[Shading3DMode, string]>+ ).map(([mode, lbl]) => (+ <button+ key={mode}+ type="button"+ onClick={() => store3DActions.setShadingMode(mode)}+ className={`py-1 rounded text-[10px] transition-colors cursor-pointer ${+ shadingMode === mode+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>++ {(shadingMode === 'shaded' || shadingMode === 'smooth') && (+ <div className="space-y-0.5 pt-1">+ <div className="flex justify-between text-[10px]">+ <span className="text-[#8a8a8a]">Roughness</span>+ <span className="font-mono text-[#e5e5e5]">+ {Math.round(materialRoughness * 100)}%+ </span>+ </div>+ <input+ type="range"+ min={0.1}+ max={1}+ step={0.05}+ value={materialRoughness}+ onChange={(e) => store3DActions.setMaterialRoughness(parseFloat(e.target.value))}+ className="w-full"+ />+ </div>+ )}++ <label className="flex items-center justify-between text-[10px] text-[#cccccc] pt-1 cursor-pointer">+ <span>Manga Outline Preview</span>+ <input+ type="checkbox"+ checked={toonOutline}+ onChange={(e) => store3DActions.setToonOutline(e.target.checked)}+ />+ </label>+ </div>++ {/* Perspective & Reference Opacity */}+ <div className="space-y-2 pt-1 border-t border-white/[0.06]">+ <div>+ <div className="flex justify-between text-[10px] mb-0.5">+ <span className="text-[#8a8a8a]">Perspective (FOV)</span>+ <span className="font-mono text-[#e5e5e5]">+ {perspective.toFixed(1)}x · {fov}°+ </span>+ </div>+ <input+ type="range"+ min={0.3}+ max={2.5}+ step={0.05}+ value={perspective}+ onChange={(e) => scene3DBridge.applyPerspectiveDollyZoom?.(parseFloat(e.target.value))}+ className="w-full"+ />+ </div>++ <div>+ <div className="flex justify-between text-[10px] mb-0.5">+ <span className="text-[#8a8a8a]">Stage Opacity</span>+ <span className="font-mono text-[#e5e5e5]">{Math.round(opacity * 100)}%</span>+ </div>+ <input+ type="range"+ min={0.1}+ max={1}+ step={0.05}+ value={opacity}+ onChange={(e) => store3DActions.setOpacity(parseFloat(e.target.value))}+ className="w-full"+ />+ </div>+ </div>++ {/* Guides & Perspective Ruler Sync */}+ <div className="space-y-1.5 pt-1 border-t border-white/[0.06]">+ <label className="flex items-center justify-between text-[10px] text-[#cccccc] cursor-pointer">+ <span>Floor Grid</span>+ <input+ type="checkbox"+ checked={showGrid}+ onChange={(e) => store3DActions.setShowGrid(e.target.checked)}+ />+ </label>+ <label className="flex items-center justify-between text-[10px] text-[#cccccc] cursor-pointer">+ <span>Live Sync Perspective Ruler</span>+ <input+ type="checkbox"+ checked={syncCameraPerspective}+ onChange={(e) => store3DActions.setSyncCameraPerspective(e.target.checked)}+ />+ </label>+ <button+ type="button"+ onClick={() => scene3DBridge.syncPerspectiveRulerNow?.()}+ className="w-full flex items-center justify-center gap-1 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#cccccc] hover:text-[#e5e5e5] cursor-pointer"+ >+ <Compass className="w-3 h-3 text-[var(--accent)]" />+ <span>Sync Ruler to Camera Now</span>+ </button>+ </div>+ </>+ )}++ {activeTab === 'pose' && isMannequinActive && (+ <>+ <div className="space-y-1">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ Pose Presets+ </span>+ <div className="grid grid-cols-2 gap-1">+ {(+ [+ ['standing', 'Standing'],+ ['action', 'Action'],+ ['sitting', 'Seated'],+ ['fists', 'Fists'],+ ['relaxed_palm', 'Relaxed'],+ ] as Array<[PosePresetName, string]>+ ).map(([preset, lbl]) => (+ <button+ key={preset}+ type="button"+ onClick={() => scene3DBridge.applyPosePreset?.(preset)}+ className="py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] border border-white/[0.06] text-[10px] text-[#e5e5e5] text-left cursor-pointer"+ >+ {lbl}+ </button>+ ))}+ </div>+ </div>++ <div className="space-y-1.5 pt-1 border-t border-white/[0.06]">+ <div className="flex items-center justify-between">+ <span className="text-[10px] uppercase tracking-wider text-[#6e6e6e]">+ IK Limb Handles+ </span>+ {activeIKHandle && (+ <button+ type="button"+ onClick={() => scene3DBridge.selectIKTarget?.(null)}+ className="text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"+ >+ Done+ </button>+ )}+ </div>+ <p className="text-[10px] text-[#8a8a8a] leading-snug">+ Click any colored joint sphere on the canvas or pick a limb below to drag it.+ </p>+ <div className="grid grid-cols-3 gap-1">+ {(+ [+ ['head', 'Head'],+ ['leftHand', 'L-Hand'],+ ['rightHand', 'R-Hand'],+ ['leftFoot', 'L-Foot'],+ ['rightFoot', 'R-Foot'],+ ] as const+ ).map(([limb, lbl]) => (+ <button+ key={limb}+ type="button"+ onClick={() =>+ scene3DBridge.selectIKTarget?.(activeIKHandle === limb ? null : limb)+ }+ className={`py-1 px-1 rounded text-[10px] transition-colors cursor-pointer ${+ activeIKHandle === limb+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-medium'+ : 'bg-[#161616] border border-white/[0.06] text-[#cccccc] hover:bg-[#2c2c2c]'+ }`}+ >+ {lbl}+ </button>+ ))}+ </div>+ <label className="flex items-center justify-between text-[10px] text-[#cccccc] pt-1 cursor-pointer">+ <span>Show Joint Spheres</span>+ <input+ type="checkbox"+ checked={showIKHandles}+ onChange={(e) => store3DActions.setShowIKHandles(e.target.checked)}+ />+ </label>+ </div>+ </>+ )}++ {/* Collapsible 3D Behavior Rules Reference */}+ <div className="pt-1 border-t border-white/[0.06]">+ <button+ type="button"+ onClick={() => setShowRules((v) => !v)}+ className="w-full flex items-center justify-between text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] py-0.5 cursor-pointer"+ >+ <span>Controls & Rules</span>+ <span>{showRules ? 'Hide' : 'Show'}</span>+ </button>+ {showRules && (+ <div className="mt-1.5 space-y-1 bg-[#161616] rounded p-1.5 border border-white/[0.06]">+ {TOOL_3D_BEHAVIOR_RULES.map((rule) => (+ <div key={rule.gesture} className="text-[9px] leading-tight">+ <span className="font-mono text-[#e5e5e5]">{rule.gesture}: </span>+ <span className="text-[#8a8a8a]">{rule.action}</span>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>++ {/* Footer Bake / Stamp Actions */}+ <div className="p-2 border-t border-white/[0.06] bg-[#1a1a1a] grid grid-cols-2 gap-1 shrink-0">+ <button+ type="button"+ disabled={isBaking || !hasModel}+ onClick={() => {+ void scene3DBridge.bakeTo2D?.(false);+ }}+ title="Bake a 2D raster copy while keeping the 3D stage open"+ className="flex items-center justify-center gap-1 py-1.5 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] disabled:opacity-40 cursor-pointer"+ >+ <CopyPlus className="w-3 h-3" />+ <span>Stamp</span>+ </button>+ <button+ type="button"+ disabled={isBaking || !hasModel}+ onClick={() => {+ void scene3DBridge.bakeTo2D?.(true);+ }}+ title="Rasterize 3D model into a 2D Layer and close stage"+ className="flex items-center justify-center gap-1 py-1.5 rounded bg-[var(--accent)] text-[var(--accent-contrast)] hover:opacity-90 text-[10px] font-medium disabled:opacity-40 cursor-pointer"+ >+ <Layers className="w-3 h-3" />+ <span>{isBaking ? 'Baking...' : 'Bake Layer'}</span>+ </button>+ </div>+ </div>+ );+};diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsxindex fb51911..e2c1adb 100644--- a/src/components/ToolPropertyInspector.tsx+++ b/src/components/ToolPropertyInspector.tsx@@ -21,6 +21,7 @@ import {CspBrush,BrushDynamics,DEFAULT_BRUSH_DYNAMICS,+ DEFAULT_NATURAL_PAINT_SETTINGS,LiquifyMode,CspAngleDynamicsMode,CspBlendTipsMode,@@ -58,6 +59,8 @@ import {useUiStore,uiStoreActions,} from '../stores';+import { Tool3DPropertyInspector } from './Tool3DPropertyInspector';+import { PigmentBlendControl } from './PigmentBlendControl';interface CompactSliderProps {label: string;@@ -306,7 +309,9 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = Reacttaper: newSettings.taper ?? activeCustomBrush.taper,spray: newSettings.spray ?? activeCustomBrush.spray,colorMixing: newSettings.colorMixing ?? activeCustomBrush.colorMixing,+ perceptualMixing: newSettings.perceptualMixing ?? activeCustomBrush.perceptualMixing,mixingMode: newSettings.mixingMode ?? activeCustomBrush.mixingMode,+ naturalPaint: newSettings.naturalPaint ?? activeCustomBrush.naturalPaint,amountOfPaint: newSettings.amountOfPaint ?? activeCustomBrush.amountOfPaint,densityOfPaint: newSettings.densityOfPaint ?? activeCustomBrush.densityOfPaint,colorStretch: newSettings.colorStretch ?? activeCustomBrush.colorStretch,@@ -346,6 +351,10 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React};if (!isBrushOrEraser) {+ if (currentTool === '3d') {+ return <Tool3DPropertyInspector />;+ }+if (currentTool === 'fill') {const method = fillSettings.method ?? 'refer-all';return (@@ -731,6 +740,17 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React<option value="overlay">Overlay</option></select></div>+ <div className="pt-1 border-t border-[#2c2c2c]">+ <PigmentBlendControl+ label="Color Blending"+ enabled={Boolean(gradientSettings.pigmentBlending)}+ onEnabledChange={(enabled) =>+ toolStoreActions.updateGradientSettings({ pigmentBlending: enabled })+ }+ primaryColor={primaryColor}+ secondaryColor={secondaryColor}+ />+ </div><label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer"><span>Dither</span><input@@ -824,19 +844,40 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React/></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) =>+ {(retouchSettings.mode === 'smudge' || retouchSettings.mode === 'blur') && (+ <div className="space-y-2.5 pt-2 border-t border-[#2c2c2c]">+ <PigmentBlendControl+ label="Blending"+ strengthLabel="Pigment Strength"+ enabled={Boolean(retouchSettings.pigmentBlending)}+ onEnabledChange={(enabled) =>+ toolStoreActions.updateRetouchSettings({ pigmentBlending: enabled })+ }+ strength={(retouchSettings.pigmentStrength ?? 100) / 100}+ onStrengthChange={(s) =>toolStoreActions.updateRetouchSettings({- smudgeFingerPainting: e.target.checked,+ pigmentStrength: Math.round(s * 100),})}+ primaryColor={primaryColor}+ secondaryColor={secondaryColor}/>- </label>++ {retouchSettings.mode === 'smudge' && (+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1.5 border-t border-[#2c2c2c]/70">+ <span>Finger Painting</span>+ <input+ type="checkbox"+ checked={retouchSettings.smudgeFingerPainting}+ onChange={(e) =>+ toolStoreActions.updateRetouchSettings({+ smudgeFingerPainting: e.target.checked,+ })+ }+ />+ </label>+ )}+ </div>)}{(retouchSettings.mode === 'dodge' || retouchSettings.mode === 'burn') && (@@ -2410,19 +2451,32 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React)}</div>- {/* 4. Color Mixing & Watercolor Edge */}+ {/* 4. Color Mixing & Blending */}<div className="bg-[#202020]"><buttontype="button"onClick={() => toggleAccordion('mixing')}className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer">- <span>Color Mixing & Edge</span>- {openAccordion === 'mixing' ? (- <ChevronDown className="w-3 h-3" />- ) : (- <ChevronRight className="w-3 h-3" />- )}+ <span>Blending & Mixing</span>+ <div className="flex items-center gap-1">+ {brushSettings.colorMixing && (+ <span+ className={`px-1.5 py-[1px] rounded-full text-[9px] font-medium border ${+ (brushSettings.perceptualMixing ?? true)+ ? 'bg-emerald-500/12 text-emerald-300 border-emerald-400/25'+ : 'bg-white/[0.04] text-[#8a8a8a] border-white/[0.08]'+ }`}+ >+ {(brushSettings.perceptualMixing ?? true) ? 'Pigment' : 'Regular'}+ </span>+ )}+ {openAccordion === 'mixing' ? (+ <ChevronDown className="w-3 h-3" />+ ) : (+ <ChevronRight className="w-3 h-3" />+ )}+ </div></button>{openAccordion === 'mixing' && (@@ -2473,16 +2527,29 @@ export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React</button>))}</div>- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">- <span>Perceptual (OKLab)</span>- <input- type="checkbox"- checked={brushSettings.perceptualMixing ?? true}- onChange={(e) =>- handleUpdateBrushSettings({ perceptualMixing: e.target.checked })- }- />- </label>+ <PigmentBlendControl+ label="Color Blending"+ strengthLabel="Pigment Strength"+ enabled={brushSettings.perceptualMixing ?? true}+ onEnabledChange={(enabled) =>+ handleUpdateBrushSettings({+ perceptualMixing: enabled,+ })+ }+ strength={brushSettings.naturalPaint?.pigmentMixingStrength ?? 1.0}+ onStrengthChange={(s) =>+ handleUpdateBrushSettings({+ perceptualMixing: true,+ naturalPaint: {+ ...DEFAULT_NATURAL_PAINT_SETTINGS,+ ...(brushSettings.naturalPaint || {}),+ pigmentMixingStrength: s,+ },+ })+ }+ primaryColor={primaryColor}+ secondaryColor={secondaryColor}+ /><CompactSliderlabel="Amount of Paint"valueLabel={`${Math.round((brushSettings.amountOfPaint ?? brushSettings.naturalPaint?.paintLoad ?? 0.7) * 100)}%`}diff --git a/src/components/ToolStrip.tsx b/src/components/ToolStrip.tsxindex 4d8c4c2..4e2ae9f 100644--- a/src/components/ToolStrip.tsx+++ b/src/components/ToolStrip.tsx@@ -22,6 +22,7 @@ import {Blend,Droplets,Feather,+ Box,} from 'lucide-react';import { ToolType } from '../types/editor';import { LiquifyIcon } from './LiquifyIcon';@@ -119,6 +120,15 @@ export const ToolStrip: React.FC<ToolStripProps> = React.memo({ id: 'frame', label: 'Frame Border (F)', icon: <Frame className="w-3.5 h-3.5" /> },{ id: 'balloon', label: 'Speech Balloon', icon: <MessageSquare className="w-3.5 h-3.5" /> },{ id: 'vector-edit', label: 'Correct Line', icon: <Spline className="w-3.5 h-3.5" /> },+ {+ id: '3d',+ label: '3D Object & Camera Tool (K)',+ icon: <Box className="w-3.5 h-3.5" />,+ onClick: () => {+ toolStoreActions.selectTool('3d');+ if (isHidden) uiStoreActions.toggleLeftPanelHidden();+ },+ },];return (diff --git a/src/components/brushStudio/BrushStudioTabsSecondary.tsx b/src/components/brushStudio/BrushStudioTabsSecondary.tsxindex 283331c..b7a4e20 100644--- a/src/components/brushStudio/BrushStudioTabsSecondary.tsx+++ b/src/components/brushStudio/BrushStudioTabsSecondary.tsx@@ -15,7 +15,9 @@ import {DEFAULT_NATURAL_PAINT_SETTINGS,} from '../../types/editor';import { cleanDirtyBrush } from '../../utils/colorMixingEngine';+import { useToolStore } from '../../stores';import { LightSourceWidget } from '../LightSourceWidget';+import { PigmentBlendControl } from '../PigmentBlendControl';import { PressureCurveEditor } from '../PressureCurveEditor';import {StudioSegmented,@@ -25,6 +27,8 @@ import {import type { BrushStudioTabProps } from './BrushStudioTabsPrimary';export const NaturalPaintMixingTab: React.FC<BrushStudioTabProps> = ({ bs, onPatch }) => {+ const primaryColor = useToolStore((s) => s.primaryColor);+ const secondaryColor = useToolStore((s) => s.secondaryColor);const np: NaturalPaintSettings = {...DEFAULT_NATURAL_PAINT_SETTINGS,...(bs.naturalPaint || {}),@@ -75,13 +79,21 @@ export const NaturalPaintMixingTab: React.FC<BrushStudioTabProps> = ({ bs, onPat<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 })}+ <PigmentBlendControl+ variant="studio"+ label="Color Blending"+ strengthLabel="Kubelka-Munk Pigment Strength"+ enabled={bs.perceptualMixing !== false}+ onEnabledChange={(enabled) => onPatch({ perceptualMixing: enabled })}+ strength={np.pigmentMixingStrength}+ onStrengthChange={(s) =>+ onPatch({+ perceptualMixing: true,+ naturalPaint: { ...np, pigmentMixingStrength: s },+ })+ }+ primaryColor={primaryColor}+ secondaryColor={secondaryColor}/><StudioSliderlabel="Paint Load (0% = Pure Blender)"diff --git a/src/components/canvasArea/CanvasArtboardOverlays.tsx b/src/components/canvasArea/CanvasArtboardOverlays.tsxindex 7fc5efb..d498032 100644--- a/src/components/canvasArea/CanvasArtboardOverlays.tsx+++ b/src/components/canvasArea/CanvasArtboardOverlays.tsx@@ -44,8 +44,6 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({interactionRef,dimensions,zoom,- pan,- rotation,peers = [],activePings = [],remoteDraftCanvasesRef,@@ -461,13 +459,19 @@ export const CanvasArtboardOverlays: React.FC<CanvasArtboardOverlaysProps> = ({/>)}- {/* Local-Only 3D Viewport Ghost Layer (Strictly Client-Side Isolated State) */}+ {/* Local-Only 3D Viewport Reference Stage (Interactive with 3D Tool, Pass-Through with 2D Tools) */}{is3DLayerOpen && onClose3DLayer && onInsertRasterLayer && (<Local3DContainerdimensions={dimensions}- zoom={zoom}- pan={pan}- rotation={rotation}+ viewportRef={canvasProps.viewportRef}+ navigation={canvasProps.navigation}+ zoom={liveZoom}+ pan={livePan}+ rotation={liveRotation}+ flipX={liveFlipX}+ flipY={liveFlipY}+ activeTool={tool}+ isSpaceDown={canvasProps.isSpaceDown}isOpen={is3DLayerOpen}initialFile={initial3DFile}onClose={onClose3DLayer}diff --git a/src/components/canvasArea/types.ts b/src/components/canvasArea/types.tsindex b9d6054..24b7490 100644--- a/src/components/canvasArea/types.ts+++ b/src/components/canvasArea/types.ts@@ -290,7 +290,7 @@ export function getCursorStyle({if (tool === 'liquify' || tool === 'retouch') {return { cursor: isOverCanvas ? 'none' : 'default' };}- if (tool === 'transform') {+ if (tool === 'transform' || tool === '3d') {return { cursor: 'default' };}if (tool === 'brush' || tool === 'eraser' || tool === 'select-pen' || tool === 'select-eraser') {diff --git a/src/components/canvasArea/useCanvasPointerHandlers.ts b/src/components/canvasArea/useCanvasPointerHandlers.tsindex d36801c..5112415 100644--- a/src/components/canvasArea/useCanvasPointerHandlers.ts+++ b/src/components/canvasArea/useCanvasPointerHandlers.ts@@ -190,7 +190,9 @@ export function useCanvasPointerHandlers({allowDrawingPassThrough &&e.button === 0 &&e.altKey &&- ((tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') || tool === 'pen')+ ((tool === 'retouch' && retouchSettings?.mode === 'clone-stamp') ||+ tool === 'pen' ||+ tool === '3d')) {return false;}diff --git a/src/engine/BristleRibbonEngine.ts b/src/engine/BristleRibbonEngine.tsindex 563d812..2c9ef5d 100644--- a/src/engine/BristleRibbonEngine.ts+++ b/src/engine/BristleRibbonEngine.ts@@ -94,12 +94,23 @@ export function extractBristleStrokeConfig(bs.colorMixing === false? false: bs.naturalPaint?.spatialMixing ?? DEFAULT_NATURAL_PAINT_SETTINGS.spatialMixing;+ const resolvedPigmentStrength =+ bs.perceptualMixing === false+ ? 0+ : Math.max(+ 0,+ Math.min(+ 1,+ bs.naturalPaint?.pigmentMixingStrength ?? DEFAULT_NATURAL_PAINT_SETTINGS.pigmentMixingStrength+ )+ );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,+ pigmentMixingStrength: resolvedPigmentStrength,};return {color: strokeColor,diff --git a/src/engine/BrushEngine.ts b/src/engine/BrushEngine.tsindex 8df2f2c..4773bca 100644--- a/src/engine/BrushEngine.ts+++ b/src/engine/BrushEngine.ts@@ -87,6 +87,7 @@ export interface BrushRenderOptions {taper?: CspTaperSettings;colorMixing?: boolean;perceptualMixing?: boolean;+ pigmentMixingStrength?: number;amountOfPaint?: number;densityOfPaint?: number;colorStretch?: number;@@ -1876,7 +1877,8 @@ function sampleAndMixColor(flow,stepDist,options.perceptualMixing !== false,- pressureAlreadyApplied+ pressureAlreadyApplied,+ options.pigmentMixingStrength ?? 1.0);// Spacing-aware alpha normalization for dense mixing strokes: prevents hard opaque walls@@ -2044,6 +2046,7 @@ export function drawBrushDot(colorStretch: options.colorStretch ?? 0.75,mixingMode: options.mixingMode ?? 'blend',perceptualMixing: options.perceptualMixing !== false,+ pigmentMixingStrength: options.pigmentMixingStrength ?? 1.0,tipImage: activeTip,sampler: options.sampler,grainDensity: grainAmount,@@ -2606,6 +2609,7 @@ export function drawBrushCubicBezierSegment(colorStretch: options.colorStretch ?? 0.75,mixingMode: options.mixingMode ?? 'blend',perceptualMixing: options.perceptualMixing !== false,+ pigmentMixingStrength: options.pigmentMixingStrength ?? 1.0,tipImage: activeTip,sampler: options.sampler,grainDensity: grainAmount,@@ -2866,6 +2870,7 @@ export function buildBrushRenderOptions(taper: bs.taper,colorMixing: bs.colorMixing,perceptualMixing: bs.perceptualMixing,+ pigmentMixingStrength: bs.naturalPaint?.pigmentMixingStrength ?? 1.0,amountOfPaint: bs.amountOfPaint,densityOfPaint: bs.densityOfPaint,colorStretch: bs.colorStretch,diff --git a/src/engine/WebGlBrushEngine.ts b/src/engine/WebGlBrushEngine.tsindex a589369..ea3b6fd 100644--- a/src/engine/WebGlBrushEngine.ts+++ b/src/engine/WebGlBrushEngine.ts@@ -131,6 +131,7 @@ uniform vec2 u_paperTexSize;uniform bool u_colorMixing;uniform bool u_perceptualMixing;+uniform float u_pigmentStrength;uniform bool u_hasCanvasTexture;uniform sampler2D u_canvasTexture;uniform vec2 u_canvasResolution;@@ -187,28 +188,142 @@ float samplePaperTooth(vec2 worldPos) {return clamp(g, 0.0, 1.0);}-vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float w2) {- float w1 = 1.0 - w2;+// 7-band Spectral Kubelka-Munk + OKLab Pigment Mixing (WebGL1-safe unrolled bands)+float kmReflectanceBand(vec3 c, float bR, float bG, float bB, float bC, float bM, float bY) {+ float rr = 0.025 + c.r * 0.97;+ float gg = 0.025 + c.g * 0.97;+ float bb = 0.025 + c.b * 0.97;+ if (rr <= gg && rr <= bb) {+ if (gg <= bb) {+ return rr + (gg - rr) * bC + (bb - gg) * bB;+ }+ return rr + (bb - rr) * bC + (gg - bb) * bG;+ } else if (gg <= rr && gg <= bb) {+ if (rr <= bb) {+ return gg + (rr - gg) * bM + (bb - rr) * bB;+ }+ return gg + (bb - gg) * bM + (rr - bb) * bR;+ } else {+ if (rr <= gg) {+ return bb + (rr - bb) * bY + (gg - rr) * bG;+ }+ return bb + (gg - bb) * bY + (rr - gg) * bR;+ }+}++float kmMixBand(float s1, float s2, float w1, float w2) {+ float a = clamp(s1, 0.02, 0.998);+ float b = clamp(s2, 0.02, 0.998);+ float ks1 = pow(((1.0 - a) * (1.0 - a)) / (2.0 * a), 0.72);+ float ks2 = pow(((1.0 - b) * (1.0 - b)) / (2.0 * b), 0.72);+ float ks = pow(max(0.0, ks1 * w1 + ks2 * w2), 1.3888889);+ return 1.0 + ks - sqrt(ks * ks + 2.0 * ks);+}++vec3 linRgbToOklabGpu(vec3 c) {+ float l = 0.4122214708 * c.r + 0.5363325363 * c.g + 0.0514459929 * c.b;+ float m = 0.2119034982 * c.r + 0.6806995451 * c.g + 0.1073969566 * c.b;+ float s = 0.0883024619 * c.r + 0.2817188376 * c.g + 0.6299787005 * c.b;+ float l_ = pow(max(0.0, l), 0.33333333);+ float m_ = pow(max(0.0, m), 0.33333333);+ float s_ = pow(max(0.0, s), 0.33333333);+ return vec3(+ 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,+ 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_+ );+}++vec3 oklabToLinRgbGpu(vec3 lab) {+ float l_ = lab.x + 0.3963377774 * lab.y + 0.2158037573 * lab.z;+ float m_ = lab.x - 0.1055613458 * lab.y - 0.0638541728 * lab.z;+ float s_ = lab.x - 0.0894841775 * lab.y - 1.2914855480 * lab.z;+ float l = l_ * l_ * l_;+ float m = m_ * m_ * m_;+ float s = s_ * s_ * s_;+ return vec3(+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s+ );+}++vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float t) {+ float invT = 1.0 - t;vec3 l1 = pow(max(c1, vec3(0.0)), vec3(2.2));vec3 l2 = pow(max(c2, vec3(0.0)), vec3(2.2));- vec3 abs1 = vec3(1.0) - sqrt(l1);- vec3 abs2 = vec3(1.0) - sqrt(l2);- vec3 mixAbs = abs1 * w1 + abs2 * w2;- vec3 sub = pow(max(vec3(0.0), vec3(1.0) - mixAbs), vec3(2.0));-- float y1 = max(0.0, min(l1.r, l1.g) - l1.b);- float y2 = max(0.0, min(l2.r, l2.g) - l2.b);- float b1 = max(0.0, l1.b - l1.r);- float b2 = max(0.0, l2.b - l2.r);- float ybCross = (y1 * b2 + y2 * b1) * 4.0 * w1 * w2;- if (ybCross > 0.001) {- sub.g = min(1.0, sub.g + ybCross * 0.55);- sub.r = max(0.0, sub.r * (1.0 - ybCross * 0.45));- sub.b = max(0.0, sub.b * (1.0 - ybCross * 0.45));- }-- return clamp(pow(max(sub, vec3(0.0)), vec3(1.0 / 2.2)), 0.0, 1.0);+ float Y1 = dot(l1, vec3(0.2126, 0.7152, 0.0722));+ float Y2 = dot(l2, vec3(0.2126, 0.7152, 0.0722));+ float conc1 = pow(0.06 + Y1, 0.36);+ float conc2 = pow(0.06 + Y2, 0.36);+ float w1 = (invT * conc1) / max(1e-5, invT * conc1 + t * conc2);+ float w2 = 1.0 - w1;++ vec3 b1 = vec3(0.0);+ vec3 b2 = vec3(0.0);+ vec3 mBase = vec3(0.0);++ // Band 0 (420nm)+ float s1 = kmReflectanceBand(l1, 0.025, 0.020, 0.880, 0.720, 0.780, 0.018);+ float s2 = kmReflectanceBand(l2, 0.025, 0.020, 0.880, 0.720, 0.780, 0.018);+ vec3 wv = vec3(0.140, -0.050, 0.340);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 1 (460nm)+ s1 = kmReflectanceBand(l1, 0.018, 0.040, 0.990, 0.980, 0.500, 0.022);+ s2 = kmReflectanceBand(l2, 0.018, 0.040, 0.990, 0.980, 0.500, 0.022);+ wv = vec3(0.030, 0.045, 0.550);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 2 (500nm)+ s1 = kmReflectanceBand(l1, 0.020, 0.420, 0.780, 0.990, 0.055, 0.280);+ s2 = kmReflectanceBand(l2, 0.020, 0.420, 0.780, 0.990, 0.055, 0.280);+ wv = vec3(-0.145, 0.250, 0.145);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 3 (540nm)+ s1 = kmReflectanceBand(l1, 0.035, 0.980, 0.340, 0.840, 0.025, 0.930);+ s2 = kmReflectanceBand(l2, 0.035, 0.980, 0.340, 0.840, 0.025, 0.930);+ wv = vec3(-0.080, 0.500, -0.028);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 4 (580nm)+ s1 = kmReflectanceBand(l1, 0.360, 0.900, 0.025, 0.140, 0.640, 0.995);+ s2 = kmReflectanceBand(l2, 0.360, 0.900, 0.025, 0.140, 0.640, 0.995);+ wv = vec3(0.365, 0.300, -0.007);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 5 (620nm)+ s1 = kmReflectanceBand(l1, 0.965, 0.420, 0.020, 0.025, 0.975, 0.990);+ s2 = kmReflectanceBand(l2, 0.965, 0.420, 0.020, 0.025, 0.975, 0.990);+ wv = vec3(0.465, -0.018, 0.000);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ // Band 6 (660nm)+ s1 = kmReflectanceBand(l1, 0.990, 0.060, 0.055, 0.025, 0.990, 0.980);+ s2 = kmReflectanceBand(l2, 0.990, 0.060, 0.055, 0.025, 0.990, 0.980);+ wv = vec3(0.225, -0.027, 0.000);+ b1 += s1 * wv; b2 += s2 * wv; mBase += kmMixBand(s1, s2, w1, w2) * wv;++ vec3 res1 = l1 - (b1 - vec3(0.025)) * 1.0309278;+ vec3 res2 = l2 - (b2 - vec3(0.025)) * 1.0309278;+ vec3 mixLin = max(vec3(0.0), (mBase - vec3(0.025)) * 1.0309278 + res1 * invT + res2 * t);++ vec3 lab1 = linRgbToOklabGpu(l1);+ vec3 lab2 = linRgbToOklabGpu(l2);+ vec3 labM = linRgbToOklabGpu(mixLin);++ float tunedL = clamp(labM.x * 0.40 + (lab1.x * invT + lab2.x * t) * 0.60, 0.0, 1.0);+ float c1Ch = length(lab1.yz);+ float c2Ch = length(lab2.yz);+ float mCh = length(labM.yz);+ float linCh = c1Ch * invT + c2Ch * t;+ float boost = (mCh > 0.008 && linCh > mCh) ? min(1.65, (mCh + (linCh - mCh) * 0.50) / mCh) : 1.0;+ vec2 ab = labM.yz * boost;++ vec3 fin = oklabToLinRgbGpu(vec3(tunedL, ab));+ return clamp(pow(max(fin, vec3(0.0)), vec3(1.0 / 2.2)), 0.0, 1.0);}void main() {@@ -332,8 +447,10 @@ void main() {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);+ if (u_perceptualMixing && u_pigmentStrength > 0.005) {+ vec3 pig = mixPigmentsGpu(canvasColor.rgb, rgb, effectiveAmount);+ vec3 lin = mix(canvasColor.rgb, rgb, effectiveAmount);+ rgb = mix(lin, pig, clamp(u_pigmentStrength, 0.0, 1.0));} else {rgb = mix(canvasColor.rgb, rgb, effectiveAmount);}@@ -581,6 +698,7 @@ export class WebGlBrushEngine {private uPaperTexSizeLoc: WebGLUniformLocation | null = null;private uColorMixingLoc: WebGLUniformLocation | null = null;private uPerceptualMixingLoc: WebGLUniformLocation | null = null;+ private uPigmentStrengthLoc: WebGLUniformLocation | null = null;private uHasCanvasTextureLoc: WebGLUniformLocation | null = null;private uCanvasTextureLoc: WebGLUniformLocation | null = null;private uAmountOfPaintLoc: WebGLUniformLocation | null = null;@@ -874,6 +992,7 @@ export class WebGlBrushEngine {this.uPaperTexSizeLoc = gl.getUniformLocation(program, 'u_paperTexSize');this.uColorMixingLoc = gl.getUniformLocation(program, 'u_colorMixing');this.uPerceptualMixingLoc = gl.getUniformLocation(program, 'u_perceptualMixing');+ this.uPigmentStrengthLoc = gl.getUniformLocation(program, 'u_pigmentStrength');this.uHasCanvasTextureLoc = gl.getUniformLocation(program, 'u_hasCanvasTexture');this.uCanvasTextureLoc = gl.getUniformLocation(program, 'u_canvasTexture');this.uAmountOfPaintLoc = gl.getUniformLocation(program, 'u_amountOfPaint');@@ -1809,6 +1928,10 @@ export class WebGlBrushEngine {const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;gl.uniform1i(this.uColorMixingLoc, enableColorMix ? 1 : 0);gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);+ if (this.uPigmentStrengthLoc) {+ const pStr = settings.perceptualMixing === false ? 0.0 : (settings.naturalPaint?.pigmentMixingStrength ?? 1.0);+ gl.uniform1f(this.uPigmentStrengthLoc, Math.max(0, Math.min(1, pStr)));+ }if (enableColorMix && underlyingCanvas) {const canvasTex = this.uploadCanvasTexture(underlyingCanvas, {diff --git a/src/hooks/drawing/types.ts b/src/hooks/drawing/types.tsindex b4985d7..bfa39a0 100644--- a/src/hooks/drawing/types.ts+++ b/src/hooks/drawing/types.ts@@ -85,7 +85,7 @@ export interface UseCanvasDrawingProps {activeLayerLocked?: boolean;activeLayerVisible?: boolean;layers?: LayerItem[];- onUpdateLayerThumbnail: (layerId: string) => void;+ onUpdateLayerThumbnail: (layerId: string, immediate?: boolean) => void;onApplyLayerTreeDelta?: ApplyLayerTreeDeltaFn;isMaskMode?: boolean;onUpdateMaskThumbnail?: (layerId: string) => void;diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.tsindex 19418ed..0698d6d 100644--- a/src/hooks/drawing/useDrawingHistory.ts+++ b/src/hooks/drawing/useDrawingHistory.ts@@ -46,7 +46,7 @@ export interface UseDrawingHistoryParams {activeLayerIdRef: React.MutableRefObject<string>;colorModeRef: React.MutableRefObject<CanvasColorMode>;layersRef: React.MutableRefObject<LayerItem[] | undefined>;- onUpdateLayerThumbnail: (layerId: string) => void;+ onUpdateLayerThumbnail: (layerId: string, immediate?: boolean) => void;onApplyLayerTreeDeltaRef?: React.MutableRefObject<ApplyLayerTreeDeltaFn | undefined>;onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;isDrawingRef: React.MutableRefObject<boolean>;@@ -274,6 +274,36 @@ export function useDrawingHistory({const hasDeltas = Boolean(tileDeltas && tileDeltas.length > 0);+ // Coalesce rapid continuous property slider edits (e.g. opacity, tone frequency) into one undo step+ if (+ !hasDeltas &&+ layerTreeDelta?.coalesceKey &&+ layerTreeDelta.beforeLayers &&+ layerTreeDelta.afterLayers &&+ historyIndexRef.current >= 0 &&+ historyIndexRef.current === historyRef.current.length - 1+ ) {+ const topItem = historyRef.current[historyIndexRef.current];+ if (+ topItem &&+ topItem.layerTreeDelta?.coalesceKey === layerTreeDelta.coalesceKey &&+ topItem.layerTreeDelta.beforeLayers &&+ now - topItem.timestamp <= 800+ ) {+ topItem.label = label;+ topItem.timestamp = now;+ topItem.timeFormatted = formatTime(now);+ topItem.layerTreeDelta = {+ ...topItem.layerTreeDelta,+ afterLayers: layerTreeDelta.afterLayers,+ afterActiveLayerId: layerTreeDelta.afterActiveLayerId,+ };+ persistSessionHistory(docId);+ syncHistoryState();+ return;+ }+ }+const item: HistoryItem = {id: `hist-${now}-${Math.random().toString(36).substring(2, 7)}`,type: actionType,@@ -451,19 +481,37 @@ export function useDrawingHistory({const deltas = await undoCache.resolveDeltas(item);if (item.layerTreeDelta) {+ const applied = onApplyLayerTreeDeltaRef?.current?.(item.layerTreeDelta, 'undo');+ if (applied) {+ layersRef.current = applied.nextLayers;+ if (applied.nextActiveLayerId !== null) {+ activeLayerIdRef.current = applied.nextActiveLayerId;+ }+ }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');+ const liveLayerIds = new Set((layersRef.current ?? []).map((l) => l.id));+ const affectedLayerIds = new Set<string>();+ if (deltas) {+ for (const d of deltas) {+ affectedLayerIds.add(parseTileKey(d.key).layerId);+ }+ }if (applied) {- layersRef.current = applied.nextLayers;- if (applied.nextActiveLayerId !== null) {- activeLayerIdRef.current = applied.nextActiveLayerId;+ for (const added of applied.addedLayers) {+ affectedLayerIds.add(added.id);}}+ for (const lid of affectedLayerIds) {+ if (lid !== targetLayerId && liveLayerIds.has(lid)) {+ onUpdateLayerThumbnail(lid, true);+ }+ }+ grid.notifyChange(true);} else if (item.isMaskEdit && targetLayer?.maskCanvas) {const mCtx = get2DContext(targetLayer.maskCanvas);if (mCtx && item.beforeImageData) {@@ -546,7 +594,7 @@ export function useDrawingHistory({}for (const lid of affectedLayerIds) {if (lid !== targetLayerId) {- onUpdateLayerThumbnail(lid);+ onUpdateLayerThumbnail(lid, true);}}} else {@@ -584,7 +632,12 @@ export function useDrawingHistory({}}- onUpdateLayerThumbnail(targetLayerId);+ if (+ !item.layerTreeDelta ||+ (layersRef.current ?? []).some((l) => l.id === targetLayerId)+ ) {+ onUpdateLayerThumbnail(targetLayerId, true);+ }}}} else {@@ -609,16 +662,25 @@ export function useDrawingHistory({if (multiplayerService.isConnected()) {multiplayerService.sendTileDeltas(deltas, grid, { force: true });}- const affectedLayerIds = new Set<string>();+ }+ const liveLayerIds = new Set((layersRef.current ?? []).map((l) => l.id));+ const affectedLayerIds = new Set<string>();+ if (deltas) {for (const d of deltas) {affectedLayerIds.add(parseTileKey(d.key).layerId);}- for (const lid of affectedLayerIds) {- if (lid !== targetLayerId) {- onUpdateLayerThumbnail(lid);- }+ }+ if (applied) {+ for (const added of applied.addedLayers) {+ affectedLayerIds.add(added.id);}}+ for (const lid of affectedLayerIds) {+ if (lid !== targetLayerId && liveLayerIds.has(lid)) {+ onUpdateLayerThumbnail(lid, true);+ }+ }+ grid.notifyChange(true);} else if (item.isMaskEdit && targetLayer?.maskCanvas) {const mCtx = get2DContext(targetLayer.maskCanvas);if (mCtx && dataToApply) {@@ -701,7 +763,7 @@ export function useDrawingHistory({}for (const lid of affectedLayerIds) {if (lid !== targetLayerId) {- onUpdateLayerThumbnail(lid);+ onUpdateLayerThumbnail(lid, true);}}} else {@@ -739,7 +801,12 @@ export function useDrawingHistory({}}- onUpdateLayerThumbnail(targetLayerId);+ if (+ !item.layerTreeDelta ||+ (layersRef.current ?? []).some((l) => l.id === targetLayerId)+ ) {+ onUpdateLayerThumbnail(targetLayerId, true);+ }}}}diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.tsindex e262242..6b5f379 100644--- a/src/hooks/drawing/useSelectionTools.ts+++ b/src/hooks/drawing/useSelectionTools.ts@@ -6,6 +6,7 @@ import {CanvasSelection,DirtyRect,LayerItem,+ LayerTreeDelta,TileDelta,TransformSession,} from '../../types/editor';@@ -42,8 +43,10 @@ import {createDefaultMeshPoints,computeMeshSubdivisions,getMeshSurfaceBounds,+ resolveTransformTargetLayers,+ getTransformPreviewLayerState,} from '../../utils/transformEngine';-import { get2DContext } from '../../utils/canvasUtils';+import { get2DContext, getCanvasCompositeOperation } from '../../utils/canvasUtils';import { useToolStore, toolStoreActions } from '../../stores';import { PushHistoryStepFn } from './types';@@ -211,7 +214,7 @@ export interface UseSelectionToolsParams {blendMode?: BlendMode,opacity?: number,layerOverrides?: Partial<LayerItem>- ) => { id: string; name: string; tileDeltas: TileDelta[] };+ ) => { id: string; name: string; tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta };}export interface UseSelectionToolsResult {@@ -242,7 +245,7 @@ export interface UseSelectionToolsResult {pt: { x: number; y: number }) => boolean;handleSelectionPointerMove: (pt: { x: number; y: number }) => boolean;- handleSelectionPointerUp: (pt: { x: number; y: number }) => boolean;+ handleSelectionPointerUp: (pt: { x: number; y: number }, e?: React.PointerEvent<HTMLElement>) => boolean;}export function useSelectionTools({@@ -288,6 +291,7 @@ export function useSelectionTools({lastPt: { x: number; y: number };maskCanvas: HTMLCanvasElement;ctx: CanvasRenderingContext2D;+ lastPreviewTs: number;} | null>(null);const selectionDragRef = useRef<{@@ -635,7 +639,7 @@ export function useSelectionTools({);const combinedDeltas = [...srcDeltas, ...created.tileDeltas];- if (combinedDeltas.length > 0) {+ if (combinedDeltas.length > 0 || created.layerTreeDelta) {pushHistoryStep('selection-move','Move Selection to New Layer',@@ -643,7 +647,12 @@ export function useSelectionTools({null,created.id,dirtyRect,- combinedDeltas+ combinedDeltas,+ undefined,+ undefined,+ undefined,+ false,+ created.layerTreeDelta);}@@ -700,7 +709,7 @@ export function useSelectionTools({overrides);- if (created.tileDeltas.length > 0) {+ if (created.tileDeltas.length > 0 || created.layerTreeDelta) {pushHistoryStep('selection-move','Copy Selection to New Layer',@@ -708,7 +717,12 @@ export function useSelectionTools({null,created.id,snapshot.bounds,- created.tileDeltas+ created.tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ created.layerTreeDelta);}@@ -733,9 +747,54 @@ export function useSelectionTools({const handleFillSelectionColor = useCallback(() => {if (!selection) return;+ if (selection.floating) {+ handleCommitFloatingSelection();+ }+ if (!activeLayer || !activeLayerId) {+ showToast('Select a raster layer to fill');+ return;+ }+ if (activeLayer.type === 'frame-folder') {+ showToast('Select a child layer inside the Frame Border Folder to fill');+ return;+ }+ if (activeLayer.type !== 'raster') {+ showToast('Select a raster layer to fill');+ return;+ }+ if (activeLayer.locked) {+ showToast('Active layer is locked');+ return;+ }+ // Check effective visibility (including ancestor folders)+ let effectivelyVisible = activeLayer.visible;+ let pId = activeLayer.parentId;+ let guard = 0;+ while (effectivelyVisible && pId && guard < 32) {+ const parent = layers.find((l) => l.id === pId);+ if (!parent) break;+ if (!parent.visible) effectivelyVisible = false;+ pId = parent.parentId;+ guard++;+ }+ if (!effectivelyVisible) {+ showToast('Active layer is hidden');+ return;+ }++ const { primaryColor, isTransparentColor } = useToolStore.getState();+ if (isTransparentColor) {+ handleClearSelection();+ return;+ }+flushPendingHistoryTasks?.();const grid = getGrid();- const primaryColor = useToolStore.getState().primaryColor;+ if (activeLayer.alphaLocked && !grid.hasLayerTiles(activeLayerId)) {+ showToast('Alpha Lock is enabled on an empty layer');+ return;+ }+const targetFormat = resolveLayerFormat(activeLayerId);const { dirtyRect, tileDeltas } = fillSelectionInTileGrid({@@ -745,7 +804,7 @@ export function useSelectionTools({selection,colorCss: primaryColor,targetFormat,- alphaLocked: Boolean(activeLayer?.alphaLocked),+ alphaLocked: Boolean(activeLayer.alphaLocked),});if (tileDeltas.length > 0) {@@ -762,14 +821,18 @@ export function useSelectionTools({updateLayerThumbnail(activeLayerId, true);}, [selection,+ handleCommitFloatingSelection,+ handleClearSelection,flushPendingHistoryTasks,getGrid,+ layers,activeLayerId,activeLayer,dimensions,resolveLayerFormat,updateLayerThumbnail,pushHistoryStep,+ showToast,]);const handleExpandSelection = useCallback(@@ -893,41 +956,24 @@ export function useSelectionTools({const handleStartTransform = useCallback(() => {if (transformSession?.active) return;- if (activeLayer?.locked || (activeLayer && activeLayer.type !== 'raster')) {- showToast('Select an unlocked raster layer to transform');- return;- }flushPendingHistoryTasks?.();const grid = getGrid();- if (selection) {- let floatCanvas = selection.floating?.canvas;- const targetLayerId = selection.floating?.layerId || activeLayerId;- const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');- const targetFormat = resolveLayerFormat(targetLayerId);-- let floatX = selection.floating?.x ?? selection.bounds.x;- let floatY = selection.floating?.y ?? selection.bounds.y;- let beforeTileSnapshot = selection.floating?.beforeTileSnapshot;-- if (!floatCanvas) {- const lifted = liftSelectionFromTileGrid({- grid,- layerId: targetLayerId,- dimensions,- selection,- isBackground: isBg,- targetFormat,- });- if (!lifted) return;- floatCanvas = lifted.floatingCanvas;- floatX = lifted.bounds.x;- floatY = lifted.bounds.y;- beforeTileSnapshot = lifted.beforeTileSnapshot;- updateLayerThumbnail(targetLayerId, true);+ // If there is already a floating selection canvas lifted from a specific layer, transform it directly+ if (selection?.floating?.canvas) {+ const targetLayerId = selection.floating.layerId || activeLayerId;+ const floatingTarget = layers.find((l) => l.id === targetLayerId);+ if (floatingTarget && (floatingTarget.locked || floatingTarget.type !== 'raster')) {+ showToast('Select an unlocked raster layer or folder to transform');+ return;}+ const floatCanvas = selection.floating.canvas;+ const floatX = selection.floating.x;+ const floatY = selection.floating.y;+ const beforeTileSnapshot = selection.floating.beforeTileSnapshot;+const quad = createDefaultPerspectiveQuad(floatX,floatY,@@ -956,121 +1002,301 @@ export function useSelectionTools({meshPoints: createDefaultMeshPoints(quad, 4, 4),});setSelection(null);- } else {- const isMultiLayer = selectedLayerIds && selectedLayerIds.length > 1;- const multiTargetLayers = isMultiLayer- ? layers.filter((l) => selectedLayerIds.includes(l.id) && l.type === 'raster' && !l.locked)- : [];-- if (isMultiLayer && multiTargetLayers.length > 1) {- let minX = Infinity;- let minY = Infinity;- let maxX = -Infinity;- let maxY = -Infinity;-- for (const lyr of multiTargetLayers) {- const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');- const cb = grid.getLayerContentBounds(lyr.id, dimensions, isLayerBg);- if (cb) {- minX = Math.min(minX, cb.x);- minY = Math.min(minY, cb.y);- maxX = Math.max(maxX, cb.x + cb.width);- maxY = Math.max(maxY, cb.y + cb.height);- }- }+ toolStoreActions.setToolRaw('transform');+ return;+ }- if (!isFinite(minX) || !isFinite(minY) || maxX <= minX || maxY <= minY) {- showToast('Selected layers are empty');- return;- }+ const resolved = resolveTransformTargetLayers(layers, activeLayer, selectedLayerIds);+ if (resolved.targetLayers.length === 0) {+ if (resolved.blockedReason === 'locked') {+ showToast(+ resolved.includesFolder+ ? 'Unlock the selected folder to transform'+ : 'Select an unlocked raster layer or folder to transform'+ );+ } else if (resolved.blockedReason === 'empty-folder') {+ showToast('Selected folder has no unlocked raster layers to transform');+ } else {+ showToast('Select an unlocked raster layer or folder to transform');+ }+ return;+ }- const b: DirtyRect = {- x: Math.max(0, minX),- y: Math.max(0, minY),- width: Math.max(1, maxX - minX),- height: Math.max(1, maxY - minY),- };+ const { targetLayers, includesFolder } = resolved;+ const layerMap = new Map(layers.map((l) => [l.id, l]));+ const selectedRootIds = new Set(+ selectedLayerIds && selectedLayerIds.length > 0+ ? selectedLayerIds+ : activeLayer+ ? [activeLayer.id]+ : []+ );+ if (selection) {+ if (targetLayers.length > 1) {const layerBeforeSnapshots = new Map<string, Map<string, TileSnapshotEntry>>();const layerSourceCanvases = new Map<string, HTMLCanvasElement>();+ const orderedLayers = targetLayers.slice().reverse();- const compositeCanvas = document.createElement('canvas');- compositeCanvas.width = b.width;- compositeCanvas.height = b.height;- const compCtx = get2DContext(compositeCanvas);+ let liftBounds: DirtyRect | null = null;+ let compositeCanvas: HTMLCanvasElement | null = null;+ let compCtx: CanvasRenderingContext2D | null = null;- const orderedLayers = multiTargetLayers.slice().reverse();for (const lyr of orderedLayers) {- const sCanvas = grid.createRegionCanvas(lyr.id, b);- if (!sCanvas) continue;- layerSourceCanvases.set(lyr.id, sCanvas);+ if (!grid.hasLayerTiles(lyr.id)) continue;+ const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');+ const targetFormat = resolveLayerFormat(lyr.id);+ const lifted = liftSelectionFromTileGrid({+ grid,+ layerId: lyr.id,+ dimensions,+ selection,+ isBackground: isLayerBg,+ targetFormat,+ });+ if (!lifted) continue;++ if (!liftBounds) {+ liftBounds = lifted.bounds;+ compositeCanvas = document.createElement('canvas');+ compositeCanvas.width = lifted.floatingCanvas.width;+ compositeCanvas.height = lifted.floatingCanvas.height;+ compCtx = get2DContext(compositeCanvas);+ }++ layerSourceCanvases.set(lyr.id, lifted.floatingCanvas);+ layerBeforeSnapshots.set(lyr.id, lifted.beforeTileSnapshot);- if (compCtx) {+ const previewState = getTransformPreviewLayerState(lyr, layerMap, selectedRootIds);+ if (compCtx && previewState.visible && previewState.opacity > 0.001) {compCtx.save();- compCtx.globalAlpha = lyr.opacity;- compCtx.drawImage(sCanvas, 0, 0);+ compCtx.globalAlpha = previewState.opacity;+ compCtx.globalCompositeOperation = getCanvasCompositeOperation(lyr.blendMode);+ compCtx.drawImage(lifted.floatingCanvas, 0, 0);compCtx.restore();}- const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');- const beforeSnap = new Map<string, TileSnapshotEntry>();- grid.clearRectInLayer(lyr.id, b, isLayerBg, beforeSnap, true);- layerBeforeSnapshots.set(lyr.id, beforeSnap);updateLayerThumbnail(lyr.id, true);}- grid.notifyChange(true);- const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);+ const liftedLayerIds = targetLayers+ .filter((l) => layerSourceCanvases.has(l.id))+ .map((l) => l.id);+ if (!liftBounds || !compositeCanvas || liftedLayerIds.length === 0) {+ if (compositeCanvas) releaseTemporaryCanvas(compositeCanvas);+ showToast(includesFolder ? 'Selected folder is empty' : 'Selected layers are empty');+ return;+ }++ grid.notifyChange(true);+ const primaryLayerId = liftedLayerIds[0];+ const quad = createDefaultPerspectiveQuad(+ liftBounds.x,+ liftBounds.y,+ compositeCanvas.width,+ compositeCanvas.height,+ 0+ );setTransformSession({active: true,- layerId: activeLayerId,- layerIds: multiTargetLayers.map((l) => l.id),+ layerId: primaryLayerId,+ layerIds: liftedLayerIds,layerSourceCanvases,layerBeforeSnapshots,sourceCanvas: compositeCanvas,- beforeTileSnapshot: layerBeforeSnapshots.get(activeLayerId),- bounds: { x: b.x, y: b.y, width: b.width, height: b.height },- x: b.x,- y: b.y,- width: b.width,- height: b.height,+ beforeTileSnapshot: layerBeforeSnapshots.get(primaryLayerId),+ bounds: {+ x: liftBounds.x,+ y: liftBounds.y,+ width: compositeCanvas.width,+ height: compositeCanvas.height,+ },+ x: liftBounds.x,+ y: liftBounds.y,+ width: compositeCanvas.width,+ height: compositeCanvas.height,rotation: 0,flipH: false,flipV: false,- isSelection: false,+ isSelection: true,mode: 'affine',perspectiveQuad: quad,meshCols: 4,meshRows: 4,meshPoints: createDefaultMeshPoints(quad, 4, 4),});+ setSelection(null);toolStoreActions.setToolRaw('transform');return;}- const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');- const contentBounds = grid.getLayerContentBounds(activeLayerId, dimensions, isBg);+ const targetLayerId = targetLayers[0].id;+ const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');+ const targetFormat = resolveLayerFormat(targetLayerId);+ const lifted = liftSelectionFromTileGrid({+ grid,+ layerId: targetLayerId,+ dimensions,+ selection,+ isBackground: isBg,+ targetFormat,+ });+ if (!lifted) return;++ const floatCanvas = lifted.floatingCanvas;+ const floatX = lifted.bounds.x;+ const floatY = lifted.bounds.y;+ const beforeTileSnapshot = lifted.beforeTileSnapshot;+ updateLayerThumbnail(targetLayerId, true);++ const quad = createDefaultPerspectiveQuad(+ floatX,+ floatY,+ floatCanvas.width,+ floatCanvas.height,+ 0+ );+ setTransformSession({+ active: true,+ layerId: targetLayerId,+ sourceCanvas: floatCanvas,+ beforeTileSnapshot,+ bounds: { x: floatX, y: floatY, width: floatCanvas.width, height: floatCanvas.height },+ x: floatX,+ y: floatY,+ width: floatCanvas.width,+ height: floatCanvas.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ isSelection: true,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ });+ setSelection(null);+ } else if (targetLayers.length > 1) {+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;++ for (const lyr of targetLayers) {+ const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');+ const cb = grid.getLayerContentBounds(lyr.id, dimensions, isLayerBg);+ if (cb) {+ minX = Math.min(minX, cb.x);+ minY = Math.min(minY, cb.y);+ maxX = Math.max(maxX, cb.x + cb.width);+ maxY = Math.max(maxY, cb.y + cb.height);+ }+ }++ if (!isFinite(minX) || !isFinite(minY) || maxX <= minX || maxY <= minY) {+ showToast(includesFolder ? 'Selected folder is empty' : 'Selected layers are empty');+ return;+ }++ const b: DirtyRect = {+ x: Math.max(0, minX),+ y: Math.max(0, minY),+ width: Math.max(1, maxX - minX),+ height: Math.max(1, maxY - minY),+ };++ const layerBeforeSnapshots = new Map<string, Map<string, TileSnapshotEntry>>();+ const layerSourceCanvases = new Map<string, HTMLCanvasElement>();++ const compositeCanvas = document.createElement('canvas');+ compositeCanvas.width = b.width;+ compositeCanvas.height = b.height;+ const compCtx = get2DContext(compositeCanvas);++ const orderedLayers = targetLayers.slice().reverse();+ for (const lyr of orderedLayers) {+ if (!grid.hasLayerTiles(lyr.id)) continue;+ const sCanvas = grid.createRegionCanvas(lyr.id, b);+ if (!sCanvas) continue;+ layerSourceCanvases.set(lyr.id, sCanvas);++ const previewState = getTransformPreviewLayerState(lyr, layerMap, selectedRootIds);+ if (compCtx && previewState.visible && previewState.opacity > 0.001) {+ compCtx.save();+ compCtx.globalAlpha = previewState.opacity;+ compCtx.globalCompositeOperation = getCanvasCompositeOperation(lyr.blendMode);+ compCtx.drawImage(sCanvas, 0, 0);+ compCtx.restore();+ }++ const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');+ const beforeSnap = new Map<string, TileSnapshotEntry>();+ grid.clearRectInLayer(lyr.id, b, isLayerBg, beforeSnap, true);+ layerBeforeSnapshots.set(lyr.id, beforeSnap);+ updateLayerThumbnail(lyr.id, true);+ }+ grid.notifyChange(true);++ const liftedLayerIds = targetLayers+ .filter((l) => layerSourceCanvases.has(l.id))+ .map((l) => l.id);+ if (liftedLayerIds.length === 0) {+ releaseTemporaryCanvas(compositeCanvas);+ showToast(includesFolder ? 'Selected folder is empty' : 'Selected layers are empty');+ return;+ }++ const primaryLayerId = liftedLayerIds[0];+ const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);+ setTransformSession({+ active: true,+ layerId: primaryLayerId,+ layerIds: liftedLayerIds,+ layerSourceCanvases,+ layerBeforeSnapshots,+ sourceCanvas: compositeCanvas,+ beforeTileSnapshot: layerBeforeSnapshots.get(primaryLayerId),+ bounds: { x: b.x, y: b.y, width: b.width, height: b.height },+ x: b.x,+ y: b.y,+ width: b.width,+ height: b.height,+ rotation: 0,+ flipH: false,+ flipV: false,+ isSelection: false,+ mode: 'affine',+ perspectiveQuad: quad,+ meshCols: 4,+ meshRows: 4,+ meshPoints: createDefaultMeshPoints(quad, 4, 4),+ });+ } else {+ const targetLayerId = targetLayers[0].id;+ const isBg = targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg');+ const contentBounds = grid.getLayerContentBounds(targetLayerId, dimensions, isBg);let b = contentBounds;if (!b) {if (isBg) {b = { x: 0, y: 0, width: dimensions.width, height: dimensions.height };} else {- showToast('Active layer is empty');+ showToast(includesFolder ? 'Selected folder is empty' : 'Active layer is empty');return;}}- const sourceCanvas = grid.createRegionCanvas(activeLayerId, b);+ const sourceCanvas = grid.createRegionCanvas(targetLayerId, b);if (!sourceCanvas) return;const beforeTileSnapshot = new Map<string, TileSnapshotEntry>();- grid.clearRectInLayer(activeLayerId, b, isBg, beforeTileSnapshot, false);- updateLayerThumbnail(activeLayerId, true);+ grid.clearRectInLayer(targetLayerId, b, isBg, beforeTileSnapshot, false);+ updateLayerThumbnail(targetLayerId, true);const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);setTransformSession({active: true,- layerId: activeLayerId,+ layerId: targetLayerId,sourceCanvas,beforeTileSnapshot,bounds: { x: b.x, y: b.y, width: b.width, height: b.height },@@ -1111,9 +1337,12 @@ export function useSelectionTools({if (transformSession.layerIds &&- transformSession.layerIds.length > 1 &&+ transformSession.layerIds.length > 0 &&transformSession.layerSourceCanvases) {+ const allTileDeltas: TileDelta[] = [];+ let combinedDestRect: DirtyRect | null = null;+for (const lId of transformSession.layerIds) {const sCanvas = transformSession.layerSourceCanvases.get(lId);if (!sCanvas) continue;@@ -1132,22 +1361,44 @@ export function useSelectionTools({beforeSnap);+ if (destRect) {+ if (!combinedDestRect) {+ combinedDestRect = { ...destRect };+ } else {+ const minX = Math.min(combinedDestRect.x, destRect.x);+ const minY = Math.min(combinedDestRect.y, destRect.y);+ const maxX = Math.max(+ combinedDestRect.x + combinedDestRect.width,+ destRect.x + destRect.width+ );+ const maxY = Math.max(+ combinedDestRect.y + combinedDestRect.height,+ destRect.y + destRect.height+ );+ combinedDestRect = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };+ }+ }+const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, lId);- if (tileDeltas.length > 0) {- pushHistoryStep(- 'transform',- 'Batch Free Transform',- null,- null,- lId,- destRect ?? undefined,- tileDeltas- );+ for (const d of tileDeltas) {+ allTileDeltas.push(d);}releaseTemporaryCanvas(sCanvas);updateLayerThumbnail(lId, true);}+ if (allTileDeltas.length > 0) {+ pushHistoryStep(+ 'transform',+ `Free Transform (${transformSession.layerIds.length} layers)`,+ null,+ null,+ transformSession.layerIds[0],+ combinedDestRect ?? undefined,+ allTileDeltas+ );+ }+releaseTemporaryCanvas(transformSession.sourceCanvas);grid.notifyChange(true);setTransformSession(null);@@ -1326,12 +1577,19 @@ export function useSelectionTools({mCtx.fill();mCtx.restore();+ try {+ (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore capture errors in synthetic events+ }+isSelectionPenDrawingRef.current = true;selectionPenDrawingRef.current = {isDrawing: true,lastPt: pt,maskCanvas,ctx: mCtx,+ lastPreviewTs: Date.now(),};const mImgData = mCtx.getImageData(0, 0, w, h);@@ -1417,12 +1675,22 @@ export function useSelectionTools({}if (tool === 'select-rect') {+ try {+ (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore capture errors in synthetic events+ }selectRectStartRef.current = pt;setSelection({type: 'rect',bounds: { x: pt.x, y: pt.y, width: 0, height: 0 },});} else {+ try {+ (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore capture errors in synthetic events+ }lassoPointsRef.current = [pt];setSelection({type: 'lasso',@@ -1473,10 +1741,43 @@ export function useSelectionTools({mCtx.restore();selectionPenDrawingRef.current.lastPt = pt;++ // Throttle live marching-ants preview while painting with Selection Pen / Eraser+ const nowTs = Date.now();+ if (nowTs - selectionPenDrawingRef.current.lastPreviewTs >= 60) {+ selectionPenDrawingRef.current.lastPreviewTs = nowTs;+ const w = dimensions.width;+ const h = dimensions.height;+ if (w * h <= 4096 * 4096) {+ const mImgData = mCtx.getImageData(0, 0, w, h);+ const newMask = new Uint8Array(w * h);+ for (let i = 0; i < newMask.length; i++) {+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;+ }+ const b = maskToBounds(newMask, w, h);+ if (b) {+ const svg = maskToSvgPath(newMask, w, h);+ setSelection({+ type: 'mask',+ bounds: b,+ mask: newMask,+ maskWidth: w,+ maskHeight: h,+ svgPath: svg,+ });+ } else {+ setSelection(null);+ }+ }+ }return true;}if (selectionDragRef.current?.isDragging) {+ if (tool !== 'select-rect' && tool !== 'select-lasso') {+ selectionDragRef.current = null;+ return false;+ }const drag = selectionDragRef.current;const dx = pt.x - drag.startX;const dy = pt.y - drag.startY;@@ -1507,6 +1808,10 @@ export function useSelectionTools({}if (selectRectStartRef.current) {+ if (tool !== 'select-rect') {+ selectRectStartRef.current = null;+ return false;+ }const s = selectRectStartRef.current;const x0 = Math.max(0, Math.min(dimensions.width, Math.floor(Math.min(s.x, pt.x))));const y0 = Math.max(0, Math.min(dimensions.height, Math.floor(Math.min(s.y, pt.y))));@@ -1520,6 +1825,10 @@ export function useSelectionTools({}if (lassoPointsRef.current.length > 0) {+ if (tool !== 'select-lasso') {+ lassoPointsRef.current = [];+ return false;+ }const pts = lassoPointsRef.current;const last = pts[pts.length - 1];if (Math.hypot(pt.x - last.x, pt.y - last.y) >= 2) {@@ -1538,13 +1847,22 @@ export function useSelectionTools({}, [dimensions.height, dimensions.width]);const handleSelectionPointerUp = useCallback(- (pt: { x: number; y: number }): boolean => {+ (pt: { x: number; y: number }, e?: React.PointerEvent<HTMLElement>): boolean => {const { tool } = useToolStore.getState();+ const releaseCapture = () => {+ if (!e) return;+ try {+ (e.currentTarget as HTMLElement)?.releasePointerCapture?.(e.pointerId);+ } catch {+ // Ignore release errors+ }+ };if ((tool === 'select-pen' || tool === 'select-eraser') &&selectionPenDrawingRef.current?.isDrawing) {+ releaseCapture();const { ctx: mCtx } = selectionPenDrawingRef.current;selectionPenDrawingRef.current = null;isSelectionPenDrawingRef.current = false;@@ -1578,6 +1896,7 @@ export function useSelectionTools({}if (selectRectStartRef.current) {+ releaseCapture();const s = selectRectStartRef.current;selectRectStartRef.current = null;const x0 = Math.max(0, Math.min(dimensions.width, Math.floor(Math.min(s.x, pt.x))));@@ -1598,6 +1917,7 @@ export function useSelectionTools({}if (lassoPointsRef.current.length > 0) {+ releaseCapture();if (lassoPointsRef.current.length < 3) {setSelection(null);} else {diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.tsindex 0b67256..b2ff24c 100644--- a/src/hooks/drawing/useShapeAndFillTools.ts+++ b/src/hooks/drawing/useShapeAndFillTools.ts@@ -64,6 +64,7 @@ export interface UseShapeAndFillToolsParams {activeLayerId: string;selectedLayerIds?: string[];selection: CanvasSelection | null;+ onCommitFloatingSelection?: () => void;flushPendingHistoryTasks?: () => void;isLayerEffectivelyVisible: (layer: LayerItem) => boolean;getEffectiveOpacity: (layer: LayerItem) => number;@@ -149,6 +150,7 @@ export function useShapeAndFillTools({activeLayerId,selectedLayerIds = [],selection,+ onCommitFloatingSelection,flushPendingHistoryTasks,isLayerEffectivelyVisible,getEffectiveOpacity,@@ -346,16 +348,9 @@ export function useShapeAndFillTools({x: textSession.x,y: textSession.y,};- const savedLayer = upsertTextLayer(textData, textSession.editingLayerId);- pushHistoryStep(- 'text',- textSession.editingLayerId ? 'Edit Text Layer' : 'Create Text Layer',- null,- null,- savedLayer.id- );+ upsertTextLayer(textData, textSession.editingLayerId);setTextSession(null);- }, [textSession, upsertTextLayer, pushHistoryStep]);+ }, [textSession, upsertTextLayer]);const handleCancelText = useCallback(() => {setTextSession(null);@@ -363,17 +358,10 @@ export function useShapeAndFillTools({const handleConfirmBalloon = useCallback(() => {if (!activeBalloon) return;- const savedLayer = upsertBalloonLayer(activeBalloon, editingBalloonLayerId);- pushHistoryStep(- 'balloon',- editingBalloonLayerId ? 'Edit Speech Balloon' : 'Create Speech Balloon',- null,- null,- savedLayer.id- );+ upsertBalloonLayer(activeBalloon, editingBalloonLayerId);setActiveBalloon(null);setEditingBalloonLayerId(null);- }, [activeBalloon, editingBalloonLayerId, upsertBalloonLayer, pushHistoryStep]);+ }, [activeBalloon, editingBalloonLayerId, upsertBalloonLayer]);const handleDeleteBalloon = useCallback(() => {if (editingBalloonLayerId && deleteLayer) {@@ -632,7 +620,36 @@ export function useShapeAndFillTools({if (tool === 'fill') {e.preventDefault();+ if (selection?.floating) {+ onCommitFloatingSelection?.();+ }+ if (!activeLayerId || !activeLayer) {+ showToast?.('Select a raster layer to use the Fill tool');+ return true;+ }+ if (activeLayer.type === 'frame-folder') {+ showToast?.('Select a child layer inside the Frame Border Folder to fill');+ return true;+ }+ if (activeLayer.type !== 'raster') {+ showToast?.('Select a raster layer to use the Fill tool');+ return true;+ }+ if (activeLayer.locked) {+ showToast?.('Active layer is locked');+ return true;+ }+ if (!isLayerEffectivelyVisible(activeLayer)) {+ showToast?.('Active layer is hidden');+ return true;+ }+if (fillSettings.method === 'lasso') {+ try {+ (e.currentTarget as HTMLElement)?.setPointerCapture?.(e.pointerId);+ } catch {+ // Ignore capture errors in synthetic events+ }lassoFillPointsRef.current = [pt];return true;}@@ -642,18 +659,16 @@ export function useShapeAndFillTools({if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;flushPendingHistoryTasks?.();- if (- !activeLayerId ||- activeLayer?.locked ||- (activeLayer && !isLayerEffectivelyVisible(activeLayer))- ) {++ const grid = documentStore.getActiveTileGrid();+ if (activeLayer.alphaLocked && !grid.hasLayerTiles(activeLayerId)) {+ showToast?.('Alpha Lock is enabled on an empty layer');return true;}- const grid = documentStore.getActiveTileGrid();const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');const isMono =- !isBg && (colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome');+ !isBg && (colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome');const targetFormat: TileFormat = isMono ? 'monochrome-1bit' : 'color-32bit';const referMode =fillSettings.method === 'refer-all'@@ -665,7 +680,13 @@ export function useShapeAndFillTools({const selMask = selection? createSelectionMask(selection, dimensions.width, dimensions.height): null;+ if (selMask && selMask[py * dimensions.width + px] === 0) {+ showToast?.('Click inside the active selection to fill');+ return true;+ }+ const isTransparentInk = useToolStore.getState().isTransparentColor;+ const effectiveFillColor = isTransparentInk ? 'rgba(0,0,0,0)' : primaryColor;const targetLayerId = activeLayerId;void executeFloodFillOnTileGridAsync({grid,@@ -674,7 +695,7 @@ export function useShapeAndFillTools({dimensions,startX: px,startY: py,- fillColorHex: primaryColor,+ fillColorHex: effectiveFillColor,tolerance: fillSettings.tolerance,referMode,targetFormat,@@ -683,21 +704,27 @@ export function useShapeAndFillTools({areaScale: fillSettings.areaScale ?? 0,antiAlias: fillSettings.antiAlias ?? true,selectionMask: selMask,+ alphaLocked: Boolean(activeLayer.alphaLocked),},- }).then((fillRes) => {- if (fillRes.modified && fillRes.tileDeltas.length > 0) {- pushHistoryStep(- 'fill',- 'Bucket Fill',- null,- null,- targetLayerId,- fillRes.dirtyRect ?? undefined,- fillRes.tileDeltas- );- updateLayerThumbnail(targetLayerId, true);- }- });+ })+ .then((fillRes) => {+ if (fillRes.modified && fillRes.tileDeltas.length > 0) {+ pushHistoryStep(+ 'fill',+ isTransparentInk ? 'Erase Fill' : 'Bucket Fill',+ null,+ null,+ targetLayerId,+ fillRes.dirtyRect ?? undefined,+ fillRes.tileDeltas+ );+ updateLayerThumbnail(targetLayerId, true);+ }+ })+ .catch((err) => {+ console.warn('Flood fill failed:', err);+ showToast?.('Fill failed');+ });return true;}@@ -775,6 +802,7 @@ export function useShapeAndFillTools({isLayerEffectivelyVisible,flushPendingHistoryTasks,selection,+ onCommitFloatingSelection,dimensions,colorMode,startLiquifyLoop,@@ -1068,31 +1096,50 @@ export function useShapeAndFillTools({fillSettings.method === 'lasso' &&lassoFillPointsRef.current.length >= 3) {+ try {+ (e.currentTarget as HTMLElement)?.releasePointerCapture?.(e.pointerId);+ } catch {+ // Ignore release errors+ }const pts = [...lassoFillPointsRef.current];lassoFillPointsRef.current = [];flushPendingHistoryTasks?.();- if (!activeLayerId || activeLayer?.locked) return true;+ if (+ !activeLayerId ||+ !activeLayer ||+ activeLayer.type !== 'raster' ||+ activeLayer.locked ||+ !isLayerEffectivelyVisible(activeLayer)+ ) {+ return true;+ }const grid = documentStore.getActiveTileGrid();const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');const isMono =- !isBg && (colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome');+ !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 isTransparentInk = useToolStore.getState().isTransparentColor;+ const effectiveFillColor = isTransparentInk ? 'rgba(0,0,0,0)' : primaryColor;const res = executeLassoFillOnTileGrid({grid,targetLayerId: activeLayerId,dimensions,polygon: pts,- fillColorHex: primaryColor,+ fillColorHex: effectiveFillColor,targetFormat,- alphaLocked: Boolean(activeLayer?.alphaLocked),+ alphaLocked: Boolean(activeLayer.alphaLocked),+ selectionMask: selMask,});if (res.modified && res.tileDeltas.length > 0) {pushHistoryStep('fill',- 'Lasso Fill',+ isTransparentInk ? 'Lasso Erase' : 'Lasso Fill',null,null,activeLayerId,diff --git a/src/hooks/layerManager/layerTreeOps.ts b/src/hooks/layerManager/layerTreeOps.tsindex b34d740..7d8c4b2 100644--- a/src/hooks/layerManager/layerTreeOps.ts+++ b/src/hooks/layerManager/layerTreeOps.ts@@ -145,6 +145,97 @@ export function computeBatchDeleteLayers(}// Pure group selected layers helper+export function getFolderDescendantIds(layers: LayerItem[], folderId: string): string[] {+ const descendants: string[] = [];+ const collect = (parentId: string) => {+ for (const l of layers) {+ if (l.parentId === parentId) {+ descendants.push(l.id);+ if (isFolderLikeLayer(l)) {+ collect(l.id);+ }+ }+ }+ };+ collect(folderId);+ return descendants;+}++export interface ComputeMergeFolderResult {+ folder: LayerItem;+ descendantLayers: LayerItem[];+ descendantIds: string[];+ mergedLayer: LayerItem;+ nextLayers: LayerItem[];+}++// Pure folder-to-single-layer merge tree computation+export function computeMergeFolderLayers(+ layers: LayerItem[],+ folderId: string,+ customMergedId?: string+): ComputeMergeFolderResult | null {+ const folderIdx = layers.findIndex((l) => l.id === folderId);+ if (folderIdx < 0) return null;++ const folder = layers[folderIdx];+ if (!folder || !isFolderLikeLayer(folder) || folder.locked) {+ return null;+ }++ const descendantIds = getFolderDescendantIds(layers, folder.id);+ const descendantIdSet = new Set(descendantIds);+ // Preserve stack order (top-to-bottom) for descendants+ const descendantLayers = layers.filter((l) => descendantIdSet.has(l.id));++ const mergedId =+ customMergedId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;++ const mergedLayer: LayerItem = {+ id: mergedId,+ name: folder.name,+ type: 'raster',+ visible: folder.visible,+ opacity: folder.opacity,+ blendMode: folder.blendMode === 'pass-through' ? 'normal' : folder.blendMode,+ locked: false,+ clipped: folder.clipped,+ parentId: folder.parentId,+ thumbnailUrl: '',+ isReference: folder.isReference,+ expressionColor: folder.expressionColor ?? 'color',+ monoThreshold: folder.monoThreshold ?? 128,+ monoExpressBlack: folder.monoExpressBlack ?? true,+ monoExpressWhite: folder.monoExpressWhite ?? true,+ ...(folder.maskCanvas+ ? {+ maskCanvas: folder.maskCanvas,+ maskEnabled: folder.maskEnabled,+ maskLinked: folder.maskLinked,+ maskThumbnailUrl: folder.maskThumbnailUrl,+ maskVersion: folder.maskVersion,+ }+ : {}),+ };++ const nextLayers: LayerItem[] = [];+ for (const l of layers) {+ if (l.id === folder.id) {+ nextLayers.push(mergedLayer);+ } else if (!descendantIdSet.has(l.id)) {+ nextLayers.push(l);+ }+ }++ return {+ folder,+ descendantLayers,+ descendantIds,+ mergedLayer,+ nextLayers,+ };+}+export function computeGroupLayers(layers: LayerItem[],selectedIds: string[],@@ -338,9 +429,27 @@ export function cloneComicFrames(frames: ComicFrame[]): ComicFrame[] {}));}-export function cloneLayerItemForHistory(layer: LayerItem): LayerItem {+export function cloneMaskCanvasForHistory(+ canvas: HTMLCanvasElement | undefined+): HTMLCanvasElement | undefined {+ if (!canvas || typeof document === 'undefined') return canvas;+ const copy = document.createElement('canvas');+ copy.width = canvas.width;+ copy.height = canvas.height;+ const ctx = copy.getContext('2d');+ if (ctx) {+ ctx.drawImage(canvas, 0, 0);+ }+ return copy;+}++export function cloneLayerItemForHistory(+ layer: LayerItem,+ cloneMask: boolean = false+): LayerItem {return {...layer,+ maskCanvas: cloneMask && layer.maskCanvas ? cloneMaskCanvasForHistory(layer.maskCanvas) : layer.maskCanvas,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,@@ -351,6 +460,23 @@ export function cloneLayerItemForHistory(layer: LayerItem): LayerItem {};}+export function createLayerTreeSnapshotDelta(+ beforeLayers: LayerItem[],+ afterLayers: LayerItem[],+ beforeActiveLayerId: string,+ afterActiveLayerId: string,+ options?: { cloneMasks?: boolean; coalesceKey?: string }+): LayerTreeDelta {+ const cloneMasks = Boolean(options?.cloneMasks);+ return {+ beforeLayers: beforeLayers.map((l) => cloneLayerItemForHistory(l, cloneMasks)),+ afterLayers: afterLayers.map((l) => cloneLayerItemForHistory(l, cloneMasks)),+ beforeActiveLayerId,+ afterActiveLayerId,+ coalesceKey: options?.coalesceKey,+ };+}+export interface ApplyLayerTreeDeltaResult {nextLayers: LayerItem[];nextActiveLayerId: string | null;@@ -358,13 +484,45 @@ export interface ApplyLayerTreeDeltaResult {addedLayers: LayerItem[];}-// Pure undo/redo application of a targeted LayerTreeDelta (e.g. create/divide frame border folder)+// Pure undo/redo application of a LayerTreeDelta (both targeted frame deltas and full tree snapshots)export function applyLayerTreeDelta(layers: LayerItem[],currentActiveLayerId: string,delta: LayerTreeDelta,direction: 'undo' | 'redo'): ApplyLayerTreeDeltaResult {+ // Full snapshot path: handles arbitrary add, delete, duplicate, group, merge, reorder, property & mask changes+ if (delta.beforeLayers && delta.afterLayers) {+ const targetSnapshot = direction === 'undo' ? delta.beforeLayers : delta.afterLayers;+ const prevIdSet = new Set(layers.map((l) => l.id));+ const targetIdSet = new Set(targetSnapshot.map((l) => l.id));++ const removedLayerIds: string[] = [];+ for (const l of layers) {+ if (!targetIdSet.has(l.id)) {+ removedLayerIds.push(l.id);+ }+ }++ const nextLayers = targetSnapshot.map((l) => cloneLayerItemForHistory(l));+ const addedLayers = nextLayers.filter((l) => !prevIdSet.has(l.id));++ const desiredActiveId =+ direction === 'undo' ? delta.beforeActiveLayerId : delta.afterActiveLayerId;+ let nextActiveLayerId: string | null = null;+ if (desiredActiveId && nextLayers.some((l) => l.id === desiredActiveId)) {+ nextActiveLayerId = desiredActiveId;+ } 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 };+ }+let nextLayers = [...layers];const removedLayerIds: string[] = [];const addedLayers: LayerItem[] = [];@@ -428,7 +586,7 @@ export function applyLayerTreeDelta(const existingIds = new Set(nextLayers.map((l) => l.id));const toAdd = delta.addedLayers.filter((al) => !existingIds.has(al.id))- .map(cloneLayerItemForHistory);+ .map((al) => cloneLayerItemForHistory(al));if (toAdd.length > 0) {let insertIdx: number;diff --git a/src/hooks/layerManager/types.ts b/src/hooks/layerManager/types.tsindex 5497866..0906ad5 100644--- a/src/hooks/layerManager/types.ts+++ b/src/hooks/layerManager/types.ts@@ -1,14 +1,19 @@import { Dispatch, MutableRefObject, SetStateAction } from 'react';import {CanvasDimensions,+ HistoryActionType,LayerItem,+ LayerTreeDelta,+ TileDelta,} from '../../types/editor';import { SparseTileGrid } from '../../utils/tileEngine';+import type { PushHistoryStepFn } from '../drawing/types';export interface UseLayerManagerProps {dimensions: CanvasDimensions;activeSessionId?: string | null;tileGrid?: SparseTileGrid;+ pushHistoryStepRef?: MutableRefObject<PushHistoryStepFn | null | undefined>;}export interface LayerManagerContext {@@ -27,6 +32,14 @@ export interface LayerManagerContext {selectedLayerIds: string[];setSelectedLayerIds: (ids: string[] | ((prev: string[]) => string[])) => void;selectedLayerIdsRef: MutableRefObject<string[]>;+ suppressHistoryDepthRef: MutableRefObject<number>;+ recordLayerHistory: (+ label: string,+ targetLayerId: string,+ layerTreeDelta?: LayerTreeDelta,+ tileDeltas?: TileDelta[],+ actionType?: HistoryActionType+ ) => void;}export interface LayerCanvasRegistryApi {diff --git a/src/hooks/layerManager/useLayerClipboard.ts b/src/hooks/layerManager/useLayerClipboard.tsindex b8bb9a6..79b53b5 100644--- a/src/hooks/layerManager/useLayerClipboard.ts+++ b/src/hooks/layerManager/useLayerClipboard.ts@@ -3,6 +3,7 @@ import {BlendMode,CanvasSelection,LayerItem,+ LayerTreeDelta,isFolderLikeLayer,} from '../../types/editor';import { createCanvasThumbnail } from '../../utils/canvasUtils';@@ -22,6 +23,7 @@ import {unpack1BitToRGBA,unpack8BitToRGBA,} from '../../utils/tileEngine';+import { createLayerTreeSnapshotDelta } from './layerTreeOps';import { LayerManagerContext } from './types';export function useLayerClipboard(ctx: LayerManagerContext) {@@ -36,6 +38,7 @@ export function useLayerClipboard(ctx: LayerManagerContext) {activeLayerId,setActiveLayerId,activeLayerIdRef,+ recordLayerHistory,} = ctx;// Internal Layer Clipboard (tile-backed; zero full-doc HTMLCanvasElement allocation)@@ -61,82 +64,82 @@ export function useLayerClipboard(ctx: LayerManagerContext) {thumb: string,layerOverrides?: Partial<LayerItem>,insertTarget?: LayerInsertTarget- ) => {- setLayers((prev) => {- const getSubtreeEndIndex = (list: LayerItem[], folderIndex: number): number => {- const folderId = list[folderIndex].id;- const subtreeIds = new Set<string>([folderId]);- let endIdx = folderIndex + 1;- while (endIdx < list.length) {- const item = list[endIdx];- if (item.parentId && subtreeIds.has(item.parentId)) {- subtreeIds.add(item.id);- endIdx++;- } else {- break;- }- }- return endIdx;- };-- let insertIdx = 0;- let resolvedParentId: string | null = null;- let expandFolderId: string | null = null;-- const targetIdx = insertTarget?.targetLayerId- ? prev.findIndex((l) => l.id === insertTarget.targetLayerId)- : -1;-- if (targetIdx >= 0) {- const targetItem = prev[targetIdx];- const pos = insertTarget?.position || (isFolderLikeLayer(targetItem) ? 'inside' : 'above');- if (pos === 'inside' && isFolderLikeLayer(targetItem)) {- resolvedParentId = targetItem.id;- insertIdx = targetIdx + 1;- if (targetItem.collapsed) expandFolderId = targetItem.id;- } else if (pos === 'below') {- resolvedParentId = targetItem.parentId;- insertIdx = isFolderLikeLayer(targetItem)- ? getSubtreeEndIndex(prev, targetIdx)- : targetIdx + 1;+ ): LayerItem[] => {+ const prev = layersRef.current;+ const getSubtreeEndIndex = (list: LayerItem[], folderIndex: number): number => {+ const folderId = list[folderIndex].id;+ const subtreeIds = new Set<string>([folderId]);+ let endIdx = folderIndex + 1;+ while (endIdx < list.length) {+ const item = list[endIdx];+ if (item.parentId && subtreeIds.has(item.parentId)) {+ subtreeIds.add(item.id);+ endIdx++;} else {- resolvedParentId = targetItem.parentId;- insertIdx = targetIdx;+ break;}+ }+ return endIdx;+ };++ let insertIdx = 0;+ let resolvedParentId: string | null = null;+ let expandFolderId: string | null = null;++ const targetIdx = insertTarget?.targetLayerId+ ? prev.findIndex((l) => l.id === insertTarget.targetLayerId)+ : -1;++ if (targetIdx >= 0) {+ const targetItem = prev[targetIdx];+ const pos = insertTarget?.position || (isFolderLikeLayer(targetItem) ? 'inside' : 'above');+ if (pos === 'inside' && isFolderLikeLayer(targetItem)) {+ resolvedParentId = targetItem.id;+ insertIdx = targetIdx + 1;+ if (targetItem.collapsed) expandFolderId = targetItem.id;+ } else if (pos === 'below') {+ resolvedParentId = targetItem.parentId;+ insertIdx = isFolderLikeLayer(targetItem)+ ? getSubtreeEndIndex(prev, targetIdx)+ : targetIdx + 1;} else {- const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);- const activeItem = activeIdx >= 0 ? prev[activeIdx] : undefined;- if (activeItem && isFolderLikeLayer(activeItem)) {- resolvedParentId = activeItem.id;- insertIdx = activeIdx + 1;- if (activeItem.collapsed) expandFolderId = activeItem.id;- } else {- resolvedParentId = activeItem?.parentId || null;- insertIdx = activeIdx >= 0 ? activeIdx : 0;- }+ resolvedParentId = targetItem.parentId;+ insertIdx = targetIdx;+ }+ } else {+ const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);+ const activeItem = activeIdx >= 0 ? prev[activeIdx] : undefined;+ if (activeItem && isFolderLikeLayer(activeItem)) {+ resolvedParentId = activeItem.id;+ insertIdx = activeIdx + 1;+ if (activeItem.collapsed) expandFolderId = activeItem.id;+ } else {+ resolvedParentId = activeItem?.parentId || null;+ insertIdx = activeIdx >= 0 ? activeIdx : 0;}+ }- const newLayer: LayerItem = {- id: newId,- name: layerName,- type: layerOverrides?.type || 'raster',- visible: true,- opacity,- blendMode,- locked: false,- collapsed: false,- parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : resolvedParentId,- thumbnailUrl: thumb,- ...layerOverrides,- };+ const newLayer: LayerItem = {+ id: newId,+ name: layerName,+ type: layerOverrides?.type || 'raster',+ visible: true,+ opacity,+ blendMode,+ locked: false,+ collapsed: false,+ parentId: layerOverrides?.parentId !== undefined ? layerOverrides.parentId : resolvedParentId,+ thumbnailUrl: thumb,+ ...layerOverrides,+ };- const nextLayers = expandFolderId- ? prev.map((l) => (l.id === expandFolderId ? { ...l, collapsed: false } : l))- : [...prev];- nextLayers.splice(insertIdx, 0, newLayer);- layersRef.current = nextLayers;- return nextLayers;- });+ const nextLayers = expandFolderId+ ? prev.map((l) => (l.id === expandFolderId ? { ...l, collapsed: false } : l))+ : [...prev];+ nextLayers.splice(insertIdx, 0, newLayer);+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ return nextLayers;},[activeLayerIdRef, layersRef, setLayers]);@@ -152,6 +155,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {layerOverrides?: Partial<LayerItem>,insertTarget?: LayerInsertTarget) => {+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const newId = customId || `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;const grid = activeTileGridRef.current;const isMono = layerOverrides?.expressionColor === 'monochrome';@@ -159,12 +164,25 @@ export function useLayerClipboard(ctx: LayerManagerContext) {grid.notifyChange(true);const dims = dimensionsRef.current;+ const tileDeltas = grid.computeDeltasFromSnapshot(new Map(), newId, {+ x: 0,+ y: 0,+ width: Math.max(dims.width, sourceCanvas.width),+ height: Math.max(dims.height, sourceCanvas.height),+ });const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);- insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, layerOverrides, insertTarget);+ const nextLayers = insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, layerOverrides, insertTarget);setActiveLayerId(newId);+ recordLayerHistory(+ `Paste Layer (${layerName})`,+ newId,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, newId),+ tileDeltas,+ 'layer'+ );return newId;},- [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]+ [activeLayerIdRef, activeTileGridRef, dimensionsRef, insertNewLayerItem, layersRef, recordLayerHistory, setActiveLayerId]);// Fill selection with non-destructive screentone layer directly in SparseTileGrid (GPU renders dots)@@ -176,11 +194,14 @@ export function useLayerClipboard(ctx: LayerManagerContext) {angle: number = 45,dotShape: HalftoneDotShape = 'circle',densityType: 'specified' | 'image' = 'specified'- ): { id: string; tileDeltas: TileDelta[] } => {+ ): { id: string; tileDeltas: TileDelta[]; layerTreeDelta: LayerTreeDelta } => {+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const resolvedFreq = frequency || defaultToneFrequencyRef.current || 60;const resolvedDensity = Math.max(1, Math.min(100, Math.round(density <= 1.0 && density > 0 ? density * 100 : density)));const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;const grid = activeTileGridRef.current;+ const dims = dimensionsRef.current;// Continuous source value: black ink in 'specified' mode, grayscale value in 'image' modeconst grayVal = densityType === 'specified' ? 0 : Math.round(255 * (1 - resolvedDensity / 100));@@ -191,7 +212,7 @@ export function useLayerClipboard(ctx: LayerManagerContext) {const res = fillSelectionInTileGrid({grid,layerId: newId,- dimensions,+ dimensions: dims,selection,colorCss: fillCss,targetFormat: 'color-32bit',@@ -199,22 +220,49 @@ export function useLayerClipboard(ctx: LayerManagerContext) {tileDeltas = res.tileDeltas;} else {const beforeSnapshot = grid.snapshotLayerTiles(newId);- grid.fillLayerSolidColor(newId, dimensions.width, dimensions.height, fillCss, 'color-32bit');- tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, newId);+ grid.fillLayerSolidColor(newId, dims.width, dims.height, fillCss, 'color-32bit');+ tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, newId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });+ }++ const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);+ const activeIdx = beforeLayers.findIndex((l) => l.id === beforeActiveLayerId);+ const activeItem = activeIdx >= 0 ? beforeLayers[activeIdx] : undefined;+ const isActiveFolderLike = Boolean(activeItem && isFolderLikeLayer(activeItem));+ const parentId = isActiveFolderLike ? activeItem!.id : (activeItem?.parentId || null);++ let name = 'Screen Tone';+ let count = 1;+ beforeLayers.forEach((l) => {+ if (l.name.startsWith('Screen Tone')) {+ const num = parseInt(l.name.replace('Screen Tone', '').trim(), 10);+ if (!isNaN(num) && num >= count) {+ count = num + 1;+ } else if (num === 1 || count === 1) {+ count = Math.max(count, 2);+ }+ }+ });+ if (count > 1) {+ name = `Screen Tone ${count}`;}- const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions }, true);const newLayer: LayerItem = {id: newId,- name: 'Screen Tone',+ name,type: 'raster',visible: true,opacity: 1,blendMode: 'normal',locked: false,collapsed: false,- parentId: null,+ parentId,thumbnailUrl: thumb,+ isToneLayer: densityType === 'specified',toneEnabled: true,toneFrequency: resolvedFreq,toneAngle: angle,@@ -223,60 +271,53 @@ export function useLayerClipboard(ctx: LayerManagerContext) {toneDensityType: densityType,};- setLayers((prev) => {- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);- const activeItem = prev[activeIdx];- const parentId = activeItem?.type === 'folder' ? activeItem.id : (activeItem?.parentId || null);- newLayer.parentId = parentId;-- let name = 'Screen Tone';- let count = 1;- prev.forEach((l) => {- if (l.name.startsWith('Screen Tone')) {- const num = parseInt(l.name.replace('Screen Tone', '').trim(), 10);- if (!isNaN(num) && num >= count) {- count = num + 1;- } else if (num === 1 || count === 1) {- count = Math.max(count, 2);- }- }+ const insertIdx = isActiveFolderLike ? activeIdx + 1 : (activeIdx >= 0 ? activeIdx : 0);+ let nextLayers =+ isActiveFolderLike && activeItem?.collapsed+ ? beforeLayers.map((l) => (l.id === activeItem.id ? { ...l, collapsed: false } : l))+ : [...beforeLayers];+ nextLayers.splice(insertIdx, 0, newLayer);++ const hasBg = beforeLayers.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');+ if (!hasBg) {+ const bgId = `layer-bg-${Date.now()}`;+ grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');+ const bgDeltas = grid.computeDeltasFromSnapshot(new Map(), bgId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,});- if (count > 1) {- name = `Screen Tone ${count}`;- }- newLayer.name = name;-- const insertIdx = activeIdx >= 0 ? activeIdx : 0;- let nextLayers = [...prev];- nextLayers.splice(insertIdx, 0, newLayer);-- const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');- if (!hasBg) {- const bgId = `layer-bg-${Date.now()}`;- grid.fillLayerSolidWhite(bgId, dimensions.width, dimensions.height, 'color-32bit');- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions }, false);- const bgLayer: LayerItem = {- id: bgId,- name: 'Background',- type: 'raster',- visible: true,- opacity: 1,- blendMode: 'normal',- locked: true,- parentId: null,- thumbnailUrl: bgThumb,- };- nextLayers = [...nextLayers, bgLayer];- }-- return nextLayers;- });+ tileDeltas = [...tileDeltas, ...bgDeltas];+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);+ const bgLayer: LayerItem = {+ id: bgId,+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: true,+ parentId: null,+ thumbnailUrl: bgThumb,+ };+ nextLayers = [...nextLayers, bgLayer];+ }+ layersRef.current = nextLayers;+ setLayers(nextLayers);grid.notifyChange(true);setActiveLayerId(newId);- return { id: newId, tileDeltas };++ const layerTreeDelta = createLayerTreeSnapshotDelta(+ beforeLayers,+ nextLayers,+ beforeActiveLayerId,+ newId+ );+ return { id: newId, tileDeltas, layerTreeDelta };},- [activeLayerId, activeTileGridRef, defaultToneFrequencyRef, dimensions, setActiveLayerId, setLayers]+ [activeLayerIdRef, activeTileGridRef, defaultToneFrequencyRef, dimensionsRef, layersRef, setActiveLayerId, setLayers]);// Create a new raster layer directly from a sparse tile snapshot (zero full-doc canvas)@@ -291,7 +332,9 @@ export function useLayerClipboard(ctx: LayerManagerContext) {opacity: number = 1,layerOverrides?: Partial<LayerItem>,insertTarget?: LayerInsertTarget- ): { id: string; name: string; tileDeltas: TileDelta[] } => {+ ): { id: string; name: string; tileDeltas: TileDelta[]; layerTreeDelta: LayerTreeDelta } => {+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;const grid = activeTileGridRef.current;grid.pasteLayerTilesSnapshot(newId, tileSnapshot);@@ -306,11 +349,17 @@ export function useLayerClipboard(ctx: LayerManagerContext) {...(tileSnapshot.format === 'monochrome-1bit' ? { expressionColor: 'monochrome' as const } : {}),...layerOverrides,};- insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, resolvedOverrides, insertTarget);+ const nextLayers = insertNewLayerItem(newId, layerName, blendMode, opacity, thumb, resolvedOverrides, insertTarget);setActiveLayerId(newId);- return { id: newId, name: layerName, tileDeltas };+ const layerTreeDelta = createLayerTreeSnapshotDelta(+ beforeLayers,+ nextLayers,+ beforeActiveLayerId,+ newId+ );+ return { id: newId, name: layerName, tileDeltas, layerTreeDelta };},- [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]+ [activeLayerIdRef, activeTileGridRef, dimensionsRef, insertNewLayerItem, layersRef, setActiveLayerId]);// Copy ONLY the selected pixels from a single layer into the sparse tile clipboard@@ -465,6 +514,7 @@ export function useLayerClipboard(ctx: LayerManagerContext) {layerId?: string;layerName?: string;tileDeltas?: TileDelta[];+ layerTreeDelta?: LayerTreeDelta;}> => {// 1. Check internal tile-backed clipboard (zero full-doc canvas)if (layerClipboardRef.current) {@@ -478,7 +528,13 @@ export function useLayerClipboard(ctx: LayerManagerContext) {data.opacity,overrides);- return { success: true, layerId: created.id, layerName: created.name, tileDeltas: created.tileDeltas };+ return {+ success: true,+ layerId: created.id,+ layerName: created.name,+ tileDeltas: created.tileDeltas,+ layerTreeDelta: created.layerTreeDelta,+ };}// 2. Check system clipboard@@ -497,6 +553,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {img.src = url;});+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const scale = Math.min(1, Math.min(dimensions.width / img.naturalWidth, dimensions.height / img.naturalHeight));const dw = Math.max(1, Math.round(img.naturalWidth * scale));const dh = Math.max(1, Math.round(img.naturalHeight * scale));@@ -525,10 +583,16 @@ export function useLayerClipboard(ctx: LayerManagerContext) {});const newName = 'Pasted Image';const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions }, true);- insertNewLayerItem(newId, newName, 'normal', 1, thumb);+ const nextLayers = insertNewLayerItem(newId, newName, 'normal', 1, thumb);setActiveLayerId(newId);grid.notifyChange(true);- return { success: true, layerId: newId, layerName: newName, tileDeltas };+ const layerTreeDelta = createLayerTreeSnapshotDelta(+ beforeLayers,+ nextLayers,+ beforeActiveLayerId,+ newId+ );+ return { success: true, layerId: newId, layerName: newName, tileDeltas, layerTreeDelta };}}}@@ -537,7 +601,7 @@ export function useLayerClipboard(ctx: LayerManagerContext) {}return { success: false };- }, [activeTileGridRef, createLayerFromTileSnapshot, dimensions, insertNewLayerItem, setActiveLayerId]);+ }, [activeLayerIdRef, activeTileGridRef, createLayerFromTileSnapshot, dimensions, insertNewLayerItem, layersRef, setActiveLayerId]);// Import an image file directly as a centered/fitted raster layer (tight-sized canvas -> tiles)const importImageFileAsLayer = useCallback(@@ -585,6 +649,8 @@ export function useLayerClipboard(ctx: LayerManagerContext) {const dx = Math.round((dims.width - dw) / 2);const dy = Math.round((dims.height - dh) / 2);+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const newId = `raster-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;const grid = activeTileGridRef.current;const tight = document.createElement('canvas');@@ -600,14 +666,27 @@ export function useLayerClipboard(ctx: LayerManagerContext) {}releaseTemporaryCanvas(tight);+ const tileDeltas = grid.computeDeltasFromSnapshot(new Map(), newId, {+ x: dx,+ y: dy,+ width: dw,+ height: dh,+ });const layerName = sanitizeImportedLayerName(file.name);const thumb = createCanvasThumbnail({ grid, layerId: newId, dimensions: dims }, true);- insertNewLayerItem(newId, layerName, 'normal', 1, thumb, undefined, insertTarget);+ const nextLayers = insertNewLayerItem(newId, layerName, 'normal', 1, thumb, undefined, insertTarget);setActiveLayerId(newId);grid.notifyChange(true);+ recordLayerHistory(+ `Import Image (${layerName})`,+ newId,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, newId),+ tileDeltas,+ 'layer'+ );return { id: newId, name: layerName };},- [activeTileGridRef, dimensionsRef, insertNewLayerItem, setActiveLayerId]+ [activeLayerIdRef, activeTileGridRef, dimensionsRef, insertNewLayerItem, layersRef, recordLayerHistory, setActiveLayerId]);// Paste a photo from filediff --git a/src/hooks/layerManager/useLayerCrud.ts b/src/hooks/layerManager/useLayerCrud.tsindex ee33045..beec1e5 100644--- a/src/hooks/layerManager/useLayerCrud.ts+++ b/src/hooks/layerManager/useLayerCrud.ts@@ -2,15 +2,16 @@ import { useCallback } from 'react';import {LayerItem,LayerType,+ TileDelta,isFolderLikeLayer,hasTileBackedLayer,} from '../../types/editor';import { get2DContext } from '../../utils/canvasUtils';-import { releaseTemporaryCanvas } from '../../utils/tileEngine';import {computeBatchDeleteLayers,computeBatchReorderLayers,computeGroupLayers,+ createLayerTreeSnapshotDelta,} from './layerTreeOps';import { LayerManagerContext } from './types';@@ -25,6 +26,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {activeLayerIdRef,setSelectedLayerIds,selectedLayerIdsRef,+ recordLayerHistory,} = ctx;// Add a new raster layer, folder, frame-folder, text, balloon, or adjustment layer@@ -37,9 +39,10 @@ export function useLayerCrud(ctx: LayerManagerContext) {selectNewLayer: boolean = true): LayerItem => {const id = customId || `${type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;- const currentLayers = layersRef.current;- const currentActiveIdx = currentLayers.findIndex((l) => l.id === activeLayerIdRef.current);- const currentActiveLayer = currentLayers[currentActiveIdx];+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const currentActiveIdx = beforeLayers.findIndex((l) => l.id === beforeActiveLayerId);+ const currentActiveLayer = beforeLayers[currentActiveIdx];let initialParentId: string | null = null;if (explicitParentId !== undefined) {@@ -72,7 +75,7 @@ export function useLayerCrud(ctx: LayerManagerContext) {const createdLayer: LayerItem = {id,- name: resolveLayerName(currentLayers),+ name: resolveLayerName(beforeLayers),type,visible: true,opacity: 1,@@ -92,30 +95,14 @@ export function useLayerCrud(ctx: LayerManagerContext) {monoExpressWhite: currentActiveLayer?.monoExpressWhite ?? true,};- setLayers((prev) => {- if (prev.some((l) => l.id === id)) return prev;- const activeIdx = prev.findIndex((l) => l.id === activeLayerIdRef.current);- const activeLayer = prev[activeIdx];-- let parentId: string | null = null;- if (explicitParentId !== undefined) {- parentId = explicitParentId;- } else if (activeLayer) {- parentId = isFolderLikeLayer(activeLayer) ? activeLayer.id : activeLayer.parentId;- }-- const newLayer: LayerItem = {- ...createdLayer,- name: resolveLayerName(prev),- parentId,- };-- const insertIndex = activeIdx >= 0 ? activeIdx : 0;- const nextLayers = [...prev];- nextLayers.splice(insertIndex, 0, newLayer);+ let nextLayers = beforeLayers;+ if (!beforeLayers.some((l) => l.id === id)) {+ const insertIndex = currentActiveIdx >= 0 ? currentActiveIdx : 0;+ nextLayers = [...beforeLayers];+ nextLayers.splice(insertIndex, 0, createdLayer);layersRef.current = nextLayers;- return nextLayers;- });+ setLayers(nextLayers);+ }if (hasTileBackedLayer({ type })) {const grid = activeTileGridRef.current;@@ -124,68 +111,98 @@ export function useLayerCrud(ctx: LayerManagerContext) {grid.markLayerIngested(id);}+ const afterActiveId = selectNewLayer ? id : beforeActiveLayerId;if (selectNewLayer) {setActiveLayerId(id);}++ if (nextLayers !== beforeLayers) {+ const label =+ type === 'folder' ? 'Add Folder' :+ type === 'vector' ? 'Add Vector Layer' :+ type === 'frame-folder' ? 'Add Frame Folder' :+ 'Add Layer';+ recordLayerHistory(+ label,+ id,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, afterActiveId),+ undefined,+ 'layer'+ );+ }+return createdLayer;},- [activeLayerIdRef, activeTileGridRef, layersRef, setActiveLayerId, setLayers]+ [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]);// Duplicate an existing layer or folder hierarchy with a single clickconst duplicateLayer = useCallback((id: string) => {- setLayers((prev) => {- const sourceIdx = prev.findIndex((l) => l.id === id);- if (sourceIdx < 0) return prev;- const grid = activeTileGridRef.current;-- const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {- const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;-- if (hasTileBackedLayer(source)) {- grid.cloneLayer(source.id, newId);- }-- let newMaskCanvas: HTMLCanvasElement | undefined;- let newMaskThumb: string | undefined;- if (source.maskCanvas) {- newMaskCanvas = document.createElement('canvas');- newMaskCanvas.width = source.maskCanvas.width;- newMaskCanvas.height = source.maskCanvas.height;- const mCtx = get2DContext(newMaskCanvas);- if (mCtx) mCtx.drawImage(source.maskCanvas, 0, 0);- newMaskThumb = source.maskThumbnailUrl;+ const prev = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const sourceIdx = prev.findIndex((l) => l.id === id);+ if (sourceIdx < 0) return;+ const grid = activeTileGridRef.current;+ const allTileDeltas: TileDelta[] = [];++ const cloneSingleLayer = (source: LayerItem, newParentId: string | null, nameSuffix: string = ' Copy'): LayerItem => {+ const newId = `${source.type}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;++ if (hasTileBackedLayer(source)) {+ grid.cloneLayer(source.id, newId);+ const clonedTiles = grid.getLayerTiles(newId, 0);+ for (const t of clonedTiles) {+ if (t.data) {+ allTileDeltas.push({+ key: `${newId}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: null,+ afterData: new Uint8Array(t.data),+ });+ }}+ }- return {- ...source,- id: newId,- name: `${source.name}${nameSuffix}`,- parentId: newParentId,- thumbnailUrl: source.thumbnailUrl,- maskCanvas: newMaskCanvas,- maskThumbnailUrl: newMaskThumb,- maskVersion: source.maskCanvas ? 1 : undefined,- vectorStrokes: source.vectorStrokes ? JSON.parse(JSON.stringify(source.vectorStrokes)) : undefined,- comicFrames: source.comicFrames ? JSON.parse(JSON.stringify(source.comicFrames)) : undefined,- textData: source.textData ? JSON.parse(JSON.stringify(source.textData)) : undefined,- balloonData: source.balloonData ? JSON.parse(JSON.stringify(source.balloonData)) : undefined,- balloons: source.balloons ? JSON.parse(JSON.stringify(source.balloons)) : undefined,- adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,- styles: source.styles ? JSON.parse(JSON.stringify(source.styles)) : undefined,- };- };-- const source = prev[sourceIdx];- if (!isFolderLikeLayer(source)) {- const newLayer = cloneSingleLayer(source, source.parentId, ' Copy');- const nextLayers = [...prev];- nextLayers.splice(sourceIdx, 0, newLayer);- setActiveLayerId(newLayer.id);- return nextLayers;+ let newMaskCanvas: HTMLCanvasElement | undefined;+ let newMaskThumb: string | undefined;+ if (source.maskCanvas) {+ newMaskCanvas = document.createElement('canvas');+ newMaskCanvas.width = source.maskCanvas.width;+ newMaskCanvas.height = source.maskCanvas.height;+ const mCtx = get2DContext(newMaskCanvas);+ if (mCtx) mCtx.drawImage(source.maskCanvas, 0, 0);+ newMaskThumb = source.maskThumbnailUrl;}- // Recursively duplicate folder or frame-folder and all nested descendants in stack order+ return {+ ...source,+ id: newId,+ name: `${source.name}${nameSuffix}`,+ parentId: newParentId,+ thumbnailUrl: source.thumbnailUrl,+ maskCanvas: newMaskCanvas,+ maskThumbnailUrl: newMaskThumb,+ maskVersion: source.maskCanvas ? 1 : undefined,+ vectorStrokes: source.vectorStrokes ? JSON.parse(JSON.stringify(source.vectorStrokes)) : undefined,+ comicFrames: source.comicFrames ? JSON.parse(JSON.stringify(source.comicFrames)) : undefined,+ textData: source.textData ? JSON.parse(JSON.stringify(source.textData)) : undefined,+ balloonData: source.balloonData ? JSON.parse(JSON.stringify(source.balloonData)) : undefined,+ balloons: source.balloons ? JSON.parse(JSON.stringify(source.balloons)) : undefined,+ adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,+ styles: source.styles ? JSON.parse(JSON.stringify(source.styles)) : undefined,+ };+ };++ const source = prev[sourceIdx];+ let nextLayers: LayerItem[];+ let nextActiveId = beforeActiveLayerId;++ if (!isFolderLikeLayer(source)) {+ const newLayer = cloneSingleLayer(source, source.parentId, ' Copy');+ nextLayers = [...prev];+ nextLayers.splice(sourceIdx, 0, newLayer);+ nextActiveId = newLayer.id;+ } else {const clonedItems: LayerItem[] = [];const cloneFolderSubtree = (folder: LayerItem, targetParentId: string | null, isRootFolder: boolean) => {const folderCopy = cloneSingleLayer(folder, targetParentId, isRootFolder ? ' Copy' : '');@@ -201,185 +218,297 @@ export function useLayerCrud(ctx: LayerManagerContext) {};cloneFolderSubtree(source, source.parentId, true);- const nextLayers = [...prev];+ nextLayers = [...prev];nextLayers.splice(sourceIdx, 0, ...clonedItems);if (clonedItems[0]) {- setActiveLayerId(clonedItems[0].id);+ nextActiveId = clonedItems[0].id;}- return nextLayers;- });- }, [activeTileGridRef, setActiveLayerId, setLayers]);+ }++ layersRef.current = nextLayers;+ setLayers(nextLayers);+ setActiveLayerId(nextActiveId);+ grid.notifyChange(true);+ recordLayerHistory(+ 'Duplicate Layer',+ nextActiveId,+ createLayerTreeSnapshotDelta(prev, nextLayers, beforeActiveLayerId, nextActiveId),+ allTileDeltas,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]);// Delete a layer or folder (including nested folder hierarchies)const deleteLayer = useCallback((id: string) => {- setLayers((prev) => {- const res = computeBatchDeleteLayers(prev, [id], activeLayerIdRef.current);- if (res.deletedIds.length === 0) return prev;- const grid = activeTileGridRef.current;-- for (const delId of res.deletedIds) {- const timer = thumbDebounceTimersRef.current.get(delId);- if (timer) {- clearTimeout(timer);- thumbDebounceTimersRef.current.delete(delId);- }+ const prev = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const res = computeBatchDeleteLayers(prev, [id], beforeActiveLayerId);+ if (res.deletedIds.length === 0) return;++ const grid = activeTileGridRef.current;+ const deletedTileDeltas: TileDelta[] = [];++ for (const delId of res.deletedIds) {+ const timer = thumbDebounceTimersRef.current.get(delId);+ if (timer) {+ clearTimeout(timer);+ thumbDebounceTimersRef.current.delete(delId);+ }- const deletedLayer = prev.find((l) => l.id === delId);- if (deletedLayer?.maskCanvas) {- releaseTemporaryCanvas(deletedLayer.maskCanvas);+ const tiles = grid.getLayerTiles(delId, 0);+ for (const t of tiles) {+ if (t.data) {+ deletedTileDeltas.push({+ key: `${delId}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: new Uint8Array(t.data),+ afterData: null,+ });}-- grid.clearLayer(delId);}- if (res.deletedIds.includes(activeLayerIdRef.current)) {- setActiveLayerId(res.nextActiveId);- } else {- setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => !res.deletedIds.includes(sid)));- }- return res.nextLayers;- });- }, [activeLayerIdRef, activeTileGridRef, setActiveLayerId, setLayers, setSelectedLayerIds, thumbDebounceTimersRef]);+ grid.clearLayer(delId);+ }++ layersRef.current = res.nextLayers;+ setLayers(res.nextLayers);++ let afterActiveId = beforeActiveLayerId;+ if (res.deletedIds.includes(beforeActiveLayerId)) {+ afterActiveId = res.nextActiveId;+ setActiveLayerId(res.nextActiveId);+ } else {+ setSelectedLayerIds((prevSelected) => prevSelected.filter((sid) => !res.deletedIds.includes(sid)));+ }++ recordLayerHistory(+ 'Delete Layer',+ afterActiveId || id,+ createLayerTreeSnapshotDelta(prev, res.nextLayers, beforeActiveLayerId, afterActiveId, {+ cloneMasks: true,+ }),+ deletedTileDeltas,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers, setSelectedLayerIds, thumbDebounceTimersRef]);// Delete all selected layers or foldersconst deleteSelectedLayers = useCallback(() => {- setLayers((prev) => {- const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);- if (res.deletedIds.length === 0) return prev;- const grid = activeTileGridRef.current;-- for (const delId of res.deletedIds) {- const timer = thumbDebounceTimersRef.current.get(delId);- if (timer) {- clearTimeout(timer);- thumbDebounceTimersRef.current.delete(delId);- }+ const prev = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const res = computeBatchDeleteLayers(prev, selectedLayerIdsRef.current, beforeActiveLayerId);+ if (res.deletedIds.length === 0) return;++ const grid = activeTileGridRef.current;+ const deletedTileDeltas: TileDelta[] = [];++ for (const delId of res.deletedIds) {+ const timer = thumbDebounceTimersRef.current.get(delId);+ if (timer) {+ clearTimeout(timer);+ thumbDebounceTimersRef.current.delete(delId);+ }- const deletedLayer = prev.find((l) => l.id === delId);- if (deletedLayer?.maskCanvas) {- releaseTemporaryCanvas(deletedLayer.maskCanvas);+ const tiles = grid.getLayerTiles(delId, 0);+ for (const t of tiles) {+ if (t.data) {+ deletedTileDeltas.push({+ key: `${delId}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: new Uint8Array(t.data),+ afterData: null,+ });}-- grid.clearLayer(delId);}- setActiveLayerId(res.nextActiveId);- return res.nextLayers;- });- }, [activeLayerIdRef, activeTileGridRef, selectedLayerIdsRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);+ grid.clearLayer(delId);+ }++ layersRef.current = res.nextLayers;+ setLayers(res.nextLayers);+ setActiveLayerId(res.nextActiveId);++ recordLayerHistory(+ res.deletedIds.length > 1 ? `Delete ${res.deletedIds.length} Layers` : 'Delete Layer',+ res.nextActiveId || beforeActiveLayerId,+ createLayerTreeSnapshotDelta(prev, res.nextLayers, beforeActiveLayerId, res.nextActiveId, {+ cloneMasks: true,+ }),+ deletedTileDeltas,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]);// Group all currently selected layers into a new folderconst groupSelectedLayers = useCallback(() => {- setLayers((prev) => {- const res = computeGroupLayers(prev, selectedLayerIdsRef.current, activeLayerIdRef.current);- if (!res) return prev;-- setActiveLayerId(res.newFolder.id);- return res.nextLayers;- });- }, [activeLayerIdRef, selectedLayerIdsRef, setActiveLayerId, setLayers]);+ const prev = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const res = computeGroupLayers(prev, selectedLayerIdsRef.current, beforeActiveLayerId);+ if (!res) return;++ layersRef.current = res.nextLayers;+ setLayers(res.nextLayers);+ setActiveLayerId(res.newFolder.id);++ recordLayerHistory(+ 'Group Layers',+ res.newFolder.id,+ createLayerTreeSnapshotDelta(prev, res.nextLayers, beforeActiveLayerId, res.newFolder.id),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setActiveLayerId, setLayers]);// Rename a layerconst renameLayer = useCallback((id: string, newName: string) => {- if (!newName.trim()) return;- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, name: newName.trim() } : l))+ const trimmed = newName.trim();+ if (!trimmed) return;+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || target.name === trimmed) return;++ const next = prev.map((l) => (l.id === id ? { ...l, name: trimmed } : l));+ layersRef.current = next;+ setLayers(next);+ recordLayerHistory(+ 'Rename Layer',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer');- }, [setLayers]);+ }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);// Move layer up or down in visual stackconst moveLayer = useCallback((id: string, direction: 'up' | 'down') => {- setLayers((prev) => {- const idx = prev.findIndex((l) => l.id === id);- if (idx < 0) return prev;-- const targetIdx = direction === 'up' ? idx - 1 : idx + 1;- if (targetIdx < 0 || targetIdx >= prev.length) return prev;-- const next = [...prev];- const [item] = next.splice(idx, 1);- next.splice(targetIdx, 0, item);- return next;- });- }, [setLayers]);+ const prev = layersRef.current;+ const idx = prev.findIndex((l) => l.id === id);+ if (idx < 0) return;++ const targetIdx = direction === 'up' ? idx - 1 : idx + 1;+ if (targetIdx < 0 || targetIdx >= prev.length) return;++ const next = [...prev];+ const [item] = next.splice(idx, 1);+ next.splice(targetIdx, 0, item);+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Reorder Layer',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Move layer into a specific folder or to rootconst moveLayerToFolder = useCallback((id: string, targetFolderId: string | null) => {- setLayers((prev) => {- const item = prev.find((l) => l.id === id);- if (!item || item.id === targetFolderId) return prev;-- // If moving a folder into itself, ignore- if (isFolderLikeLayer(item) && targetFolderId) {- let curr: LayerItem | undefined = prev.find((l) => l.id === targetFolderId);- while (curr) {- if (curr.id === id) return prev;- curr = prev.find((l) => l.id === curr?.parentId);- }+ const prev = layersRef.current;+ const item = prev.find((l) => l.id === id);+ if (!item || item.id === targetFolderId || item.parentId === targetFolderId) return;++ // If moving a folder into itself, ignore+ if (isFolderLikeLayer(item) && targetFolderId) {+ let curr: LayerItem | undefined = prev.find((l) => l.id === targetFolderId);+ while (curr) {+ if (curr.id === id) return;+ curr = prev.find((l) => l.id === curr?.parentId);}-- return prev.map((l) => (l.id === id ? { ...l, parentId: targetFolderId } : l));- });- }, [setLayers]);+ }++ const next = prev.map((l) => (l.id === id ? { ...l, parentId: targetFolderId } : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Move Layer to Folder',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Reorder layer via drag-and-drop (supports multi-layer selection)const reorderLayers = useCallback((draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => {- setLayers((prev) => computeBatchReorderLayers(prev, selectedLayerIdsRef.current, draggedId, targetId, position));- }, [selectedLayerIdsRef, setLayers]);+ const prev = layersRef.current;+ const next = computeBatchReorderLayers(prev, selectedLayerIdsRef.current, draggedId, targetId, position);+ if (next === prev) return;+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Reorder Layers',+ draggedId,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Move selected layers into a target parent folder or indexconst moveSelectedLayers = useCallback((targetParentId: string | null, targetIndex?: number) => {- setLayers((prev) => {- const selectedIds = selectedLayerIdsRef.current.length > 0- ? selectedLayerIdsRef.current- : activeLayerIdRef.current ? [activeLayerIdRef.current] : [];- if (selectedIds.length === 0) return prev;-- const getDescendantIds = (parentId: string): string[] => {- const ids: string[] = [];- for (const item of prev) {- if (item.parentId === parentId) {- ids.push(item.id);- ids.push(...getDescendantIds(item.id));- }- }- return ids;- };-- const movingIds = new Set<string>();- for (const id of selectedIds) {- movingIds.add(id);- const item = prev.find((l) => l.id === id);- if (isFolderLikeLayer(item)) {- getDescendantIds(id).forEach((descId) => movingIds.add(descId));+ const prev = layersRef.current;+ const selectedIds = selectedLayerIdsRef.current.length > 0+ ? selectedLayerIdsRef.current+ : activeLayerIdRef.current ? [activeLayerIdRef.current] : [];+ if (selectedIds.length === 0) return;++ const getDescendantIds = (parentId: string): string[] => {+ const ids: string[] = [];+ for (const item of prev) {+ if (item.parentId === parentId) {+ ids.push(item.id);+ ids.push(...getDescendantIds(item.id));}}+ return ids;+ };- if (targetParentId && movingIds.has(targetParentId)) return prev;-- const movingItems = prev- .filter((l) => movingIds.has(l.id))- .map((l) => {- if (!l.parentId || !movingIds.has(l.parentId)) {- return { ...l, parentId: targetParentId };- }- return l;- });+ const movingIds = new Set<string>();+ for (const id of selectedIds) {+ movingIds.add(id);+ const item = prev.find((l) => l.id === id);+ if (isFolderLikeLayer(item)) {+ getDescendantIds(id).forEach((descId) => movingIds.add(descId));+ }+ }- const remaining = prev.filter((l) => !movingIds.has(l.id));+ if (targetParentId && movingIds.has(targetParentId)) return;- let insertIdx = remaining.length;- if (typeof targetIndex === 'number') {- insertIdx = Math.max(0, Math.min(remaining.length, targetIndex));- } else if (targetParentId) {- const parentIdx = remaining.findIndex((l) => l.id === targetParentId);- insertIdx = parentIdx >= 0 ? parentIdx + 1 : remaining.length;- }+ const movingItems = prev+ .filter((l) => movingIds.has(l.id))+ .map((l) => {+ if (!l.parentId || !movingIds.has(l.parentId)) {+ return { ...l, parentId: targetParentId };+ }+ return l;+ });- remaining.splice(insertIdx, 0, ...movingItems);- return remaining;- });- }, [activeLayerIdRef, selectedLayerIdsRef, setLayers]);+ const remaining = prev.filter((l) => !movingIds.has(l.id));++ let insertIdx = remaining.length;+ if (typeof targetIndex === 'number') {+ insertIdx = Math.max(0, Math.min(remaining.length, targetIndex));+ } else if (targetParentId) {+ const parentIdx = remaining.findIndex((l) => l.id === targetParentId);+ insertIdx = parentIdx >= 0 ? parentIdx + 1 : remaining.length;+ }++ remaining.splice(insertIdx, 0, ...movingItems);+ layersRef.current = remaining;+ setLayers(remaining);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Move Layers',+ activeLayerIdRef.current,+ createLayerTreeSnapshotDelta(prev, remaining, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Calculate effective opacity accounting for parent foldersconst getEffectiveOpacity = useCallback((layer: LayerItem): number => {diff --git a/src/hooks/layerManager/useLayerDocumentOps.ts b/src/hooks/layerManager/useLayerDocumentOps.tsindex a954fed..aa04179 100644--- a/src/hooks/layerManager/useLayerDocumentOps.ts+++ b/src/hooks/layerManager/useLayerDocumentOps.ts@@ -4,13 +4,20 @@ import {CanvasDimensions,LayerItem,LoadedDocument,+ TileDelta,hasTileBackedLayer,+ isFolderLikeLayer,} from '../../types/editor';import { createCanvasThumbnail } from '../../utils/canvasUtils';import { documentStore } from '../../utils/documentStore';import { multiplayerService } from '../../services/multiplayerService';+import { compositeCanvas } from '../../utils/saveManager/gpuComposite';import { releaseTemporaryCanvas } from '../../utils/tileEngine';-import { isBackgroundLayerId } from './layerTreeOps';+import {+ computeMergeFolderLayers,+ createLayerTreeSnapshotDelta,+ isBackgroundLayerId,+} from './layerTreeOps';import { LayerCanvasRegistryApi, LayerManagerContext } from './types';export function useLayerDocumentOps(@@ -26,33 +33,49 @@ export function useLayerDocumentOps(setLayers,layersRef,activeLayerId,+ activeLayerIdRef,setActiveLayerId,setSelectedLayerIds,+ recordLayerHistory,} = ctx;const { updateLayerThumbnail } = canvasRegistry;// Clear active layer content directly in SparseTileGrid (zero forced full canvas allocation)const clearActiveLayer = useCallback(() => {+ const targetId = activeLayerIdRef.current || activeLayerId;+ if (!targetId) return;const grid = activeTileGridRef.current;const dims = dimensionsRef.current;- const isBg = isBackgroundLayerId(activeLayerId);+ const isBg = isBackgroundLayerId(targetId);+ const beforeSnapshot = grid.snapshotLayerTiles(targetId);if (isBg) {- grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');+ grid.fillLayerSolidWhite(targetId, dims.width, dims.height, 'color-32bit');} else {- grid.clearLayer(activeLayerId);- grid.markLayerIngested(activeLayerId);+ grid.clearLayer(targetId);+ grid.markLayerIngested(targetId);}+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });grid.notifyChange(true);- updateLayerThumbnail(activeLayerId);- }, [activeLayerId, activeTileGridRef, dimensionsRef, updateLayerThumbnail]);+ updateLayerThumbnail(targetId, true);++ if (tileDeltas.length > 0) {+ recordLayerHistory('Clear Layer', targetId, undefined, tileDeltas, 'clear');+ }+ }, [activeLayerId, activeLayerIdRef, activeTileGridRef, dimensionsRef, recordLayerHistory, updateLayerThumbnail]);// Merge active raster layer down onto the raster layer directly below it (tile-by-tile, zero full-doc canvas)const mergeDown = useCallback((targetLayerId?: string): { targetId: string; removedId: string } | null => {const currentLayers = layersRef.current;- const srcId = targetLayerId || activeLayerId;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const srcId = targetLayerId || activeLayerIdRef.current || activeLayerId;const srcIdx = currentLayers.findIndex((l) => l.id === srcId);if (srcIdx < 0) return null;@@ -72,6 +95,7 @@ export function useLayerDocumentOps(if (dstLayer.locked) return null;const grid = activeTileGridRef.current;+ const dims = dimensionsRef.current;const dstFormat =dstLayer.expressionColor === 'monochrome'? 'monochrome-1bit'@@ -79,34 +103,275 @@ export function useLayerDocumentOps(? 'grayscale-8bit': 'color-32bit';+ // Snapshot both source layer tiles (which will be removed) and destination layer tiles (before merge)+ const srcTileDeltas: TileDelta[] = [];+ for (const t of grid.getLayerTiles(srcLayer.id, 0)) {+ if (t.data) {+ srcTileDeltas.push({+ key: `${srcLayer.id}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: new Uint8Array(t.data),+ afterData: null,+ });+ }+ }+ const dstBeforeSnapshot = grid.snapshotLayerTiles(dstLayer.id);+grid.mergeLayersInGrid(srcLayer.id, dstLayer.id, {opacity: srcLayer.opacity,blendMode: srcLayer.blendMode,visible: srcLayer.visible,maskCanvas: srcLayer.maskCanvas,maskEnabled: srcLayer.maskEnabled,- dimensions: dimensionsRef.current,+ dimensions: dims,dstFormat,});- if (multiplayerService.isConnected()) {- multiplayerService.streamLayerTiles(dstLayer.id, grid, { force: true });+ const dstTileDeltas = grid.computeDeltasFromSnapshot(dstBeforeSnapshot, dstLayer.id, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });+ // Ensure any newly created tiles on dstLayer that weren't in dstBeforeSnapshot are captured too+ const seenDstKeys = new Set(dstTileDeltas.map((d) => d.key));+ for (const t of grid.getLayerTiles(dstLayer.id, 0)) {+ const key = `${dstLayer.id}:${t.tileX}:${t.tileY}`;+ if (!seenDstKeys.has(key) && t.data && !dstBeforeSnapshot.has(key)) {+ dstTileDeltas.push({+ key,+ format: t.format,+ beforeData: null,+ afterData: new Uint8Array(t.data),+ });+ }}- if (srcLayer.maskCanvas) {- releaseTemporaryCanvas(srcLayer.maskCanvas);+ if (multiplayerService.isConnected()) {+ multiplayerService.streamLayerTiles(dstLayer.id, grid, { force: true });}const nextLayers = currentLayers.filter((l) => l.id !== srcLayer.id);+ const layerTreeDelta = createLayerTreeSnapshotDelta(+ currentLayers,+ nextLayers,+ beforeActiveLayerId,+ dstLayer.id,+ { cloneMasks: true }+ );layersRef.current = nextLayers;setLayers(nextLayers);setActiveLayerId(dstLayer.id);setSelectedLayerIds([dstLayer.id]);- updateLayerThumbnail(dstLayer.id);+ updateLayerThumbnail(dstLayer.id, true);+ recordLayerHistory(+ 'Merge Down',+ dstLayer.id,+ layerTreeDelta,+ [...srcTileDeltas, ...dstTileDeltas],+ 'layer'+ );return { targetId: dstLayer.id, removedId: srcLayer.id };},- [activeLayerId, activeTileGridRef, dimensionsRef, layersRef, setActiveLayerId, setLayers, setSelectedLayerIds, updateLayerThumbnail]+ [activeLayerId, activeLayerIdRef, activeTileGridRef, dimensionsRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers, setSelectedLayerIds, updateLayerThumbnail]+ );++ // Merge a folder (or frame-folder) and all of its descendants into a single raster layer+ const mergeFolder = useCallback(+ (+ targetFolderId?: string,+ customMergedId?: string+ ): {+ mergedLayerId: string;+ removedFolderId: string;+ removedDescendantIds: string[];+ } | null => {+ const currentLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const folderId = targetFolderId || activeLayerIdRef.current || activeLayerId;+ const mergePlan = computeMergeFolderLayers(currentLayers, folderId, customMergedId);+ if (!mergePlan) return null;++ const { folder, descendantLayers, descendantIds, mergedLayer, nextLayers } = mergePlan;+ const grid = activeTileGridRef.current;+ const dims = dimensionsRef.current;++ const mergedFormat =+ mergedLayer.expressionColor === 'monochrome'+ ? 'monochrome-1bit'+ : mergedLayer.expressionColor === 'gray'+ ? 'grayscale-8bit'+ : 'color-32bit';++ // Snapshot all descendant tiles before mutating grid so undo restores everything atomically+ const removedTileDeltas: TileDelta[] = [];+ for (const descId of descendantIds) {+ for (const t of grid.getLayerTiles(descId, 0)) {+ if (t.data) {+ removedTileDeltas.push({+ key: `${descId}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: new Uint8Array(t.data),+ afterData: null,+ });+ }+ }+ }++ // Render subtree with the root folder normalized to visible=true, opacity=1, blendMode='normal'+ // so the folder's own visibility, opacity, and blend mode stay non-destructively on mergedLayer.+ const rootForComposite: LayerItem = {+ ...folder,+ parentId: null,+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ maskCanvas: undefined,+ maskEnabled: false,+ };+ const subtreeLayers: LayerItem[] = [rootForComposite, ...descendantLayers];+ const subtreeMap = new Map<string, LayerItem>(subtreeLayers.map((l) => [l.id, l]));++ const getSubtreeOpacity = (layer: LayerItem): number => {+ let alpha = layer.opacity;+ let currParentId = layer.parentId;+ while (currParentId) {+ const parent = subtreeMap.get(currParentId);+ if (!parent) break;+ alpha *= parent.opacity;+ currParentId = parent.parentId;+ }+ return alpha;+ };++ const isSubtreeVisible = (layer: LayerItem): boolean => {+ let curr: LayerItem | undefined = layer;+ while (curr) {+ if (!curr.visible) return false;+ curr = curr.parentId ? subtreeMap.get(curr.parentId) : undefined;+ }+ return true;+ };++ const hasRenderableContent =+ folder.type === 'frame-folder' ||+ descendantLayers.some(+ (l) => !isFolderLikeLayer(l) && isSubtreeVisible(l) && getSubtreeOpacity(l) > 0.001+ );++ grid.setLayerFormat(mergedLayer.id, mergedFormat);+ grid.markLayerIngested(mergedLayer.id);++ if (hasRenderableContent && dims.width > 0 && dims.height > 0) {+ let hasCanvas2D = false;+ if (typeof document !== 'undefined') {+ const probe = document.createElement('canvas');+ probe.width = 1;+ probe.height = 1;+ hasCanvas2D = Boolean(probe.getContext('2d'));+ releaseTemporaryCanvas(probe);+ }++ if (hasCanvas2D) {+ const composited = compositeCanvas(+ dims,+ subtreeLayers,+ undefined,+ getSubtreeOpacity,+ isSubtreeVisible,+ false,+ grid+ );+ grid.ingestCanvas(mergedLayer.id, composited, mergedFormat);+ releaseTemporaryCanvas(composited);+ } else {+ // Headless / jsdom fallback when neither WebGL2 nor Canvas2D is available+ const bottomToTop = descendantLayers.slice().reverse();+ for (const child of bottomToTop) {+ if (!hasTileBackedLayer(child)) continue;+ if (!isSubtreeVisible(child)) continue;+ const effOpacity = getSubtreeOpacity(child);+ if (effOpacity <= 0.001 || !grid.hasLayerTiles(child.id)) continue;+ grid.mergeLayersInGrid(child.id, mergedLayer.id, {+ opacity: effOpacity,+ blendMode: child.blendMode,+ visible: true,+ maskCanvas: child.maskCanvas,+ maskEnabled: child.maskEnabled,+ dimensions: dims,+ dstFormat: mergedFormat,+ });+ }+ }+ }++ for (const remId of [folder.id, ...descendantIds]) {+ const timer = thumbDebounceTimersRef.current.get(remId);+ if (timer) {+ clearTimeout(timer);+ thumbDebounceTimersRef.current.delete(remId);+ }+ grid.clearLayer(remId);+ }++ const mergedTileDeltas: TileDelta[] = [];+ for (const t of grid.getLayerTiles(mergedLayer.id, 0)) {+ if (t.data) {+ mergedTileDeltas.push({+ key: `${mergedLayer.id}:${t.tileX}:${t.tileY}`,+ format: t.format,+ beforeData: null,+ afterData: new Uint8Array(t.data),+ });+ }+ }++ if (multiplayerService.isConnected()) {+ multiplayerService.streamLayerTiles(mergedLayer.id, grid, { force: true });+ }++ const layerTreeDelta = createLayerTreeSnapshotDelta(+ currentLayers,+ nextLayers,+ beforeActiveLayerId,+ mergedLayer.id,+ { cloneMasks: true }+ );+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ setActiveLayerId(mergedLayer.id);+ setSelectedLayerIds([mergedLayer.id]);+ grid.notifyChange(true);+ updateLayerThumbnail(mergedLayer.id, true);++ recordLayerHistory(+ 'Merge Folder',+ mergedLayer.id,+ layerTreeDelta,+ [...removedTileDeltas, ...mergedTileDeltas],+ 'layer'+ );++ return {+ mergedLayerId: mergedLayer.id,+ removedFolderId: folder.id,+ removedDescendantIds: descendantIds,+ };+ },+ [+ activeLayerId,+ activeLayerIdRef,+ activeTileGridRef,+ dimensionsRef,+ layersRef,+ recordLayerHistory,+ setActiveLayerId,+ setLayers,+ setSelectedLayerIds,+ thumbDebounceTimersRef,+ updateLayerThumbnail,+ ]);// Switch active document tab in O(1): binds session's SparseTileGrid without clearing or re-slicing@@ -296,6 +561,7 @@ export function useLayerDocumentOps(return {clearActiveLayer,mergeDown,+ mergeFolder,switchDocumentSession,resetToNewCanvas,clearDocument,diff --git a/src/hooks/layerManager/useLayerEffects.ts b/src/hooks/layerManager/useLayerEffects.tsindex 26465dc..a00b8f0 100644--- a/src/hooks/layerManager/useLayerEffects.ts+++ b/src/hooks/layerManager/useLayerEffects.ts@@ -1,12 +1,21 @@import { useCallback } from 'react';-import { ExpressionColor, LayerItem } from '../../types/editor';+import {+ CanvasSelection,+ ExpressionColor,+ LayerItem,+ LayerTreeDelta,+ isDedicatedToneLayer,+ isFolderLikeLayer,+} from '../../types/editor';import { createCanvasThumbnail } from '../../utils/canvasUtils';import {applyExpressionColorToImageData,applyLayerTintToImageData,} from '../../utils/layerEffectsEngine';import { HalftoneDotShape } from '../../utils/screentoneEngine';+import { fillSelectionInTileGrid } from '../../utils/selectionUtils';import { TILE_SIZE, TileDelta, TileSnapshotEntry } from '../../utils/tileEngine';+import { createLayerTreeSnapshotDelta } from './layerTreeOps';import { LayerCanvasRegistryApi, LayerManagerContext } from './types';export function useLayerEffects(@@ -17,194 +26,338 @@ export function useLayerEffects(activeTileGridRef,dimensionsRef,defaultToneFrequencyRef,- layers,+ layersRef,+ activeLayerIdRef,setLayers,+ recordLayerHistory,} = ctx;const { updateLayerThumbnail } = canvasRegistry;- // Toggle non-destructive screentone effect (rendered live on GPU by ViewportCompositor from raw tile data)- const toggleTone = useCallback((id: string) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;-- const newEnabled = !target.toneEnabled;- const updatedLayer: LayerItem = {- ...target,- toneEnabled: newEnabled,- toneFrequency: target.toneFrequency ?? defaultToneFrequencyRef.current ?? 60,- toneAngle: target.toneAngle ?? 45,- toneDotShape: target.toneDotShape ?? 'circle',- toneDensity: target.toneDensity ?? 40,- toneDensityType: target.toneDensityType ?? 'specified',+ // Toggle non-destructive screentone effect (rendered live on GPU by ViewportCompositor from raw tile data).+ // When enabling screentone on an empty raster layer while a selection is active, automatically fills+ // the selection with tone so checking "Screentone" after Lasso/Marquee/Wand works immediately!+ const toggleTone = useCallback((id: string, activeSelection?: CanvasSelection | null) => {+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return;++ const grid = activeTileGridRef.current;+ const dims = dimensionsRef.current;+ const newEnabled = !target.toneEnabled;+ const shouldFillSelection =+ newEnabled &&+ Boolean(activeSelection) &&+ target.type === 'raster' &&+ !target.locked &&+ !grid.hasLayerTiles(id);++ let tileDeltas: TileDelta[] = [];+ if (shouldFillSelection && activeSelection) {+ const fillRes = fillSelectionInTileGrid({+ grid,+ layerId: id,+ dimensions: dims,+ selection: activeSelection,+ colorCss: 'rgb(0,0,0)',+ targetFormat: 'color-32bit',+ });+ tileDeltas = fillRes.tileDeltas;+ }++ const isToneLayer = shouldFillSelection ? true : isDedicatedToneLayer(target);+ const updatedLayer: LayerItem = {+ ...target,+ isToneLayer: shouldFillSelection ? true : target.isToneLayer,+ toneEnabled: newEnabled,+ toneFrequency: target.toneFrequency ?? defaultToneFrequencyRef.current ?? 60,+ toneAngle: target.toneAngle ?? 45,+ toneDotShape: target.toneDotShape ?? 'circle',+ toneDensity: target.toneDensity ?? 40,+ toneDensityType: isToneLayer ? 'specified' : 'image',+ };++ let nextLayers = prev.map((l) => (l.id === id ? updatedLayer : l));++ // Ensure white paper background exists when enabling screentone on a transparent doc+ const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');+ if (newEnabled && !hasBg) {+ const bgId = `layer-bg-${Date.now()}`;+ grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');+ const bgDeltas = grid.computeDeltasFromSnapshot(new Map(), bgId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });+ tileDeltas = [...tileDeltas, ...bgDeltas];+ const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);+ const bgLayer: LayerItem = {+ id: bgId,+ name: 'Background',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: true,+ parentId: null,+ thumbnailUrl: bgThumb,};-- const grid = activeTileGridRef.current;- let nextLayers = prev.map((l) => (l.id === id ? updatedLayer : l));-- // Ensure white paper background exists when enabling screentone on a transparent doc- const hasBg = prev.some((l) => l.id.startsWith('layer-bg') || l.name.toLowerCase() === 'background');- if (newEnabled && !hasBg) {- const bgId = `layer-bg-${Date.now()}`;- const dims = dimensionsRef.current;- grid.fillLayerSolidWhite(bgId, dims.width, dims.height, 'color-32bit');- const bgThumb = createCanvasThumbnail({ grid, layerId: bgId, dimensions: dims }, false);- const bgLayer: LayerItem = {- id: bgId,- name: 'Background',- type: 'raster',- visible: true,- opacity: 1,- blendMode: 'normal',- locked: true,- parentId: null,- thumbnailUrl: bgThumb,- };- nextLayers = [...nextLayers, bgLayer];- }-- grid.notifyChange(true);- updateLayerThumbnail(id, false);- return nextLayers;- });- }, [activeTileGridRef, defaultToneFrequencyRef, dimensionsRef, setLayers, updateLayerThumbnail]);+ nextLayers = [...nextLayers, bgLayer];+ }++ layersRef.current = nextLayers;+ setLayers(nextLayers);+ grid.notifyChange(true);+ updateLayerThumbnail(id, shouldFillSelection);+ recordLayerHistory(+ newEnabled ? (shouldFillSelection ? 'Screentone Selection' : 'Enable Screentone') : 'Disable Screentone',+ id,+ createLayerTreeSnapshotDelta(prev, nextLayers, activeLayerIdRef.current, activeLayerIdRef.current),+ tileDeltas,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, defaultToneFrequencyRef, dimensionsRef, layersRef, recordLayerHistory, setLayers, updateLayerThumbnail]);// Update screentone frequency (Lines / LPI, 20 to 85)const setToneFrequency = useCallback((id: string, frequency: number) => {const clampedFreq = Math.max(20, Math.min(85, Math.round(frequency)));- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, toneFrequency: clampedFreq } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.toneFrequency === clampedFreq) return;+ const next = prev.map((l) => (l.id === id ? { ...l, toneFrequency: clampedFreq } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Screentone Frequency',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `toneFreq:${id}`,+ }),+ undefined,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update screentone angle (0 to 90 degrees)const setToneAngle = useCallback((id: string, angle: number) => {const clampedAngle = Math.max(0, Math.min(90, Math.round(angle)));- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, toneAngle: clampedAngle } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.toneAngle === clampedAngle) return;+ const next = prev.map((l) => (l.id === id ? { ...l, toneAngle: clampedAngle } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Screentone Angle',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `toneAngle:${id}`,+ }),+ undefined,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update screentone dot shape (default: circle)const setToneDotShape = useCallback((id: string, dotShape: HalftoneDotShape) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, toneDotShape: dotShape } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.toneDotShape === dotShape) return;+ const next = prev.map((l) => (l.id === id ? { ...l, toneDotShape: dotShape } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Screentone Dot Shape',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update screentone density (1 to 100%)const setToneDensity = useCallback((id: string, density: number) => {const clampedDensity = Math.max(1, Math.min(100, Math.round(density)));- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, toneDensity: clampedDensity } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.toneDensity === clampedDensity) return;+ const next = prev.map((l) => (l.id === id ? { ...l, toneDensity: clampedDensity } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Screentone Density',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `toneDensity:${id}`,+ }),+ undefined,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update screentone density mode ('specified' vs 'image')const setToneDensityType = useCallback((id: string, densityType: 'specified' | 'image') => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, toneDensityType: densityType } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.toneDensityType === densityType) return;+ const next = prev.map((l) =>+ l.id === id+ ? { ...l, toneDensityType: densityType, isToneLayer: densityType === 'specified' }+ : l+ );+ layersRef.current = next;+ setLayers(next);+ if (target.toneEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Screentone Density Mode',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'screentone'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle non-destructive Layer Color (Tint) effect (rendered on GPU)const toggleLayerColor = useCallback((id: string) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;-- const updatedLayer: LayerItem = {- ...target,- layerColorEnabled: !target.layerColorEnabled,- layerColor: target.layerColor || '#1c73c2',- layerSubColor: target.layerSubColor || '#ffffff',- };- activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? updatedLayer : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return;++ const updatedLayer: LayerItem = {+ ...target,+ layerColorEnabled: !target.layerColorEnabled,+ layerColor: target.layerColor || '#1c73c2',+ layerSubColor: target.layerSubColor || '#ffffff',+ };+ const next = prev.map((l) => (l.id === id ? updatedLayer : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ updatedLayer.layerColorEnabled ? 'Enable Layer Tint' : 'Disable Layer Tint',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Layer Color (Tint primary color)const setLayerColor = useCallback((id: string, color: string) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, layerColor: color } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.layerColor === color) return;+ const next = prev.map((l) => (l.id === id ? { ...l, layerColor: color } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Layer Tint Color',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `layerColor:${id}`,+ }),+ undefined,+ 'layer-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Layer Sub Color (Tint secondary color)const setLayerSubColor = useCallback((id: string, color: string) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, layerSubColor: color } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.layerSubColor === color) return;+ const next = prev.map((l) => (l.id === id ? { ...l, layerSubColor: color } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.layerColorEnabled) activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Layer Sub Color',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `layerSubColor:${id}`,+ }),+ undefined,+ 'layer-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update non-destructive Expression Color preview ('color' | 'gray' | 'monochrome')const setLayerExpressionColor = useCallback((id: string, mode: ExpressionColor) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;-- const updatedLayer: LayerItem = {- ...target,- expressionColor: mode,- monoThreshold: target.monoThreshold ?? 128,- monoExpressBlack: target.monoExpressBlack ?? true,- monoExpressWhite: target.monoExpressWhite ?? true,- };- activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? updatedLayer : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.expressionColor === mode) return;++ const updatedLayer: LayerItem = {+ ...target,+ expressionColor: mode,+ monoThreshold: target.monoThreshold ?? 128,+ monoExpressBlack: target.monoExpressBlack ?? true,+ monoExpressWhite: target.monoExpressWhite ?? true,+ };+ const next = prev.map((l) => (l.id === id ? updatedLayer : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ `Expression Color (${mode})`,+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'expression-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Monochrome Color threshold (1 - 255)const setLayerMonoThreshold = useCallback((id: string, threshold: number) => {const clamped = Math.max(1, Math.min(255, Math.round(threshold)));- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);- return prev.map((l) => (l.id === id ? { ...l, monoThreshold: clamped } : l));- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || target.monoThreshold === clamped) return;+ const next = prev.map((l) => (l.id === id ? { ...l, monoThreshold: clamped } : l));+ layersRef.current = next;+ setLayers(next);+ if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Monochrome Threshold',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `monoThreshold:${id}`,+ }),+ undefined,+ 'expression-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Monochrome Express Colors (express black, express white)const setLayerMonoExpressMode = useCallback((id: string, expressBlack: boolean, expressWhite: boolean) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || target.type === 'folder') return prev;- if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);- return prev.map((l) =>- l.id === id ? { ...l, monoExpressBlack: expressBlack, monoExpressWhite: expressWhite } : l- );- });- }, [activeTileGridRef, setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return;+ const next = prev.map((l) =>+ l.id === id ? { ...l, monoExpressBlack: expressBlack, monoExpressWhite: expressWhite } : l+ );+ layersRef.current = next;+ setLayers(next);+ if (target.expressionColor === 'monochrome') activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Monochrome Expression',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'expression-color'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Bake previewed expression color permanently into SparseTileGrid tiles (tile-native, zero full-doc canvas)const applyExpressionColorOfPreview = useCallback((id: string): { tileDeltas: TileDelta[] } | null => {- const target = layers.find((l) => l.id === id);- if (!target || target.type === 'folder') return null;+ const target = layersRef.current.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return null;const exprMode = target.expressionColor || 'color';if (exprMode === 'color') return null;@@ -241,14 +394,15 @@ export function useLayerEffects(updateLayerThumbnail(id, true);return { tileDeltas };},- [activeTileGridRef, layers, updateLayerThumbnail]+ [activeTileGridRef, layersRef, updateLayerThumbnail]);// Bake layer color tint permanently into SparseTileGrid tiles and disable layerColorEnabledconst applyLayerColorPermanently = useCallback(- (id: string): { tileDeltas: TileDelta[] } | null => {- const target = layers.find((l) => l.id === id);- if (!target || target.type === 'folder' || !target.layerColorEnabled) return null;+ (id: string): { tileDeltas: TileDelta[]; layerTreeDelta: LayerTreeDelta } | null => {+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target) || !target.layerColorEnabled) return null;const grid = activeTileGridRef.current;const beforeSnapshot = new Map<string, TileSnapshotEntry>();@@ -266,20 +420,26 @@ export function useLayerEffects(});- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l))+ const next = prev.map((l) => (l.id === id ? { ...l, layerColorEnabled: false } : l));+ layersRef.current = next;+ setLayers(next);+ const layerTreeDelta = createLayerTreeSnapshotDelta(+ prev,+ next,+ activeLayerIdRef.current,+ activeLayerIdRef.current);if (!modified) {grid.notifyChange(true);- return { tileDeltas: [] };+ return { tileDeltas: [], layerTreeDelta };}const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, id);updateLayerThumbnail(id, true);- return { tileDeltas };+ return { tileDeltas, layerTreeDelta };},- [activeTileGridRef, layers, setLayers, updateLayerThumbnail]+ [activeLayerIdRef, activeTileGridRef, layersRef, setLayers, updateLayerThumbnail]);// Direct permanent conversion of any layer to Color, Gray, or Monochrome (tile-native)@@ -288,9 +448,10 @@ export function useLayerEffects(id: string,targetMode: ExpressionColor,options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }- ): { tileDeltas: TileDelta[] } | null => {- const target = layers.find((l) => l.id === id);- if (!target || target.type === 'folder') return null;+ ): { tileDeltas: TileDelta[]; layerTreeDelta: LayerTreeDelta } | null => {+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return null;const grid = activeTileGridRef.current;const beforeSnapshot = new Map<string, TileSnapshotEntry>();@@ -334,12 +495,20 @@ export function useLayerEffects(grid.setLayerFormat(id, targetFormat);const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, id);- setLayers((prev) => prev.map((l) => (l.id === id ? updatedLayer : l)));+ const next = prev.map((l) => (l.id === id ? updatedLayer : l));+ layersRef.current = next;+ setLayers(next);grid.notifyChange(true);updateLayerThumbnail(id, true);- return { tileDeltas };+ const layerTreeDelta = createLayerTreeSnapshotDelta(+ prev,+ next,+ activeLayerIdRef.current,+ activeLayerIdRef.current+ );+ return { tileDeltas, layerTreeDelta };},- [activeTileGridRef, layers, setLayers, updateLayerThumbnail]+ [activeLayerIdRef, activeTileGridRef, layersRef, setLayers, updateLayerThumbnail]);return {diff --git a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts b/src/hooks/layerManager/useLayerPropertiesAndMasks.tsindex dc721c2..22a8ec2 100644--- a/src/hooks/layerManager/useLayerPropertiesAndMasks.ts+++ b/src/hooks/layerManager/useLayerPropertiesAndMasks.ts@@ -4,14 +4,15 @@ import {BlendMode,LayerItem,LayerStyles,+ TileDelta,isFolderLikeLayer,} from '../../types/editor';import { createCanvasThumbnail, get2DContext } from '../../utils/canvasUtils';import { multiplayerService } from '../../services/multiplayerService';-import { releaseTemporaryCanvas } from '../../utils/tileEngine';import {computeBatchLock,computeBatchVisibility,+ createLayerTreeSnapshotDelta,isBackgroundLayerId,} from './layerTreeOps';import { LayerCanvasRegistryApi, LayerManagerContext } from './types';@@ -25,144 +26,259 @@ export function useLayerPropertiesAndMasks(activeTileGridRef,setLayers,layersRef,- activeLayerId,+ activeLayerIdRef,setActiveLayerId,selectedLayerIdsRef,+ recordLayerHistory,} = ctx;const { updateLayerThumbnail } = canvasRegistry;// Toggle visibility of a layer or folder (batch toggle if part of multi-selection)const toggleVisibility = useCallback((id: string) => {- setLayers((prev) => computeBatchVisibility(prev, selectedLayerIdsRef.current, id));- }, [selectedLayerIdsRef, setLayers]);+ const prev = layersRef.current;+ const next = computeBatchVisibility(prev, selectedLayerIdsRef.current, id);+ if (next === prev) return;+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Toggle Visibility',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Set layer opacity (0.0 to 1.0)const setOpacity = useCallback((id: string, opacity: number) => {const clamped = Math.max(0, Math.min(1, opacity));- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, opacity: clamped } : l))+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || Math.abs(target.opacity - clamped) < 0.0001) return;+ const next = prev.map((l) => (l.id === id ? { ...l, opacity: clamped } : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Layer Opacity',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ coalesceKey: `opacity:${id}`,+ }),+ undefined,+ 'layer');- }, [setLayers]);+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Set layer blend modeconst setBlendMode = useCallback((id: string, blendMode: BlendMode) => {- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, blendMode } : l))+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || target.blendMode === blendMode) return;+ const next = prev.map((l) => (l.id === id ? { ...l, blendMode } : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ `Blend Mode (${blendMode})`,+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer');- }, [setLayers]);+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle locked state (batch toggle if part of multi-selection)const toggleLock = useCallback((id: string) => {- setLayers((prev) => computeBatchLock(prev, selectedLayerIdsRef.current, id));- }, [selectedLayerIdsRef, setLayers]);+ const prev = layersRef.current;+ const next = computeBatchLock(prev, selectedLayerIdsRef.current, id);+ if (next === prev) return;+ layersRef.current = next;+ setLayers(next);+ recordLayerHistory(+ 'Toggle Layer Lock',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, layersRef, recordLayerHistory, selectedLayerIdsRef, setLayers]);// Toggle folder collapse stateconst toggleCollapse = useCallback((id: string) => {- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l))- );- }, [setLayers]);+ setLayers((prev) => {+ const next = prev.map((l) => (l.id === id ? { ...l, collapsed: !l.collapsed } : l));+ layersRef.current = next;+ return next;+ });+ }, [layersRef, setLayers]);// Toggle clipping mask state (Clip to Layer Below)const toggleClipping = useCallback((id: string) => {- setLayers((prev) => {- const idx = prev.findIndex((l) => l.id === id);- if (idx === -1 || idx === prev.length - 1 || isBackgroundLayerId(id)) {- return prev;- }- return prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));- });- }, [setLayers]);+ const prev = layersRef.current;+ const idx = prev.findIndex((l) => l.id === id);+ if (idx === -1 || idx === prev.length - 1 || isBackgroundLayerId(id)) {+ return;+ }+ const next = prev.map((l) => (l.id === id ? { ...l, clipped: !l.clipped } : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Toggle Clipping Mask',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle alpha locked state (Lock Transparent Pixels)const toggleAlphaLock = useCallback((id: string) => {- setLayers((prev) =>- prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l))+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target) return;+ const next = prev.map((l) => (l.id === id ? { ...l, alphaLocked: !l.alphaLocked } : l));+ layersRef.current = next;+ setLayers(next);+ recordLayerHistory(+ 'Toggle Alpha Lock',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer');- }, [setLayers]);+ }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);// Add a non-destructive grayscale Layer Maskconst addLayerMask = useCallback((layerId: string) => {- setLayers((prev) =>- prev.map((l) => {- if (l.id !== layerId) return l;- if (l.maskCanvas) return l; // Already has mask+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === layerId);+ if (!target || target.maskCanvas) return;- const mask = document.createElement('canvas');- mask.width = dimensions.width;- mask.height = dimensions.height;- const mCtx = get2DContext(mask);- if (mCtx) {- mCtx.fillStyle = '#ffffff';- mCtx.fillRect(0, 0, mask.width, mask.height);- }- const thumb = createCanvasThumbnail(mask, false);- return {- ...l,- maskCanvas: mask,- maskEnabled: true,- maskLinked: true,- maskThumbnailUrl: thumb,- maskVersion: 1,- };- })+ const mask = document.createElement('canvas');+ mask.width = dimensions.width;+ mask.height = dimensions.height;+ const mCtx = get2DContext(mask);+ if (mCtx) {+ mCtx.fillStyle = '#ffffff';+ mCtx.fillRect(0, 0, mask.width, mask.height);+ }+ const thumb = createCanvasThumbnail(mask, false);+ const next = prev.map((l) =>+ l.id === layerId+ ? {+ ...l,+ maskCanvas: mask,+ maskEnabled: true,+ maskLinked: true,+ maskThumbnailUrl: thumb,+ maskVersion: 1,+ }+ : l);+ layersRef.current = next;+ setLayers(next);activeTileGridRef.current.notifyChange(true);- }, [activeTileGridRef, dimensions, setLayers]);+ recordLayerHistory(+ 'Add Layer Mask',+ layerId,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current, {+ cloneMasks: true,+ }),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers]);// Remove or apply layer mask (directly onto SparseTileGrid tiles, zero full-doc layer canvas)const removeLayerMask = useCallback((layerId: string, apply: boolean = false) => {- const grid = activeTileGridRef.current;- setLayers((prev) =>- prev.map((l) => {- if (l.id !== layerId || !l.maskCanvas) return l;+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === layerId);+ if (!target || !target.maskCanvas) return;- if (apply) {- const beforeSnap = multiplayerService.isConnected()- ? grid.snapshotLayerTiles(layerId)- : null;- grid.applyMaskCanvasToLayer(layerId, l.maskCanvas, dimensions);- if (beforeSnap && multiplayerService.isConnected()) {- const deltas = grid.computeDeltasFromSnapshot(beforeSnap, layerId);- if (deltas.length > 0) {- multiplayerService.sendTileDeltas(deltas, grid, { force: true });- }- }- updateLayerThumbnail(layerId, true);- }+ const grid = activeTileGridRef.current;+ let tileDeltas: TileDelta[] = [];- releaseTemporaryCanvas(l.maskCanvas);+ if (apply) {+ const beforeSnap = grid.snapshotLayerTiles(layerId);+ grid.applyMaskCanvasToLayer(layerId, target.maskCanvas, dimensions);+ tileDeltas = grid.computeDeltasFromSnapshot(beforeSnap, layerId);+ if (tileDeltas.length > 0 && multiplayerService.isConnected()) {+ multiplayerService.sendTileDeltas(tileDeltas, grid, { force: true });+ }+ updateLayerThumbnail(layerId, true);+ }- return {- ...l,- maskCanvas: undefined,- maskEnabled: undefined,- maskLinked: undefined,- maskThumbnailUrl: undefined,- maskVersion: undefined,- };- })+ const next = prev.map((l) =>+ l.id === layerId+ ? {+ ...l,+ maskCanvas: undefined,+ maskEnabled: undefined,+ maskLinked: undefined,+ maskThumbnailUrl: undefined,+ maskVersion: undefined,+ }+ : l);+ const delta = createLayerTreeSnapshotDelta(+ prev,+ next,+ activeLayerIdRef.current,+ activeLayerIdRef.current,+ { cloneMasks: true }+ );+ layersRef.current = next;+ setLayers(next);grid.notifyChange(true);+ recordLayerHistory(+ apply ? 'Apply Layer Mask' : 'Delete Layer Mask',+ layerId,+ delta,+ tileDeltas,+ 'layer'+ );},- [activeTileGridRef, dimensions, setLayers, updateLayerThumbnail]+ [activeLayerIdRef, activeTileGridRef, dimensions, layersRef, recordLayerHistory, setLayers, updateLayerThumbnail]);// Toggle layer mask enabled stateconst toggleLayerMask = useCallback((layerId: string) => {- setLayers((prev) =>- prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l))- );+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === layerId);+ if (!target || !target.maskCanvas) return;+ const next = prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l));+ layersRef.current = next;+ setLayers(next);activeTileGridRef.current.notifyChange(true);- }, [activeTileGridRef, setLayers]);+ recordLayerHistory(+ 'Toggle Layer Mask',+ layerId,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Toggle mask linked stateconst toggleMaskLinked = useCallback((layerId: string) => {- setLayers((prev) =>- prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l))+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === layerId);+ if (!target || !target.maskCanvas) return;+ const next = prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l));+ layersRef.current = next;+ setLayers(next);+ recordLayerHistory(+ 'Toggle Mask Link',+ layerId,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer');- }, [setLayers]);+ }, [activeLayerIdRef, layersRef, recordLayerHistory, setLayers]);// Update mask thumbnailconst updateMaskThumbnail = useCallback((layerId: string, immediate: boolean = false) => {@@ -193,7 +309,8 @@ export function useLayerPropertiesAndMasks(type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',customData?: AdjustmentLayerData): LayerItem => {- let createdLayer: LayerItem | null = null;+ const prev = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;const id = `adjustment-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;let defaultData: AdjustmentLayerData;@@ -247,64 +364,90 @@ export function useLayerPropertiesAndMasks(break;}- setLayers((prev) => {- const activeIdx = prev.findIndex((l) => l.id === activeLayerId);- const activeLayer = prev[activeIdx];- const parentId = activeLayer ? (activeLayer.type === 'folder' ? activeLayer.id : activeLayer.parentId) : null;-- let count = 1;- const base = layerName.replace(/ \d+$/, '');- prev.forEach((l) => {- if (l.name.startsWith(base)) {- const num = parseInt(l.name.replace(`${base} `, ''), 10);- if (!isNaN(num) && num >= count) count = num + 1;- }- });- const name = `${base} ${count}`;-- const newLayer: LayerItem = {- id,- name,- type: 'adjustment',- visible: true,- opacity: 1,- blendMode: 'normal',- locked: false,- collapsed: false,- parentId,- adjustmentData: defaultData,- };- createdLayer = newLayer;+ const activeIdx = prev.findIndex((l) => l.id === beforeActiveLayerId);+ const activeLayer = prev[activeIdx];+ const parentId = activeLayer+ ? isFolderLikeLayer(activeLayer)+ ? activeLayer.id+ : activeLayer.parentId+ : null;- const insertIndex = activeIdx >= 0 ? activeIdx : 0;- const next = [...prev];- next.splice(insertIndex, 0, newLayer);- return next;+ let count = 1;+ const base = layerName.replace(/ \d+$/, '');+ prev.forEach((l) => {+ if (l.name.startsWith(base)) {+ const num = parseInt(l.name.replace(`${base} `, ''), 10);+ if (!isNaN(num) && num >= count) count = num + 1;+ }});+ const name = `${base} ${count}`;+ const newLayer: LayerItem = {+ id,+ name,+ type: 'adjustment',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ collapsed: false,+ parentId,+ adjustmentData: defaultData,+ };++ const insertIndex = activeIdx >= 0 ? activeIdx : 0;+ const next = [...prev];+ next.splice(insertIndex, 0, newLayer);+ layersRef.current = next;+ setLayers(next);setActiveLayerId(id);activeTileGridRef.current.notifyChange(true);- return createdLayer!;+ recordLayerHistory(+ `Add ${name}`,+ id,+ createLayerTreeSnapshotDelta(prev, next, beforeActiveLayerId, id),+ undefined,+ 'layer'+ );+ return newLayer;},- [activeLayerId, activeTileGridRef, setActiveLayerId, setLayers]+ [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setActiveLayerId, setLayers]);// Update adjustment layer dataconst updateAdjustmentData = useCallback((layerId: string, data: AdjustmentLayerData) => {- setLayers((prev) =>- prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l))- );+ const prev = layersRef.current;+ if (!prev.some((l) => l.id === layerId)) return;+ const next = prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l));+ layersRef.current = next;+ setLayers(next);activeTileGridRef.current.notifyChange(true);- }, [activeTileGridRef, setLayers]);+ recordLayerHistory(+ 'Update Adjustment',+ layerId,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);// Update Layer Styles (Stroke, Drop Shadow, Outer Glow)const updateLayerStyles = useCallback((id: string, styles: LayerStyles) => {- setLayers((prev) => {- const target = prev.find((l) => l.id === id);- if (!target || isFolderLikeLayer(target)) return prev;- return prev.map((l) => (l.id === id ? { ...l, styles } : l));- });- }, [setLayers]);+ const prev = layersRef.current;+ const target = prev.find((l) => l.id === id);+ if (!target || isFolderLikeLayer(target)) return;+ const next = prev.map((l) => (l.id === id ? { ...l, styles } : l));+ layersRef.current = next;+ setLayers(next);+ activeTileGridRef.current.notifyChange(true);+ recordLayerHistory(+ 'Layer Styles',+ id,+ createLayerTreeSnapshotDelta(prev, next, activeLayerIdRef.current, activeLayerIdRef.current),+ undefined,+ 'layer'+ );+ }, [activeLayerIdRef, activeTileGridRef, layersRef, recordLayerHistory, setLayers]);return {toggleVisibility,diff --git a/src/hooks/layerManager/useLayerSpecialLayers.ts b/src/hooks/layerManager/useLayerSpecialLayers.tsindex b06b4df..148ba0f 100644--- a/src/hooks/layerManager/useLayerSpecialLayers.ts+++ b/src/hooks/layerManager/useLayerSpecialLayers.ts@@ -18,6 +18,7 @@ import {applyLayerTreeDelta as applyLayerTreeDeltaPure,cloneComicFrames,cloneLayerItemForHistory,+ createLayerTreeSnapshotDelta,} from './layerTreeOps';import { LayerManagerContext } from './types';@@ -52,6 +53,8 @@ export function useLayerSpecialLayers(layersRef,setActiveLayerId,activeLayerIdRef,+ suppressHistoryDepthRef,+ recordLayerHistory,} = ctx;// Create or update a non-destructive Vector Text Layer (re-renders crisply into tileGrid)@@ -60,41 +63,96 @@ export function useLayerSpecialLayers(const grid = activeTileGridRef.current;const dims = dimensionsRef.current;const snippet = textData.text.trim().replace(/\s+/g, ' ').slice(0, 22) || 'Text';+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;if (editingLayerId) {- const existing = layersRef.current.find((l) => l.id === editingLayerId);+ const existing = beforeLayers.find((l) => l.id === editingLayerId);if (existing && existing.type === 'text') {+ const beforeTileSnap = grid.snapshotLayerTiles(editingLayerId);const updated: LayerItem = {...existing,name: snippet,textData: { ...textData },};- setLayers((prev) => {- const next = prev.map((l) => (l.id === editingLayerId ? updated : l));- layersRef.current = next;- return next;- });+ const nextLayers = beforeLayers.map((l) => (l.id === editingLayerId ? updated : l));+ layersRef.current = nextLayers;+ setLayers(nextLayers);syncVectorObjectLayerToGrid(updated, dims, grid);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeTileSnap, editingLayerId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });+ for (const t of grid.getLayerTiles(editingLayerId, 0)) {+ const key = getTileKey(editingLayerId, t.tileX, t.tileY, 0);+ if (t.data && !beforeTileSnap.has(key) && !tileDeltas.some((d) => d.key === key)) {+ tileDeltas.push({ key, format: t.format, beforeData: null, afterData: new Uint8Array(t.data) });+ }+ }updateLayerThumbnail(editingLayerId, true);+ recordLayerHistory(+ 'Edit Text Layer',+ editingLayerId,+ createLayerTreeSnapshotDelta(+ beforeLayers,+ layersRef.current,+ beforeActiveLayerId,+ activeLayerIdRef.current+ ),+ tileDeltas,+ 'text'+ );return updated;}}- const created = addLayer('text', undefined, snippet, undefined, true);+ suppressHistoryDepthRef.current += 1;+ let created: LayerItem;+ try {+ created = addLayer('text', undefined, snippet, undefined, true);+ } finally {+ suppressHistoryDepthRef.current = Math.max(0, suppressHistoryDepthRef.current - 1);+ }const withData: LayerItem = {...created,textData: { ...textData },};- setLayers((prev) => {- const next = prev.map((l) => (l.id === created.id ? { ...l, textData: { ...textData } } : l));- layersRef.current = next;- return next;- });+ const nextLayers = layersRef.current.map((l) =>+ l.id === created.id ? { ...l, textData: { ...textData } } : l+ );+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ const beforeTileSnap = grid.snapshotLayerTiles(created.id);syncVectorObjectLayerToGrid(withData, dims, grid);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeTileSnap, created.id, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });updateLayerThumbnail(created.id, true);+ recordLayerHistory(+ 'Add Text Layer',+ created.id,+ createLayerTreeSnapshotDelta(beforeLayers, layersRef.current, beforeActiveLayerId, created.id),+ tileDeltas,+ 'text'+ );return withData;},- [activeTileGridRef, addLayer, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]+ [+ activeLayerIdRef,+ activeTileGridRef,+ addLayer,+ dimensionsRef,+ layersRef,+ recordLayerHistory,+ setLayers,+ suppressHistoryDepthRef,+ updateLayerThumbnail,+ ]);// Create or update a non-destructive Speech Balloon Layer (re-renders crisply into tileGrid)@@ -105,41 +163,96 @@ export function useLayerSpecialLayers(const clonedBalloon: SpeechBalloon = JSON.parse(JSON.stringify(balloonData));const snippet = clonedBalloon.text.trim().replace(/\s+/g, ' ').slice(0, 18);const label = snippet ? `Balloon: ${snippet}` : undefined;+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;if (editingLayerId) {- const existing = layersRef.current.find((l) => l.id === editingLayerId);+ const existing = beforeLayers.find((l) => l.id === editingLayerId);if (existing && existing.type === 'balloon') {+ const beforeTileSnap = grid.snapshotLayerTiles(editingLayerId);const updated: LayerItem = {...existing,name: label || existing.name,balloonData: clonedBalloon,};- setLayers((prev) => {- const next = prev.map((l) => (l.id === editingLayerId ? updated : l));- layersRef.current = next;- return next;- });+ const nextLayers = beforeLayers.map((l) => (l.id === editingLayerId ? updated : l));+ layersRef.current = nextLayers;+ setLayers(nextLayers);syncVectorObjectLayerToGrid(updated, dims, grid);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeTileSnap, editingLayerId, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });+ for (const t of grid.getLayerTiles(editingLayerId, 0)) {+ const key = getTileKey(editingLayerId, t.tileX, t.tileY, 0);+ if (t.data && !beforeTileSnap.has(key) && !tileDeltas.some((d) => d.key === key)) {+ tileDeltas.push({ key, format: t.format, beforeData: null, afterData: new Uint8Array(t.data) });+ }+ }updateLayerThumbnail(editingLayerId, true);+ recordLayerHistory(+ 'Edit Speech Balloon',+ editingLayerId,+ createLayerTreeSnapshotDelta(+ beforeLayers,+ layersRef.current,+ beforeActiveLayerId,+ activeLayerIdRef.current+ ),+ tileDeltas,+ 'balloon'+ );return updated;}}- const created = addLayer('balloon', undefined, label, undefined, true);+ suppressHistoryDepthRef.current += 1;+ let created: LayerItem;+ try {+ created = addLayer('balloon', undefined, label, undefined, true);+ } finally {+ suppressHistoryDepthRef.current = Math.max(0, suppressHistoryDepthRef.current - 1);+ }const withData: LayerItem = {...created,balloonData: clonedBalloon,};- setLayers((prev) => {- const next = prev.map((l) => (l.id === created.id ? { ...l, balloonData: clonedBalloon } : l));- layersRef.current = next;- return next;- });+ const nextLayers = layersRef.current.map((l) =>+ l.id === created.id ? { ...l, balloonData: clonedBalloon } : l+ );+ layersRef.current = nextLayers;+ setLayers(nextLayers);+ const beforeTileSnap = grid.snapshotLayerTiles(created.id);syncVectorObjectLayerToGrid(withData, dims, grid);+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeTileSnap, created.id, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,+ });updateLayerThumbnail(created.id, true);+ recordLayerHistory(+ 'Add Speech Balloon',+ created.id,+ createLayerTreeSnapshotDelta(beforeLayers, layersRef.current, beforeActiveLayerId, created.id),+ tileDeltas,+ 'balloon'+ );return withData;},- [activeTileGridRef, addLayer, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]+ [+ activeLayerIdRef,+ activeTileGridRef,+ addLayer,+ dimensionsRef,+ layersRef,+ recordLayerHistory,+ setLayers,+ suppressHistoryDepthRef,+ updateLayerThumbnail,+ ]);// Create a true Manga Frame Border Folder with auto-clipping & initial child raster layer@@ -247,7 +360,7 @@ export function useLayerSpecialLayers(grid.notifyChange(true);const layerTreeDelta: LayerTreeDelta = {- addedLayers: addedLayers.map(cloneLayerItemForHistory),+ addedLayers: addedLayers.map((l) => cloneLayerItemForHistory(l)),insertBeforeLayerId,insertIndex,beforeActiveLayerId,@@ -375,7 +488,7 @@ export function useLayerSpecialLayers(return {divided: true,layerTreeDelta: {- addedLayers: addedLayers.map(cloneLayerItemForHistory),+ addedLayers: addedLayers.map((l) => cloneLayerItemForHistory(l)),insertBeforeLayerId: folder.id,insertIndex: folderIdx,updatedLayers: [@@ -412,22 +525,20 @@ export function useLayerSpecialLayers(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);+ for (const delId of syncResult.removedLayerIds) {+ const timer = thumbDebounceTimersRef.current.get(delId);+ if (timer) {+ clearTimeout(timer);+ thumbDebounceTimersRef.current.delete(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);- }+ grid.clearLayer(delId);+ }++ 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);}}@@ -435,6 +546,7 @@ export function useLayerSpecialLayers(setActiveLayerId(syncResult.nextActiveLayerId);}+ grid.notifyChange(true);return syncResult;},[activeLayerIdRef, activeTileGridRef, layersRef, setActiveLayerId, setLayers, thumbDebounceTimersRef]@@ -443,7 +555,9 @@ export function useLayerSpecialLayers(// Rasterize a non-destructive text, balloon, or vector layer into a standard raster layerconst rasterizeLayer = useCallback((id: string): boolean => {- const target = layersRef.current.find((l) => l.id === id);+ const beforeLayers = layersRef.current;+ const beforeActiveLayerId = activeLayerIdRef.current;+ const target = beforeLayers.find((l) => l.id === id);if (!target) return false;if (target.type !== 'text' && target.type !== 'balloon' && target.type !== 'vector') {return false;@@ -451,29 +565,48 @@ export function useLayerSpecialLayers(const grid = activeTileGridRef.current;const dims = dimensionsRef.current;+ const beforeTileSnap = grid.snapshotLayerTiles(id);if (target.type === 'text' || target.type === 'balloon') {syncVectorObjectLayerToGrid(target, dims, grid);}- setLayers((prev) => {- const next = prev.map((l) => {- if (l.id !== id) return l;- const { textData: _td, balloonData: _bd, vectorStrokes: _vs, ...rest } = l;- return {- ...rest,- type: 'raster' as const,- };- });- layersRef.current = next;- return next;+ const nextLayers = beforeLayers.map((l) => {+ if (l.id !== id) return l;+ const { textData: _td, balloonData: _bd, vectorStrokes: _vs, ...rest } = l;+ return {+ ...rest,+ type: 'raster' as const,+ };+ });+ layersRef.current = nextLayers;+ setLayers(nextLayers);++ const tileDeltas = grid.computeDeltasFromSnapshot(beforeTileSnap, id, {+ x: 0,+ y: 0,+ width: dims.width,+ height: dims.height,});+ for (const t of grid.getLayerTiles(id, 0)) {+ const key = getTileKey(id, t.tileX, t.tileY, 0);+ if (t.data && !beforeTileSnap.has(key) && !tileDeltas.some((d) => d.key === key)) {+ tileDeltas.push({ key, format: t.format, beforeData: null, afterData: new Uint8Array(t.data) });+ }+ }updateLayerThumbnail(id, true);grid.notifyChange(true);+ recordLayerHistory(+ 'Rasterize Layer',+ id,+ createLayerTreeSnapshotDelta(beforeLayers, nextLayers, beforeActiveLayerId, activeLayerIdRef.current),+ tileDeltas,+ 'layer-convert'+ );return true;},- [activeTileGridRef, dimensionsRef, layersRef, setLayers, updateLayerThumbnail]+ [activeLayerIdRef, activeTileGridRef, dimensionsRef, layersRef, recordLayerHistory, setLayers, updateLayerThumbnail]);return {diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsxindex afc1ad4..27ad199 100644--- a/src/hooks/useAppMenuSections.tsx+++ b/src/hooks/useAppMenuSections.tsx@@ -89,6 +89,8 @@ export interface UseAppMenuSectionsParams {handleContractSelection: (pixels?: number) => void;handleFeatherSelection: (radius?: number) => void;handleAddLayer: (type?: 'raster' | 'folder') => void;+ handleFillScreentone?: () => void;+ toggleTone?: (layerId: string) => void;handleOpenAdjustmentModal: (layerId?: string,initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance'@@ -99,6 +101,7 @@ export interface UseAppMenuSectionsParams {toggleMaskLinked: (layerId: string) => void;duplicateLayer: (layerId: string) => void;handleMergeDown: () => void;+ handleMergeFolder?: (folderId?: string) => void;handleOpenLayerStylesModal: (layerId?: string) => void;toggleLayerColor: (layerId: string) => void;handleConvertLayer: (layerId: string, mode: ExpressionColor) => void;@@ -166,6 +169,8 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleContractSelection,handleFeatherSelection,handleAddLayer,+ handleFillScreentone,+ toggleTone,handleOpenAdjustmentModal,addLayerMask,removeLayerMask,@@ -173,6 +178,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiotoggleMaskLinked,duplicateLayer,handleMergeDown,+ handleMergeFolder,handleOpenLayerStylesModal,toggleLayerColor,handleConvertLayer,@@ -618,11 +624,20 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiodisabled: !hasOpenDocument,onClick: () => handleAddLayer('folder'),},+ {+ id: 'layer-new-screentone',+ label: 'New Screentone Layer...',+ disabled: !hasOpenDocument || !handleFillScreentone,+ onClick: () => handleFillScreentone?.(),+ },{id: 'layer-new-3d',label: 'New 3D Reference Layer...',disabled: !hasOpenDocument,- onClick: () => uiStoreActions.set3DLayerOpen(true),+ onClick: () => {+ toolStoreActions.selectTool('3d');+ uiStoreActions.set3DLayerOpen(true);+ },},{id: 'layer-new-adjustment',@@ -719,6 +734,17 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiodisabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || layers.length <= 1,onClick: handleMergeDown,},+ {+ id: 'layer-merge-folder',+ label: 'Merge Folder',+ disabled:+ !hasOpenDocument ||+ !activeLayer ||+ !isFolderLikeLayer(activeLayer) ||+ activeLayer.locked ||+ !handleMergeFolder,+ onClick: () => activeLayer && handleMergeFolder?.(activeLayer.id),+ },{ id: 'layer-div-effects', label: '', divider: true },{id: 'layer-styles',@@ -730,6 +756,14 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectioactiveLayer.type === 'adjustment',onClick: () => handleOpenLayerStylesModal(activeLayerId),},+ {+ id: 'layer-toggle-tone',+ label: activeLayer?.toneEnabled+ ? 'Disable Screentone'+ : 'Enable Screentone',+ disabled: !hasOpenDocument || !activeLayer || isFolderLikeLayer(activeLayer) || !toggleTone,+ onClick: () => toggleTone?.(activeLayerId),+ },{id: 'layer-toggle-tint',label: activeLayer?.layerColorEnabled@@ -1446,9 +1480,11 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiohandleExpandSelection,handleExportImage,handleFeatherSelection,+ handleFillScreentone,handleFillSelectionColor,handleInvertSelection,handleMergeDown,+ handleMergeFolder,handleMoveSelectionToNewLayer,handleOpenAdjustmentModal,handleOpenLayerStylesModal,@@ -1490,6 +1526,7 @@ export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSectiotoggleLayerColor,toggleLayerMask,toggleMaskLinked,+ toggleTone,visiblePanels,zoomIn,zoomOut,diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.tsindex b18c64c..dd2262f 100644--- a/src/hooks/useLayerManager.ts+++ b/src/hooks/useLayerManager.ts@@ -1,5 +1,5 @@import { useState, useRef, useCallback, useEffect } from 'react';-import { CanvasDimensions, LayerItem } from '../types/editor';+import { CanvasDimensions, HistoryActionType, LayerItem, LayerTreeDelta, TileDelta } from '../types/editor';import { SparseTileGrid, globalTileGrid } from '../utils/tileEngine';import { documentStore } from '../utils/documentStore';import { recoveryService } from '../services/recoveryService';@@ -22,13 +22,21 @@ export {computeLayerSelection,computeBatchDeleteLayers,computeGroupLayers,+ getFolderDescendantIds,+ computeMergeFolderLayers,computeBatchReorderLayers,computeBatchVisibility,computeBatchLock,applyLayerTreeDelta,+ createLayerTreeSnapshotDelta,} from './layerManager/layerTreeOps';-export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileGrid }: UseLayerManagerProps) {+export function useLayerManager({+ dimensions: _dimensions,+ activeSessionId,+ tileGrid,+ pushHistoryStepRef,+}: UseLayerManagerProps) {// Active document's SparseTileGrid (isolated per document tab)const activeTileGridRef = useRef<SparseTileGrid>(tileGrid ?? (activeSessionId ? documentStore.getOrCreateSession(activeSessionId).tileGrid : globalTileGrid)@@ -146,6 +154,47 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tilesetSelectedLayerIds(res.nextSelectedIds);}, [setSelectedLayerIds]);+ const suppressHistoryDepthRef = useRef<number>(0);++ const recordLayerHistory = useCallback(+ (+ label: string,+ targetLayerId: string,+ layerTreeDelta?: LayerTreeDelta,+ tileDeltas?: TileDelta[],+ actionType: HistoryActionType = 'layer'+ ) => {+ if (suppressHistoryDepthRef.current > 0) return;+ const pushFn = pushHistoryStepRef?.current;+ if (!pushFn) return;+ if (!layerTreeDelta && (!tileDeltas || tileDeltas.length === 0)) return;+ pushFn(+ actionType,+ label,+ null,+ null,+ targetLayerId,+ undefined,+ tileDeltas && tileDeltas.length > 0 ? tileDeltas : undefined,+ undefined,+ undefined,+ undefined,+ false,+ layerTreeDelta+ );+ },+ [pushHistoryStepRef]+ );++ const runWithoutLayerHistory = useCallback(<T,>(fn: () => T): T => {+ suppressHistoryDepthRef.current += 1;+ try {+ return fn();+ } finally {+ suppressHistoryDepthRef.current = Math.max(0, suppressHistoryDepthRef.current - 1);+ }+ }, []);+const ctx: LayerManagerContext = {dimensions: _dimensions,activeTileGridRef,@@ -162,6 +211,8 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileselectedLayerIds,setSelectedLayerIds,selectedLayerIdsRef,+ suppressHistoryDepthRef,+ recordLayerHistory,};const canvasRegistry = useLayerCanvasRegistry(ctx);@@ -238,6 +289,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileisLayerEffectivelyVisible: crud.isLayerEffectivelyVisible,clearActiveLayer: documentOps.clearActiveLayer,mergeDown: documentOps.mergeDown,+ mergeFolder: documentOps.mergeFolder,resetToNewCanvas: documentOps.resetToNewCanvas,setDefaultToneFrequency: (freq: number) => {defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(freq || 60)));@@ -248,6 +300,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tileaddLayerMask: propertiesAndMasks.addLayerMask,removeLayerMask: propertiesAndMasks.removeLayerMask,toggleLayerMask: propertiesAndMasks.toggleLayerMask,+ runWithoutLayerHistory,toggleMaskLinked: propertiesAndMasks.toggleMaskLinked,updateMaskThumbnail: propertiesAndMasks.updateMaskThumbnail,addAdjustmentLayer: propertiesAndMasks.addAdjustmentLayer,diff --git a/src/hooks/useTonalAndFilterActions.ts b/src/hooks/useTonalAndFilterActions.tsindex 9f0997a..70b23f9 100644--- a/src/hooks/useTonalAndFilterActions.ts+++ b/src/hooks/useTonalAndFilterActions.ts@@ -8,6 +8,7 @@ import {FilterType,LayerItem,LayerStyles,+ LayerTreeDelta,TileDelta,} from '../types/editor';import { documentStore } from '../utils/documentStore';@@ -100,18 +101,18 @@ export interface UseTonalAndFilterActionsParams {angle: number,dotShape: HalftoneDotShape,densityType: 'specified' | 'image'- ) => { id: string; tileDeltas: TileDelta[] };+ ) => { id: string; tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta };applyExpressionColorOfPreview: (layerId: string) => { tileDeltas: TileDelta[] } | null | undefined;applyLayerColorPermanently: (layerId: string- ) => { tileDeltas: TileDelta[] } | null | undefined;+ ) => { tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta } | null | undefined;convertLayer: (layerId: string,targetMode: ExpressionColor,options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }- ) => { tileDeltas: TileDelta[] } | null | undefined;+ ) => { tileDeltas: TileDelta[]; layerTreeDelta?: LayerTreeDelta } | null | undefined;showToast: (msg: string) => void;}@@ -636,7 +637,10 @@ export function useTonalAndFilterActions({const handleConfirmTone = useCallback((settings: SimpleToneSettings) => {uiStoreActions.setToneModalOpen(false);- const { id, tileDeltas } = fillScreentoneSelection(+ if (selection?.floating) {+ handleCommitFloatingSelection();+ }+ const { id, tileDeltas, layerTreeDelta } = fillScreentoneSelection(selection,settings.density,settings.frequency,@@ -644,7 +648,7 @@ export function useTonalAndFilterActions({settings.dotShape,settings.densityType);- if (tileDeltas.length > 0) {+ if (tileDeltas.length > 0 || layerTreeDelta) {pushHistoryStepRef.current?.('screentone',`Screentone (${settings.density}%)`,@@ -652,12 +656,17 @@ export function useTonalAndFilterActions({null,id,selection?.bounds,- tileDeltas+ tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ layerTreeDelta);}showToast(`Created Screentone Layer (${settings.density}%)`);},- [selection, fillScreentoneSelection, pushHistoryStepRef, showToast]+ [selection, handleCommitFloatingSelection, fillScreentoneSelection, pushHistoryStepRef, showToast]);const handleApplyExpressionColor = useCallback(@@ -682,7 +691,7 @@ export function useTonalAndFilterActions({const handleApplyLayerColor = useCallback((layerId: string) => {const result = applyLayerColorPermanently(layerId);- if (result && result.tileDeltas.length > 0) {+ if (result && (result.tileDeltas.length > 0 || result.layerTreeDelta)) {pushHistoryStepRef.current?.('layer-color','Apply Layer Color Tint',@@ -690,7 +699,12 @@ export function useTonalAndFilterActions({null,layerId,undefined,- result.tileDeltas+ result.tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ result.layerTreeDelta);showToast('Applied tint to layer permanently');}@@ -705,7 +719,7 @@ export function useTonalAndFilterActions({options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }) => {const result = convertLayer(layerId, targetMode, options);- if (result && result.tileDeltas.length > 0) {+ if (result && (result.tileDeltas.length > 0 || result.layerTreeDelta)) {pushHistoryStepRef.current?.('layer-convert',`Convert to ${targetMode.toUpperCase()}`,@@ -713,7 +727,12 @@ export function useTonalAndFilterActions({null,layerId,undefined,- result.tileDeltas+ result.tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ result.layerTreeDelta);showToast(`Converted layer to ${targetMode}`);}diff --git a/src/services/bake3DService.ts b/src/services/bake3DService.tsindex 354b6c8..28e22a2 100644--- a/src/services/bake3DService.ts+++ b/src/services/bake3DService.ts@@ -13,6 +13,7 @@ export interface Bake3DOptions {layerName?: string;opacity?: number;blendMode?: BlendMode;+ disposeOnComplete?: boolean;onInsertLayer?: (layer: LayerItem, canvas: HTMLCanvasElement) => void;onBroadcastLayer?: (layer: LayerItem, dataUrl: string) => void;}@@ -236,6 +237,7 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3layerName = '3D Layer',opacity = 1,blendMode = 'normal',+ disposeOnComplete = true,onInsertLayer,onBroadcastLayer,} = options;@@ -277,6 +279,14 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3offscreenRenderer.setSize(renderWidth, renderHeight, false);offscreenRenderer.setPixelRatio(1);offscreenRenderer.setClearColor(0x000000, 0);+ if (activeRenderer && 'toneMapping' in activeRenderer && 'toneMapping' in offscreenRenderer) {+ offscreenRenderer.toneMapping = activeRenderer.toneMapping;+ offscreenRenderer.toneMappingExposure = activeRenderer.toneMappingExposure;+ }+ if (offscreenRenderer.shadowMap && activeRenderer?.shadowMap) {+ offscreenRenderer.shadowMap.enabled = activeRenderer.shadowMap.enabled;+ offscreenRenderer.shadowMap.type = activeRenderer.shadowMap.type;+ }// Synchronize camera projection aspect ratio with document geometryconst renderCamera = camera.clone();@@ -296,17 +306,27 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3const ctx = rasterCanvas.getContext('2d', { willReadFrequently: false });if (!ctx) {- disposeThreeResources(null, offscreenRenderer);+ if (!reusedActiveRenderer) {+ disposeThreeResources(null, offscreenRenderer);+ }throw new Error('Unable to create 2D canvas context for 3D rasterization');}ctx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);const dataUrl = rasterCanvas.toDataURL('image/png');- // 3. Immediate Memory Cleanup: Free WebGL contexts, VRAM buffers, and scene graph- disposeThreeResources(scene, offscreenRenderer);- if (activeRenderer && !reusedActiveRenderer) {- disposeThreeResources(null, activeRenderer);+ // 3. Memory Cleanup: Free offscreen WebGL context; preserve live scene if disposeOnComplete=false+ if (disposeOnComplete) {+ disposeThreeResources(scene, offscreenRenderer);+ if (activeRenderer && !reusedActiveRenderer) {+ disposeThreeResources(null, activeRenderer);+ }+ } else if (reusedActiveRenderer) {+ if (savedActiveSize.x > 0 && savedActiveSize.y > 0) {+ offscreenRenderer.setSize(savedActiveSize.x, savedActiveSize.y, false);+ }+ } else {+ disposeThreeResources(null, offscreenRenderer);}// 4. Construct standard document raster layer@@ -343,20 +363,22 @@ export async function bake3DToRasterLayer(options: Bake3DOptions): Promise<Bake3export interface Bake3DLTOptions {scene: THREE.Scene;camera: THREE.Camera;- dimensions: { width: number; height: number };+ dimensions: { width: number; height: number; dpi?: number };+ dpi?: number;activeRenderer?: THREE.WebGLRenderer | null;modelName?: string;targetFolderName?: string;baseLayerName?: string;lineWidth?: number; // 1 to 5 (default: 1)lineThreshold?: number; // 0.05 to 0.8 (default: 0.28)- toneCount?: number; // 1 to 4 tone layers (default: 2)+ toneCount?: number; // 0 to 4 tone layers (default: 2; 0 = outline only)toneBands?: 2 | 3; // Backward-compatibility alias for toneCounttoneFrequencies?: number[]; // Lines per inch [light, deep, ...] (default: 60)- toneAngles?: number[]; // Halftone grid angles (default: [45, 60, ...])+ toneAngles?: number[]; // Halftone grid angles (default: 45° for all tiers)toneDensities?: number[]; // Density normalized [0-1] (e.g. [0.20, 0.45])- antiAliasing?: boolean;+ antiAliasing?: boolean; // default: false for crisp 1-bit CSP manga lineartdisposeOnComplete?: boolean;+ previewOnly?: boolean;onInsertLayers?: (layers: LayerItem[], canvases: HTMLCanvasElement[]) => void;onBroadcastLayer?: (layer: LayerItem, dataUrl: string) => void;}@@ -407,70 +429,73 @@ const sobelFragmentShader = `return z;}- void main() {- vec2 texel = (max(1.0, uLineWidth) / uResolution);+ float evaluateEdgeAt(vec2 uv, vec2 px) {+ vec4 centerNorm = texture2D(tNormal, uv);+ if (centerNorm.a < 0.5) {+ return 0.0;+ }- vec4 centerNorm = texture2D(tNormal, vUv);- if (centerNorm.a < 0.05) {- gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);- return;+ vec2 uvL = uv + vec2(-px.x, 0.0);+ vec2 uvR = uv + vec2(px.x, 0.0);+ vec2 uvT = uv + vec2(0.0, px.y);+ vec2 uvB = uv + vec2(0.0, -px.y);++ vec4 sL = texture2D(tNormal, uvL);+ vec4 sR = texture2D(tNormal, uvR);+ vec4 sT = texture2D(tNormal, uvT);+ vec4 sB = texture2D(tNormal, uvB);++ // Crisp outer silhouette against transparent background+ if (sL.a < 0.5 || sR.a < 0.5 || sT.a < 0.5 || sB.a < 0.5) {+ return 10.0;}- // Outer silhouette check against 4-neighborhood background- float aL = texture2D(tNormal, vUv + vec2(-texel.x, 0.0)).a;- float aR = texture2D(tNormal, vUv + vec2(texel.x, 0.0)).a;- float aT = texture2D(tNormal, vUv + vec2(0.0, texel.y)).a;- float aB = texture2D(tNormal, vUv + vec2(0.0, -texel.y)).a;+ // Angular normal crease detection (eliminates blurry smudging on smooth curved surfaces)+ vec3 nC = normalize(centerNorm.rgb * 2.0 - 1.0);+ vec3 nL = normalize(sL.rgb * 2.0 - 1.0);+ vec3 nR = normalize(sR.rgb * 2.0 - 1.0);+ vec3 nT = normalize(sT.rgb * 2.0 - 1.0);+ vec3 nB = normalize(sB.rgb * 2.0 - 1.0);++ float creaseH = max(1.0 - clamp(dot(nC, nL), -1.0, 1.0), 1.0 - clamp(dot(nC, nR), -1.0, 1.0));+ float creaseV = max(1.0 - clamp(dot(nC, nT), -1.0, 1.0), 1.0 - clamp(dot(nC, nB), -1.0, 1.0));+ float normalEdge = max(creaseH, creaseV);++ // Second-order depth Laplacian: zero on tilted flat planes, sharp spike on true occlusion steps+ float dC = readDepth(uv);+ float dL = readDepth(uvL);+ float dR = readDepth(uvR);+ float dT = readDepth(uvT);+ float dB = readDepth(uvB);+ float depthLap = abs(dL + dR - 2.0 * dC) + abs(dT + dB - 2.0 * dC);+ float depthEdge = depthLap * 90.0;++ return normalEdge * 1.15 + depthEdge;+ }- if (aL < 0.5 || aR < 0.5 || aT < 0.5 || aB < 0.5) {- gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);- return;+ void main() {+ vec2 px = 1.0 / max(vec2(1.0), uResolution);+ float maxEdge = evaluateEdgeAt(vUv, px);++ // Crisp morphological dilation for lineWidth > 1 (solid stroke, zero hollow/double-edge artifacts)+ if (uLineWidth > 1.5 && maxEdge <= uThreshold) {+ float radius = min(2.5, uLineWidth * 0.5);+ for (int dy = -2; dy <= 2; dy++) {+ for (int dx = -2; dx <= 2; dx++) {+ if (dx == 0 && dy == 0) continue;+ vec2 off = vec2(float(dx), float(dy));+ if (length(off) <= radius) {+ float e = evaluateEdgeAt(vUv + off * px, px);+ if (e > maxEdge) maxEdge = e;+ }+ }+ }}- // 3x3 Sobel sample coordinates- vec2 uv00 = vUv + vec2(-texel.x, -texel.y);- vec2 uv10 = vUv + vec2(0.0, -texel.y);- vec2 uv20 = vUv + vec2(texel.x, -texel.y);- vec2 uv01 = vUv + vec2(-texel.x, 0.0);- vec2 uv21 = vUv + vec2(texel.x, 0.0);- vec2 uv02 = vUv + vec2(-texel.x, texel.y);- vec2 uv12 = vUv + vec2(0.0, texel.y);- vec2 uv22 = vUv + vec2(texel.x, texel.y);-- // Normal discontinuity Sobel filter (crease detection)- vec3 n00 = texture2D(tNormal, uv00).rgb * 2.0 - 1.0;- vec3 n10 = texture2D(tNormal, uv10).rgb * 2.0 - 1.0;- vec3 n20 = texture2D(tNormal, uv20).rgb * 2.0 - 1.0;- vec3 n01 = texture2D(tNormal, uv01).rgb * 2.0 - 1.0;- vec3 n21 = texture2D(tNormal, uv21).rgb * 2.0 - 1.0;- vec3 n02 = texture2D(tNormal, uv02).rgb * 2.0 - 1.0;- vec3 n12 = texture2D(tNormal, uv12).rgb * 2.0 - 1.0;- vec3 n22 = texture2D(tNormal, uv22).rgb * 2.0 - 1.0;-- vec3 gx_n = -n00 + n20 - 2.0 * n01 + 2.0 * n21 - n02 + n22;- vec3 gy_n = -n00 - 2.0 * n10 - n20 + n02 + 2.0 * n12 + n22;- float normalEdge = length(gx_n) + length(gy_n);-- // Depth discontinuity Sobel filter (depth step/silhouette detection)- float d00 = readDepth(uv00);- float d10 = readDepth(uv10);- float d20 = readDepth(uv20);- float d01 = readDepth(uv01);- float d21 = readDepth(uv21);- float d02 = readDepth(uv02);- float d12 = readDepth(uv12);- float d22 = readDepth(uv22);-- float gx_d = -d00 + d20 - 2.0 * d01 + 2.0 * d21 - d02 + d22;- float gy_d = -d00 - 2.0 * d10 - d20 + d02 + 2.0 * d12 + d22;- float depthEdge = sqrt(gx_d * gx_d + gy_d * gy_d) * 160.0;-- float totalEdge = normalEdge * 0.45 + depthEdge * 0.55;-- if (totalEdge > uThreshold) {+ if (maxEdge > uThreshold) {if (uAntiAliasing == 1) {- float alpha = clamp((totalEdge - uThreshold) / max(0.01, uThreshold * 0.25), 0.0, 1.0);- gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);+ float alpha = smoothstep(uThreshold, uThreshold + 0.08, maxEdge);+ gl_FragColor = alpha >= 0.15 ? vec4(0.0, 0.0, 0.0, alpha) : vec4(0.0, 0.0, 0.0, 0.0);} else {gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);}@@ -511,6 +536,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakscene,camera,dimensions,+ dpi,activeRenderer,modelName,targetFolderName,@@ -522,15 +548,18 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BaktoneFrequencies,toneAngles,toneDensities,- antiAliasing = true,+ antiAliasing = false,disposeOnComplete = true,+ previewOnly = false,onInsertLayers,onBroadcastLayer,} = options;+ const effectiveDisposeOnComplete = previewOnly ? false : disposeOnComplete;const targetWidth = Math.max(1, Math.round(dimensions.width));const targetHeight = Math.max(1, Math.round(dimensions.height));- const resolvedToneCount = Math.max(1, Math.min(4, Math.round(explicitToneCount ?? toneBands ?? 2)));+ const resolvedDpi = Math.max(1, dpi ?? dimensions.dpi ?? 600);+ const resolvedToneCount = Math.max(0, Math.min(4, Math.round(explicitToneCount ?? toneBands ?? 2)));let offscreenRenderer: THREE.WebGLRenderer;let reusedActiveRenderer = false;@@ -564,6 +593,14 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BakoffscreenRenderer.setSize(renderWidth, renderHeight, false);offscreenRenderer.setPixelRatio(1);offscreenRenderer.setClearColor(0x000000, 0);+ if (activeRenderer && 'toneMapping' in activeRenderer && 'toneMapping' in offscreenRenderer) {+ offscreenRenderer.toneMapping = activeRenderer.toneMapping;+ offscreenRenderer.toneMappingExposure = activeRenderer.toneMappingExposure;+ }+ if (offscreenRenderer.shadowMap && activeRenderer?.shadowMap) {+ offscreenRenderer.shadowMap.enabled = activeRenderer.shadowMap.enabled;+ offscreenRenderer.shadowMap.type = activeRenderer.shadowMap.type;+ }const renderCamera = camera.clone();let isPerspective = 1;@@ -585,11 +622,17 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BakisPerspective = 0;}- // Preserve original materials for restoring after normal pass+ // Preserve original materials for restoring after normal pass (skipping helpers/hidden meshes)const savedMaterials = new Map<THREE.Mesh, THREE.Material | THREE.Material[]>();+ const hiddenHelpers: THREE.Object3D[] = [];scene.traverse((obj) => {+ if (obj.userData?.is3DHelper && obj.visible) {+ hiddenHelpers.push(obj);+ obj.visible = false;+ return;+ }const mesh = obj as THREE.Mesh;- if (mesh.isMesh) {+ if (mesh.isMesh && !mesh.userData?.is3DHelper) {savedMaterials.set(mesh, mesh.material);}});@@ -604,35 +647,38 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak});const normalMat = new THREE.MeshNormalMaterial();- scene.traverse((obj) => {- const mesh = obj as THREE.Mesh;- if (mesh.isMesh) {- mesh.material = normalMat;- }- });-- offscreenRenderer.setRenderTarget(targetA);- offscreenRenderer.clear();- offscreenRenderer.render(scene, renderCamera);-- // 2. Offscreen Render Target B: Diffuse Lighting Bufferconst targetB = new THREE.WebGLRenderTarget(renderWidth, renderHeight, {- minFilter: THREE.LinearFilter,- magFilter: THREE.LinearFilter,+ minFilter: THREE.NearestFilter,+ magFilter: THREE.NearestFilter,format: THREE.RGBAFormat,type: THREE.UnsignedByteType,});- scene.traverse((obj) => {- const mesh = obj as THREE.Mesh;- if (mesh.isMesh && savedMaterials.has(mesh)) {- mesh.material = savedMaterials.get(mesh)!;+ try {+ for (const mesh of savedMaterials.keys()) {+ mesh.material = normalMat;}- });- offscreenRenderer.setRenderTarget(targetB);- offscreenRenderer.clear();- offscreenRenderer.render(scene, renderCamera);+ offscreenRenderer.setRenderTarget(targetA);+ offscreenRenderer.clear();+ offscreenRenderer.render(scene, renderCamera);++ // 2. Offscreen Render Target B: Diffuse Lighting Buffer+ for (const [mesh, origMat] of savedMaterials.entries()) {+ mesh.material = origMat;+ }++ offscreenRenderer.setRenderTarget(targetB);+ offscreenRenderer.clear();+ offscreenRenderer.render(scene, renderCamera);+ } finally {+ for (const [mesh, origMat] of savedMaterials.entries()) {+ mesh.material = origMat;+ }+ for (const helper of hiddenHelpers) {+ helper.visible = true;+ }+ }// 3. GLSL Fragment Sobel Edge Detection Pass over Target A (Normals + Depth)const lineTarget = new THREE.WebGLRenderTarget(renderWidth, renderHeight, {@@ -691,17 +737,9 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BakoffscreenRenderer.setRenderTarget(null);offscreenRenderer.clear();offscreenRenderer.render(postScene, postCamera);+ lineCtx.imageSmoothingEnabled = false;lineCtx.drawImage(offscreenRenderer.domElement, 0, 0, targetWidth, targetHeight);- // Extract binary line pixel map to ensure screentone shading doesn't bleed into outline- const renderLineCanvas = document.createElement('canvas');- renderLineCanvas.width = renderWidth;- renderLineCanvas.height = renderHeight;- const renderLineCtx = renderLineCanvas.getContext('2d', { willReadFrequently: true })!;- renderLineCtx.drawImage(offscreenRenderer.domElement, 0, 0, renderWidth, renderHeight);- const linePixels = renderLineCtx.getImageData(0, 0, renderWidth, renderHeight);- const lineData32 = new Uint32Array(linePixels.data.buffer);-// 4. Capture Diffuse Lighting Buffer for Shadow Tier PosterizationdisplayMaterial.uniforms.tSource.value = targetB.texture;offscreenRenderer.setRenderTarget(null);@@ -712,6 +750,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BakdiffuseCanvas.width = renderWidth;diffuseCanvas.height = renderHeight;const diffCtx = diffuseCanvas.getContext('2d', { willReadFrequently: true })!;+ diffCtx.imageSmoothingEnabled = false;diffCtx.drawImage(offscreenRenderer.domElement, 0, 0, renderWidth, renderHeight);const diffImageData = diffCtx.getImageData(0, 0, renderWidth, renderHeight);const diffData = diffImageData.data;@@ -722,12 +761,12 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakconst folderName = targetFolderName?.trim() || `3D Extraction [${cleanModelName}]`;const folderId = `folder-lt-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;- // 5. Posterize Diffuse Lighting into 1 to 4 Manga Screentone Shadow Tiers- // Default Tier Configurations:- // Tier 1 (Light shadow): 60 LPI, 20% density- // Tier 2 (Deep shadow): 60 LPI, 45% density+ // 5. Posterize Diffuse Lighting into 1 to 4 Mutually Exclusive Manga Screentone Shadow Tiers+ // Each pixel belongs to at most ONE shadow band at uniform 45° angle (Clip Studio Paint style),+ // eliminating overlapping-band moiré and preserving exact requested tone densities.type ToneTierDef = {- threshold: number;+ minLum: number;+ maxLum: number;density: number;frequency: number;angle: number;@@ -735,9 +774,12 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak};const tierConfigs: ToneTierDef[] = [];- if (resolvedToneCount === 1) {+ if (resolvedToneCount === 0) {+ // Lineart-only extraction+ } else if (resolvedToneCount === 1) {tierConfigs.push({- threshold: 0.45,+ minLum: -1.0,+ maxLum: 0.45,density: toneDensities?.[0] ?? 0.45,frequency: toneFrequencies?.[0] ?? 60,angle: toneAngles?.[0] ?? 45,@@ -746,38 +788,43 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak} else if (resolvedToneCount === 2) {tierConfigs.push({- threshold: 0.65,+ minLum: 0.35,+ maxLum: 0.65,density: toneDensities?.[0] ?? 0.20,frequency: toneFrequencies?.[0] ?? 60,angle: toneAngles?.[0] ?? 45,name: '3D Tone 1 (Light)',},{- threshold: 0.35,+ minLum: -1.0,+ maxLum: 0.35,density: toneDensities?.[1] ?? 0.45,frequency: toneFrequencies?.[1] ?? 60,- angle: toneAngles?.[1] ?? 60,+ angle: toneAngles?.[1] ?? 45,name: '3D Tone 2 (Deep)',});} else if (resolvedToneCount === 3) {tierConfigs.push({- threshold: 0.70,+ minLum: 0.45,+ maxLum: 0.70,density: toneDensities?.[0] ?? 0.15,frequency: toneFrequencies?.[0] ?? 60,angle: toneAngles?.[0] ?? 45,name: '3D Tone 1 (Light)',},{- threshold: 0.45,+ minLum: 0.25,+ maxLum: 0.45,density: toneDensities?.[1] ?? 0.30,frequency: toneFrequencies?.[1] ?? 60,- angle: toneAngles?.[1] ?? 60,+ angle: toneAngles?.[1] ?? 45,name: '3D Tone 2 (Mid)',},{- threshold: 0.25,+ minLum: -1.0,+ maxLum: 0.25,density: toneDensities?.[2] ?? 0.50,frequency: toneFrequencies?.[2] ?? 60,angle: toneAngles?.[2] ?? 45,@@ -788,31 +835,35 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak// 4 Tone LayerstierConfigs.push({- threshold: 0.75,+ minLum: 0.55,+ maxLum: 0.75,density: toneDensities?.[0] ?? 0.10,frequency: toneFrequencies?.[0] ?? 60,angle: toneAngles?.[0] ?? 45,name: '3D Tone 1 (Light)',},{- threshold: 0.55,+ minLum: 0.35,+ maxLum: 0.55,density: toneDensities?.[1] ?? 0.25,frequency: toneFrequencies?.[1] ?? 60,- angle: toneAngles?.[1] ?? 60,+ angle: toneAngles?.[1] ?? 45,name: '3D Tone 2 (Mid-Light)',},{- threshold: 0.35,+ minLum: 0.18,+ maxLum: 0.35,density: toneDensities?.[2] ?? 0.40,frequency: toneFrequencies?.[2] ?? 60,angle: toneAngles?.[2] ?? 45,name: '3D Tone 3 (Mid-Deep)',},{- threshold: 0.18,+ minLum: -1.0,+ maxLum: 0.18,density: toneDensities?.[3] ?? 0.55,frequency: toneFrequencies?.[3] ?? 60,- angle: toneAngles?.[3] ?? 60,+ angle: toneAngles?.[3] ?? 45,name: '3D Tone 4 (Deep)',});@@ -833,42 +884,54 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakfor (let i = 0; i < renderWidth * renderHeight; i++) {const pIdx = i * 4;const alpha = diffData[pIdx + 3];- // Skip background pixels and lineart contours- if (alpha === 0 || (lineData32[i] & SOLID_BLACK_U32) !== 0) continue;+ // Threshold alpha cleanly at 128 to prevent darkened transparent silhouette fringes.+ // Do NOT cut out outline pixels: "3D Outline" sits above tone layers, so keeping solid+ // tone masks underneath prevents white/gray halos around lines.+ if (alpha < 128) continue;const r = diffData[pIdx];const g = diffData[pIdx + 1];const b = diffData[pIdx + 2];const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255.0;- if (lum < tier.threshold) {+ if (lum >= tier.minLum && lum < tier.maxLum) {maskData32[i] = SOLID_BLACK_U32;}}maskCtx.putImageData(maskImageData, 0, 0);- const toneRenderCanvas = document.createElement('canvas');- toneRenderCanvas.width = renderWidth;- toneRenderCanvas.height = renderHeight;-- applyScreentoneCPU(maskCanvas, toneRenderCanvas, {- frequency: tier.frequency,- angle: tier.angle,- specifiedDensity: tier.density,- densityType: 'specified',- dpi: 600,- antiAliasing: true,- });-const finalToneCanvas = document.createElement('canvas');finalToneCanvas.width = targetWidth;finalToneCanvas.height = targetHeight;const finalToneCtx = finalToneCanvas.getContext('2d')!;- finalToneCtx.drawImage(toneRenderCanvas, 0, 0, targetWidth, targetHeight);+ finalToneCtx.imageSmoothingEnabled = false;++ if (previewOnly) {+ // Live 2D modal preview composites toneCanvases directly without the WebGL compositor,+ // so render crisp 1-bit binary screentone dots at preview resolution.+ const toneRenderCanvas = document.createElement('canvas');+ toneRenderCanvas.width = renderWidth;+ toneRenderCanvas.height = renderHeight;+ applyScreentoneCPU(maskCanvas, toneRenderCanvas, {+ frequency: tier.frequency,+ angle: tier.angle,+ dotShape: 'circle',+ specifiedDensity: tier.density,+ densityType: 'specified',+ dpi: resolvedDpi,+ antiAliasing: false,+ });+ finalToneCtx.drawImage(toneRenderCanvas, 0, 0, targetWidth, targetHeight);+ } else {+ // Extracted tone layers are non-destructive Clip Studio Paint tone layers (toneEnabled: true):+ // store the crisp solid-black shadow mask so the compositor renders the 1-bit halftone dots+ // ONCE at exact document DPI (eliminating double-screentoning blur & moiré artifacts).+ finalToneCtx.drawImage(maskCanvas, 0, 0, targetWidth, targetHeight);+ }toneCanvases.push(finalToneCanvas);- const toneDataUrl = finalToneCanvas.toDataURL('image/png');+ const toneDataUrl = previewOnly ? '' : finalToneCanvas.toDataURL('image/png');const toneLayer: LayerItem = {id: `raster-lt-tone-${t + 1}-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,name: tier.name,@@ -880,9 +943,11 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakcollapsed: false,parentId: folderId,thumbnailUrl: toneDataUrl,+ isToneLayer: true,toneEnabled: true,toneFrequency: tier.frequency,toneAngle: tier.angle,+ toneDotShape: 'circle',toneDensity: Math.round(tier.density * 100),toneDensityType: 'specified',};@@ -890,7 +955,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bak}// 6. Outline Layer ("3D Outline")- const lineDataUrl = lineCanvas.toDataURL('image/png');+ const lineDataUrl = previewOnly ? '' : lineCanvas.toDataURL('image/png');const lineLayer: LayerItem = {id: `raster-lt-line-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`,name: '3D Outline',@@ -902,6 +967,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakcollapsed: false,parentId: folderId,thumbnailUrl: lineDataUrl,+ expressionColor: antiAliasing ? 'gray' : 'monochrome',};// 7. Folder Group Layer: "3D Extraction [Model Name]"@@ -930,7 +996,7 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<BaklineTarget.texture.dispose();lineTarget.dispose();- if (disposeOnComplete) {+ if (effectiveDisposeOnComplete) {disposeThreeResources(scene, offscreenRenderer);if (activeRenderer && !reusedActiveRenderer) {disposeThreeResources(null, activeRenderer);@@ -963,23 +1029,25 @@ export async function bake3DToLineAndTone(options: Bake3DLTOptions): Promise<Bakconst allLayers: LayerItem[] = [folderLayer, lineLayer, ...toneLayersStackOrder];const allCanvases: HTMLCanvasElement[] = [folderCanvas, lineCanvas, ...toneCanvasesStackOrder];- if (onInsertLayers) {+ if (!previewOnly && onInsertLayers) {onInsertLayers(allLayers, allCanvases);}- if (onBroadcastLayer) {- onBroadcastLayer(folderLayer, '');- onBroadcastLayer(lineLayer, lineDataUrl);- toneLayersStackOrder.forEach((l, i) => onBroadcastLayer(l, toneCanvasesStackOrder[i].toDataURL('image/png')));- } else if (multiplayerService.isConnected()) {- const activeGrid = documentStore.getActiveTileGrid();- multiplayerService.sendLayerAdd(folderLayer);- multiplayerService.sendLayerAdd(lineLayer);- multiplayerService.streamLayerTiles(lineLayer.id, activeGrid);- toneLayersStackOrder.forEach((l) => {- multiplayerService.sendLayerAdd(l);- multiplayerService.streamLayerTiles(l.id, activeGrid);- });+ if (!previewOnly) {+ if (onBroadcastLayer) {+ onBroadcastLayer(folderLayer, '');+ onBroadcastLayer(lineLayer, lineDataUrl);+ toneLayersStackOrder.forEach((l, i) => onBroadcastLayer(l, toneCanvasesStackOrder[i].toDataURL('image/png')));+ } else if (multiplayerService.isConnected()) {+ const activeGrid = documentStore.getActiveTileGrid();+ multiplayerService.sendLayerAdd(folderLayer);+ multiplayerService.sendLayerAdd(lineLayer);+ multiplayerService.streamLayerTiles(lineLayer.id, activeGrid);+ toneLayersStackOrder.forEach((l) => {+ multiplayerService.sendLayerAdd(l);+ multiplayerService.streamLayerTiles(l.id, activeGrid);+ });+ }}return {diff --git a/src/services/multiplayerService.ts b/src/services/multiplayerService.tsindex 4bd37d1..208445f 100644--- a/src/services/multiplayerService.ts+++ b/src/services/multiplayerService.ts@@ -119,6 +119,7 @@ const TOOL_TYPES_LIST: ToolType[] = ['liquify','shape','object',+ '3d',];export const DEEP_LINK_SCHEME = 'inkstudio:';diff --git a/src/stores/index.ts b/src/stores/index.tsindex fb16e26..c08902e 100644--- a/src/stores/index.ts+++ b/src/stores/index.ts@@ -42,3 +42,15 @@ export type { AutoActionStoreState } from './useAutoActionStore';export { useUpdaterStore, updaterStoreActions } from './useUpdaterStore';export type { UpdaterStoreState, UpdaterStatus } from './useUpdaterStore';++export {+ use3DStore,+ store3DActions,+ scene3DBridge,+ INITIAL_MODEL_3D_TRANSFORM,+} from './use3DStore';+export type {+ Scene3DStoreState,+ Model3DTransformState,+ Scene3DCommandBridge,+} from './use3DStore';diff --git a/src/stores/use3DStore.ts b/src/stores/use3DStore.tsnew file mode 100644index 0000000..54c02d2--- /dev/null+++ b/src/stores/use3DStore.ts@@ -0,0 +1,268 @@+import { createStore } from './createStore';+import {+ Camera3DPreset,+ DEFAULT_3D_LIGHTING,+ Gizmo3DMode,+ Gizmo3DSpace,+ Scene3DLightingSettings,+ Shading3DMode,+ Tool3DMode,+} from '../utils/tool3DRules';+import { PosePresetName } from '../utils/mannequin3D';+import { LTConversionSettings } from '../types/editor';++export interface Model3DTransformState {+ position: [number, number, number];+ rotation: [number, number, number]; // degrees+ scale: [number, number, number]; // multiplier (1 = 100%)+ uniformScale: boolean;+}++export const INITIAL_MODEL_3D_TRANSFORM: Model3DTransformState = {+ position: [0, 0, 0],+ rotation: [0, 0, 0],+ scale: [1, 1, 1],+ uniformScale: true,+};++export interface Scene3DStoreState {+ activeMode: Tool3DMode;+ gizmoMode: Gizmo3DMode;+ gizmoSpace: Gizmo3DSpace;+ snapEnabled: boolean;+ isReferenceVisible: boolean;+ loadedModelName: string | null;+ modelKind: 'none' | 'imported';+ isMannequinActive: boolean;+ activeIKHandle: string | null;+ showIKHandles: boolean;+ isBaking: boolean;+ canUndo3D: boolean;+ canRedo3D: boolean;+ modelTransform: Model3DTransformState;+ lighting: Scene3DLightingSettings;+ shadingMode: Shading3DMode;+ materialRoughness: number; // 0.1..1.0+ toonOutline: boolean;+ opacity: number; // 0.1..1.0+ showGrid: boolean;+ perspective: number; // 0.3..2.5 dolly zoom factor+ fov: number; // 18..95 deg+ syncCameraPerspective: boolean;+ previousToolBefore3D: string | null;+}++const cloneDefaultLighting = (): Scene3DLightingSettings => ({+ keyLight: { ...DEFAULT_3D_LIGHTING.keyLight },+ rimLight: { ...DEFAULT_3D_LIGHTING.rimLight },+ ambientIntensity: DEFAULT_3D_LIGHTING.ambientIntensity,+ ambientColor: DEFAULT_3D_LIGHTING.ambientColor,+ castGroundShadow: DEFAULT_3D_LIGHTING.castGroundShadow,+ shadowOpacity: DEFAULT_3D_LIGHTING.shadowOpacity,+});++const createInitial3DState = (): Scene3DStoreState => ({+ activeMode: 'smart',+ gizmoMode: 'rotate',+ gizmoSpace: 'local',+ snapEnabled: false,+ isReferenceVisible: true,+ loadedModelName: null,+ modelKind: 'none',+ isMannequinActive: false,+ activeIKHandle: null,+ showIKHandles: true,+ isBaking: false,+ canUndo3D: false,+ canRedo3D: false,+ modelTransform: {+ position: [...INITIAL_MODEL_3D_TRANSFORM.position],+ rotation: [...INITIAL_MODEL_3D_TRANSFORM.rotation],+ scale: [...INITIAL_MODEL_3D_TRANSFORM.scale],+ uniformScale: true,+ },+ lighting: cloneDefaultLighting(),+ shadingMode: 'shaded',+ materialRoughness: 0.4,+ toonOutline: false,+ opacity: 0.92,+ showGrid: true,+ perspective: 1.0,+ fov: 45,+ syncCameraPerspective: false,+ previousToolBefore3D: null,+});++export const use3DStore = createStore<Scene3DStoreState>(createInitial3DState);++export const store3DActions = {+ setActiveMode(activeMode: Tool3DMode): void {+ use3DStore.setState({ activeMode });+ },++ setGizmoMode(gizmoMode: Gizmo3DMode): void {+ use3DStore.setState({ gizmoMode });+ },++ setGizmoSpace(gizmoSpace: Gizmo3DSpace): void {+ use3DStore.setState({ gizmoSpace });+ },++ setSnapEnabled(snapEnabled: boolean): void {+ use3DStore.setState({ snapEnabled });+ },++ setReferenceVisible(isReferenceVisible: boolean): void {+ use3DStore.setState({ isReferenceVisible });+ },++ toggleReferenceVisible(): void {+ use3DStore.setState((prev) => ({ isReferenceVisible: !prev.isReferenceVisible }));+ },++ setLoadedModel(+ loadedModelName: string | null,+ modelKind: 'none' | 'imported',+ isMannequinActive: boolean+ ): void {+ use3DStore.setState({+ loadedModelName,+ modelKind,+ isMannequinActive,+ activeIKHandle: null,+ });+ },++ setActiveIKHandle(activeIKHandle: string | null): void {+ use3DStore.setState({ activeIKHandle });+ },++ setShowIKHandles(showIKHandles: boolean): void {+ use3DStore.setState({ showIKHandles });+ },++ setIsBaking(isBaking: boolean): void {+ use3DStore.setState({ isBaking });+ },++ setHistoryFlags(canUndo3D: boolean, canRedo3D: boolean): void {+ use3DStore.setState({ canUndo3D, canRedo3D });+ },++ setModelTransform(patch: Partial<Model3DTransformState>): void {+ use3DStore.setState((prev) => ({+ modelTransform: { ...prev.modelTransform, ...patch },+ }));+ },++ updateLighting(patch: Partial<Scene3DLightingSettings>): void {+ use3DStore.setState((prev) => ({+ lighting: { ...prev.lighting, ...patch },+ }));+ },++ updateKeyLight(patch: Partial<Scene3DLightingSettings['keyLight']>): void {+ use3DStore.setState((prev) => ({+ lighting: {+ ...prev.lighting,+ keyLight: { ...prev.lighting.keyLight, ...patch },+ },+ }));+ },++ updateRimLight(patch: Partial<Scene3DLightingSettings['rimLight']>): void {+ use3DStore.setState((prev) => ({+ lighting: {+ ...prev.lighting,+ rimLight: { ...prev.lighting.rimLight, ...patch },+ },+ }));+ },++ resetLighting(): void {+ use3DStore.setState({ lighting: cloneDefaultLighting() });+ },++ setShadingMode(shadingMode: Shading3DMode): void {+ use3DStore.setState({ shadingMode });+ },++ setMaterialRoughness(materialRoughness: number): void {+ use3DStore.setState({ materialRoughness: Math.max(0.08, Math.min(1.0, materialRoughness)) });+ },++ setToonOutline(toonOutline: boolean): void {+ use3DStore.setState({ toonOutline });+ },++ setOpacity(opacity: number): void {+ use3DStore.setState({ opacity: Math.max(0.1, Math.min(1.0, opacity)) });+ },++ setShowGrid(showGrid: boolean): void {+ use3DStore.setState({ showGrid });+ },++ setPerspective(perspective: number, fov?: number): void {+ use3DStore.setState((prev) => ({+ perspective,+ fov: fov ?? prev.fov,+ }));+ },++ setFov(fov: number): void {+ use3DStore.setState({ fov: Math.max(15, Math.min(105, fov)) });+ },++ setSyncCameraPerspective(syncCameraPerspective: boolean): void {+ use3DStore.setState({ syncCameraPerspective });+ },++ setPreviousToolBefore3D(previousToolBefore3D: string | null): void {+ use3DStore.setState({ previousToolBefore3D });+ },++ resetSceneMeta(): void {+ use3DStore.setState({+ loadedModelName: null,+ modelKind: 'none',+ isMannequinActive: false,+ activeIKHandle: null,+ isBaking: false,+ canUndo3D: false,+ canRedo3D: false,+ isReferenceVisible: true,+ modelTransform: {+ position: [0, 0, 0],+ rotation: [0, 0, 0],+ scale: [1, 1, 1],+ uniformScale: true,+ },+ });+ },+};++export interface Scene3DCommandBridge {+ triggerFilePicker?: () => void;+ loadFile?: (file: File) => void;+ applyNumericTransform?: (next: Model3DTransformState) => void;+ applyTransformDelta?: (mode: Tool3DMode, dx: number, dy: number, snap?: boolean) => void;+ rotateModelYaw?: (degrees: number) => void;+ snapToGround?: () => void;+ resetModelTransform?: () => void;+ resetCamera?: () => void;+ setCameraPreset?: (preset: Camera3DPreset) => void;+ applyPerspectiveDollyZoom?: (factor: number) => void;+ applyPosePreset?: (preset: PosePresetName) => void;+ selectIKTarget?: (targetName: string | null) => void;+ syncPerspectiveRulerNow?: () => void;+ bakeTo2D?: (closeAfter?: boolean) => Promise<void>;+ extractLineAndTone?: (settings?: LTConversionSettings) => Promise<void>;+ commitHistoryNow?: () => void;+ undo?: () => boolean;+ redo?: () => boolean;+ canUndo?: () => boolean;+ canRedo?: () => boolean;+}++export const scene3DBridge: Scene3DCommandBridge = {};diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.tsindex a943605..580fbae 100644--- a/src/stores/useToolStore.ts+++ b/src/stores/useToolStore.ts@@ -32,6 +32,8 @@ import { enforceColorMode } from '../utils/colorUtils';import { safeLocalStorageSetItem } from '../utils/safeStorage';import { createStore } from './createStore';import { useDocumentStore } from './useDocumentStore';+import { uiStoreActions } from './useUiStore';+import { store3DActions } from './use3DStore';export interface QuickModifiersState {isAltActive: boolean;@@ -335,6 +337,15 @@ export const toolStoreActions = {selectTool(newTool: ToolType): void {const state = useToolStore.getState();const prevTool = state.tool;+ if (newTool === '3d') {+ if (prevTool !== '3d') {+ store3DActions.setPreviousToolBefore3D(prevTool);+ }+ store3DActions.setReferenceVisible(true);+ if (useDocumentStore.getState().documents.length > 0) {+ uiStoreActions.set3DLayerOpen(true);+ }+ }if (prevTool === newTool) return;if (newTool === 'eraser') {diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.tsindex 845e3b9..000486e 100644--- a/src/stores/useUiStore.ts+++ b/src/stores/useUiStore.ts@@ -195,10 +195,12 @@ export const uiStoreActions = {},set3DLayerOpen(open: boolean, initialFile: File | null = null): void {- useUiStore.setState({+ useUiStore.setState((prev) => ({is3DLayerOpen: open,- initial3DFile: open ? initialFile : null,- });+ initial3DFile: open+ ? (initialFile ?? (prev.is3DLayerOpen ? prev.initial3DFile : null))+ : null,+ }));},updateAppSettings(newSettings: AppSettings): void {diff --git a/src/types/editor.ts b/src/types/editor.tsindex 9b54f95..e26b876 100644--- a/src/types/editor.ts+++ b/src/types/editor.ts@@ -45,7 +45,8 @@ export type ToolType =| 'balloon'| 'object'| 'vector-edit'- | 'liquify';+ | 'liquify'+ | '3d';export interface Point {x: number;@@ -571,7 +572,8 @@ export type HistoryActionType =| 'retouch'| 'pen'| 'filter'- | 'auto-action';+ | 'auto-action'+ | 'layer';export type LiquifyMode =| 'push'@@ -879,6 +881,11 @@ export interface LayerTreeDelta {insertBeforeLayerId?: string | null;insertIndex?: number;updatedLayers?: LayerTreeDeltaUpdate[];+ /** Full layer list snapshots before/after for general layer tree mutations (add, delete, reorder, merge, properties, masks, etc.). */+ beforeLayers?: LayerItem[];+ afterLayers?: LayerItem[];+ /** Optional key to coalesce rapid continuous slider edits (e.g. opacity, tone frequency) into a single undo step. */+ coalesceKey?: string;beforeActiveLayerId?: string;afterActiveLayerId?: string;}@@ -1009,12 +1016,13 @@ export interface LayerItem {thumbnailUrl?: string; // live layer thumbnail data URLisReference?: boolean; // Clip Studio Paint Reference Layer toggle// Screentone (CSP Tone Effect)+ isToneLayer?: boolean; // True for dedicated screentone fill layers with flat editable density; false/undefined for regular layers whose tone adapts to image tonestoneEnabled?: boolean;toneFrequency?: number; // Lines / LPI (20 to 85, default: 60)toneAngle?: number; // Angle in degrees (0 to 90, default: 45)toneDotShape?: 'circle' | 'euclidean' | 'line' | 'diamond'; // Default: circle- toneDensity?: number; // Density percentage (1 to 100, default: 40)- toneDensityType?: 'specified' | 'image'; // 'specified' ("Use specified density") or 'image' ("Use image brightness")+ toneDensity?: number; // Density percentage (1 to 100, default: 40; editable on dedicated tone layers)+ toneDensityType?: 'specified' | 'image'; // 'specified' (dedicated tone layer) or 'image' (existing layer tones)// Clip Studio Paint Style Layer Color (Tint Effect)layerColorEnabled?: boolean;layerColor?: string; // Primary tint color (default: '#1c73c2')@@ -1055,6 +1063,31 @@ export function isFolderLikeLayer(layer: Pick<LayerItem, 'type'> | null | undefireturn layer?.type === 'folder' || layer?.type === 'frame-folder';}+/**+ * Returns true if the layer is a dedicated Screen Tone layer (flat tone sheet+ * whose density is directly editable, like Clip Studio Paint's Tone layer).+ * Regular layers with the Screentone effect enabled return false so their+ * halftone dots adapt to the layer's own brightness and opacity tones.+ */+export function isDedicatedToneLayer(+ layer: Pick<LayerItem, 'isToneLayer' | 'toneDensityType'> | null | undefined+): boolean {+ if (!layer) return false;+ if (typeof layer.isToneLayer === 'boolean') return layer.isToneLayer;+ return layer.toneDensityType === 'specified';+}++/**+ * Resolves the effective screentone density mode for rendering:+ * dedicated tone layers use their specified flat density, while existing+ * layers adapt dynamically to their image luminance and alpha.+ */+export function resolveToneDensityType(+ layer: Pick<LayerItem, 'isToneLayer' | 'toneDensityType'> | null | undefined+): 'specified' | 'image' {+ return isDedicatedToneLayer(layer) ? 'specified' : 'image';+}+export function hasTileBackedLayer(layer: Pick<LayerItem, 'type'> | null | undefined): boolean {return (layer?.type === 'raster' ||diff --git a/src/types/multiplayer.ts b/src/types/multiplayer.tsindex a2c5ab2..bfdc3b0 100644--- a/src/types/multiplayer.ts+++ b/src/types/multiplayer.ts@@ -90,6 +90,7 @@ export type LayerClearableField =| 'alphaLocked'| 'clipped'| 'isReference'+ | 'isToneLayer'| 'toneEnabled'| 'toneFrequency'| 'toneAngle'diff --git a/src/utils/__tests__/folderMergeAndTransform.test.tsx b/src/utils/__tests__/folderMergeAndTransform.test.tsxnew file mode 100644index 0000000..f5c1980--- /dev/null+++ b/src/utils/__tests__/folderMergeAndTransform.test.tsx@@ -0,0 +1,966 @@+import { act, useRef } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ useLayerManager,+ getFolderDescendantIds,+ computeMergeFolderLayers,+} from '../../hooks/useLayerManager';+import { useDrawingHistory } from '../../hooks/drawing/useDrawingHistory';+import { useSelectionTools } from '../../hooks/drawing/useSelectionTools';+import {+ resolveTransformTargetLayers,+ getTransformPreviewLayerState,+} from '../transformEngine';+import { SparseTileGrid } from '../tileEngine';+import type { CanvasDimensions, LayerItem } from '../../types/editor';++// Lightweight in-memory 2D Canvas shim so pixel transforms & region canvases execute real pixel ops in Node Vitest+class ShimImageData {+ data: Uint8ClampedArray;+ width: number;+ height: number;+ constructor(dataOrW: Uint8ClampedArray | number, widthOrH: number, height?: number) {+ if (typeof dataOrW === 'number') {+ this.width = dataOrW;+ this.height = widthOrH;+ this.data = new Uint8ClampedArray(this.width * this.height * 4);+ } else {+ this.data = dataOrW;+ this.width = widthOrH;+ this.height = height ?? Math.floor(dataOrW.length / (4 * widthOrH));+ }+ }+}++class ShimCanvas2DContext {+ canvas: ShimCanvasElement;+ globalAlpha = 1;+ globalCompositeOperation = 'source-over';+ imageSmoothingEnabled = true;+ imageSmoothingQuality = 'high';+ private tx = 0;+ private ty = 0;+ private sx = 1;+ private sy = 1;+ private stack: Array<{+ tx: number;+ ty: number;+ sx: number;+ sy: number;+ globalAlpha: number;+ globalCompositeOperation: string;+ }> = [];++ constructor(canvas: ShimCanvasElement) {+ this.canvas = canvas;+ }++ save() {+ this.stack.push({+ tx: this.tx,+ ty: this.ty,+ sx: this.sx,+ sy: this.sy,+ globalAlpha: this.globalAlpha,+ globalCompositeOperation: this.globalCompositeOperation,+ });+ }++ restore() {+ const prev = this.stack.pop();+ if (prev) {+ this.tx = prev.tx;+ this.ty = prev.ty;+ this.sx = prev.sx;+ this.sy = prev.sy;+ this.globalAlpha = prev.globalAlpha;+ this.globalCompositeOperation = prev.globalCompositeOperation;+ }+ }++ setTransform(_a: number, _b: number, _c: number, _d: number, e: number, f: number) {+ this.tx = e;+ this.ty = f;+ this.sx = 1;+ this.sy = 1;+ }++ resetTransform() {+ this.tx = 0;+ this.ty = 0;+ this.sx = 1;+ this.sy = 1;+ }++ translate(x: number, y: number) {+ this.tx += x * this.sx;+ this.ty += y * this.sy;+ }++ rotate(_rad: number) {+ // Supported for zero-rotation affine tests+ }++ scale(x: number, y: number) {+ this.sx *= x;+ this.sy *= y;+ }++ createImageData(w: number, h: number): ShimImageData {+ return new ShimImageData(w, h);+ }++ clearRect(x: number, y: number, w: number, h: number) {+ const buf = this.canvas.pixels;+ const cw = this.canvas.width;+ const ch = this.canvas.height;+ const x0 = Math.max(0, Math.floor(x));+ const y0 = Math.max(0, Math.floor(y));+ const x1 = Math.min(cw, Math.ceil(x + w));+ const y1 = Math.min(ch, Math.ceil(y + h));+ for (let py = y0; py < y1; py++) {+ for (let px = x0; px < x1; px++) {+ const off = (py * cw + px) * 4;+ buf[off] = 0;+ buf[off + 1] = 0;+ buf[off + 2] = 0;+ buf[off + 3] = 0;+ }+ }+ }++ putImageData(+ img: ShimImageData,+ dx: number,+ dy: number,+ dirtyX = 0,+ dirtyY = 0,+ dirtyW = img.width,+ dirtyH = img.height+ ) {+ const dst = this.canvas.pixels;+ const cw = this.canvas.width;+ const ch = this.canvas.height;+ for (let sy = dirtyY; sy < dirtyY + dirtyH; sy++) {+ const py = Math.floor(dy + sy);+ if (py < 0 || py >= ch || sy < 0 || sy >= img.height) continue;+ for (let sx = dirtyX; sx < dirtyX + dirtyW; sx++) {+ const px = Math.floor(dx + sx);+ if (px < 0 || px >= cw || sx < 0 || sx >= img.width) continue;+ const sOff = (sy * img.width + sx) * 4;+ const dOff = (py * cw + px) * 4;+ dst[dOff] = img.data[sOff];+ dst[dOff + 1] = img.data[sOff + 1];+ dst[dOff + 2] = img.data[sOff + 2];+ dst[dOff + 3] = img.data[sOff + 3];+ }+ }+ }++ getImageData(x: number, y: number, w: number, h: number): ShimImageData {+ const out = new Uint8ClampedArray(w * h * 4);+ const src = this.canvas.pixels;+ const cw = this.canvas.width;+ const ch = this.canvas.height;+ const x0 = Math.floor(x);+ const y0 = Math.floor(y);+ for (let py = 0; py < h; py++) {+ const sy = y0 + py;+ if (sy < 0 || sy >= ch) continue;+ for (let px = 0; px < w; px++) {+ const sx = x0 + px;+ if (sx < 0 || sx >= cw) continue;+ const sOff = (sy * cw + sx) * 4;+ const dOff = (py * w + px) * 4;+ out[dOff] = src[sOff];+ out[dOff + 1] = src[sOff + 1];+ out[dOff + 2] = src[sOff + 2];+ out[dOff + 3] = src[sOff + 3];+ }+ }+ return new ShimImageData(out, w, h);+ }++ drawImage(+ src: ShimCanvasElement,+ dx: number,+ dy: number,+ dw?: number,+ dh?: number+ ) {+ if (!src || !src.pixels) return;+ const sw = src.width;+ const sh = src.height;+ const drawW = dw ?? sw;+ const drawH = dh ?? sh;+ if (sw <= 0 || sh <= 0 || drawW <= 0 || drawH <= 0) return;++ const dst = this.canvas.pixels;+ const cw = this.canvas.width;+ const ch = this.canvas.height;+ const alpha = Math.max(0, Math.min(1, this.globalAlpha));++ for (let py = 0; py < Math.ceil(drawH); py++) {+ const sy = Math.min(sh - 1, Math.floor((py / drawH) * sh));+ const worldY = Math.floor(this.ty + (dy + py) * this.sy);+ if (worldY < 0 || worldY >= ch) continue;++ for (let px = 0; px < Math.ceil(drawW); px++) {+ const sx = Math.min(sw - 1, Math.floor((px / drawW) * sw));+ const worldX = Math.floor(this.tx + (dx + px) * this.sx);+ if (worldX < 0 || worldX >= cw) continue;++ const sOff = (sy * sw + sx) * 4;+ const sA = (src.pixels[sOff + 3] / 255) * alpha;+ if (sA <= 0) continue;++ const dOff = (worldY * cw + worldX) * 4;+ const dA = dst[dOff + 3] / 255;+ const outA = sA + dA * (1 - sA);+ if (outA > 0) {+ dst[dOff] = Math.round((src.pixels[sOff] * sA + dst[dOff] * dA * (1 - sA)) / outA);+ dst[dOff + 1] = Math.round((src.pixels[sOff + 1] * sA + dst[dOff + 1] * dA * (1 - sA)) / outA);+ dst[dOff + 2] = Math.round((src.pixels[sOff + 2] * sA + dst[dOff + 2] * dA * (1 - sA)) / outA);+ dst[dOff + 3] = Math.round(outA * 255);+ }+ }+ }+ }+}++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(_type?: string): any {+ return null;+ }+}++class ShimCanvasElement extends ShimNode {+ private _width = 0;+ private _height = 0;+ pixels = new Uint8ClampedArray(0);+ private ctx2d: ShimCanvas2DContext | null = null;+ private enable2d: boolean;++ constructor(doc?: any, enable2d = true) {+ super('CANVAS', doc);+ this.enable2d = enable2d;+ }++ get width() {+ return this._width;+ }+ set width(v: number) {+ this._width = Math.max(0, Math.floor(v));+ this.pixels = new Uint8ClampedArray(this._width * this._height * 4);+ }+ get height() {+ return this._height;+ }+ set height(v: number) {+ this._height = Math.max(0, Math.floor(v));+ this.pixels = new Uint8ClampedArray(this._width * this._height * 4);+ }++ getContext(type?: string): any {+ if (type === '2d' && this.enable2d) {+ if (!this.ctx2d) this.ctx2d = new ShimCanvas2DContext(this);+ return this.ctx2d;+ }+ return null;+ }++ toDataURL() {+ return 'data:image/png;base64,';+ }+}++function installDomShim(enable2d = true) {+ const doc: any = new ShimNode('#document');+ doc.nodeType = 9;+ doc.activeElement = null;+ doc.createElement = (tag: string) =>+ tag.toLowerCase() === 'canvas' ? new ShimCanvasElement(doc, enable2d) : 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;+ (globalThis as any).ImageData = ShimImageData;+ return doc;+}++function makeLayer(+ id: string,+ overrides: Partial<LayerItem> = {}+): LayerItem {+ const type = overrides.type ?? 'raster';+ return {+ id,+ name: overrides.name ?? id,+ type,+ visible: true,+ opacity: 1,+ blendMode: type === 'folder' ? 'pass-through' : 'normal',+ locked: false,+ collapsed: false,+ parentId: null,+ thumbnailUrl: '',+ ...overrides,+ };+}++function paintRect(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number,+ w: number,+ h: number,+ r: number,+ g: number,+ b: number,+ a = 255+) {+ 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');+}++describe('Folder Merge Pure Logic', () => {+ it('collects direct and nested descendants and replaces folder with a single raster layer at exact stack index', () => {+ const layers: LayerItem[] = [+ makeLayer('top', { name: 'Top' }),+ makeLayer('f1', {+ name: 'Character',+ type: 'folder',+ opacity: 0.8,+ blendMode: 'pass-through',+ clipped: true,+ visible: true,+ }),+ makeLayer('c1', { name: 'Lineart', parentId: 'f1' }),+ makeLayer('sub', { name: 'Colors', type: 'folder', parentId: 'f1' }),+ makeLayer('c2', { name: 'Flat', parentId: 'sub' }),+ makeLayer('c3', { name: 'Shade', parentId: 'sub' }),+ makeLayer('bg', { name: 'Background' }),+ ];++ expect(getFolderDescendantIds(layers, 'f1')).toEqual(['c1', 'sub', 'c2', 'c3']);++ const plan = computeMergeFolderLayers(layers, 'f1', 'merged-char');+ expect(plan).not.toBeNull();+ if (!plan) return;++ expect(plan.mergedLayer.id).toBe('merged-char');+ expect(plan.mergedLayer.type).toBe('raster');+ expect(plan.mergedLayer.name).toBe('Character');+ expect(plan.mergedLayer.opacity).toBe(0.8);+ expect(plan.mergedLayer.blendMode).toBe('normal'); // pass-through -> normal+ expect(plan.mergedLayer.clipped).toBe(true);+ expect(plan.mergedLayer.parentId).toBeNull();+ expect(plan.nextLayers.map((l) => l.id)).toEqual(['top', 'merged-char', 'bg']);+ });++ it('preserves isolated folder blend mode, parentId, visibility, and rejects locked or non-folder targets', () => {+ const layers: LayerItem[] = [+ makeLayer('outer', { type: 'folder' }),+ makeLayer('inner', {+ name: 'Shadows',+ type: 'folder',+ parentId: 'outer',+ blendMode: 'multiply',+ opacity: 0.65,+ visible: false,+ }),+ makeLayer('child', { parentId: 'inner' }),+ makeLayer('locked-folder', { type: 'folder', locked: true }),+ makeLayer('plain', { type: 'raster' }),+ ];++ const plan = computeMergeFolderLayers(layers, 'inner', 'merged-shadows');+ expect(plan).not.toBeNull();+ expect(plan?.mergedLayer.blendMode).toBe('multiply');+ expect(plan?.mergedLayer.parentId).toBe('outer');+ expect(plan?.mergedLayer.opacity).toBe(0.65);+ expect(plan?.mergedLayer.visible).toBe(false);++ expect(computeMergeFolderLayers(layers, 'locked-folder')).toBeNull();+ expect(computeMergeFolderLayers(layers, 'plain')).toBeNull();+ });++ it('supports merging an empty folder or a frame-folder into a single raster layer', () => {+ const layers: LayerItem[] = [+ makeLayer('empty-f', { name: 'Empty Group', type: 'folder' }),+ makeLayer('frame-f', { name: 'Panel 1', type: 'frame-folder', blendMode: 'normal' }),+ makeLayer('panel-art', { parentId: 'frame-f' }),+ ];++ const emptyPlan = computeMergeFolderLayers(layers, 'empty-f', 'merged-empty');+ expect(emptyPlan?.descendantIds).toEqual([]);+ expect(emptyPlan?.nextLayers.map((l) => l.id)).toEqual(['merged-empty', 'frame-f', 'panel-art']);++ const framePlan = computeMergeFolderLayers(layers, 'frame-f', 'merged-frame');+ expect(framePlan?.descendantIds).toEqual(['panel-art']);+ expect(framePlan?.mergedLayer.type).toBe('raster');+ expect(framePlan?.nextLayers.map((l) => l.id)).toEqual(['empty-f', 'merged-frame']);+ });+});++describe('Folder Transform Target Resolution', () => {+ const layers: LayerItem[] = [+ makeLayer('folder-main', { type: 'folder', opacity: 0.8 }),+ makeLayer('l-top', { parentId: 'folder-main', opacity: 0.5 }),+ makeLayer('sub-open', { type: 'folder', parentId: 'folder-main', opacity: 0.5 }),+ makeLayer('l-nested', { parentId: 'sub-open', visible: true }),+ makeLayer('l-hidden', { parentId: 'sub-open', visible: false }),+ makeLayer('l-locked-child', { parentId: 'folder-main', locked: true }),+ makeLayer('sub-locked', { type: 'folder', parentId: 'folder-main', locked: true }),+ makeLayer('l-in-locked-sub', { parentId: 'sub-locked' }),+ makeLayer('l-adj', { type: 'adjustment', parentId: 'folder-main' }),+ makeLayer('folder-locked', { type: 'folder', locked: true }),+ makeLayer('l-in-locked', { parentId: 'folder-locked' }),+ makeLayer('folder-empty', { type: 'folder' }),+ makeLayer('frame-folder', { type: 'frame-folder' }),+ makeLayer('l-frame-art', { parentId: 'frame-folder' }),+ makeLayer('l-outside'),+ ];++ it('recursively resolves all unlocked raster layers inside a selected folder while skipping locked descendants', () => {+ const folderMain = layers.find((l) => l.id === 'folder-main')!;+ const res = resolveTransformTargetLayers(layers, folderMain, ['folder-main']);+ expect(res.includesFolder).toBe(true);+ expect(res.blockedReason).toBeUndefined();+ expect(res.targetLayers.map((l) => l.id)).toEqual(['l-top', 'l-nested', 'l-hidden']);+ });++ it('blocks locked folders and empty folders with specific reasons', () => {+ const lockedFolder = layers.find((l) => l.id === 'folder-locked')!;+ const lockedRes = resolveTransformTargetLayers(layers, lockedFolder, ['folder-locked']);+ expect(lockedRes.targetLayers).toEqual([]);+ expect(lockedRes.blockedReason).toBe('locked');++ const emptyFolder = layers.find((l) => l.id === 'folder-empty')!;+ const emptyRes = resolveTransformTargetLayers(layers, emptyFolder, ['folder-empty']);+ expect(emptyRes.targetLayers).toEqual([]);+ expect(emptyRes.blockedReason).toBe('empty-folder');+ });++ it('resolves frame-folders and multi-selections mixing folders and individual layers without duplicates', () => {+ const frameFolder = layers.find((l) => l.id === 'frame-folder')!;+ const frameRes = resolveTransformTargetLayers(layers, frameFolder, ['frame-folder']);+ expect(frameRes.targetLayers.map((l) => l.id)).toEqual(['l-frame-art']);++ const folderMain = layers.find((l) => l.id === 'folder-main')!;+ const multiRes = resolveTransformTargetLayers(layers, folderMain, [+ 'folder-main',+ 'l-top',+ 'l-outside',+ ]);+ expect(multiRes.includesFolder).toBe(true);+ expect(multiRes.targetLayers.map((l) => l.id)).toEqual([+ 'l-top',+ 'l-nested',+ 'l-hidden',+ 'l-outside',+ ]);+ });++ it('computes accurate preview visibility and nested opacity relative to selected folder root', () => {+ const layerMap = new Map(layers.map((l) => [l.id, l]));+ const roots = new Set(['folder-main']);++ const topState = getTransformPreviewLayerState(layerMap.get('l-top')!, layerMap, roots);+ expect(topState.visible).toBe(true);+ expect(topState.opacity).toBeCloseTo(0.4, 5); // 0.5 * 0.8++ const nestedState = getTransformPreviewLayerState(layerMap.get('l-nested')!, layerMap, roots);+ expect(nestedState.visible).toBe(true);+ expect(nestedState.opacity).toBeCloseTo(0.4, 5); // 1 * 0.5 * 0.8++ const hiddenState = getTransformPreviewLayerState(layerMap.get('l-hidden')!, layerMap, roots);+ expect(hiddenState.visible).toBe(false);+ });+});++describe('End-to-End Folder Merge and Folder Transform with SparseTileGrid & Undo/Redo', () => {+ let root: Root | null = null;+ let container: any = null;++ beforeEach(() => {+ const doc = installDomShim(true);+ container = doc.createElement('div');+ doc.body.appendChild(container);+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root?.unmount();+ });+ root = null;+ }+ container = null;+ });++ it('merges a folder with nested layers into one raster layer and fully supports Undo and Redo', async () => {+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 128, height: 128 };+ let layerMgrApi: ReturnType<typeof useLayerManager> | null = null;+ let historyApi: ReturnType<typeof useDrawingHistory> | null = null;++ function Harness() {+ const pushHistoryRef = useRef<any>(null);+ const layerMgr = useLayerManager({+ dimensions: dims,+ tileGrid: grid,+ pushHistoryStepRef: pushHistoryRef,+ });++ const dimsRef = useRef(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 applyTreeRef = useRef(layerMgr.applyLayerTreeDelta);+ applyTreeRef.current = layerMgr.applyLayerTreeDelta;+ const updateMaskRef = useRef(layerMgr.updateMaskThumbnail);+ updateMaskRef.current = layerMgr.updateMaskThumbnail;+ const isDrawingRef = useRef(false);+ const lastStrokeEndRef = useRef(null);+ const abortRef = useRef(() => {});++ const history = useDrawingHistory({+ tileGrid: grid,+ activeLayerId: layerMgr.activeLayerId,+ activeLayerLocked: false,+ dimensions: dims,+ dimensionsRef: dimsRef,+ activeLayerIdRef,+ colorModeRef,+ layersRef,+ onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,+ onApplyLayerTreeDeltaRef: applyTreeRef,+ onUpdateMaskThumbnailRef: updateMaskRef,+ isDrawingRef,+ lastStrokeEndRef,+ abortActiveStrokeRef: abortRef,+ });++ pushHistoryRef.current = history.pushHistoryStep;+ layerMgrApi = layerMgr;+ historyApi = history;+ return null;+ }++ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ const initialLayers: LayerItem[] = [+ makeLayer('folder-1', { name: 'Hero', type: 'folder', opacity: 0.75, blendMode: 'pass-through' }),+ makeLayer('child-top', { name: 'Top Blue', parentId: 'folder-1', opacity: 1 }),+ makeLayer('sub-1', { name: 'Sub', type: 'folder', parentId: 'folder-1' }),+ makeLayer('child-bottom', { name: 'Bottom Red', parentId: 'sub-1', opacity: 1 }),+ makeLayer('child-hidden', { name: 'Hidden Green', parentId: 'folder-1', visible: false }),+ makeLayer('outside', { name: 'Outside' }),+ ];++ // Paint non-overlapping & overlapping squares on children+ paintRect(grid, 'child-bottom', 10, 10, 20, 20, 255, 0, 0, 255); // Red at (10..30, 10..30)+ paintRect(grid, 'child-top', 20, 10, 20, 20, 0, 0, 255, 255); // Blue at (20..40, 10..30)+ paintRect(grid, 'child-hidden', 50, 50, 10, 10, 0, 255, 0, 255); // Hidden green at (50..60, 50..60)+ paintRect(grid, 'outside', 80, 80, 10, 10, 255, 255, 0, 255); // Outside yellow++ act(() => {+ layerMgrApi!.setLayers(initialLayers);+ layerMgrApi!.setActiveLayerId('folder-1');+ });++ let mergeRes: ReturnType<ReturnType<typeof useLayerManager>['mergeFolder']> = null;+ act(() => {+ mergeRes = layerMgrApi!.mergeFolder('folder-1', 'merged-hero');+ });++ expect(mergeRes).toEqual({+ mergedLayerId: 'merged-hero',+ removedFolderId: 'folder-1',+ removedDescendantIds: ['child-top', 'sub-1', 'child-bottom', 'child-hidden'],+ });+ expect(layerMgrApi!.layers.map((l) => l.id)).toEqual(['merged-hero', 'outside']);+ expect(layerMgrApi!.activeLayerId).toBe('merged-hero');++ const mergedMeta = layerMgrApi!.layers[0];+ expect(mergedMeta.name).toBe('Hero');+ expect(mergedMeta.type).toBe('raster');+ expect(mergedMeta.opacity).toBe(0.75);+ expect(mergedMeta.blendMode).toBe('normal');++ // Verify composited pixels on merged-hero+ expect(grid.getPixelRGBA('merged-hero', 15, 15)).toEqual([255, 0, 0, 255]); // Red from child-bottom+ expect(grid.getPixelRGBA('merged-hero', 25, 15)).toEqual([0, 0, 255, 255]); // Blue over Red from child-top+ expect(grid.getPixelRGBA('merged-hero', 55, 55)).toEqual([0, 0, 0, 0]); // Hidden green excluded+ expect(grid.getPixelRGBA('outside', 85, 85)).toEqual([255, 255, 0, 255]); // Outside untouched+ expect(grid.hasLayerTiles('child-top')).toBe(false);+ expect(grid.hasLayerTiles('child-bottom')).toBe(false);+ expect(grid.hasLayerTiles('child-hidden')).toBe(false);++ // Undo Merge Folder -> restores folder, all descendants, and all pixels+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex - 1);+ });++ expect(layerMgrApi!.layers.map((l) => l.id)).toEqual(initialLayers.map((l) => l.id));+ expect(layerMgrApi!.activeLayerId).toBe('folder-1');+ expect(grid.hasLayerTiles('merged-hero')).toBe(false);+ expect(grid.getPixelRGBA('child-bottom', 15, 15)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('child-top', 25, 15)).toEqual([0, 0, 255, 255]);+ expect(grid.getPixelRGBA('child-hidden', 55, 55)).toEqual([0, 255, 0, 255]);++ // Redo Merge Folder -> re-applies merged raster layer and its pixels+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex + 1);+ });++ expect(layerMgrApi!.layers.map((l) => l.id)).toEqual(['merged-hero', 'outside']);+ expect(layerMgrApi!.activeLayerId).toBe('merged-hero');+ expect(grid.getPixelRGBA('merged-hero', 15, 15)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('merged-hero', 25, 15)).toEqual([0, 0, 255, 255]);+ });++ it('applies Transform to all layers inside a selected folder, supports Cancel, and commits atomically for Undo/Redo', async () => {+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 160, height: 160 };+ const toasts: string[] = [];++ const layers: LayerItem[] = [+ makeLayer('folder-art', { name: 'Art Folder', type: 'folder' }),+ makeLayer('layer-a', { name: 'Layer A', parentId: 'folder-art' }),+ makeLayer('sub-folder', { name: 'Nested', type: 'folder', parentId: 'folder-art' }),+ makeLayer('layer-b', { name: 'Layer B', parentId: 'sub-folder' }),+ makeLayer('layer-outside', { name: 'Outside' }),+ ];++ // Layer A: red square at (10..20, 10..20)+ // Layer B: blue square at (30..40, 30..40)+ // Outside: green square at (100..110, 100..110)+ paintRect(grid, 'layer-a', 10, 10, 10, 10, 255, 0, 0, 255);+ paintRect(grid, 'layer-b', 30, 30, 10, 10, 0, 0, 255, 255);+ paintRect(grid, 'layer-outside', 100, 100, 10, 10, 0, 255, 0, 255);++ let selApi: ReturnType<typeof useSelectionTools> | null = null;+ let historyApi: ReturnType<typeof useDrawingHistory> | null = null;+ const pushHistorySpy = vi.fn();++ function Harness() {+ const dimsRef = useRef(dims);+ const activeLayerIdRef = useRef('folder-art');+ const colorModeRef = useRef<'color' | 'grayscale' | 'monochrome'>('color');+ const layersRef = useRef<LayerItem[] | undefined>(layers);+ const updateMaskRef = useRef<((id: string) => void) | undefined>(undefined);+ const isDrawingRef = useRef(false);+ const lastStrokeEndRef = useRef(null);+ const abortRef = useRef(() => {});++ const history = useDrawingHistory({+ tileGrid: grid,+ activeLayerId: 'folder-art',+ activeLayerLocked: false,+ dimensions: dims,+ dimensionsRef: dimsRef,+ activeLayerIdRef,+ colorModeRef,+ layersRef,+ onUpdateLayerThumbnail: () => {},+ onUpdateMaskThumbnailRef: updateMaskRef,+ isDrawingRef,+ lastStrokeEndRef,+ abortActiveStrokeRef: abortRef,+ });++ const wrappedPush: typeof history.pushHistoryStep = (...args) => {+ pushHistorySpy(...args);+ history.pushHistoryStep(...args);+ };++ const selectionTools = useSelectionTools({+ dimensions: dims,+ colorMode: 'color',+ layers,+ activeLayer: layers[0], // folder-art is selected!+ activeLayerId: 'folder-art',+ selectedLayerIds: ['folder-art'],+ tileGrid: grid,+ updateLayerThumbnail: () => {},+ pushHistoryStep: wrappedPush,+ showToast: (m) => toasts.push(m),+ });++ selApi = selectionTools;+ historyApi = history;+ return null;+ }++ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ // 1. Start transform on selected folder+ act(() => {+ selApi!.handleStartTransform();+ });++ expect(selApi!.transformSession?.active).toBe(true);+ expect(selApi!.transformSession?.layerIds).toEqual(['layer-a', 'layer-b']);+ // Original pixels lifted/cleared from both child layers while outside layer stays intact+ expect(grid.getPixelRGBA('layer-a', 15, 15)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('layer-b', 35, 35)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('layer-outside', 105, 105)).toEqual([0, 255, 0, 255]);++ // 2. Cancel transform -> restores both child layers identically+ act(() => {+ selApi!.handleCancelTransform();+ });++ expect(selApi!.transformSession).toBeNull();+ expect(grid.getPixelRGBA('layer-a', 15, 15)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('layer-b', 35, 35)).toEqual([0, 0, 255, 255]);+ expect(pushHistorySpy).not.toHaveBeenCalled();++ // 3. Start again, translate by (+20, +15), and Apply+ act(() => {+ selApi!.handleStartTransform();+ });+ expect(selApi!.transformSession?.active).toBe(true);++ act(() => {+ selApi!.setTransformSession((prev) =>+ prev ? { ...prev, x: prev.x + 20, y: prev.y + 15 } : null+ );+ });++ act(() => {+ selApi!.handleApplyTransform();+ });++ expect(selApi!.transformSession).toBeNull();+ // Both child layers translated by (+20, +15)+ expect(grid.getPixelRGBA('layer-a', 15, 15)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('layer-a', 35, 30)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('layer-b', 35, 35)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('layer-b', 55, 50)).toEqual([0, 0, 255, 255]);+ // Outside layer completely untouched+ expect(grid.getPixelRGBA('layer-outside', 105, 105)).toEqual([0, 255, 0, 255]);+ // Recorded as ONE atomic history step+ expect(pushHistorySpy).toHaveBeenCalledTimes(1);++ // 4. Single Undo restores BOTH child layers simultaneously+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex - 1);+ });++ expect(grid.getPixelRGBA('layer-a', 15, 15)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('layer-a', 35, 30)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('layer-b', 35, 35)).toEqual([0, 0, 255, 255]);+ expect(grid.getPixelRGBA('layer-b', 55, 50)).toEqual([0, 0, 0, 0]);++ // 5. Single Redo re-applies transform to BOTH child layers simultaneously+ await act(async () => {+ await historyApi!.jumpToHistoryIndex(historyApi!.historyIndex + 1);+ });++ expect(grid.getPixelRGBA('layer-a', 35, 30)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('layer-b', 55, 50)).toEqual([0, 0, 255, 255]);+ expect(toasts).toEqual([]);+ });++ it('transforms a folder containing a single child raster layer cleanly', () => {+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 128, height: 128 };++ const layers: LayerItem[] = [+ makeLayer('folder-single', { name: 'Single Folder', type: 'folder' }),+ makeLayer('only-child', { name: 'Only Child', parentId: 'folder-single' }),+ ];+ paintRect(grid, 'only-child', 10, 10, 12, 12, 200, 100, 50, 255);++ let selApi: ReturnType<typeof useSelectionTools> | null = null;+ const pushHistorySpy = vi.fn();++ function Harness() {+ selApi = useSelectionTools({+ dimensions: dims,+ colorMode: 'color',+ layers,+ activeLayer: layers[0],+ activeLayerId: 'folder-single',+ selectedLayerIds: ['folder-single'],+ tileGrid: grid,+ updateLayerThumbnail: () => {},+ pushHistoryStep: pushHistorySpy,+ showToast: () => {},+ });+ return null;+ }++ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ act(() => {+ selApi!.handleStartTransform();+ });+ expect(selApi!.transformSession?.active).toBe(true);+ expect(selApi!.transformSession?.layerId).toBe('only-child');++ act(() => {+ selApi!.setTransformSession((prev) =>+ prev ? { ...prev, x: prev.x + 15, y: prev.y + 10 } : null+ );+ });+ act(() => {+ selApi!.handleApplyTransform();+ });++ expect(grid.getPixelRGBA('only-child', 12, 12)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('only-child', 30, 25)).toEqual([200, 100, 50, 255]);+ expect(pushHistorySpy).toHaveBeenCalledTimes(1);+ });++ it('transforms only the selected region across all layers in a folder when a selection is active', () => {+ const grid = new SparseTileGrid();+ const dims: CanvasDimensions = { width: 128, height: 128 };++ const layers: LayerItem[] = [+ makeLayer('folder-sel', { name: 'Folder Sel', type: 'folder' }),+ makeLayer('sel-a', { name: 'A', parentId: 'folder-sel' }),+ makeLayer('sel-b', { name: 'B', parentId: 'folder-sel' }),+ ];+ // Paint two 10x10 squares on each layer: one inside selection (10..20) and one outside (80..90)+ paintRect(grid, 'sel-a', 10, 10, 10, 10, 255, 0, 0, 255);+ paintRect(grid, 'sel-a', 80, 80, 10, 10, 255, 0, 0, 255);+ paintRect(grid, 'sel-b', 10, 10, 10, 10, 0, 0, 255, 255);+ paintRect(grid, 'sel-b', 80, 80, 10, 10, 0, 0, 255, 255);++ let selApi: ReturnType<typeof useSelectionTools> | null = null;+ const pushHistorySpy = vi.fn();++ function Harness() {+ selApi = useSelectionTools({+ dimensions: dims,+ colorMode: 'color',+ layers,+ activeLayer: layers[0],+ activeLayerId: 'folder-sel',+ selectedLayerIds: ['folder-sel'],+ tileGrid: grid,+ updateLayerThumbnail: () => {},+ pushHistoryStep: pushHistorySpy,+ showToast: () => {},+ });+ return null;+ }++ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ // Set a rectangular selection around (8..22, 8..22)+ act(() => {+ selApi!.setSelection({+ type: 'rect',+ bounds: { x: 8, y: 8, width: 14, height: 14 },+ });+ });++ act(() => {+ selApi!.handleStartTransform();+ });+ expect(selApi!.transformSession?.active).toBe(true);+ expect(selApi!.transformSession?.isSelection).toBe(true);+ expect(selApi!.transformSession?.layerIds).toEqual(['sel-a', 'sel-b']);++ // Pixels outside selection stay untouched; pixels inside selection are lifted+ expect(grid.getPixelRGBA('sel-a', 15, 15)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('sel-b', 15, 15)).toEqual([0, 0, 0, 0]);+ expect(grid.getPixelRGBA('sel-a', 85, 85)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('sel-b', 85, 85)).toEqual([0, 0, 255, 255]);++ // Move selection by (+30, +0) and apply+ act(() => {+ selApi!.setTransformSession((prev) => (prev ? { ...prev, x: prev.x + 30 } : null));+ });+ act(() => {+ selApi!.handleApplyTransform();+ });++ expect(grid.getPixelRGBA('sel-a', 45, 15)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('sel-b', 45, 15)).toEqual([0, 0, 255, 255]);+ expect(grid.getPixelRGBA('sel-a', 85, 85)).toEqual([255, 0, 0, 255]);+ expect(grid.getPixelRGBA('sel-b', 85, 85)).toEqual([0, 0, 255, 255]);+ expect(pushHistorySpy).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/utils/__tests__/ltConversion.test.ts b/src/utils/__tests__/ltConversion.test.tsindex 3608720..20ba760 100644--- a/src/utils/__tests__/ltConversion.test.ts+++ b/src/utils/__tests__/ltConversion.test.ts@@ -2,28 +2,74 @@ import { describe, it, expect, vi } from 'vitest';import * as THREE from 'three';function createMockCanvas(width = 64, height = 64) {+ let pixels = new Uint8ClampedArray(width * height * 4);const canvas: any = {- width,- height,+ get width() {+ return width;+ },+ set width(v: number) {+ width = v;+ pixels = new Uint8ClampedArray(width * height * 4);+ },+ get height() {+ return height;+ },+ set height(v: number) {+ height = v;+ pixels = new Uint8ClampedArray(width * height * 4);+ },+ getData: () => pixels,getContext: () => ({+ imageSmoothingEnabled: true,createImageData: (w: number, h: number) => ({width: w,height: h,data: new Uint8ClampedArray(w * h * 4),}),- getImageData: (_x: number, _y: number, w: number, h: number) => {- const data = new Uint8ClampedArray(w * h * 4);- // Fill diffuse buffer with mid-gray (lum ~ 0.5) so tone layers trigger- for (let i = 0; i < data.length; i += 4) {- data[i] = 100;- data[i + 1] = 100;- data[i + 2] = 100;- data[i + 3] = 255;+ getImageData: (x: number, y: number, w: number, h: number) => {+ const out = new Uint8ClampedArray(w * h * 4);+ let hasAny = false;+ for (let i = 3; i < pixels.length; i += 4) {+ if (pixels[i] !== 0) {+ hasAny = true;+ break;+ }+ }+ if (!hasAny) {+ // Default diffuse buffer with two shadow bands: left half mid-gray (lum ~ 0.47), right half deep shadow (lum ~ 0.20)+ for (let row = 0; row < h; row++) {+ for (let col = 0; col < w; col++) {+ const i = (row * w + col) * 4;+ const v = col < w / 2 ? 120 : 50;+ out[i] = v;+ out[i + 1] = v;+ out[i + 2] = v;+ out[i + 3] = 255;+ }+ }+ return { width: w, height: h, data: out };+ }+ for (let row = 0; row < h; row++) {+ const srcStart = ((y + row) * width + x) * 4;+ out.set(pixels.subarray(srcStart, srcStart + w * 4), row * w * 4);+ }+ return { width: w, height: h, data: out };+ },+ putImageData: (img: ImageData, x: number, y: number) => {+ for (let row = 0; row < img.height; row++) {+ const dstStart = ((y + row) * width + x) * 4;+ const srcStart = row * img.width * 4;+ pixels.set(img.data.subarray(srcStart, srcStart + img.width * 4), dstStart);+ }+ },+ drawImage: (src: any) => {+ if (src && typeof src.getData === 'function') {+ const srcData: Uint8ClampedArray = src.getData();+ if (srcData.length === pixels.length) {+ pixels.set(srcData);+ }}- return { width: w, height: h, data };},- putImageData: () => {},- drawImage: () => {},fillRect: () => {},clearRect: () => {},}),@@ -140,4 +186,99 @@ describe('3D LT Conversion Service', () => {expect(result.toneLayers[1].toneDensity).toBe(30);expect(result.toneLayers[2].toneDensity).toBe(50);});++ it('supports non-destructive previewOnly mode and outline-only extraction (toneCount = 0)', async () => {+ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial());+ scene.add(mesh);++ const onInsertLayers = vi.fn();++ const previewRes = await bake3DToLineAndTone({+ scene,+ camera,+ dimensions: { width: 32, height: 32 },+ modelName: 'PreviewModel',+ toneCount: 0,+ previewOnly: true,+ onInsertLayers,+ });++ expect(onInsertLayers).not.toHaveBeenCalled();+ expect(previewRes.lineCanvas).toBeDefined();+ expect(previewRes.toneLayers.length).toBe(0);+ expect(previewRes.toneCanvases.length).toBe(0);+ // Scene graph must remain intact after previewOnly render+ expect(scene.children.length).toBe(1);+ });++ it('prevents double-screentoning, overlapping band moiré, and AA blur in extracted 3D LT layers', async () => {+ const scene = new THREE.Scene();+ const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial());+ scene.add(mesh);++ const extracted = await bake3DToLineAndTone({+ scene,+ camera,+ dimensions: { width: 64, height: 64, dpi: 600 },+ modelName: 'CrispModel',+ toneCount: 2,+ });++ // Outline defaults to crisp monochrome (no AA gray smudges)+ expect(extracted.lineLayer.expressionColor).toBe('monochrome');++ // All tone tiers default to uniform 45° angle (no 45° vs 60° moiré interference)+ expect(extracted.toneLayers[0].toneAngle).toBe(45);+ expect(extracted.toneLayers[1].toneAngle).toBe(45);+ expect(extracted.toneLayers[0].toneDotShape).toBe('circle');+ expect(extracted.toneLayers[1].toneDotShape).toBe('circle');++ // Extracted tone layers store mutually exclusive solid masks (no pre-baked dots on toneEnabled layers!)+ const lightData: Uint8ClampedArray = (extracted.toneCanvases[0] as any).getData();+ const deepData: Uint8ClampedArray = (extracted.toneCanvases[1] as any).getData();++ let lightSolid = 0;+ let deepSolid = 0;+ let overlapCount = 0;+ for (let i = 0; i < 64 * 64; i++) {+ const aL = lightData[i * 4 + 3];+ const aD = deepData[i * 4 + 3];+ // Strictly binary solid mask pixels (0 or 255)+ expect(aL === 0 || aL === 255).toBe(true);+ expect(aD === 0 || aD === 255).toBe(true);+ if (aL === 255) lightSolid++;+ if (aD === 255) deepSolid++;+ if (aL === 255 && aD === 255) overlapCount++;+ }+ // Left half (32*64 = 2048 px) is light shadow, right half (2048 px) is deep shadow -> zero overlap!+ expect(lightSolid).toBe(32 * 64);+ expect(deepSolid).toBe(32 * 64);+ expect(overlapCount).toBe(0);++ // previewOnly renders crisp 1-bit binary halftone dots (strictly 0 or 255 alpha, no gray blur)+ const preview = await bake3DToLineAndTone({+ scene,+ camera,+ dimensions: { width: 64, height: 64, dpi: 600 },+ modelName: 'CrispModel',+ toneCount: 2,+ previewOnly: true,+ });+ const prevDeep: Uint8ClampedArray = (preview.toneCanvases[1] as any).getData();+ let prevBlack = 0;+ let prevEmptyInDeepRegion = 0;+ for (let y = 0; y < 64; y++) {+ for (let x = 32; x < 64; x++) {+ const a = prevDeep[(y * 64 + x) * 4 + 3];+ expect(a === 0 || a === 255).toBe(true);+ if (a === 255) prevBlack++;+ else prevEmptyInDeepRegion++;+ }+ }+ expect(prevBlack).toBeGreaterThan(0);+ expect(prevEmptyInDeepRegion).toBeGreaterThan(0);+ });});diff --git a/src/utils/__tests__/pigmentBlending.test.ts b/src/utils/__tests__/pigmentBlending.test.tsnew file mode 100644index 0000000..da6637c--- /dev/null+++ b/src/utils/__tests__/pigmentBlending.test.ts@@ -0,0 +1,228 @@+import { describe, it, expect } from 'vitest';+import {+ mixSubtractivePigments,+ mixPigmentsWithStrength,+ mixPigmentRgbOut,+ parseColorToRgb,+} from '../colorMixingEngine';+import {+ DEFAULT_RETOUCH_SETTINGS,+ applyRetouchStrokeSegment,+ createRetouchStrokeSession,+} from '../retouchEngine';+import { sampleGradientStops, ParsedRgbaStop } from '../gradientEngine';+import { buildPigmentPreviewGradient } from '../../components/PigmentBlendControl';+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+) {+ grid.setLayerFormat(layerId, 'color-32bit');+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < w * h; i++) {+ const o = i * 4;+ data[o] = r;+ data[o + 1] = g;+ data[o + 2] = b;+ data[o + 3] = a;+ }+ grid.writeImageData(layerId, { data, width: w, height: h }, x, y, 'color-32bit', true);+}++describe('7-Band Spectral Kubelka-Munk Pigment Blending', () => {+ it('mixes Blue + Yellow into vibrant Green (vs dull gray in Regular RGB)', () => {+ const blue = { r: 0, g: 136, b: 255 };+ const yellow = { r: 255, g: 244, b: 0 };++ const pigment = mixSubtractivePigments(blue, yellow, 0.5);+ const regular = mixPigmentsWithStrength(blue, yellow, 0.5, 0);++ // Regular RGB collapses toward gray-olive (r ≈ b ≈ 128)+ expect(Math.abs(regular.r - regular.b)).toBeLessThan(2);++ // Spectral pigment produces clearly green-dominant emerald hue+ expect(pigment.g).toBeGreaterThan(pigment.r + 50);+ expect(pigment.g).toBeGreaterThan(pigment.b + 50);+ });++ it('mixes Green + Magenta into warm golden-amber instead of muddy gray', () => {+ const green = { r: 40, g: 255, b: 0 };+ const magenta = { r: 255, g: 0, b: 170 };++ const pigment = mixSubtractivePigments(green, magenta, 0.5);++ // Warm golden-amber: red & green strongly exceed blue+ expect(pigment.r).toBeGreaterThan(pigment.b + 70);+ expect(pigment.g).toBeGreaterThan(pigment.b + 50);+ });++ it('mixes Red + Yellow into vibrant Orange and Red + Blue into rich Violet', () => {+ const red = { r: 235, g: 20, b: 20 };+ const yellow = { r: 255, g: 240, b: 0 };+ const blue = { r: 15, g: 60, b: 240 };++ const orange = mixSubtractivePigments(red, yellow, 0.5);+ expect(orange.r).toBeGreaterThan(220);+ expect(orange.g).toBeGreaterThan(110);+ expect(orange.b).toBeLessThan(30);++ const violet = mixSubtractivePigments(red, blue, 0.5);+ expect(violet.r).toBeGreaterThan(violet.g + 60);+ expect(violet.b).toBeGreaterThan(violet.g + 60);+ });++ it('keeps Black + White strictly neutral gray and preserves exact self-mix invariance', () => {+ const gray50 = mixSubtractivePigments({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 }, 0.5);+ expect(Math.abs(gray50.r - gray50.g)).toBeLessThan(1.5);+ expect(Math.abs(gray50.g - gray50.b)).toBeLessThan(1.5);++ const testColors = [+ { r: 0, g: 136, b: 255 },+ { r: 255, g: 244, b: 0 },+ { r: 40, g: 255, b: 0 },+ { r: 255, g: 0, b: 170 },+ { r: 155, g: 0, b: 255 },+ { r: 0, g: 0, b: 0 },+ { r: 255, g: 255, b: 255 },+ ];+ const out = { r: 0, g: 0, b: 0 };+ for (const c of testColors) {+ mixPigmentRgbOut(c.r, c.g, c.b, c.r, c.g, c.b, 0.5, 1.0, out);+ expect(Math.abs(out.r - c.r)).toBeLessThan(1.5);+ expect(Math.abs(out.g - c.g)).toBeLessThan(1.5);+ expect(Math.abs(out.b - c.b)).toBeLessThan(1.5);+ }+ });++ it('Retouch Smudge produces vibrant Green when blending Blue into Yellow with Pigment Blending enabled', () => {+ const runSmudge = (pigmentBlending: boolean) => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ const layerId = 'layer-pigment-smudge';+ // Left half: Blue, Right half: Yellow+ fillRectRgba(grid, layerId, 0, 0, 64, 128, 0, 120, 255, 255);+ fillRectRgba(grid, layerId, 64, 0, 64, 128, 255, 240, 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: 32,+ strength: 75,+ hardness: 70,+ usePressure: false,+ pigmentBlending,+ pigmentStrength: 100,+ };++ applyRetouchStrokeSegment({ grid, session, pt: { x: 48, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });+ applyRetouchStrokeSegment({ grid, session, pt: { x: 76, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });++ // Peak green dominance across the smudged Blue -> Yellow transition zone (x = 64..90)+ let maxGreenDom = -999;+ for (let x = 64; x <= 90; x++) {+ const px = grid.getPixelRGBA(layerId, x, 64);+ const dom = px[1] - Math.max(px[0], px[2]);+ if (dom > maxGreenDom) maxGreenDom = dom;+ }+ return maxGreenDom;+ };++ const pigGreenDom = runSmudge(true);+ const regGreenDom = runSmudge(false);++ // Pigment smudge pushes vibrant green well above regular RGB smudge+ expect(pigGreenDom).toBeGreaterThan(40);+ expect(pigGreenDom).toBeGreaterThan(regGreenDom + 25);+ });++ it('Retouch Blur produces Green across a Blue | Yellow seam when Pigment Blending is enabled', () => {+ const runBlur = (pigmentBlending: boolean) => {+ const grid = new SparseTileGrid();+ const dims = { width: 128, height: 128 };+ const layerId = 'layer-pigment-blur';+ fillRectRgba(grid, layerId, 0, 0, 64, 128, 0, 110, 255, 255);+ fillRectRgba(grid, layerId, 64, 0, 64, 128, 255, 242, 0, 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: 36,+ strength: 100,+ hardness: 80,+ usePressure: false,+ pigmentBlending,+ pigmentStrength: 100,+ };++ applyRetouchStrokeSegment({ grid, session, pt: { x: 64, y: 64 }, pressure: 1, settings, primaryColor: '#000000' });+ return grid.getPixelRGBA(layerId, 64, 64);+ };++ const pigPx = runBlur(true);+ const regPx = runBlur(false);++ const pigGreenDom = pigPx[1] - Math.max(pigPx[0], pigPx[2]);+ const regGreenDom = regPx[1] - Math.max(regPx[0], regPx[2]);+ expect(pigGreenDom).toBeGreaterThan(35);+ expect(pigGreenDom).toBeGreaterThan(regGreenDom + 25);+ });++ it('Gradient stop sampling blends Blue -> Yellow through Green when pigmentBlending is enabled', () => {+ const stops: ParsedRgbaStop[] = [+ { offset: 0, r: 0, g: 120, b: 255, a: 255 },+ { offset: 1, r: 255, g: 244, b: 0, a: 255 },+ ];+ const regOut: [number, number, number, number] = [0, 0, 0, 0];+ const pigOut: [number, number, number, number] = [0, 0, 0, 0];++ sampleGradientStops(stops, 0.5, 'clamp', false, regOut, false);+ sampleGradientStops(stops, 0.5, 'clamp', false, pigOut, true);++ expect(pigOut[1]).toBeGreaterThan(pigOut[0] + 50);+ expect(pigOut[1]).toBeGreaterThan(pigOut[2] + 50);+ expect(Math.abs(regOut[0] - regOut[2])).toBeLessThan(2);+ });++ it('PigmentBlendControl preview gradient visually distinguishes Regular vs Pigment midpoints', () => {+ const regGrad = buildPigmentPreviewGradient('#0084ff', '#fff000', false, 1.0);+ const pigGrad = buildPigmentPreviewGradient('#0084ff', '#fff000', true, 1.0);+ expect(regGrad).not.toBe(pigGrad);++ // Extract the 50% stop hex from both CSS gradients+ const regMidMatch = regGrad.match(/(#[0-9a-f]{6}) 50%/i);+ const pigMidMatch = pigGrad.match(/(#[0-9a-f]{6}) 50%/i);+ expect(regMidMatch).toBeTruthy();+ expect(pigMidMatch).toBeTruthy();++ const regMid = parseColorToRgb(regMidMatch![1]);+ const pigMid = parseColorToRgb(pigMidMatch![1]);+ expect(pigMid.g - Math.max(pigMid.r, pigMid.b)).toBeGreaterThan(+ regMid.g - Math.max(regMid.r, regMid.b) + 30+ );+ });+});diff --git a/src/utils/__tests__/screentoneEngine.test.ts b/src/utils/__tests__/screentoneEngine.test.tsindex d60839d..65a58ae 100644--- a/src/utils/__tests__/screentoneEngine.test.ts+++ b/src/utils/__tests__/screentoneEngine.test.ts@@ -1,24 +1,111 @@import { describe, it, expect } from 'vitest';import {+ applyScreentoneCPU,+ computeRationalHalftoneBasis,evaluateHalftoneDot,fract,} from '../screentoneEngine';+import { isDedicatedToneLayer, resolveToneDensityType } from '../../types/editor';+import { sanitizeWireLayer } from '../collabSyncUtils';++function createMockCanvas(width: number, height: number, pixels: Uint8ClampedArray) {+ let stored = new Uint8ClampedArray(pixels);+ const ctx = {+ createImageData: (w: number, h: number) => ({+ width: w,+ height: h,+ data: new Uint8ClampedArray(w * h * 4),+ }),+ getImageData: (x: number, y: number, w: number, h: number) => {+ const out = new Uint8ClampedArray(w * h * 4);+ for (let row = 0; row < h; row++) {+ const srcStart = ((y + row) * width + x) * 4;+ out.set(stored.subarray(srcStart, srcStart + w * 4), row * w * 4);+ }+ return { width: w, height: h, data: out };+ },+ putImageData: (img: ImageData, x: number, y: number) => {+ for (let row = 0; row < img.height; row++) {+ const dstStart = ((y + row) * width + x) * 4;+ const srcStart = row * img.width * 4;+ stored.set(img.data.subarray(srcStart, srcStart + img.width * 4), dstStart);+ }+ },+ };+ return {+ width,+ height,+ getContext: () => ctx,+ getData: () => stored,+ } as unknown as HTMLCanvasElement & { getData: () => Uint8ClampedArray };+}describe('Anti-Moiré Manga Screentone GPU & CPU Pipeline', () => {- it('evaluates Euclidean manga dot spot formula correctly', () => {+ it('evaluates Clip Studio Paint circle & Euclidean halftone dot formulas accurately', () => {const cosA = Math.cos(Math.PI / 4);const sinA = Math.sin(Math.PI / 4);- const cellSize = 10; // 600 DPI / 60 LPI+ const cellSize = 10; // 600 DPI / 60 LPI -> rational basis (7, 7), denom = 98- // Center of a cell (xr = cellSize * 0.5) with 50% density should be black ink- const centerX = cellSize * 0.5 * cosA;- const centerY = cellSize * 0.5 * sinA;- const isInk = evaluateHalftoneDot(centerX, centerY, 0.5, cellSize, cosA, sinA, 'circle');- expect(isInk).toBe(true);+ // True center of a 45° cell: xr = 7*7 - 0*7 = 49 = denom/2, yr = 7*7 + 0*7 = 49 = denom/2 -> (u=0, v=0)+ expect(evaluateHalftoneDot(7, 0, 0.2, cellSize, cosA, sinA, 'circle')).toBe(true);+ expect(evaluateHalftoneDot(7, 0, 0.5, cellSize, cosA, sinA, 'euclidean')).toBe(true);- // Far corner of cell (u = 0.5, v = 0.5) with 10% density should be white paper- const isInkCorner = evaluateHalftoneDot(0, 0, 0.1, cellSize, cosA, sinA, 'circle');- expect(isInkCorner).toBe(false);+ // Far corner of cell (x = 0, y = 0 -> u = -0.5, v = -0.5) with 10% density should be white paper+ expect(evaluateHalftoneDot(0, 0, 0.1, cellSize, cosA, sinA, 'circle')).toBe(false);+ expect(evaluateHalftoneDot(0, 0, 0.1, cellSize, cosA, sinA, 'euclidean')).toBe(false);+ });++ it('produces strictly 1-bit binary Clip Studio dots with zero gray anti-aliasing fringe and exact periodicity', () => {+ const w = 84; // 6 full 14px periods at 600 DPI / 60 LPI / 45°+ const h = 84;+ const srcPixels = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < srcPixels.length; i += 4) {+ srcPixels[i] = 0;+ srcPixels[i + 1] = 0;+ srcPixels[i + 2] = 0;+ srcPixels[i + 3] = 255;+ }++ const srcCanvas = createMockCanvas(w, h, srcPixels);+ const dstCanvas = createMockCanvas(w, h, new Uint8ClampedArray(w * h * 4));+ // Default options (no antiAliasing flag needed -> strict 1-bit binary by default)+ applyScreentoneCPU(srcCanvas, dstCanvas, {+ frequency: 60,+ dpi: 600,+ angle: 45,+ dotShape: 'circle',+ densityType: 'specified',+ specifiedDensity: 0.4,+ });++ const out = dstCanvas.getData();+ const { a, b } = computeRationalHalftoneBasis(10, Math.cos(Math.PI / 4), Math.sin(Math.PI / 4));+ expect(a).toBe(7);+ expect(b).toBe(7);++ let blackCount = 0;+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const idx = (y * w + x) * 4;+ const alpha = out[idx + 3];+ // Strictly 1-bit binary: zero gray anti-aliasing pixels+ expect(alpha === 0 || alpha === 255).toBe(true);+ if (alpha === 255) blackCount++;++ // Exact integer-lattice periodicity: every dot separated by (14, 0) or (7, 7) is bit-for-bit identical+ if (x + 14 < w) {+ expect(out[(y * w + (x + 14)) * 4 + 3]).toBe(alpha);+ }+ if (x + 7 < w && y + 7 < h) {+ expect(out[((y + 7) * w + (x + 7)) * 4 + 3]).toBe(alpha);+ }+ }+ }++ // Area-calibrated coverage at 40% density should be closely centered near 40%+ const coverage = blackCount / (w * h);+ expect(coverage).toBeGreaterThan(0.35);+ expect(coverage).toBeLessThan(0.45);});it('fract function strictly yields [0.0, 1.0)', () => {@@ -27,4 +114,104 @@ describe('Anti-Moiré Manga Screentone GPU & CPU Pipeline', () => {expect(fract(-0.25)).toBeCloseTo(0.75);expect(fract(-1.5)).toBeCloseTo(0.5);});++ it('distinguishes dedicated screen tone layers from existing layers with tone effect', () => {+ // Dedicated screen tone layer -> editable flat specified density+ expect(isDedicatedToneLayer({ isToneLayer: true, toneDensityType: 'specified' })).toBe(true);+ expect(resolveToneDensityType({ isToneLayer: true, toneDensityType: 'specified' })).toBe('specified');++ // Existing normal layer with screentone toggled on -> adapts to layer tones+ expect(isDedicatedToneLayer({ toneDensityType: undefined })).toBe(false);+ expect(resolveToneDensityType({ toneDensityType: undefined })).toBe('image');+ expect(isDedicatedToneLayer({ isToneLayer: false, toneDensityType: 'image' })).toBe(false);+ expect(resolveToneDensityType({ isToneLayer: false, toneDensityType: 'image' })).toBe('image');++ // Legacy saved screen tone layer without isToneLayer flag preserves specified density+ expect(isDedicatedToneLayer({ toneDensityType: 'specified' })).toBe(true);+ expect(resolveToneDensityType({ toneDensityType: 'specified' })).toBe('specified');+ });++ it('adapts screentone dot density to layer brightness in image mode vs flat density in specified mode', () => {+ const w = 60;+ const h = 20;+ const srcPixels = new Uint8ClampedArray(w * h * 4);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 4;+ // 3 horizontal bands: dark gray (51), light gray (204), pure white (255)+ const v = x < 20 ? 51 : x < 40 ? 204 : 255;+ srcPixels[i] = v;+ srcPixels[i + 1] = v;+ srcPixels[i + 2] = v;+ srcPixels[i + 3] = 255;+ }+ }++ const srcCanvas = createMockCanvas(w, h, srcPixels);+ const imgTarget = createMockCanvas(w, h, new Uint8ClampedArray(w * h * 4));+ applyScreentoneCPU(srcCanvas, imgTarget, {+ frequency: 60,+ dpi: 600,+ angle: 45,+ densityType: 'image',+ specifiedDensity: 0.4,+ antiAliasing: false,+ });++ const countBandInk = (data: Uint8ClampedArray, x0: number, x1: number) => {+ let ink = 0;+ for (let y = 0; y < h; y++) {+ for (let x = x0; x < x1; x++) {+ if (data[(y * w + x) * 4 + 3] > 0) ink++;+ }+ }+ return ink;+ };++ const imgData = imgTarget.getData();+ const darkInk = countBandInk(imgData, 0, 20);+ const lightInk = countBandInk(imgData, 20, 40);+ const whiteInk = countBandInk(imgData, 40, 60);++ // Image tone mode adapts smoothly to layer brightness+ expect(darkInk).toBeGreaterThan(lightInk * 2);+ expect(lightInk).toBeGreaterThan(0);+ expect(whiteInk).toBe(0);++ // Specified density mode (dedicated tone layer) produces flat uniform density across all opaque bands+ const specTarget = createMockCanvas(w, h, new Uint8ClampedArray(w * h * 4));+ applyScreentoneCPU(srcCanvas, specTarget, {+ frequency: 60,+ dpi: 600,+ angle: 45,+ densityType: 'specified',+ specifiedDensity: 0.4,+ antiAliasing: false,+ });+ const specData = specTarget.getData();+ const specBand1 = countBandInk(specData, 0, 20);+ const specBand3 = countBandInk(specData, 40, 60);+ expect(specBand1).toBeGreaterThan(0);+ expect(specBand3).toBeGreaterThan(0);+ expect(Math.abs(specBand1 - specBand3)).toBeLessThan(15);+ });++ it('preserves isToneLayer through multiplayer wire sanitization', () => {+ const sanitized = sanitizeWireLayer({+ id: 'tone-1',+ name: 'Screen Tone',+ type: 'raster',+ visible: true,+ opacity: 1,+ blendMode: 'normal',+ locked: false,+ parentId: null,+ isToneLayer: true,+ toneEnabled: true,+ toneDensity: 35,+ toneDensityType: 'specified',+ });+ expect(sanitized?.isToneLayer).toBe(true);+ expect(sanitized?.toneDensityType).toBe('specified');+ });});diff --git a/src/utils/__tests__/selectionFillScreentoneUndo.test.tsx b/src/utils/__tests__/selectionFillScreentoneUndo.test.tsxnew file mode 100644index 0000000..5ac5fea--- /dev/null+++ b/src/utils/__tests__/selectionFillScreentoneUndo.test.tsx@@ -0,0 +1,505 @@+import React, { act, useRef } from 'react';+import { createRoot, Root } from 'react-dom/client';+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { SparseTileGrid } from '../tileEngine';+import {+ executeFloodFillOnTileGrid,+ executeLassoFillOnTileGrid,+} from '../floodFill';+import { fillSelectionInTileGrid } from '../selectionUtils';+import { createSelectionMask } from '../tonalEngine';+import { useLayerManager } from '../../hooks/useLayerManager';+import { useDrawingHistory, PushHistoryStepFn } from '../../hooks/drawing';+import { isEditableTarget } from '../../components/GlobalShortcutListener';+import type { CanvasDimensions, CanvasSelection, LayerItem } from '../../types/editor';++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> = {};+ isContentEditable = false;+ type = '';+ 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;+}++const DIMS: CanvasDimensions = { width: 256, height: 256, dpi: 300 };++function makeTriangleLasso(): CanvasSelection {+ const polygon = [+ { x: 40, y: 40 },+ { x: 180, y: 40 },+ { x: 110, y: 180 },+ ];+ return {+ type: 'lasso',+ bounds: { x: 40, y: 40, width: 140, height: 140 },+ polygon,+ };+}++function paintSolidRect(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number,+ w: number,+ h: number,+ rgba: [number, number, number, number]+) {+ const data = new Uint8ClampedArray(w * h * 4);+ for (let i = 0; i < data.length; i += 4) {+ data[i] = rgba[0];+ data[i + 1] = rgba[1];+ data[i + 2] = rgba[2];+ data[i + 3] = rgba[3];+ }+ grid.writeImageData(layerId, { data, width: w, height: h }, x, y, 'color-32bit', true);+}++function readPixel(+ grid: SparseTileGrid,+ layerId: string,+ x: number,+ y: number+): [number, number, number, number] {+ const img = grid.readImageData(layerId, x, y, 1, 1);+ return [img.data[0], img.data[1], img.data[2], img.data[3]];+}++describe('Selection + Screentone, Fill Tool, LOD Invalidation, and Comprehensive Ctrl+Z Undo', () => {+ let root: Root | null = null;++ beforeEach(() => {+ installDomShim();+ });++ afterEach(() => {+ if (root) {+ act(() => {+ root!.unmount();+ });+ root = null;+ }+ });++ it('fillLayerSolidColor parses rgb(...) strings accurately instead of defaulting to white', () => {+ const grid = new SparseTileGrid();+ grid.fillLayerSolidColor('tone-1', 64, 64, 'rgb(0,0,0)', 'color-32bit');+ expect(readPixel(grid, 'tone-1', 10, 10)).toEqual([0, 0, 0, 255]);++ grid.fillLayerSolidColor('tone-2', 64, 64, 'rgb(120, 120, 120)', 'color-32bit');+ expect(readPixel(grid, 'tone-2', 10, 10)).toEqual([120, 120, 120, 255]);+ });++ it('createSelectionMask and fillSelectionInTileGrid clip strictly inside a lasso polygon even without 2D canvas context', () => {+ const lasso = makeTriangleLasso();+ const mask = createSelectionMask(lasso, DIMS.width, DIMS.height);+ expect(mask).not.toBeNull();+ // Centroid (110, 86) is inside triangle; corner (45, 170) is outside triangle but inside bounding box+ expect(mask![86 * DIMS.width + 110]).toBe(1);+ expect(mask![170 * DIMS.width + 45]).toBe(0);++ const grid = new SparseTileGrid();+ const res = fillSelectionInTileGrid({+ grid,+ layerId: 'layer-1',+ dimensions: DIMS,+ selection: lasso,+ colorCss: '#cc2244',+ targetFormat: 'color-32bit',+ });+ expect(res.tileDeltas.length).toBeGreaterThan(0);+ expect(readPixel(grid, 'layer-1', 110, 86)).toEqual([204, 34, 68, 255]);+ expect(readPixel(grid, 'layer-1', 45, 170)[3]).toBe(0);+ });++ it('executeFloodFillOnTileGrid respects lasso selectionMask, hidden folders, and alphaLock', () => {+ const grid = new SparseTileGrid();+ const lasso = makeTriangleLasso();+ const mask = createSelectionMask(lasso, DIMS.width, DIMS.height);++ // Put a barrier stroke inside a HIDDEN folder — refer-all must ignore it+ paintSolidRect(grid, 'hidden-child', 90, 60, 40, 60, [0, 0, 0, 255]);+ // White background layer+ grid.fillLayerSolidWhite('layer-bg', DIMS.width, DIMS.height, 'color-32bit');++ const layers: LayerItem[] = [+ { id: 'layer-1', name: 'Layer 1', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: null },+ { id: 'folder-hidden', name: 'Hidden Folder', type: 'folder', visible: false, opacity: 1, blendMode: 'pass-through', locked: false, parentId: null },+ { id: 'hidden-child', name: 'Hidden Child', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: false, parentId: 'folder-hidden' },+ { id: 'layer-bg', name: 'Background', type: 'raster', visible: true, opacity: 1, blendMode: 'normal', locked: true, parentId: null },+ ];++ const fillRes = executeFloodFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ layers,+ dimensions: DIMS,+ startX: 110,+ startY: 86,+ fillColorHex: '#2563eb',+ tolerance: 24,+ referMode: 'refer-all',+ options: { selectionMask: mask, antiAlias: false },+ });++ expect(fillRes.modified).toBe(true);+ expect(fillRes.tileDeltas.length).toBeGreaterThan(0);+ // Inside lasso filled (even where hidden-child was)+ expect(readPixel(grid, 'layer-1', 110, 86)).toEqual([37, 99, 235, 255]);+ // Outside lasso untouched+ expect(readPixel(grid, 'layer-1', 45, 170)[3]).toBe(0);+ expect(readPixel(grid, 'layer-1', 10, 10)[3]).toBe(0);++ // Now test alphaLocked: filling over layer-1 should recolor existing pixels without leaking into transparent ones+ const recolorRes = executeFloodFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ layers,+ dimensions: DIMS,+ startX: 110,+ startY: 86,+ fillColorHex: '#ef4444',+ tolerance: 24,+ referMode: 'active',+ options: { alphaLocked: true, antiAlias: false },+ });+ expect(recolorRes.modified).toBe(true);+ expect(readPixel(grid, 'layer-1', 110, 86)).toEqual([239, 68, 68, 255]);+ expect(readPixel(grid, 'layer-1', 45, 170)[3]).toBe(0);+ });++ it('executeLassoFillOnTileGrid clips strictly to active selectionMask', () => {+ const grid = new SparseTileGrid();+ const rectSel: CanvasSelection = {+ type: 'rect',+ bounds: { x: 50, y: 50, width: 60, height: 60 },+ };+ const selMask = createSelectionMask(rectSel, DIMS.width, DIMS.height);++ const res = executeLassoFillOnTileGrid({+ grid,+ targetLayerId: 'layer-1',+ dimensions: DIMS,+ polygon: [+ { x: 10, y: 10 },+ { x: 200, y: 10 },+ { x: 200, y: 200 },+ { x: 10, y: 200 },+ ],+ fillColorHex: '#10b981',+ selectionMask: selMask,+ });++ expect(res.modified).toBe(true);+ expect(readPixel(grid, 'layer-1', 80, 80)).toEqual([16, 185, 129, 255]);+ expect(readPixel(grid, 'layer-1', 20, 20)[3]).toBe(0);+ });++ it('evicts stale LOD 3 mipmap tiles when undoing back to an empty layer (prevents stale thumbnails & Navigator preview)', () => {+ const grid = new SparseTileGrid();+ const beforeSnap = grid.snapshotLayerTiles('layer-1');+ paintSolidRect(grid, 'layer-1', 20, 20, 100, 100, [20, 20, 20, 255]);+ const deltas = grid.computeDeltasFromSnapshot(beforeSnap, 'layer-1', {+ x: 0,+ y: 0,+ width: 256,+ height: 256,+ });+ expect(deltas.length).toBeGreaterThan(0);++ // Populate LOD 3 cache (as Layer Thumbnail and Navigator Preview do)+ const lod3Before = grid.getOrBuildLod3Tiles('layer-1');+ expect(lod3Before.length).toBe(1);++ // Undo back to empty layer+ grid.applyTileDeltas(deltas, 'undo');+ expect(grid.getLayerTiles('layer-1', 0).length).toBe(0);+ // LOD 3 MUST now be empty, never returning the stale pre-undo tile+ expect(grid.getOrBuildLod3Tiles('layer-1').length).toBe(0);+ });++ it('supports full Ctrl+Z / Ctrl+Y undo and redo for screentone, toggleTone with selection, layer CRUD, clear, merge, and rasterize', async () => {+ const grid = new SparseTileGrid();+ let harness!: {+ layerMgr: ReturnType<typeof useLayerManager>;+ history: ReturnType<typeof useDrawingHistory>;+ };++ const Harness: React.FC = () => {+ const pushHistoryStepRef = useRef<PushHistoryStepFn | null>(null);+ const layerMgr = useLayerManager({+ dimensions: DIMS,+ tileGrid: grid,+ pushHistoryStepRef,+ });++ const dimensionsRef = useRef(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: Boolean(layerMgr.activeLayer?.locked),+ dimensions: DIMS,+ dimensionsRef,+ activeLayerIdRef,+ colorModeRef,+ layersRef,+ onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,+ onApplyLayerTreeDeltaRef,+ onUpdateMaskThumbnailRef,+ isDrawingRef,+ lastStrokeEndRef,+ abortActiveStrokeRef,+ });++ pushHistoryStepRef.current = history.pushHistoryStep;+ harness = { layerMgr, history };+ return null;+ };++ const container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root!.render(<Harness />);+ });++ act(() => {+ harness.layerMgr.resetToNewCanvas(DIMS, '#ffffff', 'color', 60);+ harness.history.resetHistory();+ });++ const initialLayer1Id = harness.layerMgr.activeLayerId;+ expect(harness.layerMgr.layers.length).toBe(2);++ // 1. Screentone with Lasso selection -> Undo removes BOTH pixels AND Screen Tone layer -> Redo restores both+ const lasso = makeTriangleLasso();+ let toneId = '';+ act(() => {+ const res = harness.layerMgr.fillScreentoneSelection(lasso, 40, 60, 45, 'circle', 'specified');+ toneId = res.id;+ harness.history.pushHistoryStep(+ 'screentone',+ 'Screentone (40%)',+ null,+ null,+ res.id,+ lasso.bounds,+ res.tileDeltas,+ undefined,+ undefined,+ undefined,+ false,+ res.layerTreeDelta+ );+ });+ expect(harness.layerMgr.layers.some((l) => l.id === toneId)).toBe(true);+ expect(readPixel(grid, toneId, 110, 86)[3]).toBe(255);+ expect(readPixel(grid, toneId, 45, 170)[3]).toBe(0);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === toneId)).toBe(false);+ expect(grid.getLayerTiles(toneId, 0).length).toBe(0);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex + 1);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === toneId)).toBe(true);+ expect(readPixel(grid, toneId, 110, 86)[3]).toBe(255);++ // 2. Delete Screentone layer -> Undo restores BOTH layer AND pixels+ act(() => {+ harness.layerMgr.deleteLayer(toneId);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === toneId)).toBe(false);+ expect(grid.getLayerTiles(toneId, 0).length).toBe(0);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === toneId)).toBe(true);+ expect(readPixel(grid, toneId, 110, 86)[3]).toBe(255);++ // 3. toggleTone with active selection on empty Layer 1 -> fills selection AND undoes cleanly+ act(() => {+ harness.layerMgr.toggleTone(initialLayer1Id, lasso);+ });+ const layer1AfterTone = harness.layerMgr.layers.find((l) => l.id === initialLayer1Id);+ expect(layer1AfterTone?.toneEnabled).toBe(true);+ expect(layer1AfterTone?.isToneLayer).toBe(true);+ expect(readPixel(grid, initialLayer1Id, 110, 86)[3]).toBe(255);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.find((l) => l.id === initialLayer1Id)?.toneEnabled).toBeFalsy();+ expect(grid.getLayerTiles(initialLayer1Id, 0).length).toBe(0);++ // 4. Add Layer, Clear Active Layer, Merge Down, Blend Mode, and Rasterize all undo cleanly+ let addedId = '';+ act(() => {+ const added = harness.layerMgr.addLayer('raster');+ addedId = added.id;+ });+ expect(harness.layerMgr.layers.some((l) => l.id === addedId)).toBe(true);++ act(() => {+ paintSolidRect(grid, addedId, 10, 10, 30, 30, [255, 0, 0, 255]);+ harness.layerMgr.clearActiveLayer();+ });+ expect(readPixel(grid, addedId, 20, 20)[3]).toBe(0);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(readPixel(grid, addedId, 20, 20)).toEqual([255, 0, 0, 255]);++ // Merge Down onto layer below (toneId)+ act(() => {+ harness.layerMgr.mergeDown(addedId);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === addedId)).toBe(false);+ expect(readPixel(grid, toneId, 20, 20)).toEqual([255, 0, 0, 255]);++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.some((l) => l.id === addedId)).toBe(true);+ expect(readPixel(grid, addedId, 20, 20)).toEqual([255, 0, 0, 255]);+ expect(readPixel(grid, toneId, 20, 20)[3]).toBe(0);++ // Blend Mode undo+ act(() => {+ harness.layerMgr.setBlendMode(addedId, 'multiply');+ });+ expect(harness.layerMgr.layers.find((l) => l.id === addedId)?.blendMode).toBe('multiply');+ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.find((l) => l.id === addedId)?.blendMode).toBe('normal');++ // Text layer create + Rasterize -> Undo reverts type back to 'text'+ let textId = '';+ act(() => {+ const tl = harness.layerMgr.upsertTextLayer({+ text: 'Hello',+ fontFamily: 'sans-serif',+ fontSize: 24,+ color: '#000000',+ bold: false,+ italic: false,+ align: 'left',+ outline: false,+ outlineColor: '#ffffff',+ outlineWidth: 0,+ writingMode: 'horizontal-tb',+ lineSpacing: 1.25,+ x: 50,+ y: 50,+ });+ textId = tl.id;+ });+ expect(harness.layerMgr.layers.find((l) => l.id === textId)?.type).toBe('text');++ act(() => {+ harness.layerMgr.rasterizeLayer(textId);+ });+ expect(harness.layerMgr.layers.find((l) => l.id === textId)?.type).toBe('raster');++ await act(async () => {+ await harness.history.jumpToHistoryIndex(harness.history.historyIndex - 1);+ });+ expect(harness.layerMgr.layers.find((l) => l.id === textId)?.type).toBe('text');+ });++ it('isEditableTarget does not block Ctrl+Z / Ctrl+Y when a <select> dropdown has focus', () => {+ const selectEl = document.createElement('select');+ const ctrlZ = { ctrlKey: true, metaKey: false, key: 'z' } as KeyboardEvent;+ const bareB = { ctrlKey: false, metaKey: false, key: 'b' } as KeyboardEvent;+ expect(isEditableTarget(selectEl, ctrlZ)).toBe(false);+ expect(isEditableTarget(selectEl, bareB)).toBe(true);++ const textInput = document.createElement('input');+ (textInput as any).type = 'text';+ expect(isEditableTarget(textInput, ctrlZ)).toBe(true);+ });+});diff --git a/src/utils/__tests__/tool3DRules.test.ts b/src/utils/__tests__/tool3DRules.test.tsnew file mode 100644index 0000000..aee7855--- /dev/null+++ b/src/utils/__tests__/tool3DRules.test.ts@@ -0,0 +1,318 @@+import { describe, it, expect } from 'vitest';+import * as THREE from 'three';+import {+ DEFAULT_3D_LIGHTING,+ mapScreenDeltaToCanvasDelta,+ resolve3DPointerAction,+ resolve3DWheelAction,+ Scene3DHistoryStack,+ Scene3DSnapshot,+ snapAngleDeg,+ snapPositionCoord,+ snapScaleFactor,+ sphericalLightToVector,+ TOOL_3D_BEHAVIOR_RULES,+} from '../tool3DRules';+import {+ createIKHandles,+ createProceduralMannequin,+ solveTwoBoneIK,+ syncIKHandlesToBones,+} from '../mannequin3D';+import { DEFAULT_COMMANDS } from '../shortcutManager';+import { store3DActions, use3DStore } from '../../stores';++function makeSnapshot(overrides: Partial<Scene3DSnapshot> = {}): Scene3DSnapshot {+ return {+ modelPosition: [0, 0, 0],+ modelQuaternion: [0, 0, 0, 1],+ modelScale: [1, 1, 1],+ cameraPosition: [0, 1.35, 3.8],+ cameraTarget: [0, 0.85, 0],+ cameraFov: 45,+ perspective: 1.0,+ lighting: {+ keyLight: { ...DEFAULT_3D_LIGHTING.keyLight },+ rimLight: { ...DEFAULT_3D_LIGHTING.rimLight },+ ambientIntensity: DEFAULT_3D_LIGHTING.ambientIntensity,+ ambientColor: DEFAULT_3D_LIGHTING.ambientColor,+ castGroundShadow: DEFAULT_3D_LIGHTING.castGroundShadow,+ shadowOpacity: DEFAULT_3D_LIGHTING.shadowOpacity,+ },+ shadingMode: 'shaded',+ materialRoughness: 0.4,+ toonOutline: false,+ opacity: 0.92,+ showGrid: true,+ ...overrides,+ };+}++describe('3D Tool Behavior Rules & Pointer Routing', () => {+ const baseInput = {+ activeTool: '3d' as const,+ isSpaceDown: false,+ isReferenceVisible: true,+ button: 0,+ altKey: false,+ activeMode: 'smart' as const,+ gizmoMode: 'rotate' as const,+ isGizmoHit: false,+ isIKHandleHit: false,+ isModelHit: false,+ hasModel: true,+ };++ it('passes pointer events through to 2D canvas when another tool is selected or Space is held', () => {+ expect(resolve3DPointerAction({ ...baseInput, activeTool: 'brush' })).toBe('pass-through-2d');+ expect(resolve3DPointerAction({ ...baseInput, isSpaceDown: true })).toBe('pass-through-2d');+ expect(resolve3DPointerAction({ ...baseInput, isReferenceVisible: false })).toBe('pass-through-2d');+ });++ it('gives top priority to active gizmo handles on left click', () => {+ expect(resolve3DPointerAction({ ...baseInput, isGizmoHit: true, isModelHit: true })).toBe(+ 'gizmo-drag'+ );+ });++ it('routes middle, right, and Alt+left clicks consistently to camera controls from any mode', () => {+ expect(resolve3DPointerAction({ ...baseInput, button: 1, activeMode: 'model-scale' })).toBe(+ 'camera-pan'+ );+ expect(resolve3DPointerAction({ ...baseInput, button: 2, activeMode: 'model-move' })).toBe(+ 'camera-zoom'+ );+ expect(+ resolve3DPointerAction({ ...baseInput, button: 0, altKey: true, isGizmoHit: true })+ ).toBe('camera-orbit');+ });++ it('selects IK handle spheres directly when clicked', () => {+ expect(resolve3DPointerAction({ ...baseInput, isIKHandleHit: true, isModelHit: true })).toBe(+ 'ik-select'+ );+ });++ it('implements Clip Studio Smart mode: drag model transforms by gizmo mode, drag background orbits camera', () => {+ expect(+ resolve3DPointerAction({ ...baseInput, isModelHit: true, gizmoMode: 'rotate' })+ ).toBe('model-rotate');+ expect(+ resolve3DPointerAction({ ...baseInput, isModelHit: true, gizmoMode: 'translate' })+ ).toBe('model-move');+ expect(+ resolve3DPointerAction({ ...baseInput, isModelHit: true, gizmoMode: 'scale' })+ ).toBe('model-scale');+ expect(resolve3DPointerAction({ ...baseInput, isModelHit: false })).toBe('camera-orbit');+ });++ it('respects explicit transform/camera sub-modes and falls back to orbit when no model is loaded', () => {+ expect(resolve3DPointerAction({ ...baseInput, activeMode: 'model-scale' })).toBe('model-scale');+ expect(resolve3DPointerAction({ ...baseInput, activeMode: 'camera-pan' })).toBe('camera-pan');+ expect(+ resolve3DPointerAction({ ...baseInput, activeMode: 'model-rotate', hasModel: false })+ ).toBe('camera-orbit');+ });++ it('routes unmodified wheel to 3D camera zoom and Ctrl/Meta+wheel to 2D canvas zoom', () => {+ expect(+ resolve3DWheelAction({+ activeTool: '3d',+ isSpaceDown: false,+ isReferenceVisible: true,+ ctrlKey: false,+ metaKey: false,+ })+ ).toBe('camera-zoom');++ expect(+ resolve3DWheelAction({+ activeTool: '3d',+ isSpaceDown: false,+ isReferenceVisible: true,+ ctrlKey: true,+ metaKey: false,+ })+ ).toBe('pass-through-2d');++ expect(+ resolve3DWheelAction({+ activeTool: 'brush',+ isSpaceDown: false,+ isReferenceVisible: true,+ ctrlKey: false,+ metaKey: false,+ })+ ).toBe('pass-through-2d');+ });++ it('defines user-facing behavior rules and registers the 3D tool shortcut', () => {+ expect(TOOL_3D_BEHAVIOR_RULES.length).toBeGreaterThanOrEqual(6);+ const cmd = DEFAULT_COMMANDS.find((c) => c.id === 'tool.3d');+ expect(cmd).toBeDefined();+ expect(cmd?.toolId).toBe('3d');+ expect(cmd?.defaultShortcut).toBe('K');+ });+});++describe('3D Coordinate Delta Mapping, Snapping & Lighting Math', () => {+ it('maps screen drag deltas accurately under canvas rotation and flip', () => {+ const id = mapScreenDeltaToCanvasDelta(10, 0, 0, false, false);+ expect(id.dx).toBeCloseTo(10, 5);+ expect(id.dy).toBeCloseTo(0, 5);++ const flippedX = mapScreenDeltaToCanvasDelta(10, 5, 0, true, false);+ expect(flippedX.dx).toBeCloseTo(-10, 5);+ expect(flippedX.dy).toBeCloseTo(5, 5);++ const rot90 = mapScreenDeltaToCanvasDelta(10, 0, 90, false, false);+ expect(rot90.dx).toBeCloseTo(0, 5);+ expect(rot90.dy).toBeCloseTo(-10, 5);+ });++ it('snaps angles, scale factors, and positions cleanly', () => {+ expect(snapAngleDeg(23, 15)).toBe(30);+ expect(snapAngleDeg(-8, 15)).toBe(-15);+ expect(snapScaleFactor(1.24, 0.1)).toBeCloseTo(1.2, 5);+ expect(snapScaleFactor(0.01, 0.1)).toBeCloseTo(0.05, 5);+ expect(snapPositionCoord(1.36, 0.1)).toBeCloseTo(1.4, 5);+ });++ it('computes unified normalized spherical light vectors for front and backlit modes', () => {+ const front = sphericalLightToVector(0, 0, false, 5);+ expect(front.x).toBeCloseTo(0, 5);+ expect(front.y).toBeCloseTo(0, 5);+ expect(front.z).toBeCloseTo(5, 5);++ const back = sphericalLightToVector(0, 0, true, 5);+ expect(back.z).toBeCloseTo(-5, 5);++ const elevated = sphericalLightToVector(45, 45, false, 1);+ expect(Math.hypot(elevated.x, elevated.y, elevated.z)).toBeCloseTo(1, 5);+ });+});++describe('3D Undo / Redo History Stack (Ctrl+Z / Ctrl+Y)', () => {+ it('undoes and redoes transforms, camera, lighting, shading, and mannequin bone poses', () => {+ const stack = new Scene3DHistoryStack(10);+ const s0 = makeSnapshot({+ bones: { leftUpperArm: { q: [0, 0, 0, 1] } },+ });+ const s1 = makeSnapshot({+ modelPosition: [1, 0.5, -0.2],+ bones: { leftUpperArm: { q: [0, 0, 0, 1] } },+ });+ const s2 = makeSnapshot({+ modelPosition: [1, 0.5, -0.2],+ shadingMode: 'toon',+ lighting: {+ ...s0.lighting,+ keyLight: { ...s0.lighting.keyLight, azimuth: 120, color: '#ffb56b' },+ },+ bones: { leftUpperArm: { q: [0.3, 0, 0, 0.95] } },+ });++ stack.reset(s0);+ expect(stack.canUndo()).toBe(false);+ expect(stack.canRedo()).toBe(false);++ // Duplicate snapshot is deduplicated+ expect(stack.push(makeSnapshot({ bones: { leftUpperArm: { q: [0, 0, 0, 1] } } }))).toBe(false);++ expect(stack.push(s1)).toBe(true);+ expect(stack.push(s2)).toBe(true);+ expect(stack.canUndo()).toBe(true);+ expect(stack.canRedo()).toBe(false);++ const u1 = stack.undo();+ expect(u1?.modelPosition).toEqual([1, 0.5, -0.2]);+ expect(u1?.shadingMode).toBe('shaded');+ expect(stack.canRedo()).toBe(true);++ const u0 = stack.undo();+ expect(u0?.modelPosition).toEqual([0, 0, 0]);+ expect(stack.canUndo()).toBe(false);++ const r1 = stack.redo();+ expect(r1?.modelPosition).toEqual([1, 0.5, -0.2]);++ // Pushing after undo truncates the redo tail+ const sBranch = makeSnapshot({ modelScale: [2, 2, 2] });+ expect(stack.push(sBranch)).toBe(true);+ expect(stack.canRedo()).toBe(false);+ expect(stack.undo()?.modelPosition).toEqual([1, 0.5, -0.2]);+ });++ it('enforces max history capacity', () => {+ const stack = new Scene3DHistoryStack(3);+ stack.reset(makeSnapshot({ modelPosition: [0, 0, 0] }));+ stack.push(makeSnapshot({ modelPosition: [1, 0, 0] }));+ stack.push(makeSnapshot({ modelPosition: [2, 0, 0] }));+ stack.push(makeSnapshot({ modelPosition: [3, 0, 0] }));++ expect(stack.length).toBe(3);+ expect(stack.undo()?.modelPosition[0]).toBe(2);+ expect(stack.undo()?.modelPosition[0]).toBe(1);+ expect(stack.canUndo()).toBe(false);+ });+});++describe('3D Store State & Rotated-Root IK Math', () => {+ it('solves 2-bone IK accurately even when the parent root group is rotated 90 degrees', () => {+ const parentRoot = new THREE.Group();+ parentRoot.rotation.y = Math.PI / 2;++ const rootBone = new THREE.Bone();+ rootBone.position.set(0, 1.0, 0);+ parentRoot.add(rootBone);++ const midBone = new THREE.Bone();+ midBone.position.set(0, -0.5, 0);+ rootBone.add(midBone);++ const endBone = new THREE.Bone();+ endBone.position.set(0, -0.5, 0);+ midBone.add(endBone);++ parentRoot.updateMatrixWorld(true);++ const target = new THREE.Vector3(0.45, 0.7, 0.25);+ const pole = new THREE.Vector3(0, 0.8, -1.0);++ solveTwoBoneIK(rootBone, midBone, endBone, target, pole);++ const solvedEnd = new THREE.Vector3();+ endBone.getWorldPosition(solvedEnd);+ expect(solvedEnd.distanceTo(target)).toBeLessThan(0.05);+ });++ it('syncs IK handles to moved mannequin bone world positions', () => {+ const { group, bones } = createProceduralMannequin();+ const { handles } = createIKHandles();++ group.position.set(1.5, 0.2, -0.5);+ group.updateMatrixWorld(true);+ syncIKHandlesToBones(bones, handles);++ const headWorld = new THREE.Vector3();+ bones.head!.getWorldPosition(headWorld);+ expect(handles.head.position.distanceTo(headWorld)).toBeLessThan(1e-4);+ });++ it('updates and resets 3D store lighting, shading, and history flags cleanly', () => {+ store3DActions.setGizmoMode('scale');+ expect(use3DStore.getState().gizmoMode).toBe('scale');++ store3DActions.updateKeyLight({ intensity: 2.2, color: '#ffb56b' });+ expect(use3DStore.getState().lighting.keyLight.intensity).toBe(2.2);++ store3DActions.setHistoryFlags(true, false);+ expect(use3DStore.getState().canUndo3D).toBe(true);+ expect(use3DStore.getState().canRedo3D).toBe(false);++ store3DActions.resetLighting();+ expect(use3DStore.getState().lighting.keyLight.color).toBe('#ffffff');+ store3DActions.setGizmoMode('rotate');+ store3DActions.setHistoryFlags(false, false);+ });+});diff --git a/src/utils/autoActionEngine.ts b/src/utils/autoActionEngine.tsindex e88b4dc..b7299f0 100644--- a/src/utils/autoActionEngine.ts+++ b/src/utils/autoActionEngine.ts@@ -25,6 +25,7 @@ export type AutoActionCommandType =| 'fill-layer'| 'clear-layer'| 'merge-down'+ | 'merge-folder'| 'rasterize-layer'| 'apply-filter'| 'apply-tonal-correction'@@ -75,6 +76,7 @@ export interface AutoActionExecutionContext {fillLayer: (layerId: string, color: string) => void;clearLayer: (layerId: string) => void;mergeDown: () => void;+ mergeFolder?: (folderId?: string) => void;rasterizeLayer?: (layerId: string) => void;applyFilter?: (type: FilterType, params?: Record<string, unknown>) => void;applyTonalCorrection?: (type: TonalCorrectionType, params?: Record<string, unknown>) => void;@@ -112,6 +114,7 @@ const VALID_COMMAND_TYPES = new Set<AutoActionCommandType>(['fill-layer','clear-layer','merge-down',+ 'merge-folder','rasterize-layer','apply-filter','apply-tonal-correction',@@ -471,6 +474,9 @@ export async function executeAutoAction(case 'merge-down':ctx.mergeDown();break;+ case 'merge-folder':+ ctx.mergeFolder?.(activeId);+ break;case 'rasterize-layer':if (activeId && ctx.rasterizeLayer) ctx.rasterizeLayer(activeId);break;diff --git a/src/utils/collabSyncUtils.ts b/src/utils/collabSyncUtils.tsindex d4e34cf..2f67a04 100644--- a/src/utils/collabSyncUtils.ts+++ b/src/utils/collabSyncUtils.ts@@ -61,6 +61,7 @@ const CLEARABLE_FIELDS_SET = new Set<LayerClearableField>(['alphaLocked','clipped','isReference',+ 'isToneLayer','toneEnabled','toneFrequency','toneAngle',@@ -103,6 +104,7 @@ const SYNCED_LAYER_KEYS: ReadonlyArray<keyof WireLayerItem> = ['clipped','parentId','isReference',+ 'isToneLayer','toneEnabled','toneFrequency','toneAngle',@@ -286,6 +288,7 @@ export function sanitizeWireLayerPatch(raw: unknown): Partial<WireLayerItem> {if (typeof src.isReference === 'boolean') out.isReference = src.isReference;// Screentone+ if (typeof src.isToneLayer === 'boolean') out.isToneLayer = src.isToneLayer;if (typeof src.toneEnabled === 'boolean') out.toneEnabled = src.toneEnabled;if (typeof src.toneFrequency === 'number' && Number.isFinite(src.toneFrequency)) {out.toneFrequency = Math.round(clampFinite(src.toneFrequency, 20, 85, 60));diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.tsindex c468920..97d439a 100644--- a/src/utils/colorMixingEngine.ts+++ b/src/utils/colorMixingEngine.ts@@ -147,73 +147,286 @@ 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';+// -------------------------------------------------------------+// 7-Band Spectral Kubelka-Munk Pigment Engine (420–660nm, CIE 1931 D65)+// Closed-form physical pigment reflectance decomposition + Kubelka-Munk K/S+// absorption/scattering blending + OKLab perceptual lightness/chroma polish.+// Guarantees:+// - Blue + Yellow -> vibrant emerald/leaf green (no gray mud)+// - Green + Magenta -> warm golden-amber / coral (no dead olive-gray)+// - Red + Blue -> rich royal violet; Red + Yellow -> luminous orange+// - Exact self-mix invariance: mix(c, c, t) === c+// - Exact neutral-gray invariance: Black + White stays pure neutral gray+// -------------------------------------------------------------++const KM_LO = 0.025;+const KM_SPAN = 0.97;+const KM_INV_SPAN = 1.0 / KM_SPAN;+const KM_EXP = 0.72;+const KM_INV_EXP = 1.0 / KM_EXP;++// Normalized CIE 1931 D65 band-to-Linear-sRGB weights (columns sum to 1.0)+const SPEC_W_R = new Float32Array([0.140, 0.030, -0.145, -0.080, 0.365, 0.465, 0.225]);+const SPEC_W_G = new Float32Array([-0.050, 0.045, 0.250, 0.500, 0.300, -0.018, -0.027]);+const SPEC_W_B = new Float32Array([0.340, 0.550, 0.145, -0.028, -0.007, 0.000, 0.000]);+{+ let sr = 0;+ let sg = 0;+ let sb = 0;+ for (let i = 0; i < 7; i++) {+ sr += SPEC_W_R[i];+ sg += SPEC_W_G[i];+ sb += SPEC_W_B[i];+ }+ for (let i = 0; i < 7; i++) {+ SPEC_W_R[i] /= sr;+ SPEC_W_G[i] /= sg;+ SPEC_W_B[i] /= sb;+ }+}++// Calibrated physical artist-pigment reflectance curves across 7 bands (420..660nm)+const BASIS_R = new Float32Array([0.025, 0.018, 0.020, 0.035, 0.360, 0.965, 0.990]);+const BASIS_G = new Float32Array([0.020, 0.040, 0.420, 0.980, 0.900, 0.420, 0.060]);+const BASIS_B = new Float32Array([0.880, 0.990, 0.780, 0.340, 0.025, 0.020, 0.055]);+const BASIS_C = new Float32Array([0.720, 0.980, 0.990, 0.840, 0.140, 0.025, 0.025]);+const BASIS_M = new Float32Array([0.780, 0.500, 0.055, 0.025, 0.640, 0.975, 0.990]);+const BASIS_Y = new Float32Array([0.018, 0.022, 0.280, 0.930, 0.995, 0.990, 0.980]);++// Module-level scratch buffers for zero-allocation hot-loop pigment mixing+const _kmSp1 = new Float32Array(7);+const _kmSp2 = new Float32Array(7);+const _kmSpM = new Float32Array(7);++function linearRgbToReflectance(r: number, g: number, b: number, out: Float32Array): void {+ const rr = KM_LO + r * KM_SPAN;+ const gg = KM_LO + g * KM_SPAN;+ const bb = KM_LO + b * KM_SPAN;++ if (rr <= gg && rr <= bb) {+ const w = rr;+ if (gg <= bb) {+ const c = gg - rr;+ const p = bb - gg;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_C[i] + p * BASIS_B[i];+ } else {+ const c = bb - rr;+ const p = gg - bb;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_C[i] + p * BASIS_G[i];+ }+ } else if (gg <= rr && gg <= bb) {+ const w = gg;+ if (rr <= bb) {+ const c = rr - gg;+ const p = bb - rr;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_M[i] + p * BASIS_B[i];+ } else {+ const c = bb - gg;+ const p = rr - bb;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_M[i] + p * BASIS_R[i];+ }+ } else {+ const w = bb;+ if (rr <= gg) {+ const c = rr - bb;+ const p = gg - rr;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_Y[i] + p * BASIS_G[i];+ } else {+ const c = gg - bb;+ const p = rr - gg;+ for (let i = 0; i < 7; i++) out[i] = w + c * BASIS_Y[i] + p * BASIS_R[i];+ }+ }+}+/**- * Subtractive Pigment Mixing (Physical Paint Simulation — CSP Perceptual / Krita Kubelka-Munk).- * Simulates real-world physical absorption and spectral overlap where Blue + Yellow = vibrant Green,- * Red + Blue = Purple/Violet, Red + Yellow = Orange, and colors don't collapse into muddy RGB grays!+ * Encodes an sRGB color [0..255] into 7-band compressed Kubelka-Munk K/S + 3 linear residual channels+ * (10 floats written starting at `offset`). Useful for fast separable spectral convolution (Pigment Blur).*/-export function mixSubtractivePigments(- c1: RgbColor,- c2: RgbColor,- weight2: number // 0.0 = 100% c1, 1.0 = 100% c2+export function encodeSrgbToSpectralKS(+ r: number,+ g: number,+ b: number,+ out: Float32Array,+ offset: number+): void {+ const lr = srgbToLinear(r);+ const lg = srgbToLinear(g);+ const lb = srgbToLinear(b);+ linearRgbToReflectance(lr, lg, lb, _kmSp1);++ let br = 0;+ let bg = 0;+ let bb = 0;+ for (let i = 0; i < 7; i++) {+ const sp = _kmSp1[i];+ br += sp * SPEC_W_R[i];+ bg += sp * SPEC_W_G[i];+ bb += sp * SPEC_W_B[i];+ const rc = sp < 0.02 ? 0.02 : sp > 0.998 ? 0.998 : sp;+ const ks = ((1 - rc) * (1 - rc)) / (2 * rc);+ out[offset + i] = Math.pow(ks, KM_EXP);+ }+ out[offset + 7] = lr - (br - KM_LO) * KM_INV_SPAN;+ out[offset + 8] = lg - (bg - KM_LO) * KM_INV_SPAN;+ out[offset + 9] = lb - (bb - KM_LO) * KM_INV_SPAN;+}++/**+ * Decodes 7-band compressed Kubelka-Munk K/S + 3 linear residual channels back to sRGB [0..255].+ */+export function decodeSpectralKSToSrgb(+ buf: Float32Array,+ offset: number,+ out: RgbColor): 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 w1 = 1 - w2;-- // Convert to linear reflectance- const r1 = srgbToLinear(c1.r);- const g1 = srgbToLinear(c1.g);- const b1 = srgbToLinear(c1.b);-- const r2 = srgbToLinear(c2.r);- const g2 = srgbToLinear(c2.g);- const b2 = srgbToLinear(c2.b);-- // 1. Subtractive absorption coefficients (Kubelka-Munk K/S approximation)- const absR1 = 1 - Math.sqrt(r1);- const absG1 = 1 - Math.sqrt(g1);- const absB1 = 1 - Math.sqrt(b1);-- const absR2 = 1 - Math.sqrt(r2);- const absG2 = 1 - Math.sqrt(g2);- const absB2 = 1 - Math.sqrt(b2);-- const mixAbsR = absR1 * w1 + absR2 * w2;- const mixAbsG = absG1 * w1 + absG2 * w2;- const mixAbsB = absB1 * w1 + absB2 * w2;-- let subR = Math.pow(Math.max(0, 1 - mixAbsR), 2);- let subG = Math.pow(Math.max(0, 1 - mixAbsG), 2);- let subB = Math.pow(Math.max(0, 1 - mixAbsB), 2);-- // 2. Spectral Yellow + Blue -> Green pigment transmittance coupling- // In RGB, pure blue has R=0, G=0, B=1, which falsely implies infinite green absorption.- // Physical blue/cyan pigments transmit 490-540nm (green) wavelengths that overlap with yellow's passband.- const yellow1 = Math.max(0, Math.min(r1, g1) - b1);- const yellow2 = Math.max(0, Math.min(r2, g2) - b2);- const blue1 = Math.max(0, b1 - r1);- const blue2 = Math.max(0, b2 - r2);-- const ybCross = (yellow1 * blue2 + yellow2 * blue1) * 4.0 * w1 * w2;- if (ybCross > 0.001) {- subG = Math.min(1.0, subG + ybCross * 0.55);- subR = Math.max(0.0, subR * (1.0 - ybCross * 0.45));- subB = Math.max(0.0, subB * (1.0 - ybCross * 0.45));+ let mr = 0;+ let mg = 0;+ let mb = 0;+ for (let i = 0; i < 7; i++) {+ const cks = buf[offset + i];+ const ks = cks > 0 ? Math.pow(cks, KM_INV_EXP) : 0;+ const ref = 1 + ks - Math.sqrt(ks * ks + 2 * ks);+ mr += ref * SPEC_W_R[i];+ mg += ref * SPEC_W_G[i];+ mb += ref * SPEC_W_B[i];+ }+ const lr = (mr - KM_LO) * KM_INV_SPAN + buf[offset + 7];+ const lg = (mg - KM_LO) * KM_INV_SPAN + buf[offset + 8];+ const lb = (mb - KM_LO) * KM_INV_SPAN + buf[offset + 9];+ out.r = linearToSrgbFloat(lr);+ out.g = linearToSrgbFloat(lg);+ out.b = linearToSrgbFloat(lb);+ return out;+}++/**+ * Zero-allocation 7-Band Spectral Kubelka-Munk pigment mixer writing directly into `out`.+ * `pigmentStrength` in [0..1]: 0.0 = regular sRGB blend, 1.0 = full physical Kubelka-Munk pigment blend.+ */+export function mixPigmentRgbOut(+ r1In: number,+ g1In: number,+ b1In: number,+ r2In: number,+ g2In: number,+ b2In: number,+ weight2: number,+ pigmentStrength: number,+ out: RgbColor+): RgbColor {+ const t = weight2 <= 0 ? 0 : weight2 >= 1 ? 1 : weight2;+ if (t <= 0.0001) {+ out.r = r1In;+ out.g = g1In;+ out.b = b1In;+ return out;+ }+ if (t >= 0.9999) {+ out.r = r2In;+ out.g = g2In;+ out.b = b2In;+ return out;}- // 3. Perceptual Lightness & Chroma preservation via OKLab with hue-safe gamut clamping+ const strength = pigmentStrength <= 0 ? 0 : pigmentStrength >= 1 ? 1 : pigmentStrength;+ if (strength <= 0.005) {+ out.r = r1In + (r2In - r1In) * t;+ out.g = g1In + (g2In - g1In) * t;+ out.b = b1In + (b2In - b1In) * t;+ return out;+ }++ const invT = 1 - t;+ const r1 = srgbToLinear(r1In);+ const g1 = srgbToLinear(g1In);+ const b1 = srgbToLinear(b1In);++ const r2 = srgbToLinear(r2In);+ const g2 = srgbToLinear(g2In);+ const b2 = srgbToLinear(b2In);++ // 1. Decompose into 7-band physical reflectance spectra + exact linear RGB residuals+ linearRgbToReflectance(r1, g1, b1, _kmSp1);+ linearRgbToReflectance(r2, g2, b2, _kmSp2);++ let b1r = 0;+ let b1g = 0;+ let b1b = 0;+ let b2r = 0;+ let b2g = 0;+ let b2b = 0;+ for (let i = 0; i < 7; i++) {+ const s1 = _kmSp1[i];+ const s2 = _kmSp2[i];+ const wr = SPEC_W_R[i];+ const wg = SPEC_W_G[i];+ const wb = SPEC_W_B[i];+ b1r += s1 * wr;+ b1g += s1 * wg;+ b1b += s1 * wb;+ b2r += s2 * wr;+ b2g += s2 * wg;+ b2b += s2 * wb;+ }+ const res1r = r1 - (b1r - KM_LO) * KM_INV_SPAN;+ const res1g = g1 - (b1g - KM_LO) * KM_INV_SPAN;+ const res1b = b1 - (b1b - KM_LO) * KM_INV_SPAN;+ const res2r = r2 - (b2r - KM_LO) * KM_INV_SPAN;+ const res2g = g2 - (b2g - KM_LO) * KM_INV_SPAN;+ const res2b = b2 - (b2b - KM_LO) * KM_INV_SPAN;++ // 2. Perceptual luminance concentration (physical tinting strength balance)+ const Y1 = 0.2126 * r1 + 0.7152 * g1 + 0.0722 * b1;+ const Y2 = 0.2126 * r2 + 0.7152 * g2 + 0.0722 * b2;+ const conc1 = Math.pow(0.06 + Y1, 0.36);+ const conc2 = Math.pow(0.06 + Y2, 0.36);+ const w1Raw = invT * conc1;+ const w1 = w1Raw / (w1Raw + t * conc2);+ const w2 = 1 - w1;++ // 3. Mix in Kubelka-Munk K/S absorption-scattering space and reconstruct Linear RGB+ let mr = 0;+ let mg = 0;+ let mb = 0;+ for (let i = 0; i < 7; i++) {+ const a = _kmSp1[i] < 0.02 ? 0.02 : _kmSp1[i] > 0.998 ? 0.998 : _kmSp1[i];+ const b = _kmSp2[i] < 0.02 ? 0.02 : _kmSp2[i] > 0.998 ? 0.998 : _kmSp2[i];+ const ks1 = Math.pow(((1 - a) * (1 - a)) / (2 * a), KM_EXP);+ const ks2 = Math.pow(((1 - b) * (1 - b)) / (2 * b), KM_EXP);+ const ks = Math.pow(ks1 * w1 + ks2 * w2, KM_INV_EXP);+ const ref = 1 + ks - Math.sqrt(ks * ks + 2 * ks);+ _kmSpM[i] = ref;+ mr += ref * SPEC_W_R[i];+ mg += ref * SPEC_W_G[i];+ mb += ref * SPEC_W_B[i];+ }++ const mixR = Math.max(0, (mr - KM_LO) * KM_INV_SPAN + res1r * invT + res2r * t);+ const mixG = Math.max(0, (mg - KM_LO) * KM_INV_SPAN + res1g * invT + res2g * t);+ const mixB = Math.max(0, (mb - KM_LO) * KM_INV_SPAN + res1b * invT + res2b * t);++ // 4. OKLab perceptual lightness & chroma polish 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 tunedL = Math.max(0, Math.min(1, targetLightness * 0.68 + subLab.L * 0.32));- let finalLinear = oklabToLinearRgb(tunedL, subLab.a, subLab.b);+ const labM = linearRgbToOklab(mixR, mixG, mixB);++ const targetL = lab1.L * invT + lab2.L * t;+ const tunedL = Math.max(0, Math.min(1, labM.L * 0.40 + targetL * 0.60));++ const c1Chroma = Math.hypot(lab1.a, lab1.b);+ const c2Chroma = Math.hypot(lab2.a, lab2.b);+ const mChroma = Math.hypot(labM.a, labM.b);+ const linChroma = c1Chroma * invT + c2Chroma * t;+ let chromaBoost = 1.0;+ if (mChroma > 0.008 && linChroma > mChroma) {+ const targetC = mChroma + (linChroma - mChroma) * 0.50;+ chromaBoost = Math.min(1.65, targetC / mChroma);+ }+ const aM = labM.a * chromaBoost;+ const bM = labM.b * chromaBoost;- // 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).+ let finalLinear = oklabToLinearRgb(tunedL, aM, bM);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) {@@ -226,19 +439,46 @@ export function mixSubtractivePigments(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);+ finalLinear = oklabToLinearRgb(tunedL, aM * scale, bM * scale);}- return {- r: linearToSrgbFloat(finalLinear.r),- g: linearToSrgbFloat(finalLinear.g),- b: linearToSrgbFloat(finalLinear.b),- };+ const subR = linearToSrgbFloat(finalLinear.r);+ const subG = linearToSrgbFloat(finalLinear.g);+ const subB = linearToSrgbFloat(finalLinear.b);++ if (strength >= 0.995) {+ out.r = subR;+ out.g = subG;+ out.b = subB;+ return out;+ }++ const linR = r1In + (r2In - r1In) * t;+ const linG = g1In + (g2In - g1In) * t;+ const linB = b1In + (b2In - b1In) * t;+ out.r = linR + (subR - linR) * strength;+ out.g = linG + (subG - linG) * strength;+ out.b = linB + (subB - linB) * strength;+ return out;+}++/**+ * Subtractive Pigment Mixing (Physical Paint Simulation — 7-Band Spectral Kubelka-Munk + OKLab).+ * Simulates real-world physical absorption and spectral overlap where Blue + Yellow = vibrant Green,+ * Green + Magenta = warm golden-amber/coral, Red + Blue = Violet, Red + Yellow = Orange.+ */+export function mixSubtractivePigments(+ c1: RgbColor,+ c2: RgbColor,+ weight2: number // 0.0 = 100% c1, 1.0 = 100% c2+): RgbColor {+ const out: RgbColor = { r: c1.r, g: c1.g, b: c1.b };+ return mixPigmentRgbOut(c1.r, c1.g, c1.b, c2.r, c2.g, c2.b, weight2, 1.0, out);}/*** 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.+ * 0.0 = standard linear RGB interpolation; 1.0 = full 7-band Kubelka-Munk + OKLab pigment mixing.*/export function mixPigmentsWithStrength(c1: RgbColor,@@ -246,28 +486,8 @@ export function mixPigmentsWithStrength(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: linR + (sub.r - linR) * s,- g: linG + (sub.g - linG) * s,- b: linB + (sub.b - linB) * s,- };+ const out: RgbColor = { r: c1.r, g: c1.g, b: c1.b };+ return mixPigmentRgbOut(c1.r, c1.g, c1.b, c2.r, c2.g, c2.b, weight2, pigmentStrength, out);}// -------------------------------------------------------------@@ -950,7 +1170,8 @@ export class PaintReservoir {flow: number = 0.85,stepDist: number = 0,perceptualMixing: boolean = true,- pressureAlreadyAppliedToFlow: boolean = false+ pressureAlreadyAppliedToFlow: boolean = false,+ pigmentStrength: number = 1.0): { r: number; g: number; b: number; alpha: number; colorHex: string } {this.cumulativeDistance += stepDist;@@ -959,10 +1180,11 @@ export class PaintReservoir {const isPureSmudge = clampedAmount <= 0.005 || mixingMode === 'smear';const isFullFresh = !isPureSmudge && clampedAmount >= 0.995;const canvasAlpha = sampledColor.a;+ const effPigmentStrength = perceptualMixing ? Math.max(0, Math.min(1, pigmentStrength)) : 0;const mixFn = (c1: RgbColor, c2: RgbColor, w2: number): RgbColor => {- if (perceptualMixing) {- return mixSubtractivePigments(c1, c2, w2);+ if (effPigmentStrength > 0.005) {+ return mixPigmentsWithStrength(c1, c2, w2, effPigmentStrength);}const w = Math.max(0, Math.min(1, w2));return {@@ -1589,6 +1811,7 @@ export interface SpatialTipStampParams {colorStretch: number;mixingMode: NaturalMixingMode;perceptualMixing: boolean;+ pigmentMixingStrength?: number;tipImage?: HTMLImageElement;sampler?: LayerPixelSampler;grainDensity?: number;@@ -1659,7 +1882,6 @@ export class SpatialTipMixer {private readonly sampleScratch: RgbaColor = { r: 0, g: 0, b: 0, a: 0 };private readonly c1Scratch: RgbColor = { r: 0, g: 0, b: 0 };- private readonly c2Scratch: RgbColor = { r: 0, g: 0, b: 0 };constructor(initialColor: string) {const rgb = parseColorToRgb(initialColor);@@ -1783,6 +2005,10 @@ export class SpatialTipMixer {const smudgeDecay = carryDecay;+ const effPigmentStrength = p.perceptualMixing+ ? Math.max(0, Math.min(1, p.pigmentMixingStrength ?? 1.0))+ : 0;+const mixColorInto = (r1: number,g1: number,@@ -1805,14 +2031,8 @@ export class SpatialTipMixer {this.c1Scratch.b = b2;return this.c1Scratch;}- if (p.perceptualMixing) {- this.c1Scratch.r = r1;- this.c1Scratch.g = g1;- this.c1Scratch.b = b1;- this.c2Scratch.r = r2;- this.c2Scratch.g = g2;- this.c2Scratch.b = b2;- return mixSubtractivePigments(this.c1Scratch, this.c2Scratch, w);+ if (effPigmentStrength > 0.005) {+ return mixPigmentRgbOut(r1, g1, b1, r2, g2, b2, w, effPigmentStrength, this.c1Scratch);}this.c1Scratch.r = r1 + (r2 - r1) * w;this.c1Scratch.g = g1 + (g2 - g1) * w;diff --git a/src/utils/compositor/fallback2d.ts b/src/utils/compositor/fallback2d.tsindex 6dfa3b9..9497d4f 100644--- a/src/utils/compositor/fallback2d.ts+++ b/src/utils/compositor/fallback2d.ts@@ -1,6 +1,7 @@-import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';+import { CanvasDimensions, LayerItem, isFolderLikeLayer, resolveToneDensityType } from '../../types/editor';import { getCanvasCompositeOperation } from '../canvasUtils';import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';+import { applyScreentoneCPU } from '../screentoneEngine';import { SparseTileGrid, TILE_SIZE, TileBuffer } from '../tileEngine';import { applyAdjustment } from '../tonalEngine';import { calculateVisibleDocumentBounds } from './bounds';@@ -93,7 +94,17 @@ export function render2DSingleLayer(frustum?: DocumentBounds | null): void {targetCtx.save();- targetCtx.globalAlpha = Math.max(0, Math.min(1, layer.opacity * opacityMultiplier));+ const effectiveOpacity = Math.max(0, Math.min(1, layer.opacity * opacityMultiplier));+ const toneEnabled = Boolean(layer.toneEnabled);+ const toneDensityType = resolveToneDensityType(layer);+ const toneDpi = state.currentOptions?.dimensions?.dpi ?? 600;+ const toneSpecifiedDensity = Math.max(0, Math.min(1, (layer.toneDensity ?? 40) / 100));++ if ((toneEnabled || layer.expressionColor === 'monochrome') && state.currentZoom >= 0.99) {+ targetCtx.imageSmoothingEnabled = false;+ }++ targetCtx.globalAlpha = effectiveOpacity;targetCtx.globalCompositeOperation = getCanvasCompositeOperation(layer.blendMode);const { tiles, lodTileDocSize } = collectVisible2DTiles(@@ -110,6 +121,16 @@ export function render2DSingleLayer(if (!tileCtx || !state.fallbackTileCanvas) return;const imgData = getReusableTileImageData(state, tileCtx);const scaleRatio = lodTileDocSize / TILE_SIZE;+ const renderCrispTone = toneEnabled && scaleRatio === 1;+ const prevAlpha = ctx.globalAlpha;+ if (toneEnabled) {+ ctx.globalAlpha = renderCrispTone+ ? 1.0+ : toneDensityType === 'specified'+ ? Math.max(0, Math.min(1, effectiveOpacity * toneSpecifiedDensity))+ : effectiveOpacity;+ }+for (const tile of tiles) {const rgba = grid.getTileAsRGBA(tile);imgData.data.set(rgba);@@ -125,7 +146,29 @@ export function render2DSingleLayer(}}+ if (renderCrispTone && toneDensityType === 'image' && effectiveOpacity < 0.999) {+ const d = imgData.data;+ for (let i = 3; i < d.length; i += 4) {+ if (d[i] > 0) d[i] = Math.round(d[i] * effectiveOpacity);+ }+ }+tileCtx.putImageData(imgData, 0, 0);++ if (renderCrispTone) {+ applyScreentoneCPU(state.fallbackTileCanvas, state.fallbackTileCanvas, {+ frequency: layer.toneFrequency ?? 60,+ angle: layer.toneAngle ?? 45,+ dotShape: layer.toneDotShape ?? 'circle',+ dpi: toneDpi,+ densityType: toneDensityType,+ specifiedDensity: toneSpecifiedDensity * effectiveOpacity,+ antiAliasing: false,+ docOriginX: tile.tileX * TILE_SIZE,+ docOriginY: tile.tileY * TILE_SIZE,+ });+ }+if (scaleRatio === 1) {ctx.drawImage(state.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);} else {@@ -138,6 +181,10 @@ export function render2DSingleLayer();}}++ if (toneEnabled) {+ ctx.globalAlpha = prevAlpha;+ }};const styles = layer.styles;diff --git a/src/utils/compositor/layerRenderer.ts b/src/utils/compositor/layerRenderer.tsindex fd7f28a..5dde31f 100644--- a/src/utils/compositor/layerRenderer.ts+++ b/src/utils/compositor/layerRenderer.ts@@ -124,6 +124,7 @@ export function renderSingleLayer(gl.clear(gl.COLOR_BUFFER_BIT);gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);+ const tonePreAppliesOpacity = Boolean(layer.toneEnabled) && draftOp === 'destination-out';if (visibleTiles.length > 0) {drawVisibleTiles(state,@@ -133,7 +134,7 @@ export function renderSingleLayer(layer,dimensions,lodTileDocSize,- 1.0,+ tonePreAppliesOpacity ? effectiveOpacity : 1.0,0,null,maskTex@@ -171,7 +172,7 @@ export function renderSingleLayer(gl,state.layerTexture,layer.blendMode,- effectiveOpacity,+ tonePreAppliesOpacity ? 1.0 : effectiveOpacity,fs.viewportW,fs.viewportH,target,diff --git a/src/utils/compositor/layerUniforms.ts b/src/utils/compositor/layerUniforms.tsindex 52032ed..97de0cc 100644--- a/src/utils/compositor/layerUniforms.ts+++ b/src/utils/compositor/layerUniforms.ts@@ -1,4 +1,4 @@-import { CanvasDimensions, LayerItem } from '../../types/editor';+import { CanvasDimensions, LayerItem, resolveToneDensityType } from '../../types/editor';import { parseHexColor } from './bounds';import { CompositorState, LayerUniformLocs } from './types';@@ -93,8 +93,8 @@ export function applyLayerUniforms(const toneEnabled = Boolean(layer.toneEnabled);gl.uniform1i(locs.uToneEnabled, toneEnabled ? 1 : 0);if (toneEnabled) {- gl.uniform1f(locs.uToneFrequency, layer.toneFrequency || 60);- gl.uniform1f(locs.uToneAngleRad, ((layer.toneAngle || 45) * Math.PI) / 180);+ gl.uniform1f(locs.uToneFrequency, layer.toneFrequency ?? 60);+ gl.uniform1f(locs.uToneAngleRad, ((layer.toneAngle ?? 45) * Math.PI) / 180);gl.uniform1f(locs.uToneDpi, dimensions.dpi || 600);const dotShapeCode =layer.toneDotShape === 'line'@@ -106,7 +106,7 @@ export function applyLayerUniforms(: 0;gl.uniform1i(locs.uToneDotShape, dotShapeCode);gl.uniform1f(locs.uToneDensity, (layer.toneDensity ?? 40) / 100);- gl.uniform1i(locs.uToneDensityType, layer.toneDensityType === 'image' ? 1 : 0);+ gl.uniform1i(locs.uToneDensityType, resolveToneDensityType(layer) === 'image' ? 1 : 0);}// Layer Tint Uniformsdiff --git a/src/utils/compositor/previewRenderer.ts b/src/utils/compositor/previewRenderer.tsindex 87ae2c4..503131c 100644--- a/src/utils/compositor/previewRenderer.ts+++ b/src/utils/compositor/previewRenderer.ts@@ -1,4 +1,4 @@-import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';+import { CanvasDimensions, LayerItem, isFolderLikeLayer, resolveToneDensityType } from '../../types/editor';import { getCanvasCompositeOperation } from '../canvasUtils';import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';import { SparseTileGrid, TILE_SIZE, globalTileGrid } from '../tileEngine';@@ -76,7 +76,11 @@ export function renderLowResPreview(opacityMul: number,compositeOverride?: GlobalCompositeOperation) => {- const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul));+ const toneDensityMul =+ layer.toneEnabled && resolveToneDensityType(layer) === 'specified'+ ? Math.max(0, Math.min(1, (layer.toneDensity ?? 40) / 100))+ : 1.0;+ const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul * toneDensityMul));if (alpha <= 0.001) return;const tiles = grid.getOrBuildLodTiles(layer.id, targetLod);diff --git a/src/utils/compositor/shaders/coreShaders.ts b/src/utils/compositor/shaders/coreShaders.tsindex 26a7798..4d12077 100644--- a/src/utils/compositor/shaders/coreShaders.ts+++ b/src/utils/compositor/shaders/coreShaders.ts@@ -1,4 +1,5 @@import { buildBlendModeGlsl } from './blendModesGlsl';+import { buildScreentoneGlsl } from './screentoneGlsl';// Document-Space Solid Polygon Shaders for Frame Border Folder Stencil Clipping & Bordersexport const FRAME_POLY_VERTEX_SHADER = `#version 300 es@@ -176,70 +177,9 @@ uniform int u_monoExpressWhite;out vec4 fragColor;-float fractVal(float x) {- return x - floor(x);-}-${buildBlendModeGlsl()}-vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {- if (srcColor.a < 0.0039) {- return vec4(0.0);- }-- float density;- if (u_toneDensityType == 0) {- // Specified density- density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);- } else {- // Luminance- float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));- density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);- }-- if (density <= 0.001) return vec4(0.0);- if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);-- float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));- float cosA = cos(u_toneAngleRad);- float sinA = sin(u_toneAngleRad);-- float xr = docCoord.x * cosA - docCoord.y * sinA;- float yr = docCoord.x * sinA + docCoord.y * cosA;-- float u = fractVal(xr / cellSize) - 0.5;- float v = fractVal(yr / cellSize) - 0.5;-- float spot;- if (u_toneDotShape == 2) {- // Line- spot = 1.0 - 2.0 * abs(u);- } else if (u_toneDotShape == 3) {- // Diamond- spot = 1.0 - (abs(u) + abs(v));- } else {- // Euclidean circle- float absU = abs(u);- float absV = abs(v);- if (absU + absV <= 0.5) {- spot = 1.0 - 2.0 * (u * u + v * v);- } else {- float uc = absU - 0.5;- float vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);- }- }-- float diff = spot - (1.0 - density);- float halfSpan = min(0.25, 0.75 / cellSize);- float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);- vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);-- // Anti-moiré smoothstep crossfading- float moireBlend = smoothstep(0.35, 0.95, u_zoom);- vec4 contColor = vec4(0.0, 0.0, 0.0, density);- return mix(contColor, halftoneColor, moireBlend);-}+${buildScreentoneGlsl()}vec4 applyLayerTint(vec4 color) {if (u_layerColorEnabled == 0) return color;@@ -311,22 +251,32 @@ void main() {}if (u_toneEnabled == 1) {+ if (u_maskEnabled == 1) {+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);+ vec4 maskPixel = texture(u_maskTexture, maskCoord);+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;+ finalColor.a *= maskLum;+ }+ finalColor.a *= u_layerOpacity;finalColor = evaluateScreentone(finalColor, v_docCoord);- }+ if (u_layerColorEnabled == 1) {+ finalColor = applyLayerTint(finalColor);+ }+ } else {+ if (u_layerColorEnabled == 1) {+ finalColor = applyLayerTint(finalColor);+ }- if (u_layerColorEnabled == 1) {- finalColor = applyLayerTint(finalColor);- }+ if (u_maskEnabled == 1) {+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);+ vec4 maskPixel = texture(u_maskTexture, maskCoord);+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;+ finalColor.a *= maskLum;+ }- if (u_maskEnabled == 1) {- vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);- vec4 maskPixel = texture(u_maskTexture, maskCoord);- float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;- finalColor.a *= maskLum;+ finalColor.a *= u_layerOpacity;}- finalColor.a *= u_layerOpacity;-if (finalColor.a < 0.002) {discard;}diff --git a/src/utils/compositor/shaders/instancedShaders.ts b/src/utils/compositor/shaders/instancedShaders.tsindex 54a7e4f..360f34a 100644--- a/src/utils/compositor/shaders/instancedShaders.ts+++ b/src/utils/compositor/shaders/instancedShaders.ts@@ -1,4 +1,5 @@import { buildBlendModeGlsl } from './blendModesGlsl';+import { buildScreentoneGlsl } from './screentoneGlsl';// Instanced Vertex Shader: Batched tile rendering via TEXTURE_2D_ARRAY + drawArraysInstancedexport const COMPOSITOR_INSTANCED_VERTEX_SHADER = `#version 300 es@@ -90,64 +91,9 @@ uniform int u_monoExpressWhite;out vec4 fragColor;-float fractVal(float x) {- return x - floor(x);-}-${buildBlendModeGlsl()}-vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {- if (srcColor.a < 0.0039) {- return vec4(0.0);- }-- float density;- if (u_toneDensityType == 0) {- density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);- } else {- float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));- density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);- }-- if (density <= 0.001) return vec4(0.0);- if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);-- float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));- float cosA = cos(u_toneAngleRad);- float sinA = sin(u_toneAngleRad);-- float xr = docCoord.x * cosA - docCoord.y * sinA;- float yr = docCoord.x * sinA + docCoord.y * cosA;-- float u = fractVal(xr / cellSize) - 0.5;- float v = fractVal(yr / cellSize) - 0.5;-- float spot;- if (u_toneDotShape == 2) {- spot = 1.0 - 2.0 * abs(u);- } else if (u_toneDotShape == 3) {- spot = 1.0 - (abs(u) + abs(v));- } else {- float absU = abs(u);- float absV = abs(v);- if (absU + absV <= 0.5) {- spot = 1.0 - 2.0 * (u * u + v * v);- } else {- float uc = absU - 0.5;- float vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);- }- }-- float diff = spot - (1.0 - density);- float halfSpan = min(0.25, 0.75 / cellSize);- float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);- vec4 halftoneColor = vec4(0.0, 0.0, 0.0, coverage);-- float moireBlend = smoothstep(0.35, 0.95, u_zoom);- vec4 contColor = vec4(0.0, 0.0, 0.0, density);- return mix(contColor, halftoneColor, moireBlend);-}+${buildScreentoneGlsl()}vec4 applyLayerTint(vec4 color) {if (u_layerColorEnabled == 0) return color;@@ -189,22 +135,32 @@ void main() {}if (u_toneEnabled == 1) {+ if (u_maskEnabled == 1) {+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);+ vec4 maskPixel = texture(u_maskTexture, maskCoord);+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;+ finalColor.a *= maskLum;+ }+ finalColor.a *= u_layerOpacity;finalColor = evaluateScreentone(finalColor, v_docCoord);- }+ if (u_layerColorEnabled == 1) {+ finalColor = applyLayerTint(finalColor);+ }+ } else {+ if (u_layerColorEnabled == 1) {+ finalColor = applyLayerTint(finalColor);+ }- if (u_layerColorEnabled == 1) {- finalColor = applyLayerTint(finalColor);- }+ if (u_maskEnabled == 1) {+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);+ vec4 maskPixel = texture(u_maskTexture, maskCoord);+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;+ finalColor.a *= maskLum;+ }- if (u_maskEnabled == 1) {- vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);- vec4 maskPixel = texture(u_maskTexture, maskCoord);- float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;- finalColor.a *= maskLum;+ finalColor.a *= u_layerOpacity;}- finalColor.a *= u_layerOpacity;-if (finalColor.a < 0.002) {discard;}diff --git a/src/utils/compositor/shaders/screentoneGlsl.ts b/src/utils/compositor/shaders/screentoneGlsl.tsnew file mode 100644index 0000000..faaaa4c--- /dev/null+++ b/src/utils/compositor/shaders/screentoneGlsl.ts@@ -0,0 +1,104 @@+/**+ * Shared GLSL 300 es Screentone Evaluator for WebGL2 Compositor Shaders+ * (used by both COMPOSITOR_FRAGMENT_SHADER and COMPOSITOR_INSTANCED_FRAGMENT_SHADER).+ *+ * Implements Clip Studio Paint style 1-bit binary screentones using a rational integer-lattice+ * halftone basis (a, b) with exact integer modulo arithmetic:+ * - At 100%+ zoom (u_zoom >= 0.99) and GPU export: 100% pure 1-bit binary black/transparent pixels+ * snapped to discrete document pixels, with bit-for-bit identical uniform dots across the entire canvas.+ * - Below 100% zoom (u_zoom < 0.99): 2x2 supersampled coverage of the exact 1-bit pattern with smooth+ * low-zoom anti-moiré convergence when screen pixels approach the halftone cell pitch.+ */+export function buildScreentoneGlsl(): string {+ return `+float evalScreentoneInkAtPixel(vec2 docPx, float density, float a, float b, float denom) {+ float xr = docPx.x * a - docPx.y * b;+ float yr = docPx.x * b + docPx.y * a;+ float u = (mod(xr, denom) / denom) - 0.5;+ float v = (mod(yr, denom) / denom) - 0.5;++ if (u_toneDotShape == 2) {+ // Line (parallel manga hatching)+ return (1.0 - 2.0 * abs(u)) >= (1.0 - density) ? 1.0 : 0.0;+ } else if (u_toneDotShape == 3) {+ // Diamond (area-calibrated)+ float dThresh = density <= 0.5+ ? (1.0 - sqrt(0.5 * density))+ : sqrt(0.5 * (1.0 - density));+ return (1.0 - (abs(u) + abs(v))) >= dThresh ? 1.0 : 0.0;+ } else if (u_toneDotShape == 1) {+ // Smooth continuous Euclidean dot (area-calibrated cosine spot)+ float spot = 0.5 + 0.25 * (cos(6.2831853 * u) + cos(6.2831853 * v));+ float eu = density <= 0.5 ? (2.0 * density) : (2.0 * (1.0 - density));+ float eOff = 0.78539816 * eu - 0.28539816 * eu * eu;+ float eThresh = density <= 0.5 ? (1.0 - eOff) : eOff;+ return spot >= eThresh ? 1.0 : 0.0;+ } else {+ // Clip Studio Paint standard Circle dot (exact geometric round dot)+ float rDot = density <= 0.78539816+ ? sqrt(density * 0.31830989)+ : (0.70710678 - 0.20710678 * pow(max(0.0, (1.0 - density) / 0.21460184), 0.43));+ return (u * u + v * v) <= (rDot * rDot + 0.000001) ? 1.0 : 0.0;+ }+}++vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {+ if (srcColor.a < 0.0039) {+ return vec4(0.0);+ }++ float density;+ if (u_toneDensityType == 0) {+ // Specified density (dedicated CSP tone layer)+ density = clamp(u_toneDensity * srcColor.a, 0.0, 1.0);+ } else {+ // Image brightness luminance mode+ float lum = dot(srcColor.rgb, vec3(0.299, 0.587, 0.114));+ density = clamp((1.0 - lum) * srcColor.a, 0.0, 1.0);+ }++ if (density <= 0.001) return vec4(0.0);+ if (density >= 0.999) return vec4(0.0, 0.0, 0.0, 1.0);++ float cellSize = max(3.5, u_toneDpi / max(1.0, u_toneFrequency));+ float cosA = cos(u_toneAngleRad);+ float sinA = sin(u_toneAngleRad);++ float a = floor(cellSize * cosA + 0.5);+ float b = floor(cellSize * sinA + 0.5);+ float denom = a * a + b * b;+ if (denom < 4.0) {+ float fb = max(2.0, floor(cellSize + 0.5));+ if (abs(cosA) >= abs(sinA)) {+ a = cosA >= 0.0 ? fb : -fb;+ b = 0.0;+ } else {+ a = 0.0;+ b = sinA >= 0.0 ? fb : -fb;+ }+ denom = a * a + b * b;+ }++ // At 100%+ zoom (and 1:1 GPU export), emit strictly 1-bit binary Clip Studio Paint pixels+ if (u_zoom >= 0.99) {+ float ink = evalScreentoneInkAtPixel(floor(docCoord), density, a, b, denom);+ return vec4(0.0, 0.0, 0.0, ink);+ }++ // Below 100% zoom: 2x2 supersampled coverage of the exact 1-bit binary lattice+ vec2 dx = dFdx(docCoord);+ vec2 dy = dFdy(docCoord);+ float s0 = evalScreentoneInkAtPixel(floor(docCoord - 0.25 * dx - 0.25 * dy), density, a, b, denom);+ float s1 = evalScreentoneInkAtPixel(floor(docCoord + 0.25 * dx - 0.25 * dy), density, a, b, denom);+ float s2 = evalScreentoneInkAtPixel(floor(docCoord - 0.25 * dx + 0.25 * dy), density, a, b, denom);+ float s3 = evalScreentoneInkAtPixel(floor(docCoord + 0.25 * dx + 0.25 * dy), density, a, b, denom);+ float ssCoverage = 0.25 * (s0 + s1 + s2 + s3);++ // Only transition to continuous average tone when a screen pixel approaches the cell pitch+ float cellPx = sqrt(denom);+ float footprint = max(length(dx), length(dy));+ float moireBlend = 1.0 - smoothstep(cellPx * 0.35, cellPx * 0.85, footprint);+ return vec4(0.0, 0.0, 0.0, mix(density, ssCoverage, moireBlend));+}+`;+}diff --git a/src/utils/compositor/stackCache.ts b/src/utils/compositor/stackCache.tsindex 6530c56..9fc6123 100644--- a/src/utils/compositor/stackCache.ts+++ b/src/utils/compositor/stackCache.ts@@ -1,4 +1,4 @@-import { LayerItem } from '../../types/editor';+import { LayerItem, resolveToneDensityType } from '../../types/editor';import { hasActiveLayerStyles } from './shaders/effectShaders';import { partitionLayerStack } from './layerTree';import {@@ -23,7 +23,7 @@ function serializeLayerNodeSignature(const stylesSig = hasActiveLayerStyles(l.styles) ? JSON.stringify(l.styles) : '';const adjSig = l.type === 'adjustment' && l.adjustmentData ? JSON.stringify(l.adjustmentData) : '';const toneSig = l.toneEnabled- ? `1:${l.toneFrequency ?? 60}:${l.toneAngle ?? 45}:${l.toneDotShape ?? ''}:${l.toneDensity ?? 40}:${l.toneDensityType ?? ''}`+ ? `1:${l.toneFrequency ?? 60}:${l.toneAngle ?? 45}:${l.toneDotShape ?? ''}:${l.toneDensity ?? 40}:${resolveToneDensityType(l)}`: '0';const tintSig = l.layerColorEnabled? `1:${l.layerColor ?? ''}:${l.layerSubColor ?? ''}`diff --git a/src/utils/compositor/tileDraw.ts b/src/utils/compositor/tileDraw.tsindex eff67c1..eded44d 100644--- a/src/utils/compositor/tileDraw.ts+++ b/src/utils/compositor/tileDraw.ts@@ -38,8 +38,11 @@ export function drawTilesFallback2D();gl.uniform2f(state.uTileSizeLoc, lodTileDocSize, lodTileDocSize);+ const forceCrispNearest =+ (Boolean(layer.toneEnabled) || layer.expressionColor === 'monochrome') && state.currentZoom >= 0.99;+for (const tile of visibleTiles) {- const tex = getTileTexture(state, tile, grid);+ const tex = getTileTexture(state, tile, grid, forceCrispNearest);if (!tex) continue;gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D, tex);@@ -85,16 +88,20 @@ export function drawVisibleTiles(gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D_ARRAY, state.tileArrayTexture);+ const forceCrispNearest =+ (Boolean(layer.toneEnabled) || layer.expressionColor === 'monochrome') && state.currentZoom >= 0.99;const desiredTier =- state.filteringQuality === 'smooth'- ? 1- : state.filteringQuality === 'pixelated'- ? 2- : state.currentZoom < 0.99- ? 0- : state.currentZoom < 2.0- ? 1- : 2;+ forceCrispNearest+ ? 2+ : state.filteringQuality === 'smooth'+ ? 1+ : state.filteringQuality === 'pixelated'+ ? 2+ : state.currentZoom < 0.99+ ? 0+ : state.currentZoom < 2.0+ ? 1+ : 2;if (state.arrayPoolFilterTier !== desiredTier) {const filter = desiredTier <= 1 ? gl.LINEAR : gl.NEAREST;gl.texParameteri(gl.TEXTURE_2D_ARRAY, gl.TEXTURE_MIN_FILTER, filter);diff --git a/src/utils/compositor/tileTexturePool.ts b/src/utils/compositor/tileTexturePool.tsindex 6978704..deb15a8 100644--- a/src/utils/compositor/tileTexturePool.ts+++ b/src/utils/compositor/tileTexturePool.ts@@ -129,7 +129,8 @@ export function getOrUploadArrayTileSlice(export function getTileTexture(state: CompositorState,tile: TileBuffer,- grid: SparseTileGrid+ grid: SparseTileGrid,+ forceNearest: boolean = false): WebGLTexture | null {if (!state.gl) return null;const gl = state.gl;@@ -179,15 +180,17 @@ export function getTileTexture(slot.lastUsed = accessTick;const desiredTier =- state.filteringQuality === 'smooth'- ? 1- : state.filteringQuality === 'pixelated'- ? 2- : state.currentZoom < 0.99- ? 0- : state.currentZoom < 2.0- ? 1- : 2;+ forceNearest+ ? 2+ : state.filteringQuality === 'smooth'+ ? 1+ : state.filteringQuality === 'pixelated'+ ? 2+ : state.currentZoom < 0.99+ ? 0+ : state.currentZoom < 2.0+ ? 1+ : 2;// Re-upload if version changed (direct GPU unpack premultiplication, zero JS pixel loop)if (slot.version !== tile.version) {@@ -262,6 +265,8 @@ export function getMaskTexture(state: CompositorState, layer: LayerItem): WebGLTconst currentVersion = layer.maskVersion ?? 0;const maskW = layer.maskCanvas.width;const maskH = layer.maskCanvas.height;+ const useNearest =+ (Boolean(layer.toneEnabled) || layer.expressionColor === 'monochrome') && state.currentZoom >= 0.99;if (!cached) {const tex = gl.createTexture();@@ -270,12 +275,13 @@ export function getMaskTexture(state: CompositorState, layer: LayerItem): WebGLTstate.maskTextureCache.set(layer.id, cached);}+ const maskFilter = useNearest ? gl.NEAREST : gl.LINEAR;if (cached.version !== currentVersion || cached.width !== maskW || cached.height !== maskH) {gl.bindTexture(gl.TEXTURE_2D, cached.texture);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, maskFilter);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, maskFilter);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);gl.texImage2D(@@ -290,6 +296,10 @@ export function getMaskTexture(state: CompositorState, layer: LayerItem): WebGLTcached.version = currentVersion;cached.width = maskW;cached.height = maskH;+ } else {+ gl.bindTexture(gl.TEXTURE_2D, cached.texture);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, maskFilter);+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, maskFilter);}return cached.texture;diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.tsindex 227a3b2..904476d 100644--- a/src/utils/floodFill.ts+++ b/src/utils/floodFill.ts@@ -59,6 +59,40 @@ export interface FloodFillOptions {antiAlias?: boolean;/** Optional active selection mask (1/255 = inside selection, 0 = outside) */selectionMask?: Uint8Array | null;+ /** When true, only modifies pixels with existing non-zero alpha on the target layer */+ alphaLocked?: boolean;+}++function isLayerEffectivelyVisibleInList(layer: LayerItem, layers: LayerItem[]): boolean {+ if (!layer.visible) return false;+ let parentId = layer.parentId;+ let guard = 0;+ while (parentId && guard < 32) {+ const parent = layers.find((l) => l.id === parentId);+ if (!parent) break;+ if (!parent.visible) return false;+ parentId = parent.parentId;+ guard++;+ }+ return true;+}++function pointInPolygonFlood(+ px: number,+ py: number,+ polygon: Array<{ x: number; y: number }>+): boolean {+ if (polygon.length < 3) return false;+ let inside = false;+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {+ const xi = polygon[i].x;+ const yi = polygon[i].y;+ const xj = polygon[j].x;+ const yj = polygon[j].y;+ const intersect = yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi;+ if (intersect) inside = !inside;+ }+ return inside;}/**@@ -719,13 +753,32 @@ export function executeFloodFillOnTileGrid(params: {return { dirtyRect: null, modified: false, tileDeltas: [] };}- // Determine reference layers for lazy tile compositing+ // Determine reference layers for lazy tile compositing (respecting ancestor folder visibility)let refLayers: LayerItem[] | null = null;if (referMode === 'refer-reference') {- const refs = layers.filter((l) => l.visible && l.isReference && l.type !== 'folder' && l.type !== 'frame-folder');- refLayers = refs.length > 0 ? refs : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');+ const refs = layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.isReference &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );+ refLayers =+ refs.length > 0+ ? refs+ : layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );} else if (referMode === 'refer-all') {- refLayers = layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');+ refLayers = layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );}const refTileCache = new Map<number, Uint8ClampedArray | null>();@@ -1019,6 +1072,7 @@ export function executeFloodFillOnTileGrid(params: {const maxTx = pixelToTileCoord(maxX, 0);const maxTy = pixelToTileCoord(maxY, 0);+ const alphaLocked = Boolean(options?.alphaLocked);const workBuf = new Uint8ClampedArray(BYTES_32BIT);for (let ty = minTy; ty <= maxTy; ty++) {@@ -1034,6 +1088,9 @@ export function executeFloodFillOnTileGrid(params: {if (!tileVisited && !antiAlias) continue;const existingTile = grid.getTile(targetLayerId, tx, ty, 0);+ if (alphaLocked && (!existingTile || !existingTile.data)) {+ continue;+ }if (existingTile && existingTile.data) {workBuf.set(grid.getTileAsRGBA(existingTile));} else {@@ -1053,11 +1110,22 @@ export function executeFloodFillOnTileGrid(params: {const filled = tileVisited ? tileVisited[rowOff + lx] !== 0 : false;if (filled) {const off = (rowOff + lx) << 2;- workBuf[off] = fillR;- workBuf[off + 1] = fillG;- workBuf[off + 2] = fillB;- workBuf[off + 3] = fillA;- tileChanged = true;+ if (alphaLocked) {+ const dstAlpha = workBuf[off + 3];+ if (dstAlpha === 0) continue;+ const srcA = fillA / 255;+ const invSrcA = 1 - srcA;+ workBuf[off] = Math.round(fillR * srcA + workBuf[off] * invSrcA);+ workBuf[off + 1] = Math.round(fillG * srcA + workBuf[off + 1] * invSrcA);+ workBuf[off + 2] = Math.round(fillB * srcA + workBuf[off + 2] * invSrcA);+ tileChanged = true;+ } else {+ workBuf[off] = fillR;+ workBuf[off + 1] = fillG;+ workBuf[off + 2] = fillB;+ workBuf[off + 3] = fillA;+ tileChanged = true;+ }} else if (antiAlias) {let filledNeighbors = 0;if (gx > 0 && isVisited(gx - 1, gy)) filledNeighbors++;@@ -1066,14 +1134,22 @@ export function executeFloodFillOnTileGrid(params: {if (gy < height - 1 && isVisited(gx, gy + 1)) filledNeighbors++;if (filledNeighbors >= 2) {const off = (rowOff + lx) << 2;+ if (alphaLocked && workBuf[off + 3] === 0) continue;const blendAlpha = (filledNeighbors / 4) * (fillA / 255) * 0.5;const dstA = workBuf[off + 3] / 255;- const outA = blendAlpha + dstA * (1 - blendAlpha);+ const outA = alphaLocked ? dstA : blendAlpha + dstA * (1 - blendAlpha);if (outA > 0) {- workBuf[off] = Math.round((fillR * blendAlpha + workBuf[off] * dstA * (1 - blendAlpha)) / outA);- workBuf[off + 1] = Math.round((fillG * blendAlpha + workBuf[off + 1] * dstA * (1 - blendAlpha)) / outA);- workBuf[off + 2] = Math.round((fillB * blendAlpha + workBuf[off + 2] * dstA * (1 - blendAlpha)) / outA);- workBuf[off + 3] = Math.round(outA * 255);+ if (alphaLocked) {+ const inv = 1 - blendAlpha;+ workBuf[off] = Math.round(fillR * blendAlpha + workBuf[off] * inv);+ workBuf[off + 1] = Math.round(fillG * blendAlpha + workBuf[off + 1] * inv);+ workBuf[off + 2] = Math.round(fillB * blendAlpha + workBuf[off + 2] * inv);+ } else {+ workBuf[off] = Math.round((fillR * blendAlpha + workBuf[off] * dstA * (1 - blendAlpha)) / outA);+ workBuf[off + 1] = Math.round((fillG * blendAlpha + workBuf[off + 1] * dstA * (1 - blendAlpha)) / outA);+ workBuf[off + 2] = Math.round((fillB * blendAlpha + workBuf[off + 2] * dstA * (1 - blendAlpha)) / outA);+ workBuf[off + 3] = Math.round(outA * 255);+ }tileChanged = true;}}@@ -1118,9 +1194,18 @@ export function executeLassoFillOnTileGrid(params: {fillColorHex: string;targetFormat?: TileFormat;alphaLocked?: boolean;+ selectionMask?: Uint8Array | null;}): { dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] } {- const { grid, targetLayerId, dimensions, polygon, fillColorHex, alphaLocked = false } = params;- if (polygon.length < 3 || typeof document === 'undefined') {+ const {+ grid,+ targetLayerId,+ dimensions,+ polygon,+ fillColorHex,+ alphaLocked = false,+ selectionMask = null,+ } = params;+ if (polygon.length < 3) {return { dirtyRect: null, modified: false, tileDeltas: [] };}@@ -1146,44 +1231,78 @@ export function executeLassoFillOnTileGrid(params: {const targetFormat = params.targetFormat ?? grid.getLayerFormat(targetLayerId);const beforeSnapshot = new Map<string, TileSnapshotEntry>();const CHUNK = 512;- const chunkCanvas = document.createElement('canvas');- chunkCanvas.width = Math.min(CHUNK, rw);- chunkCanvas.height = Math.min(CHUNK, rh);- const cCtx = chunkCanvas.getContext('2d', { willReadFrequently: true });- if (!cCtx) {- releaseTemporaryCanvas(chunkCanvas);- return { dirtyRect: null, modified: false, tileDeltas: [] };- }+ const chunkCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ const cCtx = chunkCanvas ? chunkCanvas.getContext('2d', { willReadFrequently: true }) : null;+ const [fillR, fillG, fillB, fillA] = parseColorToRgba(fillColorHex);+ const isEraseFill = fillA === 0;+ const hasSelectionMask = Boolean(+ selectionMask && selectionMask.length === dimensions.width * dimensions.height+ );try {for (let cy = ry; cy < ry1; cy += CHUNK) {const ch = Math.min(CHUNK, ry1 - cy);for (let cx = rx; cx < rx1; cx += CHUNK) {const cw = Math.min(CHUNK, rx1 - cx);- if (chunkCanvas.width !== cw) chunkCanvas.width = cw;- if (chunkCanvas.height !== ch) chunkCanvas.height = ch;-- cCtx.clearRect(0, 0, cw, ch);- cCtx.save();- cCtx.translate(-cx, -cy);- cCtx.fillStyle = fillColorHex;- cCtx.beginPath();- cCtx.moveTo(polygon[0].x, polygon[0].y);- for (let i = 1; i < polygon.length; i++) {- cCtx.lineTo(polygon[i].x, polygon[i].y);+ let chunkData: Uint8ClampedArray;++ if (chunkCanvas && cCtx) {+ if (chunkCanvas.width !== cw) chunkCanvas.width = cw;+ if (chunkCanvas.height !== ch) chunkCanvas.height = ch;++ cCtx.clearRect(0, 0, cw, ch);+ cCtx.save();+ cCtx.translate(-cx, -cy);+ cCtx.fillStyle = isEraseFill ? '#000000' : fillColorHex;+ cCtx.beginPath();+ cCtx.moveTo(polygon[0].x, polygon[0].y);+ for (let i = 1; i < polygon.length; i++) {+ cCtx.lineTo(polygon[i].x, polygon[i].y);+ }+ cCtx.closePath();+ cCtx.fill();+ cCtx.restore();+ chunkData = cCtx.getImageData(0, 0, cw, ch).data;+ } else {+ chunkData = new Uint8ClampedArray(cw * ch * 4);+ for (let ly = 0; ly < ch; ly++) {+ const gy = cy + ly + 0.5;+ const row = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ if (pointInPolygonFlood(cx + lx + 0.5, gy, polygon)) {+ const off = row + lx * 4;+ chunkData[off] = fillR;+ chunkData[off + 1] = fillG;+ chunkData[off + 2] = fillB;+ chunkData[off + 3] = isEraseFill ? 255 : fillA;+ }+ }+ }+ }++ if (hasSelectionMask && selectionMask) {+ for (let ly = 0; ly < ch; ly++) {+ const selRow = (cy + ly) * dimensions.width + cx;+ const dRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ if (selectionMask[selRow + lx] === 0) {+ chunkData[dRow + lx * 4 + 3] = 0;+ }+ }+ }}- cCtx.closePath();- cCtx.fill();- cCtx.restore();- const img = cCtx.getImageData(0, 0, cw, ch);grid.compositeStrokeToTiles({layerId: targetLayerId,- strokeData: img,+ strokeData: { data: chunkData, width: cw, height: ch },destX: cx,destY: cy,format: targetFormat,- compositeOp: alphaLocked ? 'source-atop' : 'source-over',+ compositeOp: isEraseFill+ ? 'destination-out'+ : alphaLocked+ ? 'source-atop'+ : 'source-over',opacity: 1.0,snapshotOut: beforeSnapshot,suppressNotify: true,@@ -1191,7 +1310,7 @@ export function executeLassoFillOnTileGrid(params: {}}} finally {- releaseTemporaryCanvas(chunkCanvas);+ if (chunkCanvas) releaseTemporaryCanvas(chunkCanvas);}const dirtyRect: DirtyRect = { x: rx, y: ry, width: rw, height: rh };@@ -1218,7 +1337,7 @@ export async function executeFloodFillOnTileGridAsync(params: {targetFormat?: TileFormat;options?: FloodFillOptions;}): Promise<{ dirtyRect: DirtyRect | null; modified: boolean; tileDeltas: TileDelta[] }> {- if (!isNativeRustAvailable()) {+ if (!isNativeRustAvailable() || params.options?.alphaLocked) {return executeFloodFillOnTileGrid(params);}@@ -1257,13 +1376,27 @@ export async function executeFloodFillOnTileGridAsync(params: {referMode === 'refer-reference'? (() => {const r = layers.filter(- (l) => l.visible && l.isReference && l.type !== 'folder' && l.type !== 'frame-folder'+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.isReference &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder');return r.length > 0? r- : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');+ : layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );})()- : layers.filter((l) => l.visible && l.type !== 'folder' && l.type !== 'frame-folder');+ : layers.filter(+ (l) =>+ isLayerEffectivelyVisibleInList(l, layers) &&+ l.type !== 'folder' &&+ l.type !== 'frame-folder'+ );const comp = new Uint8ClampedArray(width * height * 4);const tilesX = Math.ceil(width / TILE_SIZE);@@ -1287,20 +1420,26 @@ export async function executeFloodFillOnTileGridAsync(params: {refRgba = comp;}- const res = await floodFillNative({- refRgba,- targetRgba: referMode === 'active' ? null : targetRgba,- selectionMask: options?.selectionMask ?? null,- width,- height,- startX: px,- startY: py,- fillRgba: parseColorToRgba(fillColorHex),- tolerance,- closeGap: Math.max(0, Math.min(20, Math.round(options?.closeGap ?? 0))),- areaScale: Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0))),- antiAlias: options?.antiAlias ?? false,- });+ let res: Awaited<ReturnType<typeof floodFillNative>>;+ try {+ res = await floodFillNative({+ refRgba,+ targetRgba: referMode === 'active' ? null : targetRgba,+ selectionMask: options?.selectionMask ?? null,+ width,+ height,+ startX: px,+ startY: py,+ fillRgba: parseColorToRgba(fillColorHex),+ tolerance,+ closeGap: Math.max(0, Math.min(20, Math.round(options?.closeGap ?? 0))),+ areaScale: Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0))),+ antiAlias: options?.antiAlias ?? false,+ });+ } catch (err) {+ console.warn('Native flood fill failed, falling back to JS tile flood fill:', err);+ return executeFloodFillOnTileGrid(params);+ }if (!res.modified || !res.dirtyRect || !res.dirtyRgba) {return { dirtyRect: null, modified: false, tileDeltas: [] };diff --git a/src/utils/gradientEngine.ts b/src/utils/gradientEngine.tsindex 2e35301..b88ef85 100644--- a/src/utils/gradientEngine.ts+++ b/src/utils/gradientEngine.ts@@ -16,6 +16,9 @@ import type {TileDelta,} from '../types/editor';import { createSelectionMask } from './tonalEngine';+import { RgbColor, mixPigmentRgbOut } from './colorMixingEngine';++const _gradMixOut: RgbColor = { r: 0, g: 0, b: 0 };import {BYTES_32BIT,SparseTileGrid,@@ -61,6 +64,7 @@ export interface GradientSettings {blendMode: GradientBlendMode;repeat: GradientRepeatMode;dither: boolean;+ pigmentBlending?: boolean;reverse: boolean;meshCols: number; // 2..6meshRows: number; // 2..6@@ -158,6 +162,7 @@ export const DEFAULT_GRADIENT_SETTINGS: GradientSettings = {blendMode: 'normal',repeat: 'clamp',dither: true,+ pigmentBlending: false,reverse: false,meshCols: 3,meshRows: 3,@@ -249,7 +254,8 @@ export function sampleGradientStops(t: number,repeat: GradientRepeatMode,reverse: boolean,- out: [number, number, number, number]+ out: [number, number, number, number],+ pigmentBlending: boolean = false): void {if (stops.length === 0) {out[0] = 0;@@ -284,9 +290,16 @@ export function sampleGradientStops(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;+ if (pigmentBlending) {+ mixPigmentRgbOut(s0.r, s0.g, s0.b, s1.r, s1.g, s1.b, f, 1.0, _gradMixOut);+ out[0] = _gradMixOut.r;+ out[1] = _gradMixOut.g;+ out[2] = _gradMixOut.b;+ } else {+ 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;}@@ -841,7 +854,14 @@ export function renderGradientToTileGrid(params: RenderGradientParams): RenderGr} else {t = invRad > 0 ? Math.hypot(gx - start.x, gy - start.y) * invRad : 0;}- sampleGradientStops(stops, t, settings.repeat, settings.reverse, sampleOut);+ sampleGradientStops(+ stops,+ t,+ settings.repeat,+ settings.reverse,+ sampleOut,+ Boolean(settings.pigmentBlending)+ );const effAlpha = (sampleOut[3] / 255) * opacity * maskWeight;if (effAlpha <= 0) continue;compositePixelInPlace(diff --git a/src/utils/layerEffectsEngine.ts b/src/utils/layerEffectsEngine.tsindex 81cba10..ef7a62f 100644--- a/src/utils/layerEffectsEngine.ts+++ b/src/utils/layerEffectsEngine.ts@@ -1,4 +1,4 @@-import { LayerItem, DirtyRect } from '../types/editor';+import { LayerItem, DirtyRect, resolveToneDensityType } from '../types/editor';import { parseRgba } from './colorUtils';import { applyScreentone } from './screentoneEngine';@@ -209,7 +209,7 @@ export function applyLayerEffects(angle: layer.toneAngle ?? 45,dotShape: layer.toneDotShape ?? 'circle',dpi,- densityType: layer.toneDensityType ?? 'specified',+ densityType: resolveToneDensityType(layer),specifiedDensity: Math.max(0, Math.min(1, (layer.toneDensity ?? 40) / 100)),renderBackend: 'auto',},diff --git a/src/utils/mannequin3D.ts b/src/utils/mannequin3D.tsindex cc01a0a..0c8fdda 100644--- a/src/utils/mannequin3D.ts+++ b/src/utils/mannequin3D.ts@@ -353,9 +353,29 @@ export function findHumanoidBones(root: THREE.Object3D): HumanoidBones {return bones;}+/**+ * Applies a world-space delta rotation to a bone's local quaternion,+ * accounting for any rotation on the bone's ancestors/root.+ */+function applyWorldRotationDeltaToBone(+ bone: THREE.Bone,+ worldRotDelta: THREE.Quaternion+): void {+ const parentWorldQuat = new THREE.Quaternion();+ if (bone.parent) {+ bone.parent.updateMatrixWorld(true);+ bone.parent.getWorldQuaternion(parentWorldQuat);+ }+ const invParent = parentWorldQuat.clone().invert();+ const localDelta = invParent.multiply(worldRotDelta).multiply(parentWorldQuat);+ bone.quaternion.premultiply(localDelta).normalize();+ bone.updateMatrixWorld(true);+}+/*** Closed-form analytic 2-bone Inverse Kinematics (IK) with pole target constraint.- * Solves root (shoulder/hip) and mid (elbow/knee) joint rotations in real time.+ * Solves root (shoulder/hip) and mid (elbow/knee) joint rotations in real time,+ * properly converting world-space rotations into each bone's parent-local space.*/export function solveTwoBoneIK(rootBone: THREE.Bone,@@ -364,6 +384,10 @@ export function solveTwoBoneIK(targetWorldPos: THREE.Vector3,poleWorldPos: THREE.Vector3): void {+ rootBone.updateMatrixWorld(true);+ midBone.updateMatrixWorld(true);+ endBone.updateMatrixWorld(true);+const rootWorldPos = new THREE.Vector3();const midWorldPos = new THREE.Vector3();const endWorldPos = new THREE.Vector3();@@ -379,11 +403,15 @@ export function solveTwoBoneIK(if (l1 <= 1e-4 || l2 <= 1e-4) return;const toTarget = new THREE.Vector3().subVectors(targetWorldPos, rootWorldPos);- const targetDist = Math.max(0.001, Math.min(totalLength - 1e-4, toTarget.length()));- const targetDir = toTarget.clone().normalize();+ const rawDist = toTarget.length();+ if (rawDist <= 1e-5) return;- // Law of Cosines for limb angles- // cos(alpha): angle at root joint+ const minReach = Math.abs(l1 - l2) + 1e-3;+ const maxReach = totalLength - 1e-4;+ const targetDist = Math.max(minReach, Math.min(maxReach, rawDist));+ const targetDir = toTarget.clone().divideScalar(rawDist);++ // Law of Cosines for angle at root jointconst cosAlpha = Math.max(-1.0,Math.min(1.0, (l1 * l1 + targetDist * targetDist - l2 * l2) / (2.0 * l1 * targetDist))@@ -391,10 +419,17 @@ export function solveTwoBoneIK(const alpha = Math.acos(cosAlpha);// Compute bend plane normal from pole vector- const toPole = new THREE.Vector3().subVectors(poleWorldPos, rootWorldPos).normalize();+ const toPole = new THREE.Vector3().subVectors(poleWorldPos, rootWorldPos);+ if (toPole.lengthSq() > 1e-6) {+ toPole.normalize();+ } else {+ toPole.set(0, 0, 1);+ }let bendNormal = new THREE.Vector3().crossVectors(targetDir, toPole);if (bendNormal.lengthSq() < 1e-4) {- bendNormal = new THREE.Vector3(0, 0, 1).applyQuaternion(rootBone.quaternion);+ const worldQuat = new THREE.Quaternion();+ rootBone.getWorldQuaternion(worldQuat);+ bendNormal = new THREE.Vector3(0, 0, 1).applyQuaternion(worldQuat).normalize();} else {bendNormal.normalize();}@@ -406,24 +441,53 @@ export function solveTwoBoneIK(.normalize();const solvedMidWorldPos = rootWorldPos.clone().addScaledVector(midDir, l1);- // Orient Root Bone towards solved mid position- const rootParent = rootBone.parent;- if (rootParent) {- const currentLimbDir = new THREE.Vector3().subVectors(midWorldPos, rootWorldPos).normalize();- const targetLimbDir = new THREE.Vector3().subVectors(solvedMidWorldPos, rootWorldPos).normalize();+ // 1. Orient Root Bone towards solved mid position (in parent-local space)+ const currentLimbDir = new THREE.Vector3().subVectors(midWorldPos, rootWorldPos).normalize();+ const targetLimbDir = new THREE.Vector3().subVectors(solvedMidWorldPos, rootWorldPos).normalize();+ if (currentLimbDir.lengthSq() > 1e-6 && targetLimbDir.lengthSq() > 1e-6) {const rotDelta = new THREE.Quaternion().setFromUnitVectors(currentLimbDir, targetLimbDir);- rootBone.quaternion.premultiply(rotDelta);- rootBone.updateMatrixWorld(true);+ applyWorldRotationDeltaToBone(rootBone, rotDelta);}- // Orient Mid Bone towards target position- const midParent = midBone.parent;- if (midParent) {- const currentEndDir = new THREE.Vector3().subVectors(endWorldPos, midWorldPos).normalize();- const targetEndDir = new THREE.Vector3().subVectors(targetWorldPos, solvedMidWorldPos).normalize();+ // 2. Re-read updated world positions after root bone rotated, then orient Mid Bone towards target+ midBone.getWorldPosition(midWorldPos);+ endBone.getWorldPosition(endWorldPos);++ const currentEndDir = new THREE.Vector3().subVectors(endWorldPos, midWorldPos).normalize();+ const targetEndDir = new THREE.Vector3().subVectors(targetWorldPos, midWorldPos).normalize();+ if (currentEndDir.lengthSq() > 1e-6 && targetEndDir.lengthSq() > 1e-6) {const rotDelta = new THREE.Quaternion().setFromUnitVectors(currentEndDir, targetEndDir);- midBone.quaternion.premultiply(rotDelta);- midBone.updateMatrixWorld(true);+ applyWorldRotationDeltaToBone(midBone, rotDelta);+ }+}++/**+ * Synchronizes IK handle meshes to the live world positions of their corresponding bones.+ */+export function syncIKHandlesToBones(+ bones: HumanoidBones | null,+ handles: Record<string, THREE.Mesh> | null+): void {+ if (!bones || !handles) return;+ const wp = new THREE.Vector3();+ const pairs: Array<[string, THREE.Bone | undefined]> = [+ ['head', bones.head],+ ['leftHand', bones.leftHand],+ ['rightHand', bones.rightHand],+ ['leftFoot', bones.leftFoot],+ ['rightFoot', bones.rightFoot],+ ];+ for (const [name, bone] of pairs) {+ const handle = handles[name];+ if (!handle) continue;+ if (bone) {+ bone.updateMatrixWorld(true);+ bone.getWorldPosition(wp);+ handle.position.copy(wp);+ handle.visible = true;+ } else {+ handle.visible = false;+ }}}@@ -436,6 +500,7 @@ export function createIKHandles(): {} {const container = new THREE.Group();container.name = 'IKHandles';+ container.userData.is3DHelper = true;const handles: Record<string, THREE.Mesh> = {};@@ -456,13 +521,31 @@ export function createIKHandles(): {const geom = new THREE.SphereGeometry(def.size, 16, 16);const mat = new THREE.MeshBasicMaterial({color: def.color,- wireframe: true,+ transparent: true,+ opacity: 0.55,+ wireframe: false,depthTest: false,});const mesh = new THREE.Mesh(geom, mat);mesh.name = `IKHandle_${def.name}`;+ mesh.userData.is3DHelper = true;+ mesh.userData.ikHandleName = def.name;mesh.position.set(...def.initialPos);mesh.renderOrder = 999;++ // Crisp outer ring wireframe for clear hit-target readability+ const wireGeom = new THREE.SphereGeometry(def.size * 1.15, 12, 12);+ const wireMat = new THREE.MeshBasicMaterial({+ color: def.color,+ wireframe: true,+ depthTest: false,+ });+ const wire = new THREE.Mesh(wireGeom, wireMat);+ wire.userData.is3DHelper = true;+ wire.userData.ikHandleName = def.name;+ wire.renderOrder = 1000;+ mesh.add(wire);+container.add(mesh);handles[def.name] = mesh;}diff --git a/src/utils/retouchEngine.ts b/src/utils/retouchEngine.tsindex f664aa5..80a66d1 100644--- a/src/utils/retouchEngine.ts+++ b/src/utils/retouchEngine.ts@@ -23,6 +23,17 @@ import {unpack8BitToRGBA,} from './tileEngine';import { parseHexRgb } from './gradientEngine';+import {+ RgbColor,+ decodeSpectralKSToSrgb,+ encodeSrgbToSpectralKS,+ mixPigmentRgbOut,+} from './colorMixingEngine';++const _smudgeMixOut: RgbColor = { r: 0, g: 0, b: 0 };+const _smudgeReloadOut: RgbColor = { r: 0, g: 0, b: 0 };+const _blurDecodeOut: RgbColor = { r: 0, g: 0, b: 0 };+const _blurMixOut: RgbColor = { r: 0, g: 0, b: 0 };export type RetouchMode = 'smudge' | 'blur' | 'dodge' | 'burn' | 'clone-stamp';export type RetouchTonalRange = 'shadows' | 'midtones' | 'highlights';@@ -38,6 +49,8 @@ export interface RetouchSettings {tonalRange: RetouchTonalRange; // Dodge / Burn rangeprotectTones: boolean; // Dodge / Burn hue preservationsmudgeFingerPainting: boolean; // Load primary color at stroke start+ pigmentBlending: boolean; // Physical 7-band Kubelka-Munk spectral pigment blending for Smudge & Blur+ pigmentStrength: number; // 0..100 % Kubelka-Munk pigment blending strengthcloneAligned: boolean; // Keep relative offset across strokescloneSampleMode: CloneSampleMode; // Active layer vs all visible composited}@@ -52,6 +65,8 @@ export const DEFAULT_RETOUCH_SETTINGS: RetouchSettings = {tonalRange: 'midtones',protectTones: true,smudgeFingerPainting: false,+ pigmentBlending: false,+ pigmentStrength: 100,cloneAligned: true,cloneSampleMode: 'active',};@@ -300,7 +315,9 @@ function applySmudgeDab(strength: number,hardness: number,primaryColor: string,- fingerPainting: boolean+ fingerPainting: boolean,+ pigmentBlending: boolean = false,+ pigmentStrength: number = 1.0): DirtyRect | null {const docW = session.dimensions.width;const docH = session.dimensions.height;@@ -399,10 +416,50 @@ function applySmudgeDab(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;+ let outPR: number;+ let outPG: number;+ let outPB: number;+ let outR = 0;+ let outG = 0;+ let outB = 0;++ const usePigment = pigmentBlending && pigmentStrength > 0.005 && dstA > 0.5 && srcA > 0.5;+ if (usePigment) {+ const invSrcA = 255 / srcA;+ const srcR = srcPR * invSrcA;+ const srcG = srcPG * invSrcA;+ const srcB = srcPB * invSrcA;+ const colorW = (srcA * w) / Math.max(1e-4, dstA * invW + srcA * w);+ mixPigmentRgbOut(+ data[rIdx],+ data[rIdx + 1],+ data[rIdx + 2],+ srcR,+ srcG,+ srcB,+ colorW,+ pigmentStrength,+ _smudgeMixOut+ );+ outR = _smudgeMixOut.r;+ outG = _smudgeMixOut.g;+ outB = _smudgeMixOut.b;+ const outANorm = outA / 255;+ outPR = outR * outANorm;+ outPG = outG * outANorm;+ outPB = outB * outANorm;+ } else {+ outPR = dstPR * invW + srcPR * w;+ outPG = dstPG * invW + srcPG * w;+ outPB = dstPB * invW + srcPB * w;+ if (outA > 0.5) {+ const invOutA = 255 / outA;+ outR = outPR * invOutA;+ outG = outPG * invOutA;+ outB = outPB * invOutA;+ }+ }if (outA <= 0.5) {data[rIdx] = 0;@@ -410,20 +467,41 @@ function applySmudgeDab(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] = clamp255(Math.round(outR));+ data[rIdx + 1] = clamp255(Math.round(outG));+ data[rIdx + 2] = clamp255(Math.round(outB));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;+ const nextBufA = srcA * invPickup + outA * pickupRate;+ if (usePigment && nextBufA > 0.5) {+ const invSrcA = 255 / srcA;+ const reloadColorW = (outA * pickupRate) / Math.max(1e-4, srcA * invPickup + outA * pickupRate);+ mixPigmentRgbOut(+ srcPR * invSrcA,+ srcPG * invSrcA,+ srcPB * invSrcA,+ outR,+ outG,+ outB,+ reloadColorW,+ pigmentStrength,+ _smudgeReloadOut+ );+ const nextANorm = nextBufA / 255;+ buf[bIdx] = _smudgeReloadOut.r * nextANorm;+ buf[bIdx + 1] = _smudgeReloadOut.g * nextANorm;+ buf[bIdx + 2] = _smudgeReloadOut.b * nextANorm;+ buf[bIdx + 3] = nextBufA;+ } else {+ buf[bIdx] = srcPR * invPickup + outPR * pickupRate;+ buf[bIdx + 1] = srcPG * invPickup + outPG * pickupRate;+ buf[bIdx + 2] = srcPB * invPickup + outPB * pickupRate;+ buf[bIdx + 3] = nextBufA;+ }touched = true;}}@@ -440,7 +518,9 @@ function applyBlurDab(cy: number,radius: number,strength: number,- hardness: number+ hardness: number,+ pigmentBlending: boolean = false,+ pigmentStrength: number = 1.0): DirtyRect | null {const docW = session.dimensions.width;const docH = session.dimensions.height;@@ -466,6 +546,10 @@ function applyBlurDab(const srcRoi = grid.readImageData(session.layerId, px0, py0, pw, ph);const srcData = srcRoi.data;+ const usePigment = pigmentBlending && pigmentStrength > 0.005;+ const kSize = blurK * 2 + 1;+ const invK = 1 / kSize;+// Convert to premultiplied Float32 for fringe-free separable box blurconst premul = new Float32Array(pw * ph * 4);const horiz = new Float32Array(pw * ph * 4);@@ -478,16 +562,35 @@ function applyBlurDab(premul[o + 3] = srcData[o + 3];}- const kSize = blurK * 2 + 1;- const invK = 1 / kSize;+ // Optional 10-channel premultiplied Kubelka-Munk K/S + residual buffers for true spectral pigment blur+ let specPremul: Float32Array | null = null;+ let specHoriz: Float32Array | null = null;+ if (usePigment) {+ specPremul = new Float32Array(pw * ph * 10);+ specHoriz = new Float32Array(pw * ph * 10);+ const tmpSpec = new Float32Array(10);+ for (let i = 0; i < pw * ph; i++) {+ const o = i * 4;+ const a = srcData[o + 3] / 255;+ if (a > 0) {+ encodeSrgbToSpectralKS(srcData[o], srcData[o + 1], srcData[o + 2], tmpSpec, 0);+ const so = i * 10;+ for (let c = 0; c < 10; c++) {+ specPremul[so + c] = tmpSpec[c] * a;+ }+ }+ }+ }// Horizontal pass+ const sRowSum = usePigment ? new Float32Array(10) : null;for (let y = 0; y < ph; y++) {const rowBase = y * pw;let sr = 0;let sg = 0;let sb = 0;let sa = 0;+ if (sRowSum) sRowSum.fill(0);for (let k = -blurK; k <= blurK; k++) {const sx = k < 0 ? 0 : k >= pw ? pw - 1 : k;const o = (rowBase + sx) * 4;@@ -495,6 +598,10 @@ function applyBlurDab(sg += premul[o + 1];sb += premul[o + 2];sa += premul[o + 3];+ if (sRowSum && specPremul) {+ const so = (rowBase + sx) * 10;+ for (let c = 0; c < 10; c++) sRowSum[c] += specPremul[so + c];+ }}for (let x = 0; x < pw; x++) {const o = (rowBase + x) * 4;@@ -502,6 +609,10 @@ function applyBlurDab(horiz[o + 1] = sg * invK;horiz[o + 2] = sb * invK;horiz[o + 3] = sa * invK;+ if (sRowSum && specHoriz) {+ const so = (rowBase + x) * 10;+ for (let c = 0; c < 10; c++) specHoriz[so + c] = sRowSum[c] * invK;+ }const remX = x - blurK < 0 ? 0 : x - blurK;const addX = x + blurK + 1 >= pw ? pw - 1 : x + blurK + 1;@@ -511,6 +622,11 @@ function applyBlurDab(sg += premul[ao + 1] - premul[ro + 1];sb += premul[ao + 2] - premul[ro + 2];sa += premul[ao + 3] - premul[ro + 3];+ if (sRowSum && specPremul) {+ const rso = (rowBase + remX) * 10;+ const aso = (rowBase + addX) * 10;+ for (let c = 0; c < 10; c++) sRowSum[c] += specPremul[aso + c] - specPremul[rso + c];+ }}}@@ -525,6 +641,9 @@ function applyBlurDab(snapshotRoiTiles(grid, session.layerId, rx0, ry0, rw, rh, session.beforeSnapshot);+ const sColSum = usePigment ? new Float32Array(10) : null;+ const sColDec = usePigment ? new Float32Array(10) : null;+for (let lx = 0; lx < rw; lx++) {const sx = rx0 - px0 + lx;const gx = rx0 + lx;@@ -535,6 +654,7 @@ function applyBlurDab(let sg = 0;let sb = 0;let sa = 0;+ if (sColSum) sColSum.fill(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;@@ -542,6 +662,10 @@ function applyBlurDab(sg += horiz[o + 1];sb += horiz[o + 2];sa += horiz[o + 3];+ if (sColSum && specHoriz) {+ const so = (sy * pw + sx) * 10;+ for (let c = 0; c < 10; c++) sColSum[c] += specHoriz[so + c];+ }}for (let ly = 0; ly < rh; ly++) {@@ -552,6 +676,25 @@ function applyBlurDab(const bb = sb * invK;const ba = sa * invK;+ let pigBlurR = 0;+ let pigBlurG = 0;+ let pigBlurB = 0;+ const hasPigBlur = Boolean(sColSum && sColDec && ba > 0.5);+ if (hasPigBlur && sColSum && sColDec) {+ const invAlphaNorm = 1 / ((ba / 255) * kSize);+ for (let c = 0; c < 10; c++) {+ sColDec[c] = sColSum[c] * invAlphaNorm;+ }+ decodeSpectralKSToSrgb(sColDec, 0, _blurDecodeOut);+ const invBa = 255 / ba;+ const regBlurR = br * invBa;+ const regBlurG = bg * invBa;+ const regBlurB = bb * invBa;+ pigBlurR = regBlurR + (_blurDecodeOut.r - regBlurR) * pigmentStrength;+ pigBlurG = regBlurG + (_blurDecodeOut.g - regBlurG) * pigmentStrength;+ pigBlurB = regBlurB + (_blurDecodeOut.b - regBlurB) * pigmentStrength;+ }+const remY = Math.max(0, curY - blurK);const addY = Math.min(ph - 1, curY + blurK + 1);const ro = (remY * pw + sx) * 4;@@ -560,6 +703,11 @@ function applyBlurDab(sg += horiz[ao + 1] - horiz[ro + 1];sb += horiz[ao + 2] - horiz[ro + 2];sa += horiz[ao + 3] - horiz[ro + 3];+ if (sColSum && specHoriz) {+ const rso = (remY * pw + sx) * 10;+ const aso = (addY * pw + sx) * 10;+ for (let c = 0; c < 10; c++) sColSum[c] += specHoriz[aso + c] - specHoriz[rso + c];+ }const distY = gy + 0.5 - cy;const dNorm = Math.hypot(distX, distY) * invR;@@ -577,11 +725,7 @@ function applyBlurDab(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) {@@ -589,7 +733,28 @@ function applyBlurDab(outData[oIdx + 1] = 0;outData[oIdx + 2] = 0;outData[oIdx + 3] = 0;+ } else if (hasPigBlur && dstA > 0.5) {+ const colorW = (ba * w) / Math.max(1e-4, dstA * invW + ba * w);+ mixPigmentRgbOut(+ outData[oIdx],+ outData[oIdx + 1],+ outData[oIdx + 2],+ pigBlurR,+ pigBlurG,+ pigBlurB,+ colorW,+ pigmentStrength,+ _blurMixOut+ );+ outData[oIdx] = clamp255(Math.round(_blurMixOut.r));+ outData[oIdx + 1] = clamp255(Math.round(_blurMixOut.g));+ outData[oIdx + 2] = clamp255(Math.round(_blurMixOut.b));+ outData[oIdx + 3] = clamp255(Math.round(finalA));} else {+ const dstANorm = dstA / 255;+ 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 invA = 255 / finalA;outData[oIdx] = clamp255(Math.round(finalPR * invA));outData[oIdx + 1] = clamp255(Math.round(finalPG * invA));@@ -843,6 +1008,9 @@ export function applyRetouchStrokeSegment(params: {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 pigmentBlending = Boolean(settings.pigmentBlending);+ const pigmentStrength = clamp01((settings.pigmentStrength ?? 100) / 100);+const runDab = (dx: number, dy: number): DirtyRect | null => {switch (session.mode) {case 'smudge':@@ -855,10 +1023,22 @@ export function applyRetouchStrokeSegment(params: {strength,hardness,primaryColor,- settings.smudgeFingerPainting+ settings.smudgeFingerPainting,+ pigmentBlending,+ pigmentStrength);case 'blur':- return applyBlurDab(grid, session, dx, dy, radius, strength, hardness);+ return applyBlurDab(+ grid,+ session,+ dx,+ dy,+ radius,+ strength,+ hardness,+ pigmentBlending,+ pigmentStrength+ );case 'dodge':case 'burn':return applyDodgeBurnDab(diff --git a/src/utils/saveManager/cpuComposite.ts b/src/utils/saveManager/cpuComposite.tsindex 4234996..4ccefc8 100644--- a/src/utils/saveManager/cpuComposite.ts+++ b/src/utils/saveManager/cpuComposite.ts@@ -1,10 +1,11 @@-import { CanvasDimensions, LayerItem, isFolderLikeLayer } from '../../types/editor';+import { CanvasDimensions, LayerItem, isFolderLikeLayer, resolveToneDensityType } from '../../types/editor';import { getCanvasCompositeOperation } from '../canvasUtils';import {buildLayerTree,groupTreeNodesForCompositing,LayerTreeNode,} from '../compositor';+import { applyScreentoneCPU } from '../screentoneEngine';import { applyAdjustment } from '../tonalEngine';import { applyMultiFrameClip, renderFrameBorder } from '../frameEngine';import { SparseTileGrid, releaseTemporaryCanvas } from '../tileEngine';@@ -62,6 +63,39 @@ export function compositeCanvasCpuFallback(return { canvas: masked, isTemporary: true };};+ const getPreparedLayerCanvas = (+ layer: LayerItem,+ srcCanvas: HTMLCanvasElement,+ effectiveOpacity: number+ ): { canvas: HTMLCanvasElement; isTemporary: boolean; opacityBaked: boolean } => {+ const masked = getMaskedLayerCanvas(layer, srcCanvas);+ if (!layer.toneEnabled) {+ return { ...masked, opacityBaked: false };+ }+ const toneCanvas = document.createElement('canvas');+ toneCanvas.width = dimensions.width;+ toneCanvas.height = dimensions.height;+ const toneType = resolveToneDensityType(layer);+ const specDensity = Math.max(0, Math.min(1, (layer.toneDensity ?? 40) / 100));+ applyScreentoneCPU(masked.canvas, toneCanvas, {+ frequency: layer.toneFrequency ?? 60,+ angle: layer.toneAngle ?? 45,+ dotShape: layer.toneDotShape ?? 'circle',+ dpi: dimensions.dpi ?? 600,+ densityType: toneType,+ specifiedDensity: toneType === 'specified' ? specDensity * effectiveOpacity : specDensity,+ antiAliasing: false,+ });+ if (masked.isTemporary) {+ releaseTemporaryCanvas(masked.canvas);+ }+ return {+ canvas: toneCanvas,+ isTemporary: true,+ opacityBaked: toneType === 'specified',+ };+ };+const renderTreeNodes = (targetCtx: CanvasRenderingContext2D,nodes: LayerTreeNode[],@@ -160,7 +194,8 @@ export function compositeCanvasCpuFallback(const baseAcq = acquireLayerExportCanvas(baseLayer, dimensions, layerCanvasesMap, tileGrid);if (!baseAcq.canvas) continue;- const maskedBase = getMaskedLayerCanvas(baseLayer, baseAcq.canvas);+ const baseEffOpacity = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));+ const maskedBase = getPreparedLayerCanvas(baseLayer, baseAcq.canvas, baseEffOpacity);const activeClipped = group.clippedNodes.map((n) => n.layer)@@ -168,7 +203,7 @@ export function compositeCanvasCpuFallback(if (activeClipped.length === 0) {targetCtx.save();- targetCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));+ targetCtx.globalAlpha = maskedBase.opacityBaked ? 1.0 : baseEffOpacity;targetCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);targetCtx.drawImage(maskedBase.canvas, 0, 0);targetCtx.restore();@@ -179,17 +214,18 @@ export function compositeCanvasCpuFallback(const gCtx = groupCanvas.getContext('2d');if (gCtx) {gCtx.save();- gCtx.globalAlpha = Math.max(0, Math.min(1, baseLayer.opacity * opacityMul));+ gCtx.globalAlpha = maskedBase.opacityBaked ? 1.0 : baseEffOpacity;gCtx.drawImage(maskedBase.canvas, 0, 0);gCtx.restore();for (const clipped of activeClipped) {const clipAcq = acquireLayerExportCanvas(clipped, dimensions, layerCanvasesMap, tileGrid);if (!clipAcq.canvas) continue;- const maskedClip = getMaskedLayerCanvas(clipped, clipAcq.canvas);+ const clipEffOpacity = Math.max(0, Math.min(1, clipped.opacity * opacityMul));+ const maskedClip = getPreparedLayerCanvas(clipped, clipAcq.canvas, clipEffOpacity);gCtx.save();- gCtx.globalAlpha = Math.max(0, Math.min(1, clipped.opacity * opacityMul));+ gCtx.globalAlpha = maskedClip.opacityBaked ? 1.0 : clipEffOpacity;gCtx.globalCompositeOperation = 'source-atop';gCtx.drawImage(maskedClip.canvas, 0, 0);gCtx.restore();diff --git a/src/utils/screentoneEngine.ts b/src/utils/screentoneEngine.tsindex 9c83f5d..3a569a4 100644--- a/src/utils/screentoneEngine.ts+++ b/src/utils/screentoneEngine.ts@@ -43,8 +43,9 @@ export interface ScreentoneOptions {solidBlackAtMax?: boolean;/**- * Sub-pixel edge anti-aliasing for smooth on-screen display without moiré or staircase aliasing.- * Set false for strict 1-bit binary output (e.g. monochrome print). (default: true)+ * Sub-pixel edge anti-aliasing for dots.+ * Clip Studio Paint screentones are strictly 1-bit binary (pure black ink / transparent paper)+ * with zero gray fringe. (default: false)*/antiAliasing?: boolean;@@ -62,10 +63,17 @@ export interface ScreentoneOptions {specifiedDensity?: number;/**- * Viewport zoom scale. When zoom < 1.0, automatically crossfades into equivalent- * continuous grayscale luminance to eliminate spatial aliasing and moiré patterns.+ * Viewport zoom scale. When zoom < 1.0, smoothly prevents moiré at low zoom levels+ * while keeping 100%+ zoom strictly 1-bit binary.*/zoom?: number;++ /**+ * Optional document-space origin offset for tile-local CPU rendering so every tile+ * aligns seamlessly to the global document halftone lattice.+ */+ docOriginX?: number;+ docOriginY?: number;}// Runtime system endianness check for ultra-fast 32-bit pixel writes@@ -93,18 +101,82 @@ export function fract(t: number): number {return t - Math.floor(t);}+const TWO_PI = Math.PI * 2.0;+const PI_OVER_4 = Math.PI * 0.25;+const INV_PI = 1.0 / Math.PI;+const ONE_MINUS_PI_OVER_4 = 1.0 - PI_OVER_4;++export interface RationalHalftoneBasis {+ a: number;+ b: number;+ denom: number;+}++/**+ * Computes an exact integer-lattice orthogonal basis (a, b) & (-b, a) for Clip Studio Paint /+ * Holladay rational-tangent halftone screening. Snapping the rotated cell vector to the integer+ * pixel grid ensures every single screentone dot across the entire canvas is bit-for-bit+ * identical with zero irrational-angle shape drift or beating artifacts.+ */+export function computeRationalHalftoneBasis(+ cellSize: number,+ cosA: number,+ sinA: number+): RationalHalftoneBasis {+ const safeCell = Math.max(2.0, cellSize);+ let a = Math.round(safeCell * cosA);+ let b = Math.round(safeCell * sinA);+ if (a * a + b * b < 4) {+ const fallback = Math.max(2, Math.round(safeCell));+ if (Math.abs(cosA) >= Math.abs(sinA)) {+ a = cosA >= 0 ? fallback : -fallback;+ b = 0;+ } else {+ a = 0;+ b = sinA >= 0 ? fallback : -fallback;+ }+ }+ return { a, b, denom: a * a + b * b };+}++/**+ * Exact area-calibrated circle dot radius inside [-0.5, 0.5]^2 for density in [0, 1].+ * - 0% to 78.54% (π/4): exact geometric circle radius R = sqrt(density / π)+ * - 78.54% to 100%: smooth clipped-circle continuation to R = sqrt(2)/2 (max area error < 0.37%)+ */+function circleDotRadius(density: number): number {+ if (density <= PI_OVER_4) {+ return Math.sqrt(density * INV_PI);+ }+ const t = Math.max(0.0, (1.0 - density) / ONE_MINUS_PI_OVER_4);+ return Math.SQRT1_2 - (Math.SQRT1_2 - 0.5) * Math.pow(t, 0.43);+}+/**- * Evaluates the mathematical Clip Studio Paint style halftone formula for a single- * document-space point (x, y) with a given ink density in [0.0, 1.0].+ * Area-calibrated threshold for smooth continuous Euclidean (cosine) spot function+ * spot(u, v) = 0.5 + 0.25 * (cos(2π u) + cos(2π v)).+ */+function euclideanSpotThreshold(density: number): number {+ const u = density <= 0.5 ? 2.0 * density : 2.0 * (1.0 - density);+ const offset = 0.78539816 * u - 0.28539816 * u * u;+ return density <= 0.5 ? 1.0 - offset : offset;+}++/**+ * Area-calibrated threshold for diamond spot function spot(u, v) = 1.0 - (|u| + |v|).+ */+function diamondSpotThreshold(density: number): number {+ return density <= 0.5+ ? 1.0 - Math.sqrt(0.5 * density)+ : Math.sqrt(0.5 * (1.0 - density));+}++/**+ * Evaluates the exact 1-bit binary Clip Studio Paint halftone formula for a single+ * document-space pixel (x, y) with ink density in [0.0, 1.0].*- * Formula:- * xr = x * cos(θ) - y * sin(θ)- * yr = x * sin(θ) + y * cos(θ)- * u = fract(xr / cellSize) - 0.5- * v = fract(yr / cellSize) - 0.5- * dist = sqrt(u * u + v * v)- * dotRadius = sqrt(density) * 0.5- * Binary Threshold: dist <= dotRadius => pure black (true), else transparent (false)+ * Uses rational integer-lattice screening so every dot on the canvas has an identical,+ * razor-sharp symmetric 1-bit bitmap shape with zero floating-point drift.*/export function evaluateHalftoneDot(x: number,@@ -119,41 +191,35 @@ export function evaluateHalftoneDot(if (density <= 0.001) return false;if (solidBlackAtMax && density >= 0.999) return true;- // 1. Coordinate Transformation in document space- const xr = x * cosA - y * sinA;- const yr = x * sinA + y * cosA;+ const px = Math.floor(x);+ const py = Math.floor(y);+ const { a, b, denom } = computeRationalHalftoneBasis(cellSize, cosA, sinA);- // 2. Normalized Cell Coordinates centered in [-0.5, 0.5]- const invCellSize = 1.0 / cellSize;- const u = (xr * invCellSize) - Math.floor(xr * invCellSize) - 0.5;- const v = (yr * invCellSize) - Math.floor(yr * invCellSize) - 0.5;+ const xr = px * a - py * b;+ const yr = px * b + py * a;+ const invDenom = 1.0 / denom;++ const u = ((((xr % denom) + denom) % denom) * invDenom) - 0.5;+ const v = ((((yr % denom) + denom) % denom) * invDenom) - 0.5;if (dotShape === 'line') {const spot = 1.0 - 2.0 * Math.abs(u);- return spot >= (1.0 - density);+ return spot >= 1.0 - density;}if (dotShape === 'diamond') {const spot = 1.0 - (Math.abs(u) + Math.abs(v));- return spot >= (1.0 - density);+ return spot >= diamondSpotThreshold(density);}- // Authentic Manga / Clip Studio Euclidean Round Dot Spot Function- const absU = Math.abs(u);- const absV = Math.abs(v);- let spot: number;-- if (absU + absV <= 0.5) {- // Inner diamond: round black dot centered at (0, 0)- spot = 1.0 - 2.0 * (u * u + v * v);- } else {- // Corner region: white pinholes centered at cell corners (±0.5, ±0.5)- const uc = absU - 0.5;- const vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);+ if (dotShape === 'euclidean') {+ const spot = 0.5 + 0.25 * (Math.cos(TWO_PI * u) + Math.cos(TWO_PI * v));+ return spot >= euclideanSpotThreshold(density);}- return spot >= (1.0 - density);+ // Clip Studio Paint standard Circle dot: true geometric round dot+ const r = circleDotRadius(density);+ return u * u + v * v <= r * r + 1e-7;}let cachedDstImageData: ImageData | null = null;@@ -169,8 +235,8 @@ function getScratchImageData(ctx: CanvasRenderingContext2D, w: number, h: number/*** High-throughput CPU 32-bit TypedArray implementation.*- * Guarantees bit-for-bit mathematical determinism across all dirtyRect updates- * with zero floating-point accumulation drift and zero seam artifacts.+ * Renders crisp 1-bit binary Clip Studio Paint screentone dots locked to the document-space+ * rational integer lattice with bit-for-bit determinism across dirtyRect and tile updates.*/export function applyScreentoneCPU(sourceCanvas: HTMLCanvasElement,@@ -191,7 +257,7 @@ export function applyScreentoneCPU(const dstCtx = targetCanvas.getContext('2d');if (!srcCtx || !dstCtx) return;- // Bounding rect in document space+ // Bounding rect in local canvas coordinateslet minX = 0;let minY = 0;let maxX = width;@@ -223,51 +289,63 @@ export function applyScreentoneCPU(const sinT = Math.sin(rad);const dpi = Math.max(1, options.dpi ?? 600);- // Ensure cellSize has a 3.5px minimum to prevent high-frequency moire noise on low-DPI canvases+ // Ensure cellSize has a 3.5px minimum to prevent high-frequency noise on low-DPI canvasesconst cellSize = Math.max(3.5, dpi / frequency);- const invCellSize = 1.0 / cellSize;+ const { a: basisA, b: basisB, denom } = computeRationalHalftoneBasis(cellSize, cosT, sinT);+ const invDenom = 1.0 / denom;+const dotShape = options.dotShape ?? 'circle';const isLine = dotShape === 'line';const isDiamond = dotShape === 'diamond';+ const isEuclidean = dotShape === 'euclidean';const solidBlackAtMax = options.solidBlackAtMax !== false;- const antiAliasing = options.antiAliasing !== false;+ // Clip Studio Paint screentones are strictly 1-bit binary by default (zero gray AA blur)+ const antiAliasing = options.antiAliasing === true;const isSpecified = options.densityType !== 'image';const specDensity = Math.max(0, Math.min(1, options.specifiedDensity ?? 0.4));- const specOneMinusDensity = 1.0 - specDensity;-- // Sub-pixel anti-aliasing transition half-width in spot function units- const aaHalfSpan = Math.min(0.25, 0.75 * invCellSize);+ const docOriginX = Math.floor(options.docOriginX ?? 0);+ const docOriginY = Math.floor(options.docOriginY ?? 0);++ // Precompute threshold for full-alpha specified-density fast path+ const specCircleR = !isLine && !isDiamond && !isEuclidean ? circleDotRadius(specDensity) : 0;+ const specCircleR2 = specCircleR * specCircleR + 1e-7;+ const specEuclidThresh = isEuclidean ? euclideanSpotThreshold(specDensity) : 0;+ const specDiamondThresh = isDiamond ? diamondSpotThreshold(specDensity) : 0;+ const specLineThresh = 1.0 - specDensity;++ // Sub-pixel anti-aliasing transition half-width (only used when antiAliasing === true)+ const aaHalfSpan = Math.min(0.18, 0.5 / Math.sqrt(denom));const invTwoAaHalfSpan = 1.0 / (2.0 * aaHalfSpan);let srcIdx = 0;let dstIdx = 0;const zoom = options.zoom ?? 1.0;- const isDownscaled = zoom < 0.95;+ const isDownscaled = antiAliasing && zoom < 0.95;const moireBlend = isDownscaled ? Math.max(0, Math.min(1, (zoom - 0.35) / 0.6)) : 1.0;for (let y = minY; y < maxY; y++) {- const ySinT = y * sinT;- const yCosT = y * cosT;- let xr = minX * cosT - ySinT;- let yr = minX * sinT + yCosT;+ const docY = y + docOriginY;+ const baseXr = -docY * basisB;+ const baseYr = docY * basisA;- for (let x = minX; x < maxX; x++, srcIdx += 4, dstIdx++, xr += cosT, yr += sinT) {+ for (let x = minX; x < maxX; x++, srcIdx += 4, dstIdx++) {// 32-bit fast path: completely transparent pixelif (srcData32[dstIdx] === 0) {dstData32[dstIdx] = TRANSPARENT_U32;continue;}- const a = srcData[srcIdx + 3];- if (a === 0) {+ const alphaByte = srcData[srcIdx + 3];+ if (alphaByte === 0) {dstData32[dstIdx] = TRANSPARENT_U32;continue;}- let oneMinusDensity: number;+ let density: number;+ let isFastSpecFullAlpha = false;if (isSpecified) {- if (a === 255) {+ if (alphaByte === 255) {if (specDensity <= 0.001) {dstData32[dstIdx] = TRANSPARENT_U32;continue;@@ -276,9 +354,10 @@ export function applyScreentoneCPU(dstData32[dstIdx] = SOLID_BLACK_U32;continue;}- oneMinusDensity = specOneMinusDensity;+ density = specDensity;+ isFastSpecFullAlpha = true;} else {- const density = specDensity * (a * INV_255);+ density = specDensity * (alphaByte * INV_255);if (density <= 0.001) {dstData32[dstIdx] = TRANSPARENT_U32;continue;@@ -287,7 +366,6 @@ export function applyScreentoneCPU(dstData32[dstIdx] = SOLID_BLACK_U32;continue;}- oneMinusDensity = 1.0 - density;}} else {const r = srcData[srcIdx];@@ -295,7 +373,7 @@ export function applyScreentoneCPU(const b = srcData[srcIdx + 2];// Perceptual ITU-R BT.601 luminance (0.0 = pure black, 1.0 = pure white)const luminance = (r * 299 + g * 587 + b * 114) * INV_LUMINANCE_255K;- const density = (1.0 - luminance) * (a * INV_255);+ density = (1.0 - luminance) * (alphaByte * INV_255);if (density <= 0.001) {dstData32[dstIdx] = TRANSPARENT_U32;continue;@@ -304,37 +382,56 @@ export function applyScreentoneCPU(dstData32[dstIdx] = SOLID_BLACK_U32;continue;}- oneMinusDensity = 1.0 - density;}- // Normalized cell coordinates in [-0.5, 0.5]- const u = (xr * invCellSize) - Math.floor(xr * invCellSize) - 0.5;- const v = (yr * invCellSize) - Math.floor(yr * invCellSize) - 0.5;-- let spot: number;- if (isLine) {- spot = 1.0 - 2.0 * Math.abs(u);- } else if (isDiamond) {- spot = 1.0 - (Math.abs(u) + Math.abs(v));+ const docX = x + docOriginX;+ const xr = docX * basisA + baseXr;+ const yr = docX * basisB + baseYr;++ // Exact integer modulo -> zero floating-point drift across arbitrary document sizes+ const u = ((((xr % denom) + denom) % denom) * invDenom) - 0.5;+ const v = ((((yr % denom) + denom) % denom) * invDenom) - 0.5;++ if (!antiAliasing) {+ let isInk: boolean;+ if (isLine) {+ const thresh = isFastSpecFullAlpha ? specLineThresh : 1.0 - density;+ isInk = 1.0 - 2.0 * Math.abs(u) >= thresh;+ } else if (isDiamond) {+ const thresh = isFastSpecFullAlpha ? specDiamondThresh : diamondSpotThreshold(density);+ isInk = 1.0 - (Math.abs(u) + Math.abs(v)) >= thresh;+ } else if (isEuclidean) {+ const thresh = isFastSpecFullAlpha ? specEuclidThresh : euclideanSpotThreshold(density);+ const spot = 0.5 + 0.25 * (Math.cos(TWO_PI * u) + Math.cos(TWO_PI * v));+ isInk = spot >= thresh;+ } else {+ const r2 = isFastSpecFullAlpha ? specCircleR2 : (() => {+ const radDot = circleDotRadius(density);+ return radDot * radDot + 1e-7;+ })();+ isInk = u * u + v * v <= r2;+ }+ dstData32[dstIdx] = isInk ? SOLID_BLACK_U32 : TRANSPARENT_U32;} else {- const absU = Math.abs(u);- const absV = Math.abs(v);- if (absU + absV <= 0.5) {- spot = 1.0 - 2.0 * (u * u + v * v);+ let diff: number;+ if (isLine) {+ const thresh = isFastSpecFullAlpha ? specLineThresh : 1.0 - density;+ diff = (1.0 - 2.0 * Math.abs(u)) - thresh;+ } else if (isDiamond) {+ const thresh = isFastSpecFullAlpha ? specDiamondThresh : diamondSpotThreshold(density);+ diff = (1.0 - (Math.abs(u) + Math.abs(v))) - thresh;+ } else if (isEuclidean) {+ const thresh = isFastSpecFullAlpha ? specEuclidThresh : euclideanSpotThreshold(density);+ const spot = 0.5 + 0.25 * (Math.cos(TWO_PI * u) + Math.cos(TWO_PI * v));+ diff = spot - thresh;} else {- const uc = absU - 0.5;- const vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);+ const radDot = isFastSpecFullAlpha ? specCircleR : circleDotRadius(density);+ diff = radDot - Math.sqrt(u * u + v * v);}- }-- const diff = spot - oneMinusDensity;- if (antiAliasing) {let coverage = Math.max(0, Math.min(1, diff * invTwoAaHalfSpan + 0.5));if (isDownscaled) {- const contDensity = 1.0 - oneMinusDensity;- coverage = contDensity * (1.0 - moireBlend) + coverage * moireBlend;+ coverage = density * (1.0 - moireBlend) + coverage * moireBlend;}if (coverage <= 0.0) {dstData32[dstIdx] = TRANSPARENT_U32;@@ -344,8 +441,6 @@ export function applyScreentoneCPU(const alpha = (coverage * 255 + 0.5) | 0;dstData32[dstIdx] = isLittleEndian ? (alpha << 24) : alpha;}- } else {- dstData32[dstIdx] = (diff >= 0.0) ? SOLID_BLACK_U32 : TRANSPARENT_U32;}}}@@ -411,55 +506,67 @@ void main() {return;}- float x = u_regionOrigin.x + v_texCoord.x * u_regionSize.x;- float y = u_regionOrigin.y + v_texCoord.y * u_regionSize.y;+ float px = floor(u_regionOrigin.x + v_texCoord.x * u_regionSize.x);+ float py = floor(u_regionOrigin.y + v_texCoord.y * u_regionSize.y);float cosA = cos(u_angleRad);float sinA = sin(u_angleRad);- float xr = x * cosA - y * sinA;- float yr = x * sinA + y * cosA;+ float safeCell = max(2.0, u_cellSize);+ float a = floor(safeCell * cosA + 0.5);+ float b = floor(safeCell * sinA + 0.5);+ float denom = a * a + b * b;+ if (denom < 4.0) {+ float fb = max(2.0, floor(safeCell + 0.5));+ if (abs(cosA) >= abs(sinA)) {+ a = cosA >= 0.0 ? fb : -fb;+ b = 0.0;+ } else {+ a = 0.0;+ b = sinA >= 0.0 ? fb : -fb;+ }+ denom = a * a + b * b;+ }- float u = fract(xr / u_cellSize) - 0.5;- float v = fract(yr / u_cellSize) - 0.5;+ float xr = px * a - py * b;+ float yr = px * b + py * a;+ float u = (mod(xr, denom) / denom) - 0.5;+ float v = (mod(yr, denom) / denom) - 0.5;- float spot;+ float diff;if (u_dotShape == 2) {- spot = 1.0 - 2.0 * abs(u);+ diff = (1.0 - 2.0 * abs(u)) - (1.0 - density);} else if (u_dotShape == 3) {- spot = 1.0 - (abs(u) + abs(v));+ float dThresh = density <= 0.5 ? (1.0 - sqrt(0.5 * density)) : sqrt(0.5 * (1.0 - density));+ diff = (1.0 - (abs(u) + abs(v))) - dThresh;+ } else if (u_dotShape == 1) {+ float spot = 0.5 + 0.25 * (cos(6.2831853 * u) + cos(6.2831853 * v));+ float eu = density <= 0.5 ? (2.0 * density) : (2.0 * (1.0 - density));+ float eOff = 0.78539816 * eu - 0.28539816 * eu * eu;+ float eThresh = density <= 0.5 ? (1.0 - eOff) : eOff;+ diff = spot - eThresh;} else {- float absU = abs(u);- float absV = abs(v);- if (absU + absV <= 0.5) {- spot = 1.0 - 2.0 * (u * u + v * v);- } else {- float uc = absU - 0.5;- float vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);- }+ float rDot = density <= 0.78539816+ ? sqrt(density * 0.31830989)+ : (0.70710678 - 0.20710678 * pow(max(0.0, (1.0 - density) / 0.21460184), 0.43));+ diff = rDot - length(vec2(u, v));}- float diff = spot - (1.0 - density);vec4 halftoneColor;-if (u_antiAliasing == 1) {- float halfSpan = min(0.25, 0.75 / u_cellSize);+ float halfSpan = min(0.18, 0.5 / sqrt(denom));float coverage = clamp(diff / (2.0 * halfSpan) + 0.5, 0.0, 1.0);halftoneColor = vec4(0.0, 0.0, 0.0, coverage);} else {- if (diff >= 0.0) {- halftoneColor = vec4(0.0, 0.0, 0.0, 1.0);- } else {- halftoneColor = vec4(0.0, 0.0, 0.0, 0.0);- }+ halftoneColor = diff >= -0.000001 ? vec4(0.0, 0.0, 0.0, 1.0) : vec4(0.0, 0.0, 0.0, 0.0);}- // Clip Studio Paint style Anti-Moiré Viewport Downsampling:- // When viewport zoom Z < 1.0, high-frequency dots alias against screen pixels.- // Smoothstep crossfade from discrete dot pattern to continuous grayscale luminance.- float moireBlend = smoothstep(0.35, 0.95, u_zoom);- vec4 contColor = vec4(0.0, 0.0, 0.0, density);- gl_FragColor = mix(contColor, halftoneColor, moireBlend);+ if (u_zoom >= 0.99) {+ gl_FragColor = halftoneColor;+ } else {+ float moireBlend = smoothstep(0.25, 0.85, u_zoom);+ vec4 contColor = vec4(0.0, 0.0, 0.0, density);+ gl_FragColor = mix(contColor, halftoneColor, moireBlend);+ }}`;@@ -668,7 +775,7 @@ class WebGLHalftonePipeline {const dotShapeVal = options.dotShape === 'line' ? 2 : options.dotShape === 'diamond' ? 3 : (options.dotShape === 'euclidean' ? 1 : 0);gl.uniform1i(this.uDotShapeLoc, dotShapeVal);gl.uniform1i(this.uSolidBlackAtMaxLoc, options.solidBlackAtMax !== false ? 1 : 0);- gl.uniform1i(this.uAntiAliasingLoc, options.antiAliasing !== false ? 1 : 0);+ gl.uniform1i(this.uAntiAliasingLoc, options.antiAliasing === true ? 1 : 0);gl.uniform1i(this.uDensityTypeLoc, options.densityType === 'image' ? 1 : 0);gl.uniform1f(this.uSpecifiedDensityLoc, Math.max(0, Math.min(1, options.specifiedDensity ?? 0.4)));if (this.uZoomLoc) {@@ -727,22 +834,14 @@ export function createSeamlessHalftonePattern(const data32 = new Uint32Array(imgData.data.buffer);const solidBlack = isLittleEndian ? 0xff000000 : 0x000000ff;+ const rDot = circleDotRadius(density);+ const r2 = rDot * rDot + 1e-7;for (let cy = 0; cy < cH; cy++) {const v = (cy / cH) - 0.5;for (let cx = 0; cx < cW; cx++) {const u = (cx / cW) - 0.5;- const absU = Math.abs(u);- const absV = Math.abs(v);- let spot: number;- if (absU + absV <= 0.5) {- spot = 1.0 - 2.0 * (u * u + v * v);- } else {- const uc = absU - 0.5;- const vc = absV - 0.5;- spot = 2.0 * (uc * uc + vc * vc);- }const idx = cy * cW + cx;- data32[idx] = spot >= (1.0 - density) ? solidBlack : 0x00000000;+ data32[idx] = (u * u + v * v) <= r2 ? solidBlack : 0x00000000;}}ctx.putImageData(imgData, 0, 0);diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.tsindex 33370a7..8429551 100644--- a/src/utils/selectionUtils.ts+++ b/src/utils/selectionUtils.ts@@ -147,8 +147,23 @@ export function selectionToMask(width: number,height: number): Uint8Array {- if (selection.mask && selection.maskWidth === width && selection.maskHeight === height) {- return new Uint8Array(selection.mask);+ if (selection.mask && selection.maskWidth && selection.maskHeight) {+ if (selection.maskWidth === width && selection.maskHeight === height) {+ return new Uint8Array(selection.mask);+ }+ const resized = new Uint8Array(width * height);+ const mw = selection.maskWidth;+ const mh = selection.maskHeight;+ const copyW = Math.min(mw, width);+ const copyH = Math.min(mh, height);+ for (let y = 0; y < copyH; y++) {+ const sRow = y * mw;+ const dRow = y * width;+ for (let x = 0; x < copyW; x++) {+ resized[dRow + x] = selection.mask[sRow + x];+ }+ }+ return resized;}const mask = new Uint8Array(width * height);@@ -165,23 +180,59 @@ export function selectionToMask(}}} else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {- // Rasterize polygon onto offscreen 2D canvas- const offCanvas = document.createElement('canvas');- offCanvas.width = width;- offCanvas.height = height;- const offCtx = offCanvas.getContext('2d');- if (offCtx) {- offCtx.fillStyle = '#ffffff';- offCtx.beginPath();- offCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);- for (let i = 1; i < selection.polygon.length; i++) {- offCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);- }- offCtx.closePath();- offCtx.fill();- const imgData = offCtx.getImageData(0, 0, width, height);- for (let i = 0; i < width * height; i++) {- mask[i] = imgData.data[i * 4 + 3];+ const b = selection.bounds;+ const x0 = Math.max(0, Math.floor(b.x));+ const y0 = Math.max(0, Math.floor(b.y));+ const x1 = Math.min(width, Math.ceil(b.x + b.width));+ const y1 = Math.min(height, Math.ceil(b.y + b.height));+ if (x1 > x0 && y1 > y0) {+ const offCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ const offCtx = offCanvas ? offCanvas.getContext('2d', { willReadFrequently: true }) : null;+ if (offCanvas && offCtx) {+ const CHUNK = 1024;+ try {+ for (let cy = y0; cy < y1; cy += CHUNK) {+ const ch = Math.min(CHUNK, y1 - cy);+ for (let cx = x0; cx < x1; cx += CHUNK) {+ const cw = Math.min(CHUNK, x1 - cx);+ if (offCanvas.width !== cw) offCanvas.width = cw;+ if (offCanvas.height !== ch) offCanvas.height = ch;+ offCtx.clearRect(0, 0, cw, ch);+ offCtx.save();+ offCtx.translate(-cx, -cy);+ offCtx.fillStyle = '#ffffff';+ offCtx.beginPath();+ offCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);+ for (let i = 1; i < selection.polygon.length; i++) {+ offCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);+ }+ offCtx.closePath();+ offCtx.fill();+ offCtx.restore();+ const imgData = offCtx.getImageData(0, 0, cw, ch);+ for (let ly = 0; ly < ch; ly++) {+ const dRow = (cy + ly) * width + cx;+ const sRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ mask[dRow + lx] = imgData.data[sRow + lx * 4 + 3];+ }+ }+ }+ }+ } finally {+ releaseTemporaryCanvas(offCanvas);+ }+ } else {+ const poly = selection.polygon;+ for (let y = y0; y < y1; y++) {+ const row = y * width;+ const py = y + 0.5;+ for (let x = x0; x < x1; x++) {+ if (isPointInPolygon(x + 0.5, py, poly)) {+ mask[row + x] = 255;+ }+ }+ }}}}@@ -1317,22 +1368,40 @@ export function fillSelectionInTileGrid(params: {}}}- } else if (polyCanvas && pCtx && selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {- if (polyCanvas.width !== cw) polyCanvas.width = cw;- if (polyCanvas.height !== ch) polyCanvas.height = ch;- pCtx.clearRect(0, 0, cw, ch);- pCtx.save();- pCtx.translate(-cx, -cy);- pCtx.fillStyle = colorCss;- pCtx.beginPath();- pCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);- for (let i = 1; i < selection.polygon.length; i++) {- pCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {+ if (polyCanvas && pCtx) {+ if (polyCanvas.width !== cw) polyCanvas.width = cw;+ if (polyCanvas.height !== ch) polyCanvas.height = ch;+ pCtx.clearRect(0, 0, cw, ch);+ pCtx.save();+ pCtx.translate(-cx, -cy);+ pCtx.fillStyle = colorCss;+ pCtx.beginPath();+ pCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);+ for (let i = 1; i < selection.polygon.length; i++) {+ pCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);+ }+ pCtx.closePath();+ pCtx.fill();+ pCtx.restore();+ chunkData = pCtx.getImageData(0, 0, cw, ch).data;+ } else {+ chunkData = new Uint8ClampedArray(cw * ch * 4);+ 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;+ chunkData[off] = r;+ chunkData[off + 1] = g;+ chunkData[off + 2] = b;+ chunkData[off + 3] = a;+ }+ }+ }}- pCtx.closePath();- pCtx.fill();- pCtx.restore();- chunkData = pCtx.getImageData(0, 0, cw, ch).data;} else {// Solid rect fillchunkData = new Uint8ClampedArray(cw * ch * 4);diff --git a/src/utils/shortcutManager.ts b/src/utils/shortcutManager.tsindex d6ff277..9a534b0 100644--- a/src/utils/shortcutManager.ts+++ b/src/utils/shortcutManager.ts@@ -202,6 +202,15 @@ export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [toolId: 'vector-edit',springLoaded: true,},+ {+ id: 'tool.3d',+ label: '3D Object & Camera Tool',+ description: 'Manipulate 3D models, lighting, camera, and poses on the canvas',+ category: 'Tools',+ defaultShortcut: 'K',+ toolId: '3d',+ springLoaded: false,+ },{id: 'tool.brushSizeDown',label: 'Decrease Brush Size',diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.tsindex 717184d..e439925 100644--- a/src/utils/tileEngine.ts+++ b/src/utils/tileEngine.ts@@ -258,7 +258,27 @@ export class SparseTileGrid {this.memoryManager?.notifyTileFreed(tile);this.tiles.delete(key);if (lod === 0) {- this.markLodAncestorsDirty(layerId, tileX, tileY);+ let ax = tileX;+ let ay = tileY;+ for (let ancestorLod = 1; ancestorLod <= 3; ancestorLod++) {+ ax = ax >> 1;+ ay = ay >> 1;+ const ancestorKey = getTileKey(layerId, ax, ay, ancestorLod);+ if (!this.hasPopulatedLodTile(layerId, ax, ay, ancestorLod)) {+ const stale = this.tiles.get(ancestorKey);+ if (stale) {+ this.memoryManager?.notifyTileFreed(stale);+ this.tiles.delete(ancestorKey);+ }+ this.dirtyLodTiles.delete(ancestorKey);+ } else {+ this.dirtyLodTiles.add(ancestorKey);+ const existing = this.tiles.get(ancestorKey);+ if (existing) {+ existing.dirty = true;+ }+ }+ }this.bumpLayerVersion(layerId);}}diff --git a/src/utils/tileEngine/mipmap.ts b/src/utils/tileEngine/mipmap.tsindex 6aece8c..aae632f 100644--- a/src/utils/tileEngine/mipmap.ts+++ b/src/utils/tileEngine/mipmap.ts@@ -267,7 +267,10 @@ export function getOrBuildLodTiles(const occ = host.layerLodOccupancy.get(layerId);const lodOccMap = occ ? occ[lod - 1] : null;if (!lodOccMap || lodOccMap.size === 0) {- return host.getLayerTiles(layerId, lod);+ // Only return manually-populated clean LOD tiles (never stale dirty LOD tiles left behind after deletes)+ return host+ .getLayerTiles(layerId, lod)+ .filter((t) => !isLodTileDirty(host, layerId, t.tileX, t.tileY, lod));}const result: TileBuffer[] = [];diff --git a/src/utils/tileEngine/tileFill.ts b/src/utils/tileEngine/tileFill.tsindex 9cdd70e..c4f69b5 100644--- a/src/utils/tileEngine/tileFill.ts+++ b/src/utils/tileEngine/tileFill.ts@@ -47,11 +47,22 @@ export function fillLayerSolidColor(g = parseInt(hex.slice(2, 4), 16) || 0;b = parseInt(hex.slice(4, 6), 16) || 0;if (hex.length === 8) {- a = parseInt(hex.slice(6, 8), 16) || 255;+ const parsedA = parseInt(hex.slice(6, 8), 16);+ a = Number.isNaN(parsedA) ? 255 : parsedA;}}} else if (lower === 'black') {r = 0; g = 0; b = 0;+ } else {+ const rgbaMatch = lower.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)$/);+ if (rgbaMatch) {+ r = Math.max(0, Math.min(255, parseInt(rgbaMatch[1], 10)));+ g = Math.max(0, Math.min(255, parseInt(rgbaMatch[2], 10)));+ b = Math.max(0, Math.min(255, parseInt(rgbaMatch[3], 10)));+ a = rgbaMatch[4] !== undefined+ ? Math.max(0, Math.min(255, Math.round(parseFloat(rgbaMatch[4]) * 255)))+ : 255;+ }}host.clearLayer(layerId);diff --git a/src/utils/tileEngine/tileOps.ts b/src/utils/tileEngine/tileOps.tsindex cfd85a9..18a95ba 100644--- a/src/utils/tileEngine/tileOps.ts+++ b/src/utils/tileEngine/tileOps.ts@@ -518,8 +518,24 @@ export function mergeLayersInGrid(const srcTiles = host.getLayerTiles(srcLayerId, 0);const dstFormat = options.dstFormat ?? host.getLayerFormat(dstLayerId);- if (typeof document === 'undefined') {- // Headless fallback: straight alpha-over per tile+ const srcTileCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ if (srcTileCanvas) {+ srcTileCanvas.width = TILE_SIZE;+ srcTileCanvas.height = TILE_SIZE;+ }+ const sCtx = srcTileCanvas ? srcTileCanvas.getContext('2d', { willReadFrequently: true }) : null;++ const dstTileCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ if (dstTileCanvas) {+ dstTileCanvas.width = TILE_SIZE;+ dstTileCanvas.height = TILE_SIZE;+ }+ const dCtx = dstTileCanvas ? dstTileCanvas.getContext('2d', { willReadFrequently: true }) : null;++ if (!sCtx || !dCtx || !srcTileCanvas || !dstTileCanvas) {+ if (srcTileCanvas) releaseTemporaryCanvas(srcTileCanvas);+ if (dstTileCanvas) releaseTemporaryCanvas(dstTileCanvas);+ // Headless / no-2D-context fallback: straight alpha-over per tilefor (const srcTile of srcTiles) {if (!srcTile.data) continue;const srcRgba = new Uint8ClampedArray(host.getTileAsRGBA(srcTile));@@ -551,22 +567,11 @@ export function mergeLayersInGrid(return;}- const srcTileCanvas = document.createElement('canvas');- srcTileCanvas.width = TILE_SIZE;- srcTileCanvas.height = TILE_SIZE;- const sCtx = srcTileCanvas.getContext('2d', { willReadFrequently: true });-- const dstTileCanvas = document.createElement('canvas');- dstTileCanvas.width = TILE_SIZE;- dstTileCanvas.height = TILE_SIZE;- const dCtx = dstTileCanvas.getContext('2d', { willReadFrequently: true });-const hasMask = Boolean(maskCanvas && maskEnabled !== false);const maskCtx = hasMask && maskCanvas ? maskCanvas.getContext('2d', { willReadFrequently: true }) : null;const compositeOp = getCanvasCompositeOperation(blendMode);try {- if (!sCtx || !dCtx) return;for (const srcTile of srcTiles) {if (!srcTile.data) continue;diff --git a/src/utils/tonalEngine.ts b/src/utils/tonalEngine.tsindex b087c04..17ed1c4 100644--- a/src/utils/tonalEngine.ts+++ b/src/utils/tonalEngine.ts@@ -61,6 +61,20 @@ export interface ProcessingBounds {y1: number;}+function pointInPolygonLocal(px: number, py: number, polygon: Array<{ x: number; y: number }>): boolean {+ if (polygon.length < 3) return false;+ let inside = false;+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {+ const xi = polygon[i].x;+ const yi = polygon[i].y;+ const xj = polygon[j].x;+ const yj = polygon[j].y;+ const intersect = yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi;+ if (intersect) inside = !inside;+ }+ return inside;+}+/*** Creates an ultra-fast 1-byte lookup mask for active selection.* Returns null if no selection is active (meaning full canvas is processed).@@ -70,13 +84,27 @@ export function createSelectionMask(width: number,height: number): Uint8Array | null {- if (!selection) return null;+ if (!selection || width <= 0 || height <= 0) return null;- if (selection.mask && selection.maskWidth === width && selection.maskHeight === height) {+ if (selection.mask && selection.maskWidth && selection.maskHeight) {const mask = new Uint8Array(width * height);const src = selection.mask;- for (let i = 0; i < src.length; i++) {- if (src[i] >= 64) mask[i] = 1;+ const mw = selection.maskWidth;+ const mh = selection.maskHeight;+ if (mw === width && mh === height) {+ for (let i = 0; i < src.length; i++) {+ if (src[i] >= 64) mask[i] = 1;+ }+ return mask;+ }+ const copyW = Math.min(mw, width);+ const copyH = Math.min(mh, height);+ for (let y = 0; y < copyH; y++) {+ const sRow = y * mw;+ const dRow = y * width;+ for (let x = 0; x < copyW; x++) {+ if (src[sRow + x] >= 64) mask[dRow + x] = 1;+ }}return mask;}@@ -98,27 +126,67 @@ export function createSelectionMask(}if (type === 'lasso' && polygon && polygon.length >= 3) {- const offCanvas = document.createElement('canvas');- offCanvas.width = width;- offCanvas.height = height;- const ctx = offCanvas.getContext('2d', { willReadFrequently: true });- if (!ctx) return null;-- ctx.beginPath();- ctx.moveTo(polygon[0].x, polygon[0].y);- for (let i = 1; i < polygon.length; i++) {- ctx.lineTo(polygon[i].x, polygon[i].y);+ // Rasterize strictly within clamped selection bounds (avoids huge full-doc allocations on 600 DPI canvases)+ const x0 = Math.max(0, Math.floor(bounds.x));+ const y0 = Math.max(0, Math.floor(bounds.y));+ const x1 = Math.min(width, Math.ceil(bounds.x + bounds.width));+ const y1 = Math.min(height, Math.ceil(bounds.y + bounds.height));+ const bw = x1 - x0;+ const bh = y1 - y0;+ if (bw <= 0 || bh <= 0) return mask;++ const offCanvas = typeof document !== 'undefined' ? document.createElement('canvas') : null;+ const ctx = offCanvas ? offCanvas.getContext('2d', { willReadFrequently: true }) : null;+ if (offCanvas && ctx) {+ const CHUNK = 1024;+ try {+ for (let cy = y0; cy < y1; cy += CHUNK) {+ const ch = Math.min(CHUNK, y1 - cy);+ for (let cx = x0; cx < x1; cx += CHUNK) {+ const cw = Math.min(CHUNK, x1 - cx);+ if (offCanvas.width !== cw) offCanvas.width = cw;+ if (offCanvas.height !== ch) offCanvas.height = ch;+ ctx.clearRect(0, 0, cw, ch);+ ctx.save();+ ctx.translate(-cx, -cy);+ ctx.beginPath();+ ctx.moveTo(polygon[0].x, polygon[0].y);+ for (let i = 1; i < polygon.length; i++) {+ ctx.lineTo(polygon[i].x, polygon[i].y);+ }+ ctx.closePath();+ ctx.fillStyle = '#ffffff';+ ctx.fill();+ ctx.restore();++ const imgData = ctx.getImageData(0, 0, cw, ch);+ const d = imgData.data;+ for (let ly = 0; ly < ch; ly++) {+ const dstRow = (cy + ly) * width + cx;+ const srcRow = ly * cw * 4;+ for (let lx = 0; lx < cw; lx++) {+ if (d[srcRow + lx * 4 + 3] > 64) {+ mask[dstRow + lx] = 1;+ }+ }+ }+ }+ }+ } finally {+ offCanvas.width = 0;+ offCanvas.height = 0;+ }+ return mask;}- ctx.closePath();- ctx.fillStyle = '#ffffff';- ctx.fill();-- const imgData = ctx.getImageData(0, 0, width, height);- const d = imgData.data;- const totalPixels = width * height;- for (let i = 0; i < totalPixels; i++) {- if (d[i * 4 + 3] > 64) {- mask[i] = 1;++ // Pure-math fallback when 2D canvas context is unavailable+ for (let y = y0; y < y1; y++) {+ const rowOffset = y * width;+ const py = y + 0.5;+ for (let x = x0; x < x1; x++) {+ if (pointInPolygonLocal(x + 0.5, py, polygon)) {+ mask[rowOffset + x] = 1;+ }}}return mask;diff --git a/src/utils/tool3DRules.ts b/src/utils/tool3DRules.tsnew file mode 100644index 0000000..b1f72ff--- /dev/null+++ b/src/utils/tool3DRules.ts@@ -0,0 +1,475 @@+import { ToolType } from '../types/editor';++export type Tool3DMode =+ | 'smart'+ | 'model-rotate'+ | 'model-rotate-yaw'+ | 'model-rotate-roll'+ | 'model-move'+ | 'model-plane-move'+ | 'model-scale'+ | 'camera-orbit'+ | 'camera-pan'+ | 'camera-zoom';++export type Gizmo3DMode = 'rotate' | 'translate' | 'scale' | 'none';+export type Gizmo3DSpace = 'local' | 'world';+export type Shading3DMode = 'shaded' | 'smooth' | 'toon' | 'wireframe' | 'silhouette';+export type Camera3DPreset = 'front' | 'threeQuarter' | 'side' | 'back' | 'top' | 'lowAngle';++export type Resolved3DPointerAction =+ | 'pass-through-2d'+ | 'gizmo-drag'+ | 'ik-select'+ | 'camera-orbit'+ | 'camera-pan'+ | 'camera-zoom'+ | 'model-rotate'+ | 'model-rotate-yaw'+ | 'model-rotate-roll'+ | 'model-move'+ | 'model-plane-move'+ | 'model-scale';++export interface Pointer3DResolutionInput {+ activeTool: ToolType;+ isSpaceDown: boolean;+ isReferenceVisible: boolean;+ button: number; // 0 = left, 1 = middle, 2 = right+ altKey: boolean;+ shiftKey?: boolean;+ ctrlKey?: boolean;+ metaKey?: boolean;+ activeMode: Tool3DMode;+ gizmoMode: Gizmo3DMode;+ isGizmoHit: boolean;+ isIKHandleHit: boolean;+ isModelHit: boolean;+ hasModel: boolean;+}++export interface Wheel3DResolutionInput {+ activeTool: ToolType;+ isSpaceDown: boolean;+ isReferenceVisible: boolean;+ ctrlKey: boolean;+ metaKey: boolean;+}++export interface Behavior3DRuleDoc {+ gesture: string;+ action: string;+}++/**+ * Canonical user-facing behavior rules for the 3D Tool (Clip Studio Paint Advanced 3D style).+ */+export const TOOL_3D_BEHAVIOR_RULES: readonly Behavior3DRuleDoc[] = [+ { gesture: 'Left-Drag Model / Gizmo', action: 'Rotate, Move, or Scale object' },+ { gesture: 'Left-Drag Background', action: 'Orbit 3D camera (Smart mode)' },+ { gesture: 'Right-Drag or Wheel', action: 'Zoom 3D camera in / out' },+ { gesture: 'Middle-Drag', action: 'Pan 3D camera' },+ { gesture: 'Alt + Left-Drag', action: 'Orbit camera from any mode' },+ { gesture: 'Hold Shift', action: 'Snap rotation (15°), scale (10%), or move' },+ { gesture: 'Ctrl+Z / Ctrl+Y', action: 'Undo / Redo any 3D manipulation' },+ { gesture: 'Click Joint Sphere', action: 'Select & pose IK limb directly' },+ { gesture: 'Space + Drag / Ctrl+Wheel', action: 'Pan / zoom the 2D canvas' },+ { gesture: 'Switch to Brush (B)', action: 'Draw directly over live 3D reference' },+];++/**+ * Deterministic pointer-down routing rule table for the 3D viewport.+ *+ * Priority order:+ * 1. If 3D reference is hidden, active tool is not '3d', or Space is held -> pass through to 2D canvas.+ * 2. Active 3D Transform Gizmo handle hit -> 'gizmo-drag' (never moves camera).+ * 3. Middle mouse button -> 'camera-pan'.+ * 4. Right mouse button -> 'camera-zoom'.+ * 5. Alt + Left button -> 'camera-orbit' (quick inspect from any sub-mode).+ * 6. Left button on an IK handle sphere -> 'ik-select'.+ * 7. Left button in 'smart' mode:+ * - On model -> maps from gizmoMode ('translate' -> model-move, 'scale' -> model-scale, else model-rotate).+ * - On empty space -> 'camera-orbit'.+ * 8. Left button in an explicit mode -> executes that mode (falling back to camera-orbit if no model is loaded for model-* modes).+ */+export function resolve3DPointerAction(input: Pointer3DResolutionInput): Resolved3DPointerAction {+ if (!input.isReferenceVisible || input.activeTool !== '3d' || input.isSpaceDown) {+ return 'pass-through-2d';+ }++ if (input.button === 0 && input.isGizmoHit && !input.altKey) {+ return 'gizmo-drag';+ }++ if (input.button === 1) {+ return 'camera-pan';+ }++ if (input.button === 2) {+ return 'camera-zoom';+ }++ if (input.button !== 0) {+ return 'pass-through-2d';+ }++ if (input.altKey) {+ return 'camera-orbit';+ }++ if (input.isIKHandleHit) {+ return 'ik-select';+ }++ if (input.activeMode === 'smart') {+ if (input.hasModel && input.isModelHit) {+ if (input.gizmoMode === 'translate') return 'model-move';+ if (input.gizmoMode === 'scale') return 'model-scale';+ return 'model-rotate';+ }+ return 'camera-orbit';+ }++ if (input.activeMode.startsWith('model-') && !input.hasModel) {+ return 'camera-orbit';+ }++ return input.activeMode;+}++/**+ * Deterministic mouse wheel routing for 3D viewport.+ * - Ctrl/Meta + Wheel or Space held or non-3D tool -> 2D canvas zoom.+ * - Unmodified Wheel while 3D tool is active -> 3D camera dolly zoom.+ */+export function resolve3DWheelAction(+ input: Wheel3DResolutionInput+): 'camera-zoom' | 'pass-through-2d' {+ if (+ !input.isReferenceVisible ||+ input.activeTool !== '3d' ||+ input.isSpaceDown ||+ input.ctrlKey ||+ input.metaKey+ ) {+ return 'pass-through-2d';+ }+ return 'camera-zoom';+}++/**+ * Converts a screen-space pointer delta (dx, dy) into the artboard's unrotated, unflipped+ * coordinate frame so dragging right on screen always rotates/moves visually right,+ * even when the 2D canvas is rotated or mirrored.+ */+export function mapScreenDeltaToCanvasDelta(+ dx: number,+ dy: number,+ canvasRotationDeg: number,+ flipX: boolean,+ flipY: boolean+): { dx: number; dy: number } {+ const rad = (-canvasRotationDeg * Math.PI) / 180;+ const cos = Math.cos(rad);+ const sin = Math.sin(rad);+ const rx = dx * cos - dy * sin;+ const ry = dx * sin + dy * cos;+ return {+ dx: flipX ? -rx : rx,+ dy: flipY ? -ry : ry,+ };+}++/**+ * Snaps an angle in degrees to the nearest step (default 15°).+ */+export function snapAngleDeg(angleDeg: number, stepDeg = 15): number {+ if (!Number.isFinite(angleDeg) || stepDeg <= 0) return angleDeg;+ return Math.round(angleDeg / stepDeg) * stepDeg;+}++/**+ * Snaps a scale factor to the nearest step (default 0.1 = 10%), clamped to [min, max].+ */+export function snapScaleFactor(scale: number, step = 0.1, min = 0.05, max = 10): number {+ const safe = Number.isFinite(scale) ? scale : 1;+ if (step <= 0) return Math.max(min, Math.min(max, safe));+ const snapped = Math.round(safe / step) * step;+ return Math.max(min, Math.min(max, snapped));+}++/**+ * Snaps a world position coordinate to the nearest grid step (default 0.1).+ */+export function snapPositionCoord(value: number, step = 0.1): number {+ if (!Number.isFinite(value) || step <= 0) return value;+ return Math.round(value / step) * step;+}++/**+ * Shared single-source-of-truth conversion from spherical light angles to a 3D unit vector+ * or world-space position. Used identically by LightSourceWidget and Local3DContainer so the+ * shaded sphere UI always matches the 3D scene lighting.+ */+export function sphericalLightToVector(+ azimuthDeg: number,+ elevationDeg: number,+ isBacklit: boolean,+ distance = 1+): { x: number; y: number; z: number } {+ const az = (azimuthDeg * Math.PI) / 180;+ const el = (elevationDeg * Math.PI) / 180;+ const y = Math.sin(el);+ const hyp = Math.cos(el);+ const x = hyp * Math.sin(az);+ let z = hyp * Math.cos(az);+ if (isBacklit) {+ z = -Math.abs(z);+ }+ const len = Math.hypot(x, y, z) || 1;+ return {+ x: (x / len) * distance,+ y: (y / len) * distance,+ z: (z / len) * distance,+ };+}++export interface KeyLight3DSettings {+ enabled: boolean;+ azimuth: number; // 0..360 deg+ elevation: number; // -85..85 deg+ intensity: number; // 0..3+ color: string;+ isBacklit: boolean;+}++export interface RimLight3DSettings {+ enabled: boolean;+ azimuth: number; // 0..360 deg+ elevation: number; // -85..85 deg+ intensity: number; // 0..3+ color: string;+}++export interface Scene3DLightingSettings {+ keyLight: KeyLight3DSettings;+ rimLight: RimLight3DSettings;+ ambientIntensity: number; // 0..1.5+ ambientColor: string;+ castGroundShadow: boolean;+ shadowOpacity: number; // 0.05..0.85+}++export const DEFAULT_3D_LIGHTING: Scene3DLightingSettings = {+ keyLight: {+ enabled: true,+ azimuth: 40,+ elevation: 45,+ intensity: 1.4,+ color: '#ffffff',+ isBacklit: false,+ },+ rimLight: {+ enabled: true,+ azimuth: 225,+ elevation: 25,+ intensity: 0.55,+ color: '#93c5fd',+ },+ ambientIntensity: 0.55,+ ambientColor: '#ffffff',+ castGroundShadow: true,+ shadowOpacity: 0.32,+};++export interface BonePoseSnapshot {+ q: [number, number, number, number];+ p?: [number, number, number];+}++export interface Scene3DSnapshot {+ modelPosition: [number, number, number];+ modelQuaternion: [number, number, number, number];+ modelScale: [number, number, number];+ cameraPosition: [number, number, number];+ cameraTarget: [number, number, number];+ cameraFov: number;+ perspective: number;+ lighting: Scene3DLightingSettings;+ shadingMode: Shading3DMode;+ materialRoughness: number;+ toonOutline: boolean;+ opacity: number;+ showGrid: boolean;+ bones?: Record<string, BonePoseSnapshot>;+}++function cloneSnapshot(s: Scene3DSnapshot): Scene3DSnapshot {+ const bonesCopy: Record<string, BonePoseSnapshot> | undefined = s.bones+ ? Object.fromEntries(+ Object.entries(s.bones).map(([k, v]) => [+ k,+ {+ q: [...v.q] as [number, number, number, number],+ ...(v.p ? { p: [...v.p] as [number, number, number] } : {}),+ },+ ])+ )+ : undefined;++ return {+ modelPosition: [...s.modelPosition],+ modelQuaternion: [...s.modelQuaternion],+ modelScale: [...s.modelScale],+ cameraPosition: [...s.cameraPosition],+ cameraTarget: [...s.cameraTarget],+ cameraFov: s.cameraFov,+ perspective: s.perspective,+ lighting: {+ keyLight: { ...s.lighting.keyLight },+ rimLight: { ...s.lighting.rimLight },+ ambientIntensity: s.lighting.ambientIntensity,+ ambientColor: s.lighting.ambientColor,+ castGroundShadow: s.lighting.castGroundShadow,+ shadowOpacity: s.lighting.shadowOpacity,+ },+ shadingMode: s.shadingMode,+ materialRoughness: s.materialRoughness,+ toonOutline: s.toonOutline,+ opacity: s.opacity,+ showGrid: s.showGrid,+ ...(bonesCopy ? { bones: bonesCopy } : {}),+ };+}++function approxArrEqual(a: readonly number[], b: readonly number[], eps = 1e-4): boolean {+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ if (Math.abs(a[i] - b[i]) > eps) return false;+ }+ return true;+}++export function areScene3DSnapshotsEqual(a: Scene3DSnapshot, b: Scene3DSnapshot): boolean {+ if (+ !approxArrEqual(a.modelPosition, b.modelPosition) ||+ !approxArrEqual(a.modelQuaternion, b.modelQuaternion) ||+ !approxArrEqual(a.modelScale, b.modelScale) ||+ !approxArrEqual(a.cameraPosition, b.cameraPosition) ||+ !approxArrEqual(a.cameraTarget, b.cameraTarget) ||+ Math.abs(a.cameraFov - b.cameraFov) > 1e-3 ||+ Math.abs(a.perspective - b.perspective) > 1e-3 ||+ a.shadingMode !== b.shadingMode ||+ Math.abs(a.materialRoughness - b.materialRoughness) > 1e-3 ||+ a.toonOutline !== b.toonOutline ||+ Math.abs(a.opacity - b.opacity) > 1e-3 ||+ a.showGrid !== b.showGrid+ ) {+ return false;+ }++ const la = a.lighting;+ const lb = b.lighting;+ if (+ la.keyLight.enabled !== lb.keyLight.enabled ||+ la.keyLight.azimuth !== lb.keyLight.azimuth ||+ la.keyLight.elevation !== lb.keyLight.elevation ||+ Math.abs(la.keyLight.intensity - lb.keyLight.intensity) > 1e-3 ||+ la.keyLight.color.toLowerCase() !== lb.keyLight.color.toLowerCase() ||+ la.keyLight.isBacklit !== lb.keyLight.isBacklit ||+ la.rimLight.enabled !== lb.rimLight.enabled ||+ la.rimLight.azimuth !== lb.rimLight.azimuth ||+ la.rimLight.elevation !== lb.rimLight.elevation ||+ Math.abs(la.rimLight.intensity - lb.rimLight.intensity) > 1e-3 ||+ la.rimLight.color.toLowerCase() !== lb.rimLight.color.toLowerCase() ||+ Math.abs(la.ambientIntensity - lb.ambientIntensity) > 1e-3 ||+ la.ambientColor.toLowerCase() !== lb.ambientColor.toLowerCase() ||+ la.castGroundShadow !== lb.castGroundShadow ||+ Math.abs(la.shadowOpacity - lb.shadowOpacity) > 1e-3+ ) {+ return false;+ }++ const aKeys = a.bones ? Object.keys(a.bones) : [];+ const bKeys = b.bones ? Object.keys(b.bones) : [];+ if (aKeys.length !== bKeys.length) return false;+ if (a.bones && b.bones) {+ for (const key of aKeys) {+ const ba = a.bones[key];+ const bb = b.bones[key];+ if (!bb) return false;+ if (!approxArrEqual(ba.q, bb.q)) return false;+ if (ba.p && bb.p && !approxArrEqual(ba.p, bb.p)) return false;+ if (Boolean(ba.p) !== Boolean(bb.p)) return false;+ }+ }++ return true;+}++/**+ * Bounded linear Undo / Redo snapshot stack for all 3D scene manipulations+ * (transform, camera, lighting, shading, and mannequin IK/pose).+ */+export class Scene3DHistoryStack {+ private entries: Scene3DSnapshot[] = [];+ private index = -1;+ private readonly maxEntries: number;++ constructor(maxEntries = 60) {+ this.maxEntries = Math.max(2, maxEntries);+ }++ reset(initialSnapshot: Scene3DSnapshot): void {+ this.entries = [cloneSnapshot(initialSnapshot)];+ this.index = 0;+ }++ clear(): void {+ this.entries = [];+ this.index = -1;+ }++ push(snapshot: Scene3DSnapshot): boolean {+ if (this.index >= 0 && areScene3DSnapshotsEqual(this.entries[this.index], snapshot)) {+ return false;+ }+ if (this.index < this.entries.length - 1) {+ this.entries = this.entries.slice(0, this.index + 1);+ }+ this.entries.push(cloneSnapshot(snapshot));+ if (this.entries.length > this.maxEntries) {+ this.entries.shift();+ }+ this.index = this.entries.length - 1;+ return true;+ }++ canUndo(): boolean {+ return this.index > 0;+ }++ canRedo(): boolean {+ return this.index >= 0 && this.index < this.entries.length - 1;+ }++ undo(): Scene3DSnapshot | null {+ if (!this.canUndo()) return null;+ this.index -= 1;+ return cloneSnapshot(this.entries[this.index]);+ }++ redo(): Scene3DSnapshot | null {+ if (!this.canRedo()) return null;+ this.index += 1;+ return cloneSnapshot(this.entries[this.index]);+ }++ get length(): number {+ return this.entries.length;+ }++ get currentIndex(): number {+ return this.index;+ }+}diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.tsindex 1d585a9..13cd883 100644--- a/src/utils/transformEngine.ts+++ b/src/utils/transformEngine.ts@@ -1,4 +1,4 @@-import { Point2D } from '../types/editor';+import { LayerItem, Point2D, isFolderLikeLayer } from '../types/editor';/*** Computes the 3x3 projective transformation (homography) parameters@@ -951,3 +951,157 @@ export function getMeshSurfaceBounds(height: Math.max(1, maxYC - minYF),};}++export interface ResolveTransformTargetsResult {+ targetLayers: LayerItem[];+ includesFolder: boolean;+ blockedReason?: 'locked' | 'unsupported' | 'empty-folder';+}++export function isLayerOrAncestorLocked(+ layer: LayerItem,+ layerMap: Map<string, LayerItem>+): boolean {+ let curr: LayerItem | undefined = layer;+ const visited = new Set<string>();+ while (curr && !visited.has(curr.id)) {+ if (curr.locked) return true;+ visited.add(curr.id);+ curr = curr.parentId ? layerMap.get(curr.parentId) : undefined;+ }+ return false;+}++function isDescendantOfAnyFolder(+ layer: LayerItem,+ folderIds: Set<string>,+ layerMap: Map<string, LayerItem>+): boolean {+ let parentId = layer.parentId;+ const visited = new Set<string>();+ while (parentId && !visited.has(parentId)) {+ if (folderIds.has(parentId)) return true;+ visited.add(parentId);+ parentId = layerMap.get(parentId)?.parentId ?? null;+ }+ return false;+}++/**+ * Resolves all unlocked raster layers targeted by a Free Transform operation.+ * Selecting a folder (or frame-folder) recursively includes all unlocked raster layers+ * within that folder (including nested subfolders). Multi-selection expands any selected+ * folders alongside directly selected raster layers in stack order without duplicates.+ */+export function resolveTransformTargetLayers(+ layers: LayerItem[],+ activeLayer: LayerItem | undefined,+ selectedLayerIds: string[]+): ResolveTransformTargetsResult {+ const layerMap = new Map<string, LayerItem>();+ for (const l of layers) {+ layerMap.set(l.id, l);+ }++ const effectiveSelectedIds =+ selectedLayerIds && selectedLayerIds.length > 0+ ? selectedLayerIds+ : activeLayer+ ? [activeLayer.id]+ : [];++ const selectedItems = effectiveSelectedIds+ .map((id) => layerMap.get(id))+ .filter((l): l is LayerItem => Boolean(l));++ if (selectedItems.length === 0) {+ return { targetLayers: [], includesFolder: false, blockedReason: 'unsupported' };+ }++ if (selectedItems.length === 1) {+ const single = selectedItems[0];+ if (isFolderLikeLayer(single)) {+ if (isLayerOrAncestorLocked(single, layerMap)) {+ return { targetLayers: [], includesFolder: true, blockedReason: 'locked' };+ }+ const folderSet = new Set([single.id]);+ const targets = layers.filter(+ (l) =>+ l.type === 'raster' &&+ !isLayerOrAncestorLocked(l, layerMap) &&+ isDescendantOfAnyFolder(l, folderSet, layerMap)+ );+ if (targets.length === 0) {+ return { targetLayers: [], includesFolder: true, blockedReason: 'empty-folder' };+ }+ return { targetLayers: targets, includesFolder: true };+ }++ if (single.type !== 'raster') {+ return { targetLayers: [], includesFolder: false, blockedReason: 'unsupported' };+ }+ if (isLayerOrAncestorLocked(single, layerMap)) {+ return { targetLayers: [], includesFolder: false, blockedReason: 'locked' };+ }+ return { targetLayers: [single], includesFolder: false };+ }++ const selectedIdSet = new Set(selectedItems.map((l) => l.id));+ const includesFolder = selectedItems.some((l) => isFolderLikeLayer(l));+ const selectedUnlockedFolders = new Set(+ selectedItems+ .filter((l) => isFolderLikeLayer(l) && !isLayerOrAncestorLocked(l, layerMap))+ .map((l) => l.id)+ );++ const targetLayers = layers.filter(+ (l) =>+ l.type === 'raster' &&+ !isLayerOrAncestorLocked(l, layerMap) &&+ (selectedIdSet.has(l.id) ||+ (selectedUnlockedFolders.size > 0 &&+ isDescendantOfAnyFolder(l, selectedUnlockedFolders, layerMap)))+ );++ if (targetLayers.length === 0) {+ const allLocked = selectedItems.every((l) => isLayerOrAncestorLocked(l, layerMap));+ return {+ targetLayers: [],+ includesFolder,+ blockedReason: allLocked ? 'locked' : includesFolder ? 'empty-folder' : 'unsupported',+ };+ }++ return { targetLayers, includesFolder };+}++/**+ * Computes preview visibility and effective opacity for a target layer during a+ * folder / multi-layer transform preview.+ */+export function getTransformPreviewLayerState(+ layer: LayerItem,+ layerMap: Map<string, LayerItem>,+ selectedRootIds: Set<string>+): { visible: boolean; opacity: number } {+ let visible = layer.visible;+ let opacity = layer.opacity;+ let currParentId = layer.parentId;+ const visited = new Set<string>([layer.id]);++ while (currParentId && !visited.has(currParentId)) {+ visited.add(currParentId);+ const parent = layerMap.get(currParentId);+ if (!parent) break;+ opacity *= parent.opacity;+ if (!selectedRootIds.has(parent.id) && !parent.visible) {+ visible = false;+ }+ currParentId = parent.parentId;+ }++ return {+ visible,+ opacity: Math.max(0, Math.min(1, opacity)),+ };+}