Skip to content

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

rendering optimization

sora3adb6dc3c8c1
diff --git a/src/App.tsx b/src/App.tsx
index 3054b7c..929d063 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -85,6 +85,7 @@ import { HostModal } from './components/HostModal';
import { ClipboardInviteToast } from './components/ClipboardInviteToast';
import { WebLandingModal } from './components/WebLandingModal';
import { WelcomeScreen } from './components/WelcomeScreen';
+import { ModernPropertyBar } from './components/ModernPropertyBar';
import { FirstTimeNameModal } from './components/FirstTimeNameModal';
import { AdjustmentModal } from './components/AdjustmentModal';
import { LayerStylesModal } from './components/LayerStylesModal';
@@ -390,6 +391,7 @@ export function App() {
const [documents, setDocuments] = useState<DocumentTab[]>([]);
const [activeDocumentId, setActiveDocumentId] = useState<string | null>(null);
const hasOpenDocument = Boolean(activeDocumentId && documents.some((d) => d.id === activeDocumentId));
+ const [appView, setAppView] = useState<'home' | 'workspace'>('workspace');
// Panels width & visibility (global resizability)
const [leftPanelWidth, setLeftPanelWidth] = useState<number>(() => {
@@ -483,6 +485,24 @@ export function App() {
const [perspectiveRuler, setPerspectiveRuler] = useState<PerspectiveRuler | null>(null);
const [activeLockedAxis, setActiveLockedAxis] = useState<ConstraintAxis | null>(null);
+ const handleActiveConstraintAxisChange = useCallback((newAxis: ConstraintAxis | null) => {
+ setActiveLockedAxis((prev) => {
+ if (prev === newAxis) return prev;
+ if (
+ prev &&
+ newAxis &&
+ prev.type === newAxis.type &&
+ prev.origin.x === newAxis.origin.x &&
+ prev.origin.y === newAxis.origin.y &&
+ prev.dir.x === newAxis.dir.x &&
+ prev.dir.y === newAxis.dir.y
+ ) {
+ return prev;
+ }
+ return newAxis;
+ });
+ }, []);
+
const updatePerspectiveRuler = useCallback(
(
updater:
@@ -783,6 +803,7 @@ export function App() {
} = useCanvasNavigation({
dimensions,
isWebtoonMode,
+ activeDocumentId,
});
// Remote multiplayer draft overlays and stroke states
@@ -1406,7 +1427,7 @@ export function App() {
}
},
perspectiveRuler: hasOpenDocument ? perspectiveRuler : null,
- onActiveConstraintAxisChange: setActiveLockedAxis,
+ onActiveConstraintAxisChange: handleActiveConstraintAxisChange,
});
selectiveUndoRef.current = selectiveUndo;
@@ -1467,6 +1488,7 @@ export function App() {
[updateBrushSettings]
);
+
const addRecentColor = useCallback((color: string) => {
setRecentColors((prev) => {
const filtered = prev.filter((c) => c.toLowerCase() !== color.toLowerCase());
@@ -3836,6 +3858,24 @@ export function App() {
]
);
+ const needsAdaptiveFitRef = useRef<boolean>(true);
+ const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);
+
+ const handleViewportReady = useCallback(
+ (_viewport: HTMLDivElement) => {
+ if (needsAdaptiveFitRef.current) {
+ if (_viewport.clientWidth <= 0 || _viewport.clientHeight <= 0) {
+ return;
+ }
+ needsAdaptiveFitRef.current = false;
+ const targetDims = pendingFitDimsRef.current || dimensions;
+ pendingFitDimsRef.current = null;
+ resetZoomAndCenter(targetDims);
+ }
+ },
+ [dimensions, resetZoomAndCenter]
+ );
+
// Create New Canvas handler
const handleCreateNewCanvas = useCallback(
(options: NewCanvasOptions) => {
@@ -3871,6 +3911,8 @@ export function App() {
options.colorMode,
defaultFreq
);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = newDims;
resetZoomAndCenter(newDims);
resetHistory();
@@ -3890,6 +3932,7 @@ export function App() {
setPerspectiveRuler(null);
setDocuments((prev) => [...prev, newDoc]);
setActiveDocumentId(newDocId);
+ setAppView('workspace');
showToast(`Created ${name}`);
},
@@ -3984,6 +4027,8 @@ export function App() {
resizeCanvas(newDims, options);
setDimensions(newDims);
+ pendingFitDimsRef.current = newDims;
+ needsAdaptiveFitRef.current = true;
resetZoomAndCenter(newDims);
resetHistory();
showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);
@@ -4046,6 +4091,8 @@ export function App() {
setSavedFileInfo(null); // Reset handle on new import
loadDocument(doc);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = doc.dimensions;
resetZoomAndCenter(doc.dimensions);
resetHistory();
@@ -4121,6 +4168,7 @@ export function App() {
const doc = documents.find((d) => d.id === id);
if (!doc) return;
setActiveDocumentId(id);
+ setAppView('workspace');
setDimensions(doc.dimensions);
setColorMode(doc.colorMode);
setDocumentName(doc.name);
@@ -4146,6 +4194,8 @@ export function App() {
});
}
setPerspectiveRuler(doc.perspectiveRuler ?? null);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = doc.dimensions;
resetZoomAndCenter(doc.dimensions);
},
[documents, loadDocument, resetZoomAndCenter]
@@ -4180,6 +4230,8 @@ export function App() {
layers: nextActive.layers,
layerCanvases: nextActive.layerCanvasesMap,
});
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = nextActive.dimensions;
resetZoomAndCenter(nextActive.dimensions);
} else {
clearDocument();
@@ -4191,6 +4243,7 @@ export function App() {
clearDocument();
resetHistory();
setPerspectiveRuler(null);
+ setAppView('home');
}
}
return next;
@@ -5842,6 +5895,7 @@ export function App() {
const uint8 = new Uint8Array(bytes);
const file = new File([uint8], doc.title, { type: 'application/octet-stream' });
await handleProcessFile(file);
+ setAppView('workspace');
return;
}
} catch (err) {
@@ -5946,12 +6000,30 @@ export function App() {
themePreset={appSettings.themePreset}
activeDocumentTitle={documents.find((d) => d.id === activeDocumentId)?.name}
softProofSettings={softProofSettings}
+ appView={appView}
+ onSelectAppView={(view) => {
+ if (view === 'workspace' && !hasOpenDocument) {
+ setIsNewCanvasModalOpen(true);
+ } else {
+ setAppView(view);
+ }
+ }}
/>
+ {/* Modern Horizontal Property Bar below Header in Workspace matching Reference 3 */}
+ {isModernTheme && hasOpenDocument && appView === 'workspace' && (
+ <ModernPropertyBar
+ tool={tool}
+ brushSettings={brushSettings}
+ onUpdateBrushSettings={updateBrushSettings}
+ onToggleBrushEditor={() => setIsLeftPanelHidden((prev) => !prev)}
+ isBrushEditorOpen={!isLeftPanelHidden}
+ />
+ )}
{/* Main Workspace */}
<div className="flex flex-1 overflow-hidden relative">
- {!hasOpenDocument ? (
+ {!hasOpenDocument || appView === 'home' ? (
<WelcomeScreen
userName={appSettings.userName}
onNewDocument={() => setIsNewCanvasModalOpen(true)}
@@ -6018,6 +6090,7 @@ export function App() {
<CanvasArea
viewportRef={viewportRef}
+ onViewportReady={handleViewportReady}
dimensions={dimensions}
brushSettings={brushSettings}
onUpdateBrushSettings={updateBrushSettings}
@@ -6039,6 +6112,8 @@ export function App() {
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
layers={layers}
+ activeLayerId={activeLayerId}
+ colorMode={colorMode}
layerCanvasesRef={layerCanvasesRef}
registerLayerCanvas={registerLayerCanvas}
getEffectiveOpacity={getEffectiveOpacity}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index 05078c3..4b1e08f 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -10,6 +10,7 @@ import {
LiquifySettings,
SpeechBalloon,
SoftProofSettings,
+ CanvasColorMode,
} from '../types/editor';
import { ROTATE_CURSOR_CSS } from '../hooks/useCanvasNavigation';
import { SelectionOverlay } from './SelectionOverlay';
@@ -110,6 +111,9 @@ interface CanvasAreaProps {
onDeleteAnimationCel?: (frameIndex: number) => void;
onSelectCelLayer?: (layerId: string) => void;
softProofSettings?: SoftProofSettings;
+ onViewportReady?: (viewport: HTMLDivElement) => void;
+ activeLayerId?: string;
+ colorMode?: CanvasColorMode;
}
function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEvent[] {
@@ -118,7 +122,7 @@ function extractCoalescedEvents(e: React.PointerEvent<HTMLElement>): PointerEven
try {
const coalesced = native.getCoalescedEvents();
if (coalesced && coalesced.length > 0) {
- return Array.from(coalesced);
+ return coalesced as unknown as PointerEvent[];
}
} catch {}
}
@@ -131,7 +135,7 @@ function extractPredictedEvents(e: React.PointerEvent<HTMLElement>): PointerEven
try {
const predicted = native.getPredictedEvents();
if (predicted && predicted.length > 0) {
- return Array.from(predicted);
+ return predicted as unknown as PointerEvent[];
}
} catch {}
}
@@ -140,6 +144,7 @@ function extractPredictedEvents(e: React.PointerEvent<HTMLElement>): PointerEven
export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
viewportRef,
+ onViewportReady,
dimensions,
brushSettings,
onUpdateBrushSettings,
@@ -216,12 +221,17 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onDeleteAnimationCel,
onSelectCelLayer,
softProofSettings,
+ activeLayerId,
+ colorMode = 'color',
}) => {
const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;
const localPredictedCanvasRef = useRef<HTMLCanvasElement | null>(null);
const effectivePredictedCanvasRef = predictedCanvasRef || localPredictedCanvasRef;
+ const activeLayer = layers.find((l) => l.id === activeLayerId);
+ const isMonochromeActive = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome' || brushSettings.antiAlias === 0;
+
// Resolve tip image and extract vector outline silhouette
const activeTipImage = resolveBrushTipImage(brushSettings);
const [tipOutline, setTipOutline] = useState<TipOutline | null>(() => {
@@ -430,12 +440,30 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
draftCanvas.width = w;
draftCanvas.height = h;
}
+
+ const predCanvas = effectivePredictedCanvasRef?.current;
+ if (predCanvas && (predCanvas.width !== w || predCanvas.height !== h)) {
+ predCanvas.width = w;
+ predCanvas.height = h;
+ }
};
updateCanvasSizes();
window.addEventListener('resize', updateCanvasSizes);
return () => window.removeEventListener('resize', updateCanvasSizes);
- }, [viewportRef, effectiveDraftCanvasRef, effectiveLayers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames, softProofSettings]);
+ }, [viewportRef, effectiveDraftCanvasRef, effectivePredictedCanvasRef, effectiveLayers, pan, zoom, rotation, dimensions, showCheckerboard, onionSkinFrames, softProofSettings]);
+
+ useEffect(() => {
+ if (viewportRef.current) {
+ onViewportReady?.(viewportRef.current);
+ const raf = requestAnimationFrame(() => {
+ if (viewportRef.current) {
+ onViewportReady?.(viewportRef.current);
+ }
+ });
+ return () => cancelAnimationFrame(raf);
+ }
+ }, [onViewportReady, viewportRef]);
// Render scene using Unified GPU Viewport Compositor
useEffect(() => {
@@ -671,6 +699,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onPointerMove(e, coalesced, predicted);
};
+
// Determine cursor based on active mode
const getCursorStyle = (isOverCanvas: boolean): React.CSSProperties => {
if (isResizingBrush || isCtrlAltDown) {
@@ -904,7 +933,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
)}
{/* Top Transparent Interaction Surface capturing Stylus / Mouse Pointer Events */}
-
<div
ref={interactionRef}
onPointerDown={handleCanvasPointerDown}
@@ -928,6 +956,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
height: '100%',
opacity: brushSettings.opacity ?? 1.0,
display: 'block',
+ filter: isMonochromeActive ? 'url(#ink-monochrome-threshold)' : undefined,
}}
/>
@@ -940,9 +969,21 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
height: '100%',
opacity: brushSettings.opacity ?? 1.0,
display: 'block',
+ filter: isMonochromeActive ? 'url(#ink-monochrome-threshold)' : undefined,
}}
/>
+ {/* SVG 1-bit Discrete Binary Threshold Filter for Manga WYSIWYG */}
+ <svg className="absolute w-0 h-0 pointer-events-none overflow-hidden" aria-hidden="true">
+ <defs>
+ <filter id="ink-monochrome-threshold" colorInterpolationFilters="sRGB">
+ <feComponentTransfer>
+ <feFuncA type="discrete" tableValues="0 1" />
+ </feComponentTransfer>
+ </filter>
+ </defs>
+ </svg>
+
{/* Interactive Perspective Ruler Overlay Layer (Clip Studio Paint style) */}
{perspectiveRuler && onUpdatePerspectiveRuler && (
<PerspectiveRulerOverlay
diff --git a/src/components/ColorWheel.tsx b/src/components/ColorWheel.tsx
index 879b496..ed30bbf 100644
--- a/src/components/ColorWheel.tsx
+++ b/src/components/ColorWheel.tsx
@@ -785,6 +785,23 @@ export const ColorWheel: React.FC<ColorWheelProps> = ({
</button>
</div>
+ {/* Harmony Button matching Reference 2 */}
+ <button
+ onClick={() => {
+ const compHue = (hsv.h + 180) % 360;
+ const compHex = hsvToHex(compHue, hsv.s, hsv.v);
+ if (activeTarget === 'primary') {
+ onSecondaryColorChange(compHex);
+ } else {
+ onPrimaryColorChange(compHex);
+ }
+ }}
+ title="Set complementary harmony color to secondary swatch"
+ className="px-2 py-1 rounded-md bg-white/[0.05] hover:bg-white/[0.09] border border-white/[0.08] text-white/80 hover:text-white text-[11px] font-medium transition-colors cursor-pointer"
+ >
+ Harmony
+ </button>
+
{/* Toggle RGB Sliders */}
<button
onClick={() => setShowAdvanced((v) => !v)}
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index eca6b5a..48148b4 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -43,6 +43,8 @@ interface HeaderProps {
themePreset?: ThemePreset;
activeDocumentTitle?: string;
softProofSettings?: SoftProofSettings;
+ appView?: 'home' | 'workspace';
+ onSelectAppView?: (view: 'home' | 'workspace') => void;
}
export const Header: React.FC<HeaderProps> = React.memo(({
@@ -71,14 +73,16 @@ export const Header: React.FC<HeaderProps> = React.memo(({
themePreset = 'vintage-manga',
activeDocumentTitle,
softProofSettings,
+ appView = 'workspace',
+ onSelectAppView,
}) => {
if (themePreset === 'modern') {
return (
<header
data-tauri-drag-region
- className="h-10 px-3 flex items-center justify-between text-xs select-none z-30 shrink-0 cursor-default bg-[#121318] border-b border-white/[0.08] text-[#e0e0e3]"
+ className="h-10 px-3 flex items-center justify-between text-xs select-none z-30 shrink-0 cursor-default bg-[#18191d] border-b border-white/[0.08] text-white/90"
>
- {/* Brand, Menus & Document Info */}
+ {/* Brand, Menus, Home/Workspace Pills & Document Info */}
<div className="flex items-center space-x-3 min-w-0">
<div className="flex items-center space-x-2" title="Ink Studio">
<div className="w-5 h-5 flex items-center justify-center">
@@ -96,6 +100,30 @@ export const Header: React.FC<HeaderProps> = React.memo(({
{/* Menu Bar Sections: File, Edit, Layer, View, Help */}
<MenuBar sections={menuSections} />
+ {/* Home / Workspace Navigation Pills matching Reference 1 & 3 */}
+ <div className="flex items-center space-x-0.5 bg-white/[0.04] p-0.5 rounded-lg border border-white/[0.08]">
+ <button
+ onClick={() => onSelectAppView?.('home')}
+ className={`px-3 py-1 rounded-md text-xs transition-colors cursor-pointer ${
+ appView === 'home'
+ ? 'bg-white/[0.14] text-white font-medium border border-white/10 shadow-xs'
+ : 'text-white/60 hover:text-white hover:bg-white/[0.06] border border-transparent'
+ }`}
+ >
+ Home
+ </button>
+ <button
+ onClick={() => onSelectAppView?.('workspace')}
+ className={`px-3 py-1 rounded-md text-xs transition-colors cursor-pointer ${
+ appView === 'workspace'
+ ? 'bg-white/[0.14] text-white font-medium border border-white/10 shadow-xs'
+ : 'text-white/60 hover:text-white hover:bg-white/[0.06] border border-transparent'
+ }`}
+ >
+ Workspace
+ </button>
+ </div>
+
{hasOpenDocument && (
<>
<span className="text-white/15">|</span>
diff --git a/src/components/ModernPropertyBar.tsx b/src/components/ModernPropertyBar.tsx
new file mode 100644
index 0000000..c526672
--- /dev/null
+++ b/src/components/ModernPropertyBar.tsx
@@ -0,0 +1,170 @@
+import React from 'react';
+import {
+ Paintbrush,
+ Sliders,
+ ChevronDown,
+ Settings,
+ BookOpen,
+ Blend,
+} from 'lucide-react';
+import { ToolType, BrushSettings } from '../types/editor';
+
+interface ModernPropertyBarProps {
+ tool: ToolType;
+ brushSettings: BrushSettings;
+ onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
+ onToggleBrushEditor: () => void;
+ onOpenPresets?: () => void;
+ isBrushEditorOpen?: boolean;
+}
+
+const BLEND_MODES = [
+ { value: 'source-over', label: 'Normal' },
+ { value: 'multiply', label: 'Multiply' },
+ { value: 'screen', label: 'Screen' },
+ { value: 'overlay', label: 'Overlay' },
+ { value: 'darken', label: 'Darken' },
+ { value: 'lighten', label: 'Lighten' },
+ { value: 'color-dodge', label: 'Color Dodge' },
+ { value: 'color-burn', label: 'Color Burn' },
+];
+
+export const ModernPropertyBar: React.FC<ModernPropertyBarProps> = ({
+ tool: _tool,
+ brushSettings,
+ onUpdateBrushSettings,
+ onToggleBrushEditor,
+ onOpenPresets,
+ isBrushEditorOpen = false,
+}) => {
+ const currentSize = Math.round(brushSettings.size);
+ const currentOpacity = Math.round((brushSettings.opacity ?? 1) * 100);
+ const currentFlow = Math.round((brushSettings.flow ?? 1) * 100);
+ const brushDisplayName = brushSettings.brushName || (brushSettings.preset as string) || 'Brush';
+
+ return (
+ <div className="h-9 px-3 flex items-center justify-between text-xs select-none z-20 shrink-0 bg-[#1e1f24] border-b border-white/[0.08] text-white/90">
+ {/* Left controls */}
+ <div className="flex items-center space-x-2">
+ {/* Presets Button */}
+ <button
+ onClick={onOpenPresets || onToggleBrushEditor}
+ title="Browse Brush Presets"
+ className="flex items-center space-x-1 px-2.5 py-1 rounded-md bg-white/[0.05] hover:bg-white/[0.09] border border-white/[0.08] text-white/80 hover:text-white transition-colors cursor-pointer text-xs"
+ >
+ <BookOpen className="w-3.5 h-3.5 text-white/60" />
+ <span>Presets</span>
+ </button>
+
+ {/* Active Brush Preset Pill */}
+ <button
+ onClick={onToggleBrushEditor}
+ title="Current Brush Preset (Click to Toggle Editor)"
+ className={`flex items-center space-x-1.5 px-2.5 py-1 rounded-md border text-xs transition-colors cursor-pointer ${
+ isBrushEditorOpen
+ ? 'bg-white/[0.12] border-white/20 text-white'
+ : 'bg-white/[0.05] hover:bg-white/[0.09] border-white/[0.08] text-white/90'
+ }`}
+ >
+ <Paintbrush className="w-3.5 h-3.5 text-white/70" />
+ <span className="font-medium max-w-[140px] truncate">{brushDisplayName}</span>
+ <ChevronDown className="w-3 h-3 text-white/40" />
+ </button>
+
+ {/* Brush Editor Button */}
+ <button
+ onClick={onToggleBrushEditor}
+ title="Toggle Detailed Brush Settings & Dynamics"
+ className={`flex items-center space-x-1 px-2.5 py-1 rounded-md border text-xs transition-colors cursor-pointer ${
+ isBrushEditorOpen
+ ? 'bg-[var(--modern-accent-subtle)] text-[var(--modern-accent)] border-[var(--modern-accent-border)]'
+ : 'bg-white/[0.05] hover:bg-white/[0.09] border-white/[0.08] text-white/80 hover:text-white'
+ }`}
+ >
+ <Sliders className="w-3.5 h-3.5" />
+ <span>Brush Editor</span>
+ </button>
+
+ <span className="text-white/15">|</span>
+
+ {/* Mode Dropdown */}
+ <div className="flex items-center space-x-1.5 bg-white/[0.04] border border-white/[0.08] rounded-md px-2 py-0.5">
+ <Blend className="w-3.5 h-3.5 text-white/50" />
+ <span className="text-[11px] text-white/50">Mode:</span>
+ <select
+ defaultValue="source-over"
+ className="bg-transparent text-white/90 text-xs font-medium outline-none cursor-pointer pr-1"
+ title="Brush Blending Mode"
+ >
+ {BLEND_MODES.map((bm) => (
+ <option key={bm.value} value={bm.value} className="bg-[#1e1f24] text-white">
+ {bm.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Size Input */}
+ <div className="flex items-center space-x-1 bg-white/[0.04] border border-white/[0.08] rounded-md px-2 py-0.5">
+ <span className="text-[11px] text-white/50">Size:</span>
+ <input
+ type="number"
+ min={1}
+ max={500}
+ value={currentSize}
+ onChange={(e) => onUpdateBrushSettings({ size: Math.max(1, Math.min(500, Number(e.target.value))) })}
+ className="w-11 bg-transparent text-white text-xs font-mono outline-none text-right"
+ />
+ <span className="text-[11px] text-white/40 font-mono">px</span>
+ </div>
+
+ {/* Opacity Input */}
+ <div className="flex items-center space-x-1 bg-white/[0.04] border border-white/[0.08] rounded-md px-2 py-0.5">
+ <span className="text-[11px] text-white/50">Opacity:</span>
+ <input
+ type="number"
+ min={1}
+ max={100}
+ value={currentOpacity}
+ onChange={(e) =>
+ onUpdateBrushSettings({
+ opacity: Math.max(0.01, Math.min(1, Number(e.target.value) / 100)),
+ })
+ }
+ className="w-9 bg-transparent text-white text-xs font-mono outline-none text-right"
+ />
+ <span className="text-[11px] text-white/40 font-mono">%</span>
+ </div>
+
+ {/* Flow Input */}
+ <div className="flex items-center space-x-1 bg-white/[0.04] border border-white/[0.08] rounded-md px-2 py-0.5">
+ <span className="text-[11px] text-white/50">Flow:</span>
+ <input
+ type="number"
+ min={1}
+ max={100}
+ value={currentFlow}
+ onChange={(e) =>
+ onUpdateBrushSettings({
+ flow: Math.max(0.01, Math.min(1, Number(e.target.value) / 100)),
+ })
+ }
+ className="w-9 bg-transparent text-white text-xs font-mono outline-none text-right"
+ />
+ <span className="text-[11px] text-white/40 font-mono">%</span>
+ </div>
+ </div>
+
+ {/* Right controls: Tool settings cog */}
+ <div className="flex items-center space-x-1.5">
+ <button
+ onClick={onToggleBrushEditor}
+ title="Tool Options & Presets"
+ className="p-1 rounded-md text-white/60 hover:text-white hover:bg-white/[0.08] transition-colors cursor-pointer"
+ >
+ <Settings className="w-3.5 h-3.5" />
+ </button>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/WelcomeScreen.tsx b/src/components/WelcomeScreen.tsx
index 135b75a..cf323cc 100644
--- a/src/components/WelcomeScreen.tsx
+++ b/src/components/WelcomeScreen.tsx
@@ -101,85 +101,84 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
if (themePreset === 'modern') {
return (
- <div className="flex-1 flex flex-col h-full bg-[#0c0d12] text-white/90 overflow-y-auto select-none font-sans">
- {/* Top Utility Header */}
- <div className="border-b border-white/[0.08] bg-[#121318]/90 backdrop-blur-md px-8 py-3.5 shrink-0">
- <div className="max-w-6xl mx-auto flex items-center justify-between gap-4">
- <div className="flex items-center space-x-3">
- <span className="w-2.5 h-2.5 rounded-full bg-[var(--modern-accent)] shadow-[0_0_8px_var(--modern-accent)]" />
- <span className="text-sm font-semibold tracking-tight text-white">
- Ink Studio
- </span>
- <span className="text-white/20">/</span>
- <span className="text-xs text-white/50">Recent Documents</span>
+ <div className="flex-1 flex flex-col h-full bg-[#18191d] text-white/90 overflow-y-auto select-none font-sans">
+ {/* Main Content Container matching Reference 1 */}
+ <div className="max-w-4xl w-full mx-auto px-6 py-12 flex-1 flex flex-col">
+ {/* Header Row: Greeting & Action Buttons */}
+ <div className="flex items-start justify-between gap-6 mb-8">
+ <div>
+ <h1 className="text-3xl font-light tracking-tight text-white/95">
+ Welcome back{userName?.trim() ? `, ${userName.trim()}` : ', my Lord'}.
+ </h1>
+ <p className="text-xs text-white/40 mt-1 font-mono tracking-wide">
+ bdt.greeting
+ </p>
</div>
- <div className="flex items-center space-x-2.5">
+ <div className="flex items-center gap-2.5 shrink-0 pt-1">
<button
type="button"
onClick={onNewDocument}
- className="flex items-center space-x-1.5 px-3.5 py-1.5 rounded-lg bg-[var(--modern-accent)] hover:brightness-110 active:scale-[0.98] text-xs font-medium text-white shadow-sm transition-all cursor-pointer"
+ className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-white/[0.08] hover:bg-white/[0.14] active:scale-[0.98] border border-white/10 text-xs font-medium text-white shadow-xs transition-all cursor-pointer"
>
- <FilePlus className="w-3.5 h-3.5" />
- <span>New Canvas</span>
+ <FilePlus className="w-3.5 h-3.5 text-white/90" />
+ <span>+ New document</span>
</button>
<button
type="button"
onClick={onOpenFile}
- className="flex items-center space-x-1.5 px-3.5 py-1.5 rounded-lg bg-white/[0.05] hover:bg-white/[0.1] active:scale-[0.98] border border-white/10 text-xs font-medium text-white/90 transition-all cursor-pointer"
+ className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-white/[0.04] hover:bg-white/[0.08] active:scale-[0.98] border border-white/10 text-xs font-medium text-white/80 hover:text-white transition-all cursor-pointer"
>
<FolderOpen className="w-3.5 h-3.5 text-white/70" />
- <span>Open File...</span>
+ <span>Open file...</span>
</button>
</div>
</div>
- </div>
-
- {/* Main Container */}
- <div className="max-w-6xl w-full mx-auto p-8 space-y-8 flex-1">
- <div>
- <h1 className="text-xl font-semibold tracking-tight text-white">
- Welcome back, {displayName}
- </h1>
- </div>
- {/* Search Bar */}
- <div className="flex items-center justify-between gap-4 pb-3 border-b border-white/[0.06]">
- <div className="relative w-80">
- <Search className="w-3.5 h-3.5 text-white/40 absolute left-3 top-2.5 pointer-events-none" />
+ {/* Wide Search Bar */}
+ <div className="mb-2">
+ <div className="relative w-full">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Filter files..."
- className="w-full pl-9 pr-8 py-1.5 text-xs bg-white/[0.04] border border-white/[0.08] rounded-lg text-white placeholder-white/40 outline-none focus:border-[var(--modern-accent)] focus:ring-1 focus:ring-[var(--modern-accent)] transition-all"
+ placeholder="Search your documents"
+ className="w-full pl-4 pr-10 py-2.5 text-xs bg-[#222328] border border-white/[0.06] rounded-xl text-white placeholder-white/35 outline-none focus:border-white/20 focus:ring-1 focus:ring-white/20 transition-all shadow-inner"
/>
- {searchQuery && (
+ {searchQuery ? (
<button
type="button"
onClick={() => setSearchQuery('')}
- className="absolute right-2.5 top-2 text-white/40 hover:text-white"
+ className="absolute right-3 top-2.5 text-white/40 hover:text-white cursor-pointer"
>
- <X className="w-3 h-3" />
+ <X className="w-3.5 h-3.5" />
</button>
+ ) : (
+ <Search className="w-3.5 h-3.5 text-white/30 absolute right-3.5 top-3 pointer-events-none" />
)}
</div>
-
- <div className="text-[11px] font-mono text-white/40">
- {filtered.length} {filtered.length === 1 ? 'file' : 'files'}
- </div>
</div>
+ <p className="text-[11px] text-white/35 mb-8">
+ Removed from Home. Saved files are kept.
+ </p>
+
{/* Starred Section */}
- {starredDocs.length > 0 && (
- <section className="space-y-3">
- <div className="flex items-center space-x-2 text-xs font-semibold text-white/70 uppercase tracking-wider">
- <Star className="w-3.5 h-3.5 text-amber-400 fill-amber-400" />
- <span>Favorites ({starredDocs.length})</span>
- </div>
+ <div className="mb-8">
+ <div className="flex items-center gap-2 mb-3">
+ <span className="text-xs font-medium text-white/80">Starred</span>
+ <span className="text-[10px] px-2 py-0.5 rounded-full bg-white/[0.06] text-white/50 font-mono">
+ {starredDocs.length}
+ </span>
+ </div>
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3.5">
+ {starredDocs.length === 0 ? (
+ <p className="text-xs text-white/35">
+ Star a document below to keep it close.
+ </p>
+ ) : (
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
{starredDocs.map((doc) => (
<ModernDocCard
key={`starred-${doc.id}`}
@@ -192,17 +191,20 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
/>
))}
</div>
- </section>
- )}
+ )}
+ </div>
- {/* Recent Section */}
- <section className="space-y-3">
- <div className="text-xs font-semibold text-white/70 uppercase tracking-wider">
- All Documents ({regularDocs.length})
+ {/* Recent Documents Section */}
+ <div>
+ <div className="flex items-center gap-2 mb-3">
+ <span className="text-xs font-medium text-white/80">Recent documents</span>
+ <span className="text-[10px] px-2 py-0.5 rounded-full bg-white/[0.06] text-white/50 font-mono">
+ {regularDocs.length}
+ </span>
</div>
{regularDocs.length === 0 ? (
- <div className="border border-dashed border-white/10 bg-white/[0.02] p-10 text-center rounded-xl">
+ <div className="border border-dashed border-white/10 bg-white/[0.02] p-8 text-center rounded-xl">
<p className="text-xs text-white/40">
{cleanQuery
? 'No documents matched the filter.'
@@ -210,7 +212,7 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
</p>
</div>
) : (
- <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3.5">
+ <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
{regularDocs.map((doc) => (
<ModernDocCard
key={`recent-${doc.id}`}
@@ -224,7 +226,7 @@ export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({
))}
</div>
)}
- </section>
+ </div>
</div>
{/* Delete Confirmation Modal */}
@@ -472,62 +474,64 @@ const ModernDocCard: React.FC<VintageDocCardProps> = ({
return (
<div
onClick={onSelect}
- className="group relative flex flex-col bg-[#14151b] hover:bg-[#1a1b24] border border-white/[0.08] hover:border-[var(--modern-accent-border)] rounded-xl p-3 cursor-pointer transition-all duration-150 shadow-xs hover:shadow-lg hover:-translate-y-0.5"
+ className="group relative flex flex-col bg-[#222328] hover:bg-[#282930] border border-white/[0.07] hover:border-white/20 rounded-xl p-3 cursor-pointer transition-all duration-150 shadow-md hover:shadow-xl"
title={`${doc.title}\n${doc.path}`}
>
- {/* Thumbnail Area */}
- <div className="relative aspect-[4/3] bg-[#0c0d12] border border-white/[0.04] overflow-hidden flex items-center justify-center rounded-lg mb-2.5">
+ {/* Thumbnail Area - Aspect Square with Checkerboard Canvas Preview */}
+ <div
+ className="relative aspect-square border border-white/[0.05] overflow-hidden flex items-center justify-center rounded-lg mb-2.5"
+ style={{
+ background:
+ 'repeating-conic-gradient(#202126 0% 25%, #17181c 0% 50%) 50% / 12px 12px',
+ }}
+ >
{doc.coverUrl ? (
<img
src={doc.coverUrl}
alt={doc.title}
- className="w-full h-full object-cover select-none pointer-events-none group-hover:scale-105 transition-transform duration-300"
+ className="w-full h-full object-cover select-none pointer-events-none group-hover:scale-102 transition-transform duration-200"
/>
) : (
- <div className="flex flex-col items-center justify-center text-white/30 space-y-1">
+ <div className="w-3/4 h-3/4 bg-white/90 rounded-sm shadow-md flex flex-col items-center justify-center text-zinc-400">
<FileText className="w-6 h-6 stroke-[1.5]" />
- <span className="text-[9px] font-mono uppercase tracking-wider text-white/40">{doc.fileType || 'CANVAS'}</span>
</div>
)}
- {/* Quick Actions (top corners) */}
- <div className="absolute top-1.5 left-1.5 flex items-center space-x-1">
+ {/* Top Right Quick Actions: Close (X) and Star */}
+ <div className="absolute top-1.5 right-1.5 flex items-center space-x-1">
<button
type="button"
- onClick={onToggleStar}
- title={doc.isStarred ? 'Remove favorite' : 'Add favorite'}
- className={`w-6 h-6 rounded-md flex items-center justify-center transition-all cursor-pointer ${
- doc.isStarred
- ? 'bg-black/60 text-amber-400 backdrop-blur-xs'
- : 'bg-black/50 text-white/40 opacity-0 group-hover:opacity-100 hover:text-amber-400 backdrop-blur-xs'
- }`}
+ onClick={onDelete}
+ title="Remove from recents"
+ className="w-5 h-5 rounded-md bg-black/60 hover:bg-black/90 text-white/50 hover:text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all backdrop-blur-xs cursor-pointer"
>
- <Star className={`w-3.5 h-3.5 ${doc.isStarred ? 'fill-amber-400' : ''}`} />
+ <X className="w-3 h-3" />
</button>
- </div>
-
- <div className="absolute top-1.5 right-1.5">
<button
type="button"
- onClick={onDelete}
- title="Delete file options"
- className="w-6 h-6 rounded-md bg-black/50 hover:bg-rose-950/80 text-white/40 hover:text-rose-300 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all backdrop-blur-xs cursor-pointer"
+ onClick={onToggleStar}
+ title={doc.isStarred ? 'Remove favorite' : 'Add favorite'}
+ className={`w-5 h-5 rounded-md flex items-center justify-center transition-all cursor-pointer ${
+ doc.isStarred
+ ? 'bg-black/70 text-amber-400 backdrop-blur-xs'
+ : 'bg-black/60 text-white/50 opacity-0 group-hover:opacity-100 hover:text-amber-400 backdrop-blur-xs'
+ }`}
>
- <Trash2 className="w-3.5 h-3.5" />
+ <Star className={`w-3 h-3 ${doc.isStarred ? 'fill-amber-400' : ''}`} />
</button>
</div>
</div>
- {/* Meta */}
- <div className="min-w-0 space-y-1">
- <div className="text-xs font-medium text-white/90 truncate group-hover:text-[var(--modern-accent)] transition-colors">
+ {/* Meta matching Reference 1 */}
+ <div className="min-w-0 space-y-0.5">
+ <div className="text-xs font-semibold text-white/95 truncate">
{doc.title}
</div>
- <div className="flex items-center justify-between text-[10px] text-white/40 font-mono">
- <span>{formatFileSize(doc.size)}</span>
- <span className="uppercase text-[9px] px-1.5 py-0.5 bg-white/[0.05] border border-white/[0.06] rounded font-mono text-white/60">
- {doc.fileType || 'CANVAS'}
- </span>
+ <div className="text-[10px] text-white/45 truncate">
+ Previous session · Last worked on {formatFileSize(doc.size)}
+ </div>
+ <div className="text-[9px] text-white/30 font-mono truncate">
+ {doc.path}
</div>
</div>
</div>
diff --git a/src/engine/InputStabilizer.ts b/src/engine/InputStabilizer.ts
new file mode 100644
index 0000000..d20db61
--- /dev/null
+++ b/src/engine/InputStabilizer.ts
@@ -0,0 +1,329 @@
+/**
+ * InputStabilizer.ts
+ * Low-latency 1-Euro Filter + Velocity Tracker + Mass-Spring-Damper.
+ * Pre-allocated memory structures, zero GC pauses during active drawing.
+ * Upgraded with:
+ * - Critical Angle Detection (Corner Snapping, DeltaTheta > 45 deg)
+ * - Velocity-Adaptive Damping Scaling
+ * - Asymmetric Attack / Decay Pressure Filtering
+ */
+
+export interface StabilizerConfig {
+ minCutoff: number; // fc_min (Hz): lower = smoother slow movements (default ~1.0)
+ beta: number; // beta: speed coefficient; higher = less lag on flicks (default ~0.02)
+ dCutoff: number; // d_cutoff (Hz): cutoff for derivative filtering (default ~1.0)
+ deadzone: number; // Minimum delta distance (px) to register movement
+ springMass: number; // Mass for virtual pull-string / spring-damper (0 = disabled)
+ springStiffness: number; // Spring stiffness k
+ springDamping: number; // Damping coefficient c (critically damped: 2 * sqrt(k * m))
+ cornerAngleThreshold: number; // Angular deflection threshold in radians (default 45 deg = 0.785398)
+ attackCutoff: number; // Pressure attack cutoff Hz (instant contact)
+ decayCutoff: number; // Pressure decay cutoff Hz (smooth release)
+}
+
+export const DEFAULT_STABILIZER_CONFIG: StabilizerConfig = {
+ minCutoff: 1.5,
+ beta: 0.03,
+ dCutoff: 1.0,
+ deadzone: 0.1,
+ springMass: 0,
+ springStiffness: 180,
+ springDamping: 26.8,
+ cornerAngleThreshold: 0.785398, // 45 degrees
+ attackCutoff: 45.0, // Fast response on pen attack
+ decayCutoff: 4.0, // Smooth release
+};
+
+export class OneEuroAxis {
+ private xPrev: number = 0;
+ private dxPrev: number = 0;
+ private tPrev: number = 0;
+ private initialized: boolean = false;
+
+ public reset(): void {
+ this.xPrev = 0;
+ this.dxPrev = 0;
+ this.tPrev = 0;
+ this.initialized = false;
+ }
+
+ public setDirect(x: number, timestampMs: number): void {
+ this.xPrev = x;
+ this.dxPrev = 0;
+ this.tPrev = timestampMs;
+ this.initialized = true;
+ }
+
+ private alpha(rate: number, cutoff: number): number {
+ const tau = 1.0 / (2.0 * Math.PI * cutoff);
+ const te = 1.0 / Math.max(1e-5, rate);
+ return 1.0 / (1.0 + tau / te);
+ }
+
+ public filter(x: number, timestampMs: number, minCutoff: number, beta: number, dCutoff: number): number {
+ if (!this.initialized) {
+ this.xPrev = x;
+ this.dxPrev = 0;
+ this.tPrev = timestampMs;
+ this.initialized = true;
+ return x;
+ }
+
+ const dt = Math.max(1e-4, (timestampMs - this.tPrev) * 0.001); // dt in seconds
+ this.tPrev = timestampMs;
+ const rate = 1.0 / dt;
+
+ // Filter derivative
+ const dx = (x - this.xPrev) / dt;
+ const aD = this.alpha(rate, dCutoff);
+ const edx = aD * dx + (1.0 - aD) * this.dxPrev;
+ this.dxPrev = edx;
+
+ // Dynamic cutoff based on speed
+ const cutoff = minCutoff + beta * Math.abs(edx);
+ const a = this.alpha(rate, cutoff);
+ const filteredX = a * x + (1.0 - a) * this.xPrev;
+ this.xPrev = filteredX;
+
+ return filteredX;
+ }
+}
+
+export interface StabilizedSample {
+ x: number;
+ y: number;
+ pressure: number;
+ vx: number; // px / ms
+ vy: number; // px / ms
+ speed: number; // px / ms
+ timestamp: number;
+ isCorner: boolean;
+}
+
+export class InputStabilizer {
+ private filterX = new OneEuroAxis();
+ private filterY = new OneEuroAxis();
+ private filterPressure = new OneEuroAxis();
+
+ // Asymmetric pressure tracker
+ private lastRawPressure: number = 0;
+
+ // Mass-Spring-Damper simulation state
+ private smX: number = 0;
+ private smY: number = 0;
+ private smVx: number = 0;
+ private smVy: number = 0;
+
+ // Velocity tracker state
+ private lastX: number = 0;
+ private lastY: number = 0;
+ private lastTime: number = 0;
+ private instantVx: number = 0;
+ private instantVy: number = 0;
+ private instantSpeed: number = 0;
+
+ // Direction vector history for Corner Snapping (Critical Angle Detection)
+ private prevDirX: number = 0;
+ private prevDirY: number = 0;
+ private hasPrevDir: boolean = false;
+ private rawPrevX: number = 0;
+ private rawPrevY: number = 0;
+
+ // Single pre-allocated sample object for output to eliminate GC allocation
+ private outputSample: StabilizedSample = {
+ x: 0,
+ y: 0,
+ pressure: 0,
+ vx: 0,
+ vy: 0,
+ speed: 0,
+ timestamp: 0,
+ isCorner: false,
+ };
+
+ private isStarted: boolean = false;
+ private config: StabilizerConfig = { ...DEFAULT_STABILIZER_CONFIG };
+
+ public configure(config: Partial<StabilizerConfig>): void {
+ Object.assign(this.config, config);
+ }
+
+ public setStabilizerLevel(level: number): void {
+ // level: 0 to 50 (CSP slider equivalent)
+ if (level <= 0) {
+ this.config.minCutoff = 100.0; // effectively bypassed
+ this.config.beta = 0.5;
+ this.config.springMass = 0;
+ } else {
+ // Pure unconditionally stable 1-Euro adaptive curve (Clip Studio Paint style)
+ const t = Math.min(1.0, level / 50.0);
+ this.config.minCutoff = Math.max(0.6, 5.0 - t * 4.4); // 5.0 -> 0.6 Hz
+ this.config.beta = Math.max(0.008, 0.06 - t * 0.05); // 0.06 -> 0.01
+ this.config.springMass = 0; // Pure 1-Euro without oscillating spring artifacts
+ }
+ }
+
+ public reset(): void {
+ this.filterX.reset();
+ this.filterY.reset();
+ this.filterPressure.reset();
+ this.lastRawPressure = 0;
+ this.smX = 0;
+ this.smY = 0;
+ this.smVx = 0;
+ this.smVy = 0;
+ this.lastX = 0;
+ this.lastY = 0;
+ this.lastTime = 0;
+ this.instantVx = 0;
+ this.instantVy = 0;
+ this.instantSpeed = 0;
+ this.prevDirX = 0;
+ this.prevDirY = 0;
+ this.hasPrevDir = false;
+ this.rawPrevX = 0;
+ this.rawPrevY = 0;
+ this.isStarted = false;
+ }
+
+ public process(
+ rawX: number,
+ rawY: number,
+ rawPressure: number,
+ timestampMs: number
+ ): StabilizedSample {
+ if (!this.isStarted) {
+ this.reset();
+ this.lastX = rawX;
+ this.lastY = rawY;
+ this.lastTime = timestampMs;
+ this.rawPrevX = rawX;
+ this.rawPrevY = rawY;
+ this.smX = rawX;
+ this.smY = rawY;
+ this.smVx = 0;
+ this.smVy = 0;
+ this.lastRawPressure = rawPressure;
+ this.isStarted = true;
+
+ const fX = this.filterX.filter(rawX, timestampMs, this.config.minCutoff, this.config.beta, this.config.dCutoff);
+ const fY = this.filterY.filter(rawY, timestampMs, this.config.minCutoff, this.config.beta, this.config.dCutoff);
+ const fP = this.filterPressure.filter(rawPressure, timestampMs, this.config.attackCutoff, 0.1, this.config.dCutoff);
+
+ this.outputSample.x = fX;
+ this.outputSample.y = fY;
+ this.outputSample.pressure = fP;
+ this.outputSample.vx = 0;
+ this.outputSample.vy = 0;
+ this.outputSample.speed = 0;
+ this.outputSample.timestamp = timestampMs;
+ this.outputSample.isCorner = false;
+ return this.outputSample;
+ }
+
+ const dtMs = Math.max(1, timestampMs - this.lastTime);
+ const dtSec = dtMs * 0.001;
+
+ // 1. Critical Angle Detection (Corner Snapping)
+ const rawDx = rawX - this.rawPrevX;
+ const rawDy = rawY - this.rawPrevY;
+ const rawDist = Math.hypot(rawDx, rawDy);
+ let isCorner = false;
+
+ if (rawDist >= 6.0) {
+ const curDirX = rawDx / rawDist;
+ const curDirY = rawDy / rawDist;
+
+ if (this.hasPrevDir) {
+ // Dot product between consecutive motion vectors
+ const dot = Math.max(-1.0, Math.min(1.0, this.prevDirX * curDirX + this.prevDirY * curDirY));
+ const angle = Math.acos(dot);
+
+ // If angular deflection exceeds critical angle threshold (default 45 deg)
+ if (angle > this.config.cornerAngleThreshold) {
+ isCorner = true;
+ // Immediately reset filter tension and mass-spring inertia to sharp vertex coordinate
+ this.filterX.setDirect(rawX, timestampMs);
+ this.filterY.setDirect(rawY, timestampMs);
+ this.smX = rawX;
+ this.smY = rawY;
+ this.smVx = 0;
+ this.smVy = 0;
+ }
+ }
+
+ this.prevDirX = curDirX;
+ this.prevDirY = curDirY;
+ this.hasPrevDir = true;
+ this.rawPrevX = rawX;
+ this.rawPrevY = rawY;
+ }
+
+ // 2. Velocity-Adaptive Damping Scaling
+ // On high-speed ballistic flicks, scale cutoff up and latency toward zero
+ const estimatedSpeed = rawDist / dtMs; // px / ms
+ const speedBoost = Math.min(15.0, estimatedSpeed * 4.0);
+ const dynamicMinCutoff = this.config.minCutoff * (1.0 + speedBoost);
+ const dynamicBeta = this.config.beta * (1.0 + speedBoost * 0.8);
+
+ // 3. Coordinate Filtering
+ let fX = isCorner ? rawX : this.filterX.filter(rawX, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+ let fY = isCorner ? rawY : this.filterY.filter(rawY, timestampMs, dynamicMinCutoff, dynamicBeta, this.config.dCutoff);
+
+ // 4. Asymmetric Pressure Filtering (Fast Attack, Critically Damped Decay)
+ const pressureDelta = rawPressure - this.lastRawPressure;
+ this.lastRawPressure = rawPressure;
+ const pCutoff = pressureDelta > 0 ? this.config.attackCutoff : this.config.decayCutoff;
+ const pBeta = pressureDelta > 0 ? 0.2 : 0.01;
+ const fP = this.filterPressure.filter(rawPressure, timestampMs, pCutoff, pBeta, this.config.dCutoff);
+
+ // 5. Mass-Spring-Damper Simulation (when enabled for stabilizer > 15)
+ if (this.config.springMass > 0 && !isCorner) {
+ const k = this.config.springStiffness;
+ const c = this.config.springDamping;
+ const m = this.config.springMass;
+
+ // Dynamic damping reduction on fast flicks
+ const effectiveDamping = Math.max(c * 0.35, c / (1.0 + estimatedSpeed * 0.5));
+
+ const disX = fX - this.smX;
+ const disY = fY - this.smY;
+
+ const ax = (k * disX - effectiveDamping * this.smVx) / m;
+ const ay = (k * disY - effectiveDamping * this.smVy) / m;
+
+ // Semi-implicit Euler integration
+ this.smVx += ax * dtSec;
+ this.smVy += ay * dtSec;
+ this.smX += this.smVx * dtSec;
+ this.smY += this.smVy * dtSec;
+
+ fX = this.smX;
+ fY = this.smY;
+ }
+
+ // Velocity computation in px / ms
+ const dx = fX - this.lastX;
+ const dy = fY - this.lastY;
+ const dist = Math.hypot(dx, dy);
+
+ this.instantVx = dx / dtMs;
+ this.instantVy = dy / dtMs;
+ this.instantSpeed = dist / dtMs;
+
+ this.lastX = fX;
+ this.lastY = fY;
+ this.lastTime = timestampMs;
+
+ this.outputSample.x = fX;
+ this.outputSample.y = fY;
+ this.outputSample.pressure = Math.max(0, Math.min(1, fP));
+ this.outputSample.vx = this.instantVx;
+ this.outputSample.vy = this.instantVy;
+ this.outputSample.speed = this.instantSpeed;
+ this.outputSample.timestamp = timestampMs;
+ this.outputSample.isCorner = isCorner;
+
+ return this.outputSample;
+ }
+}
diff --git a/src/engine/SplineGenerator.ts b/src/engine/SplineGenerator.ts
new file mode 100644
index 0000000..5fc5b10
--- /dev/null
+++ b/src/engine/SplineGenerator.ts
@@ -0,0 +1,247 @@
+/**
+ * SplineGenerator.ts
+ * Zero-Delay Centripetal Catmull-Rom (alpha = 0.5) and Hermite provisional segment stitching.
+ * Pre-allocated data structures, zero GC pressure in render hot-paths.
+ * Upgraded with:
+ * - Corner Knot Snap commits (C0 position continuity, sharp vertices)
+ * - Seamless Hermite Tangent Extrapolation for real-time stroke head tracking
+ */
+
+export interface SplinePoint {
+ x: number;
+ y: number;
+ pressure: number;
+ width: number;
+}
+
+export interface CubicBezierSegment {
+ p0: SplinePoint;
+ c1: SplinePoint;
+ c2: SplinePoint;
+ p3: SplinePoint;
+}
+
+export class SplineGenerator {
+ // Reusable Bézier segment object to prevent GC churn
+ private segment: CubicBezierSegment = {
+ p0: { x: 0, y: 0, pressure: 0, width: 0 },
+ c1: { x: 0, y: 0, pressure: 0, width: 0 },
+ c2: { x: 0, y: 0, pressure: 0, width: 0 },
+ p3: { x: 0, y: 0, pressure: 0, width: 0 },
+ };
+
+ // Reusable exit tangent for Hermite continuity
+ private lastTangentX: number = 0;
+ private lastTangentY: number = 0;
+ private hasLastTangent: boolean = false;
+
+ public reset(): void {
+ this.hasLastTangent = false;
+ this.lastTangentX = 0;
+ this.lastTangentY = 0;
+ }
+
+ /**
+ * Commits a sharp corner knot: resets tangent memory and breaks derivative continuity
+ * to guarantee razor-sharp corners without loop overshoot or rounding.
+ */
+ public commitCornerKnot(_cornerPoint?: SplinePoint): void {
+ this.hasLastTangent = false;
+ this.lastTangentX = 0;
+ this.lastTangentY = 0;
+ }
+
+ /**
+ * Generates a sharp corner segment directly to the apex coordinate
+ * with colinear control handles along the chord.
+ */
+ public generateCornerSegment(pPrev: SplinePoint, pCorner: SplinePoint): CubicBezierSegment {
+ const dx = pCorner.x - pPrev.x;
+ const dy = pCorner.y - pPrev.y;
+
+ this.segment.p0.x = pPrev.x;
+ this.segment.p0.y = pPrev.y;
+ this.segment.p0.pressure = pPrev.pressure;
+ this.segment.p0.width = pPrev.width;
+
+ this.segment.c1.x = pPrev.x + dx * 0.333;
+ this.segment.c1.y = pPrev.y + dy * 0.333;
+ this.segment.c1.pressure = pPrev.pressure + (pCorner.pressure - pPrev.pressure) * 0.333;
+ this.segment.c1.width = pPrev.width + (pCorner.width - pPrev.width) * 0.333;
+
+ this.segment.c2.x = pPrev.x + dx * 0.667;
+ this.segment.c2.y = pPrev.y + dy * 0.667;
+ this.segment.c2.pressure = pPrev.pressure + (pCorner.pressure - pPrev.pressure) * 0.667;
+ this.segment.c2.width = pPrev.width + (pCorner.width - pPrev.width) * 0.667;
+
+ this.segment.p3.x = pCorner.x;
+ this.segment.p3.y = pCorner.y;
+ this.segment.p3.pressure = pCorner.pressure;
+ this.segment.p3.width = pCorner.width;
+
+ this.hasLastTangent = false;
+ this.lastTangentX = 0;
+ this.lastTangentY = 0;
+
+ return this.segment;
+ }
+
+ /**
+ * Generates provisional zero-latency segment between P(n-1) and current raw point P(n)
+ * using a Hermite spline parameterized by known start tangent and current velocity tangent.
+ */
+ public generateProvisionalSegment(
+ pPrev: SplinePoint,
+ pCurr: SplinePoint,
+ vx: number,
+ vy: number
+ ): CubicBezierSegment {
+ const dx = pCurr.x - pPrev.x;
+ const dy = pCurr.y - pPrev.y;
+ const chordLen = Math.hypot(dx, dy);
+
+ this.segment.p0.x = pPrev.x;
+ this.segment.p0.y = pPrev.y;
+ this.segment.p0.pressure = pPrev.pressure;
+ this.segment.p0.width = pPrev.width;
+
+ this.segment.p3.x = pCurr.x;
+ this.segment.p3.y = pCurr.y;
+ this.segment.p3.pressure = pCurr.pressure;
+ this.segment.p3.width = pCurr.width;
+
+ if (chordLen < 1e-4) {
+ this.segment.c1.x = pPrev.x;
+ this.segment.c1.y = pPrev.y;
+ this.segment.c1.pressure = pPrev.pressure;
+ this.segment.c1.width = pPrev.width;
+
+ this.segment.c2.x = pCurr.x;
+ this.segment.c2.y = pCurr.y;
+ this.segment.c2.pressure = pCurr.pressure;
+ this.segment.c2.width = pCurr.width;
+ return this.segment;
+ }
+
+ // Tangent at start: use prior exit tangent if available, else chord direction
+ let t0x = this.hasLastTangent ? this.lastTangentX : dx;
+ let t0y = this.hasLastTangent ? this.lastTangentY : dy;
+ const lenT0 = Math.hypot(t0x, t0y);
+ if (lenT0 > 1e-4) {
+ t0x = (t0x / lenT0) * (chordLen * 0.35);
+ t0y = (t0y / lenT0) * (chordLen * 0.35);
+ } else {
+ t0x = dx * 0.35;
+ t0y = dy * 0.35;
+ }
+
+ // Tangent at end: use current velocity vector if present, else chord direction
+ const vLen = Math.hypot(vx, vy);
+ let t1x: number;
+ let t1y: number;
+ if (vLen > 1e-4) {
+ t1x = (vx / vLen) * (chordLen * 0.35);
+ t1y = (vy / vLen) * (chordLen * 0.35);
+ } else {
+ t1x = dx * 0.35;
+ t1y = dy * 0.35;
+ }
+
+ this.segment.c1.x = pPrev.x + t0x;
+ this.segment.c1.y = pPrev.y + t0y;
+ this.segment.c1.pressure = pPrev.pressure + (pCurr.pressure - pPrev.pressure) * 0.333;
+ this.segment.c1.width = pPrev.width + (pCurr.width - pPrev.width) * 0.333;
+
+ this.segment.c2.x = pCurr.x - t1x;
+ this.segment.c2.y = pCurr.y - t1y;
+ this.segment.c2.pressure = pPrev.pressure + (pCurr.pressure - pPrev.pressure) * 0.667;
+ this.segment.c2.width = pPrev.width + (pCurr.width - pPrev.width) * 0.667;
+
+ return this.segment;
+ }
+
+ /**
+ * Evaluates exact Centripetal Catmull-Rom spline (alpha = 0.5) over knots [P0, P1, P2, P3].
+ * Converts the interior segment P1 -> P2 into cubic Bézier control points C1 and C2.
+ * Guarantees zero cusps, zero self-intersections, and monotonic curvature.
+ */
+ public generateCatmullRomSegment(
+ p0: SplinePoint,
+ p1: SplinePoint,
+ p2: SplinePoint,
+ p3: SplinePoint
+ ): CubicBezierSegment {
+ const d01 = Math.hypot(p1.x - p0.x, p1.y - p0.y);
+ const d12 = Math.hypot(p2.x - p1.x, p2.y - p1.y);
+ const d23 = Math.hypot(p3.x - p2.x, p3.y - p2.y);
+
+ // Centripetal parameterization (alpha = 0.5): dt = sqrt(chord)
+ const dt0 = Math.max(1e-4, Math.sqrt(d01));
+ const dt1 = Math.max(1e-4, Math.sqrt(d12));
+ const dt2 = Math.max(1e-4, Math.sqrt(d23));
+
+ // Tangents at P1 and P2
+ const t1x = (p2.x - p1.x) / dt1 - (p1.x - p0.x) / dt0 + (p2.x - p0.x) / (dt0 + dt1);
+ const t1y = (p2.y - p1.y) / dt1 - (p1.y - p0.y) / dt0 + (p2.y - p0.y) / (dt0 + dt1);
+
+ const t2x = (p3.x - p2.x) / dt2 - (p2.x - p1.x) / dt1 + (p3.x - p1.x) / (dt1 + dt2);
+ const t2y = (p3.y - p2.y) / dt2 - (p2.y - p1.y) / dt1 + (p3.y - p1.y) / (dt1 + dt2);
+
+ let dx1 = (t1x * dt1) / 3.0;
+ let dy1 = (t1y * dt1) / 3.0;
+ let dx2 = (t2x * dt1) / 3.0;
+ let dy2 = (t2y * dt1) / 3.0;
+
+ // Handle length clamping to prevent loop overshoot on tight turns
+ if (d12 > 1e-3) {
+ const maxHandle = d12 * 0.48;
+ const len1 = Math.hypot(dx1, dy1);
+ if (len1 > maxHandle) {
+ const s = maxHandle / len1;
+ dx1 *= s;
+ dy1 *= s;
+ }
+ const len2 = Math.hypot(dx2, dy2);
+ if (len2 > maxHandle) {
+ const s = maxHandle / len2;
+ dx2 *= s;
+ dy2 *= s;
+ }
+ }
+
+ this.segment.p0.x = p1.x;
+ this.segment.p0.y = p1.y;
+ this.segment.p0.pressure = p1.pressure;
+ this.segment.p0.width = p1.width;
+
+ this.segment.c1.x = p1.x + dx1;
+ this.segment.c1.y = p1.y + dy1;
+ this.segment.c1.pressure = p1.pressure + (p2.pressure - p0.pressure) / 6.0;
+ this.segment.c1.width = p1.width + (p2.width - p0.width) / 6.0;
+
+ this.segment.c2.x = p2.x - dx2;
+ this.segment.c2.y = p2.y - dy2;
+ this.segment.c2.pressure = p2.pressure - (p3.pressure - p1.pressure) / 6.0;
+ this.segment.c2.width = p2.width - (p3.width - p1.width) / 6.0;
+
+ this.segment.p3.x = p2.x;
+ this.segment.p3.y = p2.y;
+ this.segment.p3.pressure = p2.pressure;
+ this.segment.p3.width = p2.width;
+
+ // Cache tangent at P2 for subsequent Hermite provisional segment stitching
+ this.lastTangentX = dx2 * 3.0;
+ this.lastTangentY = dy2 * 3.0;
+ this.hasLastTangent = true;
+
+ return this.segment;
+ }
+
+ public getLastTangent(): { x: number; y: number; hasTangent: boolean } {
+ return {
+ x: this.lastTangentX,
+ y: this.lastTangentY,
+ hasTangent: this.hasLastTangent,
+ };
+ }
+}
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
new file mode 100644
index 0000000..e005838
--- /dev/null
+++ b/src/engine/StrokePipeline.ts
@@ -0,0 +1,477 @@
+/**
+ * StrokePipeline.ts
+ * High-performance, zero-allocation input ingestion and stroke rendering pipeline.
+ * Decouples pointer event handling from React, ingests coalesced events,
+ * manages 1-Euro + Corner-Snapping stabilization, provisional Hermite + Catmull-Rom stitching,
+ * speculative predictive tip overlay, and dirty-rect baking.
+ */
+
+import { InputStabilizer } from './InputStabilizer';
+import { SplineGenerator, SplinePoint, CubicBezierSegment } from './SplineGenerator';
+import { TaperEngine } from './TaperEngine';
+
+export interface ViewportTransform {
+ panX: number;
+ panY: number;
+ zoom: number;
+ rotation: number;
+ canvasWidth: number;
+ canvasHeight: number;
+}
+
+export interface DirtyRectBounds {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+}
+
+export type SegmentRenderCallback = (
+ ctx: CanvasRenderingContext2D,
+ segment: CubicBezierSegment,
+ color: string,
+ baseWidth: number,
+ isProvisional: boolean
+) => void;
+
+export class StrokePipeline {
+ private stabilizer = new InputStabilizer();
+ private splineGen = new SplineGenerator();
+ private taperEngine = new TaperEngine();
+
+ // Pre-allocated flat ring buffer for raw input coordinates to avoid GC
+ // Stride 6: [rawX, rawY, pressure, tiltX, tiltY, timestamp]
+ private static readonly BUFFER_CAPACITY = 2048;
+ private static readonly STRIDE = 6;
+ private inputRingBuffer = new Float64Array(StrokePipeline.BUFFER_CAPACITY * StrokePipeline.STRIDE);
+ private headIndex: number = 0;
+ private tailIndex: number = 0;
+
+ // Knot cache for spline stitching
+ private knotP0: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0 };
+ private knotP1: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0 };
+ private knotP2: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0 };
+ private knotP3: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0 };
+ private knotCount: number = 0;
+
+ // Dirty rect tracking (integer bounds in canvas space)
+ public dirtyRect: DirtyRectBounds = {
+ minX: Infinity,
+ minY: Infinity,
+ maxX: -Infinity,
+ maxY: -Infinity,
+ };
+
+ private isDrawing: boolean = false;
+ private activePointerId: number = -1;
+ private baseBrushSize: number = 10;
+ private strokeColor: string = '#000000';
+
+ // Canvases
+ private scratchCtx: CanvasRenderingContext2D | null = null;
+ private predictedCtx: CanvasRenderingContext2D | null = null;
+ private customRenderer: SegmentRenderCallback | null = null;
+
+ public constructor(customRenderer?: SegmentRenderCallback) {
+ if (customRenderer) {
+ this.customRenderer = customRenderer;
+ }
+ }
+
+ public setStabilizerLevel(level: number): void {
+ this.stabilizer.setStabilizerLevel(level);
+ }
+
+ public setBrushParameters(size: number, color: string): void {
+ this.baseBrushSize = Math.max(0.5, size);
+ this.strokeColor = color;
+ }
+
+ public bindContexts(
+ scratch: CanvasRenderingContext2D,
+ predicted: CanvasRenderingContext2D
+ ): void {
+ this.scratchCtx = scratch;
+ this.predictedCtx = predicted;
+ }
+
+ public resetDirtyRect(): void {
+ this.dirtyRect.minX = Infinity;
+ this.dirtyRect.minY = Infinity;
+ this.dirtyRect.maxX = -Infinity;
+ this.dirtyRect.maxY = -Infinity;
+ }
+
+ private expandDirtyRect(x: number, y: number, radius: number): void {
+ const pad = Math.ceil(radius + 4);
+ if (x - pad < this.dirtyRect.minX) this.dirtyRect.minX = Math.max(0, Math.floor(x - pad));
+ if (y - pad < this.dirtyRect.minY) this.dirtyRect.minY = Math.max(0, Math.floor(y - pad));
+ if (x + pad > this.dirtyRect.maxX) this.dirtyRect.maxX = Math.ceil(x + pad);
+ if (y + pad > this.dirtyRect.maxY) this.dirtyRect.maxY = Math.ceil(y + pad);
+ }
+
+ /**
+ * Pointer Down: resets filters and anchors stroke start without DOM overhead.
+ */
+ public onPointerDown(
+ e: PointerEvent,
+ view: ViewportTransform,
+ targetElement?: HTMLElement
+ ): void {
+ if (targetElement) {
+ try {
+ targetElement.setPointerCapture(e.pointerId);
+ } catch {}
+ }
+ this.isDrawing = true;
+ this.activePointerId = e.pointerId;
+
+ this.stabilizer.reset();
+ this.splineGen.reset();
+ this.taperEngine.reset();
+ this.resetDirtyRect();
+ this.headIndex = 0;
+ this.tailIndex = 0;
+ this.knotCount = 0;
+
+ // Ingest coalesced start points
+ this.ingestPointerEvent(e, view);
+ this.flush();
+ }
+
+ /**
+ * Pointer Move: Extracts full hardware coalesced event stack (133 - 240+ Hz).
+ * Zero React state updates or DOM allocations.
+ */
+ public onPointerMove(e: PointerEvent, view: ViewportTransform): void {
+ if (!this.isDrawing || e.pointerId !== this.activePointerId) return;
+
+ this.ingestPointerEvent(e, view);
+ this.flush();
+
+ // Speculative forward prediction on transient overlay
+ this.renderPrediction(e, view);
+ }
+
+ /**
+ * Pointer Up: Attenuates flick taper and prepares dirty rect for layer bake.
+ */
+ public onPointerUp(
+ e: PointerEvent,
+ view: ViewportTransform,
+ targetElement?: HTMLElement
+ ): DirtyRectBounds {
+ if (!this.isDrawing || e.pointerId !== this.activePointerId) {
+ return this.dirtyRect;
+ }
+
+ if (targetElement) {
+ try {
+ if (targetElement.hasPointerCapture(e.pointerId)) {
+ targetElement.releasePointerCapture(e.pointerId);
+ }
+ } catch {}
+ }
+
+ // Flush any remaining hardware points
+ this.ingestPointerEvent(e, view);
+ this.flush();
+
+ // Evaluate exit flick taper
+ if (this.knotCount >= 2 && this.scratchCtx) {
+ const exitSample = this.stabilizer.process(this.knotP2.x, this.knotP2.y, this.knotP2.pressure, e.timeStamp);
+ const flick = this.taperEngine.computeFlickTaper(
+ this.knotP2.x,
+ this.knotP2.y,
+ this.knotP2.width,
+ this.knotP2.pressure,
+ exitSample.vx,
+ exitSample.vy,
+ e.timeStamp
+ );
+
+ if (flick.count > 0) {
+ for (let i = 0; i < flick.count; i++) {
+ const pt = flick.points[i];
+ this.processStabilizedPoint(pt.x, pt.y, pt.pressure, pt.width, exitSample.vx, exitSample.vy, false);
+ }
+ }
+ }
+
+ // Clear prediction overlay canvas
+ if (this.predictedCtx) {
+ this.predictedCtx.resetTransform();
+ this.predictedCtx.clearRect(0, 0, view.canvasWidth, view.canvasHeight);
+ }
+
+ this.isDrawing = false;
+ this.activePointerId = -1;
+ return this.dirtyRect;
+ }
+
+ /**
+ * Ingests native coalesced events into flat typed array ring buffer.
+ */
+ private ingestPointerEvent(e: PointerEvent, view: ViewportTransform): void {
+ let events: PointerEvent[] | readonly PointerEvent[];
+ if (typeof e.getCoalescedEvents === 'function') {
+ const coalesced = e.getCoalescedEvents();
+ events = coalesced && coalesced.length > 0 ? coalesced : [e];
+ } else {
+ events = [e];
+ }
+
+ for (let i = 0; i < events.length; i++) {
+ const ev = events[i];
+ const coords = this.screenToCanvas(ev.clientX, ev.clientY, view);
+
+ let pressure = ev.pressure;
+ if (ev.pointerType === 'mouse') {
+ pressure = (ev.buttons & 1) ? 0.5 : 0.0;
+ }
+
+ const offset = (this.headIndex % StrokePipeline.BUFFER_CAPACITY) * StrokePipeline.STRIDE;
+ this.inputRingBuffer[offset] = coords.x;
+ this.inputRingBuffer[offset + 1] = coords.y;
+ this.inputRingBuffer[offset + 2] = pressure;
+ this.inputRingBuffer[offset + 3] = ev.tiltX || 0;
+ this.inputRingBuffer[offset + 4] = ev.tiltY || 0;
+ this.inputRingBuffer[offset + 5] = ev.timeStamp;
+
+ this.headIndex++;
+ }
+ }
+
+ /**
+ * Screen space to canvas space coordinate transformation matrix.
+ */
+ private screenToCanvas(
+ screenX: number,
+ screenY: number,
+ view: ViewportTransform
+ ): { x: number; y: number } {
+ const cx = view.canvasWidth / 2;
+ const cy = view.canvasHeight / 2;
+
+ const rad = (-view.rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+
+ const relX = (screenX - view.panX - cx) / view.zoom;
+ const relY = (screenY - view.panY - cy) / view.zoom;
+
+ return {
+ x: relX * cos - relY * sin + cx,
+ y: relX * sin + relY * cos + cy,
+ };
+ }
+
+ /**
+ * Flushes ring buffer, runs corner-snapping stabilizer, and draws splines.
+ */
+ private flush(): void {
+ if (!this.scratchCtx) return;
+
+ while (this.tailIndex < this.headIndex) {
+ const offset = (this.tailIndex % StrokePipeline.BUFFER_CAPACITY) * StrokePipeline.STRIDE;
+ const rawX = this.inputRingBuffer[offset];
+ const rawY = this.inputRingBuffer[offset + 1];
+ const rawP = this.inputRingBuffer[offset + 2];
+ const timeMs = this.inputRingBuffer[offset + 5];
+ this.tailIndex++;
+
+ // Adaptive stabilizer + S-Curve pressure response
+ const stabilized = this.stabilizer.process(rawX, rawY, rawP, timeMs);
+ const mappedPressure = this.taperEngine.mapPressure(stabilized.pressure);
+ const smoothPressure = this.taperEngine.smoothPressure(mappedPressure);
+
+ // Compute continuous stroke width
+ const width = Math.max(0.5, this.baseBrushSize * smoothPressure);
+
+ this.processStabilizedPoint(
+ stabilized.x,
+ stabilized.y,
+ smoothPressure,
+ width,
+ stabilized.vx,
+ stabilized.vy,
+ stabilized.isCorner
+ );
+ }
+ }
+
+ /**
+ * Zero-Delay Spline Pipeline with Adaptive Corner Snapping:
+ * When corner is detected (DeltaTheta > 45 deg), immediately commits sharp knot.
+ */
+ private processStabilizedPoint(
+ x: number,
+ y: number,
+ pressure: number,
+ width: number,
+ vx: number,
+ vy: number,
+ isCorner: boolean
+ ): void {
+ if (!this.scratchCtx) return;
+
+ if (isCorner && this.knotCount >= 1) {
+ const cornerPt: SplinePoint = { x, y, pressure, width };
+ const cornerSeg = this.splineGen.generateCornerSegment(this.knotP1, cornerPt);
+ this.renderSegment(this.scratchCtx, cornerSeg, false);
+ this.splineGen.commitCornerKnot(cornerPt);
+
+ this.knotP0.x = x;
+ this.knotP0.y = y;
+ this.knotP0.pressure = pressure;
+ this.knotP0.width = width;
+
+ this.knotP1.x = x;
+ this.knotP1.y = y;
+ this.knotP1.pressure = pressure;
+ this.knotP1.width = width;
+
+ this.knotCount = 1;
+ this.expandDirtyRect(x, y, width);
+ return;
+ }
+
+ if (this.knotCount === 0) {
+ this.knotP0.x = x;
+ this.knotP0.y = y;
+ this.knotP0.pressure = pressure;
+ this.knotP0.width = width;
+
+ this.knotP1.x = x;
+ this.knotP1.y = y;
+ this.knotP1.pressure = pressure;
+ this.knotP1.width = width;
+
+ this.knotCount = 1;
+ this.expandDirtyRect(x, y, width);
+ return;
+ }
+
+ if (this.knotCount === 1) {
+ this.knotP2.x = x;
+ this.knotP2.y = y;
+ this.knotP2.pressure = pressure;
+ this.knotP2.width = width;
+
+ const seg = this.splineGen.generateProvisionalSegment(this.knotP1, this.knotP2, vx, vy);
+ this.renderSegment(this.scratchCtx, seg, true);
+ this.knotCount = 2;
+ return;
+ }
+
+ // Third+ knot: [P0, P1, P2, P3]
+ this.knotP3.x = x;
+ this.knotP3.y = y;
+ this.knotP3.pressure = pressure;
+ this.knotP3.width = width;
+
+ const sealedSeg = this.splineGen.generateCatmullRomSegment(
+ this.knotP0,
+ this.knotP1,
+ this.knotP2,
+ this.knotP3
+ );
+ this.renderSegment(this.scratchCtx, sealedSeg, false);
+
+ const nextProvSeg = this.splineGen.generateProvisionalSegment(this.knotP2, this.knotP3, vx, vy);
+ this.renderSegment(this.scratchCtx, nextProvSeg, true);
+
+ // Shift window
+ this.knotP0.x = this.knotP1.x;
+ this.knotP0.y = this.knotP1.y;
+ this.knotP0.pressure = this.knotP1.pressure;
+ this.knotP0.width = this.knotP1.width;
+
+ this.knotP1.x = this.knotP2.x;
+ this.knotP1.y = this.knotP2.y;
+ this.knotP1.pressure = this.knotP2.pressure;
+ this.knotP1.width = this.knotP2.width;
+
+ this.knotP2.x = this.knotP3.x;
+ this.knotP2.y = this.knotP3.y;
+ this.knotP2.pressure = this.knotP3.pressure;
+ this.knotP2.width = this.knotP3.width;
+
+ this.knotCount++;
+ }
+
+ /**
+ * Speculative Forward Stroke Prediction:
+ * Uses seamless Hermite extrapolation matching exact brush thickness, geometry, and renderer.
+ * Completely eliminates wireframe lineTo artifacts.
+ */
+ private renderPrediction(e: PointerEvent, view: ViewportTransform): void {
+ if (!this.predictedCtx || this.knotCount < 2) return;
+
+ this.predictedCtx.resetTransform();
+ this.predictedCtx.clearRect(0, 0, view.canvasWidth, view.canvasHeight);
+
+ let predEvents: PointerEvent[] | readonly PointerEvent[] = [];
+ if (typeof e.getPredictedEvents === 'function') {
+ const pred = e.getPredictedEvents();
+ if (pred && pred.length > 0) predEvents = pred;
+ }
+
+ if (predEvents.length > 0) {
+ let prevPt = this.knotP2;
+ for (let i = 0; i < predEvents.length; i++) {
+ const ev = predEvents[i];
+ const pt = this.screenToCanvas(ev.clientX, ev.clientY, view);
+ const pVal = this.taperEngine.mapPressure(ev.pressure || 0.5);
+ const w = Math.max(0.5, this.baseBrushSize * pVal);
+ const curPt: SplinePoint = { x: pt.x, y: pt.y, pressure: pVal, width: w };
+
+ const seg = this.splineGen.generateProvisionalSegment(prevPt, curPt, 0, 0);
+ this.renderSegment(this.predictedCtx, seg, true);
+ prevPt = curPt;
+ }
+ } else {
+ // Hermite extrapolation forward along velocity vector
+ const sample = this.stabilizer.process(this.knotP2.x, this.knotP2.y, this.knotP2.pressure, e.timeStamp);
+ if (sample.speed > 0.05) {
+ const dt = 12.0; // ms forward
+ const predPt: SplinePoint = {
+ x: this.knotP2.x + sample.vx * dt,
+ y: this.knotP2.y + sample.vy * dt,
+ pressure: this.knotP2.pressure,
+ width: this.knotP2.width,
+ };
+ const seg = this.splineGen.generateProvisionalSegment(this.knotP2, predPt, sample.vx, sample.vy);
+ this.renderSegment(this.predictedCtx, seg, true);
+ }
+ }
+ }
+
+ /**
+ * Renders cubic Bézier segment with matching geometry.
+ */
+ private renderSegment(
+ ctx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ isProvisional: boolean
+ ): void {
+ if (this.customRenderer) {
+ this.customRenderer(ctx, seg, this.strokeColor, this.baseBrushSize, isProvisional);
+ } else {
+ ctx.strokeStyle = this.strokeColor;
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ ctx.lineWidth = Math.max(0.5, (seg.p0.width + seg.p3.width) * 0.5);
+
+ ctx.beginPath();
+ ctx.moveTo(seg.p0.x, seg.p0.y);
+ ctx.bezierCurveTo(seg.c1.x, seg.c1.y, seg.c2.x, seg.c2.y, seg.p3.x, seg.p3.y);
+ ctx.stroke();
+ }
+
+ this.expandDirtyRect(seg.p0.x, seg.p0.y, seg.p0.width);
+ this.expandDirtyRect(seg.c1.x, seg.c1.y, seg.c1.width);
+ this.expandDirtyRect(seg.c2.x, seg.c2.y, seg.c2.width);
+ this.expandDirtyRect(seg.p3.x, seg.p3.y, seg.p3.width);
+ }
+}
diff --git a/src/engine/TaperEngine.ts b/src/engine/TaperEngine.ts
new file mode 100644
index 0000000..e1f37b3
--- /dev/null
+++ b/src/engine/TaperEngine.ts
@@ -0,0 +1,194 @@
+/**
+ * TaperEngine.ts
+ * Japanese G-Pen S-curve pressure response (0-15% hairlines, 15-70% stable, 70-100% expansion),
+ * arc-length pressure smoothing, and exponential ballistic flick release (Iri-Nuki).
+ */
+
+export interface PressureConfig {
+ deadzone: number; // Activation deadzone [0.0, 0.15] (default 0.02)
+ gamma: number; // S-curve curvature steepness [1.0, 3.5] (default 1.85)
+ midpoint: number; // Inflection midpoint [0.1, 0.9] (default 0.45)
+ minPressure: number; // Lowest mapped non-zero pressure (hairline limit, default 0.005)
+}
+
+export interface FlickConfig {
+ minFlickSpeed: number; // Velocity threshold to trigger flick (px / ms, default ~0.70)
+ flickPoints: number; // Number of extrapolated knots (6 - 12, default 8)
+ decayRate: number; // Exponential radius attenuation constant lambda (default 0.40)
+ dragCoefficient: number; // Inertial velocity decay (default 0.22)
+ stepDtMs: number; // Extrapolation time step in ms (default 8.0)
+}
+
+export const DEFAULT_PRESSURE_CONFIG: PressureConfig = {
+ deadzone: 0.02,
+ gamma: 1.85,
+ midpoint: 0.45,
+ minPressure: 0.005,
+};
+
+export const DEFAULT_FLICK_CONFIG: FlickConfig = {
+ minFlickSpeed: 0.70,
+ flickPoints: 8,
+ decayRate: 0.42,
+ dragCoefficient: 0.22,
+ stepDtMs: 8.0,
+};
+
+export interface ExtrapolatedPoint {
+ x: number;
+ y: number;
+ pressure: number;
+ width: number;
+ alpha: number;
+ timestamp: number;
+}
+
+export class TaperEngine {
+ private pConfig: PressureConfig = { ...DEFAULT_PRESSURE_CONFIG };
+ private fConfig: FlickConfig = { ...DEFAULT_FLICK_CONFIG };
+
+ // Arc-length pressure smoothing ring buffer
+ private pressureHistory: Float32Array = new Float32Array(8);
+ private pressureHistoryCount: number = 0;
+
+ // Pre-allocated array of extrapolated flick points to avoid GC allocation
+ private flickPointPool: ExtrapolatedPoint[] = Array.from({ length: 16 }, () => ({
+ x: 0,
+ y: 0,
+ pressure: 0,
+ width: 0,
+ alpha: 1.0,
+ timestamp: 0,
+ }));
+
+ public configure(pressure?: Partial<PressureConfig>, flick?: Partial<FlickConfig>): void {
+ if (pressure) Object.assign(this.pConfig, pressure);
+ if (flick) Object.assign(this.fConfig, flick);
+ }
+
+ public reset(): void {
+ this.pressureHistoryCount = 0;
+ }
+
+ /**
+ * Applies Japanese G-Pen 3-stage cubic S-curve transfer function:
+ * - 0% - 15%: Hairline zone for delicate detailing and hatching
+ * - 15% - 70%: Stable, highly controllable line weight zone
+ * - 70% - 100%: Saturated, authoritative line expansion zone
+ */
+ public mapPressure(rawPressure: number): number {
+ if (rawPressure <= this.pConfig.deadzone) {
+ return 0.0;
+ }
+
+ // Remap [deadzone, 1.0] -> [0.0, 1.0]
+ const pNorm = (rawPressure - this.pConfig.deadzone) / (1.0 - this.pConfig.deadzone);
+ const u = Math.max(0, Math.min(1, pNorm));
+ const pMin = this.pConfig.minPressure;
+
+ // Piecewise cubic Hermite transfer curve with matched slopes
+ if (u <= 0.15) {
+ // Zone 1: Hairline zone [0.0, 0.15] -> [pMin, 0.18]
+ // Quadratic-cubic ease-in
+ const t = u / 0.15;
+ const curve = t * t * (1.5 - 0.5 * t);
+ return pMin + (0.18 - pMin) * curve;
+ } else if (u <= 0.70) {
+ // Zone 2: Stable controllable body [0.15, 0.70] -> [0.18, 0.72]
+ const t = (u - 0.15) / 0.55;
+ // Gentle linear-smooth slope
+ return 0.18 + (0.72 - 0.18) * t;
+ } else {
+ // Zone 3: Saturated expansion [0.70, 1.00] -> [0.72, 1.00]
+ const t = Math.max(0, Math.min(1.0, (u - 0.70) / 0.30));
+ // Cubic ease-out acceleration to maximum saturated weight
+ const easeOut = 1.0 - Math.pow(Math.max(0, 1.0 - t), 2.5);
+ return 0.72 + (1.00 - 0.72) * easeOut;
+ }
+ }
+
+ /**
+ * Smooths pressure along arc length independently of coordinate filtering
+ * to eliminate bumpy / sausage-like stroke artifacts.
+ */
+ public smoothPressure(currentMappedPressure: number): number {
+ const idx = this.pressureHistoryCount % this.pressureHistory.length;
+ this.pressureHistory[idx] = currentMappedPressure;
+ this.pressureHistoryCount++;
+
+ const sampleCount = Math.min(this.pressureHistoryCount, this.pressureHistory.length);
+ let sum = 0;
+ let weightSum = 0;
+
+ for (let i = 0; i < sampleCount; i++) {
+ const w = 1.0 + i * 0.4;
+ sum += this.pressureHistory[i] * w;
+ weightSum += w;
+ }
+
+ return sum / weightSum;
+ }
+
+ /**
+ * Procedurally extrapolates decaying points upon stylus liftoff (pointerup)
+ * if exit velocity exceeds the flick threshold.
+ * Synthesizes exponential decaying tail: w(k) = w0 * e^(-lambda * k), alpha(k) -> 0
+ * Prevents blunt chopped stubs and produces organic, razor-sharp hairlines (Iri-Nuki).
+ */
+ public computeFlickTaper(
+ lastX: number,
+ lastY: number,
+ lastWidth: number,
+ lastPressure: number,
+ exitVx: number, // px / ms
+ exitVy: number, // px / ms
+ lastTimestampMs: number
+ ): { points: ExtrapolatedPoint[]; count: number } {
+ const exitSpeed = Math.hypot(exitVx, exitVy); // px / ms
+
+ if (exitSpeed < this.fConfig.minFlickSpeed || lastWidth <= 0.4) {
+ return { points: this.flickPointPool, count: 0 };
+ }
+
+ const dirX = exitVx / exitSpeed;
+ const dirY = exitVy / exitSpeed;
+
+ const count = Math.min(this.fConfig.flickPoints, this.flickPointPool.length);
+ let curX = lastX;
+ let curY = lastY;
+ let curSpeed = exitSpeed;
+ let curTime = lastTimestampMs;
+
+ const dt = this.fConfig.stepDtMs;
+ const lambda = this.fConfig.decayRate;
+
+ for (let i = 0; i < count; i++) {
+ // Inertial damping on velocity: v(t) = v0 * exp(-drag * t)
+ const dragFactor = Math.exp(-this.fConfig.dragCoefficient * (dt * 0.05));
+ curSpeed *= dragFactor;
+ const stepDist = curSpeed * dt;
+
+ curX += dirX * stepDist;
+ curY += dirY * stepDist;
+ curTime += dt;
+
+ // Exponential attenuation of radius: w(k) = w0 * exp(-lambda * (k + 1))
+ const k = i + 1;
+ const decayFactor = Math.exp(-lambda * k);
+ const curWidth = Math.max(0.1, lastWidth * decayFactor);
+ const curPressure = Math.max(0.001, lastPressure * decayFactor);
+ // Alpha decays smoothly to 0 at the tail tip
+ const curAlpha = Math.max(0.0, 1.0 - (k / (count + 1)));
+
+ const pt = this.flickPointPool[i];
+ pt.x = curX;
+ pt.y = curY;
+ pt.width = curWidth;
+ pt.pressure = curPressure;
+ pt.alpha = curAlpha;
+ pt.timestamp = curTime;
+ }
+
+ return { points: this.flickPointPool, count };
+ }
+}
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index 00ab29d..727cf61 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -29,15 +29,17 @@ import {
catmullRomToBezier,
drawDot,
screenToCanvas,
+ getCanvasToViewportMatrix,
createCanvasThumbnail,
formatTime,
get2DContext,
- getCanvasToViewportMatrix,
getReusableBakeCanvas,
renderCompleteStroke,
applyParametricTaper,
} from '../utils/canvasUtils';
-import { enforceColorMode, binarizeCanvasRect } from '../utils/colorUtils';
+import { InputStabilizer } from '../engine/InputStabilizer';
+import { TaperEngine } from '../engine/TaperEngine';
+import { enforceColorMode, binarizeCanvasRect, binarizeImageDataBuffer } from '../utils/colorUtils';
import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
import {
drawTexturedCubicBezierSegment,
@@ -49,7 +51,6 @@ import { PaintReservoir, LayerPixelSampler } from '../utils/colorMixingEngine';
import { applyLayerEffects } from '../utils/layerEffectsEngine';
import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
import { PerspectiveSnapSession } from '../utils/perspectiveSnapping';
-import { WebGlBrushEngine } from '../utils/webglBrushEngine';
interface UseCanvasDrawingProps {
tool: ToolType;
@@ -132,6 +133,9 @@ export function useCanvasDrawing({
return null;
}, [effectiveDraftCanvasRef, predictedCanvasRef]);
+ const isPredictedCanvasDirtyRef = useRef(false);
+ const latestPredictedRef = useRef<{ predEvents: PointerEvent[]; vRect: DOMRect } | null>(null);
+
const clearPredictedCanvas = useCallback(() => {
const pCanvas = getPredictedCanvas();
if (pCanvas) {
@@ -141,6 +145,7 @@ export function useCanvasDrawing({
pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
}
}
+ isPredictedCanvasDirtyRef.current = false;
}, [getPredictedCanvas]);
// Top overlay interaction reference for pointer capture and events
@@ -188,6 +193,25 @@ export function useCanvasDrawing({
onActiveConstraintAxisChangeRef.current = onActiveConstraintAxisChange;
const snapSessionRef = useRef(new PerspectiveSnapSession());
+ const lastEmittedAxisRef = useRef<ConstraintAxis | null>(null);
+ const emitConstraintAxisChange = useCallback((newAxis: ConstraintAxis | null) => {
+ const prev = lastEmittedAxisRef.current;
+ if (prev === newAxis) return;
+ if (
+ prev &&
+ newAxis &&
+ prev.type === newAxis.type &&
+ prev.origin.x === newAxis.origin.x &&
+ prev.origin.y === newAxis.origin.y &&
+ prev.dir.x === newAxis.dir.x &&
+ prev.dir.y === newAxis.dir.y
+ ) {
+ return;
+ }
+ lastEmittedAxisRef.current = newAxis;
+ onActiveConstraintAxisChangeRef.current?.(newAxis);
+ }, []);
+
useEffect(() => {
panRef.current = pan;
zoomRef.current = zoom;
@@ -222,6 +246,8 @@ export function useCanvasDrawing({
// Stabilizer tracking ref
const stabilizedPointRef = useRef<Point | null>(null);
+ const inputStabilizerRef = useRef(new InputStabilizer());
+ const taperEngineRef = useRef(new TaperEngine());
// Distance accumulator for textured brush dab stepping
const stampRemainderDistRef = useRef<number>(0);
@@ -231,6 +257,7 @@ export function useCanvasDrawing({
const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
const strokeBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);
const dedicatedBackupCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const docDraftCanvasRef = useRef<HTMLCanvasElement | null>(null);
const getDedicatedBackupCanvas = useCallback((width: number, height: number): HTMLCanvasElement => {
if (!dedicatedBackupCanvasRef.current) {
@@ -244,6 +271,18 @@ export function useCanvasDrawing({
return c;
}, []);
+ const getDocDraftCanvas = useCallback((width: number, height: number): HTMLCanvasElement => {
+ if (!docDraftCanvasRef.current) {
+ docDraftCanvasRef.current = document.createElement('canvas');
+ }
+ const c = docDraftCanvasRef.current;
+ if (c.width !== width || c.height !== height) {
+ c.width = width;
+ c.height = height;
+ }
+ return c;
+ }, []);
+
const isWetColorStrokeRef = useRef<boolean>(false);
const drewDirectlyOnLayerCanvasRef = useRef<boolean>(false);
const lastPointTimeRef = useRef<number>(0);
@@ -470,6 +509,51 @@ export function useCanvasDrawing({
[getActiveCanvas, layerCanvasesRef, syncHistoryState]
);
+ // Background history serialization queue to eliminate main-thread hitches on stroke lift-off
+ const pendingHistoryTasksRef = useRef<Array<() => void>>([]);
+ const idleCallbackIdRef = useRef<any>(null);
+
+ const flushPendingHistoryTasks = useCallback(() => {
+ if (idleCallbackIdRef.current !== null) {
+ if (typeof window !== 'undefined' && 'cancelIdleCallback' in window) {
+ (window as any).cancelIdleCallback(idleCallbackIdRef.current);
+ } else {
+ clearTimeout(idleCallbackIdRef.current);
+ }
+ idleCallbackIdRef.current = null;
+ }
+ const tasks = pendingHistoryTasksRef.current.splice(0);
+ for (const task of tasks) {
+ try {
+ task();
+ } catch (err) {
+ console.warn('[History] Error flushing pending history task:', err);
+ }
+ }
+ }, []);
+
+ const enqueueHistoryTask = useCallback((task: () => void) => {
+ pendingHistoryTasksRef.current.push(task);
+ if (idleCallbackIdRef.current === null) {
+ const runTasks = () => {
+ idleCallbackIdRef.current = null;
+ const tasks = pendingHistoryTasksRef.current.splice(0);
+ for (const t of tasks) {
+ try {
+ t();
+ } catch (err) {
+ console.warn('[History] Error running idle history task:', err);
+ }
+ }
+ };
+ if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
+ idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 120 });
+ } else {
+ idleCallbackIdRef.current = setTimeout(runTasks, 0);
+ }
+ }
+ }, []);
+
// Abort any in-progress stroke session immediately
const abortActiveStroke = useCallback(() => {
if (!isDrawingRef.current) return;
@@ -488,6 +572,10 @@ export function useCanvasDrawing({
dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
}
}
+ if (docDraftCanvasRef.current) {
+ const docCtx = get2DContext(docDraftCanvasRef.current);
+ docCtx?.clearRect(0, 0, docDraftCanvasRef.current.width, docDraftCanvasRef.current.height);
+ }
clearPredictedCanvas();
if (drewDirectlyOnLayerCanvasRef.current && strokeBackupCanvasRef.current) {
const currentLayerId = activeLayerIdRef.current;
@@ -514,12 +602,13 @@ export function useCanvasDrawing({
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
snapSessionRef.current.endStroke();
- onActiveConstraintAxisChangeRef.current?.(null);
- }, [clearPredictedCanvas, effectiveDraftCanvasRef, getActiveCanvas, layerCanvasesRef]);
+ emitConstraintAxisChange(null);
+ }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange, getActiveCanvas, layerCanvasesRef]);
// Jump directly to any past or future history step
const jumpToHistoryIndex = useCallback(
async (targetIndex: number) => {
+ flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStroke();
}
@@ -762,30 +851,33 @@ export function useCanvasDrawing({
syncHistoryState();
globalTileGrid.notifyChange(true);
},
- [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, getActiveCanvas, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
);
// Undo action
const undo = useCallback(() => {
+ flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStroke();
}
if (historyIndexRef.current <= 0) return;
jumpToHistoryIndex(historyIndexRef.current - 1);
- }, [abortActiveStroke, jumpToHistoryIndex]);
+ }, [abortActiveStroke, flushPendingHistoryTasks, jumpToHistoryIndex]);
// Redo action
const redo = useCallback(() => {
+ flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStroke();
}
if (historyIndexRef.current >= historyRef.current.length - 1) return;
jumpToHistoryIndex(historyIndexRef.current + 1);
- }, [abortActiveStroke, jumpToHistoryIndex]);
+ }, [abortActiveStroke, flushPendingHistoryTasks, jumpToHistoryIndex]);
// Selective Undo per Peer
const selectiveUndo = useCallback(
async (peerIdToUndo?: string | number) => {
+ flushPendingHistoryTasks();
if (isDrawingRef.current) {
abortActiveStroke();
}
@@ -852,7 +944,7 @@ export function useCanvasDrawing({
}
globalTileGrid.notifyChange(true);
},
- [abortActiveStroke, activeLayerId, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
+ [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, getActiveCanvas, layerCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
);
// Clear active layer action
@@ -974,35 +1066,6 @@ export function useCanvasDrawing({
// Render a single smooth segment onto the draft overlay context using Catmull-Rom cubic splines
const renderDraftSegment = useCallback((draftCtx: CanvasRenderingContext2D, point: Point) => {
const pts = strokePointsRef.current;
- pts.push(point);
-
- if (pts.length < 3) {
- return;
- }
-
- let k0: Point, k1: Point, k2: Point, k3: Point;
- if (pts.length === 3) {
- // First segment: P0 -> P1 with knots (P0, P0, P1, P2)
- k0 = pts[0];
- k1 = pts[0];
- k2 = pts[1];
- k3 = pts[2];
- } else {
- // Subsequent segments: P_{n-2} -> P_{n-1} with knots (P_{n-3}, P_{n-2}, P_{n-1}, P_n)
- const n = pts.length;
- k0 = pts[n - 4];
- k1 = pts[n - 3];
- k2 = pts[n - 2];
- k3 = pts[n - 1];
- }
-
- if (pts.length > 5) {
- pts.shift();
- }
-
- const { c1, c2 } = catmullRomToBezier(k0, k1, k2, k3);
- const segStart = k1;
- const segEnd = k2;
const isEraser = toolRef.current === 'eraser';
const isBgEraser = isEraser && activeLayerIdRef.current === 'layer-bg';
@@ -1039,117 +1102,7 @@ export function useCanvasDrawing({
const strokeFlow = bs.flow ?? 1.0;
const strokeSpacing = bs.spacing ?? 0.08;
- if (isEraser) {
- drewDirectlyOnLayerCanvasRef.current = true;
- if (canvas) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- drawSmoothCubicBezierSegment(
- cCtx,
- segStart,
- c1,
- c2,
- segEnd,
- strokeColor,
- !isBgEraser,
- strokeHardness,
- strokeFlow,
- strokeSpacing
- );
- }
- }
- if (isToneLayer && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- drawSmoothCubicBezierSegment(
- sCtx,
- segStart,
- c1,
- c2,
- segEnd,
- strokeColor,
- !isBgEraser,
- strokeHardness,
- strokeFlow,
- strokeSpacing
- );
- }
- }
-
- // Simultaneously render eraser's path preview on draftCtx with dashed outline for immediate visual feedback
- draftCtx.save();
- draftCtx.lineCap = 'round';
- draftCtx.lineJoin = 'round';
- draftCtx.setLineDash([4, 4]);
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.lineWidth = Math.max(1, (segStart.width + segEnd.width) / 2);
- draftCtx.beginPath();
- draftCtx.moveTo(segStart.x, segStart.y);
- draftCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, segEnd.x, segEnd.y);
- draftCtx.stroke();
- draftCtx.restore();
- return;
- }
-
- // Always render the live stroke onto the draft canvas overlay for zero-latency 120 FPS feedback
- const targetCtx = draftCtx;
- drewDirectlyOnLayerCanvasRef.current = false;
-
- const dims = dimensionsRef.current;
- const gpuEngine = (bs.useGpu !== false) ? WebGlBrushEngine.getInstance() : null;
- const canUseGpu = Boolean(
- gpuEngine &&
- gpuEngine.isAvailable() &&
- !isEraser &&
- !isPencil &&
- !isMaskModeRef.current &&
- !activeLayer?.alphaLocked
- );
-
- let renderedWithGpu = false;
- if (canUseGpu && gpuEngine) {
- const midT = 0.5;
- const invMidT = 0.5;
- const midX = invMidT * invMidT * invMidT * segStart.x + 3 * invMidT * invMidT * midT * c1.x + 3 * invMidT * midT * midT * c2.x + midT * midT * midT * segEnd.x;
- const midY = invMidT * invMidT * invMidT * segStart.y + 3 * invMidT * invMidT * midT * c1.y + 3 * invMidT * midT * midT * c2.y + midT * midT * midT * segEnd.y;
- const midP = 0.5 * (segStart.pressure + segEnd.pressure);
- const midW = 0.5 * (segStart.width + segEnd.width);
- const midPt: Point = {
- x: midX,
- y: midY,
- pressure: midP,
- width: midW,
- tiltX: 0.5 * ((segStart.tiltX ?? 0) + (segEnd.tiltX ?? 0)),
- tiltY: 0.5 * ((segStart.tiltY ?? 0) + (segEnd.tiltY ?? 0)),
- };
-
- const ctrl1: Point = {
- x: (3 * c1.x - segStart.x) / 2,
- y: (3 * c1.y - segStart.y) / 2,
- pressure: 0.5 * (segStart.pressure + midP),
- width: 0.5 * (segStart.width + midW),
- };
- const ctrl2: Point = {
- x: (3 * c2.x - segEnd.x) / 2,
- y: (3 * c2.y - segEnd.y) / 2,
- pressure: 0.5 * (midP + segEnd.pressure),
- width: 0.5 * (midW + segEnd.width),
- };
-
- const res1 = gpuEngine.generateArcLengthDabs(segStart, ctrl1, midPt, bs, strokeColor, stampRemainderDistRef.current, strokeTotalDistanceRef.current);
- const res2 = gpuEngine.generateArcLengthDabs(midPt, ctrl2, segEnd, bs, strokeColor, res1.remainderDist, res1.totalStrokeDist);
- stampRemainderDistRef.current = res2.remainderDist;
- strokeTotalDistanceRef.current = res2.totalStrokeDist;
-
- const dabs = res1.dabs.concat(res2.dabs);
- if (dabs.length > 0) {
- renderedWithGpu = gpuEngine.renderDabsToContext(targetCtx, dabs, bs, toolRef.current, dims.width, dims.height, canvas || undefined);
- } else {
- renderedWithGpu = true;
- }
- }
-
- if (!renderedWithGpu) {
+ const renderSegmentToContext = (ctx: CanvasRenderingContext2D, sStart: Point, c1Pt: Point, c2Pt: Point, sEnd: Point): number => {
if (bs.customTipImage) {
const tipOptions: TexturedBrushOptions = {
size: bs.size,
@@ -1174,6 +1127,7 @@ export function useCanvasDrawing({
spray: bs.spray,
taper: bs.taper,
colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
amountOfPaint: bs.amountOfPaint,
densityOfPaint: bs.densityOfPaint,
colorStretch: bs.colorStretch,
@@ -1186,6 +1140,9 @@ export function useCanvasDrawing({
paperTextureImage: bs.paperTextureImage,
paperTextureScale: bs.paperTextureScale,
paperTextureRotate: bs.paperTextureRotate,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
useGpu: bs.useGpu,
underlyingCanvas: canvas || undefined,
sampler: layerPixelSamplerRef.current || undefined,
@@ -1199,12 +1156,12 @@ export function useCanvasDrawing({
secondaryColor: bs.secondaryColor,
};
- stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
- targetCtx,
- segStart,
- c1,
- c2,
- segEnd,
+ return drawTexturedCubicBezierSegment(
+ ctx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
strokeColor,
bs.customTipImage,
tipOptions,
@@ -1212,19 +1169,16 @@ export function useCanvasDrawing({
);
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- const pFlow = bs.flow ?? 0.74;
- const pGrain = bs.grain ?? 1.0;
-
- stampRemainderDistRef.current = drawPencilCubicBezierSegment(
- targetCtx,
- segStart,
- c1,
- c2,
- segEnd,
+ return drawPencilCubicBezierSegment(
+ ctx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
strokeColor,
grade,
- pFlow,
- pGrain,
+ bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
bs.hardness,
stampRemainderDistRef.current,
Boolean(activeLayer?.alphaLocked),
@@ -1233,6 +1187,7 @@ export function useCanvasDrawing({
} else {
const radialMixingOptions: RadialMixingOptions = {
colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
amountOfPaint: bs.amountOfPaint,
densityOfPaint: bs.densityOfPaint,
colorStretch: bs.colorStretch,
@@ -1244,13 +1199,17 @@ export function useCanvasDrawing({
isTransparentInk: Boolean(bs.isTransparentInk),
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
+ useGpu: bs.useGpu,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
};
- stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
- targetCtx,
- segStart,
- c1,
- c2,
- segEnd,
+ return drawSmoothCubicBezierSegment(
+ ctx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
strokeColor,
isEraser && !isBgEraser,
strokeHardness,
@@ -1262,17 +1221,129 @@ export function useCanvasDrawing({
radialMixingOptions
);
}
+ };
+
+ pts.push(point);
+
+ if (pts.length < 3) {
+ return;
+ }
+
+ let k0: Point, k1: Point, k2: Point, k3: Point;
+ if (pts.length === 3) {
+ k0 = pts[0];
+ k1 = pts[0];
+ k2 = pts[1];
+ k3 = pts[2];
+ } else {
+ const n = pts.length;
+ k0 = pts[n - 4];
+ k1 = pts[n - 3];
+ k2 = pts[n - 2];
+ k3 = pts[n - 1];
+ }
+
+ if (pts.length > 5) {
+ pts.shift();
+ }
+
+ const { c1, c2 } = catmullRomToBezier(k0, k1, k2, k3);
+ const segStart = k1;
+ const segEnd = k2;
+
+ if (isEraser) {
+ drewDirectlyOnLayerCanvasRef.current = true;
+ if (canvas) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ drawSmoothCubicBezierSegment(
+ cCtx,
+ segStart,
+ c1,
+ c2,
+ segEnd,
+ strokeColor,
+ !isBgEraser,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing
+ );
+ }
+ }
+ if (isToneLayer && sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ drawSmoothCubicBezierSegment(
+ sCtx,
+ segStart,
+ c1,
+ c2,
+ segEnd,
+ strokeColor,
+ !isBgEraser,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing
+ );
+ }
+ }
+
+ // Eraser path preview on draft overlay
+ draftCtx.save();
+ draftCtx.lineCap = 'round';
+ draftCtx.lineJoin = 'round';
+ draftCtx.setLineDash([4, 4]);
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.lineWidth = Math.max(1, (segStart.width + segEnd.width) / 2);
+ draftCtx.beginPath();
+ draftCtx.moveTo(segStart.x, segStart.y);
+ draftCtx.bezierCurveTo(c1.x, c1.y, c2.x, c2.y, segEnd.x, segEnd.y);
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ // Single-pass document draft rendering + dirty-ROI blit to draft overlay (50% less CPU/GPU work & 100% identical scatter/reservoir state)
+ drewDirectlyOnLayerCanvasRef.current = false;
+ const docDraftCanvas = docDraftCanvasRef.current;
+ const docCtx = docDraftCanvas ? get2DContext(docDraftCanvas) : null;
+ if (docCtx && docDraftCanvas) {
+ stampRemainderDistRef.current = renderSegmentToContext(docCtx, segStart, c1, c2, segEnd);
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const maxW = Math.max(segStart.width, segEnd.width, bs.size || 10) * (1.5 + scatterFactor * 2) + 24;
+ const sx = Math.max(0, Math.floor(Math.min(segStart.x, c1.x, c2.x, segEnd.x) - maxW));
+ const sy = Math.max(0, Math.floor(Math.min(segStart.y, c1.y, c2.y, segEnd.y) - maxW));
+ const ex = Math.min(docDraftCanvas.width, Math.ceil(Math.max(segStart.x, c1.x, c2.x, segEnd.x) + maxW));
+ const ey = Math.min(docDraftCanvas.height, Math.ceil(Math.max(segStart.y, c1.y, c2.y, segEnd.y) + maxW));
+ const sw = ex - sx;
+ const sh = ey - sy;
+ if (sw > 0 && sh > 0) {
+ draftCtx.clearRect(sx, sy, sw, sh);
+ draftCtx.drawImage(docDraftCanvas, sx, sy, sw, sh, sx, sy, sw, sh);
+ }
+ } else {
+ stampRemainderDistRef.current = renderSegmentToContext(draftCtx, segStart, c1, c2, segEnd);
}
}, [getActiveCanvas]);
// Stabilize and render point onto draft canvas
const applyStabilizedPointAndRender = useCallback(
- (draftCtx: CanvasRenderingContext2D, rawX: number, rawY: number, rawPressure: number, pointerType: string, rawTiltX: number = 0, rawTiltY: number = 0, rawTwist: number = 0, timestamp?: number) => {
+ (
+ draftCtx: CanvasRenderingContext2D,
+ rawX: number,
+ rawY: number,
+ rawPressure: number,
+ pointerType: string,
+ rawTiltX: number = 0,
+ rawTiltY: number = 0,
+ rawTwist: number = 0,
+ timestamp?: number
+ ) => {
const bs = brushSettingsRef.current;
const dims = dimensionsRef.current;
const stab = Math.min(50, Math.max(0, bs.stabilization ?? 0));
- const now = performance.now();
+ const now = timestamp ?? performance.now();
const dt = Math.max(1, now - (lastPointTimeRef.current || now));
lastPointTimeRef.current = now;
@@ -1283,14 +1354,12 @@ export function useCanvasDrawing({
velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
}
- rawPointsBufferRef.current.push({ x: rawX, y: rawY, pressure: rawPressure, pointerType, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist, timestamp });
-
let pt: Point;
if (stab <= 0) {
- rawPointsBufferRef.current.length = 0;
+ const mappedP = bs.usePressure ? taperEngineRef.current.mapPressure(rawPressure) : (rawPressure > 0 ? 1.0 : 0);
const width = calculateStrokeWidth(
bs.size,
- rawPressure,
+ mappedP,
bs.minSizeFactor,
bs.usePressure,
pointerType,
@@ -1298,37 +1367,14 @@ export function useCanvasDrawing({
velocityScale,
bs.pressureCurve
);
- pt = { x: rawX, y: rawY, pressure: rawPressure, width, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist, timestamp };
+ pt = { x: rawX, y: rawY, pressure: mappedP, width, tiltX: rawTiltX, tiltY: rawTiltY, twist: rawTwist, timestamp: now, isCorner: false };
stabilizedPointRef.current = pt;
} else {
- const buf = rawPointsBufferRef.current;
- const maxW = Math.min(8, Math.max(3, 1 + 2 * Math.floor(stab / 8)));
- if (buf.length > maxW) {
- buf.shift();
- }
-
- const len = buf.length;
- let sumX = 0, sumY = 0, sumP = 0, sumTiltX = 0, sumTiltY = 0, sumTwist = 0, sumW = 0;
- for (let i = 0; i < len; i++) {
- const w = Math.pow(1.65, i);
- sumX += buf[i].x * w;
- sumY += buf[i].y * w;
- sumP += buf[i].pressure * w;
- sumTiltX += (buf[i].tiltX ?? 0) * w;
- sumTiltY += (buf[i].tiltY ?? 0) * w;
- sumTwist += (buf[i].twist ?? 0) * w;
- sumW += w;
- }
-
- const smoothX = sumX / sumW;
- const smoothY = sumY / sumW;
- const smoothPressure = sumP / sumW;
- const smoothTiltX = sumTiltX / sumW;
- const smoothTiltY = sumTiltY / sumW;
- const smoothTwist = sumTwist / sumW;
+ const sample = inputStabilizerRef.current.process(rawX, rawY, rawPressure, now);
+ const mappedP = bs.usePressure ? taperEngineRef.current.mapPressure(sample.pressure) : (rawPressure > 0 ? 1.0 : 0);
const smoothWidth = calculateStrokeWidth(
bs.size,
- smoothPressure,
+ mappedP,
bs.minSizeFactor,
bs.usePressure,
pointerType,
@@ -1336,7 +1382,17 @@ export function useCanvasDrawing({
velocityScale,
bs.pressureCurve
);
- pt = { x: smoothX, y: smoothY, pressure: smoothPressure, width: smoothWidth, tiltX: smoothTiltX, tiltY: smoothTiltY, twist: smoothTwist, timestamp };
+ pt = {
+ x: sample.x,
+ y: sample.y,
+ pressure: mappedP,
+ width: smoothWidth,
+ tiltX: rawTiltX,
+ tiltY: rawTiltY,
+ twist: rawTwist,
+ timestamp: now,
+ isCorner: sample.isCorner,
+ };
stabilizedPointRef.current = pt;
}
@@ -1366,20 +1422,80 @@ export function useCanvasDrawing({
[renderDraftSegment]
);
+ // Low-latency speculative predicted tip overlay with tangent/distance guard to prevent stray streaks
+ const renderPredictedStroke = useCallback(
+ (predEvents: PointerEvent[], vRect: DOMRect) => {
+ clearPredictedCanvas();
+ if (!predEvents || predEvents.length === 0 || toolRef.current === 'eraser') return;
+ const pCanvas = getPredictedCanvas();
+ const lastPt = stabilizedPointRef.current;
+ if (!pCanvas || !lastPt) return;
+ const pCtx = get2DContext(pCanvas);
+ if (!pCtx) return;
+
+ const bs = brushSettingsRef.current;
+ const dims = dimensionsRef.current;
+ const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+
+ const ev = predEvents[0];
+ const rawPred = screenToCanvas(
+ ev.clientX,
+ ev.clientY,
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims
+ );
+ const dx = rawPred.x - lastPt.x;
+ const dy = rawPred.y - lastPt.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist < 0.5 || dist > maxPredDist * 2.5) return;
+
+ const clampedScale = dist > maxPredDist ? maxPredDist / dist : 1.0;
+ const targetX = lastPt.x + dx * clampedScale;
+ const targetY = lastPt.y + dy * clampedScale;
+
+ pCtx.save();
+ pCtx.globalAlpha = Math.min(0.65, (bs.opacity ?? 1.0) * 0.65);
+ pCtx.strokeStyle = bs.color || '#000000';
+ pCtx.lineCap = 'round';
+ pCtx.lineWidth = Math.max(0.5, lastPt.width * 0.85);
+ pCtx.beginPath();
+ pCtx.moveTo(lastPt.x, lastPt.y);
+ pCtx.lineTo(targetX, targetY);
+ pCtx.stroke();
+ pCtx.restore();
+ },
+ [clearPredictedCanvas, getPredictedCanvas]
+ );
+
// Flush batched points on requestAnimationFrame
const flushPendingPoints = useCallback(() => {
drawRafIdRef.current = null;
if (!isDrawingRef.current) return;
const queue = pendingPointsQueueRef.current;
- if (queue.length === 0) return;
+ if (queue.length === 0) {
+ // Update predicted stroke overlay throttled to rAF
+ const predData = latestPredictedRef.current;
+ latestPredictedRef.current = null;
+ const vRect = getViewportRect();
+ if (vRect && allStrokePointsRef.current.length > 0) {
+ renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ isPredictedCanvasDirtyRef.current = true;
+ } else if (isPredictedCanvasDirtyRef.current) {
+ clearPredictedCanvas();
+ }
+ return;
+ }
const draftCanvas = effectiveDraftCanvasRef?.current;
if (!draftCanvas) return;
const draftCtx = get2DContext(draftCanvas);
if (!draftCtx) return;
- const batch = queue.splice(0, queue.length);
+ const queueLen = queue.length;
const chunkPts: Point[] = [];
let batchMinX = Infinity;
let batchMinY = Infinity;
@@ -1387,9 +1503,19 @@ export function useCanvasDrawing({
let batchMaxY = -Infinity;
let maxStrokeWidth = 0;
- for (let i = 0; i < batch.length; i++) {
- const item = batch[i];
- applyStabilizedPointAndRender(draftCtx, item.x, item.y, item.pressure, item.pointerType, item.tiltX, item.tiltY, item.twist, item.timestamp);
+ for (let i = 0; i < queueLen; i++) {
+ const item = queue[i];
+ applyStabilizedPointAndRender(
+ draftCtx,
+ item.x,
+ item.y,
+ item.pressure,
+ item.pointerType,
+ item.tiltX,
+ item.tiltY,
+ item.twist,
+ item.timestamp
+ );
if (allStrokePointsRef.current.length > 0) {
const lastPt = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
chunkPts.push(lastPt);
@@ -1400,22 +1526,16 @@ export function useCanvasDrawing({
maxStrokeWidth = Math.max(maxStrokeWidth, lastPt.width);
}
}
+ queue.length = 0;
+
if (batchMinX <= batchMaxX) {
- const currentLayerId = activeLayerIdRef.current;
- const canvas = getActiveCanvas();
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isToneLayer = Boolean(activeLayer?.toneEnabled);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = colorModeRef.current === 'monochrome' || isMonoLayer;
const dims = dimensionsRef.current;
const margin = Math.ceil(maxStrokeWidth * 1.5 + 32);
const segMinX = Math.max(0, Math.floor(batchMinX - margin));
const segMinY = Math.max(0, Math.floor(batchMinY - margin));
const segMaxX = Math.min(dims.width, Math.ceil(batchMaxX + margin));
const segMaxY = Math.min(dims.height, Math.ceil(batchMaxY + margin));
- const segW = segMaxX - segMinX;
- const segH = segMaxY - segMinY;
if (dirtyRectRef.current) {
dirtyRectRef.current.minX = Math.min(dirtyRectRef.current.minX, segMinX);
@@ -1423,53 +1543,30 @@ export function useCanvasDrawing({
dirtyRectRef.current.maxX = Math.max(dirtyRectRef.current.maxX, segMaxX);
dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, segMaxY);
}
-
- if (segW > 0 && segH > 0 && canvas) {
- if (isMonochrome) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- binarizeCanvasRect(
- cCtx,
- { x: segMinX, y: segMinY, width: segW, height: segH },
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const sourceCanvas = layerSourceCanvasesRef.current.get(currentLayerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.clearRect(segMinX, segMinY, segW, segH);
- sCtx.drawImage(canvas, segMinX, segMinY, segW, segH, segMinX, segMinY, segW, segH);
- }
- }
- }
- } else if (isToneLayer && isToneStrokeRef.current) {
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId);
- if (sourceCanvas && activeLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dims.dpi ?? 600,
- {
- x: segMinX,
- y: segMinY,
- width: segW,
- height: segH,
- }
- );
- }
- }
- }
}
if (currentStrokeIdRef.current && chunkPts.length > 0) {
onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
}
- }, [applyStabilizedPointAndRender, effectiveDraftCanvasRef, getActiveCanvas, layerSourceCanvasesRef]);
+
+ // Update predicted stroke overlay throttled to rAF
+ const predData = latestPredictedRef.current;
+ latestPredictedRef.current = null;
+ const vRect = getViewportRect();
+ if (vRect && allStrokePointsRef.current.length > 0) {
+ renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ isPredictedCanvasDirtyRef.current = true;
+ } else if (isPredictedCanvasDirtyRef.current) {
+ clearPredictedCanvas();
+ }
+ }, [
+ applyStabilizedPointAndRender,
+ clearPredictedCanvas,
+ effectiveDraftCanvasRef,
+ getActiveCanvas,
+ getViewportRect,
+ renderPredictedStroke,
+ ]);
// Pointer Down handler: initialize lightweight live stroke overlay without touching base canvas
@@ -1478,6 +1575,7 @@ export function useCanvasDrawing({
const isBrushOrEraser = toolRef.current === 'brush' || toolRef.current === 'eraser';
if (!isBrushOrEraser || disabled || e.button !== 0 || activeLayerLockedRef.current || !activeLayerVisibleRef.current) return;
e.preventDefault();
+ flushPendingHistoryTasks();
const canvas = getActiveCanvas();
if (!canvas) return;
@@ -1485,6 +1583,7 @@ export function useCanvasDrawing({
const vRect = getViewportRect();
if (!vRect) return;
+ const dims = dimensionsRef.current;
const draftCanvas = effectiveDraftCanvasRef?.current;
if (!draftCanvas) return;
@@ -1499,25 +1598,15 @@ export function useCanvasDrawing({
clearDraftRafRef.current = null;
}
- // Ensure draft canvas buffer resolution matches screen viewport * DPR
- const dpr = window.devicePixelRatio || 1;
- const targetW = Math.max(1, Math.ceil(vRect.width * dpr));
- const targetH = Math.max(1, Math.ceil(vRect.height * dpr));
- if (draftCanvas.width !== targetW || draftCanvas.height !== targetH) {
- draftCanvas.width = targetW;
- draftCanvas.height = targetH;
- }
-
const draftCtx = get2DContext(draftCanvas);
if (!draftCtx) return;
- // Reset and configure draft canvas matrix & clipping to artboard
+ // Reset and clear draft canvas with viewport transform
draftCtx.resetTransform();
draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
const scaleX = draftCanvas.width / vRect.width;
const scaleY = draftCanvas.height / vRect.height;
-
const matrix = getCanvasToViewportMatrix(
panRef.current,
zoomRef.current,
@@ -1533,23 +1622,6 @@ export function useCanvasDrawing({
draftCtx.clip();
clearPredictedCanvas();
- const pCanvas = getPredictedCanvas();
- if (pCanvas) {
- if (pCanvas.width !== targetW || pCanvas.height !== targetH) {
- pCanvas.width = targetW;
- pCanvas.height = targetH;
- }
- const pCtx = get2DContext(pCanvas);
- if (pCtx) {
- pCtx.resetTransform();
- pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
- pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
- pCtx.save();
- pCtx.beginPath();
- pCtx.rect(0, 0, dimensionsRef.current.width, dimensionsRef.current.height);
- pCtx.clip();
- }
- }
const isEraser = toolRef.current === 'eraser';
const isBgEraser = isEraser && activeLayerIdRef.current === 'layer-bg';
@@ -1558,7 +1630,6 @@ export function useCanvasDrawing({
const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
const bs = brushSettingsRef.current;
const mode = colorModeRef.current;
- const dims = dimensionsRef.current;
const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
const isToneLayer = Boolean(activeLayer?.toneEnabled);
@@ -1598,10 +1669,13 @@ export function useCanvasDrawing({
const rawStartPoint = getCanvasPoint(firstEvent);
const isAltOverride = e.altKey;
const startPoint = snapSessionRef.current.snapPoint(rawStartPoint, rulerRef.current, isAltOverride);
- onActiveConstraintAxisChangeRef.current?.(snapSessionRef.current.getActiveAxis());
+ emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
allStrokePointsRef.current = [startPoint];
strokePointsRef.current = [startPoint];
+ inputStabilizerRef.current.reset();
+ inputStabilizerRef.current.setStabilizerLevel(bs.stabilization ?? 0);
+ taperEngineRef.current.reset();
rawPointsBufferRef.current = [{
x: startPoint.x,
y: startPoint.y,
@@ -1706,7 +1780,7 @@ export function useCanvasDrawing({
} else {
strokeBackupCanvasRef.current = null;
if (isWetColor && canvas) {
- layerPixelSamplerRef.current = new LayerPixelSampler(canvas);
+ layerPixelSamplerRef.current = new LayerPixelSampler(canvas, activeLayerIdRef.current);
activeReservoirRef.current = new PaintReservoir(strokeColor);
} else {
layerPixelSamplerRef.current = null;
@@ -1744,6 +1818,13 @@ export function useCanvasDrawing({
draftCtx.restore();
} else {
drewDirectlyOnLayerCanvasRef.current = false;
+ const docDraft = canvas ? getDocDraftCanvas(canvas.width, canvas.height) : null;
+ const docCtx = docDraft ? get2DContext(docDraft) : null;
+ if (docCtx && canvas) {
+ docCtx.clearRect(0, 0, canvas.width, canvas.height);
+ }
+
+ const primaryTargetCtx = docCtx || draftCtx;
if (bs.customTipImage) {
const tipOptions: TexturedBrushOptions = {
size: bs.size,
@@ -1767,6 +1848,7 @@ export function useCanvasDrawing({
spray: bs.spray,
taper: bs.taper,
colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
amountOfPaint: bs.amountOfPaint,
densityOfPaint: bs.densityOfPaint,
colorStretch: bs.colorStretch,
@@ -1779,6 +1861,9 @@ export function useCanvasDrawing({
paperTextureImage: bs.paperTextureImage,
paperTextureScale: bs.paperTextureScale,
paperTextureRotate: bs.paperTextureRotate,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
useGpu: bs.useGpu,
underlyingCanvas: canvas || undefined,
sampler: layerPixelSamplerRef.current || undefined,
@@ -1790,11 +1875,11 @@ export function useCanvasDrawing({
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
};
- drawTexturedDot(draftCtx, startPoint, strokeColor, bs.customTipImage, tipOptions);
+ drawTexturedDot(primaryTargetCtx, startPoint, strokeColor, bs.customTipImage, tipOptions);
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilDot(
- draftCtx,
+ primaryTargetCtx,
startPoint,
strokeColor,
grade,
@@ -1807,6 +1892,7 @@ export function useCanvasDrawing({
} else {
const radialMixingOptions: RadialMixingOptions = {
colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
amountOfPaint: bs.amountOfPaint,
densityOfPaint: bs.densityOfPaint,
colorStretch: bs.colorStretch,
@@ -1818,9 +1904,13 @@ export function useCanvasDrawing({
isTransparentInk: Boolean(bs.isTransparentInk),
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
+ useGpu: bs.useGpu,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
};
drawDot(
- draftCtx,
+ primaryTargetCtx,
startPoint,
strokeColor,
false,
@@ -1829,6 +1919,20 @@ export function useCanvasDrawing({
radialMixingOptions
);
}
+
+ if (docCtx && docDraft) {
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const pad = Math.max(startPoint.width, bs.size || 10) * (1.5 + scatterFactor * 2) + 24;
+ const sx = Math.max(0, Math.floor(startPoint.x - pad));
+ const sy = Math.max(0, Math.floor(startPoint.y - pad));
+ const ex = Math.min(docDraft.width, Math.ceil(startPoint.x + pad));
+ const ey = Math.min(docDraft.height, Math.ceil(startPoint.y + pad));
+ const sw = ex - sx;
+ const sh = ey - sy;
+ if (sw > 0 && sh > 0) {
+ draftCtx.drawImage(docDraft, sx, sy, sw, sh, sx, sy, sw, sh);
+ }
+ }
}
if (isEraser && isMonochrome && canvas && dirtyRectRef.current) {
@@ -1848,7 +1952,7 @@ export function useCanvasDrawing({
sCtx?.drawImage(canvas, dotDirty.minX, dotDirty.minY, dw, dh, dotDirty.minX, dotDirty.minY, dw, dh);
}
}
- } else if (isToneLayer && sourceCanvas && canvas && activeLayer) {
+ } else if (isEraser && isToneLayer && sourceCanvas && canvas && activeLayer) {
applyLayerEffects(
sourceCanvas,
canvas,
@@ -1866,107 +1970,7 @@ export function useCanvasDrawing({
drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
}
},
- [clearPredictedCanvas, disabled, dispatchPointerStat, effectiveDraftCanvasRef, flushPendingPoints, getActiveCanvas, getCanvasPoint, getPredictedCanvas, getViewportRect, viewportRef]
- );
-
- // Render speculative predicted head points strictly onto temporary prediction overlay canvas
- const renderPredictedStroke = useCallback(
- (predEvents: PointerEvent[], vRect: DOMRect) => {
- const pCanvas = getPredictedCanvas();
- if (!pCanvas) return;
- const predCtx = get2DContext(pCanvas);
- if (!predCtx) return;
-
- predCtx.resetTransform();
- predCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
-
- const scaleX = pCanvas.width / vRect.width;
- const scaleY = pCanvas.height / vRect.height;
- const matrix = getCanvasToViewportMatrix(
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dimensionsRef.current,
- scaleX,
- scaleY
- );
- predCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
- predCtx.save();
- predCtx.beginPath();
- predCtx.rect(0, 0, dimensionsRef.current.width, dimensionsRef.current.height);
- predCtx.clip();
-
- const bs = brushSettingsRef.current;
- const dims = dimensionsRef.current;
- const lastPt =
- allStrokePointsRef.current[allStrokePointsRef.current.length - 1] ||
- stabilizedPointRef.current;
- if (!lastPt) {
- predCtx.restore();
- return;
- }
-
- let prevPt = lastPt;
- for (let i = 0; i < predEvents.length; i++) {
- const pEv = predEvents[i];
- const rawCoords = screenToCanvas(
- pEv.clientX,
- pEv.clientY,
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims
- );
-
- let pPressure = 0;
- if (pEv.pointerType === 'mouse') {
- pPressure = (pEv.buttons & 1) ? 0.5 : 0;
- } else {
- pPressure = pEv.pressure !== undefined ? Math.max(0, Math.min(1.0, pEv.pressure)) : prevPt.pressure;
- }
-
- const pWidth = calculateStrokeWidth(
- bs.size,
- pPressure,
- bs.minSizeFactor,
- bs.usePressure,
- pEv.pointerType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
-
- const curPt: Point = {
- x: rawCoords.x,
- y: rawCoords.y,
- pressure: pPressure,
- width: pWidth,
- tiltX: pEv.tiltX ?? 0,
- tiltY: pEv.tiltY ?? 0,
- twist: pEv.twist ?? 0,
- timestamp: pEv.timeStamp,
- };
-
- predCtx.save();
- predCtx.lineCap = 'round';
- predCtx.lineJoin = 'round';
- predCtx.strokeStyle = bs.color;
- predCtx.fillStyle = bs.color;
- predCtx.globalAlpha = Math.max(0.2, (bs.opacity ?? 1.0) * (bs.flow ?? 1.0) * 0.75);
- predCtx.lineWidth = Math.max(1, (prevPt.width + curPt.width) / 2);
- predCtx.beginPath();
- predCtx.moveTo(prevPt.x, prevPt.y);
- predCtx.lineTo(curPt.x, curPt.y);
- predCtx.stroke();
- predCtx.restore();
-
- prevPt = curPt;
- }
-
- predCtx.restore();
- },
- [getPredictedCanvas]
+ [clearPredictedCanvas, disabled, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, flushPendingHistoryTasks, flushPendingPoints, getActiveCanvas, getCanvasPoint, getDocDraftCanvas, getPredictedCanvas, getViewportRect, viewportRef]
);
// Pointer Move handler: throttled & batched coordinate ingestion via rAF with coalesced and predicted events
@@ -1974,7 +1978,7 @@ export function useCanvasDrawing({
(
e: React.PointerEvent<HTMLElement>,
coalescedEvents?: PointerEvent[],
- predictedEvents?: PointerEvent[]
+ _predictedEvents?: PointerEvent[]
) => {
const point = getCanvasPoint(e);
dispatchPointerStat(point.x, point.y, point.pressure);
@@ -1986,8 +1990,6 @@ export function useCanvasDrawing({
e.preventDefault();
- clearPredictedCanvas();
-
const vRect = getViewportRect();
if (!vRect) return;
const dims = dimensionsRef.current;
@@ -1999,16 +2001,11 @@ export function useCanvasDrawing({
const events: PointerEvent[] =
rawCoalesced && rawCoalesced.length > 0 ? Array.from(rawCoalesced) : [e.nativeEvent];
- const rawPredicted =
- predictedEvents ??
- (e as any).predictedEvents ??
- (typeof e.nativeEvent?.getPredictedEvents === 'function' ? e.nativeEvent.getPredictedEvents() : null);
- const predEvents: PointerEvent[] =
- rawPredicted && rawPredicted.length > 0 ? Array.from(rawPredicted) : [];
+ const draftCanvas = effectiveDraftCanvasRef?.current;
+ const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
for (let i = 0; i < events.length; i++) {
const cEvent = events[i];
- const isLast = i === events.length - 1;
const rawCoords = screenToCanvas(
cEvent.clientX,
cEvent.clientY,
@@ -2024,11 +2021,11 @@ export function useCanvasDrawing({
const cx = snapRes.x;
const cy = snapRes.y;
if (snapRes.axis) {
- onActiveConstraintAxisChangeRef.current?.(snapRes.axis);
+ emitConstraintAxisChange(snapRes.axis);
}
const last = lastProcessedPointRef.current;
- if (last && !isLast && cx === last.x && cy === last.y) {
+ if (last && Math.hypot(cx - last.x, cy - last.y) < 0.25) {
continue;
}
@@ -2040,27 +2037,23 @@ export function useCanvasDrawing({
cPressure = cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
}
- pendingPointsQueueRef.current.push({
- x: cx,
- y: cy,
- pressure: cPressure,
- pointerType: cEvent.pointerType,
- tiltX: cEvent.tiltX ?? 0,
- tiltY: cEvent.tiltY ?? 0,
- twist: cEvent.twist ?? 0,
- timestamp: cEvent.timeStamp,
- });
- }
-
- if (drawRafIdRef.current === null) {
- drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
- }
-
- if (predEvents.length > 0) {
- renderPredictedStroke(predEvents, vRect);
+ // Render segment immediately on draft canvas for zero-latency stylus tracking (CSP style)
+ if (draftCtx) {
+ applyStabilizedPointAndRender(
+ draftCtx,
+ cx,
+ cy,
+ cPressure,
+ cEvent.pointerType,
+ cEvent.tiltX ?? 0,
+ cEvent.tiltY ?? 0,
+ cEvent.twist ?? 0,
+ cEvent.timeStamp
+ );
+ }
}
},
- [clearPredictedCanvas, dispatchPointerStat, flushPendingPoints, getCanvasPoint, getViewportRect, renderPredictedStroke]
+ [applyStabilizedPointAndRender, dispatchPointerStat, effectiveDraftCanvasRef, emitConstraintAxisChange, getCanvasPoint, getViewportRect]
);
// Pointer Up / Cancel handler: composite and bake stroke into high-res canvas at dirty rect
@@ -2092,45 +2085,6 @@ export function useCanvasDrawing({
const draftCtx = draftCanvas ? get2DContext(draftCanvas) : null;
const canvas = getActiveCanvas();
- // Drain any buffered raw points through the stabilizer
- while (rawPointsBufferRef.current.length > 0) {
- const buf = rawPointsBufferRef.current;
- const len = buf.length;
- const mid = Math.floor(len / 2);
- let sumX = 0, sumY = 0, sumP = 0, sumTiltX = 0, sumTiltY = 0, sumTwist = 0, sumW = 0;
- for (let i = 0; i < len; i++) {
- const w = Math.pow(2, mid - Math.abs(i - mid));
- sumX += buf[i].x * w;
- sumY += buf[i].y * w;
- sumP += buf[i].pressure * w;
- sumTiltX += (buf[i].tiltX ?? 0) * w;
- sumTiltY += (buf[i].tiltY ?? 0) * w;
- sumTwist += (buf[i].twist ?? 0) * w;
- sumW += w;
- }
- const ptType = buf[0].pointerType;
- buf.shift();
-
- const sX = sumX / sumW;
- const sY = sumY / sumW;
- const sP = sumP / sumW;
- const sW = calculateStrokeWidth(
- bs.size,
- sP,
- bs.minSizeFactor,
- bs.usePressure,
- ptType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
- const pt: Point = { x: sX, y: sY, pressure: sP, width: sW, tiltX: sumTiltX / sumW, tiltY: sumTiltY / sumW, twist: sumTwist / sumW };
- allStrokePointsRef.current.push(pt);
- if (draftCtx) {
- renderDraftSegment(draftCtx, pt);
- }
- }
-
// Finalize tail segment on draft canvas using Catmull-Rom cubic Bézier
const pts = strokePointsRef.current;
const currentTool = toolRef.current;
@@ -2181,6 +2135,7 @@ export function useCanvasDrawing({
}
const { c1, c2 } = catmullRomToBezier(pPrev2, pPrev, pLast, pLast);
+ const docCtx = (!isEraser && docDraftCanvasRef.current) ? get2DContext(docDraftCanvasRef.current) : null;
if (bs.customTipImage) {
const tipOptions: TexturedBrushOptions = {
@@ -2241,6 +2196,19 @@ export function useCanvasDrawing({
tipOptions,
stampRemainderDistRef.current
);
+ if (docCtx) {
+ drawTexturedCubicBezierSegment(
+ docCtx,
+ pPrev,
+ c1,
+ c2,
+ pLast,
+ strokeColor,
+ bs.customTipImage,
+ tipOptions,
+ stampRemainderDistRef.current
+ );
+ }
} else if (isPencil) {
const grade = (bs.preset as PencilGrade) || 'pencil-2b';
drawPencilCubicBezierSegment(
@@ -2258,6 +2226,23 @@ export function useCanvasDrawing({
Boolean(activeLayer?.alphaLocked),
Boolean(bs.isTransparentInk)
);
+ if (docCtx) {
+ drawPencilCubicBezierSegment(
+ docCtx,
+ pPrev,
+ c1,
+ c2,
+ pLast,
+ strokeColor,
+ grade,
+ bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ bs.hardness,
+ stampRemainderDistRef.current,
+ Boolean(activeLayer?.alphaLocked),
+ Boolean(bs.isTransparentInk)
+ );
+ }
} else {
const radialMixingOptions: RadialMixingOptions = {
colorMixing: bs.colorMixing,
@@ -2289,6 +2274,24 @@ export function useCanvasDrawing({
((bs.customTipAngle ?? 0) * Math.PI) / 180,
radialMixingOptions
);
+ if (docCtx) {
+ drawSmoothCubicBezierSegment(
+ docCtx,
+ pPrev,
+ c1,
+ c2,
+ pLast,
+ strokeColor,
+ false,
+ strokeHardness,
+ bs.flow ?? 1.0,
+ bs.spacing ?? 0.06,
+ stampRemainderDistRef.current,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ radialMixingOptions
+ );
+ }
}
if (isEraser && draftCtx) {
@@ -2322,15 +2325,20 @@ export function useCanvasDrawing({
dirtyRectRef.current.maxY = Math.max(dirtyRectRef.current.maxY, tMaxY);
}
- if (isEraser && isMonochrome && canvas) {
- const tW = tMaxX - tMinX;
- const tH = tMaxY - tMinY;
- if (tW > 0 && tH > 0) {
+ if (isEraser && isMonochrome && canvas && dirtyRectRef.current) {
+ const eDirty = dirtyRectRef.current;
+ const eMinX = Math.max(0, Math.floor(eDirty.minX));
+ const eMinY = Math.max(0, Math.floor(eDirty.minY));
+ const eMaxX = Math.min(canvas.width, Math.ceil(eDirty.maxX));
+ const eMaxY = Math.min(canvas.height, Math.ceil(eDirty.maxY));
+ const eW = eMaxX - eMinX;
+ const eH = eMaxY - eMinY;
+ if (eW > 0 && eH > 0) {
const cCtx = get2DContext(canvas);
if (cCtx) {
binarizeCanvasRect(
cCtx,
- { x: tMinX, y: tMinY, width: tW, height: tH },
+ { x: eMinX, y: eMinY, width: eW, height: eH },
activeLayer?.monoThreshold ?? 128,
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
@@ -2338,7 +2346,7 @@ export function useCanvasDrawing({
}
if (sourceCanvas) {
const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, tMinX, tMinY, tW, tH, tMinX, tMinY, tW, tH);
+ sCtx?.drawImage(canvas, eMinX, eMinY, eW, eH, eMinX, eMinY, eW, eH);
}
}
}
@@ -2369,7 +2377,8 @@ export function useCanvasDrawing({
let exitSpeed = 0;
if (recentPointsTrailRef.current.length >= 2) {
const trail = recentPointsTrailRef.current;
- const pA = trail[0];
+ const sampleIdx = Math.max(0, trail.length - 4);
+ const pA = trail[sampleIdx];
const pB = trail[trail.length - 1];
const dt = Math.max(1, pB.t - pA.t);
const dist = Math.hypot(pB.x - pA.x, pB.y - pA.y);
@@ -2406,18 +2415,38 @@ export function useCanvasDrawing({
const updatedStrokes = eraserResult.updatedStrokes;
activeLayer.vectorStrokes = updatedStrokes;
+ let minX = dirty ? dirty.minX : 0;
+ let minY = dirty ? dirty.minY : 0;
+ let maxX = dirty ? dirty.maxX : canvas.width;
+ let maxY = dirty ? dirty.maxY : canvas.height;
+ for (const st of prevStrokes) {
+ if (st.bounds) {
+ minX = Math.min(minX, st.bounds.minX);
+ minY = Math.min(minY, st.bounds.minY);
+ maxX = Math.max(maxX, st.bounds.maxX);
+ maxY = Math.max(maxY, st.bounds.maxY);
+ }
+ }
+ const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
+ const vx = Math.max(0, Math.floor(minX - vPad));
+ const vy = Math.max(0, Math.floor(minY - vPad));
+ const vw = Math.max(0, Math.min(canvas.width, Math.ceil(maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(canvas.height, Math.ceil(maxY + vPad)) - vy);
+
const ctx = get2DContext(canvas);
if (ctx) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
renderVectorLayer(ctx, updatedStrokes);
- const fullData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- globalTileGrid.writeImageData(
- currentLayerId,
- fullData,
- 0,
- 0,
- isMonochrome ? 'monochrome-1bit' : 'color-32bit'
- );
+ if (vw > 0 && vh > 0) {
+ const subData = ctx.getImageData(vx, vy, vw, vh);
+ globalTileGrid.writeImageData(
+ currentLayerId,
+ subData,
+ vx,
+ vy,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
}
pushHistoryStep(
@@ -2426,7 +2455,7 @@ export function useCanvasDrawing({
null,
null,
currentLayerId,
- { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: canvas.width, height: canvas.height },
undefined,
{ before: prevStrokes, after: updatedStrokes },
undefined,
@@ -2451,17 +2480,25 @@ export function useCanvasDrawing({
const updatedStrokes = [...prevStrokes, newStroke];
activeLayer.vectorStrokes = updatedStrokes;
+ const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
+ const vx = Math.max(0, Math.floor(bounds.minX - vPad));
+ const vy = Math.max(0, Math.floor(bounds.minY - vPad));
+ const vw = Math.max(0, Math.min(canvas.width, Math.ceil(bounds.maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(canvas.height, Math.ceil(bounds.maxY + vPad)) - vy);
+
const ctx = get2DContext(canvas);
if (ctx) {
renderVectorStroke(ctx, newStroke);
- const fullData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- globalTileGrid.writeImageData(
- currentLayerId,
- fullData,
- 0,
- 0,
- isMonochrome ? 'monochrome-1bit' : 'color-32bit'
- );
+ if (vw > 0 && vh > 0) {
+ const subData = ctx.getImageData(vx, vy, vw, vh);
+ globalTileGrid.writeImageData(
+ currentLayerId,
+ subData,
+ vx,
+ vy,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
}
pushHistoryStep(
@@ -2470,7 +2507,7 @@ export function useCanvasDrawing({
null,
null,
currentLayerId,
- { x: 0, y: 0, width: canvas.width, height: canvas.height },
+ vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: canvas.width, height: canvas.height },
undefined,
{ before: prevStrokes, after: updatedStrokes },
undefined,
@@ -2489,14 +2526,30 @@ export function useCanvasDrawing({
if (dw > 0 && dh > 0) {
const ctx = get2DContext(canvas);
if (ctx) {
- let beforeData: ImageData | null = null;
- let afterData: ImageData | null = null;
+ let label = 'Brush Stroke';
+ if (bs.isTransparentInk) {
+ label = 'Transparent Ink';
+ } else if (currentTool === 'eraser') {
+ label = 'Eraser';
+ } else if (bs.brushName) {
+ label = bs.brushName;
+ } else if (bs.preset === 'pencil-f') {
+ label = 'Pencil (F)';
+ } else if (bs.preset === 'pencil-2b') {
+ label = 'Pencil (2B)';
+ } else if (bs.preset === 'pencil-4b') {
+ label = 'Pencil (4B)';
+ } else if (bs.preset === 'pencil-hb') {
+ label = 'Pencil (HB)';
+ } else {
+ label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
+ }
- if (isEraser && strokeBackupCanvasRef.current) {
- const bCtx = get2DContext(strokeBackupCanvasRef.current);
- beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;
- afterData = ctx.getImageData(sx, sy, dw, dh);
+ const docDraft = docDraftCanvasRef.current;
+ const dirtyRect = { x: sx, y: sy, width: dw, height: dh };
+ const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
+ if (isEraser && strokeBackupCanvasRef.current) {
// Synchronize dirty bounding box to sourceCanvas so tone can be toggled without losing edits
if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
@@ -2508,38 +2561,51 @@ export function useCanvasDrawing({
}
}
}
+
+ // Synchronously snapshot and write committed tiles to globalTileGrid
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = ctx.getImageData(sx, sy, dw, dh);
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+
+ // Offload history step and tile delta generation to background task
+ enqueueHistoryTask(() => {
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ pushHistoryStep('eraser', label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
} else if (isToneLayer && sourceCanvas) {
- const bCtx = strokeBackupCanvasRef.current ? get2DContext(strokeBackupCanvasRef.current) : null;
- beforeData = bCtx ? bCtx.getImageData(sx, sy, dw, dh) : null;
-
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtxBake) {
- bCtxBake.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
- bCtxBake.save();
- bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(bCtxBake, allPoints, bs, currentTool, mode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
- bCtxBake.restore();
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ sCtx.save();
+ sCtx.beginPath();
+ sCtx.rect(sx, sy, dw, dh);
+ sCtx.clip();
+ sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if (bs.isTransparentInk) {
+ sCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ sCtx.globalCompositeOperation = 'source-atop';
+ } else {
+ sCtx.globalCompositeOperation = 'source-over';
+ }
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.save();
- sCtx.beginPath();
- sCtx.rect(sx, sy, dw, dh);
- sCtx.clip();
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
+ if (docDraft) {
+ sCtx.drawImage(docDraft, sx, sy, dw, dh, sx, sy, dw, dh);
+ } else {
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtxBake) {
+ bCtxBake.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
+ bCtxBake.save();
+ bCtxBake.translate(-sx, -sy);
+ renderCompleteStroke(bCtxBake, allPoints, bs, currentTool, mode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
+ bCtxBake.restore();
+ sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
- sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- sCtx.restore();
- afterData = sCtx.getImageData(sx, sy, dw, dh);
}
+ sCtx.restore();
}
+
if (activeLayer) {
applyLayerEffects(
sourceCanvas,
@@ -2549,49 +2615,71 @@ export function useCanvasDrawing({
{ x: sx, y: sy, width: dw, height: dh }
);
}
- } else {
- // Translucent and opaque brushes / pencils drawn onto draft canvas overlay:
- beforeData = ctx.getImageData(sx, sy, dw, dh);
+ if (docDraft) {
+ const dCtx = get2DContext(docDraft);
+ dCtx?.clearRect(sx, sy, dw, dh);
+ }
+
+ // Synchronously snapshot and write committed tiles to globalTileGrid
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (afterData) {
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ }
+
+ enqueueHistoryTask(() => {
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
+ } else {
+ // Direct zero-stall GPU blit from docDraft to layer canvas (<0.2 ms)
ctx.save();
ctx.beginPath();
ctx.rect(sx, sy, dw, dh);
ctx.clip();
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtx) {
- bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
- bCtx.restore();
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if (bs.isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (bs.isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
- } else {
- ctx.globalCompositeOperation = 'source-over';
+ if (docDraft) {
+ ctx.drawImage(docDraft, sx, sy, dw, dh, sx, sy, dw, dh);
+ } else {
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, bakeCanvas.width, bakeCanvas.height);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(bCtx, allPoints, bs, currentTool, mode, isBgEraser, canvas, Boolean(activeLayer?.alphaLocked));
+ bCtx.restore();
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
}
+ ctx.restore();
+
+ // Single-pass snapshot: read pixel buffer once, binarize in-place if monochrome, then write
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const beforeSnapshot = globalTileGrid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = ctx.getImageData(sx, sy, dw, dh);
if (isMonochrome) {
- binarizeCanvasRect(
- ctx,
- { x: sx, y: sy, width: dw, height: dh },
+ binarizeImageDataBuffer(
+ afterData,
activeLayer?.monoThreshold ?? 128,
activeLayer?.monoExpressBlack ?? true,
activeLayer?.monoExpressWhite ?? true
);
+ ctx.putImageData(afterData, sx, sy);
}
- ctx.restore();
-
- afterData = ctx.getImageData(sx, sy, dw, dh);
-
if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
if (existingSource) {
@@ -2602,64 +2690,43 @@ export function useCanvasDrawing({
}
}
}
- }
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const dirtyRect = { x: sx, y: sy, width: dw, height: dh };
+ if (docDraft) {
+ const dCtx = get2DContext(docDraft);
+ dCtx?.clearRect(sx, sy, dw, dh);
+ }
- let label = 'Brush Stroke';
- if (bs.isTransparentInk) {
- label = 'Transparent Ink';
- } else if (currentTool === 'eraser') {
- label = 'Eraser';
- } else if (bs.brushName) {
- label = bs.brushName;
- } else if (bs.preset === 'pencil-f') {
- label = 'Pencil (F)';
- } else if (bs.preset === 'pencil-2b') {
- label = 'Pencil (2B)';
- } else if (bs.preset === 'pencil-4b') {
- label = 'Pencil (4B)';
- } else if (bs.preset === 'pencil-hb') {
- label = 'Pencil (HB)';
- } else {
- label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
- }
+ globalTileGrid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- if (beforeData && afterData) {
- pushHistoryStep(
- currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush'),
- label,
- beforeData,
- afterData,
- currentLayerId,
- dirtyRect
- );
- } else if (afterData) {
- globalTileGrid.writeImageData(currentLayerId, afterData, dirtyRect.x, dirtyRect.y, targetFormat);
+ enqueueHistoryTask(() => {
+ const tileDeltas = globalTileGrid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
+ pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
+ });
}
}
}
}
- // Synchronously notify tile grid compositor BEFORE clearing draft canvas to guarantee zero flicker
+ // Synchronously notify tile grid compositor
globalTileGrid.notifyChange(true);
- // Synchronously clear draftCanvas immediately in the exact same render turn to guarantee zero flicker
+ // Atomic Zero-Flicker handoff: wait 1 frame for WebGL compositor to present its swap chain, then clear draft overlay
if (clearDraftRafRef.current !== null) {
cancelAnimationFrame(clearDraftRafRef.current);
- clearDraftRafRef.current = null;
}
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore(); // Restore artboard clip
- } catch (_) {}
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ clearDraftRafRef.current = requestAnimationFrame(() => {
+ clearDraftRafRef.current = null;
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore(); // Restore artboard clip
+ } catch (_) {}
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
}
- }
+ });
clearPredictedCanvas();
if (currentStrokeIdRef.current) {
@@ -2692,24 +2759,29 @@ export function useCanvasDrawing({
layerPixelSamplerRef.current = null;
activeReservoirRef.current = null;
snapSessionRef.current.endStroke();
- onActiveConstraintAxisChangeRef.current?.(null);
+ emitConstraintAxisChange(null);
if (isMaskModeRef.current) {
onUpdateMaskThumbnailRef.current?.(currentLayerId);
globalTileGrid.notifyChange(true);
} else {
- onUpdateLayerThumbnail(currentLayerId);
+ enqueueHistoryTask(() => {
+ onUpdateLayerThumbnail(currentLayerId);
+ });
}
},
[
applyStabilizedPointAndRender,
clearPredictedCanvas,
effectiveDraftCanvasRef,
+ emitConstraintAxisChange,
+ enqueueHistoryTask,
flushPendingPoints,
getActiveCanvas,
getCanvasPoint,
onUpdateLayerThumbnail,
pushHistoryStep,
+ renderDraftSegment,
]
);
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 2e4da3b..cff6568 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -59,14 +59,21 @@ export function calculateAdaptiveZoom(
dimensions: CanvasDimensions | undefined,
viewport: HTMLDivElement | null
): number {
- if (!viewport || !dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
+ if (!dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
return 1.0;
}
- const vw = viewport.clientWidth;
- const vh = viewport.clientHeight;
+ let vw = viewport?.clientWidth ?? 0;
+ let vh = viewport?.clientHeight ?? 0;
+
+ // Fallback to window dimensions if viewport is not yet attached to DOM or measured
if (vw <= 0 || vh <= 0) {
- return 1.0;
+ if (typeof window !== 'undefined') {
+ vw = Math.max(300, window.innerWidth - 300);
+ vh = Math.max(300, window.innerHeight - 80);
+ } else {
+ return 1.0;
+ }
}
const availH = Math.max(20, vh - VIEWPORT_FIT_PADDING);
@@ -83,9 +90,14 @@ export function calculateAdaptiveZoom(
interface UseCanvasNavigationProps {
dimensions?: CanvasDimensions;
isWebtoonMode?: boolean;
+ activeDocumentId?: string | null;
}
-export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCanvasNavigationProps = {}) {
+export function useCanvasNavigation({
+ dimensions,
+ isWebtoonMode = false,
+ activeDocumentId = null,
+}: UseCanvasNavigationProps = {}) {
const viewportRef = useRef<HTMLDivElement | null>(null);
const [zoom, setZoomState] = useState<number>(1.0);
@@ -94,9 +106,7 @@ export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCa
const [rotation, setRotationState] = useState<number>(0.0);
const dimensionsRef = useRef<CanvasDimensions | undefined>(dimensions);
- useEffect(() => {
- dimensionsRef.current = dimensions;
- }, [dimensions]);
+ dimensionsRef.current = dimensions;
const [isSpaceDown, setIsSpaceDown] = useState<boolean>(false);
const [isShiftDown, setIsShiftDown] = useState<boolean>(false);
@@ -169,11 +179,18 @@ export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCa
// Center canvas in viewport given target zoom
const centerCanvas = useCallback((targetZoom: number = zoomRef.current) => {
const viewport = viewportRef.current;
- if (!viewport) return;
-
- const vw = viewport.clientWidth;
- const vh = viewport.clientHeight;
- if (vw <= 0 || vh <= 0) return;
+ let vw = viewport?.clientWidth ?? 0;
+ let vh = viewport?.clientHeight ?? 0;
+
+ // Fallback to window bounds if viewport not yet mounted
+ if (vw <= 0 || vh <= 0) {
+ if (typeof window !== 'undefined') {
+ vw = Math.max(300, window.innerWidth - 300);
+ vh = Math.max(300, window.innerHeight - 80);
+ } else {
+ return;
+ }
+ }
const newCenter = {
x: Math.round(vw / 2),
@@ -195,6 +212,7 @@ export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCa
const targetZoom = calculateAdaptiveZoom(activeDims, viewportRef.current);
rotationRef.current = 0.0;
setRotationState(0.0);
+ hasInitializedCenterRef.current = true;
centerCanvas(targetZoom);
},
[centerCanvas]
@@ -325,7 +343,12 @@ export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCa
setIsRotating(true);
}, []);
- // Center on initial mount and handle window / viewport resize gracefully
+ // Reset centering flag when active document changes
+ useEffect(() => {
+ hasInitializedCenterRef.current = false;
+ }, [activeDocumentId]);
+
+ // Center on mount, document change, and handle window / viewport resize gracefully
useEffect(() => {
const viewport = viewportRef.current;
if (!viewport) return;
@@ -364,7 +387,7 @@ export function useCanvasNavigation({ dimensions, isWebtoonMode = false }: UseCa
ro.observe(viewport);
return () => ro.disconnect();
- }, [centerCanvas, setPan]);
+ }, [centerCanvas, setPan, activeDocumentId]);
// Mouse wheel zoom centered on cursor position (accounts for rotation angle)
useEffect(() => {
diff --git a/src/index.css b/src/index.css
index 559fad7..c71ae30 100644
--- a/src/index.css
+++ b/src/index.css
@@ -341,21 +341,21 @@ input[type="range"]:active::-moz-range-thumb {
--modern-accent-hover: rgba(59, 130, 246, 0.2);
--modern-accent-border: rgba(59, 130, 246, 0.42);
- /* Modern Theme Tone - Default Slate */
- --modern-bg-base: #0c0d12;
- --modern-bg-surface: #13141b;
- --modern-bg-elevated: #1a1b24;
- --modern-bg-input: #111217;
+ /* Modern Theme Tone - Neutral Charcoal / Graphite Palette */
+ --modern-bg-base: #18191d;
+ --modern-bg-surface: #1e1f24;
+ --modern-bg-elevated: #25262c;
+ --modern-bg-input: #151619;
--modern-border: rgba(255, 255, 255, 0.08);
--modern-border-subtle: rgba(255, 255, 255, 0.04);
}
[data-theme="modern"] {
/* Surface tokens (accent variables cascade dynamically from :root or inline element styles) */
- --modern-bg-base: #0c0d12;
- --modern-bg-surface: #13141b;
- --modern-bg-elevated: #1a1b24;
- --modern-bg-input: #111217;
+ --modern-bg-base: #18191d;
+ --modern-bg-surface: #1e1f24;
+ --modern-bg-elevated: #25262c;
+ --modern-bg-input: #151619;
--modern-border: rgba(255, 255, 255, 0.08);
--modern-border-subtle: rgba(255, 255, 255, 0.04);
}
@@ -372,12 +372,12 @@ input[type="range"]:active::-moz-range-thumb {
[data-tone="charcoal"],
[data-theme="modern"][data-tone="charcoal"] {
- --modern-bg-base: #111215;
- --modern-bg-surface: #18191d;
- --modern-bg-elevated: #212228;
- --modern-bg-input: #141518;
- --modern-border: rgba(255, 255, 255, 0.07);
- --modern-border-subtle: rgba(255, 255, 255, 0.035);
+ --modern-bg-base: #18191d;
+ --modern-bg-surface: #1f2025;
+ --modern-bg-elevated: #26272e;
+ --modern-bg-input: #15161a;
+ --modern-border: rgba(255, 255, 255, 0.08);
+ --modern-border-subtle: rgba(255, 255, 255, 0.04);
}
[data-accent="blue"],
diff --git a/src/types/editor.ts b/src/types/editor.ts
index 64e3b31..dfcf4cc 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -26,6 +26,7 @@ export interface Point {
tiltY?: number;
twist?: number;
timestamp?: number;
+ isCorner?: boolean;
}
export type BrushPresetId =
@@ -135,6 +136,7 @@ export interface CspBrush {
velocityCurve?: [number, number][];
// Advanced CSP Mathematics Parameters
colorMixing?: boolean; // Enable CSP pigment mixing
+ perceptualMixing?: boolean; // OKLab / Kubelka-Munk perceptual pigment mixing (default true)
amountOfPaint?: number; // 0.0 to 1.0 (CSP: Amount of Paint)
densityOfPaint?: number; // 0.0 to 1.0 (CSP: Density of Paint)
colorStretch?: number; // 0.0 to 1.0 (CSP: Color Stretch along stroke length)
@@ -194,6 +196,7 @@ export interface BrushSettings {
isRibbon?: boolean;
// Advanced CSP Mathematics Settings
colorMixing?: boolean; // True to activate real-time canvas color mixing
+ perceptualMixing?: boolean; // True for OKLab / Kubelka-Munk perceptual pigment mixing
amountOfPaint?: number; // 0.0 to 1.0 (default 0.7)
densityOfPaint?: number; // 0.0 to 1.0 (default 0.8)
colorStretch?: number; // 0.0 to 1.0 (default 0.6)
@@ -208,6 +211,7 @@ export interface BrushSettings {
paperTextureScale?: number;
paperTextureRotate?: number;
dualBrush?: boolean;
+ dualBrushCompositeMode?: 'multiply' | 'subtract' | 'darken' | 'overlay' | 'screen' | string;
dualTipDataUrl?: string;
dualTipImage?: HTMLImageElement;
pressureCurveGamma?: number; // 0.4 (soft) to 2.5 (hard) response curve
@@ -294,11 +298,14 @@ export interface LiquifySettings {
usePressure: boolean;
}
-export type FillMethod = 'refer-all' | 'refer-active' | 'lasso';
+export type FillMethod = 'refer-all' | 'refer-active' | 'refer-reference' | 'lasso';
export interface FillSettings {
method: FillMethod;
tolerance: number; // 0 - 100
+ closeGap?: number; // 0 - 20 px (CSP Close Gap)
+ areaScale?: number; // -20 to +20 px (CSP Area Scaling)
+ antiAlias?: boolean; // Anti-aliasing edge smoothing & spill guard
}
export interface TextSettings {
@@ -441,7 +448,11 @@ export type BlendMode =
| 'soft-light'
| 'difference'
| 'exclusion'
- | 'pass-through';
+ | 'pass-through'
+ | 'linear-burn'
+ | 'add-glow'
+ | 'color-dodge-glow'
+ | 'divide';
export interface HistoryItemMeta {
id: string;
@@ -629,6 +640,7 @@ export interface LayerItem {
monoExpressWhite?: boolean; // Express white in monochrome (default: true)
// Non-destructive Layer Mask
maskCanvas?: HTMLCanvasElement;
+ maskVersion?: number;
maskEnabled?: boolean;
maskLinked?: boolean;
maskThumbnailUrl?: string;
diff --git a/src/utils/__tests__/cspEngineRefactor.test.ts b/src/utils/__tests__/cspEngineRefactor.test.ts
new file mode 100644
index 0000000..8205078
--- /dev/null
+++ b/src/utils/__tests__/cspEngineRefactor.test.ts
@@ -0,0 +1,220 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { InputStabilizer } from '../../engine/InputStabilizer';
+import { TaperEngine } from '../../engine/TaperEngine';
+import { SplineGenerator, SplinePoint } from '../../engine/SplineGenerator';
+import { WebGlBrushEngine } from '../webglBrushEngine';
+
+describe('Clip Studio Paint Drawing Engine Refactor Tests', () => {
+ describe('Phase 3: Adaptive Corner-Snapping Stabilizer (InputStabilizer)', () => {
+ let stabilizer: InputStabilizer;
+
+ beforeEach(() => {
+ stabilizer = new InputStabilizer();
+ stabilizer.setStabilizerLevel(15);
+ });
+
+ it('detects critical angle deflection (> 45 deg) and commits sharp corner vertex', () => {
+ let t = 1000;
+ // Stroke moving along positive X axis: (0,0) -> (10,0) -> (20,0) -> (30,0)
+ stabilizer.process(0, 0, 0.5, t);
+ t += 16;
+ stabilizer.process(10, 0, 0.5, t);
+ t += 16;
+ stabilizer.process(20, 0, 0.5, t);
+ t += 16;
+ stabilizer.process(30, 0, 0.5, t);
+
+ // Sudden 90 degree turn upward to positive Y: (30, 20)
+ t += 16;
+ const cornerSample = stabilizer.process(30, 20, 0.5, t);
+
+ expect(cornerSample.isCorner).toBe(true);
+ // Coordinates should snap sharply to raw corner coordinate rather than lagging behind
+ expect(cornerSample.x).toBeCloseTo(30, 0);
+ expect(cornerSample.y).toBeCloseTo(20, 0);
+ });
+
+ it('maintains continuous smoothing for gentle curves (< 45 deg deflection)', () => {
+ let t = 1000;
+ stabilizer.process(0, 0, 0.5, t);
+ t += 16;
+ stabilizer.process(10, 0, 0.5, t);
+ t += 16;
+ stabilizer.process(20, 1, 0.5, t);
+ t += 16;
+ // Shallow curve turn
+ const smoothSample = stabilizer.process(30, 3, 0.5, t);
+
+ expect(smoothSample.isCorner).toBe(false);
+ });
+
+ it('adapts damping based on stroke velocity (high damping on slow strokes, low on fast)', () => {
+ const slowStab = new InputStabilizer();
+ slowStab.setStabilizerLevel(10);
+ const fastStab = new InputStabilizer();
+ fastStab.setStabilizerLevel(10);
+
+ // Slow stroke: small movement (5px) over large dt (50ms) -> 0.1 px/ms
+ slowStab.process(0, 0, 0.5, 0);
+ const slowSample = slowStab.process(5, 0, 0.5, 50);
+
+ // Fast stroke: large movement (50px) over small dt (10ms) -> 5 px/ms
+ fastStab.process(0, 0, 0.5, 0);
+ const fastSample = fastStab.process(50, 0, 0.5, 10);
+
+ // Fast stroke should track with lower relative lag due to velocity boost on cutoff
+ const slowLagRatio = Math.abs(5 - slowSample.x) / 5;
+ const fastLagRatio = Math.abs(50 - fastSample.x) / 50;
+ expect(fastLagRatio).toBeLessThan(slowLagRatio);
+ });
+
+ it('implements asymmetric pressure filtering (fast pen-down attack, critically damped decay)', () => {
+ const pStab = new InputStabilizer();
+ pStab.setStabilizerLevel(15);
+
+ // Pen down attack: jump from 0.0 to 1.0 pressure in 16ms
+ pStab.process(0, 0, 0.0, 0);
+ const attackSample = pStab.process(1, 0, 1.0, 16);
+
+ // Pressure attack should respond aggressively (>= 80% on first 16ms tick)
+ expect(attackSample.pressure).toBeGreaterThanOrEqual(0.8);
+
+ // Steady state
+ pStab.process(2, 0, 1.0, 32);
+
+ // Pen release decay: drop from 1.0 to 0.1 pressure
+ const decaySample = pStab.process(3, 0, 0.1, 48);
+ // Decay should be smooth and damped (not jumping immediately to 0.1)
+ expect(decaySample.pressure).toBeGreaterThan(0.2);
+ });
+ });
+
+ describe('Phase 4: Japanese Inking Dynamics (TaperEngine)', () => {
+ let taperEngine: TaperEngine;
+
+ beforeEach(() => {
+ taperEngine = new TaperEngine();
+ });
+
+ it('maps pressure through 3-stage cubic S-curve (G-Pen response)', () => {
+ // Stage 1: Delicate hairline zone (0 - 15%)
+ const pLow = taperEngine.mapPressure(0.10);
+ expect(pLow).toBeLessThan(0.10); // Ease-in hairline compression
+
+ // Stage 2: Stable controllable line weight (15% - 70%)
+ const pMid = taperEngine.mapPressure(0.40);
+ expect(pMid).toBeGreaterThan(0.15);
+ expect(pMid).toBeLessThan(0.70);
+
+ // Stage 3: Saturated expansion (70% - 100%)
+ const pHigh = taperEngine.mapPressure(0.85);
+ expect(pHigh).toBeGreaterThan(0.80);
+
+ // Monotonicity check across full range
+ let prev = -1;
+ for (let p = 0; p <= 1.0; p += 0.05) {
+ const mapped = taperEngine.mapPressure(p);
+ expect(mapped).toBeGreaterThanOrEqual(prev);
+ prev = mapped;
+ }
+ expect(taperEngine.mapPressure(0)).toBe(0);
+ expect(taperEngine.mapPressure(1)).toBe(1);
+ });
+
+ it('computes exponential ballistic flick taper on high-velocity pen lift', () => {
+ const startX = 100;
+ const startY = 100;
+ const startWidth = 10;
+ const startPressure = 0.8;
+ const exitVx = 2.5; // Fast flick in X
+ const exitVy = 0.5;
+ const timestamp = 5000;
+
+ const flick = taperEngine.computeFlickTaper(
+ startX,
+ startY,
+ startWidth,
+ startPressure,
+ exitVx,
+ exitVy,
+ timestamp
+ );
+
+ expect(flick.count).toBe(8);
+
+ // Verify exponential width and pressure decay across active points
+ let prevWidth = startWidth;
+ let prevPressure = startPressure;
+ for (let i = 0; i < flick.count; i++) {
+ const pt = flick.points[i];
+ expect(pt.width).toBeLessThan(prevWidth);
+ expect(pt.pressure).toBeLessThanOrEqual(prevPressure);
+ prevWidth = pt.width;
+ prevPressure = pt.pressure;
+ }
+
+ // Final point should taper down toward hairlines
+ const lastPoint = flick.points[flick.count - 1];
+ expect(lastPoint.width).toBeLessThan(startWidth * 0.4);
+ expect(lastPoint.pressure).toBeLessThan(0.1);
+ expect(lastPoint.alpha).toBeLessThan(0.2);
+ });
+ });
+
+ describe('Phase 2 & 3: Spline Generation with Corner Commits (SplineGenerator)', () => {
+ it('generates sharp linear corner segments to apex coordinates', () => {
+ const spline = new SplineGenerator();
+ const pPrev: SplinePoint = { x: 10, y: 0, width: 4, pressure: 0.5 };
+ const pCorner: SplinePoint = { x: 20, y: 0, width: 4, pressure: 0.5 };
+
+ spline.commitCornerKnot(pCorner);
+ const segment = spline.generateCornerSegment(pPrev, pCorner);
+
+ expect(segment.p0.x).toBe(pPrev.x);
+ expect(segment.p0.y).toBe(pPrev.y);
+ expect(segment.p3.x).toBe(pCorner.x);
+ expect(segment.p3.y).toBe(pCorner.y);
+
+ // Control points should align along straight chord to apex
+ expect(segment.c1.x).toBeCloseTo(pPrev.x + (pCorner.x - pPrev.x) * 0.333, 1);
+ expect(segment.c2.x).toBeCloseTo(pPrev.x + (pCorner.x - pPrev.x) * 0.667, 1);
+ });
+ });
+
+ describe('Phase 5: WebGlBrushEngine Track A Ribbon Inking and Track B Instanced Stamps', () => {
+ it('initializes WebGlBrushEngine singleton without throwing', () => {
+ const gpu = WebGlBrushEngine.getInstance();
+ expect(gpu).toBeDefined();
+ });
+
+ it('falls back gracefully to Canvas 2D when WebGL context is unavailable', () => {
+ const gpu = WebGlBrushEngine.getInstance();
+ const mockCanvas: any = {
+ width: 400,
+ height: 400,
+ };
+ const mockCtx: any = {
+ canvas: mockCanvas,
+ save: () => {},
+ restore: () => {},
+ beginPath: () => {},
+ moveTo: () => {},
+ lineTo: () => {},
+ stroke: () => {},
+ fill: () => {},
+ drawImage: () => {},
+ globalAlpha: 1.0,
+ globalCompositeOperation: 'source-over',
+ };
+
+ const p0 = { x: 10, y: 10, width: 5, pressure: 0.5 };
+ const c1 = { x: 20, y: 15, width: 5, pressure: 0.5 };
+ const c2 = { x: 30, y: 25, width: 5, pressure: 0.5 };
+ const p3 = { x: 40, y: 40, width: 5, pressure: 0.5 };
+
+ // Should return false or safely handle ribbon segment without crashing
+ const rendered = gpu.renderRibbonSegment(mockCtx, p0, c1, c2, p3, '#000000', 1.0, 400, 400);
+ expect(typeof rendered).toBe('boolean');
+ });
+ });
+});
diff --git a/src/utils/__tests__/cspKritaOptimizations.test.ts b/src/utils/__tests__/cspKritaOptimizations.test.ts
new file mode 100644
index 0000000..4344ec9
--- /dev/null
+++ b/src/utils/__tests__/cspKritaOptimizations.test.ts
@@ -0,0 +1,337 @@
+import { describe, it, expect } from 'vitest';
+import {
+ BLEND_MODE_MAP,
+ COMPOSITOR_FRAGMENT_SHADER,
+ FOLDER_BLIT_FRAGMENT_SHADER,
+ ViewportCompositor,
+} from '../compositor';
+import {
+ linearRgbToOklab,
+ oklabToLinearRgb,
+ mixSubtractivePigments,
+ PaintReservoir,
+ LayerPixelSampler,
+} from '../colorMixingEngine';
+import {
+ SparseTileGrid,
+ BYTES_32BIT,
+} from '../tileEngine';
+import {
+ compressTileDeltasPayload,
+ decompressTileDeltasPayload,
+ UndoCacheManager,
+ MAX_RAM_UNDO_STEPS,
+} from '../undoCache';
+import {
+ executeFloodFill,
+ compositeReferenceLayers,
+} from '../floodFill';
+import {
+ LIQUIFY_FRAGMENT_SHADER,
+ WebGlLiquifyEngine,
+} from '../liquifyEngine';
+import {
+ GAUSSIAN_BLUR_FRAGMENT_SHADER,
+ MOTION_BLUR_FRAGMENT_SHADER,
+ WebGlFilterEngine,
+} from '../filterEngine';
+import { WebGlBrushEngine } from '../webglBrushEngine';
+import { HistoryItem } from '../../types/editor';
+
+describe('CSP & Krita Rendering and Engine Optimizations', () => {
+ describe('1. WebGL2 Tile Compositor & Programmable Blend Modes', () => {
+ it('supports all 17 W3C / CSP / Krita blend modes in BLEND_MODE_MAP and shaders', () => {
+ expect(BLEND_MODE_MAP['normal']).toBe(0);
+ expect(BLEND_MODE_MAP['multiply']).toBe(1);
+ expect(BLEND_MODE_MAP['screen']).toBe(2);
+ expect(BLEND_MODE_MAP['overlay']).toBe(3);
+ expect(BLEND_MODE_MAP['darken']).toBe(4);
+ expect(BLEND_MODE_MAP['lighten']).toBe(5);
+ expect(BLEND_MODE_MAP['color-dodge']).toBe(6);
+ expect(BLEND_MODE_MAP['color-burn']).toBe(7);
+ expect(BLEND_MODE_MAP['hard-light']).toBe(8);
+ expect(BLEND_MODE_MAP['soft-light']).toBe(9);
+ expect(BLEND_MODE_MAP['difference']).toBe(10);
+ expect(BLEND_MODE_MAP['exclusion']).toBe(11);
+ expect(BLEND_MODE_MAP['pass-through']).toBe(12);
+ expect(BLEND_MODE_MAP['linear-burn']).toBe(13);
+ expect(BLEND_MODE_MAP['add-glow']).toBe(14);
+ expect(BLEND_MODE_MAP['color-dodge-glow']).toBe(15);
+ expect(BLEND_MODE_MAP['divide']).toBe(16);
+
+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain('vec3 evaluateBlendMode(vec3 Cb, vec3 Cs, int mode)');
+ expect(COMPOSITOR_FRAGMENT_SHADER).toContain('uniform sampler2D u_backdropTexture;');
+ expect(FOLDER_BLIT_FRAGMENT_SHADER).toContain('vec3 evaluateBlendModeFolder(vec3 Cb, vec3 Cs, int mode)');
+ });
+
+ it('supports mask dirty-version invalidation on ViewportCompositor', () => {
+ const dummyCanvas = { getContext: () => null } as unknown as HTMLCanvasElement;
+ const compositor = new ViewportCompositor(dummyCanvas);
+ expect(typeof compositor.invalidateMaskTexture).toBe('function');
+ compositor.invalidateMaskTexture('layer-1');
+ });
+ });
+
+ describe('2. OKLab + Kubelka-Munk Perceptual Pigment Mixing & Zero-Copy Tile Sampling', () => {
+ it('round-trips linear RGB to OKLab and back accurately', () => {
+ const samples = [
+ [1.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.4, 0.8],
+ [1.0, 0.85, 0.0],
+ [0.5, 0.25, 0.75],
+ ];
+ for (const [r, g, b] of samples) {
+ const lab = linearRgbToOklab(r, g, b);
+ const rgb = oklabToLinearRgb(lab.L, lab.a, lab.b);
+ expect(Math.abs(rgb.r - r)).toBeLessThan(1e-3);
+ expect(Math.abs(rgb.g - g)).toBeLessThan(1e-3);
+ expect(Math.abs(rgb.b - b)).toBeLessThan(1e-3);
+ }
+ });
+
+ it('mixes Yellow (#ffea00) and Blue (#0048ff) into vibrant Green instead of muddy gray', () => {
+ // Pure yellow and pure blue in RGB average to (128, 153, 128) dull gray,
+ // whereas Kubelka-Munk + OKLab spectral pigment mixing yields a green-dominant hue.
+ const mixed = mixSubtractivePigments({ r: 255, g: 234, b: 0 }, { r: 0, g: 72, b: 255 }, 0.5);
+ expect(mixed.g).toBeGreaterThan(mixed.r + 35);
+ expect(mixed.g).toBeGreaterThan(mixed.b + 20);
+
+ const res = new PaintReservoir('#0048ff');
+ const out = res.mixWithCanvas(
+ { r: 255, g: 234, b: 0, a: 1.0 },
+ 0.5,
+ 0.9,
+ 0.75,
+ 'blend',
+ 0.8,
+ 1.0,
+ 1.0
+ );
+ expect(out.g).toBeGreaterThan(out.r);
+ });
+
+ it('samples pixels directly from SparseTileGrid on 4K layers without full-canvas getImageData', () => {
+ const grid = new SparseTileGrid();
+ grid.setLayerFormat('layer-wet', 'color-32bit');
+
+ const patch = new Uint8ClampedArray(16 * 16 * 4);
+ for (let i = 0; i < 16 * 16; i++) {
+ patch[i * 4] = 40;
+ patch[i * 4 + 1] = 180;
+ patch[i * 4 + 2] = 90;
+ patch[i * 4 + 3] = 255;
+ }
+ grid.writeImageData('layer-wet', { data: patch, width: 16, height: 16 }, 300, 300);
+
+ // Mock a 4K canvas whose getContext('2d') throws if full getImageData were called
+ const mock4kCanvas = {
+ width: 4096,
+ height: 4096,
+ getContext: () => ({
+ getImageData: () => {
+ throw new Error('Should not call Canvas2D getImageData when SparseTileGrid has tiles');
+ },
+ }),
+ } as unknown as HTMLCanvasElement;
+
+ const sampler = new LayerPixelSampler(mock4kCanvas, 'layer-wet', grid);
+ const sampled = sampler.sampleColor(308, 308, 4);
+ expect(sampled.r).toBeCloseTo(40, 0);
+ expect(sampled.g).toBeCloseTo(180, 0);
+ expect(sampled.b).toBeCloseTo(90, 0);
+ expect(sampled.a).toBeGreaterThan(0.8);
+ });
+ });
+
+ describe('3. UndoCache fflate Compression & Compressed RAM Fallback', () => {
+ it('compresses and decompresses tile deltas losslessly with high compression ratio', () => {
+ const beforeData = new Uint8Array(BYTES_32BIT);
+ const afterData = new Uint8Array(BYTES_32BIT);
+ afterData.fill(200, 0, 4096);
+
+ const deltas = [
+ {
+ key: 'layer-1:0:0',
+ format: 'color-32bit' as const,
+ beforeData,
+ afterData,
+ },
+ ];
+
+ const compressed = compressTileDeltasPayload(deltas);
+ // 512KB of raw tile delta should compress down to < 2KB
+ expect(compressed.byteLength).toBeLessThan(2048);
+
+ const restored = decompressTileDeltasPayload(compressed);
+ expect(restored.length).toBe(1);
+ expect(restored[0].key).toBe('layer-1:0:0');
+ expect(restored[0].afterData![0]).toBe(200);
+ expect(restored[0].afterData![5000]).toBe(0);
+ });
+
+ it('offloads older undo steps into compressed RAM cache when exceeding MAX_RAM_UNDO_STEPS in browser mode', async () => {
+ const cache = new UndoCacheManager('test-session');
+ const history: HistoryItem[] = [];
+
+ for (let i = 0; i < MAX_RAM_UNDO_STEPS + 3; i++) {
+ const afterData = new Uint8Array(1024);
+ afterData.fill(i + 1);
+ const item: HistoryItem = {
+ id: `step-${i}`,
+ type: 'brush',
+ label: `Stroke ${i}`,
+ timestamp: Date.now() + i,
+ timeFormatted: '12:00',
+ thumbnailUrl: '',
+ beforeImageData: null,
+ afterImageData: null,
+ layerId: 'layer-1',
+ tileDeltas: [
+ {
+ key: 'layer-1:0:0',
+ format: 'monochrome-1bit',
+ beforeData: null,
+ afterData,
+ },
+ ],
+ };
+ history.push(item);
+ await cache.registerStep(item, history);
+ }
+
+ // Oldest 3 steps should have their uncompressed tileDeltas freed from RAM
+ expect(history[0].tileDeltas).toBeUndefined();
+ expect(history[1].tileDeltas).toBeUndefined();
+
+ // Resolving step-0 should transparently decompress and restore its tileDeltas
+ const resolved = await cache.resolveDeltas(history[0]);
+ expect(resolved).not.toBeNull();
+ expect(resolved![0].afterData![0]).toBe(1);
+ });
+ });
+
+ describe('4. CSP-Grade Smart Flood Fill (Close Gap, Area Scaling, Reference Layer)', () => {
+ function createMockCanvas(width: number, height: number) {
+ const buffer = new Uint8ClampedArray(width * height * 4);
+ // Fill with white background (255, 255, 255, 255)
+ for (let i = 0; i < width * height; i++) {
+ buffer[i * 4] = 255;
+ buffer[i * 4 + 1] = 255;
+ buffer[i * 4 + 2] = 255;
+ buffer[i * 4 + 3] = 255;
+ }
+ const ctx = {
+ getImageData: () => ({ data: new Uint8ClampedArray(buffer), width, height }),
+ putImageData: (imgData: { data: Uint8ClampedArray }) => {
+ buffer.set(imgData.data);
+ },
+ save: () => {},
+ restore: () => {},
+ drawImage: () => {},
+ };
+ const canvas = {
+ width,
+ height,
+ getContext: () => ctx,
+ _buffer: buffer,
+ } as unknown as HTMLCanvasElement & { _buffer: Uint8ClampedArray };
+ return canvas;
+ }
+
+ it('bridges small line-art gaps when closeGap > 0 without leaking outside the box', () => {
+ const w = 40;
+ const h = 40;
+ const refCanvas = createMockCanvas(w, h);
+ const targetNoClose = createMockCanvas(w, h);
+ const targetWithClose = createMockCanvas(w, h);
+
+ // Draw a black box from (10, 10) to (30, 30) with a 2-pixel gap at top wall (x = 19, 20, y = 10)
+ const setBlack = (x: number, y: number) => {
+ const idx = (y * w + x) * 4;
+ refCanvas._buffer[idx] = 0;
+ refCanvas._buffer[idx + 1] = 0;
+ refCanvas._buffer[idx + 2] = 0;
+ refCanvas._buffer[idx + 3] = 255;
+ };
+
+ for (let x = 10; x <= 30; x++) {
+ if (x !== 19 && x !== 20) setBlack(x, 10); // 2px gap in top wall
+ setBlack(x, 30);
+ }
+ for (let y = 10; y <= 30; y++) {
+ setBlack(10, y);
+ setBlack(30, y);
+ }
+
+ // Without closeGap, filling at center (20, 20) leaks through the gap to (2, 2)
+ executeFloodFill(targetNoClose, refCanvas, 20, 20, '#ff0000', 10, null, { closeGap: 0 });
+ const leakIdx = (2 * w + 2) * 4;
+ expect(targetNoClose._buffer[leakIdx]).toBe(255);
+ expect(targetNoClose._buffer[leakIdx + 1]).toBe(0); // Leaked red outside!
+
+ // With closeGap = 4, the 2px gap is bridged and (2, 2) stays untouched white!
+ executeFloodFill(targetWithClose, refCanvas, 20, 20, '#ff0000', 10, null, { closeGap: 4 });
+ expect(targetWithClose._buffer[leakIdx]).toBe(255);
+ expect(targetWithClose._buffer[leakIdx + 1]).toBe(255); // Untouched white outside!
+
+ // Inside box (20, 20) is filled with red
+ const insideIdx = (20 * w + 20) * 4;
+ expect(targetWithClose._buffer[insideIdx]).toBe(255);
+ expect(targetWithClose._buffer[insideIdx + 1]).toBe(0);
+ expect(targetWithClose._buffer[insideIdx + 2]).toBe(0);
+ });
+
+ it('expands and shrinks the filled area according to areaScale', () => {
+ const w = 40;
+ const h = 40;
+ const refCanvas = createMockCanvas(w, h);
+ const targetExpand = createMockCanvas(w, h);
+ const targetShrink = createMockCanvas(w, h);
+
+ // Draw a thick 3px gray border around (10..30, 10..30)
+ for (let y = 8; y <= 32; y++) {
+ for (let x = 8; x <= 32; x++) {
+ if (x <= 10 || x >= 30 || y <= 10 || y >= 30) {
+ const idx = (y * w + x) * 4;
+ refCanvas._buffer[idx] = 100;
+ refCanvas._buffer[idx + 1] = 100;
+ refCanvas._buffer[idx + 2] = 100;
+ refCanvas._buffer[idx + 3] = 255;
+ }
+ }
+ }
+
+ const resExpand = executeFloodFill(targetExpand, refCanvas, 20, 20, '#00ff00', 10, null, {
+ areaScale: 2,
+ });
+ const resShrink = executeFloodFill(targetShrink, refCanvas, 20, 20, '#00ff00', 10, null, {
+ areaScale: -2,
+ });
+
+ expect(resExpand.dirtyRect!.width).toBeGreaterThan(resShrink.dirtyRect!.width);
+ // Pixel at (10, 20) is inside the border and gets filled when expanded by +2
+ const borderIdx = (20 * w + 10) * 4;
+ expect(targetExpand._buffer[borderIdx + 1]).toBe(255);
+ // Pixel at (12, 20) is 1px inside the wall and is left unfilled when shrunk by -2
+ const shrinkEdgeIdx = (20 * w + 12) * 4;
+ expect(targetShrink._buffer[shrinkEdgeIdx + 1]).toBe(255);
+ expect(targetShrink._buffer[shrinkEdgeIdx]).toBe(255); // Still white
+ });
+
+ it('exposes compositeReferenceLayers for Reference Layer bucket filling', () => {
+ expect(typeof compositeReferenceLayers).toBe('function');
+ });
+ });
+
+ describe('5. GPU Shaders for Brush Dual-Tip, Liquify, and Convolution Filters', () => {
+ it('includes GPU Liquify and Convolution Filter engines with graceful headless fallback', () => {
+ expect(LIQUIFY_FRAGMENT_SHADER).toContain('uniform int u_mode;');
+ expect(GAUSSIAN_BLUR_FRAGMENT_SHADER).toContain('uniform float u_radius;');
+ expect(MOTION_BLUR_FRAGMENT_SHADER).toContain('uniform vec2 u_stepVec;');
+ expect(WebGlLiquifyEngine.getInstance()).toBeDefined();
+ expect(WebGlFilterEngine.getInstance()).toBeDefined();
+ expect(WebGlBrushEngine.getInstance()).toBeDefined();
+ });
+ });
+});
diff --git a/src/utils/__tests__/strokeHandshake.test.ts b/src/utils/__tests__/strokeHandshake.test.ts
new file mode 100644
index 0000000..bf50f18
--- /dev/null
+++ b/src/utils/__tests__/strokeHandshake.test.ts
@@ -0,0 +1,145 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ SparseTileGrid,
+} from '../tileEngine';
+import { binarizeCanvasRect } from '../colorUtils';
+import { TaperEngine } from '../../engine/TaperEngine';
+
+describe('Zero-Flicker Stroke Handshake & WYSIWYG Monochrome Pipeline', () => {
+ let grid: SparseTileGrid;
+
+ beforeEach(() => {
+ grid = new SparseTileGrid();
+ });
+
+ it('guarantees atomic synchronous tile commit and decoupled delta generation', () => {
+ const layerId = 'layer-test';
+ const dirtyRect = { x: 50, y: 50, width: 100, height: 100 };
+
+ // 1. Initial layer state
+ const initialBuffer = new Uint8ClampedArray(100 * 100 * 4);
+ // Draw initial blue square
+ for (let i = 0; i < 100 * 100; i++) {
+ initialBuffer[i * 4 + 2] = 255;
+ initialBuffer[i * 4 + 3] = 255;
+ }
+ grid.writeImageData(layerId, { data: initialBuffer, width: 100, height: 100 }, 50, 50, 'color-32bit');
+
+ // 2. Stroke ends on pointerup: take beforeSnapshot SYNCHRONOUSLY
+ const beforeSnapshot = grid.snapshotTilesInRect(layerId, dirtyRect);
+ expect(beforeSnapshot.size).toBeGreaterThan(0);
+
+ // 3. Stroke commits pixels to canvas, then writes to grid SYNCHRONOUSLY
+ let notifyFired = false;
+ const unsub = grid.subscribe((immediate) => {
+ if (immediate) notifyFired = true;
+ });
+
+ const newStrokeBuffer = new Uint8ClampedArray(100 * 100 * 4);
+ // Overwrite with red stroke
+ for (let i = 0; i < 100 * 100; i++) {
+ newStrokeBuffer[i * 4] = 255;
+ newStrokeBuffer[i * 4 + 3] = 255;
+ }
+ grid.writeImageData(layerId, { data: newStrokeBuffer, width: 100, height: 100 }, 50, 50, 'color-32bit');
+ grid.notifyChange(true);
+
+ // Grid MUST have the new stroke tiles IMMEDIATELY (zero waiting for background tasks)
+ expect(notifyFired).toBe(true);
+ const tile = grid.getTile(layerId, 0, 0);
+ expect(tile).not.toBeNull();
+ expect(tile?.dirty).toBe(true);
+
+ // 4. In background/idle task: compute deltas from beforeSnapshot
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, layerId, dirtyRect);
+ expect(tileDeltas.length).toBeGreaterThan(0);
+
+ // 5. Verify undo/redo parity
+ grid.applyTileDeltas(tileDeltas, 'undo');
+ const undoData = grid.readImageData(layerId, 50, 50, 100, 100);
+ // Should be restored to blue
+ expect(undoData.data[0]).toBe(0);
+ expect(undoData.data[2]).toBe(255);
+
+ grid.applyTileDeltas(tileDeltas, 'redo');
+ const redoData = grid.readImageData(layerId, 50, 50, 100, 100);
+ // Should be red again
+ expect(redoData.data[0]).toBe(255);
+ expect(redoData.data[2]).toBe(0);
+
+ unsub();
+ });
+
+ it('guarantees identical thresholding between binarizeCanvasRect and monochrome 1-bit tile packing', () => {
+ // Mock canvas context
+ const width = 10;
+ const height = 10;
+ const buffer = new Uint8ClampedArray(width * height * 4);
+
+ // Fill with a gradient of alpha (from 0 to 255)
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ const alpha = Math.round(((y * width + x) / (width * height - 1)) * 255);
+ buffer[idx] = 0; // R
+ buffer[idx + 1] = 0; // G
+ buffer[idx + 2] = 0; // B
+ buffer[idx + 3] = alpha;
+ }
+ }
+
+ const mockCtx = {
+ canvas: { width, height },
+ getImageData: (_sx: number, _sy: number, sw: number, sh: number) => ({
+ data: buffer,
+ width: sw,
+ height: sh,
+ }),
+ putImageData: (_imgData: { data: Uint8ClampedArray }, _sx: number, _sy: number) => {},
+ } as unknown as CanvasRenderingContext2D;
+
+ // Apply binarizeCanvasRect with default threshold 128
+ binarizeCanvasRect(mockCtx, { x: 0, y: 0, width, height }, 128, true, true);
+
+ // Check that every pixel with alpha < 128 was zeroed, and >= 128 is solid opaque black
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const idx = (y * width + x) * 4;
+ const origAlpha = Math.round(((y * width + x) / (width * height - 1)) * 255);
+ if (origAlpha < 128) {
+ expect(buffer[idx + 3]).toBe(0);
+ } else {
+ expect(buffer[idx + 3]).toBe(255);
+ expect(buffer[idx]).toBe(0); // Black ink
+ }
+ }
+ }
+ });
+
+ it('flick taper preserves exit velocity and generates natural tapering knots', () => {
+ const taper = new TaperEngine();
+ taper.configure(undefined, { minFlickSpeed: 0.5, flickPoints: 8 });
+
+ // High exit speed flick (1.5 px/ms)
+ const exitVx = 1.2;
+ const exitVy = 0.9;
+ const lastWidth = 20;
+ const lastPressure = 0.8;
+ const now = 1000;
+
+ const flick = taper.computeFlickTaper(100, 100, lastWidth, lastPressure, exitVx, exitVy, now);
+
+ expect(flick.count).toBe(8);
+ expect(flick.points.length).toBeGreaterThanOrEqual(8);
+
+ // Verify exponential tapering (width and pressure strictly decrease)
+ let prevW = lastWidth;
+ for (let i = 0; i < flick.count; i++) {
+ const p = flick.points[i];
+ expect(p.width).toBeLessThan(prevW);
+ prevW = p.width;
+ }
+ // Final point should taper close to minimum
+ expect(flick.points[flick.count - 1].width).toBeLessThan(5);
+ });
+});
diff --git a/src/utils/canvasUtils.ts b/src/utils/canvasUtils.ts
index e504d43..de1aa80 100644
--- a/src/utils/canvasUtils.ts
+++ b/src/utils/canvasUtils.ts
@@ -208,16 +208,20 @@ export const BLEND_MODES: { value: BlendMode; label: string }[] = [
{ value: 'pass-through', label: 'Pass Through' },
{ value: 'normal', label: 'Normal' },
{ value: 'multiply', label: 'Multiply' },
- { value: 'screen', label: 'Screen' },
- { value: 'overlay', label: 'Overlay' },
+ { value: 'linear-burn', label: 'Linear Burn' },
+ { value: 'color-burn', label: 'Color Burn' },
{ value: 'darken', label: 'Darken' },
- { value: 'lighten', label: 'Lighten' },
+ { value: 'screen', label: 'Screen' },
{ value: 'color-dodge', label: 'Color Dodge' },
- { value: 'color-burn', label: 'Color Burn' },
- { value: 'hard-light', label: 'Hard Light' },
+ { value: 'color-dodge-glow', label: 'Glow Dodge' },
+ { value: 'add-glow', label: 'Add (Glow)' },
+ { value: 'lighten', label: 'Lighten' },
+ { value: 'overlay', label: 'Overlay' },
{ value: 'soft-light', label: 'Soft Light' },
+ { value: 'hard-light', label: 'Hard Light' },
{ value: 'difference', label: 'Difference' },
{ value: 'exclusion', label: 'Exclusion' },
+ { value: 'divide', label: 'Divide' },
];
export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalCompositeOperation {
@@ -236,14 +240,19 @@ export function getCanvasCompositeOperation(blendMode: BlendMode): GlobalComposi
case 'lighten':
return 'lighten';
case 'color-dodge':
+ case 'color-dodge-glow':
return 'color-dodge';
case 'color-burn':
+ case 'linear-burn':
return 'color-burn';
+ case 'add-glow':
+ return 'lighter';
case 'hard-light':
return 'hard-light';
case 'soft-light':
return 'soft-light';
case 'difference':
+ case 'divide':
return 'difference';
case 'exclusion':
return 'exclusion';
@@ -569,7 +578,7 @@ export function renderCompleteStroke(
paperTextureImage: brushSettings.paperTextureImage,
paperTextureScale: brushSettings.paperTextureScale,
paperTextureRotate: brushSettings.paperTextureRotate,
- useGpu: false,
+ useGpu: Boolean(brushSettings.useGpu),
underlyingCanvas: underlyingCanvas || ctx.canvas,
sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
@@ -604,7 +613,7 @@ export function renderCompleteStroke(
colorStretch: brushSettings.colorStretch,
mixingMode: brushSettings.mixingMode,
underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ sampler: (brushSettings.colorMixing && underlyingCanvas) ? new LayerPixelSampler(underlyingCanvas) : undefined,
reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
alphaLocked,
isTransparentInk,
@@ -663,7 +672,7 @@ export function renderCompleteStroke(
colorStretch: brushSettings.colorStretch,
mixingMode: brushSettings.mixingMode,
underlyingCanvas: underlyingCanvas || ctx.canvas,
- sampler: underlyingCanvas ? new LayerPixelSampler(underlyingCanvas) : undefined,
+ sampler: (brushSettings.colorMixing && underlyingCanvas) ? new LayerPixelSampler(underlyingCanvas) : undefined,
reservoir: (brushSettings.colorMixing && !isEraser) ? new PaintReservoir(strokeColor) : undefined,
alphaLocked,
isTransparentInk,
diff --git a/src/utils/colorMixingEngine.ts b/src/utils/colorMixingEngine.ts
index ff5660b..ef1a14a 100644
--- a/src/utils/colorMixingEngine.ts
+++ b/src/utils/colorMixingEngine.ts
@@ -133,10 +133,12 @@ export function oklabToLinearRgb(L: number, a: number, b: number): { r: number;
};
}
+import { SparseTileGrid, TILE_SIZE, globalTileGrid } from './tileEngine';
+
/**
- * Subtractive Pigment Mixing (Physical Paint Simulation).
- * Simulates real-world physical absorption where Blue + Yellow = Green,
- * Red + Blue = Purple, and colors don't collapse into dull muddy grays!
+ * 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!
*/
export function mixSubtractivePigments(
c1: RgbColor,
@@ -155,8 +157,7 @@ export function mixSubtractivePigments(
const g2 = srgbToLinear(c2.g);
const b2 = srgbToLinear(c2.b);
- // 1. Subtractive absorption coefficients (Kubelka-Munk approximation)
- // Higher absorption = darker pigment absorption in that channel
+ // 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);
@@ -169,18 +170,33 @@ export function mixSubtractivePigments(
const mixAbsG = absG1 * w1 + absG2 * w2;
const mixAbsB = absB1 * w1 + absB2 * w2;
- const subR = Math.pow(Math.max(0, 1 - mixAbsR), 2);
- const subG = Math.pow(Math.max(0, 1 - mixAbsG), 2);
- const subB = Math.pow(Math.max(0, 1 - mixAbsB), 2);
+ 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));
+ }
- // 2. Perceptual Lightness correction via OKLab
+ // 3. Perceptual Lightness & Chroma preservation via OKLab
const lab1 = linearRgbToOklab(r1, g1, b1);
const lab2 = linearRgbToOklab(r2, g2, b2);
const targetLightness = lab1.L * w1 + lab2.L * w2;
const subLab = linearRgbToOklab(subR, subG, subB);
const tunedLab = {
- L: Math.max(0.01, targetLightness * 0.75 + subLab.L * 0.25),
+ L: Math.max(0.01, targetLightness * 0.72 + subLab.L * 0.28),
a: subLab.a,
b: subLab.b,
};
@@ -195,8 +211,8 @@ export function mixSubtractivePigments(
}
// -------------------------------------------------------------
-// Ultra-Fast Zero-Lag In-Memory Pixel Sampler
-// Eliminates GPU readback stalls (getImageData) during live drawing!
+// Ultra-Fast Zero-Lag Tile-Aware In-Memory Pixel Sampler
+// Eliminates full-canvas GPU readback stalls (getImageData) during live drawing!
// -------------------------------------------------------------
export class LayerPixelSampler {
@@ -204,14 +220,38 @@ export class LayerPixelSampler {
public height: number;
public data: Uint8ClampedArray;
public u32: Uint32Array;
-
- constructor(sourceCanvas: HTMLCanvasElement) {
+ private sourceCtx: CanvasRenderingContext2D | null = null;
+ private tileGrid: SparseTileGrid | null = null;
+ private layerId: string | null = null;
+ private useLazyTiles: boolean = false;
+ private lazyTiles: Map<number, Uint8ClampedArray> = new Map();
+ private tilesX: number = 1;
+
+ constructor(
+ sourceCanvas: HTMLCanvasElement,
+ layerId?: string,
+ tileGrid: SparseTileGrid = globalTileGrid
+ ) {
this.width = sourceCanvas.width;
this.height = sourceCanvas.height;
- const ctx = sourceCanvas.getContext('2d', { willReadFrequently: true });
- if (ctx && this.width > 0 && this.height > 0) {
+ this.tilesX = Math.max(1, Math.ceil(this.width / TILE_SIZE));
+ this.sourceCtx = sourceCanvas.getContext('2d', { willReadFrequently: true });
+
+ // If a SparseTileGrid has tiles for this layer, or if the canvas is large (> 512x512),
+ // use zero-stall on-demand 256x256 tile caching instead of a synchronous full-document getImageData!
+ const hasGridTiles = Boolean(layerId && tileGrid && tileGrid.getLayerTiles(layerId).length > 0);
+ const isLargeCanvas = this.width * this.height > 512 * 512;
+
+ if (hasGridTiles || isLargeCanvas) {
+ this.useLazyTiles = true;
+ this.layerId = layerId ?? null;
+ this.tileGrid = hasGridTiles ? tileGrid : null;
+ // Allocate a minimal 1-pixel placeholder for legacy property access
+ this.data = new Uint8ClampedArray(4);
+ this.u32 = new Uint32Array(this.data.buffer);
+ } else if (this.sourceCtx && this.width > 0 && this.height > 0) {
try {
- const imgData = ctx.getImageData(0, 0, this.width, this.height);
+ const imgData = this.sourceCtx.getImageData(0, 0, this.width, this.height);
this.data = imgData.data;
this.u32 = new Uint32Array(this.data.buffer);
} catch {
@@ -225,7 +265,53 @@ export class LayerPixelSampler {
}
/**
- * Samples average color and opacity in microseconds with ZERO GPU pipeline flushes!
+ * Fetches or initializes a 256x256 RGBA tile in CPU memory on demand (zero full-canvas stall).
+ */
+ private getOrLoadTile(tx: number, ty: number): Uint8ClampedArray {
+ const key = ty * this.tilesX + tx;
+ let buf = this.lazyTiles.get(key);
+ if (buf) return buf;
+
+ if (this.tileGrid && this.layerId) {
+ const tile = this.tileGrid.getTile(this.layerId, tx, ty);
+ if (tile) {
+ const rgba = this.tileGrid.getTileAsRGBA(tile);
+ buf = new Uint8ClampedArray(rgba.length);
+ buf.set(rgba);
+ this.lazyTiles.set(key, buf);
+ return buf;
+ }
+ }
+
+ buf = new Uint8ClampedArray(TILE_SIZE * TILE_SIZE * 4);
+ if (this.sourceCtx) {
+ const sx = tx * TILE_SIZE;
+ const sy = ty * TILE_SIZE;
+ const sw = Math.min(TILE_SIZE, this.width - sx);
+ const sh = Math.min(TILE_SIZE, this.height - sy);
+ if (sw > 0 && sh > 0) {
+ try {
+ const img = this.sourceCtx.getImageData(sx, sy, sw, sh);
+ if (sw === TILE_SIZE && sh === TILE_SIZE) {
+ buf.set(img.data);
+ } else {
+ for (let row = 0; row < sh; row++) {
+ const srcOff = row * sw * 4;
+ const dstOff = row * TILE_SIZE * 4;
+ buf.set(img.data.subarray(srcOff, srcOff + sw * 4), dstOff);
+ }
+ }
+ } catch {
+ // Ignore security/context errors
+ }
+ }
+ }
+ this.lazyTiles.set(key, buf);
+ return buf;
+ }
+
+ /**
+ * Samples average color and opacity in microseconds with ZERO full-canvas GPU pipeline flushes!
*/
public sampleColor(cx: number, cy: number, radius: number): RgbaColor {
const r = Math.max(1, Math.min(64, Math.round(radius)));
@@ -238,6 +324,67 @@ export class LayerPixelSampler {
return { r: 255, g: 255, b: 255, a: 0 };
}
+ if (this.useLazyTiles) {
+ if (r <= 2) {
+ const clampedX = Math.max(0, Math.min(w - 1, ix));
+ const clampedY = Math.max(0, Math.min(h - 1, iy));
+ const tile = this.getOrLoadTile(clampedX >> 8, clampedY >> 8);
+ const idx = (((clampedY & 255) << 8) + (clampedX & 255)) << 2;
+ const alpha = tile[idx + 3];
+ return {
+ r: tile[idx],
+ g: tile[idx + 1],
+ b: tile[idx + 2],
+ a: alpha / 255,
+ };
+ }
+
+ const x0 = Math.max(0, ix - r);
+ const x1 = Math.min(w - 1, ix + r);
+ const y0 = Math.max(0, iy - r);
+ const y1 = Math.min(h - 1, iy + r);
+
+ const step = Math.max(1, Math.floor(r / 3.5));
+ let sumR = 0;
+ let sumG = 0;
+ let sumB = 0;
+ let weightSum = 0;
+ const rSq = r * r;
+
+ for (let y = y0; y <= y1; y += step) {
+ const dy = y - iy;
+ const dySq = dy * dy;
+ const ty = y >> 8;
+ const lyOffset = (y & 255) << 8;
+ for (let x = x0; x <= x1; x += step) {
+ const dx = x - ix;
+ const distSq = dx * dx + dySq;
+ if (distSq <= rSq) {
+ const tile = this.getOrLoadTile(x >> 8, ty);
+ const idx = (lyOffset + (x & 255)) << 2;
+ const alpha = tile[idx + 3];
+ if (alpha > 4) {
+ const radialWeight = (1 - distSq / rSq) * (alpha / 255);
+ sumR += tile[idx] * radialWeight;
+ sumG += tile[idx + 1] * radialWeight;
+ sumB += tile[idx + 2] * radialWeight;
+ weightSum += radialWeight;
+ }
+ }
+ }
+ }
+
+ if (weightSum > 0.001) {
+ return {
+ r: sumR / weightSum,
+ g: sumG / weightSum,
+ b: sumB / weightSum,
+ a: Math.min(1.0, weightSum),
+ };
+ }
+ return { r: 255, g: 255, b: 255, a: 0 };
+ }
+
// Direct center sample for fine tips (<= 2.5px)
if (r <= 2) {
const clampedX = Math.max(0, Math.min(w - 1, ix));
@@ -261,7 +408,6 @@ export class LayerPixelSampler {
let sumR = 0;
let sumG = 0;
let sumB = 0;
- let sumA = 0;
let weightSum = 0;
const rSq = r * r;
@@ -281,7 +427,6 @@ export class LayerPixelSampler {
sumR += this.data[idx] * radialWeight;
sumG += this.data[idx + 1] * radialWeight;
sumB += this.data[idx + 2] * radialWeight;
- sumA += alpha;
weightSum += radialWeight;
}
}
@@ -328,6 +473,38 @@ export class LayerPixelSampler {
const invRadSq = 1 / radSq;
const step = Math.max(1, Math.floor(rad / 4.5));
+ if (this.useLazyTiles) {
+ for (let y = y0; y <= y1; y += step) {
+ const dy = y - iy;
+ const dySq = dy * dy;
+ const ty = y >> 8;
+ const lyOffset = (y & 255) << 8;
+ for (let x = x0; x <= x1; x += step) {
+ const dx = x - ix;
+ const dSq = dx * dx + dySq;
+ if (dSq <= radSq) {
+ const falloff = 1 - dSq * invRadSq;
+ const effAlpha = Math.min(1.0, a * falloff);
+ const tile = this.getOrLoadTile(x >> 8, ty);
+ const idx = (lyOffset + (x & 255)) << 2;
+ const dstA = tile[idx + 3] / 255;
+ const outA = effAlpha + dstA * (1 - effAlpha);
+ if (outA > 0.001) {
+ const outR = (r * effAlpha + tile[idx] * dstA * (1 - effAlpha)) / outA;
+ const outG = (g * effAlpha + tile[idx + 1] * dstA * (1 - effAlpha)) / outA;
+ const outB = (b * effAlpha + tile[idx + 2] * dstA * (1 - effAlpha)) / outA;
+
+ tile[idx] = Math.round(outR);
+ tile[idx + 1] = Math.round(outG);
+ tile[idx + 2] = Math.round(outB);
+ tile[idx + 3] = Math.round(Math.min(255, outA * 255));
+ }
+ }
+ }
+ }
+ return;
+ }
+
for (let y = y0; y <= y1; y += step) {
const dy = y - iy;
const dySq = dy * dy;
diff --git a/src/utils/colorUtils.ts b/src/utils/colorUtils.ts
index a19dc7d..8a37e93 100644
--- a/src/utils/colorUtils.ts
+++ b/src/utils/colorUtils.ts
@@ -109,25 +109,15 @@ export function applyColorModeToImageData(imageData: ImageData, mode: CanvasColo
}
/**
- * Ultra-fast 32-bit in-place binary thresholding on a canvas context rect.
- * Converts anti-aliased stroke edges to 1-bit crisp binary output in real time (<0.05ms).
+ * Ultra-fast 32-bit in-place binary thresholding directly on ImageData buffer.
*/
-export function binarizeCanvasRect(
- ctx: CanvasRenderingContext2D,
- rect: { x: number; y: number; width: number; height: number },
+export function binarizeImageDataBuffer(
+ imgData: ImageData | { data: Uint8ClampedArray | Uint8Array; width: number; height: number },
threshold: number = 128,
expressBlack: boolean = true,
expressWhite: boolean = true
) {
- const sx = Math.max(0, Math.floor(rect.x));
- const sy = Math.max(0, Math.floor(rect.y));
- const sw = Math.min(ctx.canvas.width - sx, Math.ceil(rect.width));
- const sh = Math.min(ctx.canvas.height - sy, Math.ceil(rect.height));
-
- if (sw <= 0 || sh <= 0) return;
-
- const imgData = ctx.getImageData(sx, sy, sw, sh);
- const u32 = new Uint32Array(imgData.data.buffer);
+ const u32 = new Uint32Array(imgData.data.buffer, imgData.data.byteOffset, (imgData.width * imgData.height));
const len = u32.length;
const thresh = Math.max(1, Math.min(255, threshold));
@@ -148,7 +138,28 @@ export function binarizeCanvasRect(
u32[i] = expressWhite ? 0xFFFFFFFF : 0;
}
}
+}
+/**
+ * Ultra-fast 32-bit in-place binary thresholding on a canvas context rect.
+ * Converts anti-aliased stroke edges to 1-bit crisp binary output in real time (<0.05ms).
+ */
+export function binarizeCanvasRect(
+ ctx: CanvasRenderingContext2D,
+ rect: { x: number; y: number; width: number; height: number },
+ threshold: number = 128,
+ expressBlack: boolean = true,
+ expressWhite: boolean = true
+) {
+ const sx = Math.max(0, Math.floor(rect.x));
+ const sy = Math.max(0, Math.floor(rect.y));
+ const sw = Math.min(ctx.canvas.width - sx, Math.ceil(rect.width));
+ const sh = Math.min(ctx.canvas.height - sy, Math.ceil(rect.height));
+
+ if (sw <= 0 || sh <= 0) return;
+
+ const imgData = ctx.getImageData(sx, sy, sw, sh);
+ binarizeImageDataBuffer(imgData, threshold, expressBlack, expressWhite);
ctx.putImageData(imgData, sx, sy);
}
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 48ab010..aad388c 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -39,6 +39,10 @@ export const BLEND_MODE_MAP: Record<BlendMode, number> = {
difference: 10,
exclusion: 11,
'pass-through': 12,
+ 'linear-burn': 13,
+ 'add-glow': 14,
+ 'color-dodge-glow': 15,
+ divide: 16,
};
export interface LayerTreeNode {
@@ -104,15 +108,56 @@ export const FOLDER_BLIT_FRAGMENT_SHADER = `#version 300 es
precision highp float;
in vec2 v_uv;
uniform sampler2D u_blitTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform int u_blendMode;
uniform float u_blitOpacity;
out vec4 fragColor;
+
+float blendChannelFolder(float b, float s, int mode) {
+ if (mode == 1) return b * s; // multiply
+ if (mode == 2) return b + s - b * s; // screen
+ if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // overlay
+ if (mode == 4) return min(b, s); // darken
+ if (mode == 5) return max(b, s); // lighten
+ if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s))); // color-dodge
+ if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s))); // color-burn
+ if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // hard-light
+ if (mode == 9) { // soft-light
+ float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
+ return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
+ }
+ if (mode == 10) return abs(b - s); // difference
+ if (mode == 11) return b + s - 2.0 * b * s; // exclusion
+ if (mode == 13) return max(0.0, b + s - 1.0); // linear-burn
+ if (mode == 14) return min(1.0, b + s); // add-glow
+ if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)); // color-dodge-glow
+ if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0); // divide
+ return s;
+}
+
+vec3 evaluateBlendModeFolder(vec3 Cb, vec3 Cs, int mode) {
+ return vec3(
+ blendChannelFolder(Cb.r, Cs.r, mode),
+ blendChannelFolder(Cb.g, Cs.g, mode),
+ blendChannelFolder(Cb.b, Cs.b, mode)
+ );
+}
+
void main() {
- vec4 color = texture(u_blitTexture, v_uv);
- color *= u_blitOpacity;
- if (color.a < 0.002) {
+ vec4 srcPremul = texture(u_blitTexture, v_uv);
+ float srcA = srcPremul.a * u_blitOpacity;
+ if (srcA < 0.002) {
discard;
}
- fragColor = color;
+ vec3 Cs = srcPremul.a > 0.001 ? clamp(srcPremul.rgb / srcPremul.a, 0.0, 1.0) : vec3(0.0);
+ if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
+ vec4 dstPremul = texture(u_backdropTexture, v_uv);
+ vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
+ vec3 blended = evaluateBlendModeFolder(Cb, Cs, u_blendMode);
+ Cs = mix(Cs, blended, dstPremul.a);
+ }
+ fragColor = vec4(Cs * srcA, srcA);
}
`;
@@ -200,6 +245,9 @@ in vec2 v_texCoord;
in vec2 v_docCoord;
uniform sampler2D u_tileTexture;
+uniform sampler2D u_backdropTexture;
+uniform int u_hasBackdrop;
+uniform vec2 u_viewportSize;
uniform float u_layerOpacity;
uniform int u_blendMode;
@@ -233,6 +281,36 @@ float fractVal(float x) {
return x - floor(x);
}
+float blendChannel(float b, float s, int mode) {
+ if (mode == 1) return b * s; // multiply
+ if (mode == 2) return b + s - b * s; // screen
+ if (mode == 3) return b < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // overlay
+ if (mode == 4) return min(b, s); // darken
+ if (mode == 5) return max(b, s); // lighten
+ if (mode == 6) return b <= 0.0 ? 0.0 : (s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s))); // color-dodge
+ if (mode == 7) return b >= 1.0 ? 1.0 : (s <= 0.0 ? 0.0 : 1.0 - min(1.0, (1.0 - b) / max(0.0001, s))); // color-burn
+ if (mode == 8) return s < 0.5 ? (2.0 * b * s) : (1.0 - 2.0 * (1.0 - b) * (1.0 - s)); // hard-light
+ if (mode == 9) { // soft-light (W3C / Photoshop)
+ float d = b <= 0.25 ? (((16.0 * b - 12.0) * b + 4.0) * b) : sqrt(max(0.0, b));
+ return s <= 0.5 ? (b - (1.0 - 2.0 * s) * b * (1.0 - b)) : (b + (2.0 * s - 1.0) * (d - b));
+ }
+ if (mode == 10) return abs(b - s); // difference
+ if (mode == 11) return b + s - 2.0 * b * s; // exclusion
+ if (mode == 13) return max(0.0, b + s - 1.0); // linear-burn (CSP / Krita)
+ if (mode == 14) return min(1.0, b + s); // add-glow (CSP / Krita)
+ if (mode == 15) return s >= 1.0 ? 1.0 : min(1.0, b / max(0.0001, 1.0 - s)); // color-dodge-glow (CSP)
+ if (mode == 16) return s <= 0.0001 ? 1.0 : clamp(b / s, 0.0, 1.0); // divide (CSP / Krita)
+ return s;
+}
+
+vec3 evaluateBlendMode(vec3 Cb, vec3 Cs, int mode) {
+ return vec3(
+ blendChannel(Cb.r, Cs.r, mode),
+ blendChannel(Cb.g, Cs.g, mode),
+ blendChannel(Cb.b, Cs.b, mode)
+ );
+}
+
vec4 evaluateScreentone(vec4 srcColor, vec2 docCoord) {
if (srcColor.a < 0.0039) {
return vec4(0.0);
@@ -341,6 +419,15 @@ void main() {
discard;
}
+ if (u_hasBackdrop == 1 && u_blendMode != 0 && u_blendMode != 12) {
+ vec2 screenUV = clamp(gl_FragCoord.xy / max(vec2(1.0), u_viewportSize), 0.0, 1.0);
+ vec4 dstPremul = texture(u_backdropTexture, screenUV);
+ vec3 Cb = dstPremul.a > 0.001 ? clamp(dstPremul.rgb / dstPremul.a, 0.0, 1.0) : vec3(1.0);
+ vec3 Cs = clamp(finalColor.rgb, 0.0, 1.0);
+ vec3 blended = evaluateBlendMode(Cb, Cs, u_blendMode);
+ finalColor.rgb = mix(Cs, blended, dstPremul.a);
+ }
+
fragColor = vec4(finalColor.rgb * finalColor.a, finalColor.a);
}
`;
@@ -868,6 +955,11 @@ export interface CompositorOptions {
devicePixelRatio?: number;
onionSkinFrames?: OnionSkinCompositorFrame[];
softProof?: SoftProofSettings;
+ // WYSIWYG In-Stack Live Stroke Compositing
+ activeDraftCanvas?: HTMLCanvasElement | null;
+ activeDraftLayerId?: string | null;
+ activeDraftDirtyRect?: { x: number; y: number; width: number; height: number } | null;
+ activeDraftVersion?: number;
}
/**
@@ -951,6 +1043,8 @@ export class ViewportCompositor {
private uIsBackgroundLoc: WebGLUniformLocation | null = null;
private uShowCheckerboardLoc: WebGLUniformLocation | null = null;
private uTileTextureLoc: WebGLUniformLocation | null = null;
+ private uBackdropTextureLoc: WebGLUniformLocation | null = null;
+ private uHasBackdropLoc: WebGLUniformLocation | null = null;
private uLayerOpacityLoc: WebGLUniformLocation | null = null;
private uBlendModeLoc: WebGLUniformLocation | null = null;
@@ -968,10 +1062,21 @@ export class ViewportCompositor {
private uLayerColorLoc: WebGLUniformLocation | null = null;
private uLayerSubColorLoc: WebGLUniformLocation | null = null;
- // Mask uniform locations
+ // Mask uniform locations & version-tracked cache
private uMaskTextureLoc: WebGLUniformLocation | null = null;
private uMaskEnabledLoc: WebGLUniformLocation | null = null;
- private maskTextureCache: Map<string, { texture: WebGLTexture }> = new Map();
+ private maskTextureCache: Map<
+ string,
+ { texture: WebGLTexture; version: number; width: number; height: number }
+ > = new Map();
+
+ // Live in-stack draft stroke texture cache
+ private draftTexture: WebGLTexture | null = null;
+ private draftTexWidth: number = 0;
+ private draftTexHeight: number = 0;
+ private lastDraftVersion: number = -1;
+ private currentOptions: CompositorOptions | null = null;
+ private currentZoom: number = 1.0;
// Adjustment program & uniforms
private adjProgram: WebGLProgram | null = null;
@@ -994,6 +1099,8 @@ export class ViewportCompositor {
private snapshotWidth: number = 0;
private snapshotHeight: number = 0;
private lutTexture: WebGLTexture | null = null;
+ private lastLutKey: string = '';
+ private lastLutAdjMode: number = 0;
// Layer Styles program, FBO & uniforms
private stylesProgram: WebGLProgram | null = null;
@@ -1023,6 +1130,9 @@ export class ViewportCompositor {
// Folder compositing blit program, uniforms, & FBOs
private blitProgram: WebGLProgram | null = null;
private uBlitTextureLoc: WebGLUniformLocation | null = null;
+ private uBlitBackdropTextureLoc: WebGLUniformLocation | null = null;
+ private uBlitHasBackdropLoc: WebGLUniformLocation | null = null;
+ private uBlitBlendModeLoc: WebGLUniformLocation | null = null;
private uBlitOpacityLoc: WebGLUniformLocation | null = null;
private folderFbos: { fbo: WebGLFramebuffer; texture: WebGLTexture; width: number; height: number }[] = [];
@@ -1037,8 +1147,11 @@ export class ViewportCompositor {
private proofSnapshotWidth: number = 0;
private proofSnapshotHeight: number = 0;
- // Tile texture cache: tileKey -> { texture, version }
- private textureCache: Map<string, { texture: WebGLTexture; version: number; lastUsed: number }> = new Map();
+ // Tile texture cache: tileKey -> { texture, version, hasMipmap, filterMode }
+ private textureCache: Map<
+ string,
+ { texture: WebGLTexture; version: number; lastUsed: number; filterTier?: number }
+ > = new Map();
private fallbackTileCanvas: HTMLCanvasElement | null = null;
constructor(canvas: HTMLCanvasElement) {
@@ -1050,6 +1163,20 @@ export class ViewportCompositor {
return this.gl !== null && this.program !== null;
}
+ /**
+ * Explicitly invalidate a cached layer mask texture (or all masks if layerId omitted).
+ */
+ public invalidateMaskTexture(layerId?: string): void {
+ if (layerId) {
+ const item = this.maskTextureCache.get(layerId);
+ if (item) item.version = -1;
+ } else {
+ for (const item of this.maskTextureCache.values()) {
+ item.version = -1;
+ }
+ }
+ }
+
private initGL(): boolean {
if (this.gl && this.program) return true;
@@ -1060,6 +1187,7 @@ export class ViewportCompositor {
antialias: false,
depth: false,
stencil: true,
+ preserveDrawingBuffer: true,
});
if (!gl) return false;
@@ -1109,6 +1237,8 @@ export class ViewportCompositor {
this.uIsBackgroundLoc = gl.getUniformLocation(prog, 'u_isBackground');
this.uShowCheckerboardLoc = gl.getUniformLocation(prog, 'u_showCheckerboard');
this.uTileTextureLoc = gl.getUniformLocation(prog, 'u_tileTexture');
+ this.uBackdropTextureLoc = gl.getUniformLocation(prog, 'u_backdropTexture');
+ this.uHasBackdropLoc = gl.getUniformLocation(prog, 'u_hasBackdrop');
this.uLayerOpacityLoc = gl.getUniformLocation(prog, 'u_layerOpacity');
this.uBlendModeLoc = gl.getUniformLocation(prog, 'u_blendMode');
@@ -1217,6 +1347,9 @@ export class ViewportCompositor {
if (gl.getProgramParameter(bProg, gl.LINK_STATUS)) {
this.blitProgram = bProg;
this.uBlitTextureLoc = gl.getUniformLocation(bProg, 'u_blitTexture');
+ this.uBlitBackdropTextureLoc = gl.getUniformLocation(bProg, 'u_backdropTexture');
+ this.uBlitHasBackdropLoc = gl.getUniformLocation(bProg, 'u_hasBackdrop');
+ this.uBlitBlendModeLoc = gl.getUniformLocation(bProg, 'u_blendMode');
this.uBlitOpacityLoc = gl.getUniformLocation(bProg, 'u_blitOpacity');
}
}
@@ -1329,7 +1462,10 @@ export class ViewportCompositor {
}
/**
- * Get or upload a WebGLTexture for a tile.
+ * Get or upload a WebGLTexture for a tile with hardware mipmap pyramid and adaptive zoom filtering.
+ * - Zoom < 0.99: Trilinear mipmap filtering (gl.LINEAR_MIPMAP_LINEAR) eliminates line-art shimmering.
+ * - 0.99 <= Zoom < 2.0: Bilinear filtering (gl.LINEAR) for smooth rotation/sub-pixel pan.
+ * - Zoom >= 2.0: Nearest-neighbor magnification (gl.NEAREST) for crisp pixel-level inspection.
*/
private getTileTexture(tile: TileBuffer, grid: SparseTileGrid): WebGLTexture | null {
if (!this.gl) return null;
@@ -1340,19 +1476,18 @@ export class ViewportCompositor {
if (!cached) {
const tex = gl.createTexture();
if (!tex) return null;
- cached = { texture: tex, version: -1, lastUsed: performance.now() };
+ cached = { texture: tex, version: -1, lastUsed: performance.now(), filterTier: -1 };
this.textureCache.set(key, cached);
}
cached.lastUsed = performance.now();
+ const desiredTier = this.currentZoom < 0.99 ? 0 : this.currentZoom < 2.0 ? 1 : 2;
// Re-upload if dirty or version bumped
if (cached.version !== tile.version || tile.dirty) {
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.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
const rgbaData = grid.getTileAsRGBA(tile);
const uploadBytes = rgbaData instanceof Uint8Array
@@ -1371,36 +1506,89 @@ export class ViewportCompositor {
uploadBytes
);
+ // Generate hardware mipmap pyramid for anti-aliased zoomed-out viewing (256x256 POT)
+ if (typeof gl.generateMipmap === 'function') {
+ gl.generateMipmap(gl.TEXTURE_2D);
+ }
+
cached.version = tile.version;
+ cached.filterTier = -1; // Force filter parameter refresh
tile.dirty = false;
}
+ if (cached.filterTier !== desiredTier) {
+ gl.bindTexture(gl.TEXTURE_2D, cached.texture);
+ if (desiredTier === 0) {
+ gl.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ typeof gl.generateMipmap === 'function' ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ } else if (desiredTier === 1) {
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ } else {
+ gl.texParameteri(
+ gl.TEXTURE_2D,
+ gl.TEXTURE_MIN_FILTER,
+ typeof gl.generateMipmap === 'function' ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST
+ );
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ }
+ cached.filterTier = desiredTier;
+ }
+
return cached.texture;
}
/**
- * Set WebGL blend mode according to standard layer blend modes.
+ * Captures the current framebuffer into `this.snapshotTexture` for programmable GLSL blend modes.
+ */
+ private ensureBackdropSnapshot(gl: WebGL2RenderingContext, viewportW: number, viewportH: number): WebGLTexture | null {
+ if (!this.snapshotTexture || this.snapshotWidth !== viewportW || this.snapshotHeight !== viewportH) {
+ if (this.snapshotTexture) gl.deleteTexture(this.snapshotTexture);
+ this.snapshotTexture = gl.createTexture();
+ this.snapshotWidth = viewportW;
+ this.snapshotHeight = viewportH;
+ gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewportW, viewportH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, viewportW, viewportH);
+ return this.snapshotTexture;
+ }
+
+ /**
+ * Set WebGL blend mode and snapshot backdrop when programmable blending is active.
+ * Because COMPOSITOR_FRAGMENT_SHADER outputs:
+ * fragColor = vec4(mix(Cs, B(Cb, Cs), dstA) * srcA, srcA)
+ * standard premultiplied Porter-Duff (gl.ONE, gl.ONE_MINUS_SRC_ALPHA) produces the exact
+ * W3C / Clip Studio Paint composited result for all 16 blend modes!
*/
private setGLBlendMode(blendMode: BlendMode): void {
if (!this.gl) return;
const gl = this.gl;
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- switch (blendMode) {
- case 'multiply':
- // dstRGB * srcRGB
- gl.blendFuncSeparate(gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- break;
- case 'screen':
- // 1 - (1 - dst) * (1 - src)
- gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- break;
- case 'pass-through':
- case 'normal':
- default:
- // Premultiplied alpha standard over
- gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- break;
+ const modeCode = BLEND_MODE_MAP[blendMode] ?? 0;
+ if (modeCode !== 0 && modeCode !== 12 && this.canvas.width > 0 && this.canvas.height > 0) {
+ const backdropTex = this.ensureBackdropSnapshot(gl, this.canvas.width, this.canvas.height);
+ if (backdropTex) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ gl.uniform1i(this.uBackdropTextureLoc, 2);
+ gl.uniform1i(this.uHasBackdropLoc, 1);
+ gl.activeTexture(gl.TEXTURE0);
+ return;
+ }
}
+ gl.uniform1i(this.uHasBackdropLoc, 0);
}
/**
@@ -1431,6 +1619,9 @@ export class ViewportCompositor {
_options: CompositorOptions = { dimensions }
): void {
const gl = this.gl;
+ this.currentOptions = _options;
+ this.currentZoom = transform.zoom;
+
if (!gl || !this.program) {
this.render2DFallback(layers, transform, dimensions, grid, _options);
return;
@@ -1457,6 +1648,7 @@ export class ViewportCompositor {
gl.uniform1f(this.uRotationRadLoc, rotRad);
gl.uniform1f(this.uDprLoc, dpr);
gl.uniform1i(this.uTileTextureLoc, 0);
+ gl.uniform1i(this.uHasBackdropLoc, 0);
// Bind Quad Vertices
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
@@ -1721,40 +1913,50 @@ export class ViewportCompositor {
}
/**
- * Get or upload a WebGLTexture for a layer's mask canvas.
+ * Get or upload a WebGLTexture for a layer's mask canvas with dirty-version caching.
*/
private getMaskTexture(layer: LayerItem): WebGLTexture | null {
if (!this.gl || !layer.maskCanvas) return null;
const gl = this.gl;
let cached = this.maskTextureCache.get(layer.id);
+ const currentVersion = layer.maskVersion ?? 0;
+ const maskW = layer.maskCanvas.width;
+ const maskH = layer.maskCanvas.height;
+
if (!cached) {
const tex = gl.createTexture();
if (!tex) return null;
- cached = { texture: tex };
+ cached = { texture: tex, version: -1, width: 0, height: 0 };
this.maskTextureCache.set(layer.id, cached);
}
- 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);
+ 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.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
- gl.texImage2D(
- gl.TEXTURE_2D,
- 0,
- gl.RGBA,
- gl.RGBA,
- gl.UNSIGNED_BYTE,
- layer.maskCanvas
- );
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ layer.maskCanvas
+ );
+
+ cached.version = currentVersion;
+ cached.width = maskW;
+ cached.height = maskH;
+ }
return cached.texture;
}
/**
- * Evaluates non-destructive adjustment layers via GPU snapshot and real-time LUT evaluation.
+ * Evaluates non-destructive adjustment layers via GPU snapshot and version-cached LUT evaluation.
*/
private renderAdjustmentLayer(
gl: WebGL2RenderingContext,
@@ -1769,73 +1971,67 @@ export class ViewportCompositor {
if (!this.adjProgram || !layer.adjustmentData) return;
// 1. Snapshot lower composite
- if (!this.snapshotTexture || this.snapshotWidth !== viewportW || this.snapshotHeight !== viewportH) {
- if (this.snapshotTexture) gl.deleteTexture(this.snapshotTexture);
- this.snapshotTexture = gl.createTexture();
- this.snapshotWidth = viewportW;
- this.snapshotHeight = viewportH;
- gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewportW, viewportH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
- }
+ this.ensureBackdropSnapshot(gl, viewportW, viewportH);
- gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
- gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, viewportW, viewportH);
-
- // 2. Prepare 256x1 LUT
+ // 2. Prepare 256x1 LUT (Cached by AdjustmentLayerData signature)
if (!this.lutTexture) {
this.lutTexture = gl.createTexture();
+ this.lastLutKey = '';
}
const adj = layer.adjustmentData;
- let lutData: Uint8Array;
- let adjMode = 0; // 0 = per-channel, 1 = gradient map
-
- if (adj.type === 'curves') {
- const { rLut, gLut, bLut } = buildCurvesCombinedLut(adj.curves);
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const off = i * 4;
- lutData[off] = rLut[i];
- lutData[off + 1] = gLut[i];
- lutData[off + 2] = bLut[i];
- lutData[off + 3] = 255;
- }
- } else if (adj.type === 'gradient-map') {
- adjMode = 1;
- const gMap = buildGradientMapLut(adj.stops, adj.interpolation || 'linear');
- lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
- } else if (adj.type === 'levels') {
- const lLut = buildLevelsLut(adj.blackPoint, adj.whitePoint, adj.gamma, adj.outputMin ?? 0, adj.outputMax ?? 255);
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const off = i * 4;
- lutData[off] = lLut[i];
- lutData[off + 1] = lLut[i];
- lutData[off + 2] = lLut[i];
- lutData[off + 3] = 255;
- }
- } else { // color-balance
- lutData = new Uint8Array(256 * 4);
- for (let i = 0; i < 256; i++) {
- const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
- const off = i * 4;
- lutData[off] = r;
- lutData[off + 1] = g;
- lutData[off + 2] = b;
- lutData[off + 3] = 255;
+ const lutKey = JSON.stringify(adj);
+
+ if (lutKey !== this.lastLutKey) {
+ let lutData: Uint8Array;
+ let adjMode = 0; // 0 = per-channel, 1 = gradient map
+
+ if (adj.type === 'curves') {
+ const { rLut, gLut, bLut } = buildCurvesCombinedLut(adj.curves);
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = rLut[i];
+ lutData[off + 1] = gLut[i];
+ lutData[off + 2] = bLut[i];
+ lutData[off + 3] = 255;
+ }
+ } else if (adj.type === 'gradient-map') {
+ adjMode = 1;
+ const gMap = buildGradientMapLut(adj.stops, adj.interpolation || 'linear');
+ lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
+ } else if (adj.type === 'levels') {
+ const lLut = buildLevelsLut(adj.blackPoint, adj.whitePoint, adj.gamma, adj.outputMin ?? 0, adj.outputMax ?? 255);
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = lLut[i];
+ lutData[off + 1] = lLut[i];
+ lutData[off + 2] = lLut[i];
+ lutData[off + 3] = 255;
+ }
+ } else { // color-balance
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
+ const off = i * 4;
+ lutData[off] = r;
+ lutData[off + 1] = g;
+ lutData[off + 2] = b;
+ lutData[off + 3] = 255;
+ }
}
- }
- gl.activeTexture(gl.TEXTURE3);
- gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
- 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
+ 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.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
+
+ this.lastLutKey = lutKey;
+ this.lastLutAdjMode = adjMode;
+ }
// 3. Switch to Adjustment Program
gl.useProgram(this.adjProgram);
@@ -1860,7 +2056,7 @@ export class ViewportCompositor {
gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
gl.uniform1i(this.uAdjLutLoc, 3);
- gl.uniform1i(this.uAdjModeLoc, adjMode);
+ gl.uniform1i(this.uAdjModeLoc, this.lastLutAdjMode);
gl.uniform1f(this.uAdjOpacityLoc, layer.opacity * opacityMultiplier);
// Mask for adjustment layer
@@ -1887,6 +2083,7 @@ export class ViewportCompositor {
/**
* Renders all visible tiles of a single layer onto WebGL2 context.
+ * Also composites any in-progress WYSIWYG draft stroke targeting this layer.
*/
private renderSingleLayer(
gl: WebGL2RenderingContext,
@@ -1954,6 +2151,8 @@ export class ViewportCompositor {
frustum.maxY
);
+ gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+
// Draw each visible tile with 1 draw call per tile
for (const tile of visibleTiles) {
const tex = this.getTileTexture(tile, grid);
@@ -1966,9 +2165,59 @@ export class ViewportCompositor {
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
+ // WYSIWYG In-Stack Live Stroke Compositing:
+ // If an active brush stroke is targeting this exact layer, composite it right here in the stack
+ // so upper layers, blend modes, clipping masks, screentones, and layer tinting apply in real time!
+ const opts = this.currentOptions;
+ if (opts?.activeDraftLayerId === layer.id && opts.activeDraftCanvas) {
+ this.renderActiveDraftForLayer(gl, opts.activeDraftCanvas, dimensions, opts.activeDraftVersion);
+ gl.uniform2f(this.uTileSizeLoc, TILE_SIZE, TILE_SIZE);
+ }
+
if (hasMask) {
gl.uniform1i(this.uMaskEnabledLoc, 0);
}
+ gl.uniform1i(this.uHasBackdropLoc, 0);
+ }
+
+ /**
+ * Uploads and renders the active draft canvas in-stack for the active layer.
+ */
+ private renderActiveDraftForLayer(
+ gl: WebGL2RenderingContext,
+ draftCanvas: HTMLCanvasElement,
+ dimensions: CanvasDimensions,
+ draftVersion?: number
+ ): void {
+ if (draftCanvas.width <= 0 || draftCanvas.height <= 0) return;
+ if (!this.draftTexture) {
+ this.draftTexture = gl.createTexture();
+ }
+ if (!this.draftTexture) return;
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.draftTexture);
+
+ const ver = draftVersion ?? -1;
+ if (
+ ver === -1 ||
+ ver !== this.lastDraftVersion ||
+ this.draftTexWidth !== draftCanvas.width ||
+ this.draftTexHeight !== draftCanvas.height
+ ) {
+ 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, this.currentZoom >= 2.0 ? gl.NEAREST : gl.LINEAR);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, draftCanvas);
+ this.draftTexWidth = draftCanvas.width;
+ this.draftTexHeight = draftCanvas.height;
+ this.lastDraftVersion = ver;
+ }
+
+ gl.uniform2f(this.uTileOriginLoc, 0, 0);
+ gl.uniform2f(this.uTileSizeLoc, dimensions.width, dimensions.height);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
}
/**
@@ -2069,7 +2318,18 @@ export class ViewportCompositor {
if (!this.blitProgram) return;
gl.viewport(0, 0, viewportW, viewportH);
- this.setGLBlendMode(blendMode);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+ const modeCode = BLEND_MODE_MAP[blendMode] ?? 0;
+ let hasBackdrop = 0;
+ if (modeCode !== 0 && modeCode !== 12 && viewportW > 0 && viewportH > 0) {
+ const backdropTex = this.ensureBackdropSnapshot(gl, viewportW, viewportH);
+ if (backdropTex) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, backdropTex);
+ hasBackdrop = 1;
+ }
+ }
gl.useProgram(this.blitProgram);
gl.bindBuffer(gl.ARRAY_BUFFER, this.stylesQuadBuffer);
@@ -2080,6 +2340,9 @@ export class ViewportCompositor {
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(this.uBlitTextureLoc, 0);
+ gl.uniform1i(this.uBlitBackdropTextureLoc, 2);
+ gl.uniform1i(this.uBlitHasBackdropLoc, hasBackdrop);
+ gl.uniform1i(this.uBlitBlendModeLoc, modeCode);
gl.uniform1f(this.uBlitOpacityLoc, opacity);
gl.drawArrays(gl.TRIANGLES, 0, 6);
@@ -2386,6 +2649,13 @@ export class ViewportCompositor {
// Draw main layer content
drawTiles(targetCtx);
+
+ // WYSIWYG 2D fallback in-stack live draft compositing
+ const opts = this.currentOptions;
+ if (opts?.activeDraftLayerId === layer.id && opts.activeDraftCanvas) {
+ targetCtx.drawImage(opts.activeDraftCanvas, 0, 0);
+ }
+
targetCtx.restore();
}
@@ -2566,6 +2836,10 @@ export class ViewportCompositor {
this.gl.deleteTexture(item.texture);
}
this.maskTextureCache.clear();
+ if (this.draftTexture) {
+ this.gl.deleteTexture(this.draftTexture);
+ this.draftTexture = null;
+ }
if (this.snapshotTexture) {
this.gl.deleteTexture(this.snapshotTexture);
this.snapshotTexture = null;
diff --git a/src/utils/filterEngine.ts b/src/utils/filterEngine.ts
index 4e7b2c8..bdac006 100644
--- a/src/utils/filterEngine.ts
+++ b/src/utils/filterEngine.ts
@@ -435,6 +435,199 @@ export function applyFilmGrain(
return output;
}
+export const FILTER_VERTEX_SHADER = `
+ attribute vec2 a_position;
+ varying vec2 v_uv;
+ void main() {
+ v_uv = a_position * 0.5 + 0.5;
+ gl_Position = vec4(a_position, 0.0, 1.0);
+ }
+`;
+
+export const GAUSSIAN_BLUR_FRAGMENT_SHADER = `
+ precision highp float;
+ varying vec2 v_uv;
+ uniform sampler2D u_tex;
+ uniform vec2 u_dir; // (1.0/width, 0.0) or (0.0, 1.0/height)
+ uniform float u_radius;
+
+ void main() {
+ float sigma = max(0.5, u_radius * 0.5);
+ float twoSigmaSq = 2.0 * sigma * sigma;
+ vec4 acc = vec4(0.0);
+ float weightSum = 0.0;
+
+ for (int i = -24; i <= 24; i++) {
+ float fi = float(i);
+ if (abs(fi) > u_radius) continue;
+ float w = exp(-(fi * fi) / twoSigmaSq);
+ acc += texture2D(u_tex, clamp(v_uv + u_dir * fi, 0.0, 1.0)) * w;
+ weightSum += w;
+ }
+
+ gl_FragColor = acc / max(0.0001, weightSum);
+ }
+`;
+
+export const MOTION_BLUR_FRAGMENT_SHADER = `
+ precision highp float;
+ varying vec2 v_uv;
+ uniform sampler2D u_tex;
+ uniform vec2 u_stepVec;
+ uniform int u_halfSteps;
+
+ void main() {
+ vec4 acc = vec4(0.0);
+ float count = 0.0;
+ for (int i = -32; i <= 32; i++) {
+ if (i < -u_halfSteps || i > u_halfSteps) continue;
+ vec2 sampleUv = clamp(v_uv + u_stepVec * float(i), 0.0, 1.0);
+ acc += texture2D(u_tex, sampleUv);
+ count += 1.0;
+ }
+ gl_FragColor = acc / max(1.0, count);
+ }
+`;
+
+export class WebGlFilterEngine {
+ private static instance: WebGlFilterEngine | null = null;
+ private canvas: HTMLCanvasElement | null = null;
+ private gl: WebGLRenderingContext | null = null;
+ private gaussProgram: WebGLProgram | null = null;
+ private motionProgram: WebGLProgram | null = null;
+ private quadBuffer: WebGLBuffer | null = null;
+ private texA: WebGLTexture | null = null;
+ private texB: WebGLTexture | null = null;
+ private fboA: WebGLFramebuffer | null = null;
+ private gpuReady = false;
+
+ public static getInstance(): WebGlFilterEngine {
+ if (!WebGlFilterEngine.instance) {
+ WebGlFilterEngine.instance = new WebGlFilterEngine();
+ }
+ return WebGlFilterEngine.instance;
+ }
+
+ private constructor() {
+ if (typeof document === 'undefined') return;
+ try {
+ this.canvas = document.createElement('canvas');
+ const gl = (this.canvas.getContext('webgl2', { premultipliedAlpha: false, alpha: true }) ||
+ this.canvas.getContext('webgl', { premultipliedAlpha: false, alpha: true })) as WebGLRenderingContext | null;
+ if (!gl) return;
+ this.gl = gl;
+
+ this.gaussProgram = this.compileProgram(gl, FILTER_VERTEX_SHADER, GAUSSIAN_BLUR_FRAGMENT_SHADER);
+ this.motionProgram = this.compileProgram(gl, FILTER_VERTEX_SHADER, MOTION_BLUR_FRAGMENT_SHADER);
+ if (!this.gaussProgram || !this.motionProgram) return;
+
+ this.quadBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
+ gl.STATIC_DRAW
+ );
+
+ this.texA = gl.createTexture();
+ this.texB = gl.createTexture();
+ this.fboA = gl.createFramebuffer();
+ this.gpuReady = true;
+ } catch {
+ this.gpuReady = false;
+ }
+ }
+
+ private compileProgram(gl: WebGLRenderingContext, vsSrc: string, fsSrc: string): WebGLProgram | null {
+ const vs = gl.createShader(gl.VERTEX_SHADER);
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!vs || !fs) return null;
+ gl.shaderSource(vs, vsSrc);
+ gl.compileShader(vs);
+ gl.shaderSource(fs, fsSrc);
+ gl.compileShader(fs);
+ if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS) || !gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
+ return null;
+ }
+ const prog = gl.createProgram();
+ if (!prog) return null;
+ gl.attachShader(prog, vs);
+ gl.attachShader(prog, fs);
+ gl.linkProgram(prog);
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null;
+ return prog;
+ }
+
+ public isAvailable(): boolean {
+ return this.gpuReady && this.gl !== null;
+ }
+
+ public renderGaussianBlurToCanvas(targetCanvas: HTMLCanvasElement, radius: number): boolean {
+ if (!this.isAvailable() || !this.gl || !this.canvas || !this.gaussProgram || !this.texA || !this.texB || !this.fboA) {
+ return false;
+ }
+ const w = targetCanvas.width;
+ const h = targetCanvas.height;
+ if (w <= 0 || h <= 0 || radius > 24) return false;
+
+ const gl = this.gl;
+ if (this.canvas.width !== w || this.canvas.height !== h) {
+ this.canvas.width = w;
+ this.canvas.height = h;
+ }
+
+ // Upload source canvas to texA
+ gl.bindTexture(gl.TEXTURE_2D, this.texA);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, targetCanvas);
+ 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);
+
+ // Allocate texB for horizontal pass FBO
+ gl.bindTexture(gl.TEXTURE_2D, this.texB);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ 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.bindFramebuffer(gl.FRAMEBUFFER, this.fboA);
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texB, 0);
+
+ gl.viewport(0, 0, w, h);
+ gl.useProgram(this.gaussProgram);
+
+ const posLoc = gl.getAttribLocation(this.gaussProgram, 'a_position');
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ gl.enableVertexAttribArray(posLoc);
+ gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
+
+ // Pass 1: Horizontal into texB
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.texA);
+ gl.uniform1i(gl.getUniformLocation(this.gaussProgram, 'u_tex'), 0);
+ gl.uniform2f(gl.getUniformLocation(this.gaussProgram, 'u_dir'), 1.0 / w, 0.0);
+ gl.uniform1f(gl.getUniformLocation(this.gaussProgram, 'u_radius'), radius);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // Pass 2: Vertical to default framebuffer
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+ gl.bindTexture(gl.TEXTURE_2D, this.texB);
+ gl.uniform2f(gl.getUniformLocation(this.gaussProgram, 'u_dir'), 0.0, 1.0 / h);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ const ctx = targetCanvas.getContext('2d');
+ if (!ctx) return false;
+ ctx.save();
+ ctx.globalCompositeOperation = 'copy';
+ ctx.drawImage(this.canvas, 0, 0);
+ ctx.restore();
+ return true;
+ }
+}
+
/**
* Universal dispatcher for convolution filters.
*/
@@ -470,3 +663,27 @@ export function applyFilter(
return imageData;
}
}
+
+/**
+ * Applies a filter directly to an HTMLCanvasElement, using WebGL2 GPU acceleration when supported.
+ */
+export function applyFilterToCanvas(
+ canvas: HTMLCanvasElement,
+ type: FilterType,
+ params: any
+): boolean {
+ if (type === 'gaussian-blur') {
+ const p = params as GaussianBlurParams;
+ const gpuFilter = WebGlFilterEngine.getInstance();
+ if (gpuFilter.isAvailable() && gpuFilter.renderGaussianBlurToCanvas(canvas, p.radius || 5)) {
+ return true;
+ }
+ }
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return false;
+ const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const filtered = applyFilter(imgData, type, params);
+ ctx.putImageData(filtered, 0, 0);
+ return true;
+}
+
diff --git a/src/utils/floodFill.ts b/src/utils/floodFill.ts
index e4754e7..3c32215 100644
--- a/src/utils/floodFill.ts
+++ b/src/utils/floodFill.ts
@@ -37,6 +37,15 @@ export function parseColorToRgba(colorStr: string): [number, number, number, num
return [0, 0, 0, 255];
}
+export interface FloodFillOptions {
+ /** Bridges gaps in line art up to N pixels wide (0–20) via morphological closing */
+ closeGap?: number;
+ /** Expands (+1..+20) or shrinks (-20..-1) the filled region in pixels */
+ areaScale?: number;
+ /** Smooths boundary pixels against anti-aliased line art */
+ antiAlias?: boolean;
+}
+
/**
* Creates a flat composite canvas of all visible layers.
* Used for "Refer to Other Layers" bucket fill.
@@ -70,8 +79,128 @@ export function compositeVisibleLayers(
}
/**
- * High performance scanline stack-based flood fill with tolerance.
- * Can refer to active layer or composite of all layers.
+ * Creates a composite canvas of only layers marked as Reference (`isReference: true`).
+ * Falls back to `compositeVisibleLayers` if no visible reference layer exists.
+ */
+export function compositeReferenceLayers(
+ layers: LayerItem[],
+ layerCanvasesMap: Map<string, HTMLCanvasElement>,
+ dimensions: CanvasDimensions
+): HTMLCanvasElement {
+ const refLayers = layers.filter((l) => l.visible && l.isReference && l.type !== 'folder');
+ if (refLayers.length === 0) {
+ return compositeVisibleLayers(layers, layerCanvasesMap, dimensions);
+ }
+
+ const composite = document.createElement('canvas');
+ composite.width = dimensions.width;
+ composite.height = dimensions.height;
+ const ctx = composite.getContext('2d');
+ if (!ctx) return composite;
+
+ const renderOrder = refLayers.slice().reverse();
+ for (const layer of renderOrder) {
+ const lCanvas = layerCanvasesMap.get(layer.id);
+ if (!lCanvas) continue;
+
+ ctx.save();
+ ctx.globalAlpha = layer.opacity ?? 1.0;
+ ctx.globalCompositeOperation = (layer.blendMode as GlobalCompositeOperation) || 'source-over';
+ ctx.drawImage(lCanvas, 0, 0);
+ ctx.restore();
+ }
+
+ return composite;
+}
+
+/**
+ * Separable 2D binary dilation (radius r) in O(W * H) time.
+ */
+function dilateBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {
+ if (radius <= 0) return new Uint8Array(mask);
+ const horiz = new Uint8Array(width * height);
+ const out = new Uint8Array(width * height);
+
+ // Horizontal pass using distance-to-last-one
+ for (let y = 0; y < height; y++) {
+ const rowOffset = y * width;
+ let lastOne = -100000;
+ for (let x = 0; x < width; x++) {
+ if (mask[rowOffset + x]) lastOne = x;
+ if (x - lastOne <= radius) horiz[rowOffset + x] = 1;
+ }
+ lastOne = 100000;
+ for (let x = width - 1; x >= 0; x--) {
+ if (mask[rowOffset + x]) lastOne = x;
+ if (lastOne - x <= radius) horiz[rowOffset + x] = 1;
+ }
+ }
+
+ // Vertical pass
+ for (let x = 0; x < width; x++) {
+ let lastOne = -100000;
+ for (let y = 0; y < height; y++) {
+ const idx = y * width + x;
+ if (horiz[idx]) lastOne = y;
+ if (y - lastOne <= radius) out[idx] = 1;
+ }
+ lastOne = 100000;
+ for (let y = height - 1; y >= 0; y--) {
+ const idx = y * width + x;
+ if (horiz[idx]) lastOne = y;
+ if (lastOne - y <= radius) out[idx] = 1;
+ }
+ }
+
+ return out;
+}
+
+/**
+ * Separable 2D binary erosion (radius r) in O(W * H) time.
+ */
+function erodeBinaryMask(mask: Uint8Array, width: number, height: number, radius: number): Uint8Array {
+ if (radius <= 0) return new Uint8Array(mask);
+ const horiz = new Uint8Array(width * height);
+ const out = new Uint8Array(width * height);
+
+ // Horizontal pass: pixel is 1 iff no 0 within radius
+ for (let y = 0; y < height; y++) {
+ const rowOffset = y * width;
+ let lastZero = -100000;
+ for (let x = 0; x < width; x++) {
+ if (!mask[rowOffset + x]) lastZero = x;
+ if (x - lastZero > radius) horiz[rowOffset + x] = 1;
+ }
+ lastZero = 100000;
+ for (let x = width - 1; x >= 0; x--) {
+ if (!mask[rowOffset + x]) lastZero = x;
+ if (lastZero - x <= radius) horiz[rowOffset + x] = 0;
+ }
+ }
+
+ // Vertical pass
+ for (let x = 0; x < width; x++) {
+ let lastZero = -100000;
+ for (let y = 0; y < height; y++) {
+ const idx = y * width + x;
+ if (!horiz[idx]) lastZero = y;
+ if (y - lastZero > radius) out[idx] = 1;
+ }
+ lastZero = 100000;
+ for (let y = height - 1; y >= 0; y--) {
+ const idx = y * width + x;
+ if (!horiz[idx]) lastZero = y;
+ if (lastZero - y <= radius) out[idx] = 0;
+ }
+ }
+
+ return out;
+}
+
+/**
+ * High performance scanline stack-based flood fill with tolerance,
+ * CSP-grade Close Gap morphological bridging, and Area Scaling.
+ * Can refer to active layer, reference layers, or composite of all layers.
*/
export function executeFloodFill(
targetCanvas: HTMLCanvasElement,
@@ -80,7 +209,8 @@ export function executeFloodFill(
startY: number,
fillColorHex: string,
tolerance: number = 32,
- sourceCanvas?: HTMLCanvasElement | null
+ sourceCanvas?: HTMLCanvasElement | null,
+ options?: FloodFillOptions
): { dirtyRect: DirtyRect | null; modified: boolean } {
const width = targetCanvas.width;
const height = targetCanvas.height;
@@ -109,9 +239,14 @@ export function executeFloodFill(
const seedB = refData[seedIdx + 2];
const seedA = refData[seedIdx + 3];
- // If clicking identical color on same canvas with 0 tolerance, exit early
+ const closeGap = Math.max(0, Math.min(20, Math.round(options?.closeGap ?? 0)));
+ const areaScale = Math.max(-20, Math.min(20, Math.round(options?.areaScale ?? 0)));
+ const antiAlias = options?.antiAlias ?? false;
+
+ // If clicking identical color on same canvas with 0 tolerance and no areaScale, exit early
if (
referenceCanvas === targetCanvas &&
+ areaScale === 0 &&
Math.abs(seedR - fillR) <= 2 &&
Math.abs(seedG - fillG) <= 2 &&
Math.abs(seedB - fillB) <= 2 &&
@@ -121,16 +256,47 @@ export function executeFloodFill(
}
const maxToleranceDistance = (tolerance / 100) * 255;
- const visited = new Uint8Array(width * height);
+ const totalPixels = width * height;
+ const visited = new Uint8Array(totalPixels);
+
+ // Build barrier map if closeGap > 0
+ let barrierMask: Uint8Array | null = null;
+ if (closeGap > 0) {
+ const rawBarrier = new Uint8Array(totalPixels);
+ for (let i = 0; i < totalPixels; i++) {
+ const idx = i * 4;
+ const diff =
+ (Math.abs(refData[idx] - seedR) +
+ Math.abs(refData[idx + 1] - seedG) +
+ Math.abs(refData[idx + 2] - seedB) +
+ Math.abs(refData[idx + 3] - seedA)) /
+ 4;
+ if (diff > maxToleranceDistance) {
+ rawBarrier[i] = 1;
+ }
+ }
+ const closingRadius = Math.max(1, Math.ceil(closeGap / 2));
+ const dilated = dilateBinaryMask(rawBarrier, width, height, closingRadius);
+ const closed = erodeBinaryMask(dilated, width, height, closingRadius);
+ for (let i = 0; i < totalPixels; i++) {
+ if (rawBarrier[i]) closed[i] = 1;
+ }
+ // Ensure the seed point itself is not blocked if it wasn't originally a barrier
+ closed[py * width + px] = rawBarrier[py * width + px];
+ barrierMask = closed;
+ }
const matchesSeed = (x: number, y: number): boolean => {
- const idx = (y * width + x) * 4;
+ const pIdx = y * width + x;
+ if (barrierMask) {
+ return barrierMask[pIdx] === 0;
+ }
+ const idx = pIdx * 4;
const r = refData[idx];
const g = refData[idx + 1];
const b = refData[idx + 2];
const a = refData[idx + 3];
- // RGBA distance metric
const diff = (Math.abs(r - seedR) + Math.abs(g - seedG) + Math.abs(b - seedB) + Math.abs(a - seedA)) / 4;
return diff <= maxToleranceDistance;
};
@@ -178,12 +344,6 @@ export function executeFloodFill(
const pIdx = curY * width + x;
visited[pIdx] = 1;
- const tIdx = pIdx * 4;
- targetData[tIdx] = fillR;
- targetData[tIdx + 1] = fillG;
- targetData[tIdx + 2] = fillB;
- targetData[tIdx + 3] = fillA;
-
// Check row above
if (curY > 0) {
const aboveVisited = visited[(curY - 1) * width + x];
@@ -212,6 +372,117 @@ export function executeFloodFill(
}
}
+ // Apply Area Scaling (Expand / Shrink) with line-art centerline stop guard
+ let finalMask: Uint8Array = visited;
+ if (areaScale > 0) {
+ // Outward BFS expansion up to areaScale steps, stopping if line-art opacity/darkness peaks and starts dropping (centerline guard)
+ const getLineStrength = (pIdx: number): number => {
+ const idx = pIdx * 4;
+ const a = refData[idx + 3] / 255;
+ const luma = (0.299 * refData[idx] + 0.587 * refData[idx + 1] + 0.114 * refData[idx + 2]) / 255;
+ return a * (1.0 - luma * 0.85);
+ };
+
+ let frontier: number[] = [];
+ for (let y = minY; y <= maxY; y++) {
+ const rowOffset = y * width;
+ for (let x = minX; x <= maxX; x++) {
+ const pIdx = rowOffset + x;
+ if (!finalMask[pIdx]) continue;
+ if (
+ (x > 0 && !finalMask[pIdx - 1]) ||
+ (x < width - 1 && !finalMask[pIdx + 1]) ||
+ (y > 0 && !finalMask[pIdx - width]) ||
+ (y < height - 1 && !finalMask[pIdx + width])
+ ) {
+ frontier.push(pIdx);
+ }
+ }
+ }
+
+ const dirs = [-1, 1, -width, width];
+ for (let step = 0; step < areaScale && frontier.length > 0; step++) {
+ const nextFrontier: number[] = [];
+ for (let i = 0; i < frontier.length; i++) {
+ const pIdx = frontier[i];
+ const pxCur = pIdx % width;
+ const pyCur = (pIdx - pxCur) / width;
+ const curStrength = getLineStrength(pIdx);
+
+ for (let d = 0; d < 4; d++) {
+ const offset = dirs[d];
+ if (offset === -1 && pxCur === 0) continue;
+ if (offset === 1 && pxCur === width - 1) continue;
+ if (offset === -width && pyCur === 0) continue;
+ if (offset === width && pyCur === height - 1) continue;
+
+ const nIdx = pIdx + offset;
+ if (finalMask[nIdx]) continue;
+
+ const nStrength = getLineStrength(nIdx);
+ // Line-art centerline guard: if current pixel is already inside dense line art (curStrength > 0.55)
+ // and neighbor is becoming lighter again (past the line centerline), stop expanding!
+ if (curStrength > 0.55 && nStrength < curStrength - 0.05) {
+ continue;
+ }
+
+ finalMask[nIdx] = 1;
+ nextFrontier.push(nIdx);
+ const nx = nIdx % width;
+ const ny = (nIdx - nx) / width;
+ if (nx < minX) minX = nx;
+ if (nx > maxX) maxX = nx;
+ if (ny < minY) minY = ny;
+ if (ny > maxY) maxY = ny;
+ }
+ }
+ frontier = nextFrontier;
+ }
+ } else if (areaScale < 0) {
+ finalMask = erodeBinaryMask(visited, width, height, Math.abs(areaScale));
+ }
+
+ // Write filled pixels to targetData
+ for (let y = minY; y <= maxY; y++) {
+ const rowOffset = y * width;
+ for (let x = minX; x <= maxX; x++) {
+ const pIdx = rowOffset + x;
+ if (finalMask[pIdx]) {
+ const tIdx = pIdx * 4;
+ targetData[tIdx] = fillR;
+ targetData[tIdx + 1] = fillG;
+ targetData[tIdx + 2] = fillB;
+ targetData[tIdx + 3] = fillA;
+ } else if (antiAlias) {
+ // Check if adjacent to filled region for 1px anti-aliased fringe smoothing
+ let filledNeighbors = 0;
+ if (x > 0 && finalMask[pIdx - 1]) filledNeighbors++;
+ if (x < width - 1 && finalMask[pIdx + 1]) filledNeighbors++;
+ if (y > 0 && finalMask[pIdx - width]) filledNeighbors++;
+ if (y < height - 1 && finalMask[pIdx + width]) filledNeighbors++;
+ if (filledNeighbors >= 2) {
+ const tIdx = pIdx * 4;
+ const blendAlpha = (filledNeighbors / 4) * (fillA / 255) * 0.5;
+ const dstA = targetData[tIdx + 3] / 255;
+ const outA = blendAlpha + dstA * (1 - blendAlpha);
+ if (outA > 0) {
+ targetData[tIdx] = Math.round((fillR * blendAlpha + targetData[tIdx] * dstA * (1 - blendAlpha)) / outA);
+ targetData[tIdx + 1] = Math.round((fillG * blendAlpha + targetData[tIdx + 1] * dstA * (1 - blendAlpha)) / outA);
+ targetData[tIdx + 2] = Math.round((fillB * blendAlpha + targetData[tIdx + 2] * dstA * (1 - blendAlpha)) / outA);
+ targetData[tIdx + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ }
+ }
+
+ if (antiAlias) {
+ minX = Math.max(0, minX - 1);
+ minY = Math.max(0, minY - 1);
+ maxX = Math.min(width - 1, maxX + 1);
+ maxY = Math.min(height - 1, maxY + 1);
+ }
+
targetCtx.putImageData(targetImgData, 0, 0);
if (sourceCanvas) {
diff --git a/src/utils/liquifyEngine.ts b/src/utils/liquifyEngine.ts
index 7a16a6c..8e72080 100644
--- a/src/utils/liquifyEngine.ts
+++ b/src/utils/liquifyEngine.ts
@@ -36,6 +36,249 @@ export interface LiquifyStepParams {
pressure?: number;
initialImageData?: ImageData | null;
selectionMask?: Uint8Array | null;
+ useGpu?: boolean;
+}
+
+export const LIQUIFY_VERTEX_SHADER = `
+ attribute vec2 a_position;
+ varying vec2 v_uv;
+ void main() {
+ v_uv = a_position * 0.5 + 0.5;
+ gl_Position = vec4(a_position, 0.0, 1.0);
+ }
+`;
+
+export const LIQUIFY_FRAGMENT_SHADER = `
+ precision highp float;
+ varying vec2 v_uv;
+ uniform sampler2D u_sourceTex;
+ uniform vec2 u_roiOrigin;
+ uniform vec2 u_roiSize;
+ uniform vec2 u_center;
+ uniform vec2 u_pushDir;
+ uniform float u_vLen;
+ uniform float u_radius;
+ uniform float u_hardness;
+ uniform float u_strength;
+ uniform int u_mode; // 0: push, 1: push-left, 2: push-right, 3: expand, 4: pinch, 5: twirl-cw, 6: twirl-ccw
+
+ void main() {
+ // Convert v_uv (with WebGL Y-flip accounted for) to canvas pixel coordinates
+ vec2 localPos = vec2(v_uv.x * u_roiSize.x, (1.0 - v_uv.y) * u_roiSize.y);
+ vec2 canvasPos = u_roiOrigin + localPos;
+ vec2 delta = canvasPos - u_center;
+ float distSq = dot(delta, delta);
+ float radiusSq = u_radius * u_radius;
+
+ if (distSq >= radiusSq) {
+ gl_FragColor = texture2D(u_sourceTex, vec2(v_uv.x, 1.0 - v_uv.y));
+ return;
+ }
+
+ float dist = sqrt(distSq);
+ float u = dist / u_radius;
+ float t = 1.0 - u * u;
+ float weight = (1.0 - u_hardness) * (t * t) + u_hardness * t;
+
+ vec2 srcCanvas = canvasPos;
+ if (u_mode == 0) {
+ float pushAmount = u_vLen * u_strength * weight;
+ srcCanvas = canvasPos - u_pushDir * pushAmount;
+ } else if (u_mode == 1) {
+ float pushAmount = max(1.5, u_vLen) * u_strength * weight;
+ srcCanvas = canvasPos + vec2(u_pushDir.y, -u_pushDir.x) * pushAmount;
+ } else if (u_mode == 2) {
+ float pushAmount = max(1.5, u_vLen) * u_strength * weight;
+ srcCanvas = canvasPos + vec2(-u_pushDir.y, u_pushDir.x) * pushAmount;
+ } else if (u_mode == 3) {
+ float factor = u_strength * weight * 0.3;
+ srcCanvas = u_center + delta * (1.0 - factor);
+ } else if (u_mode == 4) {
+ float factor = u_strength * weight * 0.3;
+ srcCanvas = u_center + delta * (1.0 + factor);
+ } else if (u_mode == 5 || u_mode == 6) {
+ float signDir = (u_mode == 5) ? 1.0 : -1.0;
+ float theta = signDir * (u_strength * 0.45) * weight;
+ float cosT = cos(theta);
+ float sinT = sin(theta);
+ srcCanvas = u_center + vec2(delta.x * cosT + delta.y * sinT, -delta.x * sinT + delta.y * cosT);
+ }
+
+ vec2 sampleLocal = clamp(srcCanvas - u_roiOrigin, vec2(0.0), u_roiSize - vec2(1.0));
+ vec2 sampleUv = sampleLocal / u_roiSize;
+ gl_FragColor = texture2D(u_sourceTex, sampleUv);
+ }
+`;
+
+export class WebGlLiquifyEngine {
+ private static instance: WebGlLiquifyEngine | null = null;
+ private canvas: HTMLCanvasElement | null = null;
+ private roiStagingCanvas: HTMLCanvasElement | null = null;
+ private gl: WebGLRenderingContext | null = null;
+ private program: WebGLProgram | null = null;
+ private quadBuffer: WebGLBuffer | null = null;
+ private sourceTex: WebGLTexture | null = null;
+ private gpuReady = false;
+
+ public static getInstance(): WebGlLiquifyEngine {
+ if (!WebGlLiquifyEngine.instance) {
+ WebGlLiquifyEngine.instance = new WebGlLiquifyEngine();
+ }
+ return WebGlLiquifyEngine.instance;
+ }
+
+ private constructor() {
+ if (typeof document === 'undefined') return;
+ try {
+ this.canvas = document.createElement('canvas');
+ this.roiStagingCanvas = document.createElement('canvas');
+ const gl = (this.canvas.getContext('webgl2', { premultipliedAlpha: false, alpha: true }) ||
+ this.canvas.getContext('webgl', { premultipliedAlpha: false, alpha: true })) as WebGLRenderingContext | null;
+ if (!gl) return;
+ this.gl = gl;
+
+ const vs = gl.createShader(gl.VERTEX_SHADER);
+ const fs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (!vs || !fs) return;
+ gl.shaderSource(vs, LIQUIFY_VERTEX_SHADER);
+ gl.compileShader(vs);
+ gl.shaderSource(fs, LIQUIFY_FRAGMENT_SHADER);
+ gl.compileShader(fs);
+ if (!gl.getShaderParameter(vs, gl.COMPILE_STATUS) || !gl.getShaderParameter(fs, gl.COMPILE_STATUS)) {
+ return;
+ }
+
+ const prog = gl.createProgram();
+ if (!prog) return;
+ gl.attachShader(prog, vs);
+ gl.attachShader(prog, fs);
+ gl.linkProgram(prog);
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return;
+ this.program = prog;
+
+ this.quadBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ gl.bufferData(
+ gl.ARRAY_BUFFER,
+ new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
+ gl.STATIC_DRAW
+ );
+
+ this.sourceTex = gl.createTexture();
+ this.gpuReady = true;
+ } catch {
+ this.gpuReady = false;
+ }
+ }
+
+ public isAvailable(): boolean {
+ return this.gpuReady && this.gl !== null && this.program !== null;
+ }
+
+ public executeStep(
+ targetCanvas: HTMLCanvasElement,
+ targetCtx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement | null | undefined,
+ minX: number,
+ minY: number,
+ roiW: number,
+ roiH: number,
+ cx: number,
+ cy: number,
+ ux: number,
+ uy: number,
+ vLen: number,
+ radius: number,
+ hardnessFactor: number,
+ strengthFactor: number,
+ mode: LiquifyMode
+ ): boolean {
+ if (!this.isAvailable() || !this.gl || !this.program || !this.canvas || !this.roiStagingCanvas || !this.sourceTex) {
+ return false;
+ }
+
+ const modeMap: Record<string, number> = {
+ push: 0,
+ 'push-left': 1,
+ 'push-right': 2,
+ expand: 3,
+ pinch: 4,
+ 'twirl-cw': 5,
+ 'twirl-ccw': 6,
+ };
+ const modeInt = modeMap[mode];
+ if (modeInt === undefined) return false;
+
+ if (this.roiStagingCanvas.width !== roiW || this.roiStagingCanvas.height !== roiH) {
+ this.roiStagingCanvas.width = roiW;
+ this.roiStagingCanvas.height = roiH;
+ }
+ const stagingCtx = this.roiStagingCanvas.getContext('2d');
+ if (!stagingCtx) return false;
+ stagingCtx.clearRect(0, 0, roiW, roiH);
+ stagingCtx.drawImage(targetCanvas, minX, minY, roiW, roiH, 0, 0, roiW, roiH);
+
+ if (this.canvas.width !== roiW || this.canvas.height !== roiH) {
+ this.canvas.width = roiW;
+ this.canvas.height = roiH;
+ }
+
+ const gl = this.gl;
+ gl.viewport(0, 0, roiW, roiH);
+ gl.useProgram(this.program);
+
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, this.sourceTex);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.roiStagingCanvas);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+
+ gl.uniform1i(gl.getUniformLocation(this.program, 'u_sourceTex'), 0);
+ gl.uniform2f(gl.getUniformLocation(this.program, 'u_roiOrigin'), minX, minY);
+ gl.uniform2f(gl.getUniformLocation(this.program, 'u_roiSize'), roiW, roiH);
+ gl.uniform2f(gl.getUniformLocation(this.program, 'u_center'), cx, cy);
+ gl.uniform2f(gl.getUniformLocation(this.program, 'u_pushDir'), ux, uy);
+ gl.uniform1f(gl.getUniformLocation(this.program, 'u_vLen'), vLen);
+ gl.uniform1f(gl.getUniformLocation(this.program, 'u_radius'), radius);
+ gl.uniform1f(gl.getUniformLocation(this.program, 'u_hardness'), hardnessFactor);
+ gl.uniform1f(gl.getUniformLocation(this.program, 'u_strength'), strengthFactor);
+ gl.uniform1i(gl.getUniformLocation(this.program, 'u_mode'), modeInt);
+
+ const posLoc = gl.getAttribLocation(this.program, 'a_position');
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.quadBuffer);
+ gl.enableVertexAttribArray(posLoc);
+ gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0);
+
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ targetCtx.save();
+ targetCtx.globalCompositeOperation = 'copy';
+ targetCtx.beginPath();
+ targetCtx.rect(minX, minY, roiW, roiH);
+ targetCtx.clip();
+ targetCtx.drawImage(this.canvas, 0, 0, roiW, roiH, minX, minY, roiW, roiH);
+ targetCtx.restore();
+
+ if (sourceCanvas && sourceCanvas !== targetCanvas) {
+ const sCtx = sourceCanvas.getContext('2d');
+ if (sCtx) {
+ sCtx.save();
+ sCtx.globalCompositeOperation = 'copy';
+ sCtx.beginPath();
+ sCtx.rect(minX, minY, roiW, roiH);
+ sCtx.clip();
+ sCtx.drawImage(this.canvas, 0, 0, roiW, roiH, minX, minY, roiW, roiH);
+ sCtx.restore();
+ }
+ }
+
+ return true;
+ }
}
/**
@@ -52,7 +295,7 @@ function computeFalloffWeight(dist: number, radius: number, hardnessFactor: numb
/**
* Executes a single localized, bilinear-interpolated liquify deformation step on the target canvas.
- * Highly optimized: only processes the local region of interest (ROI) bounding box.
+ * Uses hardware WebGL shader displacement on large brushes when available, with automatic CPU fallback.
*/
export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {
const {
@@ -66,6 +309,7 @@ export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {
pressure = 1.0,
initialImageData,
selectionMask,
+ useGpu = true,
} = params;
const width = canvas.width;
@@ -87,14 +331,6 @@ export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {
const ctx = canvas.getContext('2d', { willReadFrequently: true });
if (!ctx) return null;
- const srcImageData = ctx.getImageData(minX, minY, roiW, roiH);
- const src = srcImageData.data;
-
- // Clone source buffer for destination write
- const dstImageData = ctx.createImageData(roiW, roiH);
- const dst = dstImageData.data;
- dst.set(src);
-
const hardnessFactor = Math.max(0, Math.min(1, settings.hardness / 100));
const effectivePressure = settings.usePressure ? Math.max(0.1, pressure) : 1.0;
const strengthFactor = (settings.strength / 100) * effectivePressure;
@@ -117,12 +353,48 @@ export function applyLiquifyStep(params: LiquifyStepParams): DirtyRect | null {
return null;
}
+ // Hardware WebGL fast path for large Liquify brushes
+ if (useGpu && !selectionMask && mode !== 'reconstruct' && roiW * roiH >= 64 * 64) {
+ const gpuLiquify = WebGlLiquifyEngine.getInstance();
+ if (
+ gpuLiquify.executeStep(
+ canvas,
+ ctx,
+ sourceCanvas,
+ minX,
+ minY,
+ roiW,
+ roiH,
+ cx,
+ cy,
+ ux,
+ uy,
+ vLen,
+ radius,
+ hardnessFactor,
+ strengthFactor,
+ mode
+ )
+ ) {
+ return { x: minX, y: minY, width: roiW, height: roiH };
+ }
+ }
+
+ const srcImageData = ctx.getImageData(minX, minY, roiW, roiH);
+ const src = srcImageData.data;
+
+ // Clone source buffer for destination write
+ const dstImageData = ctx.createImageData(roiW, roiH);
+ const dst = dstImageData.data;
+ dst.set(src);
+
// Pre-calculate twirl angles if in twirl mode
const twirlBaseAngle = (mode === 'twirl-cw' ? 1 : -1) * (strengthFactor * 0.45);
const initData = initialImageData?.data;
const initW = initialImageData?.width ?? width;
+
for (let ry = 0; ry < roiH; ry++) {
const py = minY + ry;
const dy = py - cy;
diff --git a/src/utils/presetBrushes.ts b/src/utils/presetBrushes.ts
index e18772c..fa0e073 100644
--- a/src/utils/presetBrushes.ts
+++ b/src/utils/presetBrushes.ts
@@ -179,7 +179,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.035,
+ spacing: 0.04,
stabilization: 20,
usePressure: true,
smoothing: true,
@@ -203,7 +203,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.03,
+ spacing: 0.035,
stabilization: 24,
usePressure: true,
smoothing: true,
@@ -227,7 +227,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 1.0,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.04,
+ spacing: 0.07,
stabilization: 18,
usePressure: true,
smoothing: true,
@@ -251,7 +251,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 0.85,
opacity: 1.0,
hardness: 0.9,
- spacing: 0.05,
+ spacing: 0.08,
stabilization: 15,
usePressure: true,
smoothing: true,
@@ -278,7 +278,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 0.28,
opacity: 1.0,
hardness: 0.0,
- spacing: 0.05,
+ spacing: 0.08,
stabilization: 10,
usePressure: true,
smoothing: true,
@@ -303,7 +303,7 @@ export const BUILTIN_BRUSHES: BuiltinBrushDefinition[] = [
flow: 0.95,
opacity: 1.0,
hardness: 1.0,
- spacing: 0.045,
+ spacing: 0.07,
stabilization: 12,
usePressure: true,
smoothing: true,
diff --git a/src/utils/stampEngine.ts b/src/utils/stampEngine.ts
index 934a4fd..076a1e4 100644
--- a/src/utils/stampEngine.ts
+++ b/src/utils/stampEngine.ts
@@ -7,6 +7,7 @@ import {
rgbToHex,
} from './colorMixingEngine';
import { evaluateCspSpline } from './sutParser';
+import { WebGlBrushEngine, GpuDab } from './webglBrushEngine';
export interface TexturedBrushOptions {
size: number;
@@ -31,6 +32,7 @@ export interface TexturedBrushOptions {
spray?: CspSpraySettings;
taper?: CspTaperSettings;
colorMixing?: boolean;
+ perceptualMixing?: boolean;
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
@@ -44,6 +46,9 @@ export interface TexturedBrushOptions {
paperTextureImage?: HTMLImageElement;
paperTextureScale?: number;
paperTextureRotate?: number;
+ dualBrush?: boolean;
+ dualTipImage?: HTMLImageElement;
+ dualBrushCompositeMode?: string;
useGpu?: boolean;
underlyingCanvas?: HTMLCanvasElement;
sampler?: LayerPixelSampler;
@@ -787,6 +792,16 @@ export function drawTexturedCubicBezierSegment(
const thickness = options.thickness ?? 1.0;
const rotationRandomScale = options.rotationRandomScale ?? 0;
+ const gpuEngine = WebGlBrushEngine.getInstance();
+ const canUseGpu =
+ Boolean(options.useGpu) &&
+ gpuEngine.isAvailable() &&
+ !options.alphaLocked &&
+ !options.isTransparentInk &&
+ (!options.subTipImages || options.subTipImages.length <= 1) &&
+ Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
+ const gpuDabs: GpuDab[] | null = canUseGpu ? [] : null;
+
let smoothCos = Math.cos(baseAngleRad);
let smoothSin = Math.sin(baseAngleRad);
@@ -801,9 +816,10 @@ export function drawTexturedCubicBezierSegment(
? options.size * (minFactor + (1.0 - minFactor) * effPressure)
: options.size;
+ const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
+
// Stroke taper modulation (Clip Studio Paint style)
if (options.taper) {
- const strokeDist = (options.currentStrokeDist ?? 0) + currentDist;
const inLen = options.taper.inLength || (options.taper.inRatio ? options.taper.inRatio * 2.5 : 0);
if (options.taper.useIn && inLen > 0 && strokeDist < inLen) {
const inFactor = Math.max(0.01, Math.min(1.0, strokeDist / inLen));
@@ -880,7 +896,7 @@ export function drawTexturedCubicBezierSegment(
}
// Wet Edge rim boost
- if (options.wetEdge && options.wetEdge > 0) {
+ if (options.wetEdge && options.wetEdge > 0 && !gpuDabs) {
dabAlpha = Math.min(1.0, dabAlpha * (1.0 + options.wetEdge * 0.25));
}
@@ -893,7 +909,7 @@ export function drawTexturedCubicBezierSegment(
stampAngle
);
const isColorTip = Boolean(options.subTips && options.subTips[0]?.isColor);
- const master = getTintedTipMaster(activeTip, dabColor, isColorTip);
+ const master = gpuDabs ? null : getTintedTipMaster(activeTip, dabColor, isColorTip);
const tiltX = pt.tiltX ?? 0;
const tiltY = pt.tiltY ?? 0;
@@ -934,7 +950,7 @@ export function drawTexturedCubicBezierSegment(
const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = colorJitterEnabled ? parseColorToRgb(dabColor) : null;
+ const primRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(dabColor) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(options.secondaryColor || '#ffffff') : null;
for (let k = 0; k < dabCount; k++) {
@@ -975,13 +991,22 @@ export function drawTexturedCubicBezierSegment(
}
let curMaster = master;
+ let dabR = primRgb ? primRgb.r / 255 : 0;
+ let dabG = primRgb ? primRgb.g / 255 : 0;
+ let dabB = primRgb ? primRgb.b / 255 : 0;
+
if (colorJitterEnabled && primRgb && secRgb && dynamics) {
const cd = applyColorDynamics(
{ r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
dynamics
);
- curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
+ dabR = cd.r;
+ dabG = cd.g;
+ dabB = cd.b;
+ if (!gpuDabs) {
+ curMaster = getTintedTipMaster(activeTip, cd.hex, isColorTip);
+ }
}
let finalW = curDabW;
@@ -1000,22 +1025,55 @@ export function drawTexturedCubicBezierSegment(
const u2 = Math.random();
const r = radius * Math.sqrt(u1) * (1 - (options.spray.bias || 0) * (1 - u2));
const th = Math.PI * 2 * Math.random();
- drawSingleStamp(
- ctx,
- curMaster,
- curDabX + r * Math.cos(th),
- curDabY + r * Math.sin(th),
- pSize,
- pSize * aspect * curDabThickness,
- curDabAngle,
- curDabAlpha,
- isEraser,
- isBgEraser,
- options.alphaLocked,
- options.isTransparentInk
- );
+ const spX = curDabX + r * Math.cos(th);
+ const spY = curDabY + r * Math.sin(th);
+ const spH = pSize * aspect * curDabThickness;
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: spX,
+ y: spY,
+ width: pSize,
+ height: spH,
+ angle: curDabAngle,
+ r: dabR,
+ g: dabG,
+ b: dabB,
+ alpha: curDabAlpha,
+ pressure: effPressure,
+ strokeDist,
+ });
+ } else if (curMaster) {
+ drawSingleStamp(
+ ctx,
+ curMaster,
+ spX,
+ spY,
+ pSize,
+ spH,
+ curDabAngle,
+ curDabAlpha,
+ isEraser,
+ isBgEraser,
+ options.alphaLocked,
+ options.isTransparentInk
+ );
+ }
}
- } else {
+ } else if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX,
+ y: curDabY,
+ width: finalW,
+ height: finalH,
+ angle: curDabAngle,
+ r: dabR,
+ g: dabG,
+ b: dabB,
+ alpha: curDabAlpha,
+ pressure: effPressure,
+ strokeDist,
+ });
+ } else if (curMaster) {
drawSingleStamp(
ctx,
curMaster,
@@ -1037,6 +1095,32 @@ export function drawTexturedCubicBezierSegment(
currentDist += requiredStep;
}
+ if (gpuDabs && gpuDabs.length > 0) {
+ gpuEngine.renderDabsToContext(
+ ctx,
+ gpuDabs,
+ {
+ size: options.size,
+ opacity: options.opacity ?? 1.0,
+ flow: baseFlow,
+ hardness: options.hardness ?? 1.0,
+ wetEdge: options.wetEdge ?? 0,
+ grain: options.grain,
+ textureDensity: options.textureDensity,
+ paperTextureScale: options.paperTextureScale,
+ customTipImage: tipImage,
+ dualBrush: options.dualBrush,
+ dualTipImage: options.dualTipImage,
+ dualBrushCompositeMode: options.dualBrushCompositeMode,
+ colorMixing: false, // Reservoir already mixed per dab with LayerPixelSampler
+ perceptualMixing: options.perceptualMixing,
+ } as any,
+ isEraser ? 'eraser' : 'brush',
+ ctx.canvas.width,
+ ctx.canvas.height
+ );
+ }
+
const nextRemainder = currentDist - totalCurveLength;
return Math.max(0, nextRemainder);
}
@@ -1255,6 +1339,7 @@ export function centripetalCatmullRomToBezier(
export interface RadialMixingOptions {
colorMixing?: boolean;
+ perceptualMixing?: boolean;
amountOfPaint?: number;
densityOfPaint?: number;
colorStretch?: number;
@@ -1266,6 +1351,10 @@ export interface RadialMixingOptions {
isTransparentInk?: boolean;
dynamics?: BrushDynamics;
secondaryColor?: string;
+ useGpu?: boolean;
+ dualBrush?: boolean;
+ dualTipImage?: HTMLImageElement;
+ dualBrushCompositeMode?: string;
}
/**
@@ -1438,7 +1527,7 @@ export function drawRadialCubicBezierSegment(
color: string,
hardness: number = 1.0,
flow: number = 1.0,
- spacing: number = 0.06,
+ spacing: number = 0.08,
isEraser: boolean = false,
isBgEraser: boolean = false,
remainderDist: number = 0,
@@ -1453,16 +1542,26 @@ export function drawRadialCubicBezierSegment(
}
const isColorMixing = Boolean(mixingOptions?.colorMixing) && !isEraser && !isBgEraser;
+ const dynamics = mixingOptions?.dynamics;
+
+ const gpuEngine = WebGlBrushEngine.getInstance();
+ const canUseGpu =
+ Boolean(mixingOptions?.useGpu) &&
+ gpuEngine.isAvailable() &&
+ !mixingOptions?.alphaLocked &&
+ !mixingOptions?.isTransparentInk &&
+ Boolean(ctx.canvas && ctx.canvas.width > 0 && ctx.canvas.height > 0);
+ const gpuDabs: GpuDab[] | null = canUseGpu ? [] : null;
+
if (isColorMixing && mixingOptions && !mixingOptions.reservoir) {
mixingOptions.reservoir = new PaintReservoir(color);
}
const reservoir = mixingOptions?.reservoir;
const sampler = mixingOptions?.sampler;
- const staticMaster = isColorMixing ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser);
+ const staticMaster = (isColorMixing || gpuDabs) ? null : getRadialDabMaster(hardness, color, isEraser && !isBgEraser);
const spacingRatio = Math.max(0.015, Math.min(1.0, spacing));
let currentDist = remainderDist > 0 ? remainderDist : 0;
- const dynamics = mixingOptions?.dynamics;
const dabCount = Math.max(1, Math.min(10, Math.round(dynamics?.count ?? 1)));
const sizeJitter = Math.max(0, Math.min(1, dynamics?.sizeJitter ?? 0));
const angleJitter = Math.max(0, Math.min(1, dynamics?.angleJitter ?? 0));
@@ -1471,7 +1570,7 @@ export function drawRadialCubicBezierSegment(
const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const primRgb = colorJitterEnabled ? parseColorToRgb(color) : null;
+ const baseRgb = (colorJitterEnabled || gpuDabs) ? parseColorToRgb(isBgEraser ? '#ffffff' : color) : null;
const secRgb = colorJitterEnabled ? parseColorToRgb(mixingOptions?.secondaryColor || '#ffffff') : null;
while (currentDist <= totalCurveLength) {
@@ -1498,6 +1597,7 @@ export function drawRadialCubicBezierSegment(
let dabMaster = staticMaster;
let dabFlow = flow;
+ let dabRgb = baseRgb;
if (isColorMixing && reservoir) {
let sampled = { r: 255, g: 255, b: 255, a: 0 };
@@ -1522,7 +1622,11 @@ export function drawRadialCubicBezierSegment(
requiredStep
);
- dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false);
+ if (!gpuDabs) {
+ dabMaster = getRadialDabMaster(hardness, mixed.colorHex, false);
+ } else {
+ dabRgb = { r: mixed.r, g: mixed.g, b: mixed.b };
+ }
dabFlow = mixed.alpha;
if (sampler) {
@@ -1593,13 +1697,22 @@ export function drawRadialCubicBezierSegment(
}
let curMaster = dabMaster;
- if (colorJitterEnabled && primRgb && secRgb && dynamics) {
+ let rNorm = dabRgb ? dabRgb.r / 255 : 0;
+ let gNorm = dabRgb ? dabRgb.g / 255 : 0;
+ let bNorm = dabRgb ? dabRgb.b / 255 : 0;
+
+ if (colorJitterEnabled && dabRgb && secRgb && dynamics) {
const cd = applyColorDynamics(
- { r: primRgb.r / 255, g: primRgb.g / 255, b: primRgb.b / 255 },
+ { r: dabRgb.r / 255, g: dabRgb.g / 255, b: dabRgb.b / 255 },
{ r: secRgb.r / 255, g: secRgb.g / 255, b: secRgb.b / 255 },
dynamics
);
- curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser);
+ rNorm = cd.r;
+ gNorm = cd.g;
+ bNorm = cd.b;
+ if (!gpuDabs) {
+ curMaster = getRadialDabMaster(hardness, cd.hex, isEraser && !isBgEraser);
+ }
}
let finalW = curDabW;
@@ -1609,7 +1722,21 @@ export function drawRadialCubicBezierSegment(
finalH = (curDabW * curDabThickness) / (1.0 + tiltMagnitude * 0.5);
}
- if (curMaster) {
+ if (gpuDabs) {
+ gpuDabs.push({
+ x: curDabX,
+ y: curDabY,
+ width: finalW,
+ height: finalH,
+ angle: curDabRot,
+ r: rNorm,
+ g: gNorm,
+ b: bNorm,
+ alpha: curDabFlow,
+ pressure: pt.pressure ?? 1.0,
+ strokeDist: currentDist,
+ });
+ } else if (curMaster) {
drawSingleStamp(
ctx,
curMaster,
@@ -1630,6 +1757,28 @@ export function drawRadialCubicBezierSegment(
currentDist += requiredStep;
}
+ if (gpuDabs && gpuDabs.length > 0) {
+ gpuEngine.renderDabsToContext(
+ ctx,
+ gpuDabs,
+ {
+ size: p0.width || 10,
+ opacity: 1.0,
+ flow,
+ hardness,
+ wetEdge: 0,
+ dualBrush: mixingOptions?.dualBrush,
+ dualTipImage: mixingOptions?.dualTipImage,
+ dualBrushCompositeMode: mixingOptions?.dualBrushCompositeMode,
+ colorMixing: false,
+ perceptualMixing: mixingOptions?.perceptualMixing,
+ } as any,
+ isEraser ? 'eraser' : 'brush',
+ ctx.canvas.width,
+ ctx.canvas.height
+ );
+ }
+
const nextRemainder = currentDist - totalCurveLength;
return Math.max(0, nextRemainder);
}
@@ -1643,7 +1792,7 @@ export function renderCompleteRadialStroke(
color: string,
hardness: number = 1.0,
flow: number = 1.0,
- spacing: number = 0.06,
+ spacing: number = 0.08,
isEraser: boolean = false,
isBgEraser: boolean = false,
thickness: number = 1.0,
diff --git a/src/utils/undoCache.ts b/src/utils/undoCache.ts
index 649683a..45b878e 100644
--- a/src/utils/undoCache.ts
+++ b/src/utils/undoCache.ts
@@ -7,6 +7,7 @@
* older tile-delta states to high-speed temporary disk storage via Tauri v2 Rust IPC.
*/
+import { zlibSync, unzlibSync } from 'fflate';
import { TileDelta, HistoryItem } from '../types/editor';
import { serializeTileDeltas, deserializeTileDeltas } from './tileEngine';
@@ -21,10 +22,34 @@ export function isTauriEnvironment(): boolean {
);
}
+/**
+ * Compresses serialized tile deltas using fast level-1 zlib compression.
+ */
+export function compressTileDeltasPayload(deltas: TileDelta[]): Uint8Array {
+ const serialized = serializeTileDeltas(deltas);
+ return zlibSync(serialized, { level: 1 });
+}
+
+/**
+ * Decompresses and deserializes tile deltas (supports both zlib-compressed and raw payloads).
+ */
+export function decompressTileDeltasPayload(payload: Uint8Array): TileDelta[] {
+ if (payload.length >= 2 && payload[0] === 0x78) {
+ try {
+ const raw = unzlibSync(payload);
+ return deserializeTileDeltas(raw);
+ } catch {
+ // Fallback if byte 0 happened to be 0x78 in an uncompressed stream
+ }
+ }
+ return deserializeTileDeltas(payload);
+}
+
export class UndoCacheManager {
private sessionId: string;
private ramItems: Set<string> = new Set();
private diskCachedIds: Set<string> = new Set();
+ private compressedRamCache: Map<string, Uint8Array> = new Map();
constructor(sessionId?: string) {
this.sessionId = sessionId || `session-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
@@ -42,9 +67,8 @@ export class UndoCacheManager {
this.ramItems.add(item.id);
- // If RAM budget is exceeded, offload the oldest in-memory steps to disk
+ // If RAM budget is exceeded, offload the oldest in-memory steps to disk or compressed archive
if (this.ramItems.size > MAX_RAM_UNDO_STEPS) {
- // Find oldest items in allHistory that are still in ramItems
for (const oldItem of allHistory) {
if (oldItem.id !== item.id && this.ramItems.has(oldItem.id) && oldItem.tileDeltas) {
await this.offloadToDisk(oldItem);
@@ -56,51 +80,72 @@ export class UndoCacheManager {
}
/**
- * Offload a single history item's tile deltas to disk via Tauri IPC.
+ * Offload a single history item's tile deltas to disk via Tauri IPC (with fast zlib compression),
+ * or to a compact zlib-compressed RAM buffer when running in a browser environment.
*/
public async offloadToDisk(item: HistoryItem): Promise<void> {
if (!item.tileDeltas || item.tileDeltas.length === 0) return;
+ const compressed = compressTileDeltasPayload(item.tileDeltas);
+
if (isTauriEnvironment()) {
try {
const { invoke } = await import('@tauri-apps/api/core');
- const serialized = serializeTileDeltas(item.tileDeltas);
await invoke('save_undo_tile_cache', {
sessionId: this.sessionId,
stateId: item.id,
- data: Array.from(serialized),
+ data: compressed,
});
this.diskCachedIds.add(item.id);
- // Free memory in RAM
item.tileDeltas = undefined;
+ return;
} catch (err) {
- console.warn('[UndoCache] Failed to offload tile deltas to disk:', err);
+ console.warn('[UndoCache] Failed to offload tile deltas to disk, using compressed RAM fallback:', err);
}
}
+
+ // Browser / fallback path: store zlib-compressed binary payload (85-95% smaller than raw RGBA)
+ this.compressedRamCache.set(item.id, compressed);
+ item.tileDeltas = undefined;
}
/**
- * Retrieve tile deltas for a history item, restoring from disk if necessary.
+ * Retrieve tile deltas for a history item, restoring from compressed RAM or disk if necessary.
*/
public async resolveDeltas(item: HistoryItem): Promise<TileDelta[] | null> {
if (item.tileDeltas && item.tileDeltas.length > 0) {
return item.tileDeltas;
}
+ const compressedInRam = this.compressedRamCache.get(item.id);
+ if (compressedInRam) {
+ const deltas = decompressTileDeltasPayload(compressedInRam);
+ this.compressedRamCache.delete(item.id);
+ item.tileDeltas = deltas;
+ this.ramItems.add(item.id);
+ return deltas;
+ }
+
if (this.diskCachedIds.has(item.id) && isTauriEnvironment()) {
try {
const { invoke } = await import('@tauri-apps/api/core');
- const rawData = await invoke<number[]>('load_undo_tile_cache', {
+ const rawData = await invoke<number[] | Uint8Array | ArrayBuffer>('load_undo_tile_cache', {
sessionId: this.sessionId,
stateId: item.id,
});
- if (rawData && rawData.length > 0) {
- const u8 = new Uint8Array(rawData);
- const deltas = deserializeTileDeltas(u8);
- // Re-populate item
- item.tileDeltas = deltas;
- this.ramItems.add(item.id);
- return deltas;
+ if (rawData) {
+ const u8 =
+ rawData instanceof Uint8Array
+ ? rawData
+ : rawData instanceof ArrayBuffer
+ ? new Uint8Array(rawData)
+ : new Uint8Array(rawData);
+ if (u8.length > 0) {
+ const deltas = decompressTileDeltasPayload(u8);
+ item.tileDeltas = deltas;
+ this.ramItems.add(item.id);
+ return deltas;
+ }
}
} catch (err) {
console.warn('[UndoCache] Failed to restore tile deltas from disk:', err);
@@ -111,11 +156,12 @@ export class UndoCacheManager {
}
/**
- * Clear all disk cached states for this session.
+ * Clear all disk and compressed cached states for this session.
*/
public async clearCache(): Promise<void> {
this.ramItems.clear();
this.diskCachedIds.clear();
+ this.compressedRamCache.clear();
if (isTauriEnvironment()) {
try {
const { invoke } = await import('@tauri-apps/api/core');
@@ -129,3 +175,4 @@ export class UndoCacheManager {
// Global default undo cache manager instance
export const globalUndoCache = new UndoCacheManager();
+
diff --git a/src/utils/webglBrushEngine.ts b/src/utils/webglBrushEngine.ts
index 13e44bc..f96fdc4 100644
--- a/src/utils/webglBrushEngine.ts
+++ b/src/utils/webglBrushEngine.ts
@@ -1,5 +1,4 @@
import { Point, BrushSettings, ToolType } from '../types/editor';
-import { evaluateCspSpline } from './sutParser';
import { applyColorDynamics } from './stampEngine';
/**
@@ -15,7 +14,7 @@ export interface GpuInfo {
/**
* GPU Dab instance for batch drawing.
*/
-interface GpuDab {
+export interface GpuDab {
x: number;
y: number;
width: number;
@@ -30,7 +29,7 @@ interface GpuDab {
}
// -------------------------------------------------------------
-// Shaders for GPU Video Card Execution
+// Shaders for GPU Video Card Execution (Track B: Instanced Dabs)
// -------------------------------------------------------------
const VERTEX_SHADER_SRC = `
@@ -97,12 +96,17 @@ varying vec2 v_worldPos;
uniform bool u_hasTipTexture;
uniform sampler2D u_tipTexture;
+uniform bool u_hasDualTipTexture;
+uniform sampler2D u_dualTipTexture;
+uniform int u_dualBlendMode; // 0: multiply, 1: subtract, 2: darken, 3: overlay, 4: screen
+
uniform float u_hardness; // 0.05 to 1.0
uniform float u_wetEdge; // 0.0 to 1.0 (CSP Watercolor Water Edge)
uniform float u_paperGrain; // 0.0 to 1.0 (CSP Paper Tooth)
uniform float u_grainScale; // scale of paper texture
uniform bool u_colorMixing; // CSP Color Mixing active
+uniform bool u_perceptualMixing; // OKLab + Kubelka-Munk spectral pigment mixing
uniform bool u_hasCanvasTexture;
uniform sampler2D u_canvasTexture;
uniform vec2 u_canvasResolution;
@@ -121,6 +125,32 @@ float getPaperGrain(vec2 p) {
return clamp((n1 * 0.5 + n2 * 0.35 + n3 * 0.15) * 0.5 + 0.5, 0.0, 1.0);
}
+// Perceptual Kubelka-Munk + Spectral Yellow-Blue Pigment Mixing on GPU
+vec3 mixPigmentsGpu(vec3 c1, vec3 c2, float w2) {
+ float w1 = 1.0 - w2;
+ 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));
+
+ // Spectral Yellow + Blue -> Green transmittance coupling
+ 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);
+}
+
void main() {
float dist = length(v_localPos);
if (dist > 1.0) {
@@ -138,6 +168,23 @@ void main() {
tipAlpha = 1.0 - smoothstep(edge, 1.0, dist);
}
+ // 1b. Dual-Brush Texture Modulation
+ if (u_hasDualTipTexture) {
+ vec4 dualTex = texture2D(u_dualTipTexture, v_uv);
+ float dualA = dualTex.a;
+ if (u_dualBlendMode == 1) {
+ tipAlpha = max(0.0, tipAlpha - (1.0 - dualA)); // subtract
+ } else if (u_dualBlendMode == 2) {
+ tipAlpha = min(tipAlpha, dualA); // darken
+ } else if (u_dualBlendMode == 3) {
+ tipAlpha = tipAlpha < 0.5 ? (2.0 * tipAlpha * dualA) : (1.0 - 2.0 * (1.0 - tipAlpha) * (1.0 - dualA)); // overlay
+ } else if (u_dualBlendMode == 4) {
+ tipAlpha = tipAlpha + dualA - tipAlpha * dualA; // screen
+ } else {
+ tipAlpha *= dualA; // multiply (default)
+ }
+ }
+
if (tipAlpha <= 0.002) {
discard;
}
@@ -146,40 +193,35 @@ void main() {
// 2. CSP Wet Edge (Water Edge - capillary accumulation at stroke perimeter)
if (u_wetEdge > 0.001) {
- // Rim density accumulation curve
float rim = smoothstep(0.55, 0.94, dist) * (1.0 - smoothstep(0.95, 1.0, dist));
float edgeBoost = 1.0 + u_wetEdge * 2.2 * rim;
tipAlpha = clamp(tipAlpha * edgeBoost, 0.0, 1.0);
-
- // Subtle edge pigment darkening typical of drying watercolor
rgb = mix(rgb, rgb * 0.72, u_wetEdge * rim * 0.55);
}
// 3. CSP Paper Grain / Canvas Tooth
if (u_paperGrain > 0.001) {
float tooth = getPaperGrain(v_worldPos);
- // Stylus pressure penetration: hard pressure fills paper troughs, light touches only peaks
float penetration = clamp(v_pressure * 0.75, 0.0, 0.85);
float grainFactor = clamp(1.0 - u_paperGrain * (1.0 - tooth) * (1.0 - penetration), 0.05, 1.0);
tipAlpha *= grainFactor;
}
- // 4. CSP Color Mixing & Smear (Amount of Paint, Density of Paint, Color Stretch)
+ // 4. CSP Color Mixing & Smear
if (u_colorMixing && u_hasCanvasTexture && !u_isEraser) {
vec2 canvasUv = v_worldPos / u_canvasResolution;
- canvasUv.y = 1.0 - canvasUv.y; // Correct UV flip
+ canvasUv.y = 1.0 - canvasUv.y;
vec4 canvasColor = texture2D(u_canvasTexture, canvasUv);
if (canvasColor.a > 0.02) {
- // Color Stretch exponential decay along stroke length
float stretchDistLimit = max(20.0, u_colorStretch * 600.0);
float stretchDecay = exp(-v_strokeDist / stretchDistLimit);
-
- // Amount of paint controls ratio of fresh ink vs picked canvas color
float effectiveAmount = clamp(u_amountOfPaint * (1.0 - stretchDecay * 0.7), 0.04, 0.98);
- rgb = mix(canvasColor.rgb, rgb, effectiveAmount);
-
- // Density of paint modulates deposition alpha
+ if (u_perceptualMixing) {
+ rgb = mixPigmentsGpu(canvasColor.rgb, rgb, effectiveAmount);
+ } else {
+ rgb = mix(canvasColor.rgb, rgb, effectiveAmount);
+ }
tipAlpha *= mix(0.65, 1.0, u_densityOfPaint);
}
}
@@ -198,6 +240,59 @@ void main() {
}
`;
+// -------------------------------------------------------------
+// Shaders for Track A: Ribbon Inking Engine (G-Pen / Manga Lines)
+// Continuous polygonal triangle strip with analytical distance field SDF
+// -------------------------------------------------------------
+
+const RIBBON_VERTEX_SHADER_SRC = `
+precision highp float;
+
+attribute vec2 a_pos; // world pixel position
+attribute float a_normalDist;// -1.0 for left, +1.0 for right
+attribute vec4 a_color; // rgba
+attribute float a_width; // pixel width
+
+uniform vec2 u_canvasResolution;
+
+varying float v_normalDist;
+varying vec4 v_color;
+varying float v_width;
+
+void main() {
+ v_normalDist = a_normalDist;
+ v_color = a_color;
+ v_width = a_width;
+
+ vec2 clipPos = (a_pos / u_canvasResolution) * 2.0 - 1.0;
+ clipPos.y = -clipPos.y; // Invert Y for canvas coordinate system
+
+ gl_Position = vec4(clipPos, 0.0, 1.0);
+}
+`;
+
+const RIBBON_FRAGMENT_SHADER_SRC = `
+precision highp float;
+
+varying float v_normalDist;
+varying vec4 v_color;
+varying float v_width;
+
+void main() {
+ float dist = abs(v_normalDist);
+ // Analytical SDF sub-pixel antialiasing
+ float aa = clamp(1.5 / max(1.0, v_width), 0.015, 0.45);
+ float alpha = 1.0 - smoothstep(1.0 - aa, 1.0, dist);
+
+ if (alpha <= 0.002) {
+ discard;
+ }
+
+ float finalAlpha = v_color.a * alpha;
+ gl_FragColor = vec4(v_color.rgb * finalAlpha, finalAlpha);
+}
+`;
+
/**
* WebGL-accelerated GPU brush engine.
* Computes all cutting-edge CSP brush mathematics directly on the video card!
@@ -205,9 +300,10 @@ void main() {
export class WebGlBrushEngine {
private static instance: WebGlBrushEngine | null = null;
- private canvas: HTMLCanvasElement;
+ private canvas: HTMLCanvasElement | null = null;
private gl: WebGLRenderingContext | WebGL2RenderingContext | null = null;
private program: WebGLProgram | null = null;
+ private ribbonProgram: WebGLProgram | null = null;
private isGpuAvailable = false;
private gpuInfo: GpuInfo = {
isSupported: false,
@@ -216,15 +312,19 @@ export class WebGlBrushEngine {
glVersion: 'None',
};
- // Uniform locations
+ // Uniform locations (Instanced Stamp)
private uCanvasResolutionLoc: WebGLUniformLocation | null = null;
private uHasTipTextureLoc: WebGLUniformLocation | null = null;
private uTipTextureLoc: WebGLUniformLocation | null = null;
+ private uHasDualTipTextureLoc: WebGLUniformLocation | null = null;
+ private uDualTipTextureLoc: WebGLUniformLocation | null = null;
+ private uDualBlendModeLoc: WebGLUniformLocation | null = null;
private uHardnessLoc: WebGLUniformLocation | null = null;
private uWetEdgeLoc: WebGLUniformLocation | null = null;
private uPaperGrainLoc: WebGLUniformLocation | null = null;
private uGrainScaleLoc: WebGLUniformLocation | null = null;
private uColorMixingLoc: WebGLUniformLocation | null = null;
+ private uPerceptualMixingLoc: WebGLUniformLocation | null = null;
private uHasCanvasTextureLoc: WebGLUniformLocation | null = null;
private uCanvasTextureLoc: WebGLUniformLocation | null = null;
private uAmountOfPaintLoc: WebGLUniformLocation | null = null;
@@ -233,6 +333,13 @@ export class WebGlBrushEngine {
private uIsEraserLoc: WebGLUniformLocation | null = null;
private uIsBgEraserLoc: WebGLUniformLocation | null = null;
+ // Uniform locations (Ribbon Mesh)
+ private uRibbonCanvasResolutionLoc: WebGLUniformLocation | null = null;
+ private aRibbonPosLoc: number = -1;
+ private aRibbonNormalDistLoc: number = -1;
+ private aRibbonColorLoc: number = -1;
+ private aRibbonWidthLoc: number = -1;
+
// Textures cache
private tipTexturesMap = new Map<string, WebGLTexture>();
private canvasLayerTexture: WebGLTexture | null = null;
@@ -246,11 +353,17 @@ export class WebGlBrushEngine {
private instanceBuffer: WebGLBuffer | null = null;
private instanceArray: Float32Array = new Float32Array(4096 * 12);
+ // Ribbon geometry buffers (stride 8: x, y, normalDist, width, r, g, b, a)
+ private ribbonBuffer: WebGLBuffer | null = null;
+ private ribbonArray: Float32Array = new Float32Array(1024 * 8);
+
private constructor() {
- this.canvas = document.createElement('canvas');
- this.canvas.width = 1024;
- this.canvas.height = 1024;
- this.initGl();
+ if (typeof document !== 'undefined') {
+ this.canvas = document.createElement('canvas');
+ this.canvas.width = 1024;
+ this.canvas.height = 1024;
+ this.initGl();
+ }
}
public static getInstance(): WebGlBrushEngine {
@@ -261,9 +374,13 @@ export class WebGlBrushEngine {
}
/**
- * Initializes the WebGL context and GPU shader program.
+ * Initializes the WebGL context and GPU shader programs.
*/
private initGl() {
+ if (!this.canvas) {
+ this.isGpuAvailable = false;
+ return;
+ }
try {
const glOpts: WebGLContextAttributes = {
alpha: true,
@@ -272,29 +389,31 @@ export class WebGlBrushEngine {
stencil: false,
premultipliedAlpha: true,
preserveDrawingBuffer: true,
- powerPreference: 'high-performance', // Request dedicated GPU/video card
+ powerPreference: 'high-performance',
};
const gl = (this.canvas.getContext('webgl2', glOpts) ||
this.canvas.getContext('webgl', glOpts) ||
this.canvas.getContext('experimental-webgl', glOpts)) as WebGLRenderingContext | null;
- if (!gl) {
- console.warn('WebGL not supported, falling back to Canvas 2D engine.');
+ if (!gl || typeof gl.createProgram !== 'function') {
+ this.isGpuAvailable = false;
return;
}
this.gl = gl;
// Query host video card information
- const ext = gl.getExtension('WEBGL_debug_renderer_info');
let renderer = 'Generic WebGL GPU';
let vendor = 'Generic';
- if (ext) {
- renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || renderer;
- vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || vendor;
+ if (typeof gl.getExtension === 'function') {
+ const ext = gl.getExtension('WEBGL_debug_renderer_info');
+ if (ext) {
+ renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || renderer;
+ vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || vendor;
+ }
}
- const glVersion = gl.getParameter(gl.VERSION) || 'WebGL';
+ const glVersion = (typeof gl.getParameter === 'function' && gl.getParameter(gl.VERSION)) || 'WebGL';
this.gpuInfo = {
isSupported: true,
@@ -303,47 +422,62 @@ export class WebGlBrushEngine {
glVersion,
};
- // Compile shader pipeline
+ // 1. Compile Instanced Dab shader pipeline
const vs = this.compileShader(gl.VERTEX_SHADER, VERTEX_SHADER_SRC);
const fs = this.compileShader(gl.FRAGMENT_SHADER, FRAGMENT_SHADER_SRC);
- if (!vs || !fs) {
- console.error('Failed to compile brush GPU shaders.');
- return;
+ if (vs && fs) {
+ const program = gl.createProgram();
+ if (program) {
+ gl.attachShader(program, vs);
+ gl.attachShader(program, fs);
+ gl.linkProgram(program);
+ if (gl.getProgramParameter(program, gl.LINK_STATUS)) {
+ this.program = program;
+ this.uCanvasResolutionLoc = gl.getUniformLocation(program, 'u_canvasResolution');
+ this.uHasTipTextureLoc = gl.getUniformLocation(program, 'u_hasTipTexture');
+ this.uTipTextureLoc = gl.getUniformLocation(program, 'u_tipTexture');
+ this.uHasDualTipTextureLoc = gl.getUniformLocation(program, 'u_hasDualTipTexture');
+ this.uDualTipTextureLoc = gl.getUniformLocation(program, 'u_dualTipTexture');
+ this.uDualBlendModeLoc = gl.getUniformLocation(program, 'u_dualBlendMode');
+ this.uHardnessLoc = gl.getUniformLocation(program, 'u_hardness');
+ this.uWetEdgeLoc = gl.getUniformLocation(program, 'u_wetEdge');
+ this.uPaperGrainLoc = gl.getUniformLocation(program, 'u_paperGrain');
+ this.uGrainScaleLoc = gl.getUniformLocation(program, 'u_grainScale');
+ this.uColorMixingLoc = gl.getUniformLocation(program, 'u_colorMixing');
+ this.uPerceptualMixingLoc = gl.getUniformLocation(program, 'u_perceptualMixing');
+ this.uHasCanvasTextureLoc = gl.getUniformLocation(program, 'u_hasCanvasTexture');
+ this.uCanvasTextureLoc = gl.getUniformLocation(program, 'u_canvasTexture');
+ this.uAmountOfPaintLoc = gl.getUniformLocation(program, 'u_amountOfPaint');
+ this.uDensityOfPaintLoc = gl.getUniformLocation(program, 'u_densityOfPaint');
+ this.uColorStretchLoc = gl.getUniformLocation(program, 'u_colorStretch');
+ this.uIsEraserLoc = gl.getUniformLocation(program, 'u_isEraser');
+ this.uIsBgEraserLoc = gl.getUniformLocation(program, 'u_isBgEraser');
+ }
+ }
}
- const program = gl.createProgram();
- if (!program) return;
-
- gl.attachShader(program, vs);
- gl.attachShader(program, fs);
- gl.linkProgram(program);
-
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- console.error('GPU Shader program link error:', gl.getProgramInfoLog(program));
- return;
+ // 2. Compile Track A Ribbon shader pipeline
+ const rVs = this.compileShader(gl.VERTEX_SHADER, RIBBON_VERTEX_SHADER_SRC);
+ const rFs = this.compileShader(gl.FRAGMENT_SHADER, RIBBON_FRAGMENT_SHADER_SRC);
+
+ if (rVs && rFs) {
+ const rProgram = gl.createProgram();
+ if (rProgram) {
+ gl.attachShader(rProgram, rVs);
+ gl.attachShader(rProgram, rFs);
+ gl.linkProgram(rProgram);
+ if (gl.getProgramParameter(rProgram, gl.LINK_STATUS)) {
+ this.ribbonProgram = rProgram;
+ this.uRibbonCanvasResolutionLoc = gl.getUniformLocation(rProgram, 'u_canvasResolution');
+ this.aRibbonPosLoc = gl.getAttribLocation(rProgram, 'a_pos');
+ this.aRibbonNormalDistLoc = gl.getAttribLocation(rProgram, 'a_normalDist');
+ this.aRibbonColorLoc = gl.getAttribLocation(rProgram, 'a_color');
+ this.aRibbonWidthLoc = gl.getAttribLocation(rProgram, 'a_width');
+ }
+ }
}
- this.program = program;
- gl.useProgram(program);
-
- // Cache uniform locations
- this.uCanvasResolutionLoc = gl.getUniformLocation(program, 'u_canvasResolution');
- this.uHasTipTextureLoc = gl.getUniformLocation(program, 'u_hasTipTexture');
- this.uTipTextureLoc = gl.getUniformLocation(program, 'u_tipTexture');
- this.uHardnessLoc = gl.getUniformLocation(program, 'u_hardness');
- this.uWetEdgeLoc = gl.getUniformLocation(program, 'u_wetEdge');
- this.uPaperGrainLoc = gl.getUniformLocation(program, 'u_paperGrain');
- this.uGrainScaleLoc = gl.getUniformLocation(program, 'u_grainScale');
- this.uColorMixingLoc = gl.getUniformLocation(program, 'u_colorMixing');
- this.uHasCanvasTextureLoc = gl.getUniformLocation(program, 'u_hasCanvasTexture');
- this.uCanvasTextureLoc = gl.getUniformLocation(program, 'u_canvasTexture');
- this.uAmountOfPaintLoc = gl.getUniformLocation(program, 'u_amountOfPaint');
- this.uDensityOfPaintLoc = gl.getUniformLocation(program, 'u_densityOfPaint');
- this.uColorStretchLoc = gl.getUniformLocation(program, 'u_colorStretch');
- this.uIsEraserLoc = gl.getUniformLocation(program, 'u_isEraser');
- this.uIsBgEraserLoc = gl.getUniformLocation(program, 'u_isBgEraser');
-
// Create static quad vertex buffer: two triangles forming [-0.5, 0.5] quad
const quadVertices = new Float32Array([
-0.5, -0.5,
@@ -357,6 +491,9 @@ export class WebGlBrushEngine {
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, quadVertices, gl.STATIC_DRAW);
+ // Create ribbon dynamic vertex buffer
+ this.ribbonBuffer = gl.createBuffer();
+
// Initialize hardware instanced array support
if ('drawArraysInstanced' in gl) {
this.extInstanced = {
@@ -367,7 +504,7 @@ export class WebGlBrushEngine {
(gl as any).vertexAttribDivisor(index, divisor);
},
};
- } else {
+ } else if (typeof gl.getExtension === 'function') {
const ext = gl.getExtension('ANGLE_instanced_arrays');
if (ext) {
this.extInstanced = {
@@ -386,10 +523,8 @@ export class WebGlBrushEngine {
gl.enable(gl.BLEND);
gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- this.isGpuAvailable = true;
- console.log(`%c[InkStudio GPU Engine]%c Running on ${renderer} (${vendor}) ${this.extInstanced ? '(Instanced Quad Core)' : ''}`, 'color: #5ce1e6; font-weight: bold;', 'color: #ffffff;');
- } catch (err) {
- console.warn('WebGL initialization exception, using fallback:', err);
+ this.isGpuAvailable = this.program !== null || this.ribbonProgram !== null;
+ } catch {
this.isGpuAvailable = false;
}
}
@@ -401,7 +536,6 @@ export class WebGlBrushEngine {
this.gl.shaderSource(shader, src);
this.gl.compileShader(shader);
if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) {
- console.error('Shader compile error:', this.gl.getShaderInfoLog(shader));
this.gl.deleteShader(shader);
return null;
}
@@ -413,7 +547,7 @@ export class WebGlBrushEngine {
}
public isAvailable(): boolean {
- return this.isGpuAvailable && this.gl !== null && this.program !== null;
+ return this.isGpuAvailable && this.gl !== null;
}
/**
@@ -467,7 +601,7 @@ export class WebGlBrushEngine {
/**
* Parses hex or rgb color string into normalized RGB [0, 1].
*/
- private parseColor(color: string): { r: number; g: number; b: number } {
+ public parseColor(color: string): { r: number; g: number; b: number } {
if (color.startsWith('#')) {
let hex = color.slice(1);
if (hex.length === 3) {
@@ -480,12 +614,186 @@ export class WebGlBrushEngine {
b: (num & 255) / 255,
};
}
- // Fallback: neutral dark/black
return { r: 0.1, g: 0.1, b: 0.1 };
}
/**
- * Renders a series of dabs onto a target Canvas2D context using GPU hardware acceleration.
+ * Track A: Ribbon Inking Engine (G-Pen, Manga Inking, Clean Vector/Raster Lines)
+ * Evaluates spline into continuous polygonal triangle strip (gl.TRIANGLE_STRIP)
+ * with normal extrusion and analytical distance field (SDF) antialiasing.
+ */
+ public renderRibbonSegment(
+ targetCtx: CanvasRenderingContext2D,
+ p0: Point,
+ c1: Point,
+ c2: Point,
+ p3: Point,
+ color: string,
+ opacity: number = 1.0,
+ canvasWidth: number,
+ canvasHeight: number,
+ isEraser: boolean = false,
+ isBgEraser: boolean = false
+ ): boolean {
+ const canvas = this.canvas;
+ if (!this.isAvailable() || !this.gl || !canvas || !this.ribbonProgram || !this.ribbonBuffer) {
+ return false;
+ }
+
+ const gl = this.gl;
+ const chord = Math.hypot(p3.x - p0.x, p3.y - p0.y);
+ const avgW = Math.max(0.5, (p0.width + p3.width) * 0.5);
+ const steps = Math.max(8, Math.min(48, Math.ceil(chord / Math.max(1.0, avgW * 0.25))));
+
+ // Stride 8: [x, y, normalDist, width, r, g, b, a]
+ const vertexCount = (steps + 1) * 2;
+ const requiredFloats = vertexCount * 8;
+ if (this.ribbonArray.length < requiredFloats) {
+ this.ribbonArray = new Float32Array(Math.max(requiredFloats, this.ribbonArray.length * 2));
+ }
+ const arr = this.ribbonArray;
+
+ const rgb = isBgEraser ? { r: 1, g: 1, b: 1 } : this.parseColor(color);
+ const alpha = Math.max(0.01, Math.min(1.0, opacity));
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ let vIdx = 0;
+ for (let i = 0; i <= steps; i++) {
+ const t = i / steps;
+ const it = 1 - t;
+
+ // Position along cubic Bézier
+ const px = it * it * it * p0.x + 3 * it * it * t * c1.x + 3 * it * t * t * c2.x + t * t * t * p3.x;
+ const py = it * it * it * p0.y + 3 * it * it * t * c1.y + 3 * it * t * t * c2.y + t * t * t * p3.y;
+
+ // Derivative (tangent)
+ const dpx = 3 * it * it * (c1.x - p0.x) + 6 * it * t * (c2.x - c1.x) + 3 * t * t * (p3.x - c2.x);
+ const dpy = 3 * it * it * (c1.y - p0.y) + 6 * it * t * (c2.y - c1.y) + 3 * t * t * (p3.y - c2.y);
+ const speed = Math.hypot(dpx, dpy);
+
+ let nx = 0;
+ let ny = 1;
+ if (speed > 1e-4) {
+ nx = -dpy / speed;
+ ny = dpx / speed;
+ }
+
+ // Interpolated stroke width
+ const w = Math.max(0.5, p0.width + (p3.width - p0.width) * t);
+ const halfW = w * 0.5;
+
+ // Left vertex
+ const lx = px + nx * halfW;
+ const ly = py + ny * halfW;
+ // Right vertex
+ const rx = px - nx * halfW;
+ const ry = py - ny * halfW;
+
+ // Update dirty bounding box
+ minX = Math.min(minX, lx, rx);
+ minY = Math.min(minY, ly, ry);
+ maxX = Math.max(maxX, lx, rx);
+ maxY = Math.max(maxY, ly, ry);
+
+ // Left vertex (normalDist = -1.0)
+ arr[vIdx++] = lx;
+ arr[vIdx++] = ly;
+ arr[vIdx++] = -1.0;
+ arr[vIdx++] = w;
+ arr[vIdx++] = rgb.r;
+ arr[vIdx++] = rgb.g;
+ arr[vIdx++] = rgb.b;
+ arr[vIdx++] = alpha;
+
+ // Right vertex (normalDist = +1.0)
+ arr[vIdx++] = rx;
+ arr[vIdx++] = ry;
+ arr[vIdx++] = 1.0;
+ arr[vIdx++] = w;
+ arr[vIdx++] = rgb.r;
+ arr[vIdx++] = rgb.g;
+ arr[vIdx++] = rgb.b;
+ arr[vIdx++] = alpha;
+ }
+
+ const pad = 4;
+ const sx = Math.max(0, Math.floor(minX - pad));
+ const sy = Math.max(0, Math.floor(minY - pad));
+ const ex = Math.min(canvasWidth, Math.ceil(maxX + pad));
+ const ey = Math.min(canvasHeight, Math.ceil(maxY + pad));
+ const dw = ex - sx;
+ const dh = ey - sy;
+
+ if (dw <= 0 || dh <= 0) return false;
+
+ // Resize GPU canvas if needed
+ if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
+ canvas.width = canvasWidth;
+ canvas.height = canvasHeight;
+ }
+
+ gl.viewport(0, 0, canvasWidth, canvasHeight);
+ if (typeof gl.scissor === 'function') {
+ gl.enable(gl.SCISSOR_TEST);
+ gl.scissor(sx, Math.max(0, canvasHeight - ey), dw, dh);
+ }
+ gl.clearColor(0, 0, 0, 0);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+
+ gl.useProgram(this.ribbonProgram);
+ gl.uniform2f(this.uRibbonCanvasResolutionLoc, canvasWidth, canvasHeight);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this.ribbonBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, requiredFloats), gl.DYNAMIC_DRAW);
+
+ const byteStride = 8 * 4;
+ gl.enableVertexAttribArray(this.aRibbonPosLoc);
+ gl.vertexAttribPointer(this.aRibbonPosLoc, 2, gl.FLOAT, false, byteStride, 0);
+
+ gl.enableVertexAttribArray(this.aRibbonNormalDistLoc);
+ gl.vertexAttribPointer(this.aRibbonNormalDistLoc, 1, gl.FLOAT, false, byteStride, 2 * 4);
+
+ gl.enableVertexAttribArray(this.aRibbonWidthLoc);
+ gl.vertexAttribPointer(this.aRibbonWidthLoc, 1, gl.FLOAT, false, byteStride, 3 * 4);
+
+ gl.enableVertexAttribArray(this.aRibbonColorLoc);
+ gl.vertexAttribPointer(this.aRibbonColorLoc, 4, gl.FLOAT, false, byteStride, 4 * 4);
+
+ // Render continuous triangle strip
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, vertexCount);
+
+ if (typeof gl.scissor === 'function') {
+ gl.disable(gl.SCISSOR_TEST);
+ }
+
+ gl.disableVertexAttribArray(this.aRibbonPosLoc);
+ gl.disableVertexAttribArray(this.aRibbonNormalDistLoc);
+ gl.disableVertexAttribArray(this.aRibbonWidthLoc);
+ gl.disableVertexAttribArray(this.aRibbonColorLoc);
+
+ // Blit hardware GPU dirty rect onto target context
+ targetCtx.save();
+ if (isBgEraser) {
+ targetCtx.globalCompositeOperation = 'source-over';
+ } else if (isEraser) {
+ targetCtx.globalCompositeOperation = 'destination-out';
+ } else {
+ targetCtx.globalCompositeOperation = 'source-over';
+ }
+ targetCtx.globalAlpha = 1.0;
+ targetCtx.drawImage(canvas, sx, sy, dw, dh, sx, sy, dw, dh);
+ targetCtx.restore();
+
+ return true;
+ }
+
+ /**
+ * Track B: GPU Instanced Stamp Engine (Pencils, Dry Brushes, Textured Tips)
+ * Batches thousands of textured dabs into a single GPU draw call per frame.
*/
public renderDabsToContext(
targetCtx: CanvasRenderingContext2D,
@@ -495,8 +803,9 @@ export class WebGlBrushEngine {
canvasWidth: number,
canvasHeight: number,
underlyingCanvas?: HTMLCanvasElement
- ) {
- if (!this.isAvailable() || !this.gl || !this.program || dabs.length === 0) {
+ ): boolean {
+ const canvas = this.canvas;
+ if (!this.isAvailable() || !this.gl || !canvas || !this.program || dabs.length === 0) {
return false;
}
@@ -504,28 +813,56 @@ export class WebGlBrushEngine {
const isEraser = tool === 'eraser';
const isBgEraser = isEraser && targetCtx.fillStyle === '#ffffff';
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (let i = 0; i < dabs.length; i++) {
+ const d = dabs[i];
+ const rad = Math.max(d.width, d.height) * 0.75 + 4;
+ if (d.x - rad < minX) minX = d.x - rad;
+ if (d.y - rad < minY) minY = d.y - rad;
+ if (d.x + rad > maxX) maxX = d.x + rad;
+ if (d.y + rad > maxY) maxY = d.y + rad;
+ }
+
+ const dirtyX = Math.max(0, Math.floor(minX));
+ const dirtyY = Math.max(0, Math.floor(minY));
+ const dirtyMaxX = Math.min(canvasWidth, Math.ceil(maxX));
+ const dirtyMaxY = Math.min(canvasHeight, Math.ceil(maxY));
+ const dirtyW = Math.max(0, dirtyMaxX - dirtyX);
+ const dirtyH = Math.max(0, dirtyMaxY - dirtyY);
+
+ if (dirtyW <= 0 || dirtyH <= 0) {
+ return false;
+ }
+
// Resize GPU canvas if needed
- if (this.canvas.width !== canvasWidth || this.canvas.height !== canvasHeight) {
- this.canvas.width = canvasWidth;
- this.canvas.height = canvasHeight;
+ if (canvas.width !== canvasWidth || canvas.height !== canvasHeight) {
+ canvas.width = canvasWidth;
+ canvas.height = canvasHeight;
}
gl.viewport(0, 0, canvasWidth, canvasHeight);
+ if (typeof gl.scissor === 'function') {
+ gl.enable(gl.SCISSOR_TEST);
+ gl.scissor(dirtyX, Math.max(0, canvasHeight - dirtyMaxY), dirtyW, dirtyH);
+ }
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(this.program);
- // Uniforms
gl.uniform2f(this.uCanvasResolutionLoc, canvasWidth, canvasHeight);
gl.uniform1f(this.uHardnessLoc, settings.hardness ?? 1.0);
gl.uniform1f(this.uWetEdgeLoc, settings.wetEdge ?? 0.0);
gl.uniform1f(this.uPaperGrainLoc, settings.grain ?? (settings.textureDensity ?? 0.0));
- gl.uniform1f(this.uGrainScaleLoc, 1.0);
+ gl.uniform1f(this.uGrainScaleLoc, settings.paperTextureScale ?? 1.0);
gl.uniform1i(this.uIsEraserLoc, isEraser ? 1 : 0);
gl.uniform1i(this.uIsBgEraserLoc, isBgEraser ? 1 : 0);
- // Tip Texture
+ // Primary Tip Texture
let tipTex: WebGLTexture | null = null;
if (settings.customTipImage) {
tipTex = this.getOrCreateTipTexture(settings.customTipImage);
@@ -539,9 +876,35 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasTipTextureLoc, 0);
}
- // Color Mixing
+ // Dual-Brush Tip Texture Modulation
+ let dualTipTex: WebGLTexture | null = null;
+ if (settings.dualBrush && settings.dualTipImage) {
+ dualTipTex = this.getOrCreateTipTexture(settings.dualTipImage);
+ }
+ if (dualTipTex) {
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, dualTipTex);
+ gl.uniform1i(this.uDualTipTextureLoc, 2);
+ gl.uniform1i(this.uHasDualTipTextureLoc, 1);
+ const dualMode =
+ settings.dualBrushCompositeMode === 'subtract'
+ ? 1
+ : settings.dualBrushCompositeMode === 'darken'
+ ? 2
+ : settings.dualBrushCompositeMode === 'overlay'
+ ? 3
+ : settings.dualBrushCompositeMode === 'screen'
+ ? 4
+ : 0;
+ gl.uniform1i(this.uDualBlendModeLoc, dualMode);
+ } else {
+ gl.uniform1i(this.uHasDualTipTextureLoc, 0);
+ }
+
+ // Color Mixing (OKLab + Kubelka-Munk perceptual pigment mixing by default)
const enableColorMix = Boolean(settings.colorMixing) && underlyingCanvas !== undefined;
gl.uniform1i(this.uColorMixingLoc, enableColorMix ? 1 : 0);
+ gl.uniform1i(this.uPerceptualMixingLoc, settings.perceptualMixing !== false ? 1 : 0);
if (enableColorMix && underlyingCanvas) {
const canvasTex = this.uploadCanvasTexture(underlyingCanvas);
@@ -560,13 +923,11 @@ export class WebGlBrushEngine {
gl.uniform1i(this.uHasCanvasTextureLoc, 0);
}
- // Set up vertex attribute pointers
const aQuadVertexLoc = gl.getAttribLocation(this.program, 'a_quadVertex');
gl.bindBuffer(gl.ARRAY_BUFFER, this.quadVertexBuffer);
gl.enableVertexAttribArray(aQuadVertexLoc);
gl.vertexAttribPointer(aQuadVertexLoc, 2, gl.FLOAT, false, 0, 0);
- // Render in batches
const aCenterLoc = gl.getAttribLocation(this.program, 'a_center');
const aSizeLoc = gl.getAttribLocation(this.program, 'a_size');
const aAngleLoc = gl.getAttribLocation(this.program, 'a_angle');
@@ -576,7 +937,7 @@ export class WebGlBrushEngine {
const aStrokeDistLoc = gl.getAttribLocation(this.program, 'a_strokeDist');
if (this.extInstanced && this.instanceBuffer && dabs.length > 0) {
- const stride = 12; // 12 floats per dab
+ const stride = 12;
const requiredFloats = dabs.length * stride;
if (this.instanceArray.length < requiredFloats) {
this.instanceArray = new Float32Array(Math.max(requiredFloats, this.instanceArray.length * 2));
@@ -634,7 +995,6 @@ export class WebGlBrushEngine {
this.extInstanced.drawArraysInstanced(gl.TRIANGLES, 0, 6, dabs.length);
- // Clean up divisors
this.extInstanced.vertexAttribDivisor(aCenterLoc, 0);
this.extInstanced.vertexAttribDivisor(aSizeLoc, 0);
this.extInstanced.vertexAttribDivisor(aAngleLoc, 0);
@@ -651,7 +1011,6 @@ export class WebGlBrushEngine {
gl.disableVertexAttribArray(aPressureLoc);
gl.disableVertexAttribArray(aStrokeDistLoc);
} else {
- // Fallback per-dab rendering
for (const dab of dabs) {
gl.vertexAttrib2f(aCenterLoc, dab.x, dab.y);
gl.vertexAttrib2f(aSizeLoc, dab.width, dab.height);
@@ -665,7 +1024,10 @@ export class WebGlBrushEngine {
}
}
- // Blit hardware-accelerated GPU buffer onto the target 2D context
+ if (typeof gl.scissor === 'function') {
+ gl.disable(gl.SCISSOR_TEST);
+ }
+
targetCtx.save();
if (isBgEraser) {
targetCtx.globalCompositeOperation = 'source-over';
@@ -675,7 +1037,7 @@ export class WebGlBrushEngine {
targetCtx.globalCompositeOperation = 'source-over';
}
targetCtx.globalAlpha = 1.0;
- targetCtx.drawImage(this.canvas, 0, 0);
+ targetCtx.drawImage(canvas, dirtyX, dirtyY, dirtyW, dirtyH, dirtyX, dirtyY, dirtyW, dirtyH);
targetCtx.restore();
return true;
@@ -695,9 +1057,7 @@ export class WebGlBrushEngine {
): { dabs: GpuDab[]; remainderDist: number; totalStrokeDist: number } {
const dabs: GpuDab[] = [];
const rgb = this.parseColor(color);
-
- const baseSize = settings.size;
- const spacingRatio = Math.max(0.01, Math.min(1.0, settings.spacing ?? 0.08));
+ const spacingRatio = Math.max(0.06, Math.min(1.0, settings.spacing ?? 0.08));
const flow = settings.flow ?? 0.85;
const aspect =
settings.customTipImage && settings.customTipImage.naturalWidth
@@ -706,7 +1066,6 @@ export class WebGlBrushEngine {
const baseAngleRad = ((settings.customTipAngle ?? 0) * Math.PI) / 180;
const angleDynamics = settings.customTipAngleDynamics ?? 'none';
- // Adaptive subdivision based on curve length
const chord = Math.hypot(p2.x - p0.x, p2.y - p0.y);
const avgWidth = Math.max(1, (p0.width + p2.width) / 2);
const steps = Math.max(8, Math.min(128, Math.ceil(chord / Math.max(0.5, avgWidth * 0.1))));
@@ -726,31 +1085,14 @@ export class WebGlBrushEngine {
const scatterBothAxes = Boolean(dynamics?.scatterBothAxes);
const flowJitter = Math.max(0, Math.min(1, dynamics?.flowJitter ?? 0));
const colorJitterEnabled = Boolean(dynamics?.colorJitterEnabled);
- const secondaryRgb = this.parseColor(settings.secondaryColor || '#ffffff');
+ const secondaryRgb = colorJitterEnabled ? this.parseColor(settings.secondaryColor || '#ffffff') : null;
for (let i = 1; i <= steps; i++) {
const t = i / steps;
- const invT = 1.0 - t;
- const invT2 = invT * invT;
- const t2 = t * t;
- const twoInvTT = 2.0 * invT * t;
-
- // Quadratic Bézier point
- const curX = invT2 * p0.x + twoInvTT * control.x + t2 * p2.x;
- const curY = invT2 * p0.y + twoInvTT * control.y + t2 * p2.y;
- const curPressure = invT * p0.pressure + t * p2.pressure;
-
- // Pressure curve transformation (CSP cubic spline or gamma)
- const effPressure = settings.pressureCurve
- ? evaluateCspSpline(curPressure, settings.pressureCurve)
- : (settings.pressureCurveGamma && settings.pressureCurveGamma !== 1.0
- ? Math.pow(Math.max(0.01, curPressure), settings.pressureCurveGamma)
- : curPressure);
-
- // Width calculation
- const minFactor = settings.minSizeFactor ?? 0.2;
- const curWidth = Math.max(1, baseSize * (minFactor + (1.0 - minFactor) * effPressure));
- const thickness = settings.thickness ?? 1.0;
+ const it = 1 - t;
+
+ const curX = it * it * p0.x + 2 * it * t * control.x + t * t * p2.x;
+ const curY = it * it * p0.y + 2 * it * t * control.y + t * t * p2.y;
const dx = curX - prevX;
const dy = curY - prevY;
@@ -759,17 +1101,17 @@ export class WebGlBrushEngine {
accDist += stepDist;
strokeDist += stepDist;
- const requiredInterval = Math.max(0.8, curWidth * spacingRatio);
+ const effPressure = p0.pressure + (p2.pressure - p0.pressure) * t;
+ const rawWidth = p0.width + (p2.width - p0.width) * t;
+ const curWidth = Math.max(0.5, rawWidth);
- if (accDist >= requiredInterval) {
- let baseAngle = baseAngleRad;
- if (angleDynamics === 'direction' && stepDist > 0.05) {
- baseAngle = Math.atan2(dy, dx) + baseAngleRad;
- } else if (angleDynamics === 'random') {
- baseAngle = baseAngleRad + (Math.random() - 0.5) * Math.PI * 2;
- }
+ const requiredSpacing = Math.max(0.5, curWidth * spacingRatio);
- if (settings.customTipRotationRandomScale) {
+ if (accDist >= requiredSpacing) {
+ let baseAngle = baseAngleRad;
+ if (angleDynamics === 'direction' && stepDist > 0.001) {
+ baseAngle += Math.atan2(dy, dx);
+ } else if (angleDynamics === 'random' && settings.customTipRotationRandomScale) {
baseAngle += (Math.random() - 0.5) * Math.PI * 2 * settings.customTipRotationRandomScale;
}
@@ -796,7 +1138,7 @@ export class WebGlBrushEngine {
}
curDabW = Math.max(0.1, curDabW);
- let curDabThickness = thickness;
+ let curDabThickness = 1.0;
if (roundnessJitter > 0) {
curDabThickness *= Math.max(0.05, 1.0 - Math.random() * roundnessJitter);
}
@@ -829,7 +1171,7 @@ export class WebGlBrushEngine {
let dabR = rgb.r;
let dabG = rgb.g;
let dabB = rgb.b;
- if (colorJitterEnabled && dynamics) {
+ if (colorJitterEnabled && dynamics && secondaryRgb) {
const cd = applyColorDynamics(rgb, secondaryRgb, dynamics);
dabR = cd.r;
dabG = cd.g;